feat(llm): 支持增量上下文,为模型加 store: true 即走 relay
- 新增 instance.js:data_root/instance-id,首次启动生成 12 位 hex,跨 core 唯一 - engine 传 context_id = <core_id>:<user>:<session_id>,三层定位不撞车 - callModel 对 store: true 的模型只发新增消息 + X-Context-Id/Hash, 409 时改发全量重试一次;指针存内存,重启自动回落全量 - config.js 把 store 字段透传到模型对象(以前会被丢掉) - 未配 store 的模型行为完全不变
This commit is contained in:
@@ -211,6 +211,11 @@ IM 用户在实时对话,回合中插话应当“当前这步跑完就插”
|
|||||||
`{content, reasoning, tool_calls, finish_reason, usage, aborted, sseFrames}`;正文开头混入的
|
`{content, reasoning, tool_calls, finish_reason, usage, aborted, sseFrames}`;正文开头混入的
|
||||||
`<think>` 块会被 `splitInlineThinking` 剥离到 reasoning。
|
`<think>` 块会被 `splitInlineThinking` 剥离到 reasoning。
|
||||||
|
|
||||||
|
增量上下文(模型配了 `store: true` 且带 `opts.context_id`):只发上次之后新增的消息,带
|
||||||
|
`X-Context-Id` / `X-Context-Hash`;relay 回 409 说明缓存对不上(压缩、relay 重启、TTL 过期),
|
||||||
|
改发全量重试**一次**。指针存 `ctxState`(进程内存,只存 hash + 条数),进程重启即失效 →
|
||||||
|
下一轮自动全量。上游仍然是全量,语义不变。
|
||||||
|
|
||||||
## 工具层
|
## 工具层
|
||||||
|
|
||||||
- 工具全集 = `definitions.json`(14 个内置)+ MCP 发现结果;再依次叠 profile 的 `tools_allow`
|
- 工具全集 = `definitions.json`(14 个内置)+ MCP 发现结果;再依次叠 profile 的 `tools_allow`
|
||||||
|
|||||||
@@ -236,6 +236,9 @@ function normalizePlatforms(rawPlatforms, profileNames) {
|
|||||||
// 非空时发请求前给历史 assistant 行挂该字段;空(缺省)= 不回传。纯发送侧旋钮,
|
// 非空时发请求前给历史 assistant 行挂该字段;空(缺省)= 不回传。纯发送侧旋钮,
|
||||||
// 与接收解析无关(接收早已兼容 reasoning/reasoning_content 双名)。
|
// 与接收解析无关(接收早已兼容 reasoning/reasoning_content 双名)。
|
||||||
reasoning_ack_field: typeof m.reasoning_ack_field === 'string' ? m.reasoning_ack_field.trim() : '',
|
reasoning_ack_field: typeof m.reasoning_ack_field === 'string' ? m.reasoning_ack_field.trim() : '',
|
||||||
|
// 选填:该模型的请求走增量上下文(context relay),只有配合 relay 生效。
|
||||||
|
// 不配 = 每轮重传全量,和以前完全一样。
|
||||||
|
store: m.store === true,
|
||||||
// 选填:自动压缩阈值(用户自定义的「上下文用量线」,**不是**模型真实窗口)。
|
// 选填:自动压缩阈值(用户自定义的「上下文用量线」,**不是**模型真实窗口)。
|
||||||
// 回合内 In token 峰值达到它即自动压缩上下文(见 engine.runLoopInner 循环顶部);0/未配 = 不启用。
|
// 回合内 In token 峰值达到它即自动压缩上下文(见 engine.runLoopInner 循环顶部);0/未配 = 不启用。
|
||||||
max_context: Math.max(0, parseInt(m.max_context, 10) || 0),
|
max_context: Math.max(0, parseInt(m.max_context, 10) || 0),
|
||||||
@@ -363,6 +366,7 @@ function parseAndValidate(rawText, configPath) {
|
|||||||
extra_params: m.extra_params, thinking_params: m.thinking_params,
|
extra_params: m.extra_params, thinking_params: m.thinking_params,
|
||||||
reasoning_ack_field: m.reasoning_ack_field,
|
reasoning_ack_field: m.reasoning_ack_field,
|
||||||
max_context: m.max_context,
|
max_context: m.max_context,
|
||||||
|
store: m.store,
|
||||||
profile: m.profile,
|
profile: m.profile,
|
||||||
url: p.url, api_key: k.api_key, platform: p.name, type: p.type, concurrency: k.concurrency,
|
url: p.url, api_key: k.api_key, platform: p.name, type: p.type, concurrency: k.concurrency,
|
||||||
platform_index: pi, key_index: ki, model_index: mi,
|
platform_index: pi, key_index: ki, model_index: mi,
|
||||||
|
|||||||
@@ -3,6 +3,7 @@
|
|||||||
const fs = require('fs');
|
const fs = require('fs');
|
||||||
const path = require('path');
|
const path = require('path');
|
||||||
const { buildMessages, callModel, encodeBlocks, decodeBlocks, compressMessages, titleMessages, setProfilePrompts, patchImageReceipt } = require('./llm');
|
const { buildMessages, callModel, encodeBlocks, decodeBlocks, compressMessages, titleMessages, setProfilePrompts, patchImageReceipt } = require('./llm');
|
||||||
|
const { instanceId } = require('./instance');
|
||||||
const { executeTool, resolveInTask } = require('./tools/executor');
|
const { executeTool, resolveInTask } = require('./tools/executor');
|
||||||
const publicFiles = require('./public-files');
|
const publicFiles = require('./public-files');
|
||||||
const mcp = require('./mcp');
|
const mcp = require('./mcp');
|
||||||
@@ -1159,6 +1160,9 @@ async function streamAssistant(sessionId, run, session, messages, tools) {
|
|||||||
// key_slot 定位会话占用的具体 key 副本(model_id 只到「平台/模型」)
|
// key_slot 定位会话占用的具体 key 副本(model_id 只到「平台/模型」)
|
||||||
const result = await callModel(cfg, session.model_id, messages, tools, {
|
const result = await callModel(cfg, session.model_id, messages, tools, {
|
||||||
key_slot: session.model_slot,
|
key_slot: session.model_slot,
|
||||||
|
// 增量上下文用:<core_id>:<user>:<session_id>,三层保证跨 core / 跨用户 / 跨会话都不撞。
|
||||||
|
// 只有带 store: true 的模型才会真的用它(llm.js 判断)。
|
||||||
|
context_id: instanceId(cfg.data_root) + ':' + (session.user || '-') + ':' + session.id,
|
||||||
signal: run.abortController.signal,
|
signal: run.abortController.signal,
|
||||||
shouldCancel: () => run.cancelled,
|
shouldCancel: () => run.cancelled,
|
||||||
onText: delta => bus.emit(sessionId, 'assistant_delta', { text: delta }),
|
onText: delta => bus.emit(sessionId, 'assistant_delta', { text: delta }),
|
||||||
|
|||||||
@@ -0,0 +1,29 @@
|
|||||||
|
'use strict';
|
||||||
|
// 实例标识:跨 core 隔离用,作 relay 的 X-Context-Id 前缀。
|
||||||
|
// 首次启动生成并落盘到 <data_root>/instance-id,之后只读同一个值。
|
||||||
|
// 删了数据目录会换新 id —— 旧缓存成孤儿,由 relay 的 TTL 自行清理,不影响正确性。
|
||||||
|
const fs = require('node:fs');
|
||||||
|
const path = require('node:path');
|
||||||
|
const crypto = require('node:crypto');
|
||||||
|
|
||||||
|
const cache = new Map(); // dataRoot -> id
|
||||||
|
|
||||||
|
function instanceId(dataRoot) {
|
||||||
|
const root = path.resolve(String(dataRoot || '.'));
|
||||||
|
if (cache.has(root)) return cache.get(root);
|
||||||
|
const file = path.join(root, 'instance-id');
|
||||||
|
let id = '';
|
||||||
|
try {
|
||||||
|
id = fs.readFileSync(file, 'utf8').trim();
|
||||||
|
} catch (_) {}
|
||||||
|
if (!/^[0-9a-f]{12}$/.test(id)) {
|
||||||
|
id = crypto.randomBytes(6).toString('hex');
|
||||||
|
try {
|
||||||
|
fs.writeFileSync(file, id + '\n');
|
||||||
|
} catch (_) {}
|
||||||
|
}
|
||||||
|
cache.set(root, id);
|
||||||
|
return id;
|
||||||
|
}
|
||||||
|
|
||||||
|
module.exports = { instanceId };
|
||||||
+45
-2
@@ -2,6 +2,14 @@
|
|||||||
// 累积 content 与 tool_calls 分片;支持 abort。
|
// 累积 content 与 tool_calls 分片;支持 abort。
|
||||||
const fs = require('fs');
|
const fs = require('fs');
|
||||||
const path = require('path');
|
const path = require('path');
|
||||||
|
const crypto = require('node:crypto');
|
||||||
|
|
||||||
|
// 增量上下文:context_id -> { hash, len }(本进程认为 relay 已存到哪一段)。
|
||||||
|
// 只存指针不存正文;进程重启即清空 → 下一轮发全量,relay 整段替换,行为正确。
|
||||||
|
const ctxState = new Map();
|
||||||
|
function ctxHash(messages) {
|
||||||
|
return crypto.createHash('sha256').update(JSON.stringify(messages)).digest('hex');
|
||||||
|
}
|
||||||
|
|
||||||
const SYSTEM_PROMPT_TEMPLATE = fs.readFileSync(path.join(__dirname, 'templates', 'profile-default.txt'), 'utf8');
|
const SYSTEM_PROMPT_TEMPLATE = fs.readFileSync(path.join(__dirname, 'templates', 'profile-default.txt'), 'utf8');
|
||||||
|
|
||||||
@@ -714,18 +722,53 @@ async function callModel(cfg, modelId, messages, tools, options) {
|
|||||||
opts.onFetchParams(logBody);
|
opts.onFetchParams(logBody);
|
||||||
}
|
}
|
||||||
|
|
||||||
const res = await fetch(modelCfg.url + '/chat/completions', {
|
// ---- 增量上下文(context relay)----
|
||||||
|
// 仅对显式 store: true 的模型生效,且必须带 opts.context_id。
|
||||||
|
// 不做前缀比对:压缩/改写/relay 重启一律靠 409 回退全量,客户端只负责“接着上次发”。
|
||||||
|
const cid = opts.context_id;
|
||||||
|
const storeOn = !!(modelCfg.store && cid);
|
||||||
|
const fullBody = JSON.stringify(body);
|
||||||
|
if (storeOn) {
|
||||||
|
const st = ctxState.get(cid);
|
||||||
|
headers['X-Context-Id'] = cid;
|
||||||
|
if (st && messages.length > st.len) {
|
||||||
|
body.messages = messages.slice(st.len); // 只发新增
|
||||||
|
headers['X-Context-Hash'] = st.hash;
|
||||||
|
} else {
|
||||||
|
headers['X-Context-Hash'] = ''; // 首轮 / 压缩后:全量替换
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
let res = await fetch(modelCfg.url + '/chat/completions', {
|
||||||
method: 'POST',
|
method: 'POST',
|
||||||
headers,
|
headers,
|
||||||
body: JSON.stringify(body),
|
body: storeOn ? JSON.stringify(body) : fullBody,
|
||||||
signal: controller.signal,
|
signal: controller.signal,
|
||||||
});
|
});
|
||||||
|
|
||||||
|
// relay 说 hash 对不上(缓存没了 / 历史被改写):改发全量重试一次。
|
||||||
|
// 只重试一次:hash="" 对 relay 是“整段替换”,重发后不可能再 409。
|
||||||
|
if (storeOn && res.status === 409) {
|
||||||
|
body.messages = messages;
|
||||||
|
headers['X-Context-Hash'] = '';
|
||||||
|
res = await fetch(modelCfg.url + '/chat/completions', {
|
||||||
|
method: 'POST',
|
||||||
|
headers,
|
||||||
|
body: JSON.stringify(body),
|
||||||
|
signal: controller.signal,
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
if (!res.ok) {
|
if (!res.ok) {
|
||||||
const text = await res.text().catch(() => '');
|
const text = await res.text().catch(() => '');
|
||||||
const err = new Error('上游返回 ' + res.status + ': ' + text.slice(0, 500));
|
const err = new Error('上游返回 ' + res.status + ': ' + text.slice(0, 500));
|
||||||
err.upstream_status = res.status;
|
err.upstream_status = res.status;
|
||||||
throw err;
|
throw err;
|
||||||
}
|
}
|
||||||
|
// 成功才更新“relay 已存到哪”:失败下一轮自然重发全量。
|
||||||
|
if (storeOn) {
|
||||||
|
ctxState.set(cid, { hash: ctxHash(messages), len: messages.length });
|
||||||
|
}
|
||||||
|
|
||||||
let content = '';
|
let content = '';
|
||||||
let reasoning = '';
|
let reasoning = '';
|
||||||
|
|||||||
Reference in New Issue
Block a user