@@ -2354,20 +2354,41 @@ def _build_api_kwargs(self, api_messages: list) -> dict:
23542354
23552355 return kwargs
23562356
2357- sanitized_messages = copy .deepcopy (api_messages )
2358- for msg in sanitized_messages :
2357+ sanitized_messages = api_messages
2358+ needs_sanitization = False
2359+ for msg in api_messages :
23592360 if not isinstance (msg , dict ):
23602361 continue
2361-
2362- # Codex-only replay state must not leak into strict chat-completions APIs.
2363- msg . pop ( "codex_reasoning_items" , None )
2362+ if "codex_reasoning_items" in msg :
2363+ needs_sanitization = True
2364+ break
23642365
23652366 tool_calls = msg .get ("tool_calls" )
23662367 if isinstance (tool_calls , list ):
23672368 for tool_call in tool_calls :
2368- if isinstance (tool_call , dict ):
2369- tool_call .pop ("call_id" , None )
2370- tool_call .pop ("response_item_id" , None )
2369+ if not isinstance (tool_call , dict ):
2370+ continue
2371+ if "call_id" in tool_call or "response_item_id" in tool_call :
2372+ needs_sanitization = True
2373+ break
2374+ if needs_sanitization :
2375+ break
2376+
2377+ if needs_sanitization :
2378+ sanitized_messages = copy .deepcopy (api_messages )
2379+ for msg in sanitized_messages :
2380+ if not isinstance (msg , dict ):
2381+ continue
2382+
2383+ # Codex-only replay state must not leak into strict chat-completions APIs.
2384+ msg .pop ("codex_reasoning_items" , None )
2385+
2386+ tool_calls = msg .get ("tool_calls" )
2387+ if isinstance (tool_calls , list ):
2388+ for tool_call in tool_calls :
2389+ if isinstance (tool_call , dict ):
2390+ tool_call .pop ("call_id" , None )
2391+ tool_call .pop ("response_item_id" , None )
23712392
23722393 provider_preferences = {}
23732394 if self .providers_allowed :
0 commit comments