[Bug] 缺少 tool_calls ↔ tool 回执配对校验:插件钩子误删 tool 消息后,该会话所有后续请求持续 400 (insufficient tool messages following tool_calls)
问题描述
某次带工具调用的对话之后,该会话(webchat 私聊)所有后续请求全部返回 400,换平台发送(包括 WebUI 聊天页)同样报错;重启容器无效(历史持久化于 data/data_v4.db);删除/重置该会话后恢复。
如何复现?
环境
- AstrBot 版本:v4.28.2(Docker 部署,容器路径
/AstrBot,Python 3.12) - LLM:OpenAI 兼容接口(DeepSeek 系列,主/备模型均触发)
- 诱因:第三方插件
astrbot_plugin_memory_companion在on_llm_request钩子中清理历史。插件逻辑确有缺陷(见下),但本 issue 反映的是框架层缺少配对校验——任何插件/扩展以同类方式修改历史都会触发
最小复现思路(无需该插件)
任意插件在 on_llm_request 钩子中对 req.contexts 移除一条 role=tool 的消息(或将其内容清空后整条移除——实际插件即此行为),保持上游 assistant(tool_calls) 不动。下一次请求即 400,且该会话从此持续 400,直到重置会话。
实际触发链路(2026-10-03 日志时间线)
10:13:30.160 [MemoryCompanion] 已清理陪伴主动消息历史残留: removed=2 cleaned=5 (141→139)
↑ 插件逐行按关键字 "send_message_to_user" 匹配删除、不区分 role,
命中 role=tool 回执正文(内容含工具名)→ 内容清空 → 整条消息被移除
10:13:30.19x BefCompact / AftCompact 均为 137 条 → 未触发截断、未触发压缩
10:13:30.83x POST /chat/completions → 400 insufficient tool messages
当日该错误命中 5 次(含 1 次备用模型重试),全部集中在同一会话。此前另一会话还出现过同根因的反向文案 Messages with role 'tool' must be a response to a preceding message with 'tool_calls'(tool 成为孤儿),说明两个方向都缺少校验。
根因分析(v4.28.2 源码)
缺口 1:配对校验只挂在截断/压缩路径上,正常请求完全缺席
astrbot/core/agent/context/manager.py → ContextManager.process():
result = messages
# 1. 轮数截断
if self.config.enforce_max_turns != -1:
result = self.truncator.truncate_by_turns(...)
# 2. token 压缩
if self.config.max_context_tokens > 0:
...
if self.compressor.should_compress(...):
result = await self._run_compression(result, total_tokens)
return result # ← 无论走没走上面两步,出口都没有配对校验
fix_messages() 仅在 truncator.py 的 truncate_by_turns / truncate_by_dropping_oldest_turns / truncate_by_halving 三个方法尾部被调用,且这些方法各有多处早退(return messages)。本例截断未触发(压缩前后条数一致),因此没有任何一步做过配对校验。
缺口 2:即使执行,fix_messages() 也只判「有没有」、不判「够不够」
astrbot/core/agent/context/truncator.py → fix_messages():
def flush_pending_if_valid():
if pending_assistant is not None and pending_tools: # ← 只判非空
fixed_messages.append(pending_assistant)
fixed_messages.extend(pending_tools)
不比对 tool 响应数量 / tool_call_id 集合是否完整覆盖 message.tool_calls 的 id 集合。assistant 声明 N 个 tool_calls、只剩 N-1 条回执时被原样放行,上游即报 "insufficient tool messages"(数量不足型断裂),与本 issue 的错误文案吻合。
建议修复
ContextManager.process()出口无条件调用一次fix_messages()(O(n) 成本),不再依赖是否发生截断;fix_messages()判据从「存在 tool 回执」升级为「tool 回执的tool_call_id集合完整覆盖tool_calls的 id 集合」,不完整则整链剔除;更保守的变体是对缺失 id 补一条合成回执(如content="该回执丢失"),可保留其余上下文;- (可选)插件开发文档提示:在
on_llm_request钩子中修改 contexts 时必须保持 tool_calls/tool 配对完整性。
关联:PR #9691 处理的是「工具返回不支持内容类型 → 完全缺失 tool 消息」路径;本 issue 是「插件钩子删消息 → 数量不足」路径。上述第 2 点的 id 覆盖校验可同时兜住两类来源。
本地验证
我们在 manager.py 出口加「无条件校验 + id 覆盖校验」的本地补丁后,该 400 不再出现。补丁曾于 2026-10-01 生效,后因容器重建丢失,2026-10-03 在干净的 v4.28.2 镜像上复现——侧面验证补丁有效,且缺口存在于上游源码本身。
影响面(本日志窗口,约 17 小时)
插件清理事件 138 次,其中真正移除消息(removed>0)67 次,分布在 8 个会话。风险在于:任意一次误删 role=tool 回执或含 tool_calls 的 assistant 消息,都会永久污染该会话直到人工重置,且报错点(tool_loop_agent_runner)远离真正的成因点(钩子),排查成本很高。
AstrBot 版本
v4.28.2
操作系统
Linux
部署方式
Docker
使用的消息平台适配器
Onebot v11
错误日志
Error code: 400 - {'error': {'message': "An assistant message with 'tool_calls' must be followed by tool messages responding to each 'tool_call_id'. (insufficient tool messages following tool_calls message)", 'type': 'invalid_request_error', 'code': 'invalid_request_error'}}
[2026-10-03 10:13:30.836] [Core] [WARN] [v4.28.2] [runners.tool_loop_agent_runner:627]:
Chat Model deepseek/deepseek-flash request error: Error code: 400 - ...(request_id: b46ecaf7-…)
[2026-10-03 10:44:14.284] [Core] [WARN] [v4.28.2] [runners.tool_loop_agent_runner:627]:
Chat Model deepseek/deepseek-flash request error: Error code: 400 - ...(request_id: fa88ca4d-…)
辅助信息
No response
检查清单
这个我来做,今天提 PR。
两个缺口在现行 master 上都核实过:ContextManager.process() 出口确实没有任何配对校验,fix_messages() 的 flush 判据确实只看 pending_tools 非空。
修复按建议的 1+2 主线走:
process()出口无条件过一次fix_messages(),不再依赖截断是否触发;- flush 判据升级为
tool_call_id集合完整覆盖tool_calls声明的 id 集合,不完整就整链剔除(与现有孤儿处理保持一致);声明里 id 缺失的 tool_calls 保留旧的非空判据,避免误伤不回 id 的 provider;回执 id 落在声明集合之外的(反向孤儿)一并剔除,把Messages with role 'tool' must be a response to...那个方向也兜住。
合成回执的变体先不做:往上下文里编一条假的工具结果比丢一轮工具调用更容易误导模型,而且和 fix_messages 现有的"无效即剔除"语义不一致。测试会覆盖数量不足、反向孤儿、id 缺失回退、以及 process() 层面的无条件修复。
补充一条 v4.29.1 的复现记录。v4.29.3 源码核对:ContextManager.process() 出口仍没有 fix_messages(),fix_messages() 仍只判断 pending_tools 非空,问题未修复。
这次的上游来源和主贴同类,但触发路径不同:工具未注入 → 模型调用未知工具 → runner 写入 not found 回执 → 后续清理删除该回执。
时间线(已脱敏):
[12:37:15.687] [Core] [INFO] [runners.tool_loop_agent_runner:1185]: Agent 使用工具: ['<plugin_tool>']
[12:37:15.687] [Core] [WARN] [v4.29.1] [runners.tool_loop_agent_runner:1244]: 未找到指定的工具: <plugin_tool>,将跳过。
[14:09:02.248] [Core] [DBUG] [pipeline.context_utils:98]: hook(OnLLMRequestEvent) -> astrbot_plugin_memory_companion - on_llm_request
[14:09:02.268] [Plug] [INFO] [astrbot_plugin_memory_companion]: 已清理陪伴主动消息历史残留: session=[bot]:GroupMessage:[group-id] removed=1 cleaned=2 before=450 after=449
[14:09:02.335] [Core] [DBUG] [runners.tool_loop_agent_runner:696]: [BefCompact] messages -> [451] system,user,assistant,user,...,assistant,tool,assistant,user
[14:09:03.060] [Core] [DBUG] [openai._base_client:1810]: HTTP Response: POST 400
[14:09:03.061] [Core] [WARN] [v4.29.1] [runners.tool_loop_agent_runner:636]: Chat Model [provider] request error: Error code: 400 - {'error': {'code': 'invalid_request_error', 'message': "An assistant message with 'tool_calls' must be followed by tool messages responding to each 'tool_call_id'. (insufficient tool messages following tool_calls message)", 'param': '', 'type': 'invalid_request_error'}}
补充验证:用插件里的清理函数对当时 450 条历史重放,dropped 恰好等于那条 role=tool 回执,与日志里的 removed=1 cleaned=2 完全一致;该回执的内容是一行 Available tools are: ... send_message_to_user ... 的报错文本。
另外,这条 400 的上游触发源是一个独立问题:部分群消息上插件处理被跳过,导致本轮工具未注入、runner 写下 Tool ... not found 回执。它已另开 issue:#10808。该 issue 与 #10338 的现象、根因和修复层都不同,PR #10342 不能覆盖它。
#10342 的修法(无条件配对校验 + id 覆盖)能覆盖本评论这类"数量不足"路径;建议优先 review,谢谢。