来源仓库: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 经哈希比对与线上同值), 整包推送会把这些凭据永久带入本仓库,故只取「当前版本」的单提交快照。 供应商系统后续开发自本提交开始。
233 lines
10 KiB
TypeScript
233 lines
10 KiB
TypeScript
/**
|
||
* 助手会话「分段摘要」(P2b-5,2026-09-23)。
|
||
*
|
||
* 目标:长会话里"最早那几十条讲了什么"不用整段回灌,也不用模型瞎猜关键词 ——
|
||
* 后台把**较老的一段**滚动压缩成要点摘要,注入系统提示(与工作集同级),
|
||
* 与 `read_conversation_history`(读原文细节)形成"摘要导航 + 原文展开"两级。
|
||
*
|
||
* 铁律:
|
||
* - **不阻塞对话**:只在 `/chat` 落库之后 fire-and-forget 触发,失败只告警;
|
||
* - **独立开关与独立预算**:`ASSISTANT_SUMMARY` / `ASSISTANT_SUMMARY_MAX_TOKENS` / `..._TIMEOUT_MS`,
|
||
* 不挪用主回答的 token 预算;
|
||
* - **不碰最近 KEEP 条**:最近的消息仍以原文回灌,摘要只覆盖"较老且已攒够批"的部分;
|
||
* - **摘要只用于理解指代**:数字/状态/列表必须重新调工具(与 `assistantHistoryRule` 同口径)。
|
||
*
|
||
* 设计:docs/design/20260923-assistant-p2b-summary-plan-sse.md §1
|
||
*/
|
||
|
||
import { chatCompletionsWithTools, type ChatMessage } from '../mcp/llmChatWithTools';
|
||
import { resolveLlmRuntimeConfig } from './llmService';
|
||
import {
|
||
claimAssistantConversationSummary,
|
||
describeAssistantHistory,
|
||
listAssistantMessageSegment,
|
||
loadAssistantConversationSummary,
|
||
saveAssistantConversationSummary,
|
||
} from './assistantChatLogService';
|
||
|
||
function clampInt(raw: unknown, min: number, max: number, fallback: number): number {
|
||
const n = Number(raw);
|
||
if (!Number.isFinite(n)) return fallback;
|
||
return Math.min(max, Math.max(min, Math.floor(n)));
|
||
}
|
||
|
||
function readFlag(raw: unknown, fallback: boolean): boolean {
|
||
const value = String(raw ?? '').trim().toLowerCase();
|
||
if (!value) return fallback;
|
||
if (['0', 'false', 'off', 'no'].includes(value)) return false;
|
||
if (['1', 'true', 'on', 'yes'].includes(value)) return true;
|
||
return fallback;
|
||
}
|
||
|
||
/** 总开关:关闭后不再生成摘要(已存摘要仍可注入,除非开发者要求一并停用)。 */
|
||
export const ASSISTANT_SUMMARY_ENABLED = readFlag(process.env.ASSISTANT_SUMMARY, true);
|
||
/** 消息总量超过它才考虑压缩(避免短会话无谓调模型)。 */
|
||
export const ASSISTANT_SUMMARY_MIN_MESSAGES = clampInt(process.env.ASSISTANT_SUMMARY_MIN_MESSAGES, 8, 5_000, 40);
|
||
/** 每次至少新增多少条未压缩消息才触发一次。 */
|
||
export const ASSISTANT_SUMMARY_BATCH = clampInt(process.env.ASSISTANT_SUMMARY_BATCH, 4, 2_000, 20);
|
||
/** 最近多少条永不进摘要(保持原文高保真)。 */
|
||
export const ASSISTANT_SUMMARY_KEEP = clampInt(process.env.ASSISTANT_SUMMARY_KEEP, 2, 200, 8);
|
||
/** 单次摘要输出上限(独立预算,不占主回答预算)。 */
|
||
export const ASSISTANT_SUMMARY_MAX_TOKENS = clampInt(process.env.ASSISTANT_SUMMARY_MAX_TOKENS, 128, 4_000, 800);
|
||
/** 单次摘要墙钟。 */
|
||
export const ASSISTANT_SUMMARY_TIMEOUT_MS = clampInt(process.env.ASSISTANT_SUMMARY_TIMEOUT_MS, 3_000, 120_000, 20_000);
|
||
/** 摘要落库前截断长度(防止摘要本身变成新的上下文炸弹)。 */
|
||
export const ASSISTANT_SUMMARY_MAX_CHARS = clampInt(process.env.ASSISTANT_SUMMARY_MAX_CHARS, 200, 8_000, 1_500);
|
||
/** 抢锁过期时间(分钟):双活下另一实例的锁多久后可被接手。 */
|
||
export const ASSISTANT_SUMMARY_LOCK_STALE_MINUTES = clampInt(
|
||
process.env.ASSISTANT_SUMMARY_LOCK_STALE_MINUTES,
|
||
1,
|
||
60,
|
||
2
|
||
);
|
||
|
||
export type SummaryTriggerInput = {
|
||
enabled?: boolean;
|
||
total: number;
|
||
covered: number;
|
||
minMessages?: number;
|
||
batch?: number;
|
||
keep?: number;
|
||
};
|
||
|
||
/**
|
||
* 是否需要生成摘要(纯函数,便于边界测试)。
|
||
* 三个条件同时成立:总量过线、未压缩段够批、且这一段不与"最近 KEEP 条"重叠。
|
||
*/
|
||
export function shouldSummarizeConversation(input: SummaryTriggerInput): boolean {
|
||
const enabled = input.enabled ?? ASSISTANT_SUMMARY_ENABLED;
|
||
if (!enabled) return false;
|
||
const total = Math.max(0, Number(input.total) || 0);
|
||
const covered = Math.max(0, Math.min(total, Number(input.covered) || 0));
|
||
const minMessages = input.minMessages ?? ASSISTANT_SUMMARY_MIN_MESSAGES;
|
||
const batch = input.batch ?? ASSISTANT_SUMMARY_BATCH;
|
||
const keep = input.keep ?? ASSISTANT_SUMMARY_KEEP;
|
||
if (total <= minMessages) return false;
|
||
const pending = total - covered;
|
||
if (pending < batch) return false;
|
||
return pending > keep;
|
||
}
|
||
|
||
/** 本次摘要要覆盖的消息区间 `[offset, offset+limit)`(按时间正序),以及覆盖后的 covered。 */
|
||
export function summarySegmentFor(input: {
|
||
total: number;
|
||
covered: number;
|
||
keep?: number;
|
||
}): { offset: number; limit: number; nextCovered: number } {
|
||
const total = Math.max(0, Number(input.total) || 0);
|
||
const covered = Math.max(0, Math.min(total, Number(input.covered) || 0));
|
||
const keep = input.keep ?? ASSISTANT_SUMMARY_KEEP;
|
||
const end = Math.max(covered, total - keep);
|
||
return { offset: covered, limit: end - covered, nextCovered: end };
|
||
}
|
||
|
||
const SUMMARY_SYSTEM_PROMPT = [
|
||
'你在为「鲜配达」业务助手压缩更早的会话记录。',
|
||
'输出要求:',
|
||
'1) 只输出要点列表(每行以 "- " 开头),不要标题、不要客套、不要解释你在做什么;',
|
||
'2) 保留:单号(订单/结算/采购/客户/供应商/商品/批次)、客户与商品名称、日期、金额与数量、',
|
||
' 用户明确的要求与纠正、尚未办完的事项(含待确认的写操作);',
|
||
'3) 丢弃:寒暄、重复确认、工具原始 JSON、被后续对话推翻的中间结论;',
|
||
'4) 数字只照抄原文,**不要推算、不要编造**;原文没有的信息一律不写;',
|
||
'5) 中文输出,尽量紧凑。',
|
||
].join('\n');
|
||
|
||
export type SummaryPromptInput = {
|
||
previousSummary?: string;
|
||
turns: Array<{ role: 'user' | 'assistant'; content: string }>;
|
||
maxChars?: number;
|
||
};
|
||
|
||
/** 构造摘要调用消息(纯函数)。旧摘要 + 新增原文一起压,保证段落衔接。 */
|
||
export function buildSummaryMessages(input: SummaryPromptInput): ChatMessage[] {
|
||
const maxChars = input.maxChars ?? ASSISTANT_SUMMARY_MAX_CHARS;
|
||
const prev = String(input.previousSummary || '').trim();
|
||
const lines = input.turns.map((row) => `${row.role === 'assistant' ? '助手' : '用户'}:${String(row.content || '').trim()}`);
|
||
const body = [
|
||
prev ? `【已有摘要(更早的对话)】\n${prev}` : '',
|
||
`【本次要压缩的对话(时间正序)】\n${lines.join('\n')}`,
|
||
`请输出合并后的新摘要(≤${maxChars} 字),覆盖以上全部内容。`,
|
||
]
|
||
.filter(Boolean)
|
||
.join('\n\n');
|
||
return [
|
||
{ role: 'system', content: SUMMARY_SYSTEM_PROMPT },
|
||
{ role: 'user', content: body },
|
||
];
|
||
}
|
||
|
||
/** 归一化模型输出:去掉空行/多余前后缀并截断。 */
|
||
export function normalizeSummaryOutput(raw: unknown, maxChars = ASSISTANT_SUMMARY_MAX_CHARS): string {
|
||
const text = String(raw || '')
|
||
.replace(/^\s*(摘要|总结|要点)\s*[::]?\s*/u, '')
|
||
.split('\n')
|
||
.map((line) => line.trim())
|
||
.filter(Boolean)
|
||
.join('\n')
|
||
.trim();
|
||
if (text.length <= maxChars) return text;
|
||
return `${text.slice(0, maxChars)}…`;
|
||
}
|
||
|
||
export type SummarizeOutcome = {
|
||
summarized: boolean;
|
||
covered?: number;
|
||
reason?:
|
||
| 'disabled'
|
||
| 'below_threshold'
|
||
| 'locked'
|
||
| 'no_messages'
|
||
| 'not_configured'
|
||
| 'llm_failed'
|
||
| 'empty_summary'
|
||
| 'saved';
|
||
};
|
||
|
||
/**
|
||
* 惰性、后台、best-effort 的摘要生成(调用方**不要 await** 在关键路径上,或 catch 后忽略)。
|
||
* 任何失败都只告警,绝不抛给调用方,也绝不写坏 covered(只在成功时提交)。
|
||
*/
|
||
export async function maybeSummarizeAssistantConversation(input: {
|
||
userId: string;
|
||
branchCode: string;
|
||
conversationId: string;
|
||
/** 注入测试用:跳过真实模型调用。 */
|
||
complete?: (messages: ChatMessage[]) => Promise<string>;
|
||
}): Promise<SummarizeOutcome> {
|
||
try {
|
||
if (!ASSISTANT_SUMMARY_ENABLED) return { summarized: false, reason: 'disabled' };
|
||
const base = { userId: input.userId, branchCode: input.branchCode, conversationId: input.conversationId };
|
||
const meta = await describeAssistantHistory(base);
|
||
const state = await loadAssistantConversationSummary(base);
|
||
if (!shouldSummarizeConversation({ total: meta.total, covered: state.covered })) {
|
||
return { summarized: false, reason: 'below_threshold' };
|
||
}
|
||
const segment = summarySegmentFor({ total: meta.total, covered: state.covered });
|
||
const turns = await listAssistantMessageSegment({
|
||
...base,
|
||
offset: segment.offset,
|
||
limit: segment.limit,
|
||
});
|
||
if (!turns.length) return { summarized: false, reason: 'no_messages' };
|
||
|
||
// 抢锁放在读消息之后:先把要压的内容拿稳,再决定是否付出模型成本
|
||
const claimed = await claimAssistantConversationSummary({
|
||
...base,
|
||
staleMinutes: ASSISTANT_SUMMARY_LOCK_STALE_MINUTES,
|
||
});
|
||
if (!claimed) return { summarized: false, reason: 'locked' };
|
||
|
||
const messages = buildSummaryMessages({ previousSummary: state.summary, turns });
|
||
let raw: string;
|
||
let usedModel = '';
|
||
if (input.complete) {
|
||
raw = await input.complete(messages);
|
||
} else {
|
||
const runtime = await resolveLlmRuntimeConfig({ branchCode: String(input.branchCode || '').trim() || undefined });
|
||
if (!runtime?.apiKeys?.length) return { summarized: false, reason: 'not_configured' };
|
||
usedModel = `${runtime.provider}/${runtime.model}`;
|
||
const result = await chatCompletionsWithTools({
|
||
runtime,
|
||
messages,
|
||
tools: [],
|
||
maxTokens: ASSISTANT_SUMMARY_MAX_TOKENS,
|
||
signal: AbortSignal.timeout(ASSISTANT_SUMMARY_TIMEOUT_MS),
|
||
});
|
||
raw = result.content;
|
||
}
|
||
const summary = normalizeSummaryOutput(raw);
|
||
if (!summary) return { summarized: false, reason: 'empty_summary' };
|
||
const saved = await saveAssistantConversationSummary({
|
||
...base,
|
||
summary,
|
||
covered: segment.nextCovered,
|
||
model: usedModel || null,
|
||
});
|
||
if (!saved) return { summarized: false, reason: 'llm_failed' };
|
||
return { summarized: true, covered: segment.nextCovered, reason: 'saved' };
|
||
} catch (error) {
|
||
console.warn('[assistant-summary] 生成摘要失败(不影响对话)', error);
|
||
return { summarized: false, reason: 'llm_failed' };
|
||
}
|
||
}
|