Repository navigation
fix(guardrails): keep /v1/messages tools the guardrail left unchanged exactly as sent - #53290
Conversation
There was a problem hiding this comment.
Devin Review found 1 potential issue.
5 flags not posted on this PR by your GitHub settings — view them in Devin Review. (Configure)
[Medium impact] The PR appears safe to merge, with no outstanding actionable findings.
|
4 similar comments
b0a6081 to
0b0f7ad
Compare
0b0f7ad to
72acdef
Compare
72acdef to
86b69c6
Compare
…e caller sent them
86b69c6 to
8bb758a
Compare
…eturned them A guardrail that reordered or renamed tools had its order ignored: tools were rebuilt in the request's order and a renamed tool was appended last, after the tool carrying the cache_control breakpoint. Matching a rewritten tool back to a request position also rescanned the open positions once per tool. The tools now follow the guardrail's list. A tool it left alone is sent as the caller sent it, any other is converted in place, with one lookup per tool. Tools the guardrail is never shown go first, as before this branch.
…ages_guardrail_tools # Conflicts: # litellm/llms/anthropic/chat/guardrail_translation/handler.py
|
bugbot run |
…t iterable is not lost
|
bugbot run |
…t depend on execution speed
|
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 77f56dc. 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.
… exactly as sent (BerriAI#53290) * fix(guardrails): send /v1/messages tools a guardrail left alone as the caller sent them * fix(guardrails): send /v1/messages tools in the order the guardrail returned them A guardrail that reordered or renamed tools had its order ignored: tools were rebuilt in the request's order and a renamed tool was appended last, after the tool carrying the cache_control breakpoint. Matching a rewritten tool back to a request position also rescanned the open positions once per tool. The tools now follow the guardrail's list. A tool it left alone is sent as the caller sent it, any other is converted in place, with one lookup per tool. Tools the guardrail is never shown go first, as before this branch. * test(guardrails): measure write-back time growth instead of counting field reads * fix(guardrails): read the tools a guardrail returns once so a one-shot iterable is not lost * test(guardrails): drop the write-back timing test, unit tests must not depend on execution speed (cherry picked from commit ce63fa7)
Handwritten 1-3 sentence description
On /v1/messages, tools a guardrail leaves unchanged now reach the provider exactly as the caller sent them, instead of being rebuilt and losing Anthropic-only fields.
Details
TLDR
Problem this solves:
/v1/messagestoolweb_searchwas dropped,mcp_toolsetbecamelitellm_unnamed_tool_0defer_loading,strict,input_examples,allowed_callers,cache_controlwere strippedHow it solves it:
Intentional product change: a Bedrock Claude deployment behind such a guardrail used to answer 200 after silently dropping a
web_search_20250305tool. It now answers the same 400 it already gives without a guardrail, which tells the operator to enable web search interception.User Flow
Before: a developer running a coding agent through the gateway behind a default-on content filter gets deferred tools loaded up front and loses web search
pre_calllitellm_content_filterthat only masks emailstool_search_tool_regextool and two tools marked"defer_loading": truedefer_loadingand with"type": "custom"added, so they are no longer deferredweb_search_20250305tool next to a custom tool on an OpenAI model, the provider receives no web search tool at allAfter: the same request reaches the provider with the tools the developer sent
pre_calllitellm_content_filterthat only masks emailstool_search_tool_regextool and two tools marked"defer_loading": trueweb_search_20250305tool next to a custom tool on an OpenAI model, the provider receives the web search toolAdmin UI Logs page, same request on both proxies: POST /v1/messages to an OpenAI model with
[Read, web_search_20250305]behind the email-masking content filter, asking the model to list its tools.Before (f30ea8b): the provider was given 1 tool and the model says it cannot search the web
After (834fd4a73f2): the provider was given both tools
Relevant issues
Fixes #50055
Fixes #49253
Covers the cases in the open PRs #40077 and #49721.
Linear ticket
Resolves LIT-10590
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
Two live proxies ran side by side, one at the merge base and one at the tip, each with 2 workers, its own Postgres and its own Redis. Every provider call is real. A logging reverse proxy sat between each gateway and the provider (it is the deployment's
api_base), so the "provider received" lines below are the bytes the gateway sent.Provider routes covered: Bedrock InvokeModel Claude through
/v1/messages(json and stream), the Bedrock pass-through route/bedrock/model/<model>/invoke, Bedrock Converse through/v1/messages, and an OpenAI model through/v1/messages. In this matrix the direct Anthropic API key had no credits, so Anthropic answered 400 "credit balance is too low" on both legs; the Anthropic API and Azure AI Foundry Claude were proven later with a funded key, see the reviewer notes at the bottom. The Gemini deployment in the rig pointed at a retired model name and answered 404 on both legs.Shared setup: config.yaml, start command, env var names, client
For the cases where a guardrail edits or removes a tool, the
guardrailsblock is replaced by two opt-in custom guardrails selected per request with"guardrails": ["mask-read-tool"]or["drop-read-tool"]:Start command, run from each checkout:
python litellm/proxy/proxy_cli.py --config config.yaml --port <port> --num_workers 2 --use_prisma_db_pushEnv var names:
DATABASE_URL,LITELLM_MASTER_KEY,ANTHROPIC_API_KEY,OPENAI_API_KEY,AWS_BEARER_TOKEN_BEDROCK,LITELLM_LICENSEClient, the same for every case, with the
toolsand prompt of that case:The web search cases send
"tools": [<Read as above>, {"type": "web_search_20250305", "name": "web_search", "max_uses": 1}]with the prompt "Use web search to find the latest stable CPython release, then answer with the version number only."input_schemais shortened to{...}in the output below. It was identical to what the client sent in every line.Before (f30ea8b)
Deferred tools behind the default-on content filter, Bedrock InvokeModel, json and stream
"stream": false, then again with"stream": true. Both answer 200 withstop_reason: tool_useSame tools through the Bedrock pass-through route
modelandstream, with"anthropic_version": "bedrock-2023-05-31", to/bedrock/model/claude-bedrock-invoke/invoke. It answers 200defer_loadingPrompt with an email, so the guardrail edits the request
contact [EMAIL_REDACTED]defer_loadingWeb search tool next to a custom tool, OpenAI model through /v1/messages
"model": "gpt". It answers 200 with the text ``, an answer from memory/v1/responses:Web search tool next to a custom tool, Bedrock InvokeModel
"model": "claude-bedrock-invoke". It answers 200 with the text "I don't have access to a web search tool. The tools available to me only allow me to read files from disk."ReadtoolA guardrail that edits one tool, and one that removes it
"guardrails": ["mask-read-tool"]. It answers 200. Provider receivedReadwith"description": "[MASKED BY GUARDRAIL]", and the two deferred tools withoutdefer_loading"guardrails": ["drop-read-tool"]. It answers 200. Provider received noReadtool, and the two deferred tools withoutdefer_loadingBlocked word
Content blocked: keyword 'forbiddenword' detectedand the provider receives nothingAfter (834fd4a73f2)
Deferred tools behind the default-on content filter, Bedrock InvokeModel, json and stream
"stream": false, then again with"stream": true. Both answer 200 withstop_reason: tool_useSame tools through the Bedrock pass-through route
modelandstream, with"anthropic_version": "bedrock-2023-05-31", to/bedrock/model/claude-bedrock-invoke/invoke. It answers 200"defer_loading": trueon both deferred toolsPrompt with an email, so the guardrail edits the request
contact [EMAIL_REDACTED]"defer_loading": trueon both deferred toolsWeb search tool next to a custom tool, OpenAI model through /v1/messages
"model": "gpt". It answers 200 with the text3.15.2/v1/responses:Web search tool next to a custom tool, Bedrock InvokeModel
"model": "claude-bedrock-invoke". It answers 400 "Bedrock does not support Anthropic's server-side web search tool (tool type 'web_search_20250305', model 'us.anthropic.claude-haiku-4-5-20251001-v1:0'). To use web search with this model, enable LiteLLM's web search interception so the proxy executes the search instead"A guardrail that edits one tool, and one that removes it
"guardrails": ["mask-read-tool"]. It answers 200. Provider receivedReadwith"description": "[MASKED BY GUARDRAIL]"in its original second position, and the other three tools exactly as sent with"defer_loading": true"guardrails": ["drop-read-tool"]. It answers 200. Provider received noReadtool, and the two deferred tools exactly as sent with"defer_loading": trueBlocked word
Content blocked: keyword 'forbiddenword' detectedand the provider receives nothingUnchanged on both legs
Bedrock Converse through
/v1/messages,/v1/chat/completionsand/v1/responseswith the same guardrails, alogging_onlyand aduring_callguardrail that edits tools, a request with no guardrail, and a request with no tools sent the same bytes before and after.Audit at 834fd4a73f2
63 live cells per leg across three guardrail configs: 50 pass, 5 show the behavior changes listed at the bottom, 8 are blocked by a provider (no Anthropic credits, Gemini 404). The guardrails used are on the Admin UI page below.
/v1/messages,/v1/chat/completions,/v1/responses, mixed streaming, one worker killed mid-burst/v1/messagescalls of that burstSad and edge cells with the same answer on both legs:
toolsas a string, an int, a list of strings (500 on both), unknown model (400), no auth (401), unknown guardrail name, emptytools, duplicate tool names (provider 400 on both),tool_choicenaming a tool the guardrail removed (provider 400 on both), a 5 KB description, an OpenAI-format tool.Third-party guardrails, live at 77f56dc
Thirteen
pre_callguardrails against their real services (Presidio as real analyzer and anonymizer containers),/v1/messagesto the Anthropic API, main 7f08cd7 against this tip. Each got a benign prompt, the same prompt streamed, and a prompt with a card number and an email. The tools weretool_search_tool_regex, a plain tool, adefer_loadingtool and astricttool withcache_control. A recorder in front of Anthropic and each vendor logged what was sent.defer_loadingandstrictdroppedAll 42 cells per leg have the same status, the same
x-litellm-applied-guardrails, the same stream event count, the same vendor call count and the same message text on the wire. The only difference is the tools. Not run: Bedrock Guardrails and Model Armor.Tests
tests/integration/messages_endpoint/test_anthropic_messages_caller_tools_wire.pygains four cases on a real two-worker proxy with a scripted provider. They failed at f30ea8b (4 failed, 18 passed) and pass at the tip (22 passed). The unit tests cover a tool returned unchanged, edited, renamed, removed, added, returned twice, two tools the guardrail cannot tell apart, and deferred tools left alone by a removal.Type
🐛 Bug Fix
Caveats (if any)
Medium
web_search_20250305behind a guardrail: 200 without search becomes 400Low
defer_loadingtests/integrationruns on main after merge, or with therun-cilabelFinal Attestation
REVIEWER MUST KNOW BEFORE APPROVING
web_searchto guardrails. Now on main, tip 77f56dc (a8287e0 minus one timing unit test, no product change)cache_controlbreakpoint, and matching cost grew with the square of the tool count. Live on OpenAI through a forwarding recorder, main 7f08cd7 and 030c2ba both send[fmt, lint]for a reversing guardrail and[lint_v2, fmt]for a renaming one. At 030c2ba: 17675 unit tests and 84/v1/messagesintegration tests pass. Live on Bedrock Claude Haiku 4.5 at 030c2ba against main 7f08cd7, same recorder: both send[fmt, lint]and[lint_v2, fmt]with thecache_controlbreakpoint still on the last tool, and the second call with the renamed tool reads the whole tool prefix from the prompt cache (11,507 tokens on main, 11,508 here). Proxy overhead with a guardrail that renames every tool, median of 3: 2000 tools 820 ms on main and 911 ms here (about 3.0 s before 67c80d0), 1000 tools 427 ms and 436 ms, 500 tools 265 ms and 222 mstoolsas a generator,maporreversedhad every tool dropped with a 200, or the request answered 500, where main sends them. Live on OpenAI at a8287e0 against main 7f08cd7: a generator, areversedand amapthat edits one tool all send the same three tools on both legs. 17678 unit tests and 84/v1/messagesintegration tests passlitellm_content_filter: deferred tools (json and stream), acache_controltool, a validstricttool andweb_search_20250305all answer 200 on both legs. Behind the guardrail main sends rebuilt tools (defer_loadingandstrictgone,"type": "custom"added) and this branch sends the caller's tools byte for byte, the same bytes both legs send with no guardrail. The email is masked on both legs/bedrock/model/<model>/invokeand/invoke-with-response-streamwith an Anthropic body: a tool with an unknown key, noname,name: "", noinput_schema, aninput_schemawith notype,stricton a schema withoutadditionalProperties: false, or every tool deferred goes 200 to 400. A valid unchanged tool now goes out as sent, without the added"type": "custom", and still answers 200/v1/messagesto an OpenAI model:strict: trueon a schema that is not valid for OpenAI strict mode goes 200 to 400 (main droppedstrict), andname: ""goes 200 to 400 on the Responses route/v1/messagesto Vertex AI Claude: the same malformed shapes,allowed_callers, andcomputer_20250124sent without its beta header go 200 to 400/v1/messagesto the Anthropic API and to Azure AI Foundry Claude: a named tool with noinput_schemagoes 200 to 400tools: []reply now removesweb_searchweb_searchagain, because it now sees that tool and left it out. The earlier "empty tools reply keeps web search" change is gone/v1/messagesrequest carrying aweb_search_20250305tool, behind a guardrail that returns tools. Before: 200, the web search tool was silently dropped and the model answered without search. After: 400 "Bedrock does not support Anthropic's server-side web search tool", the same answer the request gets with no guardrail. This change now comes from fix(guardrails): show the /v1/messages web search tool to guardrails #53376. Approved by yucheng-berri on 2026-11-21/v1/messagestool that a guardrail returns unchanged, on a Bedrock Claude deployment. Before: the tool was rebuilt from OpenAI format, which repaired it, and Bedrock answered 200. After: it is sent as the caller sent it and Bedrock answers 400, as it does on main with no guardrail. Shapes reproduced: nonameand noinput_schema(was rewritten intolitellm_unnamed_tool_0), a named tool with noinput_schema,name: "", aninput_schemawith a top-levelanyOf, aninput_schemawith notype, an unknown key on the tool,input_examples,strict, and a list where every tool hasdefer_loading. A tool the guardrail edits is still rebuilt and repaired. Approved by yucheng-berri on 2026-11-23 for every route and provider (the nameless case on 2026-11-21)Note
Medium Risk
Changes pre-call request shaping on
/v1/messagesfor all tools-returning guardrails; malformed unchanged tools and Bedrockweb_searchnow surface provider 400s instead of silent rewrites.Overview
On
/v1/messages, guardrail write-back no longer rebuilds every tool from OpenAI format. New logic (_tools_after_guardrail, fingerprint matching, and_loaded_up_front) keeps tools the guardrail left alone exactly as the client sent them—includingdefer_loading,web_search, native tool types, and other Anthropic-only fields. Only tools the guardrail edited, added, or reordered are converted back; removed tools stay removed. When every surviving tool would be deferred-only,defer_loadingis stripped so Anthropic still accepts the request.Integration tests add vendor guardrails that redact one description or drop one tool; unit tests cover pass-through, edits, removals, duplicates, and deferred-tool edge cases.
Reviewed by Cursor Bugbot for commit a8287e0. Bugbot is set up for automated code reviews on this repo. Configure here.