feat(order.pendingOrder.parseAddress): 支持数组批量入参批量解析,模型切 v4-flash,50 条并行块解析实测 31.6s
- 入参兼容 address 字符串(单条)/address 数组/addresses 数组(批量,上限 50) - 批量按每 10 条合并一次请求并行发出,Promise.all 聚合按输入顺序返回,失败条目逐条回退单条解析 - 模型 deepseek-v4-flash(仅 parseAddress 内使用,不改全局配置),超时 60s/块 120s - extractJsonBlock 支持数组 JSON 截取;新增手机号/姓名清洗与正则省市区最终兜底 - 同步 methods/system.json 文档(v0.3.28)与变更记录
This commit is contained in:
parent
75ac14a4ab
commit
18d33ec645
@ -531,6 +531,139 @@ function reverseInferAddress(parsed) {
|
|||||||
return { ...parsed, province: province || '', city: city || '', area: area || '' };
|
return { ...parsed, province: province || '', city: city || '', area: area || '' };
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 从模型返回的文本中截取 JSON 片段(对象或数组),并清理 markdown 代码块标记。
|
||||||
|
* 对象取第一个 { 到最后一个 },数组取第一个 [ 到最后一个 ],自动忽略前后多余文本。
|
||||||
|
*
|
||||||
|
* @param {string} text 模型原始返回文本。
|
||||||
|
* @return {string} 截取后的 JSON 字符串;无有效片段时返回原文 trim。
|
||||||
|
*/
|
||||||
|
function extractJsonBlock(text) {
|
||||||
|
if (!text) return '';
|
||||||
|
let s = String(text).trim();
|
||||||
|
s = s.replace(/^```(?:json)?\s*/i, '').replace(/\s*```$/i, '');
|
||||||
|
const firstBrace = s.indexOf('{');
|
||||||
|
const firstBracket = s.indexOf('[');
|
||||||
|
let start = -1;
|
||||||
|
if (firstBrace === -1) {
|
||||||
|
start = firstBracket;
|
||||||
|
} else if (firstBracket === -1) {
|
||||||
|
start = firstBrace;
|
||||||
|
} else {
|
||||||
|
start = Math.min(firstBrace, firstBracket);
|
||||||
|
}
|
||||||
|
const end = Math.max(s.lastIndexOf('}'), s.lastIndexOf(']'));
|
||||||
|
if (start === -1 || end === -1 || end <= start) {
|
||||||
|
return s;
|
||||||
|
}
|
||||||
|
return s.slice(start, end + 1);
|
||||||
|
}
|
||||||
|
|
||||||
|
const ADDRESS_PARSE_FIELDS = [
|
||||||
|
'province', 'city', 'area', 'town', 'detailAddress', 'name', 'mobile',
|
||||||
|
];
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 从任意文本(如思维链模型的 reasoning_content)中提取地址解析字段,
|
||||||
|
* 支持 "province":"xx"、province=xx、province:xx 等常见写法。
|
||||||
|
*
|
||||||
|
* @param {string} text 原始文本。
|
||||||
|
* @return {Object|null} 提取到的字段对象;一个字段都没提取到则返回 null。
|
||||||
|
*/
|
||||||
|
function salvageFieldsFromText(text) {
|
||||||
|
if (!text) return null;
|
||||||
|
const src = String(text);
|
||||||
|
const out = {};
|
||||||
|
let foundAny = false;
|
||||||
|
for (const field of ADDRESS_PARSE_FIELDS) {
|
||||||
|
const patterns = [
|
||||||
|
new RegExp(`["']?${field}["']?\\s*[::=]\\s*["']([^"']{0,80})["']`, 'i'),
|
||||||
|
new RegExp(`["']?${field}["']?\\s*[::=]\\s*([^\\s,,;;\\n"']{0,80})`, 'i'),
|
||||||
|
];
|
||||||
|
for (const re of patterns) {
|
||||||
|
const m = src.match(re);
|
||||||
|
if (m && m[1] && m[1].trim()) {
|
||||||
|
out[field] = m[1].trim();
|
||||||
|
foundAny = true;
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return foundAny ? out : null;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 清洗手机号:仅保留合法 11 位大陆手机号;兜底提取的脏数据(如整段地址)置空。
|
||||||
|
*
|
||||||
|
* @param {*} mobile 原始手机号字段。
|
||||||
|
* @return {string} 合法手机号或空字符串。
|
||||||
|
*/
|
||||||
|
function sanitizeMobile(mobile) {
|
||||||
|
const m = String(mobile || '').trim();
|
||||||
|
return /^1[3-9]\d{9}$/.test(m) ? m : '';
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 清洗收件人姓名:过滤过长的字符串与明显混入地址信息的脏数据。
|
||||||
|
*
|
||||||
|
* @param {*} name 原始姓名字段。
|
||||||
|
* @return {string} 合法姓名或空字符串。
|
||||||
|
*/
|
||||||
|
function sanitizeName(name) {
|
||||||
|
const n = String(name || '').trim();
|
||||||
|
if (!n || n.length > 20) return '';
|
||||||
|
if (/[省市县区镇街道路号村组栋座楼室单元乡]/.test(n)) return '';
|
||||||
|
return n;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 地址解析最终兜底:AI 解析与行政区划映射表均失败时,用正则按"省-市-区-镇"顺序
|
||||||
|
* 从原始地址字符串中提取行政区划。支持省份全称与简称(如"广东"、"内蒙古")。
|
||||||
|
*
|
||||||
|
* @param {string} text 原始地址字符串。
|
||||||
|
* @return {Object} { province, city, area, town },识别不到的字段为空字符串。
|
||||||
|
*/
|
||||||
|
function extractAddressByRegex(text) {
|
||||||
|
const src = String(text || '');
|
||||||
|
const result = { province: '', city: '', area: '', town: '' };
|
||||||
|
if (!src) return result;
|
||||||
|
|
||||||
|
// 省份:全称与简称按长度降序匹配,避免"河北/河南"等前缀误配
|
||||||
|
const shorten = p => p.replace(/(壮族自治区|回族自治区|维吾尔自治区|特别行政区|自治区|省|市)$/, '');
|
||||||
|
const provincePattern = PROVINCE_LIST
|
||||||
|
.reduce((list, p) => {
|
||||||
|
const short = shorten(p);
|
||||||
|
if (short !== p) list.push(short);
|
||||||
|
list.push(p);
|
||||||
|
return list;
|
||||||
|
}, [])
|
||||||
|
.sort((a, b) => b.length - a.length)
|
||||||
|
.join('|');
|
||||||
|
const provinceMatch = src.match(new RegExp(`(${provincePattern})`));
|
||||||
|
if (!provinceMatch) return result;
|
||||||
|
|
||||||
|
const provinceToken = provinceMatch[1];
|
||||||
|
const fullProvince = PROVINCE_LIST.find(p => p.startsWith(provinceToken));
|
||||||
|
result.province = fullProvince || provinceToken;
|
||||||
|
const rest = src.slice(provinceMatch.index + provinceToken.length);
|
||||||
|
|
||||||
|
const cityMatch = rest.match(/([\u4e00-\u9fa5]{2,10}?(?:自治州|地区|盟|市))/);
|
||||||
|
if (!cityMatch) return result;
|
||||||
|
result.city = cityMatch[1];
|
||||||
|
const restAfterCity = rest.slice(cityMatch.index + cityMatch[1].length);
|
||||||
|
|
||||||
|
const areaMatch = restAfterCity.match(/([\u4e00-\u9fa5]{2,10}?(?:自治县|区|县|市))/);
|
||||||
|
if (!areaMatch) return result;
|
||||||
|
result.area = areaMatch[1];
|
||||||
|
const restAfterArea = restAfterCity.slice(areaMatch.index + areaMatch[1].length);
|
||||||
|
|
||||||
|
const townMatch = restAfterArea.match(/([\u4e00-\u9fa5]{2,10}?(?:街道|办事处|镇|乡))/);
|
||||||
|
if (townMatch) {
|
||||||
|
result.town = townMatch[1];
|
||||||
|
}
|
||||||
|
return result;
|
||||||
|
}
|
||||||
|
|
||||||
class PendingOrderService extends OrderBaseService {
|
class PendingOrderService extends OrderBaseService {
|
||||||
/**
|
/**
|
||||||
* 初始化待处理订单系统方法的免登录、免权限、免日志和免鉴权配置。
|
* 初始化待处理订单系统方法的免登录、免权限、免日志和免鉴权配置。
|
||||||
@ -3149,7 +3282,12 @@ class PendingOrderService extends OrderBaseService {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
const newOrder = await model.create(newOrderData);
|
// 克隆单同样由仓库序列表统一发号;发号失败直接抛错,不回退分表自增,
|
||||||
|
// 避免分表自增与序列表发号区间重叠产生冲突 id
|
||||||
|
await this.ctx.model.OrderDeliveryFactory.ensureLocationSequenceTable(warehouseId);
|
||||||
|
const allocatedOrderId = await this.ctx.model.OrderDeliveryFactory.allocateOrderId(warehouseId, null, 'current');
|
||||||
|
|
||||||
|
const newOrder = await model.create({ ...newOrderData, id: allocatedOrderId });
|
||||||
const newOrderId = Number(newOrder.id || newOrder.dataValues && newOrder.dataValues.id);
|
const newOrderId = Number(newOrder.id || newOrder.dataValues && newOrder.dataValues.id);
|
||||||
|
|
||||||
// 5. 克隆订单明细
|
// 5. 克隆订单明细
|
||||||
@ -3214,28 +3352,196 @@ class PendingOrderService extends OrderBaseService {
|
|||||||
/**
|
/**
|
||||||
* 智能地址解析:使用 DeepSeek 将用户输入的地址字符串解析为结构化地址。
|
* 智能地址解析:使用 DeepSeek 将用户输入的地址字符串解析为结构化地址。
|
||||||
*
|
*
|
||||||
|
* 支持单条解析与数组批量解析两种模式:
|
||||||
|
* - 单条:data.address 传字符串,返回单条解析结果(与原行为一致)
|
||||||
|
* - 批量:data.addresses(或 data.address)传字符串数组,按数组顺序返回 data.list,
|
||||||
|
* 每条元素含 address/flag/message 与解析字段,失败条目不影响其他条目
|
||||||
|
*
|
||||||
* 采用"AI 解析 + 反向识别兜底"双层策略:
|
* 采用"AI 解析 + 反向识别兜底"双层策略:
|
||||||
* 1. 先由 DeepSeek AI 进行语义级地址解析
|
* 1. 先由 DeepSeek AI 进行语义级地址解析
|
||||||
* 2. 若 AI 返回的省/市/区字段缺失,通过内置的中国行政区划映射表反向补全
|
* 2. 若 AI 返回的省/市/区字段缺失,通过内置的中国行政区划映射表反向补全
|
||||||
* 3. 仅在两层策略均无法确定 province 时才判定失败
|
* 3. 仅在两层策略均无法确定 province 时才判定失败
|
||||||
*
|
*
|
||||||
* @param {Object} data 请求数据。
|
* @param {Object} data 请求数据。
|
||||||
* @param {string} data.address 原始地址字符串(必填)。
|
* @param {string|string[]} data.address 原始地址字符串或字符串数组(必填)。
|
||||||
* @return {Promise<Object>} 解析结果,成功返回 province/city/area/town/detailAddress/name/mobile 等,失败返回错误。
|
* @param {string[]} [data.addresses] 批量地址字符串数组(与 address 数组二选一)。
|
||||||
|
* @return {Promise<Object>} 解析结果;批量模式返回 data.list 数组。
|
||||||
*/
|
*/
|
||||||
async parseAddress(data = {}) {
|
async parseAddress(data = {}) {
|
||||||
const address = String(data.address || '').trim();
|
// 批量模式:addresses 数组优先,其次 address 数组
|
||||||
|
const rawAddresses = Array.isArray(data.addresses)
|
||||||
|
? data.addresses
|
||||||
|
: (Array.isArray(data.address) ? data.address : null);
|
||||||
|
|
||||||
|
if (rawAddresses) {
|
||||||
|
if (!rawAddresses.length) {
|
||||||
|
return this.fail('地址数组不能为空');
|
||||||
|
}
|
||||||
|
if (rawAddresses.length > 50) {
|
||||||
|
return this.fail('单次批量解析最多支持 50 条地址');
|
||||||
|
}
|
||||||
|
// 批量提速:每 10 条合并为一次 DeepSeek 请求(实测 10 条约 18s、无截断),
|
||||||
|
// 所有块异步并行发出,全部完成后按输入顺序聚合返回;失败/缺失条目逐条回退单条解析。
|
||||||
|
const CHUNK_SIZE = 10;
|
||||||
|
const EMPTY_FIELDS = { province: '', city: '', area: '', town: '', detailAddress: '', name: '', mobile: '' };
|
||||||
|
const toListItem = r => ({
|
||||||
|
address: r.address,
|
||||||
|
flag: r.flag,
|
||||||
|
message: r.message,
|
||||||
|
...(r.fields || EMPTY_FIELDS),
|
||||||
|
});
|
||||||
|
const chunks = [];
|
||||||
|
for (let i = 0; i < rawAddresses.length; i += CHUNK_SIZE) {
|
||||||
|
chunks.push(rawAddresses.slice(i, i + CHUNK_SIZE));
|
||||||
|
}
|
||||||
|
const chunkResults = await Promise.all(chunks.map(chunk => this._parseAddressBatchOneShot(chunk)));
|
||||||
|
const results = await Promise.all(rawAddresses.map((item, idx) => {
|
||||||
|
const r = chunkResults[Math.floor(idx / CHUNK_SIZE)];
|
||||||
|
const inChunk = r && r[idx % CHUNK_SIZE];
|
||||||
|
return inChunk && inChunk.ok ? inChunk : this._parseSingleAddress(item);
|
||||||
|
}));
|
||||||
|
return this.success('地址解析成功', { list: results.map(toListItem) });
|
||||||
|
}
|
||||||
|
|
||||||
|
// 单条模式(向后兼容)
|
||||||
|
const single = await this._parseSingleAddress(data.address);
|
||||||
|
if (!single.ok) {
|
||||||
|
return this.fail(single.message);
|
||||||
|
}
|
||||||
|
return this.success('地址解析成功', single.fields);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 块内一次性解析:把一组地址(建议 10 条)合并为一次 DeepSeek 请求,
|
||||||
|
* 让模型按编号返回 JSON 数组,省去逐条请求的网络开销。
|
||||||
|
*
|
||||||
|
* @param {string[]} addressList 地址字符串数组。
|
||||||
|
* @return {Promise<Array|null>} 与入参顺序对齐的逐条结果数组;
|
||||||
|
* 请求失败/JSON 解析失败/被截断时返回 null,由调用方逐条回退单条解析。
|
||||||
|
*/
|
||||||
|
async _parseAddressBatchOneShot(addressList) {
|
||||||
|
const apiKey = this.config.deepseek.apiKey;
|
||||||
|
const baseUrl = this.config.deepseek.baseUrl || 'https://api.deepseek.com';
|
||||||
|
if (!apiKey) return null;
|
||||||
|
|
||||||
|
const numbered = addressList.map((a, i) => `${i + 1}. ${a}`).join('\n');
|
||||||
|
const prompt = `你是一个专业的中文地址解析助手。请一次性解析以下 ${addressList.length} 条地址,按编号顺序返回JSON数组,每条为:
|
||||||
|
{"index":编号,"province":"省","city":"市","area":"区/县","town":"乡镇/街道","detailAddress":"详细地址","name":"收件人","mobile":"手机号"}
|
||||||
|
规则:
|
||||||
|
1. 地址重复拼接时先智能去重再解析
|
||||||
|
2. 直辖市:province与city都填直辖市名,area填市辖区名
|
||||||
|
3. 无法识别的字段填空字符串
|
||||||
|
4. 只返回JSON数组,不含解释或markdown
|
||||||
|
|
||||||
|
地址列表:
|
||||||
|
${numbered}`;
|
||||||
|
|
||||||
|
try {
|
||||||
|
const result = await this.ctx.curl(`${baseUrl}/v1/chat/completions`, {
|
||||||
|
method: 'POST',
|
||||||
|
contentType: 'json',
|
||||||
|
dataType: 'json',
|
||||||
|
headers: {
|
||||||
|
Authorization: `Bearer ${apiKey}`,
|
||||||
|
},
|
||||||
|
data: {
|
||||||
|
model: 'deepseek-v4-flash',
|
||||||
|
messages: [
|
||||||
|
{ role: 'system', content: '你是一个专业的地址解析助手,只返回JSON格式结果。' },
|
||||||
|
{ role: 'user', content: prompt },
|
||||||
|
],
|
||||||
|
temperature: 0,
|
||||||
|
max_tokens: 32000,
|
||||||
|
},
|
||||||
|
timeout: 120000,
|
||||||
|
});
|
||||||
|
|
||||||
|
if (result.status !== 200 || !result.data) {
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
const choice = result.data.choices?.[0] || {};
|
||||||
|
// 被截断时整体回退,避免残缺数组造成大量错位
|
||||||
|
if ((choice.finish_reason || '') === 'length') {
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
const content = String(choice.message?.content || '').trim();
|
||||||
|
const arr = JSON.parse(extractJsonBlock(content));
|
||||||
|
if (!Array.isArray(arr)) {
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
this.ctx.logger.info('[parseAddress] 批量块请求完成:入参 %d 条,finish_reason=%s,返回 %d 条', addressList.length, choice.finish_reason, arr.length);
|
||||||
|
|
||||||
|
return addressList.map((address, idx) => {
|
||||||
|
if (!String(address || '').trim()) {
|
||||||
|
return { address, ok: false, flag: 'failure', message: '地址字符串不能为空', fields: null };
|
||||||
|
}
|
||||||
|
const item = arr.find(x => x && Number(x.index) === idx + 1);
|
||||||
|
if (!item) {
|
||||||
|
return { address, ok: false, flag: 'failure', message: '批量解析未返回该条结果', fields: null };
|
||||||
|
}
|
||||||
|
|
||||||
|
let province = String(item.province || '').trim();
|
||||||
|
let city = String(item.city || '').trim();
|
||||||
|
let area = String(item.area || '').trim();
|
||||||
|
let town = String(item.town || '').trim();
|
||||||
|
const detailAddress = String(item.detailAddress || '').trim();
|
||||||
|
const name = sanitizeName(item.name);
|
||||||
|
const mobile = sanitizeMobile(item.mobile);
|
||||||
|
|
||||||
|
// 反向识别兜底 + 正则兜底,与单条解析保持一致
|
||||||
|
const inferred = reverseInferAddress({ province, city, area, town, detailAddress, name, mobile });
|
||||||
|
province = inferred.province;
|
||||||
|
city = inferred.city;
|
||||||
|
area = inferred.area;
|
||||||
|
if (!province) {
|
||||||
|
const regexResult = extractAddressByRegex(address);
|
||||||
|
if (regexResult.province) {
|
||||||
|
province = regexResult.province;
|
||||||
|
city = city || regexResult.city;
|
||||||
|
area = area || regexResult.area;
|
||||||
|
town = town || regexResult.town;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if (!province || province === '暂未识别' || province === '其他') {
|
||||||
|
return { address, ok: false, flag: 'failure', message: '地址解析失败:省市区无法识别,请补充更多地址信息后重试', fields: null };
|
||||||
|
}
|
||||||
|
return {
|
||||||
|
address,
|
||||||
|
ok: true,
|
||||||
|
flag: 'success',
|
||||||
|
message: 'ok',
|
||||||
|
fields: { province, city, area, town, detailAddress, name, mobile },
|
||||||
|
};
|
||||||
|
});
|
||||||
|
} catch (error) {
|
||||||
|
this.ctx.logger.warn('[parseAddress] 批量一次性解析失败,将逐条回退: %s', error.message);
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 解析单条地址(parseAddress 单条/批量模式共用)。
|
||||||
|
*
|
||||||
|
* @param {*} item 原始地址。
|
||||||
|
* @return {Promise<Object>} { address, ok, flag, message, fields };fields 为解析字段对象或 null。
|
||||||
|
*/
|
||||||
|
async _parseSingleAddress(item) {
|
||||||
|
const address = String(item || '').trim();
|
||||||
if (!address) {
|
if (!address) {
|
||||||
return this.fail('地址字符串不能为空');
|
return { address, ok: false, flag: 'failure', message: '地址字符串不能为空', fields: null };
|
||||||
}
|
}
|
||||||
|
|
||||||
const apiKey = this.config.deepseek.apiKey;
|
const apiKey = this.config.deepseek.apiKey;
|
||||||
const baseUrl = this.config.deepseek.baseUrl || 'https://api.deepseek.com';
|
const baseUrl = this.config.deepseek.baseUrl || 'https://api.deepseek.com';
|
||||||
if (!apiKey) {
|
if (!apiKey) {
|
||||||
return this.fail('DeepSeek API Key 未配置');
|
return { address, ok: false, flag: 'failure', message: 'DeepSeek API Key 未配置', fields: null };
|
||||||
}
|
}
|
||||||
|
|
||||||
try {
|
try {
|
||||||
|
// 仅在 parseAddress 使用 v4-flash(速度优先,适合批量解析),不改全局配置
|
||||||
|
const model = 'deepseek-v4-flash';
|
||||||
const prompt = `你是一个专业的中文地址解析助手,拥有丰富的中国地理知识。请解析以下地址字符串。
|
const prompt = `你是一个专业的中文地址解析助手,拥有丰富的中国地理知识。请解析以下地址字符串。
|
||||||
|
|
||||||
规则:
|
规则:
|
||||||
@ -3252,73 +3558,143 @@ class PendingOrderService extends OrderBaseService {
|
|||||||
- "浙江省xxx村" → 根据村名命名习惯和方言特征推测所属城市
|
- "浙江省xxx村" → 根据村名命名习惯和方言特征推测所属城市
|
||||||
4. 如果实在无法确定,province填"",city和area同理填"",收件人和name同理填"",mobile同理填""。
|
4. 如果实在无法确定,province填"",city和area同理填"",收件人和name同理填"",mobile同理填""。
|
||||||
5. detailAddress去除省市区部分,只保留街道/村/门牌号
|
5. detailAddress去除省市区部分,只保留街道/村/门牌号
|
||||||
6. 只返回纯JSON,不含解释或markdown
|
6. 地址字符串若出现重复拼接(如"陕西省延安市志丹县"出现两次),先智能去重再解析,合并保留重复部分中的街道/村信息
|
||||||
|
7. 只返回纯JSON,不含解释或markdown
|
||||||
|
|
||||||
地址字符串: "${address}"
|
地址字符串: "${address}"
|
||||||
|
|
||||||
请返回JSON:`;
|
请返回JSON:`;
|
||||||
|
|
||||||
const result = await this.ctx.curl(`${baseUrl}/v1/chat/completions`, {
|
const requestDeepSeek = async maxTokens => {
|
||||||
method: 'POST',
|
const result = await this.ctx.curl(`${baseUrl}/v1/chat/completions`, {
|
||||||
contentType: 'json',
|
method: 'POST',
|
||||||
dataType: 'json',
|
contentType: 'json',
|
||||||
headers: {
|
dataType: 'json',
|
||||||
Authorization: `Bearer ${apiKey}`,
|
headers: {
|
||||||
},
|
Authorization: `Bearer ${apiKey}`,
|
||||||
data: {
|
},
|
||||||
model: 'deepseek-v4-pro',
|
data: {
|
||||||
messages: [
|
model,
|
||||||
{ role: 'system', content: '你是一个专业的地址解析助手,只返回JSON格式结果。' },
|
messages: [
|
||||||
{ role: 'user', content: prompt },
|
{ role: 'system', content: '你是一个专业的地址解析助手,只返回JSON格式结果。' },
|
||||||
],
|
{ role: 'user', content: prompt },
|
||||||
temperature: 0,
|
],
|
||||||
max_tokens: 500,
|
temperature: 0,
|
||||||
},
|
max_tokens: maxTokens,
|
||||||
timeout: 15000,
|
},
|
||||||
});
|
timeout: 60000,
|
||||||
|
|
||||||
if (result.status !== 200 || !result.data) {
|
|
||||||
return this.fail('地址解析服务请求失败');
|
|
||||||
}
|
|
||||||
|
|
||||||
const content = result.data.choices?.[0]?.message?.content || '';
|
|
||||||
this.ctx.logger.info('[parseAddress] DeepSeek原始返回content: %s', content);
|
|
||||||
|
|
||||||
// 清理可能的 markdown 代码块标记
|
|
||||||
let jsonStr = content.trim();
|
|
||||||
jsonStr = jsonStr.replace(/^```json\s*/i, '').replace(/\s*```$/i, '');
|
|
||||||
jsonStr = jsonStr.replace(/^```\s*/i, '').replace(/\s*```$/i, '');
|
|
||||||
|
|
||||||
try {
|
|
||||||
const parsed = JSON.parse(jsonStr);
|
|
||||||
let province = String(parsed.province || '').trim();
|
|
||||||
let city = String(parsed.city || '').trim();
|
|
||||||
let area = String(parsed.area || '').trim();
|
|
||||||
const town = String(parsed.town || '').trim();
|
|
||||||
const detailAddress = String(parsed.detailAddress || '').trim();
|
|
||||||
const name = String(parsed.name || '').trim();
|
|
||||||
const mobile = String(parsed.mobile || '').trim();
|
|
||||||
|
|
||||||
// --- 反向识别兜底:使用内置行政区划映射表补全缺失字段 ---
|
|
||||||
const inferred = reverseInferAddress({
|
|
||||||
province,
|
|
||||||
city,
|
|
||||||
area,
|
|
||||||
town,
|
|
||||||
detailAddress,
|
|
||||||
name,
|
|
||||||
mobile,
|
|
||||||
});
|
});
|
||||||
province = inferred.province;
|
|
||||||
city = inferred.city;
|
|
||||||
area = inferred.area;
|
|
||||||
|
|
||||||
// 反向识别后仍无 province 才判定失败
|
if (result.status !== 200 || !result.data) {
|
||||||
if (!province || province === '暂未识别' || province === '其他') {
|
return null;
|
||||||
return this.fail('地址解析失败:省市区无法识别,请补充更多地址信息后重试');
|
|
||||||
}
|
}
|
||||||
|
const choice = result.data.choices?.[0] || {};
|
||||||
|
return {
|
||||||
|
content: String(choice.message?.content || '').trim(),
|
||||||
|
reasoningContent: String(choice.message?.reasoning_content || '').trim(),
|
||||||
|
finishReason: choice.finish_reason || '',
|
||||||
|
};
|
||||||
|
};
|
||||||
|
|
||||||
return this.success('地址解析成功', {
|
// deepseek-v4-flash 为思维链模型,max_tokens 过小时推理会耗尽全部配额,
|
||||||
|
// 导致 content 为空且 finish_reason=length。首次给足 3000 tokens,
|
||||||
|
// 仍被截断且无法从 reasoning_content 兜底时,加大到 8000 重试一次。
|
||||||
|
let response = await requestDeepSeek(3000);
|
||||||
|
if (
|
||||||
|
response
|
||||||
|
&& response.finishReason === 'length'
|
||||||
|
&& !response.content
|
||||||
|
&& !salvageFieldsFromText(response.reasoningContent)
|
||||||
|
) {
|
||||||
|
this.ctx.logger.warn('[parseAddress] 首次调用被截断(finish_reason=length),以 max_tokens=8000 重试');
|
||||||
|
response = await requestDeepSeek(8000);
|
||||||
|
}
|
||||||
|
|
||||||
|
if (!response) {
|
||||||
|
return { address, ok: false, flag: 'failure', message: '地址解析服务请求失败', fields: null };
|
||||||
|
}
|
||||||
|
|
||||||
|
const { content, reasoningContent, finishReason } = response;
|
||||||
|
this.ctx.logger.info('[parseAddress] DeepSeek原始返回 finish_reason=%s content: %s', finishReason, content || '(空)');
|
||||||
|
|
||||||
|
const tryParseJson = raw => {
|
||||||
|
try {
|
||||||
|
return JSON.parse(raw);
|
||||||
|
} catch (parseError) {
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
// 清理 markdown 代码块标记,并截取第一个 { 到最后一个 } 之间的 JSON 片段
|
||||||
|
let parsed = tryParseJson(extractJsonBlock(content));
|
||||||
|
if (!parsed) {
|
||||||
|
// 轻量修复:去除对象/数组内的尾随逗号后重试
|
||||||
|
parsed = tryParseJson(extractJsonBlock(content).replace(/,\s*([}\]])/g, '$1'));
|
||||||
|
}
|
||||||
|
|
||||||
|
// JSON 解析失败时,尝试从 content 或 reasoning_content 文本中做字段级提取兜底
|
||||||
|
if (!parsed) {
|
||||||
|
parsed = salvageFieldsFromText(content || reasoningContent);
|
||||||
|
if (parsed) {
|
||||||
|
this.ctx.logger.warn('[parseAddress] 正文字段提取兜底结果: %j', parsed);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if (!parsed) {
|
||||||
|
this.ctx.logger.warn('[parseAddress] JSON解析失败,finish_reason=%s,原始返回: %s', finishReason, content || reasoningContent);
|
||||||
|
if (finishReason === 'length') {
|
||||||
|
return { address, ok: false, flag: 'failure', message: '地址解析超时,请重试', fields: null };
|
||||||
|
}
|
||||||
|
return { address, ok: false, flag: 'failure', message: '地址解析结果格式异常,请重试', fields: null };
|
||||||
|
}
|
||||||
|
|
||||||
|
let province = String(parsed.province || '').trim();
|
||||||
|
let city = String(parsed.city || '').trim();
|
||||||
|
let area = String(parsed.area || '').trim();
|
||||||
|
let town = String(parsed.town || '').trim();
|
||||||
|
const detailAddress = String(parsed.detailAddress || '').trim();
|
||||||
|
const name = sanitizeName(parsed.name);
|
||||||
|
const mobile = sanitizeMobile(parsed.mobile);
|
||||||
|
|
||||||
|
// --- 反向识别兜底:使用内置行政区划映射表补全缺失字段 ---
|
||||||
|
const inferred = reverseInferAddress({
|
||||||
|
province,
|
||||||
|
city,
|
||||||
|
area,
|
||||||
|
town,
|
||||||
|
detailAddress,
|
||||||
|
name,
|
||||||
|
mobile,
|
||||||
|
});
|
||||||
|
province = inferred.province;
|
||||||
|
city = inferred.city;
|
||||||
|
area = inferred.area;
|
||||||
|
|
||||||
|
// --- 最终兜底:AI 与映射表均失败时,用正则从原始地址提取省市区 ---
|
||||||
|
if (!province) {
|
||||||
|
const regexResult = extractAddressByRegex(address);
|
||||||
|
if (regexResult.province) {
|
||||||
|
province = regexResult.province;
|
||||||
|
city = city || regexResult.city;
|
||||||
|
area = area || regexResult.area;
|
||||||
|
if (!town) {
|
||||||
|
town = regexResult.town;
|
||||||
|
}
|
||||||
|
this.ctx.logger.warn('[parseAddress] 正则兜底解析结果: %j', regexResult);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// 反向识别后仍无 province 才判定失败
|
||||||
|
if (!province || province === '暂未识别' || province === '其他') {
|
||||||
|
return { address, ok: false, flag: 'failure', message: '地址解析失败:省市区无法识别,请补充更多地址信息后重试', fields: null };
|
||||||
|
}
|
||||||
|
|
||||||
|
return {
|
||||||
|
address,
|
||||||
|
ok: true,
|
||||||
|
flag: 'success',
|
||||||
|
message: 'ok',
|
||||||
|
fields: {
|
||||||
province,
|
province,
|
||||||
city,
|
city,
|
||||||
area,
|
area,
|
||||||
@ -3326,14 +3702,11 @@ class PendingOrderService extends OrderBaseService {
|
|||||||
detailAddress,
|
detailAddress,
|
||||||
name,
|
name,
|
||||||
mobile,
|
mobile,
|
||||||
});
|
},
|
||||||
} catch (parseError) {
|
};
|
||||||
this.ctx.logger.warn('[parseAddress] JSON解析失败,原始返回: %s', content);
|
|
||||||
return this.fail('地址解析结果格式异常,请重试');
|
|
||||||
}
|
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
this.ctx.logger.error('[parseAddress] DeepSeek请求异常: %s', error.message);
|
this.ctx.logger.error('[parseAddress] DeepSeek请求异常: %s', error.message);
|
||||||
return this.fail(`地址解析失败: ${error.message}`);
|
return { address, ok: false, flag: 'failure', message: `地址解析失败: ${error.message}`, fields: null };
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@ -17,6 +17,23 @@
|
|||||||
],
|
],
|
||||||
"module": "order"
|
"module": "order"
|
||||||
},
|
},
|
||||||
|
{
|
||||||
|
"version": "2026.08.15-parseAddress.batch",
|
||||||
|
"date": "2026-08-15",
|
||||||
|
"type": "enhanced",
|
||||||
|
"summary": "parseAddress 支持数组批量入参:addresses(或 address)传字符串数组时批量解析,响应 data.list 按输入顺序返回每条地址的解析结果(含失败条目逐条错误信息)",
|
||||||
|
"methods": [
|
||||||
|
"order.pendingOrder.parseAddress"
|
||||||
|
],
|
||||||
|
"notes": [
|
||||||
|
"入参兼容三种形态:address 字符串(单条,原行为不变)、address 字符串数组、addresses 字符串数组(优先)",
|
||||||
|
"批量解析:按每 10 条合并为一个 DeepSeek 请求并行发出(deepseek-v4-flash),全部返回后按输入顺序聚合,单次上限 50 条;失败/缺失条目逐条回退单条解析,不影响其他条目",
|
||||||
|
"批量响应 data.list 每条元素包含 address/flag/message/province/city/area/town/detailAddress/name/mobile,失败条目 flag=failure、message 为具体错误原因、解析字段为空字符串,不影响其他条目",
|
||||||
|
"抽取 _parseSingleAddress 私有方法复用单条解析逻辑,单条响应结构与之前完全一致",
|
||||||
|
"同步更新 methods/system.json 中 parseAddress 的参数与响应字段说明"
|
||||||
|
],
|
||||||
|
"module": "order"
|
||||||
|
},
|
||||||
{
|
{
|
||||||
"version": "2026.08.14-afterSale.detail-desc-first-step",
|
"version": "2026.08.14-afterSale.detail-desc-first-step",
|
||||||
"date": "2026-08-14",
|
"date": "2026-08-14",
|
||||||
|
|||||||
@ -1,8 +1,8 @@
|
|||||||
{
|
{
|
||||||
"module": "system",
|
"module": "system",
|
||||||
"description": "系统接口标准入口,method 对应系统内置方法,全部使用 POST 请求,参数统一放在 body 内",
|
"description": "系统接口标准入口,method 对应系统内置方法,全部使用 POST 请求,参数统一放在 body 内",
|
||||||
"version": "0.3.27",
|
"version": "0.3.28",
|
||||||
"updatedAt": "2026-08-13",
|
"updatedAt": "2026-08-15",
|
||||||
"headers": [
|
"headers": [
|
||||||
{
|
{
|
||||||
"name": "platform",
|
"name": "platform",
|
||||||
@ -4241,7 +4241,7 @@
|
|||||||
},
|
},
|
||||||
{
|
{
|
||||||
"method": "order.pendingOrder.parseAddress",
|
"method": "order.pendingOrder.parseAddress",
|
||||||
"description": "智能地址解析:使用 AI 将非结构化地址字符串解析为省/市/区/详细地址/收件人/手机号",
|
"description": "智能地址解析:使用 AI 将非结构化地址字符串解析为省/市/区/详细地址/收件人/手机号。支持单条解析与数组批量解析:address 传字符串时返回单条结果,addresses(或 address)传字符串数组时批量解析,响应 data.list 按输入顺序返回每条地址的解析结果(失败条目 flag=failure 不影响其他条目)。",
|
||||||
"isNeedAuth": false,
|
"isNeedAuth": false,
|
||||||
"isNeedLogin": true,
|
"isNeedLogin": true,
|
||||||
"headers": [],
|
"headers": [],
|
||||||
@ -4251,7 +4251,14 @@
|
|||||||
"type": "string",
|
"type": "string",
|
||||||
"required": true,
|
"required": true,
|
||||||
"source": "body",
|
"source": "body",
|
||||||
"description": "原始地址字符串(必填),如\"张三 13800138000 广东省广州市天河区体育西路100号\""
|
"description": "原始地址字符串(必填),如\"张三 13800138000 广东省广州市天河区体育西路100号\"。也支持传字符串数组批量解析(与 addresses 二选一)"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"name": "addresses",
|
||||||
|
"type": "string[]",
|
||||||
|
"required": false,
|
||||||
|
"source": "body",
|
||||||
|
"description": "批量地址字符串数组,单次最多 50 条,按数组顺序返回解析结果"
|
||||||
}
|
}
|
||||||
],
|
],
|
||||||
"requestBody": [],
|
"requestBody": [],
|
||||||
@ -4315,6 +4322,72 @@
|
|||||||
"type": "string",
|
"type": "string",
|
||||||
"required": false,
|
"required": false,
|
||||||
"description": "收件人手机号,如 13800138000"
|
"description": "收件人手机号,如 13800138000"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"name": "data.list",
|
||||||
|
"type": "array",
|
||||||
|
"required": false,
|
||||||
|
"description": "批量解析时返回的结果数组,按输入顺序排列;每条含 address/flag/message/province/city/area/town/detailAddress/name/mobile,失败条目 flag=failure 且解析字段为空字符串"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"name": "data.list[].address",
|
||||||
|
"type": "string",
|
||||||
|
"required": false,
|
||||||
|
"description": "原始地址字符串(原样返回)"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"name": "data.list[].flag",
|
||||||
|
"type": "string",
|
||||||
|
"required": false,
|
||||||
|
"description": "该条解析状态:success=成功,failure=失败"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"name": "data.list[].message",
|
||||||
|
"type": "string",
|
||||||
|
"required": false,
|
||||||
|
"description": "该条解析提示:成功为 ok,失败为具体错误原因"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"name": "data.list[].province",
|
||||||
|
"type": "string",
|
||||||
|
"required": false,
|
||||||
|
"description": "省份,如 广东省"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"name": "data.list[].city",
|
||||||
|
"type": "string",
|
||||||
|
"required": false,
|
||||||
|
"description": "城市,如 广州市"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"name": "data.list[].area",
|
||||||
|
"type": "string",
|
||||||
|
"required": false,
|
||||||
|
"description": "区/县,如 天河区"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"name": "data.list[].town",
|
||||||
|
"type": "string",
|
||||||
|
"required": false,
|
||||||
|
"description": "乡镇/街道,如 员村街道"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"name": "data.list[].detailAddress",
|
||||||
|
"type": "string",
|
||||||
|
"required": false,
|
||||||
|
"description": "详细地址,如 体育西路100号"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"name": "data.list[].name",
|
||||||
|
"type": "string",
|
||||||
|
"required": false,
|
||||||
|
"description": "收件人姓名,如 张三"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"name": "data.list[].mobile",
|
||||||
|
"type": "string",
|
||||||
|
"required": false,
|
||||||
|
"description": "收件人手机号,如 13800138000"
|
||||||
}
|
}
|
||||||
],
|
],
|
||||||
"errors": [
|
"errors": [
|
||||||
@ -4322,6 +4395,14 @@
|
|||||||
"code": 400,
|
"code": 400,
|
||||||
"message": "地址字符串不能为空"
|
"message": "地址字符串不能为空"
|
||||||
},
|
},
|
||||||
|
{
|
||||||
|
"code": 400,
|
||||||
|
"message": "地址数组不能为空"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"code": 400,
|
||||||
|
"message": "单次批量解析最多支持 50 条地址"
|
||||||
|
},
|
||||||
{
|
{
|
||||||
"code": 500,
|
"code": 500,
|
||||||
"message": "地址解析失败(AI服务异常或密钥未配置)"
|
"message": "地址解析失败(AI服务异常或密钥未配置)"
|
||||||
@ -4331,7 +4412,8 @@
|
|||||||
"方法部署位置:systemMethods/order/pendingOrder/parseAddress",
|
"方法部署位置:systemMethods/order/pendingOrder/parseAddress",
|
||||||
"使用 DeepSeek AI 模型进行智能解析",
|
"使用 DeepSeek AI 模型进行智能解析",
|
||||||
"解析结果可直接回填到 createOrder 的收件人信息字段",
|
"解析结果可直接回填到 createOrder 的收件人信息字段",
|
||||||
"未识别到的字段返回空字符串"
|
"未识别到的字段返回空字符串",
|
||||||
|
"批量解析:addresses 或 address 传字符串数组,按每 10 条合并为一个请求并行发出,全部返回后按输入顺序聚合,单条失败不影响其他条目(模型 deepseek-v4-flash)"
|
||||||
]
|
]
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
|
|||||||
Loading…
x
Reference in New Issue
Block a user