430 lines
24 KiB
JavaScript
430 lines
24 KiB
JavaScript
'use strict';
|
||
|
||
const Service = require('egg').Service;
|
||
|
||
/**
|
||
* AI 推理引擎。
|
||
* 负责调用 DeepSeek API 进行多轮推理:思考→调函数→评估→(重复或输出)。
|
||
* 函数注册、分组管理等纯工具箱逻辑在 inbox/functions.js 中。
|
||
*/
|
||
class InboxAIService extends Service {
|
||
|
||
/**
|
||
* 调用 DeepSeek API。
|
||
*
|
||
* @param {Array<{role: string, content: string}>} messages 消息列表。
|
||
* @param {Object} [options] 额外选项。
|
||
* @return {Promise<string>} AI 返回的文本内容。
|
||
*/
|
||
async callDeepSeek(messages, options = {}) {
|
||
const { ctx } = this;
|
||
const apiKey = ctx.app.config.deepseek.apiKey;
|
||
const baseUrl = ctx.app.config.deepseek.baseUrl || 'https://api.deepseek.com';
|
||
|
||
if (!apiKey) {
|
||
throw new Error('DeepSeek API Key 未配置');
|
||
}
|
||
|
||
const result = await ctx.curl(`${baseUrl}/v1/chat/completions`, {
|
||
method: 'POST',
|
||
contentType: 'json',
|
||
dataType: 'json',
|
||
headers: { Authorization: `Bearer ${apiKey}` },
|
||
data: {
|
||
model: 'deepseek-v4-pro',
|
||
messages,
|
||
temperature: options.temperature ?? 0,
|
||
max_tokens: options.maxTokens ?? 1000,
|
||
},
|
||
timeout: options.timeout || 30000,
|
||
});
|
||
|
||
if (result.status !== 200 || !result.data) {
|
||
throw new Error(`DeepSeek 请求失败, HTTP ${result.status}`);
|
||
}
|
||
|
||
let content = result.data.choices?.[0]?.message?.content || '';
|
||
const reasoning = result.data.choices?.[0]?.message?.reasoning_content || '';
|
||
const finishReason = result.data.choices?.[0]?.finish_reason || '';
|
||
|
||
// 推理模型会把 max_tokens 消耗在 reasoning 上,导致 content 为空(finish_reason=length)
|
||
if (!content.trim() && finishReason === 'length') {
|
||
ctx.logger.warn(
|
||
`[inbox ai] DeepSeek 输出被截断: reasoning=${reasoning.length} 字符, content 为空, finish_reason=length`
|
||
);
|
||
throw new Error('DeepSeek 输出被截断(max_tokens 被推理过程占满),请提高 max_tokens');
|
||
}
|
||
|
||
// 清理 markdown 代码块
|
||
content = content.replace(/^```json\s*/i, '').replace(/\s*```$/i, '');
|
||
content = content.replace(/^```\s*/i, '').replace(/\s*```$/i, '');
|
||
return content.trim();
|
||
}
|
||
|
||
/**
|
||
* 获取智能对话历史上下文。
|
||
* 同一群 + 同一用户 → 最近 N 条消息(含 AI 回复),用于多轮对话短期记忆。
|
||
* 按创建时间升序排列,并为每条消息附加序号供 AI 追踪。
|
||
*
|
||
* @param {Object} opts 查询选项。
|
||
* @param {number} [opts.parentId] 当前消息的 parent_id(兼容旧参数)。
|
||
* @param {number} [opts.maxMessages=5] 最大历史消息数。
|
||
* @return {Promise<Array<{role: string, content: string, seq?: number}>>} 历史消息列表。
|
||
*/
|
||
async getConversationHistory(opts = {}) {
|
||
const parentId = Number(opts.parentId) || 0;
|
||
const maxMessages = Math.min(10, Math.max(1, Number(opts.maxMessages) || 5));
|
||
|
||
const { ctx } = this;
|
||
const { InboxMessage } = ctx.model;
|
||
const { Op } = ctx.app.Sequelize;
|
||
|
||
const groupId = String(ctx.inboxContext?.group_id || '').trim();
|
||
const userId = String(ctx.inboxContext?.user_id || '').trim();
|
||
const warehouseId = Number(ctx.inboxContext?.warehouse_id || 0);
|
||
|
||
// 排除当前消息本身(parentId=当前消息id;recallHistory 时取上下文注入的入站消息id),
|
||
// 避免"当前请求"混入历史导致 AI 重复处理
|
||
const excludeId = parentId || Number(ctx.inboxContext?.inbound_message_id) || 0;
|
||
|
||
// 无群/用户上下文时,退回旧逻辑:沿 parent_id 追溯
|
||
if (!groupId || !userId || !warehouseId) {
|
||
if (!parentId) return [];
|
||
try {
|
||
const history = [];
|
||
let currentId = parentId;
|
||
const visited = new Set();
|
||
while (currentId && history.length < maxMessages) {
|
||
if (visited.has(currentId)) break;
|
||
visited.add(currentId);
|
||
const msg = await InboxMessage.findOne({
|
||
attributes: [ 'id', 'parent_id', 'direction', 'content' ],
|
||
where: { id: currentId },
|
||
raw: true,
|
||
});
|
||
if (!msg) break;
|
||
history.unshift({ role: msg.direction === 'inbound' ? 'user' : 'assistant', content: msg.content || '' });
|
||
currentId = msg.parent_id;
|
||
}
|
||
return history;
|
||
} catch (error) {
|
||
ctx.logger.warn(`[inbox ai] 对话历史回退查询失败: ${error.message}`);
|
||
return [];
|
||
}
|
||
}
|
||
|
||
// 智能查询:同一群,最近 maxMessages 条(入站+出站混合,含所有成员)
|
||
try {
|
||
const messages = await InboxMessage.findAll({
|
||
attributes: [ 'id', 'parent_id', 'direction', 'content', 'user_id', 'user_name', 'created_at' ],
|
||
where: {
|
||
warehouse_id: warehouseId,
|
||
group_id: groupId,
|
||
direction: { [Op.in]: [ 'inbound', 'outbound' ] },
|
||
...(excludeId ? { id: { [Op.ne]: excludeId } } : {}),
|
||
},
|
||
order: [[ 'created_at', 'DESC' ]],
|
||
limit: maxMessages,
|
||
raw: true,
|
||
});
|
||
|
||
if (messages.length === 0) return [];
|
||
|
||
// 升序排列,附加上下文信息供 AI 判断真人接管
|
||
const blockedUsers = ctx.inboxContext?._blockedUserIds || new Set();
|
||
return messages.reverse().map(msg => {
|
||
const u = String(msg.user_id || '').trim();
|
||
const name = String(msg.user_name || '').trim();
|
||
const isBlocked = u && blockedUsers.has(u);
|
||
return {
|
||
role: msg.direction === 'inbound' ? 'user' : 'assistant',
|
||
content: msg.content || '',
|
||
user_id: u || null,
|
||
user_name: name || null,
|
||
blocked: isBlocked,
|
||
};
|
||
});
|
||
} catch (error) {
|
||
ctx.logger.warn(`[inbox ai] 智能对话历史查询失败: ${error.message}`);
|
||
return [];
|
||
}
|
||
}
|
||
|
||
/**
|
||
* DeepSeek 多轮推理:思考→调函数→评估→(重复或输出)。
|
||
*
|
||
* 每轮 AI 返回 JSON,通过 action 字段决定行为:
|
||
* { "action": "call", "function": "函数名", "params": {...}, "reason": "..." }
|
||
* { "action": "reply", "reply": "最终回复内容" }
|
||
*
|
||
* 最多 MAX_ROUNDS 轮,防止无限循环。
|
||
*
|
||
* @param {Object} data 消息数据。
|
||
* @param {string} data.content 消息正文。
|
||
* @param {Object} [data.ext_data] 透传数据。
|
||
* @param {number} [data.parentId] 父消息ID。
|
||
* @return {Promise<{reply: string, functionName: string|null, functionResult: Object|null}>} AI 回复。
|
||
*/
|
||
async processWithAI(data = {}) {
|
||
const { ctx } = this;
|
||
const content = String(data.content || '').trim();
|
||
if (!content) {
|
||
return { reply: '消息正文为空,无法处理', functionName: null, functionResult: null };
|
||
}
|
||
|
||
const funcSvc = ctx.service.inbox.functions;
|
||
const groupsSvc = ctx.service.inbox.groups;
|
||
const activeGroups = groupsSvc.resolveActiveGroups();
|
||
ctx.logger.info(`[inbox ai] 当前活跃分组: ${activeGroups.join(', ')}`);
|
||
|
||
const functionListText = groupsSvc.buildFunctionListText(activeGroups);
|
||
if (!functionListText) {
|
||
ctx.logger.info('[inbox ai] 当前上下文无可用的 AI 函数');
|
||
return { reply: null, functionName: null, functionResult: null };
|
||
}
|
||
|
||
// 拉取群历史(最多 10 条),同时注入 system prompt 和对话上下文
|
||
const history = await this.getConversationHistory({
|
||
parentId: data.parentId,
|
||
maxMessages: 10,
|
||
});
|
||
const historyContext = history.length > 0
|
||
? history.map(h => {
|
||
const tag = h.blocked ? '[已屏蔽]' : '';
|
||
return `[历史]${h.role === 'user' ? h.user_name || h.user_id || '未知' : 'AI'}${tag}: ${h.content}`;
|
||
}).join('\n')
|
||
: '(无历史)';
|
||
|
||
const MAX_ROUNDS = 5;
|
||
const executedFunctions = [];
|
||
const thoughts = [];
|
||
let finalReply = null;
|
||
let lastFunctionName = null;
|
||
let lastFunctionResult = null;
|
||
let jsonRetryNote = '';
|
||
|
||
const systemPrompt = `你是一个 WMS 仓库管理系统的智能助手,支持多步推理。
|
||
已注册函数:\n${functionListText}\n
|
||
=== 群最近对话历史 ===
|
||
${historyContext}
|
||
===
|
||
|
||
对话历史中 [已屏蔽] 标记表示该用户已主动要求屏蔽(不想被 AI 打扰)。
|
||
如果 [已屏蔽] 用户发送了表示接手或正在处理的内容(如"我来处理""不用回复""稍等""我看看"),说明真人已接管 → 直接 silent。
|
||
|
||
【历史消息边界 - 最高优先级】
|
||
- 以上带 [历史] 前缀的记录均为群历史消息,**全部已处理完毕**,仅作背景参考(判断是否有人已接管等),不是待处理请求
|
||
- 严禁把历史记录中的运单号/订单号/地址/售后诉求等当作当前用户的新请求;严禁对历史记录中的请求重复调用函数或重复创建工单
|
||
- 只有最后一条不带 [历史] 前缀的用户消息才是本次待处理请求,所有函数参数只能从这条当前消息中提取
|
||
- 当前消息未提供运单号/订单号等必填参数时,必须先向用户确认,严禁从历史记录中拼凑参数
|
||
|
||
你需要通过多轮调用来完成用户的复杂请求。每轮返回纯 JSON:
|
||
|
||
如果还需要调用函数获取信息:
|
||
{
|
||
"action": "call",
|
||
"function": "函数名",
|
||
"params": { "参数名": "参数值" },
|
||
"reason": "为什么需要这个函数"
|
||
}
|
||
|
||
如果信息充足可以回复用户了:
|
||
{
|
||
"action": "reply",
|
||
"reply": "最终回复(中文纯文本,禁止Markdown,200字以内,可适当使用\\n换行分隔信息)"
|
||
}
|
||
|
||
如果消息无需回复(用户只是确认、道谢、告别或表示自己处理):
|
||
{
|
||
"action": "silent"
|
||
}
|
||
|
||
真人接管判断规则(优先级最高,先于所有其他规则):
|
||
- 如果历史中某条消息 blocked=true 的用户发送了与当前问题相关的内容(如"我来处理""稍等""我看看"等表示接手的话术),说明真人客服已介入处理 → 直接 silent
|
||
- 如果 blocked 用户发送的内容与问题无关(如闲聊、询问其他事情),且当前用户仍在提问 → 正常回复当前用户
|
||
- 如果历史中只有当前用户的连续消息,没有其他用户介入 → 正常回复
|
||
|
||
一般约束:
|
||
- 最多 ${MAX_ROUNDS} 轮函数调用,第 ${MAX_ROUNDS} 轮必须给出最终回复
|
||
- 同一函数不要重复调用(除非参数不同)
|
||
- 信息中如果携带了@标记,说明信息是针对某个特定用户的,请注意是否需要回复该用户
|
||
- 如果函数执行失败,换其他方式或直接告知用户
|
||
- 回复使用中文纯文本,禁止 Markdown 语法,可用 \\n 换行提升可读性
|
||
- silent 仅用于:用户已确认收到消息且无新问题("好的""收到""OK""谢谢""知道了""好"),或用户表示告别/离场("再见""拜拜""88")
|
||
- 以下情况严禁 silent,必须 reply:任何形式的提问(含"在吗""有人吗""在不在")、操作请求、函数执行完毕、自定义欢迎语"你好""嗨""hello"等首次问候
|
||
- 【快递群专项】快递客服发出的进度/结果反馈("已通知网点""网点正在处理""已拦截""已联系收件人""改地址失败/无法改""已签收"等)严禁 silent,必须先调用 handleExpressFeedback 记录反馈再回复
|
||
- 无法判断时,宁可回复也不要 silent
|
||
- searchStock 返回多条结果时,必须列举让用户选择(告知 id/编码/名称/可用库存),不要擅自决定
|
||
- createOrder 失败时告知失败原因(库存不足/商品不存在等),不要重试同一商品
|
||
- searchStock 返回的 stock_available 为 0 时,提醒用户该商品无库存,建议选择其他商品
|
||
- searchStock/searchWarehouseStock 返回的 image_url 为图片URL数组(可能多张),has_images 为 true 时给出链接
|
||
- searchStock/searchWarehouseStock 返回的 barcodes 为关联条码,回复时可列出帮助核对
|
||
- searchStock/searchWarehouseStock 返回的管理标识 is_sn_mgmt/is_shelf_life_mgmt/is_batch_mgmt 分别表示SN管理/效期管理/批次管理
|
||
- searchStock/searchWarehouseStock 返回的 box_spec 为箱规(长宽高体积毛净重装箱数),packing_requirements 为打包要求,用户问及时告知
|
||
- searchStock/searchWarehouseStock 返回的 prohibited_type 为违禁品类型,非空时告知用户
|
||
- 用户说"第1个""第2个"时,按 searchStock 返回的顺序对应选择
|
||
- 需要上下文但记忆不足时,主动调用 recallHistory 回顾对话历史
|
||
- 【防误判规则 - interceptWaybill】讨论已有售后工单(AS开头编号)、询问物流进度、问"快递到哪了"、转发售后截图等均不是拦截请求,严禁调用 interceptWaybill。只有用户明确说"拦截/退回/召回/追回/取消"运单时才可调用
|
||
- 【规则 - requestPickup】货主售后群/仓库客服群中客户要求上门揽收/取件(如"揽收""上门取件""退货取件""寄回""让快递来拿"等)且提供了运单号时,调用 requestPickup(keyword=运单号,多个用逗号分隔)。函数会创建揽收售后工单,并优先转发到对应快递的揽收群(未配置揽收群时回退到售后群);返回的 data.message 是模板消息必须原样回复;若消息中无运单号,先向客户确认运单号再调用
|
||
- 【措辞规则 - interceptWaybill】拦截结果回复严禁使用"已拦截""拦截成功"等确定口吻,必须使用"拦截信息已登记""已提交拦截申请"等措辞。因为快递拦截可能失败,实际结果以快递公司反馈为准。回复时需列出工单号供用户跟进
|
||
- 【规则 - handleStoreFeedback】货主售后群中客户反馈"错发/发错""破损/坏了""多发/发多""少发/漏发"且提供了运单号时,调用 handleStoreFeedback 创建售后工单(初始状态未开始处理,不通知快递群);若消息中无运单号,先向客户确认运单号再调用
|
||
- 【规则 - handleExpressFeedback】快递售后群中,快递客服反馈处理进度/结果(如"已通知网点""网点正在处理""已拦截""已联系收件人""改地址失败/无法改""已签收""加急处理"等)且消息含运单号时,必须调用 handleExpressFeedback(keyword=运单号,多个用逗号分隔)。该函数会自动查找已有售后工单追加反馈并回信到相关群,无工单则自动创建。严禁把快递客服的进度/结果反馈判定为无需处理而 silent;若消息无运单号,先用 recallHistory 或询问确认运单号,严禁跳过
|
||
- 【规则 - handleExpressFeedback 证据核实】快递售后群中快递方发消息要求"提供交易记录截图/未收到依据/核实签收/带日期单号"等证据类诉求且消息含运单号时,同样必须调用 handleExpressFeedback(as_sub_type=verify_delivery),由函数创建售后工单并回信到货主售后群;严禁仅回复"收到/已记录"等确认话术而不调用函数
|
||
- 【规则 - changeAddr】货主售后群中客户消息含"改地址/改电话/改联系人/改收件人/地址更改/改手机/催退回/催促退回/催件/催派送/尽快安排派送"等诉求且提供了运单号时,调用 changeAddr(issue_type:addr=改地址类诉求,return=催退回类诉求,urge=催件/催派送类诉求;注意区分:"催退回/催促退回"用 return,"催件/催派送/尽快安排派送"用 urge,严禁把催件判定为 return);函数会创建售后工单并把客户原文转发到对应快递群,返回的 data.message 是模板消息必须原样回复;若消息中无运单号,先向客户确认运单号再调用
|
||
- 【规则 - weishoudao】货主售后群中客户消息含"核实签收/未收到/是否发出/是否已经发货/核实/没有找到快递"等诉求且提供了运单号时,调用 weishoudao 创建核实签收售后工单,并把"运单号+核实签收"转发到对应快递群;返回的 data.message 是模板消息必须原样回复;若消息中无运单号,先向客户确认运单号再调用
|
||
- 【规则 - changeExpress】货主售后群中客户要求"改快递/换快递/改圆通/改中通/改顺丰"等且提供了订单号时,调用 changeExpress(keyword=订单号,express=目标快递名称或编码);仅待处理表中未分配快递的订单可以修改,已分配快递或不在待处理表的订单不能修改;返回的 data.message 是模板消息必须原样回复;若消息中缺订单号或目标快递,先向客户确认再调用
|
||
- 【规则 - queryPackVideo】用户询问"打包视频/打包录像/装箱视频"且提供了运单号时,调用 queryPackVideo 查询(散单按订单、团购单按波次找打包记录);仅查询不建工单;返回的 data.message 是模板消息必须原样回复;若消息中无运单号,先向客户确认运单号再调用
|
||
- 【规则 - queryWeight】用户询问"查重/重量/核实重量/核重/称重"且提供了运单号时,调用 queryWeight 查询运单称重;重量为0时模板输出"未称重";仅查询不建工单;返回的 data.message 是模板消息必须原样回复;若消息中无运单号,先向客户确认运单号再调用
|
||
- 【规则 - createPostnum】货主售后群中客户要求"出单/打单/打印单/催发货/分配快递号"且提供了订单号时,调用 createPostnum(keyword=订单号,多个用逗号分隔);仅待处理表已审核且未分配快递号的订单可分配,函数会走分配流程并按结果返回"已分配+已回传"或"分配失败,等待客服人工处理"模板;返回的 data.message 是模板消息必须原样回复;若消息中无订单号,先向客户确认订单号再调用
|
||
- 【模板消息 - queryReturn】queryReturn 返回的 data.message 是已排版好的模板消息,必须原样作为最终回复输出,禁止改写、删减、增补内容,禁止添加 Markdown 或额外说明
|
||
- 【规则 - queryWarehouseAddress】用户询问"仓库地址/收货地址/退货地址/退件地址/寄回地址"时,调用 queryWarehouseAddress 查询仓库配置中的 receiver_address;返回的 data.message 是模板消息必须原样回复
|
||
- 【模板消息 - handleStoreFeedback】handleStoreFeedback 返回的 data.message 是已排版好的模板消息(运单号+问题类型+工单号+"稍后客服将人工核实跟进"),必须原样作为最终回复输出,禁止改写、删减或增补内容
|
||
- 用户发送"查退回+运单号"时,调用 queryReturn 查询退回明细,不要误调 queryOrder 或 interceptWaybill
|
||
- 【查询类请求强制调函数】查订单/查退回/查库存等查询类请求必须实际调用对应函数获取结果后再回复,严禁仅凭历史对话或猜测臆测"服务不可用/无法处理"而跳过函数调用
|
||
- 【历史失败回复免疫】群历史中 AI 的历史回复(尤其含"失败""异常""无法处理"等字样的兜底回复)只是历史记录,不代表当前功能不可用;严禁模仿、引用这类历史回复,也严禁据此判断函数不可用而拒绝调用;登记/操作/查询类请求必须实际调用对应函数获取最新结果`;
|
||
|
||
// 多轮推理循环
|
||
for (let round = 1; round <= MAX_ROUNDS; round++) {
|
||
const contextLines = [];
|
||
if (executedFunctions.length > 0) {
|
||
contextLines.push('已执行的函数及结果:');
|
||
executedFunctions.forEach((f, i) => {
|
||
contextLines.push(
|
||
` ${i + 1}. ${f.name}(${JSON.stringify(f.params)}) → ${JSON.stringify(f.result)}`
|
||
);
|
||
});
|
||
}
|
||
|
||
const messages = [
|
||
{ role: 'system', content: systemPrompt },
|
||
...(contextLines.length > 0 ? [{ role: 'system', content: contextLines.join('\n') }] : []),
|
||
{ role: 'user', content: round === 1
|
||
? content
|
||
: (jsonRetryNote ? `${jsonRetryNote}\n` : '') + (executedFunctions.length > 0
|
||
? `已获取到函数执行结果,请根据结果 reply 告知用户(禁止 silent)。第 ${round}/${MAX_ROUNDS} 轮`
|
||
: `请根据已获取的信息,决定下一步:继续调用函数还是给出最终回复。第 ${round}/${MAX_ROUNDS} 轮`),
|
||
},
|
||
];
|
||
|
||
let raw = '';
|
||
try {
|
||
// 推理模型(deepseek-v4-pro)需要充足 max_tokens:推理过程会先占用配额,过小会导致 content 被截断为空
|
||
raw = await this.callDeepSeek(messages, { maxTokens: 4000 });
|
||
ctx.logger.info(`[inbox ai] 第 ${round}/${MAX_ROUNDS} 轮: ${raw}`);
|
||
|
||
const result = JSON.parse(raw);
|
||
|
||
// 记录思考过程
|
||
thoughts.push({
|
||
round,
|
||
action: result.action || 'unknown',
|
||
function: result.function || null,
|
||
params: result.params || null,
|
||
reason: result.reason || null,
|
||
});
|
||
|
||
if (result.action === 'reply') {
|
||
finalReply = String(result.reply || '').trim();
|
||
if (!finalReply) finalReply = '已处理完成';
|
||
break;
|
||
}
|
||
|
||
if (result.action === 'silent') {
|
||
// 已调用过操作类函数(非 recallHistory)→ 必须回复结果,不能 silent
|
||
const actionFunctions = executedFunctions.filter(f => f.name !== 'recallHistory');
|
||
if (actionFunctions.length > 0) {
|
||
ctx.logger.info('[inbox ai] 已有操作类函数调用,忽略 silent 继续要求回复');
|
||
continue;
|
||
}
|
||
ctx.logger.info('[inbox ai] AI 判定无需回复,跳过回执');
|
||
return { reply: null, functionName: null, functionResult: null, thoughts, skip: true };
|
||
}
|
||
|
||
if (result.action === 'call' && result.function) {
|
||
const fnName = String(result.function).trim();
|
||
const params = result.params || {};
|
||
|
||
if (fnName === 'none' || fnName === 'stop') {
|
||
finalReply = result.reply || '已处理完成';
|
||
break;
|
||
}
|
||
|
||
lastFunctionName = fnName;
|
||
lastFunctionResult = await funcSvc.callFunction(fnName, params);
|
||
executedFunctions.push({ name: fnName, params, result: lastFunctionResult });
|
||
|
||
// 补充函数执行结果到思考记录
|
||
const lastThought = thoughts[thoughts.length - 1];
|
||
if (lastThought) lastThought.functionResult = lastFunctionResult;
|
||
ctx.logger.info(`[inbox ai] 执行 ${fnName}: ${JSON.stringify(lastFunctionResult)}`);
|
||
|
||
// 函数携带模板消息(direct_reply=true)→ 直接作为最终回复,不再交由 AI 改写
|
||
const directReply = lastFunctionResult
|
||
&& lastFunctionResult.data
|
||
&& lastFunctionResult.data.direct_reply === true
|
||
&& lastFunctionResult.data.message
|
||
? String(lastFunctionResult.data.message)
|
||
: '';
|
||
if (directReply) {
|
||
ctx.logger.info(`[inbox ai] 函数 ${fnName} 返回模板消息,直接回复 (length=${directReply.length})`);
|
||
finalReply = directReply;
|
||
break;
|
||
}
|
||
|
||
// 最后一轮强制输出
|
||
if (round === MAX_ROUNDS) {
|
||
finalReply = lastFunctionResult?.data?.message
|
||
|| lastFunctionResult?.data?.greeting
|
||
|| JSON.stringify(lastFunctionResult?.data || lastFunctionResult);
|
||
}
|
||
continue;
|
||
}
|
||
|
||
// 无法解析 → 尝试提取 reply
|
||
finalReply = result.reply || result.message || '抱歉,暂时无法处理您的请求';
|
||
break;
|
||
} catch (error) {
|
||
ctx.logger.warn(`[inbox ai] 第 ${round} 轮异常: ${error.message}, raw: ${raw}`);
|
||
|
||
// 模型输出疑似被截断的 JSON → 提醒后重试,避免把原始 JSON 当作回复发给用户
|
||
if (error instanceof SyntaxError && raw) {
|
||
const trimmedRaw = String(raw).trim();
|
||
if (trimmedRaw.startsWith('{') || trimmedRaw.startsWith('[')) {
|
||
jsonRetryNote = '上一轮模型输出不是合法 JSON(疑似截断),请重新输出完整合法的纯 JSON,不要包含任何额外文字';
|
||
continue;
|
||
}
|
||
// 不是 JSON → 当作文本回复
|
||
finalReply = trimmedRaw;
|
||
break;
|
||
}
|
||
|
||
// 最后一轮兜底
|
||
if (round === MAX_ROUNDS) {
|
||
finalReply = '抱歉,暂时无法处理您的请求,请稍后重试';
|
||
}
|
||
continue;
|
||
}
|
||
}
|
||
|
||
// 无回复的兜底
|
||
if (!finalReply && lastFunctionResult) {
|
||
finalReply = lastFunctionResult?.data?.message
|
||
|| lastFunctionResult?.data?.greeting
|
||
|| (lastFunctionResult?.success !== false ? '操作已完成' : lastFunctionResult?.error || '处理完成');
|
||
}
|
||
if (!finalReply) {
|
||
finalReply = '抱歉,暂时无法处理您的请求';
|
||
}
|
||
|
||
ctx.logger.info(`[inbox ai] 最终回复: ${finalReply}`);
|
||
return {
|
||
reply: finalReply,
|
||
functionName: lastFunctionName,
|
||
functionResult: lastFunctionResult,
|
||
thoughts,
|
||
};
|
||
}
|
||
}
|
||
|
||
module.exports = InboxAIService;
|