260 lines
10 KiB
JavaScript
260 lines
10 KiB
JavaScript
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";
|
||
|
||
// 图片识别原文回显的分片长度:与模型流式输出的单帧量级接近,
|
||
// 避免把很长的报告塞进一帧,也让客户端能逐段追加展示
|
||
const FORMAT_ECHO_CHUNK = 800;
|
||
|
||
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;
|
||
return;
|
||
}
|
||
|
||
// 图片识别原文:服务端 OCR 已按原图排版成 markdown,这里只并入会话上下文并原样回显。
|
||
// 不再交给模型「二次整理」:模型会按咨询提示词压缩成 1-3 句,而且输出护栏有字符上限,
|
||
// 长报告必然丢行(护栏 400 字);原文投递既完整,也省一次生成
|
||
const formatMsg = msgs.find(msg => msg.type === "format");
|
||
if (formatMsg) {
|
||
const text = String(formatMsg.content || "").trim();
|
||
if (!text) return;
|
||
|
||
// 原文留在历史里,用户接着问「这项指标什么意思」时模型能看到报告内容
|
||
this.messages.push(new HumanMessage(
|
||
`${formatMsg.ts} - 用户上传了一张图片,图像识别结果如下(原文可能有误,数字与单位需与图片核对):\n${text}`
|
||
));
|
||
this._trimHistory();
|
||
|
||
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 => {
|
||
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;
|
||
}
|
||
}
|
||
}
|