- 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 结果入历史前截断
205 lines
9.2 KiB
JavaScript
205 lines
9.2 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 { OutputGuard, OUTPUT_MAX_CHARS } 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 { createHospitalInfoSubagent } from "../../subagent/hospital_info.js";
|
|
import {
|
|
webFetchTool, webSearchTool, getCalendarInfoTool, getYearHolidaysTool,
|
|
httpGetTool, escortRecordQueryTool, escortRecordSetTool,
|
|
employeeQueryTool, employeeReviewQueryTool
|
|
} from "../../infra/tools/index.js";
|
|
|
|
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;
|
|
// 单条回复字符上限:管理端要列记录,比咨询侧留更大余量
|
|
this.maxOutputChars = options.maxOutputChars || config.agent.maxOutputChars || 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: "你好" }
|
|
async streamChat(userInfo, msgs, callback) {
|
|
if (!msgs.length) {
|
|
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;
|
|
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 },
|
|
{
|
|
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}, Result: ${String(msg.content).slice(0, 200)}`);
|
|
}
|
|
}
|
|
} 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: ", 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) {
|
|
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
|
|
});
|
|
|
|
return createDeepAgent({
|
|
name: "deep-agent",
|
|
model: this.flashModel,
|
|
systemPrompt: EscortAdminPrompts.buildSystemPrompt(userInfo),
|
|
backend,
|
|
middleware: [todoListMiddleware()], // deepagents 1.12 起 todo 计划工具改为显式开启,多步记录操作用
|
|
tools: [webFetchTool, webSearchTool, httpGetTool,
|
|
getCalendarInfoTool, getYearHolidaysTool,
|
|
escortRecordQueryTool, escortRecordSetTool,
|
|
employeeQueryTool, employeeReviewQueryTool],
|
|
subagents: [createPatientRecordSubagent(this.flashModel), createHospitalInfoSubagent(this.flashModel, { allowWrite: true })],
|
|
skills: ["./agent/infra/skills/"],
|
|
});
|
|
}
|
|
}
|
|
|
|
const adminAgent = new EscortAdminAgent();
|
|
export { adminAgent };
|