From 4edc776ef8bf0439d817b0292cb5cc0d193e7952 Mon Sep 17 00:00:00 2001
From: leonsong09 <59187950+leonsong09@users.noreply.github.com>
Date: Fri, 13 Nov 2026 10:33:59 +0800
Subject: [PATCH] =?UTF-8?q?fix(llmcore):=20=E7=A9=BA=20tool=5Fuse=5Fid=20?=
=?UTF-8?q?=E7=9A=84=20tool=5Fresult=20=E4=B8=8D=E5=86=8D=E5=8F=8D?=
=?UTF-8?q?=E8=BD=AC=E9=A1=BA=E5=BA=8F/=E6=8F=92=E5=88=B0=E6=AD=A3?=
=?UTF-8?q?=E6=96=87=E5=89=8D?=
MIME-Version: 1.0
Content-Type: text/plain; charset=UTF-8
Content-Transfer-Encoding: 8bit
chat() 里 tool_use_id 为空的 tool_result(文本兜底还原出来的 MockToolCall
默认 id='')原本走「前置插入裸文本」分支:
else: combined_content = [{"type": "text", "text": f'{content}'}] + combined_content
每次 prepend 都会把上一次插入的挤到后面,导致两个缺陷:
1. 多个空 id 结果顺序反转(实测 R1,R2 发出 R2,R1)
2. 与有 id 的 tool_result_blocks(append,顺序正确)语义不一致
改为按出现顺序收进 orphan_results,循环结束后 extend 到 combined_content 尾部。
所有 id 齐全时的行为逐字节不变。
验证(抽取该函数体 + 桩依赖,4 个用例):
- 两个空 id + 一个真 id -> R1 在 R2 前,且都在用户正文之后
- 全部有 id -> 顺序与正文位置不变
- 只有空 id -> 正文在结果之前
- _pending_tool_ids 补空 content 行为不变
---
llmcore.py | 7 ++++++-
1 file changed, 6 insertions(+), 1 deletion(-)
diff --git a/llmcore.py b/llmcore.py
index 04bdeffd0..8611ec81f 100644
--- a/llmcore.py
+++ b/llmcore.py
@@ -1098,11 +1098,16 @@ def chat(self, messages, tools=None):
elif isinstance(c, list): combined_content.extend(c)
if msg['role'] == 'user' and msg.get('tool_results'): tool_results.extend(msg['tool_results'])
tr_id_set = set(); tool_result_blocks = []
+ # 2026-11-13: 空 tool_use_id 的结果按出现顺序收集, 循环结束后统一追加。
+ # 原实现是每次往 combined_content 头部 insert, 导致多个空 id 结果顺序反转
+ # (实测 R1,R2 -> 发出 R2,R1), 且被插到用户正文之前。
+ orphan_results = []
for tr in tool_results:
tool_use_id, content = tr.get("tool_use_id", ""), tr.get("content", "")
tr_id_set.add(tool_use_id)
if tool_use_id: tool_result_blocks.append({"type": "tool_result", "tool_use_id": tool_use_id, "content": tr.get("content", "")})
- else: combined_content = [{"type": "text", "text": f'{content}'}] + combined_content
+ else: orphan_results.append({"type": "text", "text": f'{content}'})
+ combined_content.extend(orphan_results)
for tid in self._pending_tool_ids:
if tid not in tr_id_set: tool_result_blocks.append({"type": "tool_result", "tool_use_id": tid, "content": ""})
self._pending_tool_ids = []