Repository navigation
feat(anthropic-messages): per-deployment deferred_tools handling on the /v1/messages bridge (lts/1.108.x) - #54213
Conversation
…he /v1/messages bridge
Codecov Report❌ Patch coverage is 📢 Thoughts on this report? Let us know! |
…ol search replay native now needs a provider with client tool search (azure, fireworks_ai, openai) and wins over the global chat completions flag. ToolSearch results keep their text and is_error state, a forced ToolSearch tool_choice answers 400 or drops, emulate forces a deferred tool through the dispatcher, sync emulate streams work, and an unknown deferred_tools value is refused on every route, the opt-in Rust messages route included
…apply and quote tool search text A provider served through its own /v1/messages API now answers 400 for any deferred_tools value but passthrough, on the Python handler and on the opt-in Rust messages route, and passthrough on OpenAI answers 400 since OpenAI rejects defer_loading without its own tool search. Both fall back under drop_params. A ToolSearch result's text replays as a quoted string labeled as tool output
… on Azure, and name loaded tools under passthrough Fireworks' Responses tool search still bills deferred tools as prompt input, so native now answers 400 there like any provider without client tool search. passthrough answers 400 on Azure as it does on OpenAI, since both reject defer_loading outside their own tool search. Every deferred_tools fallback under drop_params now logs one warning naming the setting, because Claude Code requests get drop_params on by default and never see the 400. Under passthrough a ToolSearch result's tool_reference blocks reach a chat backend as text naming each loaded tool, instead of an empty tool result. drop keeps the earlier handling.
[Medium impact] The changes affect deferred-tool behavior across the `/v1/messages` bridge and several backend routes. The code fixes the previous strict-tool issue, but the required live QA must cover the latest product commit before merging Findings
|
…ool, close sync streams, and refuse passthrough on Mistral Port of main commit 837ad2c onto lts/1.108.x, in the pass_through module paths Under emulate, a CallLoadedTool call now comes back to the client only when it names a deferred tool that a ToolSearch result in the request loaded, or the tool that tool_choice forced. A forced deferred tool also limits the dispatcher's name to that tool. Any other call stays a CallLoadedTool call, so the client never runs a tool it did not load or force The dispatcher takes the first CallLoadedTool name the caller's tools do not use, and closing a restored sync stream closes the provider stream too, before or during iteration passthrough on mistral answers 400 naming the setting, or falls back to drop under drop_params, since Mistral's chat API answers 422 on deferred tools
…mulate Port of main commit 4ac1e85 onto lts/1.108.x, in the pass_through module paths Under emulate a loaded tool's arguments reach the model as the dispatcher's free-form input, so the provider cannot enforce strict input for it. A deferred tool with strict set now answers 400 naming the setting, or goes without strict under drop_params with the fallback warning, the way an unsupported strict already drops elsewhere. Claude Code sends no strict, so its sessions are unaffected
| _refuse_deferred_tools( | ||
| None if emulation is None else emulation.strict_input_refusal(), drops_deferred_tools_setting | ||
| ) |
There was a problem hiding this comment.
This changes strict deferred-tool refusals, but completed live QA stops at 78a205df5d. The repository requires proxy-to-provider proof at the latest product commit, 0dd87fcbeb5dd9e272dec965e41aeeca85ea2db8. Finish and attach those runs, covering the changed tool and stream paths, before merging
Rule Used: Apply this rule only to PRs that fix LLM translation bugs or add LLM translation features. LLM translation means converting requests, responses, streaming events, tool calls, and errors between the API a caller uses on LiteLLM (any endpoint or SDK fu... (source)
Note: If this suggestion doesn't match your team's coding style, reply to this and let me know. I'll remember it for next time!
There was a problem hiding this comment.
Live QA round 4 at 0dd87fc is now in the PR body, covering strict, emulate restore, dispatcher rename and sync stream close
There was a problem hiding this comment.
Live QA round 5 at 968ccd9, the current tip, is now in the PR body, covering emulate drop billing and the Rust route
Port of 52171f9 from main. The emulate stream wrapper forwarded attributes through __getattr__, which the proxy's runtime-checkable disconnect billing protocol does not see, so a client that dropped a streamed /v1/messages request on an openai/ deployment set to emulate logged no spend. The wrapper now passes on the inner stream's partial_response_on_disconnect
|
bugbot run |
…request drops defer_loading
…ols passthrough and fall back to drop there Under drop_params, passthrough on Bedrock Converse, Bedrock native chat, Gemini and Vertex Gemini (vertex_ai_beta included) now sends the same request drop sends
|
bugbot run |
| case "bedrock": | ||
| return BedrockModelInfo.get_bedrock_route(model) in ("converse", "converse_like", "chat_completions") | ||
| case _: | ||
| return False |
There was a problem hiding this comment.
bedrock_converse skips passthrough refusal
Medium Severity
builds_tools_without_deferral only inspects provider bedrock, so a bedrock_converse/ deployment never matches. passthrough on that provider is not refused and defer_loading is still dropped by Converse's tool builder, so the new per-route 400 never fires.
Reviewed by Cursor Bugbot for commit d8561fb. Configure here.
There was a problem hiding this comment.
bedrock_converse is not a provider prefix here, get_llm_provider rejects bedrock_converse/ models, and Converse models resolve to provider bedrock, which this check covers
…ols passthrough on Vertex A Vertex deployment routes to Gemini when its base_model names Gemini or when it is a numeric PSC endpoint with an api_base. The passthrough refusal now reads both, so such a deployment gets the same 400, or the drop fallback under drop_params, as a Vertex Gemini model name
…and keep non-string tool names out of set lookups
|
bugbot run |
…ed_tools_per_deployment_lts # Conflicts: # litellm/litellm_core_utils/core_helpers.py
…through check and ignore a non-object tool_choice on deferred tool routes
…nces instead of silently dropping tool search The Responses API has no stop_sequences, so a native request carrying them went to chat completions with deferred tools sent the drop way. It now answers 400 naming the way out, and under drop_params falls back with a warning. The guardrail test double now types request_data and logging_obj
…ponses API 1.108 still sends OpenAI requests with stop_sequences to the Responses API, where native tool search works, so the stop_sequences refusal now applies only to requests that leave it, such as Azure's
…rries ToolSearch Without ToolSearch, native sends deferred tools the same way drop does, so a stop_sequences request that leaves the Responses API keeps going to chat completions with stop instead of answering 400
…uardrails, native replays and emulate The tool_config cache point now skips tools with defer_loading, since Anthropic refuses a deferred tool that carries cache_control. When a guardrail removes the tool search tool, the tools it kept go up without defer_loading, so they stay callable. A native replay sends a tool's schema only in the first tool_search_output that loads it. Emulate restores a CallLoadedTool call to any tool the client declared without deferring it. native with stop_sequences refuses only when the request has tool search and at least one deferred tool
A CallLoadedTool call carries free-form input, so restoring it to a strict tool would skip that tool's schema. Such a call now goes back unchanged, like a call naming an unknown tool, and the model retries with the tool itself. The tool_config cache point test now records the request at the wire instead of replacing the handler
|
bugbot run |
|
bugbot run |
There was a problem hiding this comment.
✅ Bugbot reviewed your changes and found no new issues!
1 issue from previous review remains unresolved.
Comment @cursor review or bugbot run to trigger another review on this PR
Reviewed by Cursor Bugbot for commit 2030ddd. Configure here.
…rt_53290_lts_1_108_x Conflicts with #54213 in the /v1/messages guardrail tool write-back, resolved to main's text, where #54183 sits on top of #53290: tools the guardrail returned unchanged stay as sent, and a kept tool loads up front when the guardrail removed the tool search tool. The by-name defer_loading restore from #54213 is left out, as on main.
…s it lts/1.108.x restores defer_loading by name on tools a guardrail returns (#54213). The merge took main's write-back, which converts an edited tool without it.


Handwritten 1-3 sentence description
LTS twin of #54183 for lts/1.108.x. When Claude Code loads a tool through tool search, every non-Anthropic model behind /v1/messages lost its prompt cache on that turn. This adds the same per-deployment
deferred_toolssetting on 1.108, so native tool search or emulation keeps the cache and no backend gets blocks it rejectsDetails
TLDR
Problem this solves:
defer_loadingleaks into the chat bridge's tool schemaHow it solves it:
model_info.deferred_tools:passthrough,native,emulate, ordrop(default)nativemaps ToolSearch onto Responses API tool searchemulatekeeps one fixed tool list on chat-only backends through aCallLoadedTooldispatcherdropunderdrop_paramsUser Flow
Before: a developer running Claude Code through a 1.108 proxy on an Azure deployment pays full input price on every request right after a tool load
ANTHROPIC_BASE_URL=https://litellm-domain,ENABLE_TOOL_SEARCH=trueand an MCP server connectedcache_read_input_tokens: 0, and every later tool load repeats itAfter: the same session keeps its cache across tool loads
deferred_tools: nativeunder the Azure deployment'smodel_infoand restarts the proxycache_read_input_tokens, like Anthropic directDesign decisions
Every mode, default, and error matches #54183, whose Design decisions section explains each choice. This PR only moves that behavior onto the 1.108 code layout
Picks
Pick table
Differences on this line
litellm/llms/anthropic/pass_through/where main haslitellm/llms/anthropic/messages/, andmessages/handler.pyhere is main'snative/handler.pyloads_json_objectis copied intolitellm_core_utils/core_helpers.py, since 1.108 lacks itstreaming_iterator.pymakessse_frame_eventpublic and gainssse_frames, which the emulation stream restorer reads_translate_tool_to_responses_apiis pulled out of the Responses adapter sonativecan keep deferred tools deferredimport litellmstill never loadslitellm.proxy._types_should_route_to_responses_apitakes nostop_sequences, so the call site passesnative_deferred_tools and not stop_sequences. OpenAI requests withstop_sequencesalready went to the Responses API on 1.108 and keep tool search there, so only requests that leave it, like Azure's, get main'sstop_sequences400 when they carry ToolSearch and a deferred toolLITELLM_RUSTtraffic and has one Python hook,settings(kwargs), so the refusals go there, with Rust route tests main does not need. It finds the provider withget_llm_providerand checks for a provider messages API through the handler'smessages_request_bridges, since 1.108 lacks main's_messages_configrefusal_unless_droppedwraps themessages_request_bridgescheck that stands in for main'sconfig is Noneoptional_strfromlitellm.rust_bridge.public_call, since 1.108 lackslitellm.llms.base_llm.base_utils.optional_strdefer_loadingon each tool the request deferred, since 1.108 rebuilds the tools from OpenAI format after a guardrail runs. Main already sends a tool the guardrail left unchanged exactly as it came. On both lines, a guardrail that removed ToolSearch sends the kept tools withoutdefer_loadingbase_modelfor thepassthroughcheck, since 1.108 passes it apart frommodel_info. Main merges it intomodel_infobefore the adapter runscount_tokenspart of bcb7c2e has no LTS change, since 1.108 never counteddefer_loadingLinear ticket
Resolves LIT-11175
Pre-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
After ran on 6c7d110 and Before on ba603a4 (topology, config, gist)
Last updated: 2030ddd. QA ran on 6c7d110, after merging lts/1.108.x at f57b2c5. Changes since: fixes to
nativewithstop_sequences, thetool_configcache point, guardrail write-back,nativereplays, and theemulaterestore, which now skipsstricttools. Proof remains valid because live-pr-risk re-ran each changed path on real providers at bbf3181 and 2030ddd, and only the two Low caveats below moved (report). Verification: CI passed at 2030dddPercentages are cache reads right after a tool load
emulateturnCallLoadedToolerror, 0%nativeturnsdefer_loadingdroppeddefer_loadingkeptpassthroughcurlsdrop_params200nativelongCase 1, Claude Code on
br-kimi(headline)br-kimiisbedrock/us.moonshotai.kimi-k3.1withdeferred_tools: emulate, behind thepre_callcontent filterrun_session.shWhat is the weather forecast for Paris? Use the weather MCP tool./spend/logswithspend_brief.shAfter, the forecast shows with no error, and row 3, right after the load, reads 95% from cache (full run)
Before, Claude Code shows
Error: No such tool available: CallLoadedTool, and row 3 reads 0% (full run)Case 2,
azure-solnative, 3 Claude Code turns, both legs and a control without the guardrailazure-solisazure/gpt-6.1-solwithdeferred_tools: native. Each session sendsIn one sentence, what does a three-day weather forecast usually include?, then case 1's prompt, which loads the forecast tool, thenIs Wednesday a good day for a picnic in Paris? Answer in one sentence.The control runs the same session on the After proxy with a key minted withmetadata.disable_global_guardrails: true(mint). All three sessions showed the same forecast and picnic answer (After, control, Before)After defers the same tools as the control, and row 4, right after the load, read 97% from cache, like the control. Before deferred no tool, so row 4 read 0% and cost $0.0305 instead of $0.0023
Control
Before
After still reads about 1,300 to 1,360 more input tokens than the control on rows 2 to 6, and Before carries the same extra. On both legs the guardrail repeats the last system block when Claude Code's billing header block comes first. A 3-block curl reads 2303 input tokens through the guardrail and 1163 without it, and 1163 both ways once the header block is gone, at the tip as at 7ce2004 (tip, 7ce200493b and Before)
Case 3,
claude-directcurl with atool_reference, both legs and Anthropic directclaude-directisanthropic/claude-sonnet-5-5.c3-claude.jsonhas ToolSearch up front,mcp__weather__get_forecastwithdefer_loading: true, and a ToolSearch result that references it (After, Before and direct)After
Before
The same body sent straight to Anthropic counts 660 input tokens with
defer_loadingand 652 without it (with, without). So After matches Anthropic getting the deferred tool, and Before matches the flag droppedRound 6 cases and rounds 2 and 4 case 7, After only at the tip, control key so no guardrail runs, as in those rounds
Round 6 case 1.
br-kimi-passisbedrock/chat_completions/us.moonshotai.kimi-k3.1withdeferred_tools: passthrough, and the proxy turns ondrop_paramsfor Claude Code requests. What the admin sees in the terminal running the proxy is one warning per request, and both requests answer 200 (full run, round 6 Before)The same request as a curl answered 400 naming the setting, as in round 6, and 200 with one warning once it sets
"drop_params": trueRound 6 cases 2, 3 and 5. Round 6's bodies on
nova-pass(Bedrock Converse),gemini-passandgrok-pass(Bedrock) each answered 400 naming the setting, then 200 with atool_useand one warning with"drop_params": true(curls and console)Round 6 case 4. One forced ToolSearch turn each on
fw-kimi-passandbr-kimishowed the forecast with no error, andbr-kimiread 97% right after the load (fw-kimi-pass, br-kimi)Rounds 2 and 4 case 7, a 5-turn session on
azure-solthat loads 3 tools. Rows 4, 7 and 10 follow a load and read 97%, 98% and 98%, where Before read 0% in round 4 (full run)Earlier runs, kept for history and not carried to this tip
Round 7 at 7ce2004. Case 1, case 2 with its control, case 3, and focused suites at 7ce200493b and b0254a835a
Rounds 2 to 6, before the merge, in the round 6, round 5, round 4, round 3 and round 2 gists. Round 5's gist also holds round 4's cases in files 28 to 37
Surprises
Round 6 surprises, seen again at the tip
chat_completions/Kimi route rejects tools. Pre-existingCallLoadedTool, not the restored name. Caused hereType
🆕 New Feature
Caveats (if any)
Medium
emulatenever ran on a vLLM server serving Kimi, which LIT-11175's "Done when" namesemulateskips the provider's schema check on a loaded tool's input, so a bad call reaches the client as isLow
nativeputs a pinned chat-eraapi_versionon Responses URLscount_tokensignoresdeferred_tools, soemulateover-countsnativeturns intodropwithout a warning oncompactionrequests, which go to chat completionsdrop_paramsthe fallback warning logs on every requestpassthrough400 names Claude Code to every callerCallLoadedToolunderemulateemulate, a dispatcher call to a non-deferredstricttool comes back asCallLoadedTool, and the model retries. Claude Code sends nostrictnativespend rows sayanthropic_messages, notresponses, and streams lackx-litellm-model-api-baseDecisions
passthroughis refused by provider, so anopenai/deployment pointed at a self-hosted OpenAI-compatible server gets the same 400 as OpenAI, whilehosted_vllm/goes through. LiteLLM picks per-provider rules such as the supported-params list by the provider prefix, not byapi_base, so a server that takes deferral belongs under its own provider. Underdrop_params, which Claude Code gets by default, the request falls back todropinsteadUnder
emulatethe proxy does not check a loaded tool's input against its schema. Checking it was the alternative, but a call that fails could only go back as an unknown tool or fail the turn, while passing it through lets the client's tool reject it, as it does a bad call from any model. A dispatcher call to astricttool the client did not defer is not restored, since the dispatcher's free-form input skips its schema, so the model has to call that tool directly. Checking the input against the schema in the proxy was the alternative, but it would evaluate a client-supplied schema, regex patterns included, inside the proxyA live-pr-risk run at 0dd87fc found three things. A unified guardrail dropped
defer_loadingwhen it wrote the tools back, which brokeemulateand turnednativeoff, and 7ce2004 keeps it. A tool name ortool_use_idthat is not a string answered 500 instead of the provider's 400, and 7ce2004 fixes that too.nativeon Azure sends requests to the Responses API, so spend rows and headers differ, but only a deployment that opts intonativesees thatFinal Attestation
Bugbot summary