@@ -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" )
0 commit comments