Repository navigation
fix(provider): sanitize legacy tool-call history across OpenAI providers - #11223
JosephTian876 wants to merge 2 commits into
Conversation
There was a problem hiding this comment.
Hey - I've found 5 issues
Prompt for AI Agents
Please address the comments from this code review:
## Individual Comments
### Comment 1
<location path="astrbot/core/provider/sources/openai_source.py" line_range="564-565" />
<code_context>
+ pending_assistant = msg
+ pending_tool_call_ids = {}
+ for tc in msg["tool_calls"]:
+ if not isinstance(tc, dict) or "id" not in tc:
+ continue
+ original_id = tc["id"]
+ call_id = original_id
</code_context>
<issue_to_address>
**Malformed tool calls reach providers**
When historical assistant `tool_calls` contain a non-dictionary entry or an entry without an `id`, `_sanitize_assistant_messages` skips these entries while building `pending_tool_call_ids` but leaves them in `msg["tool_calls"]`, so strict providers reject the outgoing request with a 400.
Remove malformed entries from `msg["tool_calls"]` instead of only skipping them during the scan.
</issue_to_address>
### Comment 2
<location path="astrbot/core/provider/sources/openai_source.py" line_range="455" />
<code_context>
@staticmethod
def _sanitize_assistant_messages(payloads: dict) -> None:
- """在请求发送前过滤/规范化空的 assistant 消息。
+ """Normalize assistant messages and pair tool calls with their results.
- 严格 API(Moonshot、DeepSeek Reasoner 等)会在 assistant 消息同时缺少
</code_context>
<issue_to_address>
**Responses requests retain invalid tool history**
When requests use the `openai_responses` provider with historical tool-call sequences that contain reused IDs, unmatched calls, or orphaned results, `ProviderOpenAIResponses` converts the raw context directly into Responses input items without applying this sanitizer, so the invalid history reaches the endpoint and the request can fail.
Apply the tool-history sanitization when preparing history for the Responses provider.
Also at `astrbot/core/provider/sources/openai_source.py:478`.
</issue_to_address>
### Comment 3
<location path="astrbot/core/provider/sources/openai_source.py" line_range="579-584" />
<code_context>
+ call_id = f"call_astrbot_{msg_index}_{suffix}"
+ tc["id"] = call_id
+ used_tool_call_ids.add(call_id)
+ pending_tool_call_ids[original_id] = call_id
final.append(msg)
elif role == "tool":
tool_call_id = msg.get("tool_call_id")
if tool_call_id in pending_tool_call_ids:
+ msg["tool_call_id"] = pending_tool_call_ids.pop(tool_call_id)
final.append(msg)
- pending_tool_call_ids.remove(tool_call_id)
</code_context>
<issue_to_address>
**Delayed results attach to newer calls**
When a delayed result from an earlier unanswered round arrives after a later assistant call reuses the same original ID, `pending_tool_call_ids`, keyed by the original ID, rewrites the delayed result to the newer call's generated ID and retains it as that call's response, so the model sees stale tool history.
Track pending calls separately so a delayed result cannot be rewritten as the response to a newer call.
</issue_to_address>
### Comment 4
<location path="astrbot/core/provider/sources/openai_source.py" line_range="576" />
<code_context>
+ call_id = original_id
+ if call_id in used_tool_call_ids:
+ suffix = 0
+ call_id = f"call_astrbot_{msg_index}_{suffix}"
+ while (
+ call_id in reserved_tool_call_ids
</code_context>
<issue_to_address>
**Orphan results get attached to another call**
When an orphan tool result follows a repeated call and its ID matches the generated `call_astrbot_<msg_index>_0` value, an orphan tool message has a `tool_call_id` equal to the generated replacement ID, so the sanitizer renames the repeated call to that ID and accepts the orphan result as its response; the request then contains unrelated tool output as conversation history.
Include all existing tool-message `tool_call_id` values in the reserved IDs before generating replacement IDs.
</issue_to_address>
### Comment 5
<location path="tests/test_openai_source.py" line_range="1656-1778" />
<code_context>
await provider.terminate()
+def test_sanitize_assistant_messages_renames_reused_ids_across_rounds():
+ def call(call_id):
+ return {
+ "id": call_id,
+ "type": "function",
+ "function": {"name": "search", "arguments": "{}"},
+ }
+
+ payloads = {
+ "messages": [
</code_context>
<issue_to_address>
**New tests contradict guidance**
When the PR adds test cases and fixture changes to the test suite, the PR adds new test functions and changes test fixtures and assertions in `tests/test_openai_source.py`, contrary to the repository guidance against generating test files.
Remove the newly added test cases and test-only fixture changes to follow the repository guidance.
Also at `tests/test_openai_source.py:2077`, `tests/test_openai_source.py:2086`, `tests/test_openai_source.py:2093`, `tests/test_openai_source.py:2200`.
</issue_to_address>Sourcery assessment
Approval pending. 4 findings to address first.
Blocking findings: astrbot/core/provider/sources/openai_source.py:565, astrbot/core/provider/sources/openai_source.py:455, astrbot/core/provider/sources/openai_source.py:584, astrbot/core/provider/sources/openai_source.py:576
|
Codecov Report❌ Patch coverage is
📢 Thoughts on this report? Let us know! |
|
Rebased onto latest \master\ (\22834e62) with no changes to this PR's scoped diff (\�c46a45\ / \c4e11ed) to re-trigger CI after the unrelated \ ests/unit/test_event_bus.py::TestEventFiltering::test_filter_by_event_origin\ \TimeoutError\ flake on \ubuntu-latest. Verified locally with |
1be449f to
c4e11ed
Compare
c4e11ed to
e619ae4
Compare
现象
从旧版本会话继续对话时,OpenAI 兼容 Provider 会返回 400,典型报错:
或(部分严格实现):
触发条件很窄但很常见:历史里存在被上下文截断/压缩过的工具调用轮次,
或者某些旧前端/适配器把
tool_call.id复用了(同一个id在多轮里重复出现)。根因
astrbot/core/provider/sources/openai_source.py:453的_sanitize_assistant_messages()只做了两件事:过滤全空的 assistant 消息,以及丢掉「找不到对应 assistant 的 tool 消息」。它有两个漏洞:
只按单轮收集 id。 原实现(
openai_source.py:499-513)每遇到一条 assistant就把
pending_tool_call_ids整个覆盖:于是两轮都用
"search"作为 id 时,第二条 tool 消息会被匹配到第二轮那个call 上,而第一轮的 call 变成永远无人应答 —— 一旦某轮被截断留下半个轮次,
就会拼出一个非法序列。
从不检查「call 有没有结果」。 只过滤孤儿 tool 消息,不处理反过来的情况:
assistant 声明了
tool_calls但对应结果已被截断删除。这种残留会直接让严格实现拒绝整个请求。
此外,被
removed_assistant逻辑删掉的那条空 assistant 消息没有留下任何边界,前后两段可能被错误拼接,让后面的 tool 结果匹配到更早的 call 上。
改动
_sanitize_assistant_messages()重写为一次线性扫描,维护四个集合:reserved_tool_call_ids:全量预扫,收集所有已出现的 id,作为改名时的避让池。used_tool_call_ids:已经发放过的 id,用于检测跨轮复用。pending_tool_call_ids: dict[str, str]:本轮「原始 id → 实际发放 id」的映射。用 dict 而不是 set,才能在改名后把对应的 tool 消息一起改写。
pending_assistant:持有当前未答完 call 的那条 assistant 消息。三处关键逻辑:
(a) 跨轮重复 id 就地改名。 遇到
used_tool_call_ids里已有的 id,改成call_astrbot_<msg_index>_<n>,并避开reserved_tool_call_ids与used_tool_call_ids里已有的取值:对应 tool 消息在匹配时同步改写
msg["tool_call_id"],因此配对关系保持不变。(b) 同一批内重复 id 直接省略。 一条 assistant 里两个 call 用了同一个 id 时,
无法可靠判断哪条结果是哪一个,这种情况下把该 id 的 call 连同其结果一起从本次请求
中省略,不改动已保存的会话内容:
省略后若该 assistant 已无 call 且
content也为空,整条消息一并移除。(c) 未应答的 call 在边界处清除。 扫描到「不是 tool 的消息」或输入结束时,
把仍
pending的 call 从pending_assistant["tool_calls"]里剔除;剔完为空且
content也为空时整条移除(有reasoning_content则把content置
""保留,符合既有约定)。另外,被移除的空 assistant 消息现在会往
cleaned里压一个哨兵removed_assistant,扫描时据此断开pending_tool_call_ids,避免结果跨过被删段落匹配到更早的 call。
所有改动都是就地修正本次请求的 payload,不修改已持久化的会话历史。
验证
tests/test_openai_source.py新增 5 项用例:test_sanitize_assistant_messages_renames_reused_ids_across_rounds(含幂等性断言:对同一 payload 重复调用结果不变)
test_sanitize_assistant_messages_keeps_only_resolved_unambiguous_callstest_sanitize_assistant_messages_omits_empty_ambiguous_batchtest_sanitize_assistant_messages_does_not_match_results_across_removed_batchtest_sanitize_assistant_messages_resets_tool_ids_after_non_tool_message(既有用例,断言随新语义更新:无人应答的 call 现在会被移除)
另有两项既有用例
test_query_converts_empty_content_to_none_with_tool_calls、test_query_keeps_assistant_message_with_tool_calls_and_none_content的输入补上了缺失的
{"role": "tool", "tool_call_id": ...}结果消息——原输入本身就是非法序列(只有 call 没有 result),正是本 PR 要修复的形态,
断言的消息条数相应从 3 调整为 4。
在
AstrBotDevs/AstrBot的master(b4518f10)之上,把新增的测试文件覆盖到未修复的
openai_source.py上运行:应用本 PR 后,在同一
master之上:风险
会话持久化。
但如果外部日志分析依赖原始 id,会看到
call_astrbot_*。模型因此看不到那部分工具交互。这是刻意的取舍:保留它们会被严格实现整体拒绝,
上下文全丢。原始会话数据不受影响。
_sanitize_assistant_messages结果不变),但若将来有调用点依赖「清洗前后 id 一致」,需要重新评估。
建议合并顺序
本 PR 属于 AstrBot 主仓,与记忆插件系列 PR 完全独立,可单独评审合并。
前置:无。当前
master(b4518f10)上git apply --check干净通过,astrbot/core/provider/sources/openai_source.py与tests/test_openai_source.py两个文件的 blob 与提交基点
9f761bfa完全一致,不存在基线漂移。Summary by Sourcery
Prevent OpenAI-compatible providers from rejecting legacy conversations by sanitizing tool-call history before requests are sent.
Bug Fixes:
Enhancements:
Tests: