[历史遗留BUG] 并发多图 tool_result 导致上游 400:extra_parts 插队破坏了 functionResponse 连续性 (关联 #3094)
[BUG] 并发多图 tool_result 导致上游 400:extra_parts 插队破坏了 functionResponse 连续性 (关联 #3094)
问题描述
使用 Agent 客户端(如 Claude Code / OpenCode)通过本地代理请求模型时,若模型在单轮内并发调用多个工具并返回多张图片(例如并发执行多个 Read 读取本地图片切片):
上游接口将 100% 返回 HTTP 400 校验错误:
{
"error": {
"code": 400,
"message": "messages.N: `tool_use` ids were found without `tool_result` blocks immediately after: <tool_use_id>. Each `tool_use` block must have a corresponding `tool_result` block in the next message.",
"status": "INVALID_ARGUMENT"
}
}客户端随之报错中断:API Error: 400 due to tool use concurrency issues。
注:该问题与未关闭的 #3094 属于同一技术根因。单张图片顺序读取 100% 正常,仅在并发返回多张图片时必现。
源码根因定位
问题位于 src-tauri/src/proxy/mappers/claude/request.rs 的 build_contents 函数在处理 ContentBlock::ToolResult 时的组包逻辑:
// 当前代码逻辑
ContentBlock::ToolResult { .. } => {
// 1. 生成并推入当前工具的 functionResponse
parts.push(function_response_part);
// 2. 提取该 tool_result 内的图片为 extra_parts
let mut extra_parts = Vec::new();
if block.get("type").and_then(|v| v.as_str()) == Some("image") {
...
extra_parts.push(create_gemini_inline_part(...));
}
// 3. 立即将当前工具的 inlineData 图片紧随推入 parts
for extra in extra_parts {
parts.push(extra);
}
}为什么并发多图必崩?
当单轮存在两个并发的图片工具返回(ToolResult_A 与 ToolResult_B)时,当前代码生成的 parts 数组序列为:
parts: [
0: functionResponse_A,
1: inlineData (Image A), <--- 致命插队!
2: functionResponse_B,
3: inlineData (Image B)
]上游对于工具响应轮次(role: user 响应 functionCall)有严苛的连续性规范:同一轮中针对所有 functionCall 的 functionResponse 必须紧密相邻/位于前列。
一旦 inlineData 插在 functionResponse_A 与 functionResponse_B 中间,上游的解析器会将 inlineData 视作普通用户输入断开匹配,导致后面的 functionResponse_B 被丢弃或未能识别,触发“上一轮的 tool_use 未找到紧随其后的 tool_result”的 400 拦截。
单张图之所以正常,是因为只有单个 functionResponse,后面即使有 inlineData 也无后续 functionResponse 被截断。
建议修复方案
将图片等 extra_parts 暂存延迟追加,确保同一轮 Turn 中所有的 functionResponse 排在最前面且连续无断层:
// 建议在 build_contents 处理单轮消息时:
let mut function_response_parts = Vec::new();
let mut tool_image_parts = Vec::new();
for block in blocks {
match block {
ContentBlock::ToolResult { .. } => {
function_response_parts.push(function_response_part);
if block.get("type").and_then(|v| v.as_str()) == Some("image") {
...
tool_image_parts.push(create_gemini_inline_part(...));
}
}
...
}
}
// 保证所有 functionResponse 连续紧凑排在前面,图片 inlineData 统一放在末尾
parts.extend(function_response_parts);
parts.extend(tool_image_parts);如此组装出的 parts 顺序为:
parts: [
0: functionResponse_A,
1: functionResponse_B,
2: inlineData (Image A),
3: inlineData (Image B)
]完全符合上游 Function Response 的状态机连续性校验要求,彻底解决并发多图的 400 崩溃问题。
补充说明:为什么该 Bug 会因下游模型而异(Gemini 能过,Claude 崩)?
根本原因在于上游对 parts 数组的消费方式不同:
- Gemini 原生模型:直接由 Google 原生引擎消费请求,其内部对同一个 Turn 内
functionResponse与inlineData(图片)交替穿插的结构容错度极高,能够直接正确解析,因此不报错; - Claude 家族模型:上游服务在调用 Claude 后端引擎前,需要将上述
parts数组逆向转译为 Anthropic Messages API 规范。当转译器读到插在中间的inlineData时会发生状态截断,导致紧随其后的第二个functionResponse在转译中丢失,最终被 Anthropic 引擎因“工具调用悬空、未紧邻对应结果”而直接抛出 400 拦截。
因此,只要将所有的 functionResponse 连续排列在前、图片统一延后追加,便能抹平此转译差异,让 Claude 模型同样完美支持并发多图。
Source: lbjlaq/Antigravity-Manager