Repository navigation
Description
现象
NativeToolClient.chat() 里,当一条 tool_result 的 tool_use_id 为空时(文本兜底还原出来的 MockToolCall 默认 id=''),原实现是把结果前置插入 combined_content:
else: combined_content = [{"type": "text", "text": f'<tool_result>{content}</tool_result>'}] + combined_content每次 prepend 都会把上一次插入的挤到后面,于是产生两个可见缺陷。
缺陷 1:多个空 id 结果顺序反转(数据错乱)
实测 3 个结果 R1 / R2(无 id)+ R3(有 id),实际发出:
{"role": "user", "content": [
{"type": "tool_result", "tool_use_id": "call_X", "content": "R3"},
{"type": "text", "text": "<tool_result>R2</tool_result>"},
{"type": "text", "text": "<tool_result>R1</tool_result>"},
{"type": "text", "text": "USER_TEXT"}]}R2 跑到了 R1 前面。注意 tool_result_blocks(有 id 的)是 append 的,顺序正确;
只有走裸文本分支的会反转 —— 两条路径的顺序语义不一致。
缺陷 2:结果块被插到用户正文之前
裸文本结果被塞到 combined_content 头部,意味着模型看到的顺序是「工具结果 → 用户这句话」,
而结构化路径(final_content = tool_result_blocks + filtered_content)也是结果在前。
两条路径都把结果放在正文前,但裸文本那条是 逆序 的。
复现
import llmcore
class B:
name = "b"; model = "m"; system = ""; tools = None
history = [{"role": "user", "content": "prev"}]
def ask(self, merged):
self.sent = merged
def _g():
r = llmcore.MockResponse("", "hi", [])
r.tool_calls = []
yield r
return _g()
c = llmcore.NativeToolClient(B())
list(c.chat(messages=[{"role": "user", "content": "USER_TEXT",
"tool_results": [
{"tool_use_id": "", "content": "R1"},
{"tool_use_id": "", "content": "R2"},
{"tool_use_id": "call_X", "content": "R3"},
]}], tools=None))
print(c.backend.sent["content"])输出 R2 在 R1 前。
触发条件有多常见
只有在文本兜底还原路径才会产生空 id 的 MockToolCall
(llmcore._parse_text_tool_calls / _parse_pseudo_xml_tool_calls,即模型不调用原生
tool 接口、改把调用写成正文伪 XML 时)。
本地 24 个生产会话日志(temp/model_responses/)里,该路径的出现频率:
- 真实注入的
[ERROR] Your tool call was emitted as plain XML text (...)6 次
(group/welfare×5、group/buddy×1),其中 5 次当轮自愈 - 45 处「伪 XML 收尾且无原生 tool_use」的响应,喂给真
_parse_text_tool_calls
全部可还原(43 处返 1 个调用,2 处返 2 个)→ 不存在静默丢失 - 也就是说,一次响应返回 2 个伪 XML 调用是能发生的(实测 2 例),
这时就会踩到本文的顺序反转
所以不是高频故障,但一旦发生,模型拿到的是逆序的工具结果,会导致:
- 「第 2 步的结果」被当成「第 1 步的」,多步脚本类工具(先查表结构再查数据)容易误判
- 排查时看到日志里 R2 在 R1 前,会误以为是并发/竞态
期望
空 id 的结果按出现顺序保留,且不与结构化块交叉。
附:同类但不属于本 issue 的两点
- 日志把
tool_result记成裸文本<tool_result>{...}塞进 user 消息,
重放/审计时难分「工具真返回值」和「模型自造」。这是日志格式问题,不是执行链缺陷。 textual_tool_residue()对上述 45 处全部返回None(即可还原),
说明检测器工作正常,无需改动。
PR: #879(fix/tool-result-order-v2 分支,只改 llmcore.py 一处,+6/-1)。
前一个 PR #878 已关闭:它误把本地分支的
llmcore.py整份覆盖到上游文件上,
产生了 +2314/-66 的噪声 diff。#879 基于 upstreammain@68d996a重新生成,只含目标改动。
Activity
leonsong09 commentedon Nov 14, 2026
Folded into #880 (commit 4 of 6,
llmcore.py+6/-1).