加入多模态图片识别功能

This commit is contained in:
2026-09-02 10:52:04 +08:00
parent 10e48fbade
commit f895801ad2
12 changed files with 746 additions and 22 deletions
+35 -8
View File
@@ -2,7 +2,7 @@
// 单进程内存模型:JS 单线程 + better-sqlite3 同步 API,不存在跨进程竞争。
const fs = require('fs');
const path = require('path');
const { buildMessages, callModel } = require('./llm');
const { buildMessages, callModel, encodeBlocks } = require('./llm');
const { executeTool, resolveInTask } = require('./tools/executor');
const mcp = require('./mcp');
const log = require('./log');
@@ -185,6 +185,12 @@ function modelDisplayName(modelId) {
return row ? row.display_name : modelId;
}
// 会话绑定的模型是否支持 vision(图片回传);决定 read_file 读图行为(见 tools/executor.js)。
function modelVision(session) {
const m = session.model_id && (cfg.models || []).find(x => x.id === session.model_id);
return !!(m && m.vision);
}
function enqueue(sessionId) {
const exists = db.prepare('SELECT id FROM wait_queue WHERE session_id = ?').get(sessionId);
if (!exists) db.prepare('INSERT INTO wait_queue (session_id, queued_at) VALUES (?,?)').run(sessionId, now());
@@ -419,6 +425,7 @@ async function runLoopInner(sessionId, run) {
}
// 执行工具
const vision = modelVision(session);
for (const tc of msgRow.tool_calls) {
if (run.cancelled) break;
const id = tc.id || ('call_' + Math.random().toString(36).slice(2, 10));
@@ -427,16 +434,36 @@ async function runLoopInner(sessionId, run) {
let output;
let isError = false;
try {
output = await executeTool({ sessionId, taskDir: taskDirOf(sessionId), run, cfg, db },
output = await executeTool({ sessionId, taskDir: taskDirOf(sessionId), run, cfg, db, vision },
tc.function.name, safeParse(tc.function.arguments));
} catch (err) {
output = 'Error: ' + (err && err.message || String(err));
isError = true;
}
if (run.cancelled && !isError) output = (output ? output + '\n' : '') + '(用户已终止任务)';
log.debug('[tool] ' + sessionId + ' ' + tc.function.name + (isError ? ' 失败: ' : ' 完成: ') + String(output || '').slice(0, 500));
bus.emit(sessionId, 'tool_result', { tool_call_id: id, name: tc.function.name, content: output.slice(0, 20000), is_error: isError });
saveMessage(sessionId, { role: 'tool', tool_call_id: id, name: tc.function.name, content: output });
// 工具可返回 {text, image_data_url}(read_file 读图且模型支持 vision):
// 落库时把图片以 image_url 内容块拼进 tool 消息(哨兵 JSON,见 llm.js encodeBlocks),
// buildMessages 发请求前还原为 OpenAI 内容块数组。
let outText;
let imageDataUrl = null;
if (output && typeof output === 'object' && output.image_data_url) {
outText = String(output.text || '');
imageDataUrl = String(output.image_data_url);
} else {
outText = String(output == null ? '' : output);
}
if (run.cancelled && !isError) outText = (outText ? outText + '\n' : '') + '(用户已终止任务)';
log.debug('[tool] ' + sessionId + ' ' + tc.function.name + (isError ? ' 失败: ' : ' 完成: ') + outText.slice(0, 500));
const toolContent = imageDataUrl
? encodeBlocks([
{ type: 'text', text: outText },
{ type: 'image_url', image_url: { url: imageDataUrl } },
])
: outText;
bus.emit(sessionId, 'tool_result', {
tool_call_id: id, name: tc.function.name, content: outText.slice(0, 20000),
is_error: isError, image_url: imageDataUrl || undefined,
});
saveMessage(sessionId, { role: 'tool', tool_call_id: id, name: tc.function.name, content: toolContent });
}
iter++;
}
@@ -483,10 +510,10 @@ function sessionContextContent(session) {
const model = session.model_id
? modelDisplayName(session.model_id)
: '尚未绑定(排队中,绑定后自动开始处理)';
// vision 能力随会话上下文告知 AI:不支持时读图只能拿到元信息,免得白跑一轮 read_file
// vision 能力随会话上下文告知 AI:支持时 read_file 读图会回传图片内容,不支持时只能拿到文件信息
const bound = session.model_id && cfg.models.find(m => m.id === session.model_id);
const visionLine = bound
? (bound.vision ? '支持' : '不支持')
? (bound.vision ? '支持(read_file 读图会返回压缩后的图片内容)' : '不支持(read_file 读图只能拿到文件信息)')
: '未知';
return [
'【会话上下文】由系统自动注入,无需回复本消息',
+16 -3
View File
@@ -12,6 +12,18 @@ function buildSystemPrompt() {
return SYSTEM_PROMPT_TEMPLATE;
}
// 多模态内容块存取:messages.content 列为 TEXT,含图片的 tool 消息
// 以 {"__blocks__":[content...]} 哨兵 JSON 落库(见需求 §5),
// 发请求时还原为 OpenAI 内容块数组(text + image_url)。tool/user 消息共用。
function encodeBlocks(blocks) { return JSON.stringify({ __blocks__: blocks }); }
function decodeBlocks(content) {
if (typeof content !== 'string' || !content.startsWith('{"__blocks__":')) return null;
try {
const parsed = JSON.parse(content);
return Array.isArray(parsed.__blocks__) ? parsed.__blocks__ : null;
} catch (_) { return null; }
}
// 将 DB 消息行转为 OpenAI messages 数组(不含 system,由调用方拼接)。
function buildMessages(session) {
const messages = [{ role: 'system', content: SYSTEM_PROMPT_TEMPLATE }];
@@ -22,9 +34,10 @@ function buildMessages(session) {
if (!m.content) delete m.content;
messages.push(m);
} else if (row.role === 'tool') {
messages.push({ role: 'tool', tool_call_id: row.tool_call_id, name: row.name, content: row.content || '' });
// 含图片的 tool 行:content 还原为 [text, image_url] 内容块数组
messages.push({ role: 'tool', tool_call_id: row.tool_call_id, name: row.name, content: decodeBlocks(row.content) || row.content || '' });
} else {
messages.push({ role: row.role, content: row.content || '' });
messages.push({ role: row.role, content: decodeBlocks(row.content) || row.content || '' });
}
}
return messages;
@@ -128,4 +141,4 @@ async function callModel(cfg, modelId, messages, tools, options) {
return { content, tool_calls: Array.from(toolCalls.values()), finish_reason: finishReason, usage, aborted };
}
module.exports = { callModel, buildMessages, buildSystemPrompt };
module.exports = { callModel, buildMessages, buildSystemPrompt, encodeBlocks, decodeBlocks };
+8 -2
View File
@@ -446,5 +446,11 @@ body {
.cfg-err {
margin: 8px 12px 0; padding: 8px 12px; border-radius: 8px;
background: #fdecea; color: #a3352a; font-size: 12.5px;
white-space: pre-wrap; word-break: break-all;
}
white-space: pre-wrap; word-break: break-all;
}
/* read_file 读图回传的图片缩略(点开原图) */
.tool-img {
display: block; max-width: 240px; max-height: 240px;
border-radius: 6px; margin-top: 6px; cursor: zoom-in;
}
+29 -3
View File
@@ -256,13 +256,39 @@ function renderToolCard(id, name, argsStr) {
return div;
}
function fillToolResult(id, content, isError) {
// tool 消息 content:纯文本,或含图片时的哨兵 JSON {"__blocks__":[...]}(read_file 读图回传,见 llm.js)
function parseToolContent(content) {
if (typeof content === 'string' && content.startsWith('{"__blocks__":')) {
try {
const blocks = JSON.parse(content).__blocks__ || [];
const img = blocks.find(b => b.type === 'image_url');
return {
text: blocks.filter(b => b.type === 'text').map(b => b.text).join('\n'),
imageUrl: img && img.image_url && img.image_url.url || null,
};
} catch (_) { /* 解析失败按原文显示 */ }
}
return { text: content, imageUrl: null };
}
function fillToolResult(id, content, isError, liveImageUrl) {
const card = document.getElementById('tool-' + id);
if (!card) return;
if (isError) card.classList.add('error');
card.querySelector('.spin').textContent = isError ? '✕' : '✓';
const parsed = parseToolContent(content);
const pre = card.querySelector('.tool-result');
if (pre) pre.textContent = content || '(空)';
if (!pre) return;
pre.textContent = parsed.text || '(空)';
const img = liveImageUrl || parsed.imageUrl;
if (img && !card.querySelector('.tool-img')) {
const el = document.createElement('img');
el.className = 'tool-img';
el.src = img;
el.title = '点击查看详情';
el.onclick = () => window.open(el.src);
pre.insertAdjacentElement('afterend', el);
}
}
function msgNode(m, cardMap) {
@@ -421,7 +447,7 @@ function connectStream() {
});
es.addEventListener('tool_result', ev => {
const d = JSON.parse(ev.data);
fillToolResult(d.tool_call_id, d.content, d.is_error);
fillToolResult(d.tool_call_id, d.content, d.is_error, d.image_url);
scrollBottom();
});
es.addEventListener('done', ev => {
+39 -2
View File
@@ -85,6 +85,12 @@ function truncate(text, max) {
const AUTO_OUTLINE_SIZE = 16384;
const IMAGE_EXTS = new Set(['.png', '.jpg', '.jpeg', '.webp', '.gif', '.bmp', '.tiff', '.tif']);
// read_file 读图(仅当会话绑定的模型 vision: true):sharp 压缩后转 base64 data URL,
// 由 engine 拼成下一轮请求里 tool 消息的 image_url 内容块。
const IMG_MAX_INPUT_BYTES = 50 * 1024 * 1024; // 与上传上限一致
const IMG_MAX_SIDE = 2000; // 长边压缩阈值(px)
const IMG_JPEG_QUALITY = 80;
// 简化版符号大纲(Zed 用 tree-sitter,这里用正则提取常见语言的顶层符号 + Markdown 标题)。
// 返回 "# File outline ..." 文本;无法提取时返回 null(调用方回退到首 1KB)。
const OUTLINE_RES = [
@@ -130,6 +136,29 @@ function outlineWrapper(outlineText) {
'For example, to read a function shown as [L100-150], use start_line: 100 and end_line: 150.';
}
// 用 sharp 压缩(按 EXIF 摆正、长边 ≤2000px、JPEG 质量 80)并转 base64 data URL。
// 成功返回 {text, image_data_url},engine 侧拼成 tool 消息的多模态内容块;
// sharp 缺失或解码失败时退回纯文本提示,不让整个工具回合报错。
async function readImageAsBlocks(abs, rel, size) {
let sharp;
try { sharp = require('sharp'); }
catch (_) { return '[图片文件] ' + rel + '(' + size + ' 字节)。服务端未安装 sharp,无法压缩回传图片内容。'; }
try {
const r = await sharp(abs)
.rotate()
.resize({ width: IMG_MAX_SIDE, height: IMG_MAX_SIDE, fit: 'inside', withoutEnlargement: true })
.jpeg({ quality: IMG_JPEG_QUALITY })
.toBuffer({ resolveWithObject: true });
return {
text: '[图片文件] ' + rel + '(原 ' + size + ' 字节,已压缩为 ' + r.info.width + '×' + r.info.height +
' JPEG ' + r.data.length + ' 字节,图片见同条消息的 image_url 内容块)',
image_data_url: 'data:image/jpeg;base64,' + r.data.toString('base64'),
};
} catch (err) {
return '[图片文件] ' + rel + '(' + size + ' 字节),图片解码/压缩失败:' + (err && err.message || err);
}
}
async function toolReadFile(ctx, args) {
const abs = resolveInTask(ctx.taskDir, args.path);
let st;
@@ -137,7 +166,14 @@ async function toolReadFile(ctx, args) {
catch (_) { throw new Error('文件不存在:' + args.path); }
if (st.isDirectory()) throw new Error(args.path + ' 是目录不是文件,请用 list_directory 工具查看目录内容。');
if (IMAGE_EXTS.has(path.extname(abs).toLowerCase())) {
return '[图片文件] ' + relOf(ctx.taskDir, abs) + '(' + st.size + ' 字节)。当前服务无法把图片内容回传给模型。';
const rel = relOf(ctx.taskDir, abs);
if (!ctx.vision) {
return '[图片文件] ' + rel + '(' + st.size + ' 字节)。图片文件,当前模型不支持视觉识别,无法回传图片内容。';
}
if (st.size > IMG_MAX_INPUT_BYTES) {
return '[图片文件] ' + rel + '(' + st.size + ' 字节)过大(上限 ' + IMG_MAX_INPUT_BYTES + ' 字节),已跳过回传。';
}
return await readImageAsBlocks(abs, rel, st.size);
}
if (isProbablyBinary(abs)) return '[二进制文件,跳过文本读取] ' + relOf(ctx.taskDir, abs);
const text = await fsp.readFile(abs, 'utf8');
@@ -646,7 +682,8 @@ const HANDLERS = {
run_skill: (ctx, args) => skills.runSkill(ctx, args.skill_name, args.input_args),
};
// ctx: {sessionId, taskDir, run, cfg, db}
// ctx: {sessionId, taskDir, run, cfg, db, vision}
// 返回值一般为字符串;read_file 读图且 ctx.vision 为 true 时返回 {text, image_data_url}。
// 内置工具优先;未命中时交给 MCP 注册表(启动时发现的服务工具)。
async function executeTool(baseCtx, name, args) {
const handler = HANDLERS[name];