/* Copyright (C) 2025 QuantumNous This program is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with this program. If not, see . For commercial licensing, please contact support@quantumnous.com */ // 体验中心长会话上下文管理:历史窗口裁剪 + 摘要拼接。 // 纯函数,不依赖 React,供 Playground 各发送入口与摘要 hook 复用。 import { MESSAGE_ROLES } from '../constants/playground.constants'; import { getTextContent } from './utils'; // 摘要指令:要求模型输出简洁中文摘要,保留关键信息 export const SUMMARIZE_INSTRUCTION = '请把以上对话压缩成一段简洁的中文摘要,保留关键事实、用户意图、已确定的结论与尚未解决的问题,' + '不要遗漏代码片段、数字、专有名词等关键信息。直接输出摘要正文,不要任何额外说明。'; // splitSystemPrefix 拆出开头连续的 system 消息(系统提示),其余为对话主体 const splitSystemPrefix = (messages) => { let i = 0; while (i < messages.length && messages[i]?.role === MESSAGE_ROLES.SYSTEM) { i += 1; } return { systemPrefix: messages.slice(0, i), body: messages.slice(i) }; }; /** * 把消息裁剪到「最近 maxRounds 轮」窗口。 * 一轮 = 一条 user 消息 + 其后的 assistant 回复。开头连续的 system 提示永远保留。 * maxRounds <= 0 时原样返回(不限制)。 * * 局限:纯按消息序号裁剪,不做跨消息的图片依赖分析——可能裁掉后文「这张图...」 * 引用的历史图片。这是刻意的成本控制取舍,由管理员配置轮数时自行权衡。 * * @param {Array} messages 完整消息数组 * @param {number} maxRounds 保留的最近轮数,<=0 表示不限制 * @returns {Array} 裁剪后的消息数组(maxRounds<=0 或无需裁剪时返回原数组引用) */ export const trimMessagesToWindow = (messages, maxRounds) => { if (!Array.isArray(messages) || !maxRounds || maxRounds <= 0) { return messages; } const { systemPrefix, body } = splitSystemPrefix(messages); // 收集 body 里所有 user 消息的下标 const userIdx = []; for (let i = 0; i < body.length; i += 1) { if (body[i]?.role === MESSAGE_ROLES.USER) userIdx.push(i); } // 保留最近 maxRounds 轮 + 当前新 user 消息 = 最多 maxRounds+1 条 user 消息 if (userIdx.length <= maxRounds + 1) { return messages; } const cutFrom = userIdx[userIdx.length - (maxRounds + 1)]; return [...systemPrefix, ...body.slice(cutFrom)]; }; /** * 取出落在「最近 maxRounds 轮窗口」之前的消息(即会被裁掉、需要被摘要覆盖的那部分)。 * 与 trimMessagesToWindow 互补:trim 返回保留的,本函数返回被裁掉的。 * 不含开头的 system 前缀(system 提示永远保留,不进摘要)。 * * @param {Array} messages * @param {number} maxRounds * @returns {Array} 窗口之前的消息(maxRounds<=0 或无需裁剪时返回空数组) */ export const getMessagesBeforeWindow = (messages, maxRounds) => { if (!Array.isArray(messages) || !maxRounds || maxRounds <= 0) { return []; } const { body } = splitSystemPrefix(messages); const userIdx = []; for (let i = 0; i < body.length; i += 1) { if (body[i]?.role === MESSAGE_ROLES.USER) userIdx.push(i); } if (userIdx.length <= maxRounds + 1) { return []; } const cutFrom = userIdx[userIdx.length - (maxRounds + 1)]; return body.slice(0, cutFrom); }; /** * 取出「锚点消息之后」的全部对话主体消息(不含 system 前缀)。 * 锚点 = backendId 等于 anchorBackendId 的消息(通常是已被摘要覆盖到的最后一条 user 消息)。 * * 设计要点:按位置切片而非按 backendId 过滤——直播会话里 assistant 消息没有 backendId, * 但它们必须随相邻 user 消息一起被带上,否则模型只看到提问看不到回答。 * * @param {Array} messages * @param {number} anchorBackendId 锚点消息的 backendId(<=0 视为无锚点) * @returns {Array} 锚点之后的消息;锚点不存在(如被删除)时兜底返回全部主体,避免丢上下文 */ export const getMessagesAfterAnchor = (messages, anchorBackendId) => { if (!Array.isArray(messages)) return []; const { body } = splitSystemPrefix(messages); if (!anchorBackendId || anchorBackendId <= 0) return body; const idx = body.findIndex((m) => m && m.backendId === anchorBackendId); if (idx < 0) return body; return body.slice(idx + 1); }; /** * 统计对话主体里的「轮数」(body 内 user 消息数量)。 * @param {Array} messages * @returns {number} */ export const countRounds = (messages) => { if (!Array.isArray(messages)) return 0; const { body } = splitSystemPrefix(messages); return body.filter((m) => m?.role === MESSAGE_ROLES.USER).length; }; /** * 发送前对消息做「摘要 + 窗口」处理: * - 启用摘要(summaryEnabled) 且摘要已就绪 → [system 前缀] + [摘要 system 消息] + [锚点之后的全部历史] * (锚点之后全发,不再二次截断,避免「摘要边界」与「窗口边界」之间出现上下文空洞) * - 启用摘要 但摘要还没生成 → 原样返回完整历史(首次摘要前不截断,避免丢上下文) * - 未启用摘要 → 纯 Feature A:trimMessagesToWindow 截断到最近 maxRounds 轮 * * @param {Array} messages * @param {{maxRounds?: number, summary?: string, summarizedUpToMessageId?: number, summaryEnabled?: boolean}} opts * @returns {Array} */ export const applySummaryAndWindow = (messages, opts = {}) => { if (!Array.isArray(messages)) return messages; const { maxRounds, summary, summarizedUpToMessageId, summaryEnabled } = opts; if (summaryEnabled) { if (summary && summarizedUpToMessageId > 0) { const { systemPrefix } = splitSystemPrefix(messages); let tail = getMessagesAfterAnchor(messages, summarizedUpToMessageId); // tail 以「锚点(user 消息)的 assistant 回复」开头;去掉开头的非 user 消息, // 保证发给上游的对话体首条(非 system)为 user —— Claude 等上游要求严格 user 起始, // 否则会报错。被去掉的 assistant 回复属于已被摘要覆盖的那一轮,不会丢上下文。 let cut = 0; while (cut < tail.length && tail[cut]?.role !== MESSAGE_ROLES.USER) { cut += 1; } if (cut > 0) tail = tail.slice(cut); return [ ...systemPrefix, { role: MESSAGE_ROLES.SYSTEM, content: '对话历史摘要:' + summary }, ...tail, ]; } // 摘要还没生成 → 发送完整历史 return messages; } return trimMessagesToWindow(messages, maxRounds); }; /** * 构造摘要请求的 messages:把「已有摘要 + 待摘要对话 + 摘要指令」整段塞进【一条 user 消息】。 * * 为什么塞成单条 user 消息:摘要请求会经普通 /pg/chat/completions 转发到用户当前模型, * 而待摘要片段往往以 assistant 消息开头、且未必严格 user/assistant 交替;Claude 等上游 * 对「首条非 system 必须是 user」「角色必须交替」有硬性要求,多条消息形态会被直接打回, * 导致摘要在这些模型上永远静默失败。单条 user 消息彻底规避所有角色约束。 * * 待摘要消息只取纯文本(getTextContent):摘要不需要图片,且能避开历史多模态消息里 * COS 预签名 URL 过期、当前模型不支持视觉等问题。空文本消息直接跳过。 * * @param {Array} messagesToSummarize 需要被压缩的历史消息 * @param {string} existingSummary 已有摘要(增量摘要时把旧摘要也带上) * @returns {Array} 仅含一条 user 消息的数组 */ export const buildSummaryInstructionMessages = ( messagesToSummarize, existingSummary, ) => { const parts = []; if (existingSummary && existingSummary.trim()) { parts.push('【已有摘要】\n' + existingSummary.trim()); } const transcript = []; for (const m of messagesToSummarize || []) { const text = getTextContent(m); if (!text || !text.trim()) continue; const label = m?.role === MESSAGE_ROLES.USER ? '用户' : m?.role === MESSAGE_ROLES.ASSISTANT ? '助手' : m?.role === MESSAGE_ROLES.SYSTEM ? '系统' : m?.role || '消息'; transcript.push(`${label}:${text.trim()}`); } parts.push('【待总结的对话】\n' + transcript.join('\n')); parts.push(SUMMARIZE_INSTRUCTION); return [{ role: MESSAGE_ROLES.USER, content: parts.join('\n\n') }]; };