liufumingren b436b6dd9e feat: 拦截链路全流程完善 — 新增interceptScan + 运单表同步 + 工单通知
新增:
- order.recheckOrder.interceptScan: 拦截扫描接口,入参运单号,查express标记退回,处理工单,更新订单拦截状态
- afterSale.createInterceptWorkOrdersAndNotify: 共享方法,幂等创建工单+通知快递群

修复:
- confirmIntercept: 补运单is_back同步(仅限is_intercept=Y),补工单创建+通知
- batchIntercept: 补运单is_intercept同步,补工单创建+通知
- batchUnintercept: 补运单is_intercept/is_back清除
- Qimen/OpenAPI cancel: 补运单is_intercept同步,补工单创建+通知
- interceptScan: 删除死查询,加空指针兜底

文档:
- methods/system.json: interceptScan + confirmIntercept 完整API文档
- methods/changes/system.json: 变更记录
2026-08-12 20:47:19 +08:00

371 lines
16 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.

'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 || '';
// 清理 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);
// 无群/用户上下文时,退回旧逻辑:沿 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' ] },
},
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;
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
- 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。只有用户明确说"拦截/退回/召回/追回/取消"运单时才可调用
- 【措辞规则 - interceptWaybill】拦截结果回复严禁使用"已拦截""拦截成功"等确定口吻,必须使用"拦截信息已登记""已提交拦截申请"等措辞。因为快递拦截可能失败,实际结果以快递公司反馈为准。回复时需列出工单号供用户跟进`;
// 多轮推理循环
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 },
...history,
...(contextLines.length > 0 ? [{ role: 'system', content: contextLines.join('\n') }] : []),
{ role: 'user', content: round === 1
? content
: (executedFunctions.length > 0
? `已获取到函数执行结果,请根据结果 reply 告知用户(禁止 silent)。第 ${round}/${MAX_ROUNDS} 轮`
: `请根据已获取的信息,决定下一步:继续调用函数还是给出最终回复。第 ${round}/${MAX_ROUNDS} 轮`),
},
];
let raw = '';
try {
raw = await this.callDeepSeek(messages, { maxTokens: 600 });
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)}`);
// 最后一轮强制输出
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 → 当作文本回复
if (error instanceof SyntaxError && raw) {
finalReply = raw;
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;