feat(chat): 解析/存储/发送思考(reasoning 或 reasoning_content) — DB 新增 reasoning 列,SSE 加 reasoning_delta,前端折叠面板
This commit is contained in:
@@ -29,12 +29,15 @@ function initDb(dbPath) {
|
|||||||
session_id TEXT NOT NULL,
|
session_id TEXT NOT NULL,
|
||||||
role TEXT NOT NULL,
|
role TEXT NOT NULL,
|
||||||
content TEXT,
|
content TEXT,
|
||||||
|
reasoning TEXT,
|
||||||
tool_calls TEXT,
|
tool_calls TEXT,
|
||||||
tool_call_id TEXT,
|
tool_call_id TEXT,
|
||||||
name TEXT,
|
name TEXT,
|
||||||
created_at INTEGER NOT NULL,
|
created_at INTEGER NOT NULL,
|
||||||
FOREIGN KEY (session_id) REFERENCES sessions(id)
|
FOREIGN KEY (session_id) REFERENCES sessions(id)
|
||||||
);
|
);
|
||||||
|
// 升级老库:早期表不带 reasoning 列,补上(重入安全)
|
||||||
|
try { db.exec('ALTER TABLE messages ADD COLUMN reasoning TEXT'); } catch (_) { /* 已存在 */ }
|
||||||
|
|
||||||
CREATE TABLE IF NOT EXISTS files (
|
CREATE TABLE IF NOT EXISTS files (
|
||||||
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
||||||
|
|||||||
@@ -75,8 +75,8 @@ function loadHistory(sessionId) {
|
|||||||
|
|
||||||
function saveMessage(sessionId, msg) {
|
function saveMessage(sessionId, msg) {
|
||||||
const info = db.prepare(
|
const info = db.prepare(
|
||||||
'INSERT INTO messages (session_id, role, content, tool_calls, tool_call_id, name, created_at) VALUES (?,?,?,?,?,?,?)'
|
'INSERT INTO messages (session_id, role, content, reasoning, tool_calls, tool_call_id, name, created_at) VALUES (?,?,?,?,?,?,?,?)'
|
||||||
).run(sessionId, msg.role, msg.content || null,
|
).run(sessionId, msg.role, msg.content || null, msg.reasoning || null,
|
||||||
msg.tool_calls ? JSON.stringify(msg.tool_calls) : null,
|
msg.tool_calls ? JSON.stringify(msg.tool_calls) : null,
|
||||||
msg.tool_call_id || null, msg.name || null, now());
|
msg.tool_call_id || null, msg.name || null, now());
|
||||||
// 关键动作日志:AI 每轮回复落库(含纯工具调用轮)
|
// 关键动作日志:AI 每轮回复落库(含纯工具调用轮)
|
||||||
@@ -476,6 +476,7 @@ async function runLoopInner(sessionId, run) {
|
|||||||
const msgRow = {
|
const msgRow = {
|
||||||
role: 'assistant',
|
role: 'assistant',
|
||||||
content: result.content || '',
|
content: result.content || '',
|
||||||
|
reasoning: result.reasoning || null,
|
||||||
tool_calls: hasTools ? result.tool_calls.map(tc => ({
|
tool_calls: hasTools ? result.tool_calls.map(tc => ({
|
||||||
id: tc.id, type: 'function',
|
id: tc.id, type: 'function',
|
||||||
function: { name: tc.name, arguments: tc.arguments },
|
function: { name: tc.name, arguments: tc.arguments },
|
||||||
@@ -483,7 +484,7 @@ async function runLoopInner(sessionId, run) {
|
|||||||
};
|
};
|
||||||
const assistantId = saveMessage(sessionId, msgRow);
|
const assistantId = saveMessage(sessionId, msgRow);
|
||||||
recordModelUsage(sessionId, session.model_id, result.usage);
|
recordModelUsage(sessionId, session.model_id, result.usage);
|
||||||
bus.emit(sessionId, 'assistant_message', { id: assistantId, content: msgRow.content, tool_calls: msgRow.tool_calls });
|
bus.emit(sessionId, 'assistant_message', { id: assistantId, content: msgRow.content, reasoning: msgRow.reasoning, tool_calls: msgRow.tool_calls });
|
||||||
|
|
||||||
if (!hasTools) {
|
if (!hasTools) {
|
||||||
// 回合结束;但若期间用户又发了新消息(live 投递),继续下一轮而不是收尾
|
// 回合结束;但若期间用户又发了新消息(live 投递),继续下一轮而不是收尾
|
||||||
@@ -562,6 +563,7 @@ async function streamAssistant(sessionId, run, session, messages, tools) {
|
|||||||
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 }),
|
||||||
|
onReasoning: delta => bus.emit(sessionId, 'reasoning_delta', { text: delta }),
|
||||||
// 本轮是否启用深度思考;由 postUserMessage 从消息 POST 参数写进 run
|
// 本轮是否启用深度思考;由 postUserMessage 从消息 POST 参数写进 run
|
||||||
deepThink: !!run.deepThink,
|
deepThink: !!run.deepThink,
|
||||||
});
|
});
|
||||||
|
|||||||
+10
-1
@@ -160,6 +160,7 @@ async function callModel(cfg, modelId, messages, tools, options) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
let content = '';
|
let content = '';
|
||||||
|
let reasoning = '';
|
||||||
let finishReason = null;
|
let finishReason = null;
|
||||||
let usage = null;
|
let usage = null;
|
||||||
let aborted = false;
|
let aborted = false;
|
||||||
@@ -177,6 +178,14 @@ async function callModel(cfg, modelId, messages, tools, options) {
|
|||||||
content += delta.content;
|
content += delta.content;
|
||||||
if (opts.onText) opts.onText(delta.content);
|
if (opts.onText) opts.onText(delta.content);
|
||||||
}
|
}
|
||||||
|
// 思考/推理字段:各家上游不一致,同时支持 reasoning 和 reasoning_content;只走一个,优先级 reasoning
|
||||||
|
const rPiece = (typeof delta.reasoning === 'string' && delta.reasoning)
|
||||||
|
|| (typeof delta.reasoning_content === 'string' && delta.reasoning_content)
|
||||||
|
|| '';
|
||||||
|
if (rPiece) {
|
||||||
|
reasoning += rPiece;
|
||||||
|
if (opts.onReasoning) opts.onReasoning(rPiece);
|
||||||
|
}
|
||||||
for (const tc of delta.tool_calls || []) {
|
for (const tc of delta.tool_calls || []) {
|
||||||
const idx = tc.index || 0;
|
const idx = tc.index || 0;
|
||||||
if (!toolCalls.has(idx)) toolCalls.set(idx, { id: '', name: '', arguments: '' });
|
if (!toolCalls.has(idx)) toolCalls.set(idx, { id: '', name: '', arguments: '' });
|
||||||
@@ -193,7 +202,7 @@ async function callModel(cfg, modelId, messages, tools, options) {
|
|||||||
}
|
}
|
||||||
if (opts.shouldCancel && opts.shouldCancel()) aborted = true;
|
if (opts.shouldCancel && opts.shouldCancel()) aborted = true;
|
||||||
|
|
||||||
return { content, tool_calls: Array.from(toolCalls.values()), finish_reason: finishReason, usage, aborted };
|
return { content, reasoning, tool_calls: Array.from(toolCalls.values()), finish_reason: finishReason, usage, aborted };
|
||||||
}
|
}
|
||||||
|
|
||||||
module.exports = { callModel, buildMessages, buildSystemPrompt, systemPromptText, encodeBlocks, decodeBlocks };
|
module.exports = { callModel, buildMessages, buildSystemPrompt, systemPromptText, encodeBlocks, decodeBlocks };
|
||||||
|
|||||||
@@ -125,6 +125,37 @@ main { flex: 1; min-height: 0; display: flex; flex-direction: column; }
|
|||||||
.msg.me { align-items: flex-end; }
|
.msg.me { align-items: flex-end; }
|
||||||
.msg.other { align-items: flex-start; }
|
.msg.other { align-items: flex-start; }
|
||||||
|
|
||||||
|
/* 思考过程折叠面板:位于 AI 气泡上方。summary 小圆点+灰文字,body 等宽字体淡背景 */
|
||||||
|
.msg-think {
|
||||||
|
width: 100%; max-width: 100%;
|
||||||
|
margin: 0 0 6px; padding: 0;
|
||||||
|
background: var(--surface); border: 1px solid var(--border); border-radius: 10px;
|
||||||
|
font-size: 13px; color: var(--ink);
|
||||||
|
overflow: hidden;
|
||||||
|
}
|
||||||
|
.msg-think > summary {
|
||||||
|
list-style: none; cursor: pointer; user-select: none;
|
||||||
|
padding: 6px 10px; display: flex; align-items: center; gap: 6px;
|
||||||
|
color: var(--gray); font-size: 12px;
|
||||||
|
}
|
||||||
|
.msg-think > summary::-webkit-details-marker { display: none; }
|
||||||
|
.msg-think > summary::before {
|
||||||
|
content: '▸'; font-size: 10px; color: var(--gray-light);
|
||||||
|
transition: transform .15s; display: inline-block;
|
||||||
|
}
|
||||||
|
.msg-think[open] > summary::before { transform: rotate(90deg); }
|
||||||
|
.msg-think-body {
|
||||||
|
padding: 4px 12px 10px;
|
||||||
|
font-family: ui-monospace, SFMono-Regular, Menlo, Consolas, monospace;
|
||||||
|
font-size: 12.5px; line-height: 1.55;
|
||||||
|
color: var(--ink); white-space: pre-wrap; word-break: break-word;
|
||||||
|
max-height: 360px; overflow-y: auto;
|
||||||
|
border-top: 1px solid var(--border);
|
||||||
|
background: #fafbfd;
|
||||||
|
}
|
||||||
|
/* 流式阶段给一点视觉提示:边色稍亮,收尾(assistant_message)后去除 */
|
||||||
|
.msg-think.streaming { border-color: #d8e0f5; }
|
||||||
|
|
||||||
/* 用户气泡:右侧,浅色背景,圆角矩形 */
|
/* 用户气泡:右侧,浅色背景,圆角矩形 */
|
||||||
.bubble-user {
|
.bubble-user {
|
||||||
background: var(--active-soft); color: var(--ink);
|
background: var(--active-soft); color: var(--ink);
|
||||||
|
|||||||
@@ -363,6 +363,9 @@
|
|||||||
es: null, // EventSource
|
es: null, // EventSource
|
||||||
streamText: '', // 当前流式累积文本
|
streamText: '', // 当前流式累积文本
|
||||||
streamEl: null, // 当前流式 AI 气泡
|
streamEl: null, // 当前流式 AI 气泡
|
||||||
|
streamWrap: null, // 当前流式消息容器(.msg.other);思考面板与气泡都挂它上面
|
||||||
|
streamReasoning: '', // 当前流式累积思考文本
|
||||||
|
streamThinkEl: null, // 当前流式思考面板的 body 节点(未出现思考时为 null)
|
||||||
toolCards: {}, // tool_call_id -> 工具卡片元素(同步 index 工具卡样式)
|
toolCards: {}, // tool_call_id -> 工具卡片元素(同步 index 工具卡样式)
|
||||||
typingEl: null, // 「思考中」占位
|
typingEl: null, // 「思考中」占位
|
||||||
streaming: false,
|
streaming: false,
|
||||||
@@ -444,13 +447,16 @@
|
|||||||
}
|
}
|
||||||
|
|
||||||
function aiMsgHtml(m) {
|
function aiMsgHtml(m) {
|
||||||
const hasText = !!(m.content && m.content.trim());
|
const text = (m.content || '').trim();
|
||||||
if (!hasText) return null; // 纯工具调用的应答:不渲染空气泡,工具卡由 appendToolCardsFromAssistant 铺
|
const reason = (m.reasoning || '').trim();
|
||||||
const r = mdHtml(m.content);
|
if (!text && !reason) return null; // 纯工具调用的应答:不渲染气泡,工具卡由 appendToolCardsFromAssistant 铺
|
||||||
return '<div class="msg other">' +
|
const think = reason ? thinkPanelHtml(m.reasoning) : '';
|
||||||
'<div class="bubble-ai' + (r.fmt ? ' md' : '') + '">' + r.html + '</div>' +
|
const bubble = text ? (() => { const r = mdHtml(m.content); return '<div class="bubble-ai' + (r.fmt ? ' md' : '') + '">' + r.html + '</div>'; })() : '';
|
||||||
actionsHtml(m.created_at, m.content) +
|
return '<div class="msg other">' + think + bubble + actionsHtml(m.created_at, m.content || '') + '</div>';
|
||||||
'</div>';
|
}
|
||||||
|
// 思考过程折叠面板:summary 固定名「思考过程」,body 展示推理全文
|
||||||
|
function thinkPanelHtml(text) {
|
||||||
|
return '<details class="msg-think"><summary>思考过程</summary><div class="msg-think-body">' + esc(text) + '</div></details>';
|
||||||
}
|
}
|
||||||
|
|
||||||
// ---------- 工具调用卡片(样式/交互同步 index;流式与历史共用) ----------
|
// ---------- 工具调用卡片(样式/交互同步 index;流式与历史共用) ----------
|
||||||
@@ -955,7 +961,39 @@
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// ---------- SSE 流式 ----------
|
// ---------- SSE 流 ----------
|
||||||
|
// 助手消息流式容器:首个 delta 到达时创建,同时为思考面板预留挂载点
|
||||||
|
function ensureStreamWrap() {
|
||||||
|
if (state.streamWrap) return state.streamWrap;
|
||||||
|
const wrap = document.createElement('div');
|
||||||
|
wrap.className = 'msg other';
|
||||||
|
const bubble = document.createElement('div');
|
||||||
|
bubble.className = 'bubble-ai';
|
||||||
|
wrap.appendChild(bubble);
|
||||||
|
$('chat-view').appendChild(wrap);
|
||||||
|
state.streamWrap = wrap;
|
||||||
|
state.streamEl = bubble;
|
||||||
|
return wrap;
|
||||||
|
}
|
||||||
|
// 思考面板:首次思考 delta 到达时创建,带 open 状态(流式中默认展开)
|
||||||
|
function ensureStreamThinkPanel() {
|
||||||
|
if (state.streamThinkEl) return state.streamThinkEl;
|
||||||
|
if (!state.streamWrap) ensureStreamWrap();
|
||||||
|
const det = document.createElement('details');
|
||||||
|
det.className = 'msg-think streaming';
|
||||||
|
det.open = true; // 流式阶段默认展开,看思考增量
|
||||||
|
const sum = document.createElement('summary');
|
||||||
|
sum.textContent = '思考过程';
|
||||||
|
const body = document.createElement('div');
|
||||||
|
body.className = 'msg-think-body';
|
||||||
|
det.appendChild(sum);
|
||||||
|
det.appendChild(body);
|
||||||
|
// 插在气泡之前(思考 → 结论 的顺序)
|
||||||
|
state.streamWrap.insertBefore(det, state.streamEl);
|
||||||
|
state.streamThinkEl = body;
|
||||||
|
return body;
|
||||||
|
}
|
||||||
|
|
||||||
function connectStream() {
|
function connectStream() {
|
||||||
closeStream();
|
closeStream();
|
||||||
if (!state.sessionId) return;
|
if (!state.sessionId) return;
|
||||||
@@ -974,42 +1012,64 @@
|
|||||||
state.streamText += d.text;
|
state.streamText += d.text;
|
||||||
if (!state.streamEl) {
|
if (!state.streamEl) {
|
||||||
if (!state.streamText.trim()) return; // 忽略前导空白(纯工具调用回合无文本)
|
if (!state.streamText.trim()) return; // 忽略前导空白(纯工具调用回合无文本)
|
||||||
const wrap = document.createElement('div');
|
ensureStreamWrap();
|
||||||
wrap.className = 'msg other';
|
state.streamText = d.text; // 上面 if 已 trim 为非空
|
||||||
const bubble = document.createElement('div');
|
|
||||||
bubble.className = 'bubble-ai';
|
|
||||||
wrap.appendChild(bubble);
|
|
||||||
$('chat-view').appendChild(wrap);
|
|
||||||
state.streamEl = bubble;
|
|
||||||
state.streamText = d.text;
|
|
||||||
}
|
}
|
||||||
state.streamEl.textContent = state.streamText;
|
state.streamEl.textContent = state.streamText;
|
||||||
state.streaming = true;
|
state.streaming = true;
|
||||||
maybeAutoScroll();
|
maybeAutoScroll();
|
||||||
updateScrollBottomBtn();
|
updateScrollBottomBtn();
|
||||||
});
|
});
|
||||||
|
es.addEventListener('reasoning_delta', ev => {
|
||||||
|
const d = JSON.parse(ev.data);
|
||||||
|
removeTyping();
|
||||||
|
state.streamReasoning += d.text;
|
||||||
|
if (!state.streamWrap) ensureStreamWrap();
|
||||||
|
ensureStreamThinkPanel();
|
||||||
|
state.streamThinkEl.textContent = state.streamReasoning;
|
||||||
|
state.streaming = true;
|
||||||
|
maybeAutoScroll();
|
||||||
|
updateScrollBottomBtn();
|
||||||
|
});
|
||||||
es.addEventListener('assistant_message', ev => {
|
es.addEventListener('assistant_message', ev => {
|
||||||
const d = JSON.parse(ev.data);
|
const d = JSON.parse(ev.data);
|
||||||
removeTyping();
|
removeTyping();
|
||||||
const hasText = !!(d.content && d.content.trim());
|
const hasText = !!(d.content && d.content.trim());
|
||||||
const r = hasText ? mdHtml(d.content) : null;
|
const r = hasText ? mdHtml(d.content) : null;
|
||||||
|
// 思考面板:本轮结束时锁定为后端返回的完整文本(不清空 streamReasoning 以防与历史回填不一致)
|
||||||
|
if (d.reasoning && d.reasoning.trim()) {
|
||||||
|
if (!state.streamWrap) ensureStreamWrap();
|
||||||
|
ensureStreamThinkPanel();
|
||||||
|
state.streamThinkEl.textContent = d.reasoning;
|
||||||
|
}
|
||||||
if (state.streamEl) {
|
if (state.streamEl) {
|
||||||
if (r) {
|
if (r) {
|
||||||
state.streamEl.className = 'bubble-ai' + (r.fmt ? ' md' : ''); // 增量期间是纯文本,收尾统一换 md 排版
|
state.streamEl.className = 'bubble-ai' + (r.fmt ? ' md' : ''); // 增量期间是纯文本,收尾统一换 md 排版
|
||||||
state.streamEl.innerHTML = r.html;
|
state.streamEl.innerHTML = r.html;
|
||||||
} else {
|
} else {
|
||||||
|
// 无文本时去掉气泡(纯工具调用/纯思考也要保留思考面板)
|
||||||
state.streamEl.remove();
|
state.streamEl.remove();
|
||||||
}
|
}
|
||||||
state.streamEl = null;
|
state.streamEl = null;
|
||||||
state.streamText = '';
|
state.streamText = '';
|
||||||
} else if (r) {
|
} else if (r) {
|
||||||
const wrap = document.createElement('div');
|
// 没起过气泡但收到文本:现在才创建(思考先行、文本后到的罕见场景)
|
||||||
wrap.className = 'msg other';
|
if (!state.streamWrap) ensureStreamWrap();
|
||||||
wrap.innerHTML = '<div class="bubble-ai' + (r.fmt ? ' md' : '') + '">' + r.html + '</div>';
|
const bubble = document.createElement('div');
|
||||||
$('chat-view').appendChild(wrap);
|
bubble.className = 'bubble-ai' + (r.fmt ? ' md' : '');
|
||||||
|
bubble.innerHTML = r.html;
|
||||||
|
state.streamWrap.appendChild(bubble);
|
||||||
}
|
}
|
||||||
if (d.tool_calls) appendToolCardsFromAssistant(d, $('chat-view'));
|
if (d.tool_calls) appendToolCardsFromAssistant(d, $('chat-view'));
|
||||||
state.streaming = false;
|
state.streaming = false;
|
||||||
|
// 思考面板默认折叠,避免挡着后续气泡;点击展开
|
||||||
|
if (state.streamWrap) {
|
||||||
|
const t = state.streamWrap.querySelector('.msg-think');
|
||||||
|
if (t && t.open) t.open = false;
|
||||||
|
}
|
||||||
|
state.streamWrap = null;
|
||||||
|
state.streamReasoning = '';
|
||||||
|
state.streamThinkEl = null;
|
||||||
maybeAutoScroll();
|
maybeAutoScroll();
|
||||||
updateScrollBottomBtn();
|
updateScrollBottomBtn();
|
||||||
});
|
});
|
||||||
@@ -1032,6 +1092,9 @@
|
|||||||
state.streaming = false;
|
state.streaming = false;
|
||||||
state.streamEl = null; // 防御性清理:回合异常结束(如终止)时不留悬空气泡到下一轮
|
state.streamEl = null; // 防御性清理:回合异常结束(如终止)时不留悬空气泡到下一轮
|
||||||
state.streamText = '';
|
state.streamText = '';
|
||||||
|
state.streamWrap = null;
|
||||||
|
state.streamReasoning = '';
|
||||||
|
state.streamThinkEl = null;
|
||||||
state.toolCards = {};
|
state.toolCards = {};
|
||||||
updateScrollBottomBtn();
|
updateScrollBottomBtn();
|
||||||
loadSessionList();
|
loadSessionList();
|
||||||
|
|||||||
@@ -109,7 +109,7 @@ router.get('/:id', wrap((req, res) => {
|
|||||||
const session = engine.getSession(req.params.id);
|
const session = engine.getSession(req.params.id);
|
||||||
if (!session) return sendErr(res, Object.assign(new Error('会话不存在'), { status_code: 404 }));
|
if (!session) return sendErr(res, Object.assign(new Error('会话不存在'), { status_code: 404 }));
|
||||||
const db = engine.getDb();
|
const db = engine.getDb();
|
||||||
const messages = db.prepare('SELECT id, role, content, tool_calls, tool_call_id, name, created_at FROM messages WHERE session_id = ? ORDER BY id').all(session.id);
|
const messages = db.prepare('SELECT id, role, content, reasoning, tool_calls, tool_call_id, name, created_at FROM messages WHERE session_id = ? ORDER BY id').all(session.id);
|
||||||
const taskDir = engine.taskDirOf(session.id);
|
const taskDir = engine.taskDirOf(session.id);
|
||||||
res.json({
|
res.json({
|
||||||
session,
|
session,
|
||||||
|
|||||||
Reference in New Issue
Block a user