Repository navigation
fix(responses): translate OpenAI tool_search to Anthropic tool search for Claude models - #45882
Conversation
… for Claude models
|
I'll fix CI failures and address comments from users with write access. I'll skip comments containing "(aside)".
|
Merging this PR will not alter performance
|
Codecov Report❌ Patch coverage is 📢 Thoughts on this report? Let us know! |
… validate deferred tool fields Bedrock Converse builds its own request and has no tool search, so the bridge now drops the tool_search tool there with a warning instead of sending a tool the transport loses, while Bedrock invoke, Anthropic, and Vertex keep it. A replayed tool_search_call with no stored result is dropped from the Anthropic request so a previous_response_id follow-up no longer answers 400. Only srvtoolu_ ids whose name is one of Anthropic's search tools count as search calls, so a caller function named like one stays a function call. A non-boolean defer_loading or a non-list allowed_callers now answers 400 instead of 500
… undeferred when no search tool goes out A replayed Claude tool search call that the caller answered with a tool message kept its tool_result in the user turn while its tool_use was dropped from the assistant turn, so Anthropic answered 400 on the OpenAI-SDK tool loop. The search call is now dropped only when no tool message answers it. The Responses bridge now strips defer_loading from every tool whenever no tool search tool is sent, whether the caller sent none or the route cannot run it, since a deferred tool with no search tool can never be loaded. Namespace members had started carrying the flag to every bridge provider, which providers that reject unknown tool keys answered 422. The audit round-1 integration cells for the bridge wire and chaos paths ride in this commit.
| assistant_tool_calls, | ||
| web_search_results=_web_search_results_tc, | ||
| tool_results=_tool_results_tc, | ||
| answered_tool_ids=answered_tool_call_ids(messages, msg_i), |
There was a problem hiding this comment.
🟡 Tool-heavy histories incur quadratic copies
For each assistant turn with tool calls, answered_tool_call_ids copies the remaining message history. A history with many tool turns therefore allocates quadratically while formatting one request
Learn more
The Anthropic formatter walks every assistant turn in a conversation. Each call slices messages[assistant_index:] in answered_tool_call_ids. List slicing copies the entire suffix before dropwhile and takewhile stop at the nearby tool results. When many assistant turns contain tool calls, total copied elements grow quadratically, even if there are no search calls.
Example: In an illustrative history of 1,000 assistant/tool exchanges, calls near the start copy almost 2,000 messages each. Calls near the end copy fewer, totaling roughly one million copied references for one request instead of a local scan per exchange
Recommended fix: Make answered_tool_call_ids iterate with itertools.islice(messages, assistant_index, None) or integer indexing from assistant_index. Stop after the immediately following run of tool results, without slicing the rest of the history
Was this helpful? React with 👍 or 👎 to provide feedback.
There was a problem hiding this comment.
The helper now walks lazily, skipping the assistant run and reading only the tool answers right after it, so each turn costs its own length
…e Anthropic search tools intact A native tool_search_tool_regex_20251119 or tool_search_tool_bm25_20251119 tool the caller sends through /v1/responses passes through the bridge on every route as before, and the other tools keep defer_loading whenever any Anthropic search tool goes out. The route gate now drops the OpenAI tool_search item before translation instead of filtering the translated regex tool, so bm25 counts as a search tool. answered_tool_call_ids walks the history with islice instead of a slice copy. The tool_search_call output item drops its created_by field, which OpenAI rejects on a replayed input item and the streaming item never carried
…l_search_anthropic # Conflicts: # tests/unit/responses/litellm_completion_transformation/test_litellm_completion_responses.py
|
@litereview code-review |
✅ code-review5/5 · Ready for human reviewScope: full · Full PR review. Completed · Some checks not run. No correctness findings. Checks and execution details
The new integration files in The manual E2E evidence does satisfy it:
View review · Reviewed |
…stored search calls off non-Anthropic follow-ups With drop_params on, a non-boolean defer_loading or a non-list allowed_callers on a Responses API tool (or a namespace member) is dropped before the bridge instead of answering 400, so only a request without drop_params gets the 400. A custom tool now carries defer_loading to the chat tool like a function tool does A previous_response_id follow-up routed to a provider that does not build an Anthropic request no longer replays the stored Claude search call (srvtoolu_ id) as a client tool call. Mistral answered that history 400 "Unexpected tool call id". An assistant turn that held only the search call is dropped there. The Anthropic route keeps the call, since its factory pairs it with the stored result The tool_search_call output model is renamed OutputToolSearchCall so the proxy's OpenAPI schema keeps the OpenAI SDK's ResponseToolSearchCall name. answered_tool_call_ids reads the history by index, so the lookup is linear in the history length. The streaming done event reads the response it is given, which is the same object it used to read from the iterator
|
@litereview code-review |
|
@litereview code-review |
PR overviewAll previously flagged issues have been addressed. No open security concerns remain on this pull request. Security reviewNo open security issues remain on this pull request. Fixed/addressed: 3 · PR risk: 0/10 |
…ol, and keep replays clean off Anthropic A function tool whose allowed_callers is not a list of strings now answers 400 instead of 500. The guardrail scan reads tools without malformed flags, so the route decides between a 400 and a drop under drop_params. When the caller sends a native Anthropic search tool beside tool_search, only the native one goes out. Databricks Claude no longer counts as an Anthropic request route. A previous_response_id follow-up off Anthropic also drops a search call the client replayed as a function_call with a srvtoolu_ id, and its output. The answered tool id scan in the Anthropic message factory runs once per assistant run instead of once per message. A null created_by on tool_search_call and tool_search_output output items is left out of the serialized response, so a cache hit returns the same keys as the first call.
|
@litereview code-review |
|
bugbot run |
…l_search_anthropic # Conflicts: # litellm/llms/anthropic/chat/transformation.py
|
@litereview code-review |
…il tool scan The scan translated tool_search into Anthropic's regex search tool on every route, so a guardrail returning only function tools removed tool_search from native OpenAI requests and OpenAI answered 400 for the deferred tools
…l_search_anthropic
|
@litereview code-review |
|
@litellm-stampbot |
litellm-stampbot: risk highNot approved at Rules (
Judge: skipped, the rules alone decided. Pushes do not re-run this check. Comment |
|
Automatic reviews are disabled for this repository. |
…rse with cache marks
|
bugbot run |
|
@litereview code-review |
|
@litereview code-review |
1 similar comment
|
@litereview code-review |
|
bugbot run |
There was a problem hiding this comment.
✅ Bugbot reviewed your changes and found no new issues!
Comment @cursor review or bugbot run to trigger another review on this PR
Reviewed by Cursor Bugbot for commit 86ed5be. Configure here.
…45882 landed Co-Authored-By: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com>
…landed Co-Authored-By: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com>
…er a system message after the search turn The malformed kept result cells now expect the unanswered search call to be dropped, as main does since #45882. The stream cut cell checks streamed tool call names, since the kept search result names get_weather as a tool reference. The streamed response cache hit cell runs again because #46104 fixed it. The modify_params cap cell expects the four client marks, since the placeholder answer sends the search call as a plain tool_use with its mark, and a new cell covers a system message after the trailing search turn in both stream modes
…y modify_params sends it (#46591) * fix(anthropic): count a replayed server tool call's cache mark the way modify_params sends it With modify_params on, a trailing tool search turn whose call has a kept result got a placeholder answer from the factory and went out as a marked tool_use, but the cache control hook counted marks before that placeholder existed and skipped the mark, so a request at the cap reached Anthropic with 5 marks and failed with a 400. The hook now finds client answers on the sanitized messages, the same list the factory reads. Also make the replay checks cheaper (prefix check before validation, early return without provider_specific_fields, and look up client answers only when a tool call carries cache_control), drop the two audit cells that cover old gaps outside the tool search fix, and derive the pass-through test timeout from the graceful stop budget. * fix(anthropic): keep the duplicate tool result warning out of the cache control hook The hook finds client answers with only the step of the modify_params sanitize pass that pairs tool calls with their results, so a request with a duplicate tool result logs the warning once again instead of once per mark count. Also restore the Snowflake non-stream and cached-stream tool search cells as known bugs with pytest.skip instead of deleting them, and put the Anthropic pass-through test timeout back to 240 seconds. * fix(anthropic): count cache marks next to a message the pairing step cannot read With modify_params on and a marked tool call, the cache control hook paired tool calls with their results before counting. A message without a get method (a stray string or null in extra_body.messages, or an openai SDK ChatCompletionMessage) made that pairing raise AttributeError before any provider call, where main counted the marks and let the request through. The hook now pairs only when every message can be read the way the pairing step reads it, and otherwise counts on the messages as sent, like main did. * fix(anthropic): count cache marks after placing a later system message the way the request builder does * test(anthropic): cover a leading system prompt and a system message before the answer in the cache mark census * test(anthropic): align the tool search replay cells with main and cover a system message after the search turn The malformed kept result cells now expect the unanswered search call to be dropped, as main does since #45882. The stream cut cell checks streamed tool call names, since the kept search result names get_weather as a tool reference. The streamed response cache hit cell runs again because #46104 fixed it. The modify_params cap cell expects the four client marks, since the placeholder answer sends the search call as a plain tool_use with its mark, and a new cell covers a system message after the trailing search turn in both stream modes * fix(anthropic): count marks on the raw messages when they cannot be placed, and find client answers once per request * test(anthropic): cover marked tool calls next to a malformed tool id and a later system message * perf(anthropic): look up client tool answers only when a marked tool call is a server tool call Answered ids only decide whether a marked srvtoolu_ call is rebuilt as server_tool_use, so a request whose marked tool calls are all client calls no longer places system messages or runs the modify_params pairing step to count marks * test(anthropic): reach the client answer lookup with a marked search call in the malformed tool id cell * perf(anthropic): place mid-conversation system messages in linear time for models that keep them * fix(anthropic): count cache marks with the model's own system message placement and pair tool results in linear time * test(anthropic): cover modify_params dropping a tool answer that answers no call of the latest assistant turn * fix(anthropic): count marks with in-place system placement when the model lookup cannot confirm the flag * test(anthropic): cover a bare model with custom_llm_provider filling the cache mark budget through litellm.completion and Router * fix(anthropic): give unmapped models the request builder's converting placement and survive any model lookup failure * test(anthropic): cover an unmapped model name counting cache marks with the request builder's converting placement * fix(anthropic): count server tool call cache marks the request builder's way only on routes that build Anthropic Messages requests Databricks, OpenRouter and Bedrock Converse send every marked tool call as is, so the hook keeps the census main uses there. The seeding step carries custom_llm_provider on the injection points when a server tool call is marked, so a bare model name still resolves its route. * test(anthropic): cover two answered marked server tool calls before a system message on Databricks, OpenRouter and Bedrock Converse * fix(anthropic): keep main's cache mark count on GitHub Copilot and ChatGPT routes without resolving them, so a sync call with no stored login never starts the device flow * test(anthropic): cover a marked server tool call reaching the GitHub Copilot and ChatGPT login hosts like an unmarked one
TLDR
Problem this solves:
/v1/responsesdropped OpenAI'stool_searchtool on Claude modelsHow it solves it:
tool_searchtool becomes Anthropic's regex tool search tooltool_search_callitem, streaming toodefer_loadingflagdefer_loadingas sent when no server search tool is sentdefer_loading,allowed_callers, orexecutionanswers 400, or drops underdrop_paramssrvtoolu_search call instead of 400created_by, so replays to OpenAI worktool_search_call's argumentsUser Flow
Before: a developer sends OpenAI's tool search shape to a Claude model and gets a 400 back from Anthropic
"model": "claude-sonnet-5-5", a{"type": "tool_search"}tool, and three function tools with"defer_loading": trueAt least one tool must have defer_loading=false. All tools cannot be deferred.tool_search_call, and a message saying there is no weather toolclaude-sonnet-5-5fails, and the fallback fails withAll tools cannot be deferred.await litellm.Router(...).aresponses(model="gpt-primary", ...)with the step 1 tools, wheregpt-primaryis an OpenAI deployment that falls back toanthropic/claude-sonnet-5-5, and getlitellm.AuthenticationErrorsaying the fallback to Claude also failed withlitellm.BadRequestErrorAfter: the same request reaches Claude with its tool search tool, and the output carries the search call and the function call
"model": "claude-sonnet-5-5", a{"type": "tool_search"}tool, and three function tools with"defer_loading": truetool_search_callitem, then afunction_callforget_weatherwith{"city": "Paris"}, streamed in the same order with"stream": trueget_weatherwithprevious_response_idand afunction_call_output, to Claude or togemini-flash, and get HTTP 200 using the resultclaude-sonnet-5-5answers HTTP 200 with thetool_search_calland theget_weathercallawait litellm.Router(...).aresponses(model="gpt-primary", ...)with the step 1 tools, wheregpt-primaryis an OpenAI deployment that falls back toanthropic/claude-sonnet-5-5, and get thetool_search_calland theget_weathercall from Claude, streamed in the same order withstream=TrueLinear ticket
Resolves LIT-9579
Decisions
tool_searchbecomes Anthropic's regex tool (tool_search_tool_regex_20251119), not bm25. The regex tool is what Anthropic documents first and what the native control call used. A bm25 tool the caller sends natively is recognized as a search tool and passed throughsupports_tool_searchflag through a newlitellm.supports_tool_search(model, custom_llm_provider). Models without it keep today's drop plus warning, so a provider that would reject the tool is never sent ittool_searchtool with noexecutioncounts as server execution. Client execution ("execution": "client") is out of scope and stays dropped as beforetool_search_callitem'scall_idis Anthropic'ssrvtoolu_id, and itsidistsc_plus that id, the same shape asfc_function call idstool_search_outputitem is synthesized. OpenAI fills it with the full tool definitions, which the caller already hastool_search_callandtool_search_outputinput items are left out of the Anthropic request, like the stored search call in the next bullet. On a follow-up turn Claude sees the tool calls and results that came after the search but not the search itself, so its answer can say it called a tool without searching first (case 10). Replaying the search with its result was the alternative, tested live on claude-sonnet-5-5, where Anthropic answers 400Tool reference 'get_weather' not found in available toolsonce a later turn drops a loaded tool or sends no tools. Replaying it safely needs atool_search_outputitem the bridge does not emit yet, so it is a follow-uptool_search_callwith"status": "incomplete"and empty arguments instead of an errortool_search_callstatus is alwayscompleted, since the chat tool call carries no statusprovider_builds_anthropic_request): Bedrock Converse builds its own request and has no tool search, so the bridge drops the tool there with a warning, while Bedrock invoke, Anthropic, and Vertex keep itclaude-tool-searchrule fillssupports_tool_searchfor anthropic, azure_ai, bedrock, bedrock_converse, and vertex_ai, since Microsoft Foundry runs Anthropic's tool search for Claude (Foundry blog, 2026-08-17). Case 27 sends case 1 toazure_ai/claude-sonnet-4-6tool_search_callwhose result was not stored (aprevious_response_idfollow-up) is dropped from the Anthropic request instead of echoed back, since Anthropic answers 400 to a server tool use with no resultsrvtoolu_and its name is one of Anthropic's search tools, so a caller's own function namedtool_search_tool_regexstays afunction_calldefer_loadingthat is not a boolean, or anallowed_callersthat is not a list of strings, answers 400 (litellm.BadRequestError) on every bridge route the way OpenAI's own validation does (invalid_type, checked live 2026-10-12), instead of the 500 the bridge answered before. Withdrop_paramson, the malformed flag is dropped from that tool and the request goes through, the way litellm drops other unsupported values (case 9b). Atool_searchexecutionother than"server"or"client"gets the same treatment where the route runs the search, sodrop_paramsleaves a server search, matching OpenAI's 400invalid_value(checked live 2026-10-14, case 34). A route that cannot run tool search drops the whole tool first, as the base doestool_search_calloutput item is litellm's own model (litellm.types.responses.main.OutputToolSearchCall) with the OpenAI SDK's field set, since openai 2.20.0, the lowest SDK litellm supports, has no such class. Its name differs from the SDK'sResponseToolSearchCallso the OpenAPI schema never has two components under one namesrvtoolu_detection lives in the shared chat factory, so/v1/chat/completionsalso drops a replayed search call that notoolmessage answers, while one the caller answered the OpenAI-SDK way (atoolmessage pertool_callsentry) stays paired with itstool_result. Before, a two-turn chat replay answered 400tool_use ids were found without tool_result blocks. Dropping the answered pair too was tried at c3c38ba and reverted, since Claude then said it calledget_weatherwithout searching in 4 of 6 runs, while with the kept pair it never said so in 6 of 6 runs on either leg (case 28). A turn holding only the search could not be dropped anyway, since Anthropic answers 400This model does not support assistant message prefillto a conversation that ends on an assistant turntool_search_callthe way they scan a function call. The guardrail sees a call namedtool_searchwith the search arguments as JSON text, and its rewrite goes back as a JSON object on a copy of the item. A stream is rewritten only through a guardrail policy pipeline, so a plain post-call guardrail leaves a streamedtool_search_callalone, as it leaves a streamedfunction_callon the base (case 31). The pipeline finds OpenAI's own streamedtool_search_call, whosecall_idis null, by its itemid(case 33). A rewrite that is not a JSON object goes out as{}with"status": "incomplete", so the original arguments never go out after a guardrail changed them. This also covers OpenAI's owntool_search_callon native routes, which the base never scanned. The base returned Anthropic's native search as a scannedfunction_call, so skippingtool_search_callwould let a search pattern past a post-call filter (case 31)tool_search(none at all, or only"execution": "client"), a Claude route gets every tool'sdefer_loadingas sent, as on the base (cases 32a, 32c, 32d). OpenAI's own API answers 400Deferred tools require tools.tool_search.to the same request (case 32b). The flag is stripped only when the bridge drops a servertool_searchthe route cannot run, or on a route with no deferral (Gemini, Bedrock Converse, Mistral), where a deferred tool could never load and Mistral answered 422 to the flag (case 32e). 333a5e8 stripped it on Claude routes too, which loaded every deferred tool up front where the base kept them hiddentool_search_callinput item whose id is not atsc_id is replayed to OpenAI's native Responses API without that id, the same treatmentfunction_callitems with a foreignfc_id get. A bridge-mintedtsc_srvtoolu_id keeps the genuine prefix and goes out as is, which case 13 exercises/v1/messagesrequest whose guardrail rewrites the history (structured_messages) now reaches Anthropic without an assistantsrvtoolu_block the caller never answered, so it answers 200 where Anthropic answered 400 to that unanswerable blockdefer_loading,allowed_callers, orexecution) fail before routing, so their spend rows carry the public model alias like the existing unknown-model rows, not the deployment nametool_search_callandtool_search_outputitems never carry a nullcreated_by, on any route. The response serializer drops the key when it is null, as it does for null reasoning fields, so a response-cache hit (rebuilt through the SDK's class) and OpenAI's own items match a fresh bridge answer. OpenAI answers 400Unknown parameter: 'input[2].created_by'when an item with it is replayed, which the proxy's own gpt-5.5 items hit before this PR (case 23). Ordering the output union so litellm's model wins was the alternative, but list invariance carried that type change into two other modulestool_search_tool_regex_20251119ortool_search_tool_bm25_20251119) is not the bridge's to gate: it passes through on every route as it did before this PR, and the other tools keepdefer_loadingwhenever any Anthropic search tool goes out. Only the OpenAItool_searchshape is dropped on a route that cannot run it, and that happens before translationprevious_response_idfollow-up routed to a model whose route does not build an Anthropic request (Gemini, Mistral, OpenAI-compatible providers) gets the stored history without the Claude search call (srvtoolu_id), and an assistant turn that held only that call is dropped, since Mistral answers 400Unexpected tool call idto it. The Anthropic route keeps it for the chat factory to pair or drop"type": "custom") carries itsdefer_loadingto the chat tool the way a function tool does, so a deferred custom tool is loaded through the search tool tootool_searchtogether, only the native tool goes out. Both would reach Anthropic astool_search_tool_regex, and Anthropic answers 400tools: Tool names must be unique.(case 18). Two OpenAItool_searchtools get that 400 too, where the base dropped both, and OpenAI answers 400Only one tool_search tool is allowed(checked live 2026-10-14), so the bridge does not merge themdefer_loadingandallowed_callersflags out of the tools it translates for the guardrail to scan, so the guardrail step never raises on a flag the route drops underdrop_paramsor refuses with 400 without it (case 19, 500 before and 200 after)tool_searchtool to the guardrail, the same as before this PR. It carries no caller text, so a guardrail that hands back only function tools keepstool_searchon every routefunction_callwhosecall_idstarts withsrvtoolu_(case 22's turn 2), is left out of the history sent to a route that does not build an Anthropic request, the same as a stored oneprevious_response_idfollow-up the bridge drops the stored Claude search call first and then applies main'scache_controlmarks and cap from fix(responses): propagate cache_control through responses->chat completion bridge #32511, so a dropped message never counts toward the cap. The request'sdrop_params, a named argument here, still reaches that cap (case 36)DatabricksConfigalso extends the OpenAI chat config and sends OpenAI-shaped messages, so the search tool and a stored search call are dropped therePre-Submission checklist
Please complete all items before asking a LiteLLM maintainer to review your PR
uv run pytest tests/unit/<your_test_file>.py -v. Leave the suites (make test-unit-*,make test-unit) to CI: it finishes in ~15 minutes where a laptop takes an hour or moreDelays in PR merge?
If you're seeing a delay in your PR being merged, ping the LiteLLM Team on Slack (#pr-review).
Screenshots / Proof of Fix
Last updated at 86ed5be on 2026-10-15 UTC. Cases 1 to 32 ran at 85bee09, 33 and 34 at 2e331ea, 35 and 36 at e250d78 (the first merge of main), and 37 and 38 at 86ed5be, the merge carrying #46440, whose
factory.pyresolution is the only product diff sinceBoth legs ran on the shared GCE test box as one remote rig, each leg in its own worktree with its own
.venvand a fresh Postgres, and no Redis. Every proxy booted with--num_workers 2 --timeout_worker_healthcheck 60on a random free port, one instance per config, withstore_prompts_in_spend_logs: truesoprevious_response_idworks. The before leg ran the merge base 7fa52b2, and the after leg ran every case again at 85bee09, all on 2026-10-14 UTC. Both legs sent the same cases with real Anthropic, OpenAI, Bedrock, Vertex AI, Gemini, and Mistral credentials (real $$$). Case 19 went to a second proxy on each leg, booted fromconfig_guard.yaml, which is this config plus adefault_onpre-calllitellm_content_filterguardrail andlitellm_settings.drop_params: true. Case 26 went to a third, booted fromconfig_guard2.yaml, which is this config plus thedefault_onpre-call custom guardrail below. Case 25 runs the SDK'sRouter.aresponsesin-process with no proxy.gpt-5.6is the OpenAI control, the newest GPT model in the cost mapreq_claude.json, the request an OpenAI Responses API caller sends today:{ "model": "claude-sonnet-5-5", "input": "What is the weather in Paris right now? Use the right tool.", "tools": [ {"type": "tool_search", "execution": "server"}, {"type": "function", "name": "get_weather", "description": "Get the current weather for a city", "parameters": {"type": "object", "properties": {"city": {"type": "string"}}, "required": ["city"]}, "defer_loading": true}, {"type": "function", "name": "get_stock_price", "description": "Get the current stock price for a ticker", "parameters": {"type": "object", "properties": {"ticker": {"type": "string"}}, "required": ["ticker"]}, "defer_loading": true}, {"type": "function", "name": "send_email", "description": "Send an email to a recipient", "parameters": {"type": "object", "properties": {"to": {"type": "string"}, "body": {"type": "string"}}, "required": ["to", "body"]}, "defer_loading": true} ] }Cases 1 to 26, the same on both legs, with cases 27 to 31 listed further down. Every curl passes
"${H[@]}", set withH=(-H "Authorization: Bearer $LITELLM_MASTER_KEY" -H "Content-Type: application/json"), with-Nfor the streaming cases, and the 200 bodies below are trimmed to theiroutputitemsreq_claude.jsonas above, every function tool deferredreq_claude_v2.json, the same withdefer_loadingremoved fromsend_emailreq_claude_stream.json, case 1 with"stream": truereq_gpt.json, case 1 with"model": "gpt-5.6", the OpenAI passthrough controlclient.responses.create(**case1)non-streaming and withstream=Truereq_bedrock_claude_converse.json, case 1 with"model": "bedrock-claude-converse"req_bedrock_claude_invoke.json, case 1 with"model": "bedrock-claude-invoke"req_fn_named_like_search.json, one plain function tool namedtool_search_tool_regexand notool_searchtoolreq_defer_false_string.json, case 1 with"defer_loading": "false"(a string) onget_weather, and 9b,req_defer_false_string_drop.json, the same with"drop_params": truereq_turn2_prev.json, the follow-up turn:previous_response_idset to case 1's response id and afunction_call_outputof{"temp_c": 18, "condition": "cloudy"}for itsget_weathercall/v1/chat/completionswithreq_chat_turn1.json: the same question with Anthropic's nativetool_search_tool_regex_20251119tool and the three deferred function tools, then turn 2 replays its assistant message two ways, 2a answering only theget_weathercall and 2b answering the search call tooreq_vertex_claude.json, case 1 with"model": "vertex-claude"(vertex_ai/claude-sonnet-4-5, since 5.5 on Vertex answered 429)req_gpt_replay_claude.json, an after-leg case 1 turn (idstsc_srvtoolu_andfc_toolu_) replayed togpt-5.6with the same tools and afunction_call_outputforget_weatherreq_fallback_to_claude.json, case 1 with"model": "gpt-broken", an OpenAI deployment with an invalid key whose router fallback isclaude-sonnet-5-5, the customer's OpenAI-first setupreq_turn2_gemini.json, case 10's follow-up sent to"model": "gemini-flash"(gemini/gemini-3.8-flash) with a fresh case 1'sprevious_response_idreq_turn2_mistral_plain.json, a control with no tool search: a Claude turn 1 with one plainget_weathertool (req_claude_plain.json), then its follow-up sent to"model": "mistral-small"withprevious_response_idreq_namespace.json,tool_searchwith two namespaces,weatherholdingget_currentandcrmholdingget_customer, each member deferredreq_native_plus_search.json, Anthropic's nativetool_search_tool_regex_20251119tool and OpenAI'stool_searchin one request, with case 1's deferred function toolsreq_guard_malformed.json, case 1 with"defer_loading": "false"onget_weather, sent to a proxy booted withconfig_guard.yaml(adefault_onpre-call guardrail andlitellm_settings.drop_params: true)req_namespace_junk_drop.json,tool_searchwith aweathernamespace whose members are the string"not a tool",get_currentwith"defer_loading": "false", and a deferredget_stock_price, with"drop_params": truereq_allowed_callers_string.json, one function tool with"allowed_callers": "direct"and nodrop_paramsreq_replay_t1.jsonwith"store": true, then turn 2 replays turn 1 the way a chat-style client does, thesrvtoolu_search call as a plainfunction_call, and turn 3 sends turn 2'sprevious_response_idtomistral-smallreq_gpt.json(case 4), then a turn 2 that replays every output item exactly as the proxy returned it, with afunction_call_outputforget_weatherreq_gpt.jsonwith"stream": true, the streaming control for case 23case25.py req_claude.json, the SDK client with no proxy. Alitellm.Routerwhosegpt-primary(openai/gpt-5.6, invalid key) falls back toanthropic/claude-sonnet-5-5runsaresponseswith case 1's input and tools, plain and withstream=True, and 25b callslitellm.responses(model="anthropic/claude-sonnet-5-5")req_gpt.jsonand 26breq_claude.json, sent to a proxy booted withconfig_guard2.yaml, whose guardrail hands back only the tools of typefunctionit is givencase25.pyandfunction_only_guardrail.pyare in this gistRaw command and output follow for the cases the User Flow narrates (1, 2, 3, 10, 14, 15, and the SDK case 25, with case 2 on the before leg only, since its after run matches case 1), trimmed to the
outputitems, with long ids cut and$PORTstanding in for each leg's random port. Every case's result is in the table after themBefore (7fa52b2)
Case 1, every function tool deferred
Case 2,
send_emailleft undeferredCase 3, case 1 streamed
Case 14, an OpenAI group falling back to Claude
Case 15, the follow-up turn sent to
gemini-flashCase 25, the SDK client with no proxy, an OpenAI deployment falling back to Claude
Case 10 was not sent on the before leg, since its turn 1 is case 1, which answered 400 with no response id and no
get_weathercall to answerAfter (85bee09)
Case 1, every function tool deferred
Case 3, case 1 streamed
Case 10, the follow-up turn with
previous_response_idCase 14, an OpenAI group falling back to Claude
Case 15, the follow-up turn sent to
gemini-flashCase 25, the SDK client with no proxy, an OpenAI deployment falling back to Claude
Cases 27 to 32
These came from the caveats rounds. The before leg ran cases 27 to 30 at 7fa52b2 through a fourth proxy booted from
config_r3.yaml, which is the config above plus one Microsoft Foundry deployment, and case 31 through a fifth booted fromconfig_r4.yaml, which isconfig_r3.yamlplus themask-weatherguardrail. Case 32 ran on the before leg through that fifth proxy. The after leg ran every case at 85bee09 through one proxy booted fromconfig_r4.yaml, and the guardrail isdefault_on: false, so only case 31 calls itreq_azure_claude.json, case 1 with"model": "azure-claude"/v1/chat/completionswithreq_chat_turn2_all.json(case 11's turn 2b, the search call answered besideget_weather), andreq_chat_turn2_err.json, the same with the search answered by an error string, each sampled three times/v1/chat/completionswithreq_chat_system_before_search_turn.json: user, asystemmessage, an assistant turn holding only an unansweredsrvtoolu_search call, then user/v1/chat/completionswithreq_chat_search_only_answered.json: an assistant turn holding only the search call, with the caller'stoolanswer lastreq_native_plus_search_guard.json, case 18 with"guardrails": ["mask-weather"], thenreq_native_plus_search_guard_stream.json, the same with"stream": true. The question has "weather" in it, so Claude's search pattern does tooget_weatherandget_stock_pricestay deferred andsend_emaildoes not: 32areq_nosearch_claude.jsontoclaude-sonnet-5-5, 32breq_nosearch_gpt.jsontogpt-5.6, 32creq_client_search_claude.json, which is 32a plus{"type": "tool_search", "execution": "client"}, 32dreq_nosearch_bedrock_invoke.jsontobedrock-claude-invoke, and 32ereq_nosearch_mistral.jsontomistral-smallBefore (7fa52b2)
Case 30 answered 200 with the same
get_weathercall on the base (2026-10-14T07:26:52Z)Case 31, the masking guardrail on the search pattern, trimmed to each item's type, name, arguments, and status
After (85bee09)
Case 27, Claude on azure_ai
Case 28, the search call answered with an error beside
get_weatherCase 29, a system message before a search-only turn
Case 30, a search-only turn the caller answered
Case 31, the masking guardrail on the search pattern, trimmed to each item's type, name, arguments, and status
Case 28, every sampled answer
Case 32 on both legs, trimmed to each output item's type, the message text's first 45 characters, the function call, and the input token count
Cases 33 and 34
Both went to a fourth proxy on each leg, booted from this config plus a
mask-parispost-calllitellm_content_filterthat masksParisand amask-pipepolicy attached to agpt-pipegroup (openai/gpt-5.6) whosepost_callpipeline runs that one guardrail. Case 33 streams agpt-piperequest withtool_searchand a deferredget_weather. Case 34 sends case 1 with"execution": ""on itstool_searchtool, then adds"drop_params": trueEvery case 33 run answered HTTP 200, and at 85bee09 the proxy logged
the rewrite could not be written back ... 1 of the stream's 2 tool call items carry no call_id. In case 34"execution": 5answered the same 400s, the base gave thedrop_paramsrequest its same 400, and the head's 400s made no upstream call. The streameddrop_paramsrequest streamed the same two items, andgemini-flashanswered 200 withget_weatheron both legsCases 35 and 36
These ran at e250d78, after main's #32511 started carrying
cache_controlthrough aprevious_response_idreplay, on one proxy from the merged tree with the config'sclaude-sonnet-5-5andbedrock-claude-converseand a fresh Postgres. The base has neither change, so they ran on the merged tree only. Case 35 sends case 1 with"store": trueand"cache_control": {"type": "ephemeral"}on its input message, then a follow-up tobedrock-claude-conversewith thatprevious_response_id, theget_weatheroutput, and a marked message. Case 36 sendsbedrock-claude-conversefive marked messages, with and without"drop_params": trueRaw command and output for both cases are in this gist as
cases_35_36_raw.txtThe proxy's debug log shows case 35's Converse request with two
cachePointblocks (turn 1's mark and the new one) and thetoolu_call with its result, and without thesrvtoolu_search call. Case 36 sent 4cachePointblocks withdrop_paramsand 5 without. Before the merge fix, this PR's nameddrop_paramsargument hid the flag from #32511's cap, and main's unit test for that cap failed on the merged treeCases 37 and 38
At 86ed5be, whose
factory.pyresolution puts the unanswered-search drop beside #46440's client-answered rule: cases 1, 3, 10, 11, 22 and 28 again, plus 11's turn 2c, the assistant message as returned with itstool_search_tool_resultandget_weatheranswered. Two--num_workers 2proxies with a worker-pidCustomLogger, this tip and main 7b7604f, real Anthropicclaude-sonnet-5-5, a fresh Postgres, every turn 2 on the other worker. Scripts and raw output in this gistAll tools cannot be deferredtool_search_callthenget_weather, streamed in the same ordertool_use ids were found without tool_resulttool_search_tool_resultkept (#46440)provider_specific_fields, as beforeEvery case
gpt-5.6controldefer_loadingdrop_paramsgpt-5.6tool_searchfunction_calltool_search_calldrop_paramsdrop_paramsallowed_callersgpt-5.6itemsgpt-5.6streamedlitellm.responsesgpt-5.6function_callmaskedtool_search_callmaskedgpt-5.6tool_searchtool_searchdefer_loadinggpt-5.6streamedexecution: "", Claudeexecutiondrop_paramssrvtoolu_drop_paramsdrop_paramsAudit round 3 of 3 (later commits fix caveats and /live-pr-risk findings past the cap, two of them High)
Round 3 ran at ba49b20 against the merge base f97d3df on a remote rig, each leg with its own Postgres, Redis response cache, and scripted upstream. The changed cells ran once on the base and twice on the head, and a control leg ran the cells this PR keeps
test_responses_bridge_tool_search_wire.pytest_responses_bridge_tool_search_undeferred_wire.pytest_responses_bridge_tool_search_chaos.pytest_responses_bridge_tool_search_replay_wire.pyThe two head reds were real and are fixed past the cap at 67fe21b, where a string
allowed_callerson a function tool answers 400 instead of 500 and a cache hit of a search turn no longer carriescreated_by: null. At 67fe21b the four files passed 138 of 140 cells, both of those included, and the other 2 hit the harness's 15-second client timeout while the box sat at load 58. The schema cell passes in-process at 67fe21b and fails at the base, so that timeout comes from the box. The Mistral 422 and the response cache key that ignoresdrop_paramscome from the base and are listed under Caveats with follow-up ticketsThe commits after 67fe21b are merges of main, d9da2df (keeps
tool_searchout of the guardrail tool scan), the caveats fixes c3c38ba, 8c5409d, 681bd09, 333a5e8, and 85bee09, the /live-pr-risk fixes 7d1fc80 and 2e331ea, 6800449, which moves three wire cells to the newexecution400, and the merges of main at 2ae3d06 and e250d78. The QA above covers all of them, and at 299f63f the four files passed 149 of 149 cells on the rig/live-pr-risk at 2e331ea
Two findings needed a fix, and both are fixed. At 85bee09 a policy pipeline mask let
gpt-5.6's streamed function call arguments out unmasked when OpenAI's own search was in the stream, fixed at 7d1fc80 (case 33). 85bee09 also sent"execution": ""to Claude as a server search where OpenAI answers 400, fixed at 2e331ea (case 34). The other client-visible changes below ship on purpose, approved by mateo-berri at merge, with the reasons in DecisionsBase 7fa52b2 and the head ran side by side on the GCE box with 2 workers per side, and each leg compared status, body, the upstream requests a recording proxy saw (count, keys, size), and what a logging callback got. Four scouts and an agent that saw only the diff built the target list, HTTP routes first, then the SDK, then background paths
Breaking
defer_loading0or""defer_loadinglist or"true"allowed_callers, Mistralexecution""or5, Claudetool_searchtools, ClaudeBackward incompatible
created_by: nullsupports_tool_searchsrvtoolu_call, chatRegression risk. The complexity router's compaction converts tools without the route gate, so a malformed flag raises the same 400 there, read in code and not driven. Guardrails that read response tool calls (
generic_guardrail_api,model_armor,tool_policy) now also get a search call namedtool_search, and only the content filter and a custom guardrail were drivenDependency graph. Verified live on both sides:
/v1/responseson Anthropic, azure_ai, Vertex AI, Bedrock Invoke and Converse, OpenAI, Gemini, and Mistral, streamed and not,previous_response_idfollow-ups, Router fallbacks from OpenAI to Claude and from Claude to Gemini,/v1/chat/completionsreplays on four Claude routes,/v1/messages, the content filter as a post-call guardrail and in a policy pipeline, a custom pre-call guardrail, spend logs with message redaction, and/v1/model/info. Tested by unit and integration suites only: the response cache, the OpenAPI schema, andlitellm.supports_tool_search. No dashboard page readssupports_tool_search. The legacy integration and e2e suites ran on both legs at 85bee09. The accounting, management, cost and database lanes lost to a box outage there, the guardrail files the later fixes touch, and the open MCP and security reds ran again at 6800449. Every head red also fails on the base 7fa52b2 or passes when run again on the head, so none comes from this PR. One Vertex AI e2e case got a 429 from Google,Quota exceeded for aiplatform.googleapis.com/online_prediction_input_tokens_per_minute_per_base_model with base model: anthropic-claude-fable-5-1, which is a project quota and not a code failureNot verified. Batch, the complexity router, shadow evaluation, background response polling, Presidio streaming, cold-storage spend log replay, OpenRouter, Databricks, and the
generic_guardrail_api,model_armor, andtool_policyguardrails were not drivenType
🐛 Bug Fix
Caveats (if any)
Medium
tool_searchon/v1/chat/completionsstill raisesUnsupported tool type, tracked on LIT-9580tool_search_callon native routes, where the base passed it throughtool_searchand loads every toolbedrock/invoke/for tool search on Bedrockget_weatherwithout searching (case 10)defer_loading,allowed_callers, orexecutionanswers 400 withoutdrop_params0or"direct"before now answers 400 too, as OpenAI doesdrop_paramsit answers 200 (cases 9b, 19, 20, 34)tool_searchwith only a server warningdefer_loadingand load up frontmodel_info.supports_tool_search: truemodel_id, sincemodel_infocannot mark it as Claudebedrock/invoke/Low
tool_searchand loads every tool, follow-up ticketdefer_loadingon the Anthropic request, not checked livedefer_loadingcheck still answers 500, pre-existing/v1/messagesguardrail rewrites now drop an unansweredsrvtoolu_blocktool_search_callunscanned, like a streamedfunction_callon the base (case 31)drop_params, pre-existing, follow-up tickettool_search_callis litellm'sOutputToolSearchCallon a fresh answer, the SDK's class on a cache hitFinal Attestation
Note
High Risk
Touches Responses API translation, Anthropic message shaping, session replay, guardrails, and model capability gating—incorrect pairing or dropping of tool-search calls could break multi-turn tool flows or change client-visible 400/200 behavior.
Overview
Adds end-to-end support for OpenAI Responses API
tool_searchon Claude routes: servertool_searchtools translate to Anthropic’s regex tool-search tool when the model registry sayssupports_tool_search, and providersrvtoolu_search uses surface astool_search_calloutput items (including streaming).The Responses↔chat bridge gains
tool_search.py, stricter validation fordefer_loading,allowed_callers, andexecution(400 or strip underdrop_params), and strips unsupported server search on non-Anthropic follow-ups. Chat/Anthropic prompt conversion drops unanswered replayed tool-search uses while keeping caller-answered pairs; mid-conversation system placement treats unanswered search-only assistant turns as non-rendering.litellm.supports_tool_searchis exposed via lazy imports;azure_aiis included in theclaude-tool-searchcost-map rule. Output guardrails scan and rewritetool_search_callitems (keyed bycall_idor itemidwhen streaming). OpenAPI addsOutputToolSearchCallanddefer_loadingon chat tools.Reviewed by Cursor Bugbot for commit 86ed5be. Bugbot is set up for automated code reviews on this repo. Configure here.