Files
api_health/agent/bots/bot-escort/agent.js
T
lik 50e7e7b0c7 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 结果入历史前截断
2026-11-01 11:42:40 +08:00

237 lines
9.3 KiB
JavaScript
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
import 'dotenv/config';
import fs from 'fs';
import path from 'path';
import { createDeepAgent, FilesystemBackend, CompositeBackend } from "deepagents";
import { ChatOpenAI } from "@langchain/openai";
import { AIMessageChunk, ToolMessage } from "langchain";
import { HumanMessage } from "@langchain/core/messages";
import { ChatDeepSeek } from "@langchain/deepseek";
import config from '../../../config.js';
import logger from '../../../utils/logger.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 Prompts from "./prompts.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";
import {
webFetchTool, webSearchTool, getCalendarInfoTool, getYearHolidaysTool,
httpGetTool, createEscortRecordQueryTool, createHealthProfileQueryTool,
createEmployeeQueryTool, createEmployeeReviewQueryTool
} from "../../infra/tools/index.js";
export default class EscortAgent {
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() {
this.messages = [];
}
// 按字符数裁剪历史:只以 HumanMessage 为界从头部删除完整轮次,
// 避免切断 AI(tool_calls) -> Tool 的链式结构;永远保留最新一轮
_trimHistory() {
this.messages = trimHistory(this.messages, this.maxHistoryChars);
}
// msg: { ts: "2023-08-01 10:00:00", content: "你好" }
async streamChat(userInfo, msgs, callback) {
if (!msgs.length) {
return;
}
// 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();
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 },
{
recursion_limit: 50,
streamMode: ["updates", "messages", "custom"], subgraphs: true,
configurable: {
thread_id: msgs[0].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(this.messages, msg);
logger.info(`Tool complete: ${msg.name}, Result: ${String(msg.content).slice(0, 200)}`);
}
}
} else if (nodeName === "model_request") {
this.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, metadata] = data;
if (message.tool_call_chunks?.length) {
continue;
}
if (metadata?.lcSource === "summarization" || metadata?.lc_source === "summarization") {
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]);
}
}
}
_genAgent(userInfo) {
const rootDir = process.cwd();
// 外部数据(用户记忆等)存储目录,由 conf.json agent.dataDir 配置
const dataDir = path.resolve(rootDir, config.agent.dataDir ?? "data");
const memoryFile = userInfo
? path.join(dataDir, "users", userInfo._id, "memory.txt")
: null;
// 会话中记忆文件被更新、或用户资料变更后重建 agent,
// 使 systemPrompt 中的用户记忆与个人信息保持最新(避免用旧地址/旧手机号作答)
const fingerprint = this._userFingerprint(userInfo);
if (
this.agent &&
(this._memoryMtime !== this._statMemory(memoryFile) || this._profileFingerprint !== fingerprint)
) {
this.agent = null;
}
if (this.agent) {
return this.agent;
}
// 受限后端:锁定沙箱根并禁止读取 conf.json/.env/logs 及用户数据目录;
// 登录用户挂载 /memories/ ↔ data/users/{userId}/(/memories/memory.txt ↔ .../memory.txt)
const backend = userInfo
? new CompositeBackend(
createRestrictedBackend({ rootDir, dataDir }),
{
"/memories/": new FilesystemBackend({
rootDir: path.join(dataDir, "users", userInfo._id),
virtualMode: true
})
},
)
: createRestrictedBackend({ rootDir, dataDir });
this.flashModel = new ChatDeepSeek({
model: config.agent.deepseek.flashModel,
apiKey: config.agent.deepseek.apiKey,
temperature: this.temperature
});
this._memoryMtime = this._statMemory(memoryFile);
this._profileFingerprint = fingerprint;
this.agent = createDeepAgent({
name: "deep-agent",
model: this.flashModel,
systemPrompt: Prompts.buildSystemPrompt(userInfo),
memory: ["./agent/bots/bot-escort/AGENTS.md"],
backend,
tools: [webFetchTool, webSearchTool, httpGetTool,
getCalendarInfoTool, getYearHolidaysTool,
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;
try {
return fs.statSync(memoryFile).mtimeMs;
} catch {
return null;
}
}
}