feat(agent): 接入本人数据查询工具,补齐会话清理、历史裁剪与输出护栏
- 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 结果入历史前截断
This commit is contained in:
@@ -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/"],
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user