Skip to content

Commit 1be449f

Browse files
committed
fix(provider): harden tool-call sanitization and apply to Responses API
1 parent a301d7c commit 1be449f

4 files changed

Lines changed: 292 additions & 37 deletions

File tree

‎astrbot/core/provider/sources/openai_responses_source.py‎

Lines changed: 7 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -63,15 +63,20 @@ def _convert_chat_messages_to_response_input(
6363
) -> list[dict]:
6464
"""Convert AstrBot's OpenAI chat history to Responses input items.
6565
66-
The conversion preserves function call IDs and serialized reasoning output
67-
items so the complete history can be replayed without server-side state.
66+
The conversion sanitizes legacy tool-call history and preserves valid
67+
function call IDs and serialized reasoning output items so the complete
68+
history can be replayed without server-side state.
6869
6970
Args:
7071
messages: AstrBot context in OpenAI Chat Completions format.
7172
7273
Returns:
7374
A list of Responses API input items.
7475
"""
76+
sanitized_payload: dict[str, Any] = {"messages": copy.deepcopy(messages)}
77+
self._sanitize_assistant_messages(sanitized_payload)
78+
messages = sanitized_payload["messages"]
79+
7580
response_input: list[dict] = []
7681
host = (self.client.base_url.host or "").rstrip(".").lower()
7782
is_deepseek = (

‎astrbot/core/provider/sources/openai_source.py‎

Lines changed: 80 additions & 35 deletions
Original file line numberDiff line numberDiff line change
@@ -464,7 +464,31 @@ def _sanitize_assistant_messages(payloads: dict) -> None:
464464
def _is_empty(content: Any) -> bool:
465465
return content is None or content == "" or content == []
466466

467+
# Reserve every existing tool-call ID and tool-message ID upfront so
468+
# generated replacement IDs can never collide with an orphan or later
469+
# tool message.
470+
reserved_tool_call_ids: set[str] = set()
471+
for msg in messages:
472+
if not isinstance(msg, dict):
473+
continue
474+
role = msg.get("role")
475+
if role == "assistant":
476+
raw_tool_calls = msg.get("tool_calls")
477+
if isinstance(raw_tool_calls, list):
478+
for tc in raw_tool_calls:
479+
if (
480+
isinstance(tc, dict)
481+
and isinstance(tc.get("id"), str)
482+
and tc["id"]
483+
):
484+
reserved_tool_call_ids.add(tc["id"])
485+
elif role == "tool":
486+
tool_call_id = msg.get("tool_call_id")
487+
if isinstance(tool_call_id, str) and tool_call_id:
488+
reserved_tool_call_ids.add(tool_call_id)
489+
467490
removed_assistant = object()
491+
ambiguous_ids_by_cleaned_index: dict[int, set[str]] = {}
468492
cleaned: list[Any] = []
469493
for idx, msg in enumerate(messages):
470494
if not isinstance(msg, dict) or msg.get("role") != "assistant":
@@ -476,58 +500,65 @@ def _is_empty(content: Any) -> bool:
476500
reasoning_content = msg.get("reasoning_content")
477501

478502
if tool_calls:
479-
counts = Counter(
480-
tc["id"] for tc in tool_calls if isinstance(tc, dict) and "id" in tc
481-
)
482-
ambiguous_ids = {
483-
call_id for call_id, count in counts.items() if count > 1
484-
}
485-
if ambiguous_ids:
486-
# A repeated ID in the same batch cannot be reliably matched
487-
# to its result. Omit those calls and their results from this
488-
# request without changing the saved conversation.
489-
tool_calls = [
503+
if not isinstance(tool_calls, list):
504+
tool_calls = None
505+
msg.pop("tool_calls", None)
506+
else:
507+
# Drop malformed tool-call entries (non-dict or missing/empty
508+
# string ID) so invalid items never reach strict providers.
509+
valid_tool_calls = [
490510
tc
491511
for tc in tool_calls
492-
if not isinstance(tc, dict) or tc.get("id") not in ambiguous_ids
512+
if isinstance(tc, dict)
513+
and isinstance(tc.get("id"), str)
514+
and tc["id"]
493515
]
494-
if tool_calls:
516+
counts = Counter(tc["id"] for tc in valid_tool_calls)
517+
ambiguous_ids = {
518+
call_id for call_id, count in counts.items() if count > 1
519+
}
520+
if ambiguous_ids:
521+
# A repeated ID in the same batch cannot be reliably matched
522+
# to its result. Omit those calls and their results from this
523+
# request without changing the saved conversation.
524+
ambiguous_ids_by_cleaned_index[len(cleaned)] = ambiguous_ids
525+
valid_tool_calls = [
526+
tc
527+
for tc in valid_tool_calls
528+
if tc["id"] not in ambiguous_ids
529+
]
530+
if valid_tool_calls:
531+
tool_calls = valid_tool_calls
495532
msg["tool_calls"] = tool_calls
496533
else:
534+
tool_calls = None
497535
msg.pop("tool_calls", None)
498536

499537
if _is_empty(content) and not tool_calls:
500538
if not reasoning_content:
501-
# 三者全空,真正的垃圾消息,丢弃
539+
# Drop assistant messages without content, tool_calls, or reasoning.
502540
logger.debug(
503-
f"过滤第 {idx} 条空 assistant 消息 (无 content | tool_calls | reasoning_content)"
541+
f"Filtered empty assistant message at index {idx} (no content, tool_calls, or reasoning_content)"
504542
)
505543
# Keep a boundary so a later tool result cannot be matched
506544
# to a call preceding this removed assistant message.
507545
cleaned.append(removed_assistant)
508546
continue
509547
else:
510-
# ⭐ 有 reasoning_content 但没有 content 和 tool_calls
511-
# 不能丢(推理模型需要 reasoning 历史)
512-
# 但 API 要求 content 或 tool_calls 至少有一个
513-
# → 设空字符串占位,满足校验
548+
# Preserve reasoning-only assistant messages with an empty string
549+
# placeholder to satisfy API schema validation.
514550
msg["content"] = ""
515551

516552
elif _is_empty(content) and tool_calls:
517-
msg["content"] = None # 有 tool_calls,按 OpenAI 规范
553+
msg["content"] = None
518554

519555
cleaned.append(msg)
520556

521557
# Drop orphaned or duplicate tool messages whose assistant(tool_calls)
522-
# was removed by context truncation / compression.
523-
reserved_tool_call_ids = {
524-
tc["id"]
525-
for msg in cleaned
526-
if isinstance(msg, dict) and msg.get("role") == "assistant"
527-
for tc in msg.get("tool_calls") or []
528-
if isinstance(tc, dict) and "id" in tc
529-
}
558+
# was removed by context truncation / compression, and drop unanswered
559+
# tool calls along with delayed results from earlier unanswered rounds.
530560
used_tool_call_ids: set[str] = set()
561+
unresolved_original_ids: set[str] = set()
531562
pending_tool_call_ids: dict[str, str] = {}
532563
pending_assistant = None
533564
final: list = []
@@ -536,21 +567,28 @@ def _is_empty(content: Any) -> bool:
536567
role = msg.get("role") if isinstance(msg, dict) else None
537568
if role != "tool" and pending_tool_call_ids:
538569
# An assistant tool call requires a corresponding tool result.
539-
# Remove unanswered calls before the next message or end of input.
570+
# Remove unanswered calls before the next message or end of input,
571+
# and mark their original IDs unresolved so a delayed result cannot
572+
# attach to a later call reusing the same original ID.
573+
unresolved_original_ids.update(pending_tool_call_ids.keys())
540574
unanswered_ids = set(pending_tool_call_ids.values())
541575
pending_assistant["tool_calls"] = [
542576
tc
543577
for tc in pending_assistant["tool_calls"]
544-
if not isinstance(tc, dict) or tc.get("id") not in unanswered_ids
578+
if tc["id"] not in unanswered_ids
545579
]
546580
if not pending_assistant["tool_calls"]:
547581
pending_assistant.pop("tool_calls")
548582
if _is_empty(pending_assistant.get("content")):
549583
if pending_assistant.get("reasoning_content"):
550584
pending_assistant["content"] = ""
551-
else:
585+
elif final and final[-1] is pending_assistant:
552586
final.pop()
553587
pending_tool_call_ids = {}
588+
if msg_index in ambiguous_ids_by_cleaned_index:
589+
unresolved_original_ids.update(
590+
ambiguous_ids_by_cleaned_index[msg_index]
591+
)
554592
if msg is removed_assistant:
555593
continue
556594
if not isinstance(msg, dict):
@@ -561,11 +599,12 @@ def _is_empty(content: Any) -> bool:
561599
pending_assistant = msg
562600
pending_tool_call_ids = {}
563601
for tc in msg["tool_calls"]:
564-
if not isinstance(tc, dict) or "id" not in tc:
565-
continue
566602
original_id = tc["id"]
567603
call_id = original_id
568-
if call_id in used_tool_call_ids:
604+
if (
605+
call_id in used_tool_call_ids
606+
or call_id in unresolved_original_ids
607+
):
569608
suffix = 0
570609
call_id = f"call_astrbot_{msg_index}_{suffix}"
571610
while (
@@ -576,7 +615,13 @@ def _is_empty(content: Any) -> bool:
576615
call_id = f"call_astrbot_{msg_index}_{suffix}"
577616
tc["id"] = call_id
578617
used_tool_call_ids.add(call_id)
579-
pending_tool_call_ids[original_id] = call_id
618+
if original_id in unresolved_original_ids:
619+
# An earlier call with this original ID went unanswered or
620+
# was omitted as ambiguous, so a raw tool message carrying
621+
# original_id may be a delayed result from that earlier round.
622+
pending_tool_call_ids[call_id] = call_id
623+
else:
624+
pending_tool_call_ids[original_id] = call_id
580625
final.append(msg)
581626
elif role == "tool":
582627
tool_call_id = msg.get("tool_call_id")

‎tests/test_openai_responses_source.py‎

Lines changed: 62 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -397,3 +397,65 @@ async def test_parse_failed_response_raises_provider_error():
397397

398398
with pytest.raises(RuntimeError, match="server_error: failed"):
399399
await provider._parse_response(response, tools=None)
400+
401+
402+
@pytest.mark.asyncio
403+
async def test_prepare_payload_sanitizes_legacy_tool_call_history():
404+
provider = _make_provider()
405+
contexts = [
406+
{"role": "user", "content": "turn 1"},
407+
{
408+
"role": "assistant",
409+
"content": None,
410+
"tool_calls": [
411+
{
412+
"id": "search",
413+
"type": "function",
414+
"function": {"name": "search", "arguments": '{"q":"a"}'},
415+
}
416+
],
417+
},
418+
{"role": "tool", "tool_call_id": "search", "content": "first"},
419+
{
420+
"role": "assistant",
421+
"content": None,
422+
"tool_calls": [
423+
"malformed",
424+
{
425+
"id": "unanswered",
426+
"type": "function",
427+
"function": {"name": "skip", "arguments": "{}"},
428+
},
429+
{
430+
"id": "search",
431+
"type": "function",
432+
"function": {"name": "search", "arguments": '{"q":"b"}'},
433+
},
434+
],
435+
},
436+
{"role": "tool", "tool_call_id": "search", "content": "second"},
437+
{"role": "tool", "tool_call_id": "orphan_call", "content": "stale"},
438+
]
439+
440+
payloads, _ = await provider._prepare_chat_payload(
441+
prompt="follow up",
442+
contexts=contexts,
443+
)
444+
445+
function_calls = [
446+
item for item in payloads["input"] if item.get("type") == "function_call"
447+
]
448+
function_outputs = [
449+
item for item in payloads["input"] if item.get("type") == "function_call_output"
450+
]
451+
assert len(function_calls) == 2
452+
assert len(function_outputs) == 2
453+
assert function_calls[0]["call_id"] == "search"
454+
assert function_calls[1]["call_id"] != "search"
455+
assert [item["call_id"] for item in function_outputs] == [
456+
function_calls[0]["call_id"],
457+
function_calls[1]["call_id"],
458+
]
459+
assert [item["output"] for item in function_outputs] == ["first", "second"]
460+
# Caller-owned context list must remain untouched.
461+
assert contexts[3]["tool_calls"][2]["id"] == "search"

0 commit comments

Comments
 (0)