From 50e7e7b0c769139de8ad5dd125d54f7eafca3487 Mon Sep 17 00:00:00 2001 From: lik Date: Sun, 1 Nov 2026 11:42:40 +0800 Subject: [PATCH] =?UTF-8?q?feat(agent):=20=E6=8E=A5=E5=85=A5=E6=9C=AC?= =?UTF-8?q?=E4=BA=BA=E6=95=B0=E6=8D=AE=E6=9F=A5=E8=AF=A2=E5=B7=A5=E5=85=B7?= =?UTF-8?q?=EF=BC=8C=E8=A1=A5=E9=BD=90=E4=BC=9A=E8=AF=9D=E6=B8=85=E7=90=86?= =?UTF-8?q?=E3=80=81=E5=8E=86=E5=8F=B2=E8=A3=81=E5=89=AA=E4=B8=8E=E8=BE=93?= =?UTF-8?q?=E5=87=BA=E6=8A=A4=E6=A0=8F?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - bot-escort 注入 health_profile / employee / employee_review 查询,均绑定登录用户,只返回本人数据 - bot-escort 移除 hospital-info 子代理:机构信息属公共数据,改走 web 检索 - bot-escort-admin 补 employee / employee_review 管理端查询 - clear 指令单独回执,避免客户端只等到 end 帧无法区分是否已清空 - 温度与历史上限改为可配置(bot 临时对象由 task.js 传入),默认咨询端 0.3、管理端 0 - 用户资料指纹变化时重建 agent,避免继续用旧姓名/手机号/地址作答 - 流式输出接 guard 护栏,tool 结果入历史前截断 --- agent/bots/bot-escort-admin/agent.js | 85 +++++++++++++++---- agent/bots/bot-escort/agent.js | 121 ++++++++++++++++----------- agent/bots/bot-escort/task.js | 7 +- 3 files changed, 146 insertions(+), 67 deletions(-) diff --git a/agent/bots/bot-escort-admin/agent.js b/agent/bots/bot-escort-admin/agent.js index cbb4ca5..f627a58 100644 --- a/agent/bots/bot-escort-admin/agent.js +++ b/agent/bots/bot-escort-admin/agent.js @@ -6,6 +6,8 @@ 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 { OutputGuard, OUTPUT_MAX_CHARS } from "../../infra/guard.js"; // 密钥由 conf.json 统一提供;百度地图 token 由 http_get 按域名在服务端注入 process.env.TAVILY_API_KEY ??= config.agent.tavily?.apiKey; @@ -15,14 +17,21 @@ import { createPatientRecordSubagent } from "../../subagent/patient_record.js"; import { createHospitalInfoSubagent } from "../../subagent/hospital_info.js"; import { webFetchTool, webSearchTool, getCalendarInfoTool, getYearHolidaysTool, - httpGetTool, escortRecordQueryTool, escortRecordSetTool + httpGetTool, escortRecordQueryTool, escortRecordSetTool, + employeeQueryTool, employeeReviewQueryTool } from "../../infra/tools/index.js"; export default class EscortAdminAgent { - constructor() { - // 按用户隔离会话:userId -> { agent, messages } + 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; + // 单条回复字符上限:管理端要列记录,比咨询侧留更大余量 + this.maxOutputChars = options.maxOutputChars || config.agent.maxOutputChars || OUTPUT_MAX_CHARS.admin; } clearMessages(userInfo) { @@ -52,22 +61,41 @@ export default class EscortAdminAgent { this.sessions.delete(oldest); } - msgs.forEach(msg => { - if (msg.type === "clear") { - session.messages = []; - session.agent = null; - } else { - session.messages.push(new HumanMessage(`${msg.ts} - ${msg.content}`)); - } - }); - - if (session.messages.length === 0) { + // clear 是独立指令:清空后回一句确认,否则客户端只等到 end 帧, + // 无法区分「已清空」和「没处理」 + const clearMsg = msgs.find(msg => msg.type === "clear"); + if (clearMsg) { + session.messages = []; + session.agent = null; + callback("main", "ai", "会话已清空。", clearMsg.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); + if (session.agent && session.fingerprint !== fingerprint) { + session.agent = null; + } + session.fingerprint = fingerprint; + const agent = session.agent ?? this._genAgent(userInfo); session.agent = agent; + // 输出护栏:禁用词(身份泄露/空泛客套/越界承诺)拦截; + // 长度上限只作用于主回答,子代理输出会单独展示,不受主回答篇幅约束 + const guards = { + main: new OutputGuard({ label: "admin", maxChars: this.maxOutputChars }), + subagent: new OutputGuard({ label: "admin: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 }, @@ -89,7 +117,7 @@ export default class EscortAdminAgent { // 工具结果必须并入历史,否则下一轮会出现 tool_calls 缺少对应 tool 结果的断链 for (const msg of data_.messages ?? []) { if (msg.type === "tool") { - session.messages.push(msg); + appendToolMessage(session.messages, msg); logger.info(`Tool complete: ${msg.name}, Result: ${String(msg.content).slice(0, 200)}`); } } @@ -110,8 +138,12 @@ export default class EscortAdminAgent { continue; } if (AIMessageChunk.isInstance(message)) { + lastAiId[source] = message.id ?? lastAiId[source]; if (message.text) { - callback(source, "ai", message.text, message.id); + 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); @@ -124,6 +156,21 @@ export default class EscortAdminAgent { logger.info("custom: ", 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) { + if (!userInfo) return "anonymous"; + const profile = userInfo.profile ?? {}; + return JSON.stringify([profile.name, profile.mobile, userInfo.app]); } _genAgent(userInfo) { @@ -134,7 +181,7 @@ export default class EscortAdminAgent { this.flashModel = new ChatDeepSeek({ model: config.agent.deepseek.flashModel, apiKey: config.agent.deepseek.apiKey, - temperature: 0.0 + temperature: this.temperature }); return createDeepAgent({ @@ -145,8 +192,10 @@ export default class EscortAdminAgent { middleware: [todoListMiddleware()], // deepagents 1.12 起 todo 计划工具改为显式开启,多步记录操作用 tools: [webFetchTool, webSearchTool, httpGetTool, getCalendarInfoTool, getYearHolidaysTool, - escortRecordQueryTool, escortRecordSetTool], - subagents: [createPatientRecordSubagent(this.flashModel), createHospitalInfoSubagent(this.flashModel, { allowWrite: true })] + escortRecordQueryTool, escortRecordSetTool, + employeeQueryTool, employeeReviewQueryTool], + subagents: [createPatientRecordSubagent(this.flashModel), createHospitalInfoSubagent(this.flashModel, { allowWrite: true })], + skills: ["./agent/infra/skills/"], }); } } diff --git a/agent/bots/bot-escort/agent.js b/agent/bots/bot-escort/agent.js index 7c98a6f..dac7c38 100644 --- a/agent/bots/bot-escort/agent.js +++ b/agent/bots/bot-escort/agent.js @@ -14,18 +14,23 @@ process.env.TAVILY_API_KEY ??= config.agent.tavily?.apiKey; process.env.BAIDU_MAP_AUTH_TOKEN ??= config.agent.baiduMap?.authToken; import Prompts from "./prompts.js"; import { createRestrictedBackend } from "../../infra/restricted_fs_backend.js"; -import { createHospitalInfoSubagent } from "../../subagent/hospital_info.js"; +import { appendToolMessage, trimHistory } from "../../infra/history.js"; +import { OutputGuard, OUTPUT_MAX_CHARS } from "../../infra/guard.js"; import { webFetchTool, webSearchTool, getCalendarInfoTool, getYearHolidaysTool, - httpGetTool, createEscortRecordQueryTool + httpGetTool, createEscortRecordQueryTool, createHealthProfileQueryTool, + createEmployeeQueryTool, createEmployeeReviewQueryTool } from "../../infra/tools/index.js"; export default class EscortAgent { - // 历史消息字符数上限,超出时从头部丢弃完整轮次 - static MAX_HISTORY_CHARS = config.agent.maxHistoryChars || 40000; - - constructor() { + constructor(options = {}) { this.messages = []; + // 历史消息字符数上限,超出时从头部丢弃完整轮次 + this.maxHistoryChars = options.maxHistoryChars || config.agent.maxHistoryChars || 40000; + // 咨询场景需要一点表达自由度:温度为 0 时共情回复会退化为固定句式 + this.temperature = options.temperature ?? 0.3; + // 单条回复字符上限:提示词要求 1-3 句,超长时由输出护栏兜底截断 + this.maxOutputChars = options.maxOutputChars || config.agent.maxOutputChars || OUTPUT_MAX_CHARS.escort; } clearMessages() { @@ -35,28 +40,7 @@ export default class EscortAgent { // 按字符数裁剪历史:只以 HumanMessage 为界从头部删除完整轮次, // 避免切断 AI(tool_calls) -> Tool 的链式结构;永远保留最新一轮 _trimHistory() { - const size = (msgs) => msgs.reduce((sum, m) => sum + (m.text?.length ?? 0), 0); - if (size(this.messages) <= EscortAgent.MAX_HISTORY_CHARS) { - return; - } - - const starts = []; - this.messages.forEach((m, i) => { - if (HumanMessage.isInstance(m)) starts.push(i); - }); - if (starts.length < 2) { - return; - } - - let cut = 0; - for (let i = 0; i < starts.length - 1; i++) { - cut = starts[i + 1]; - if (size(this.messages.slice(cut)) <= EscortAgent.MAX_HISTORY_CHARS) { - break; - } - } - this.messages = this.messages.slice(cut); - logger.info(`History trimmed to ${this.messages.length} messages, ${size(this.messages)} chars`); + this.messages = trimHistory(this.messages, this.maxHistoryChars); } // msg: { ts: "2023-08-01 10:00:00", content: "你好" } @@ -65,23 +49,30 @@ export default class EscortAgent { return; } - msgs.forEach(msg => { - if (msg.type === "clear") { - this.messages = []; - this.agent = null; - } else { - this.messages.push(new HumanMessage(`${msg.ts} - ${msg.content}`)); - } - }); - - if (this.messages.length === 0) { + // clear 是独立指令:清空后回一句确认,否则客户端只等到 end 帧, + // 无法区分「已清空」和「没处理」 + const clearMsg = msgs.find(msg => msg.type === "clear"); + if (clearMsg) { + this.messages = []; + this.agent = null; + callback("main", "ai", "好,之前的对话已经清空,我们重新开始。", clearMsg.id); return; } + msgs.forEach(msg => { + this.messages.push(new HumanMessage(`${msg.ts} - ${msg.content}`)); + }); + this._trimHistory(); - // 在处理完 clear 消息后再生成 agent,确保清空后使用新实例 const agent = this._genAgent(userInfo); + // 输出护栏:禁用词(身份泄露/空泛客套/越界承诺)拦截; + // 长度上限只作用于主回答,子代理输出会单独展示,不受主回答篇幅约束 + const guards = { + main: new OutputGuard({ label: "escort", maxChars: this.maxOutputChars }), + subagent: new OutputGuard({ label: "escort: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: this.messages }, @@ -100,10 +91,11 @@ export default class EscortAgent { for (const [nodeName, data_] of Object.entries(data)) { if (!INTERESTING_NODES.has(nodeName)) continue; if (nodeName === "tools") { - // 工具结果必须并入历史,否则下一轮会出现 tool_calls 缺少对应 tool 结果的断链 + // 工具结果必须并入历史,否则下一轮会出现 tool_calls 缺少对应 tool 结果的断链; + // 入历史前截断,避免网页正文等长结果挤掉真正的人机对话 for (const msg of data_.messages ?? []) { if (msg.type === "tool") { - this.messages.push(msg); + appendToolMessage(this.messages, msg); logger.info(`Tool complete: ${msg.name}, Result: ${String(msg.content).slice(0, 200)}`); } } @@ -127,8 +119,12 @@ export default class EscortAgent { continue; } if (AIMessageChunk.isInstance(message)) { + lastAiId[source] = message.id ?? lastAiId[source]; if (message.text) { - callback(source, "ai", message.text, message.id); + 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); @@ -141,6 +137,14 @@ export default class EscortAgent { logger.info("custom: ", data); } } + + // 护栏尾部预留的 holdback 文本在流结束后补发,否则最后几个字会丢 + for (const source of ["main", "subagent"]) { + const tail = guards[source].finish(); + if (tail) { + callback(source, "ai", tail, lastAiId[source]); + } + } } _genAgent(userInfo) { @@ -151,8 +155,13 @@ export default class EscortAgent { ? path.join(dataDir, "users", userInfo._id, "memory.txt") : null; - // 会话中记忆文件被更新后重建 agent,使 systemPrompt 中的用户记忆保持最新 - if (this.agent && this._memoryMtime !== this._statMemory(memoryFile)) { + // 会话中记忆文件被更新、或用户资料变更后重建 agent, + // 使 systemPrompt 中的用户记忆与个人信息保持最新(避免用旧地址/旧手机号作答) + const fingerprint = this._userFingerprint(userInfo); + if ( + this.agent && + (this._memoryMtime !== this._statMemory(memoryFile) || this._profileFingerprint !== fingerprint) + ) { this.agent = null; } if (this.agent) { @@ -176,10 +185,11 @@ export default class EscortAgent { this.flashModel = new ChatDeepSeek({ model: config.agent.deepseek.flashModel, apiKey: config.agent.deepseek.apiKey, - temperature: 0.0 + temperature: this.temperature }); this._memoryMtime = this._statMemory(memoryFile); + this._profileFingerprint = fingerprint; this.agent = createDeepAgent({ name: "deep-agent", @@ -189,14 +199,31 @@ export default class EscortAgent { backend, tools: [webFetchTool, webSearchTool, httpGetTool, getCalendarInfoTool, getYearHolidaysTool, - createEscortRecordQueryTool(userInfo)], - subagents: [createHospitalInfoSubagent(this.flashModel)], + createEscortRecordQueryTool(userInfo), + // 以下查询工具均由当前登录用户身份绑定,只返回本人数据 + createHealthProfileQueryTool(userInfo), + createEmployeeQueryTool(userInfo), + createEmployeeReviewQueryTool(userInfo)], + // organization(机构/医院)是公共数据、没有 userId,不属于用户本人数据, + // 因此不在 bot-escort 注入任何机构库查询能力;公开信息走 web 工具 + subagents: [], skills: ["./agent/infra/skills/"], }); return this.agent; } + // 用户资料指纹:姓名/手机号/地址等变化时需重建 agent,否则 systemPrompt 仍是旧资料 + _userFingerprint(userInfo) { + if (!userInfo) return "anonymous"; + const profile = userInfo.profile ?? {}; + const location = userInfo.location ?? {}; + return JSON.stringify([ + profile.name, profile.mobile, profile.sex, profile.birth, + location.province, location.city, userInfo.addresses ?? [] + ]); + } + // 返回记忆文件 mtime,文件不存在时返回 null _statMemory(memoryFile) { if (!memoryFile) return null; diff --git a/agent/bots/bot-escort/task.js b/agent/bots/bot-escort/task.js index 685cecd..5734058 100644 --- a/agent/bots/bot-escort/task.js +++ b/agent/bots/bot-escort/task.js @@ -7,7 +7,7 @@ class ChatTask { apiKey: options.apiKey, baseURL: options.baseURL, modelName: options.modelName, - temperature: options.temperature ?? 0.7, + temperature: options.temperature ?? 0.3, maxIterations: options.maxIterations || 10, }; @@ -23,7 +23,10 @@ class ChatTask { // LRU:重新插入以更新使用顺序 this.agents.delete(userId); } else { - agent = new EscortAgent(); + agent = new EscortAgent({ + temperature: this.options.temperature, + maxHistoryChars: this.options.maxHistoryChars, + }); } this.agents.set(userId, agent);