Skip to content

fix(provider): sanitize legacy tool-call history across OpenAI providers - #11223

Open
JosephTian876 wants to merge 2 commits into
AstrBotDevs:masterfrom
JosephTian876:fix/legacy-tool-call-history-20261117
Open

JosephTian876 wants to merge 2 commits into
AstrBotDevs:masterfrom
JosephTian876:fix/legacy-tool-call-history-20261117

Conversation

@JosephTian876

@JosephTian876 JosephTian876 commented Nov 17, 2026 •

Copy link
Copy Markdown
Contributor

现象

从旧版本会话继续对话时,OpenAI 兼容 Provider 会返回 400,典型报错:

Invalid parameter: messages with role 'tool' must be a response to a
preceding message with 'tool_calls'.

或(部分严格实现):

Duplicate tool_call id 'search' in messages[...]

触发条件很窄但很常见:历史里存在被上下文截断/压缩过的工具调用轮次,
或者某些旧前端/适配器把 tool_call.id 复用了(同一个 id 在多轮里重复出现)。

根因

astrbot/core/provider/sources/openai_source.py:453 的
_sanitize_assistant_messages() 只做了两件事:过滤全空的 assistant 消息,
以及丢掉「找不到对应 assistant 的 tool 消息」。它有两个漏洞:

  1. 只按单轮收集 id。 原实现(openai_source.py:499-513)每遇到一条 assistant
    就把 pending_tool_call_ids 整个覆盖:

    pending_tool_call_ids: set[str] = set()
    ...
    if role == "assistant" and msg.get("tool_calls"):
        pending_tool_call_ids = {
            tc["id"] for tc in msg["tool_calls"]
            if isinstance(tc, dict) and "id" in tc
        }

    于是两轮都用 "search" 作为 id 时,第二条 tool 消息会被匹配到第二轮那个
    call 上,而第一轮的 call 变成永远无人应答 —— 一旦某轮被截断留下半个轮次,
    就会拼出一个非法序列。

  2. 从不检查「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 里已有的取值:

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 or call_id in used_tool_call_ids:
        suffix += 1
        call_id = f"call_astrbot_{msg_index}_{suffix}"
    tc["id"] = call_id

对应 tool 消息在匹配时同步改写 msg["tool_call_id"],因此配对关系保持不变。

(b) 同一批内重复 id 直接省略。 一条 assistant 里两个 call 用了同一个 id 时,
无法可靠判断哪条结果是哪一个,这种情况下把该 id 的 call 连同其结果一起从本次请求
中省略,不改动已保存的会话内容:

counts = Counter(tc["id"] for tc in tool_calls if isinstance(tc, dict) and "id" in tc)
ambiguous_ids = {call_id for call_id, count in counts.items() if count > 1}

省略后若该 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_calls
  • test_sanitize_assistant_messages_omits_empty_ambiguous_batch
  • test_sanitize_assistant_messages_does_not_match_results_across_removed_batch
  • test_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 上运行:

python -m pytest tests/test_openai_source.py -q
5 failed, 65 passed, 1 warning in 7.25s
FAILED tests/test_openai_source.py::test_sanitize_assistant_messages_renames_reused_ids_across_rounds
FAILED tests/test_openai_source.py::test_sanitize_assistant_messages_keeps_only_resolved_unambiguous_calls
FAILED tests/test_openai_source.py::test_sanitize_assistant_messages_omits_empty_ambiguous_batch
FAILED tests/test_openai_source.py::test_sanitize_assistant_messages_does_not_match_results_across_removed_batch
FAILED tests/test_openai_source.py::test_sanitize_assistant_messages_resets_tool_ids_after_non_tool_message

应用本 PR 后,在同一 master 之上:

python -m pytest tests/test_openai_source.py -q
70 passed, 1 warning in 5.52s

风险

  • 中等偏低。改动集中在请求发送前的单条清洗函数,不触碰 Provider 调用、流式解析或
    会话持久化。
  • 改名会改动发给模型的 id。 模型只把 id 当作不透明标记,改名不影响语义;
    但如果外部日志分析依赖原始 id,会看到 call_astrbot_*。
  • 省略而非修复。 同批内重复 id 与无人应答的 call 被从请求里去掉,
    模型因此看不到那部分工具交互。这是刻意的取舍:保留它们会被严格实现整体拒绝,
    上下文全丢。原始会话数据不受影响。
  • 幂等性有测试保障(重复调用 _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:

  • Sanitize legacy tool-call histories across OpenAI Chat Completions and Responses providers to prevent invalid requests from orphaned, unanswered, malformed, or reused tool-call IDs.

Enhancements:

  • Normalize tool-call IDs and preserve valid call/result pairings while omitting ambiguous or incomplete interactions without modifying persisted conversation history.

Tests:

  • Add coverage for reused, ambiguous, malformed, orphaned, delayed, and unanswered tool-call histories, including Responses API payload preparation and sanitization idempotence.

@sourcery-ai sourcery-ai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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


Sourcery is free for open source - if you like our reviews please consider sharing them ✨

Comment thread tests/test_openai_source.py Resolved
@codecov-commenter

codecov-commenter commented Nov 17, 2026 •

Copy link
Copy Markdown

⚠️ Please install the 'codecov app svg image' to ensure uploads and comments are reliably processed by Codecov.

Codecov Report

❌ Patch coverage is 93.67089% with 5 lines in your changes missing coverage. Please review.

Files with missing lines Patch % Lines
astrbot/core/provider/sources/openai_source.py 93.42% 5 Missing ⚠️

📢 Thoughts on this report? Let us know!

@sourcery-ai sourcery-ai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Sourcery assessment

Approved.

@JosephTian876 JosephTian876 changed the title 修复历史工具调用记录导致的 400:重复 call id 与无人应答的 call fix(provider): sanitize legacy tool-call history across OpenAI providers Nov 21, 2026
@JosephTian876

Copy link
Copy Markdown
Contributor Author

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
uff check,
uff format --check, \pytest tests/test_openai_source.py\ (74 passed), and \pytest tests/test_openai_responses_source.py.

@JosephTian876
JosephTian876 force-pushed the fix/legacy-tool-call-history-20261117 branch from c4e11ed to e619ae4 Compare November 27, 2026 02:20

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants