来源仓库:jxc/ai-fresh-delivery 来源提交:f0b1a180e2deb7e4673b9d1c8542619f7bc0f73d 快照树: 09f679334ff38f0ff25e907961c94a8223bcaedd(与来源 HEAD 工作树逐字节一致,3801 个文件) 按约定本仓库不带任何历史提交:来源仓库的历史中含真实凭据 (生产 SSH 私钥 deploy/id_rsa_tencent、server/.env、.env.tencent/.env.production/.env.gitea、 deploy/小程序AppSecret.txt,其中 MP_APPSECRET / S3 AccessKey 经哈希比对与线上同值), 整包推送会把这些凭据永久带入本仓库,故只取「当前版本」的单提交快照。 供应商系统后续开发自本提交开始。
157 lines
6.8 KiB
TypeScript
157 lines
6.8 KiB
TypeScript
/**
|
||
* 会话「工作集」:把多轮任务的关键实体结构化留下来(P2b,2026-09-22)。
|
||
*
|
||
* 为什么需要它:只回灌最近几条原文,长会话里的关键指代("那单""那个客户")仍易丢;
|
||
* 而把**最近涉及的单据/客户/商品/条件**结构化后每轮注入只需几百字符,既省又准。
|
||
* 它是纯函数组合:从工具调用与结果里抽取实体 → 合并去重(有上限)→ 渲染成提示词片段。
|
||
*
|
||
* 铁律不变:工作集只是"指代线索",**数字与状态必须重新调工具**。
|
||
*/
|
||
|
||
export type AssistantWorkingSet = {
|
||
/** 最近涉及的业务实体(按 kind 分桶,新的在前)。 */
|
||
entities: { kind: string; id: string; label?: string }[];
|
||
/** 最近一次查询类工具与条件(帮助模型理解"刚才在查什么")。 */
|
||
lastTool?: { name: string; args: string; at: string } | null;
|
||
/** 最近一次待确认写操作的能力名(如有)。 */
|
||
pendingCapability?: string | null;
|
||
};
|
||
|
||
export const EMPTY_WORKING_SET: AssistantWorkingSet = { entities: [], lastTool: null, pendingCapability: null };
|
||
|
||
export const WORKING_SET_MAX_ENTITIES = 24;
|
||
const ID_PATTERNS: Array<{ kind: string; re: RegExp }> = [
|
||
{ kind: '订单', re: /\bORD_[A-Za-z0-9_]{4,}\b/g },
|
||
{ kind: '订单', re: /\bORD[A-Z0-9]{8,}\b/g },
|
||
{ kind: '结算单', re: /\bSS\d{8,}\b/g },
|
||
{ kind: '客户结算', re: /\bCS\d{8,}\b/g },
|
||
{ kind: '客户', re: /\bCUS\d{6,}\b/g },
|
||
{ kind: '供应商', re: /\bSUP\d{6,}\b/g },
|
||
{ kind: '商品', re: /\bSKU[A-Z0-9]{6,}\b/g },
|
||
{ kind: '批次', re: /\bIN\d{8,}[A-Z0-9]{2,}\b/g },
|
||
{ kind: '自采单', re: /\bPO\d{8,}\b/g },
|
||
{ kind: '售后单', re: /\b(?:OIR|SIV|OIS)_[A-Za-z0-9_]{4,}\b/g },
|
||
];
|
||
const KEY_HINTS = /order_code|customer_code|supplier_code|sku_code|statement_no|batch_no|code|_id$/i;
|
||
|
||
function clip(v: unknown, max: number): string {
|
||
const s = typeof v === 'string' ? v : '';
|
||
return s.length > max ? `${s.slice(0, max)}…` : s;
|
||
}
|
||
|
||
/** 从任意结果/参数里抽取可辨识实体(深度与数量都设上限)。 */
|
||
export function extractEntities(
|
||
value: unknown,
|
||
out: { kind: string; id: string; label?: string }[] = [],
|
||
depth = 0
|
||
): { kind: string; id: string; label?: string }[] {
|
||
if (value == null || depth > 4 || out.length >= WORKING_SET_MAX_ENTITIES * 2) return out;
|
||
if (typeof value === 'string') {
|
||
for (const { kind, re } of ID_PATTERNS) {
|
||
for (const hit of value.matchAll(re)) out.push({ kind, id: hit[0] });
|
||
}
|
||
return out;
|
||
}
|
||
if (Array.isArray(value)) {
|
||
for (const row of value.slice(0, 20)) extractEntities(row, out, depth + 1);
|
||
return out;
|
||
}
|
||
if (typeof value === 'object') {
|
||
// 同一对象里的「id 键 + 名称键」配成一条(label 打在**本对象**新抽取的第一个实体上)
|
||
const startIndex = out.length;
|
||
let nameLabel: string | null = null;
|
||
for (const [key, val] of Object.entries(value as Record<string, unknown>)) {
|
||
if (typeof val === 'string' && KEY_HINTS.test(key) && val.trim()) {
|
||
const hit = ID_PATTERNS.map((p) => ({ kind: p.kind, id: (val.match(p.re) || [])[0] })).find((x) => x.id);
|
||
if (hit?.id) out.push({ kind: hit.kind, id: hit.id });
|
||
}
|
||
// 标签键同时认 snake_case(能力结果)与 camelCase(模型给的 args / 页面 ui_action 载荷)
|
||
if (
|
||
key === 'item_name' ||
|
||
key === 'sku_name' ||
|
||
key === 'customer_name' ||
|
||
key === 'company_name' ||
|
||
key === 'itemName' ||
|
||
key === 'skuName' ||
|
||
key === 'customerName' ||
|
||
key === 'companyName'
|
||
) {
|
||
const label = clip(val, 24);
|
||
if (label) nameLabel = label;
|
||
}
|
||
extractEntities(val, out, depth + 1);
|
||
}
|
||
if (nameLabel) {
|
||
const target = out.slice(startIndex).find((row) => !row.label);
|
||
if (target) target.label = nameLabel;
|
||
}
|
||
}
|
||
return out;
|
||
}
|
||
|
||
/** 合并本轮结果到工作集:新的排前面、按 kind+id 去重、总量设上限。 */
|
||
export function mergeWorkingSet(
|
||
prev: AssistantWorkingSet | null | undefined,
|
||
input: {
|
||
toolName?: string;
|
||
args?: Record<string, unknown>;
|
||
result?: unknown;
|
||
pendingCapability?: string | null;
|
||
at?: string;
|
||
}
|
||
): AssistantWorkingSet {
|
||
// 入参与结果都要抽:只从 result 抽会漏掉"只在入参里出现"的对象 ——
|
||
// 最典型的是改单/预览(prepare_order_edit、preview_order)在**等用户确认**时 result 为空,
|
||
// 订单号与 SKU 只存在于 args 里,于是工作集拿不到任何实体,后续"那单/那个客户"就断了指代。
|
||
const fresh = [...extractEntities(input.args ?? null), ...extractEntities(input.result)];
|
||
const seen = new Set<string>();
|
||
const merged: AssistantWorkingSet['entities'] = [];
|
||
for (const row of [...fresh, ...(prev?.entities || [])]) {
|
||
const key = `${row.kind}:${row.id}`;
|
||
if (seen.has(key)) continue;
|
||
seen.add(key);
|
||
merged.push(row);
|
||
if (merged.length >= WORKING_SET_MAX_ENTITIES) break;
|
||
}
|
||
const argText = input.args
|
||
? clip(
|
||
Object.entries(input.args)
|
||
.filter(([, v]) => v !== null && v !== undefined && v !== '')
|
||
.map(([k, v]) => `${k}=${typeof v === 'object' ? JSON.stringify(v) : String(v)}`)
|
||
.join(' '),
|
||
120
|
||
)
|
||
: '';
|
||
return {
|
||
entities: merged,
|
||
lastTool: input.toolName ? { name: input.toolName, args: argText, at: input.at || '' } : prev?.lastTool || null,
|
||
pendingCapability: input.pendingCapability ?? prev?.pendingCapability ?? null,
|
||
};
|
||
}
|
||
|
||
/** 是否值得持久化(避免每轮都给同一份工作集写库)。 */
|
||
export function workingSetChanged(prev: AssistantWorkingSet | null | undefined, next: AssistantWorkingSet): boolean {
|
||
return JSON.stringify(prev || EMPTY_WORKING_SET) !== JSON.stringify(next);
|
||
}
|
||
|
||
/** 渲染成提示词片段(上限 ~700 字符;没有内容返回空串)。 */
|
||
export function renderWorkingSet(ws: AssistantWorkingSet | null | undefined, maxChars = 700): string {
|
||
if (!ws) return '';
|
||
const parts: string[] = [];
|
||
const grouped = new Map<string, string[]>();
|
||
for (const row of ws.entities || []) {
|
||
const list = grouped.get(row.kind) || [];
|
||
list.push(row.label ? `${row.id}(${row.label})` : row.id);
|
||
grouped.set(row.kind, list);
|
||
}
|
||
for (const [kind, ids] of grouped) parts.push(`${kind}:${ids.slice(0, 4).join('、')}`);
|
||
if (ws.lastTool?.name) {
|
||
parts.push(`上次调用:${ws.lastTool.name}${ws.lastTool.args ? ` ${ws.lastTool.args}` : ''}`);
|
||
}
|
||
if (ws.pendingCapability) parts.push(`待确认操作:${ws.pendingCapability}`);
|
||
if (!parts.length) return '';
|
||
const note = '工作集(最近涉及对象,仅作指代线索;数字/状态必须重新调工具):';
|
||
const text = `${note}${parts.join(';')}`;
|
||
return text.length > maxChars ? `${text.slice(0, maxChars)}…` : text;
|
||
}
|