输出上限支持按端配置并放宽到 escort 3000 / admin 5000;医院与网页类工具结果入历史保留 3000 字,数据库类维持 300 字,避免出诊信息被截断或追问时丢失。
276 lines
13 KiB
JavaScript
276 lines
13 KiB
JavaScript
import 'dotenv/config';
|
|
import { createDeepAgent } from "deepagents";
|
|
import { AIMessageChunk, ToolMessage, todoListMiddleware } from "langchain";
|
|
import { HumanMessage } from "@langchain/core/messages";
|
|
import { ChatDeepSeek } from "@langchain/deepseek";
|
|
import config from '../../../config.js';
|
|
import logger from '../../../utils/logger.js';
|
|
import { createRestrictedBackend } from "../../infra/restricted_fs_backend.js";
|
|
import { appendToolMessage, trimHistory } from "../../infra/history.js";
|
|
import { describeToolResult, describeStreamPayload } from "../../infra/tool_log.js";
|
|
import { OutputGuard, OUTPUT_MAX_CHARS, resolveOutputMaxChars } from "../../infra/guard.js";
|
|
|
|
// 密钥由 conf.json 统一提供;百度地图 token 由 http_get 按域名在服务端注入
|
|
process.env.TAVILY_API_KEY ??= config.agent.tavily?.apiKey;
|
|
process.env.BAIDU_MAP_AUTH_TOKEN ??= config.agent.baiduMap?.authToken;
|
|
import EscortAdminPrompts from "./prompts.js";
|
|
import { createPatientRecordSubagent } from "../../subagent/patient_record.js";
|
|
import {
|
|
webFetchTool, webSearchTool, getCalendarInfoTool, getYearHolidaysTool,
|
|
httpGetTool, escortRecordQueryTool, escortRecordSetTool,
|
|
employeeQueryTool, employeeReviewQueryTool,
|
|
createAttendantEscortRecordQueryTool, buildAttendantEscortRecordSetTool,
|
|
createAttendantEmployeeQueryTool,
|
|
hospitalKnowledgeListTool, hospitalKnowledgeReadTool, hospitalKnowledgeWriteTool
|
|
} from "../../infra/tools/index.js";
|
|
import { resolveEscortAdminRole } from "../../../utils/permissions.js";
|
|
|
|
// 图片识别原文回显的分片长度:与模型流式输出的单帧量级接近
|
|
const FORMAT_ECHO_CHUNK = 800;
|
|
|
|
export default class EscortAdminAgent {
|
|
constructor(options = {}) {
|
|
// 按用户隔离会话:userId -> { agent, messages, fingerprint }
|
|
this.sessions = new Map();
|
|
this.maxSessions = 100;
|
|
// 管理场景优先稳定复现,默认温度 0
|
|
this.temperature = options.temperature ?? 0.0;
|
|
// 历史消息字符数上限(管理端多步工具调用更易堆积上下文)
|
|
this.maxHistoryChars = options.maxHistoryChars || config.agent.maxHistoryChars || 40000;
|
|
// 单条回复字符上限:管理端要转述记录与医院清单,默认值需能完整输出一次排班列表;
|
|
// 可在 conf.json agent.maxOutputChars 调整
|
|
this.maxOutputChars = options.maxOutputChars
|
|
|| resolveOutputMaxChars(config.agent.maxOutputChars, "admin", OUTPUT_MAX_CHARS.admin);
|
|
}
|
|
|
|
clearMessages(userInfo) {
|
|
this.sessions.delete(userInfo._id);
|
|
}
|
|
|
|
// msg: { agent: 'escort-admin', type: 'chat', ts: "2023-08-01 10:00:00", content: "你好" }
|
|
// role: 入口已解析的 admin / attendant;不传时在这里兜底解析,避免绕过入口直接调用
|
|
async streamChat(userInfo, msgs, callback, role = null) {
|
|
if (!msgs.length) {
|
|
return;
|
|
}
|
|
|
|
const effectiveRole = role ?? await resolveEscortAdminRole(userInfo);
|
|
if (!effectiveRole) {
|
|
callback("main", "ai", "当前账号未绑定在职陪诊员档案,请联系管理员开通。", msgs[0]?.id);
|
|
return;
|
|
}
|
|
|
|
const userId = userInfo._id;
|
|
|
|
// LRU:按用户取会话,并更新使用顺序
|
|
let session = this.sessions.get(userId);
|
|
if (session) {
|
|
this.sessions.delete(userId);
|
|
} else {
|
|
session = { agent: null, messages: [] };
|
|
}
|
|
this.sessions.set(userId, session);
|
|
|
|
// 超出上限时淘汰最久未使用的会话,避免内存泄漏
|
|
if (this.sessions.size > this.maxSessions) {
|
|
const oldest = this.sessions.keys().next().value;
|
|
this.sessions.delete(oldest);
|
|
}
|
|
|
|
// clear 是独立指令:清空后回一句确认,否则客户端只等到 end 帧,
|
|
// 无法区分「已清空」和「没处理」
|
|
const clearMsg = msgs.find(msg => msg.type === "clear");
|
|
if (clearMsg) {
|
|
session.messages = [];
|
|
session.agent = null;
|
|
return;
|
|
}
|
|
|
|
// 图片识别原文:OCR 已按原图排版成 markdown,这里只并入会话上下文并原样回显。
|
|
// 不再交给模型二次整理:长截图/单据会被提示词压缩,也可能被输出护栏截断
|
|
const formatMsg = msgs.find(msg => msg.type === "format");
|
|
if (formatMsg) {
|
|
const text = String(formatMsg.content || "").trim();
|
|
if (!text) return;
|
|
|
|
// 原文留在历史里,用户接着追问图片里的内容时模型能看到
|
|
session.messages.push(new HumanMessage(
|
|
`${formatMsg.ts} - 用户上传了一张图片,图像识别结果如下(原文可能有误,数字与单位需与图片核对):\n${text}`
|
|
));
|
|
session.messages = trimHistory(session.messages, this.maxHistoryChars);
|
|
|
|
for (let offset = 0; offset < text.length; offset += FORMAT_ECHO_CHUNK) {
|
|
callback("main", "ai", text.slice(offset, offset + FORMAT_ECHO_CHUNK), formatMsg.id);
|
|
}
|
|
return;
|
|
}
|
|
|
|
msgs.forEach(msg => {
|
|
session.messages.push(new HumanMessage(`${msg.ts} - ${msg.content}`));
|
|
});
|
|
|
|
// 长会话下工具结果会挤占上下文,按完整轮次裁剪,避免上下文溢出与"忘记"前文
|
|
session.messages = trimHistory(session.messages, this.maxHistoryChars);
|
|
|
|
// 用户资料或角色变更后需重建 agent,否则 systemPrompt 与工具集仍是旧的
|
|
const fingerprint = this._userFingerprint(userInfo, effectiveRole);
|
|
if (session.agent && (session.fingerprint !== fingerprint || session.role !== effectiveRole)) {
|
|
session.agent = null;
|
|
}
|
|
session.fingerprint = fingerprint;
|
|
session.role = effectiveRole;
|
|
|
|
const agent = session.agent ?? this._genAgent(userInfo, effectiveRole);
|
|
session.agent = agent;
|
|
|
|
// 输出护栏:禁用词(身份泄露/空泛客套/越界承诺)拦截;
|
|
// 长度上限只作用于主回答,子代理输出会单独展示,不受主回答篇幅约束
|
|
const guardLabel = effectiveRole === "attendant" ? "escort-admin:attendant" : "escort-admin:admin";
|
|
const guards = {
|
|
main: new OutputGuard({ label: guardLabel, maxChars: this.maxOutputChars }),
|
|
subagent: new OutputGuard({ label: `${guardLabel}:subagent`, maxChars: Infinity }),
|
|
};
|
|
const lastAiId = { main: "", subagent: "" };
|
|
|
|
const INTERESTING_NODES = new Set(["model_request", "tools"]);
|
|
for await (const [namespace, mode, data] of await agent.stream(
|
|
{ messages: session.messages },
|
|
{
|
|
recursion_limit: 50,
|
|
streamMode: ["updates", "messages", "custom"], subgraphs: true,
|
|
configurable: {
|
|
thread_id: userId
|
|
}
|
|
})) {
|
|
const isSubagent = namespace.some(s => s.startsWith("tools:"));
|
|
const source = isSubagent ? "subagent" : "main";
|
|
if (mode === "updates") {
|
|
// Main agent updates (empty namespace)
|
|
if (namespace.length === 0) {
|
|
for (const [nodeName, data_] of Object.entries(data)) {
|
|
if (!INTERESTING_NODES.has(nodeName)) continue;
|
|
if (nodeName === "tools") {
|
|
// 工具结果必须并入历史,否则下一轮会出现 tool_calls 缺少对应 tool 结果的断链
|
|
for (const msg of data_.messages ?? []) {
|
|
if (msg.type === "tool") {
|
|
appendToolMessage(session.messages, msg);
|
|
logger.info(`Tool complete: ${msg.name}`, describeToolResult(msg.content));
|
|
}
|
|
}
|
|
} else if (nodeName === "model_request") {
|
|
session.messages.push(...data_.messages);
|
|
}
|
|
}
|
|
} else {
|
|
// Subagent updates (non-empty namespace)
|
|
for (const nodeName of Object.keys(data)) {
|
|
if (!INTERESTING_NODES.has(nodeName)) continue;
|
|
logger.info(`[${namespace[0]}] step: ${nodeName}`);
|
|
}
|
|
}
|
|
} else if (mode === "messages") {
|
|
const [message] = data;
|
|
if (message.tool_call_chunks?.length) {
|
|
continue;
|
|
}
|
|
if (AIMessageChunk.isInstance(message)) {
|
|
lastAiId[source] = message.id ?? lastAiId[source];
|
|
if (message.text) {
|
|
const text = guards[source].feed(message.text);
|
|
if (text) {
|
|
callback(source, "ai", text, message.id);
|
|
}
|
|
}
|
|
if (message.additional_kwargs.reasoning_content) {
|
|
callback(source, "reasoning", message.additional_kwargs.reasoning_content, message.id);
|
|
}
|
|
}
|
|
if (ToolMessage.isInstance(message) && message.text) {
|
|
callback(source, "tool", message.text, message.id);
|
|
}
|
|
} else if (mode === "custom") {
|
|
logger.info("custom event", describeStreamPayload(data));
|
|
}
|
|
}
|
|
|
|
// 护栏尾部预留的 holdback 文本在流结束后补发,否则最后几个字会丢
|
|
for (const source of ["main", "subagent"]) {
|
|
const tail = guards[source].finish();
|
|
if (tail) {
|
|
callback(source, "ai", tail, lastAiId[source]);
|
|
}
|
|
}
|
|
}
|
|
|
|
// 用户资料指纹:姓名/手机号/角色变化时需重建 agent,否则 systemPrompt 仍是旧资料
|
|
_userFingerprint(userInfo, role = "admin") {
|
|
if (!userInfo) return "anonymous";
|
|
const profile = userInfo.profile ?? {};
|
|
return JSON.stringify([profile.name, profile.mobile, userInfo.app, role]);
|
|
}
|
|
|
|
// 公共工具:天气、路线、日期、节假日、网页检索与医院知识库
|
|
_commonTools() {
|
|
return [
|
|
webFetchTool, webSearchTool, httpGetTool, getCalendarInfoTool, getYearHolidaysTool,
|
|
// 医院知识库:管理员与陪诊员均可读写,查询与记录规则见 hospital-info 技能
|
|
hospitalKnowledgeListTool, hospitalKnowledgeReadTool, hospitalKnowledgeWriteTool
|
|
];
|
|
}
|
|
|
|
/**
|
|
* 管理端工具集
|
|
* 仅显式管理员或员工档案为管理员时开放:跨用户查询、患者档案、医院资料维护等
|
|
*/
|
|
_adminTools() {
|
|
return [
|
|
...this._commonTools(),
|
|
escortRecordQueryTool, escortRecordSetTool,
|
|
employeeQueryTool, employeeReviewQueryTool
|
|
];
|
|
}
|
|
|
|
/**
|
|
* 陪诊员工具集
|
|
* 只给本人订单与本人档案,禁止跨用户查询与财务字段;医院知识库由公共工具提供
|
|
*/
|
|
_attendantTools(userInfo) {
|
|
return [
|
|
...this._commonTools(),
|
|
createAttendantEscortRecordQueryTool(userInfo),
|
|
buildAttendantEscortRecordSetTool({ attendantId: userInfo?._id }),
|
|
createAttendantEmployeeQueryTool(userInfo)
|
|
];
|
|
}
|
|
|
|
_genAgent(userInfo, role = "admin") {
|
|
const rootDir = process.cwd();
|
|
// 受限后端:锁定沙箱根并禁止读取 conf.json/.env/logs 及用户数据目录
|
|
const backend = createRestrictedBackend({ rootDir, dataDir: config.agent.dataDir });
|
|
|
|
this.flashModel = new ChatDeepSeek({
|
|
model: config.agent.deepseek.flashModel,
|
|
apiKey: config.agent.deepseek.apiKey,
|
|
temperature: this.temperature
|
|
});
|
|
|
|
const isAdminRole = role === "admin";
|
|
// 医院信息由主 agent 直接使用 hospital-info 技能与知识库工具,不再走子代理
|
|
const subagents = isAdminRole ? [createPatientRecordSubagent(this.flashModel)] : [];
|
|
|
|
return createDeepAgent({
|
|
name: "deep-agent",
|
|
model: this.flashModel,
|
|
systemPrompt: EscortAdminPrompts.buildSystemPrompt(userInfo, role),
|
|
backend,
|
|
middleware: [todoListMiddleware()], // deepagents 1.12 起 todo 计划工具改为显式开启,多步记录操作用
|
|
tools: isAdminRole ? this._adminTools() : this._attendantTools(userInfo),
|
|
subagents,
|
|
skills: ["./agent/infra/skills/"],
|
|
});
|
|
}
|
|
}
|
|
|
|
const adminAgent = new EscortAdminAgent();
|
|
export { adminAgent };
|