'use strict'; const Service = require('egg').Service; /** DeepSeek 调用参数:与 WMS inbox/ai.js 保持一致(推理模型需要足够的 max_tokens) */ const DEEPSEEK_MODEL = 'deepseek-v4-pro'; const DEEPSEEK_TIMEOUT = 30000; const DEEPSEEK_MAX_TOKENS = 3000; /** 收件人字段白名单与长度上限(与 order_deliveries 列长对齐,避免超长写入失败) */ const RECEIVER_FIELD_LIMITS = { name: 100, tel: 50, mobile: 50, email: 100, country_code: 50, province: 100, city: 100, area: 100, town: 100, detail_address: 500, zip_code: 20, }; /** 系统提示词:只做抽取,输出纯 JSON(与 WMS 的 JSON 输出约定一致) */ const RECEIVER_SYSTEM_PROMPT = [ '你是收件人信息抽取助手。从用户提供的文本中提取收件人信息,只输出一个 JSON 对象,不要任何解释或多余文字。', 'JSON 字段固定为:name(收件人姓名)、tel(固定电话)、mobile(手机号)、province(省)、city(市)、area(区/县)、town(街道/镇)、', 'detail_address(详细地址)、zip_code(邮编)、email(邮箱)。', '规则:', '1) 无法确定的字段返回空字符串,不要编造;', '2) 11 位手机号放 mobile;带区号的固话放 tel;两者都有时都要填;', '3) province/city/area 保留“省/市/区/县”字样,逐级拆分(如“浙江省杭州市西湖区”);', '4) detail_address 只保留街道门牌等详细部分,不要重复省市县;', '5) 只输出 JSON 对象,不要使用 markdown 代码块。', ].join('\n'); /** * AI 服务:当前用于「收件人信息智能识别」 * 调用方式与 WMS 保持一致(DeepSeek 兼容的 /v1/chat/completions + 配置项 config.deepseek) */ class AiService extends Service { /** * 从一段自由文本中抽取收件人信息 * @param {string} text 用户粘贴的文本(如「张三 13800138000 浙江省杭州市西湖区文三路100号」) * @return {Promise} 结构化收件人字段(未识别到的字段为空串) */ async parseReceiver(text) { const content = String(text == null ? '' : text).trim(); if (!content) throw new Error('待识别的文本不能为空'); if (content.length > 2000) throw new Error('待识别的文本过长(最多 2000 字)'); const raw = await this._chat([ { role: 'system', content: RECEIVER_SYSTEM_PROMPT }, { role: 'user', content }, ]); const parsed = this._extractJson(raw); if (!parsed || typeof parsed !== 'object') { throw new Error('AI 返回内容无法解析为收件人信息,请调整文本后重试'); } return this._normalizeReceiver(parsed); } /** * 调用 DeepSeek 兼容接口(与 WMS inbox/ai.js 的 callDeepSeek 同口径) * @param {Array<{role: string, content: string}>} messages 消息列表 * @param {Object} [options] { temperature, maxTokens, timeout } * @return {Promise} 模型返回的文本内容 */ async _chat(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) { const err = new Error('DeepSeek API Key 未配置(请在 .env 中设置 DEEPSEEK_API_KEY),无法使用智能识别'); err.code = 'AI_NOT_CONFIGURED'; throw err; } const result = await ctx.curl(`${baseUrl}/v1/chat/completions`, { method: 'POST', contentType: 'json', dataType: 'json', headers: { Authorization: `Bearer ${apiKey}` }, data: { model: DEEPSEEK_MODEL, messages, temperature: options.temperature == null ? 0 : options.temperature, max_tokens: options.maxTokens || DEEPSEEK_MAX_TOKENS, }, timeout: options.timeout || DEEPSEEK_TIMEOUT, }); if (result.status !== 200 || !result.data) { const message = result.data && result.data.error && result.data.error.message; throw new Error(`AI 请求失败(HTTP ${result.status})${message ? `:${message}` : ''}`); } const choice = (result.data.choices && result.data.choices[0]) || {}; const text = (choice.message && choice.message.content) || ''; if (!text.trim()) { // 推理模型会把 max_tokens 消耗在推理过程上,导致 content 为空 if (choice.finish_reason === 'length') { throw new Error('AI 输出被截断(max_tokens 被推理过程占满),请重试'); } throw new Error('AI 未返回内容,请稍后重试或调整文本'); } return this._stripCodeFence(text); } /** * 去掉 markdown 代码块包裹(```json ... ```) * @param {string} text 模型原始输出 * @return {string} 清理后的文本 */ _stripCodeFence(text) { return String(text || '') .replace(/^```json\s*/i, '') .replace(/^```\s*/i, '') .replace(/\s*```$/i, '') .trim(); } /** * 从模型输出中提取 JSON 对象(容忍前后有解释文字) * @param {string} text 模型输出 * @return {Object|null} 解析结果 */ _extractJson(text) { const cleaned = this._stripCodeFence(text); try { return JSON.parse(cleaned); } catch { // 兜底:截取首个 { 到末个 } 之间的内容 const start = cleaned.indexOf('{'); const end = cleaned.lastIndexOf('}'); if (start >= 0 && end > start) { try { return JSON.parse(cleaned.slice(start, end + 1)); } catch { return null; } } return null; } } /** * 规范化模型输出:仅保留白名单字段、去空白、按列长截断 * @param {Object} data 模型输出的 JSON * @return {Object} 规范化后的收件人字段 */ _normalizeReceiver(data) { const result = {}; for (const [ key, limit ] of Object.entries(RECEIVER_FIELD_LIMITS)) { const value = data[key]; const text = value == null ? '' : String(value).trim(); result[key] = text.length > limit ? text.slice(0, limit) : text; } return result; } } module.exports = AiService;