Repository navigation
fix(proxy)!: answer 400 for malformed tools on count_tokens instead of crashing - #46583
Conversation
… crashing A non-list tools value crashed the vector store lookup during auth and the built-in tool cost lookup in the failure logging path, so the proxy answered an unhandled 500 and closed the keep-alive connection. count_tokens now answers a 400 invalid_request_error for a malformed body, drops malformed tools when drop_params is on, and both lookups skip values of the wrong shape.
|
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! |
Also validate the count_tokens body without recursion, which the recursion detector rejects.
…ens_malformed_tools
The proxy now answers a non-list tools value with a 400, so the case is deterministic again.
|
bugbot run |
|
@litereview code-review |
✅ code-review5/5 · Ready for human reviewScope: full · Full PR review. No correctness findings. The PR title includes the breaking-change marker ( Checks and execution details
These edits only change how the guardrail and allowlist code reads
No provider request, response, streaming or usage translation changed. I ran the PR's real-proxy integration suite:
All 10 errors happened in fixture setup at
The notice is complete:
SDK callers outside the proxy see no change, because the check requires
Traced paths:
Boundary checks I ran directly:
Unit tests: the 9 touched unit files plus a filtered router run gave 494+109 passed. There were 7 initial failures in
View review · Reviewed |
…ctor store checks on malformed ids
|
@litereview code-review |
|
bugbot run |
…, and reject malformed tool vector store ids Check tools after request setup so the Claude Code default and the logged call type apply, read the request, global, and model group drop_params the way core does, drop tool_choice and friends with tools, cover Gemini generateContent, and answer 400 for a malformed tools[].vector_store_ids with the strict flag off
…n after request setup The body-shape fallback relabeled a /v1/messages rejection as acompletion and a list-input /v1/responses rejection as aembedding, so it now only applies when the logging object carries no known call type
|
@litereview code-review |
…ens_malformed_tools # Conflicts: # litellm/llms/openai/chat/guardrail_translation/handler.py
|
@litereview code-review |
…nor drop_params per entry
|
@litereview code-review |
…n auth, check the responses websocket
|
@litereview code-review |
1 similar comment
|
@litereview code-review |
Review already requestedcode-review is already reviewing |
|
bugbot run |
|
@litereview code-review |
|
@litereview code-review |
|
bugbot run |
|
@litereview code-review |
|
bugbot run |
# Conflicts: # litellm/proxy/anthropic_endpoints/endpoints.py
|
@litereview code-review |
|
@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 f34b58a. Configure here.
|
@litellm-stampbot |
…46839, #46843, #46583, #47057, #47064, #47163, #46777) (#47209) * fix(proxy)!: count prompt-only token_counter requests with the provider when call_endpoint is set (#46839) * fix(proxy): count prompt-only token_counter requests with the provider when call_endpoint is set * fix(proxy): keep the local count for a prompt-only token_counter request when the provider count fails * fix(proxy): log a prompt-only token count fallback as a one-line warning * fix(proxy): send a prompt-only token_counter request to the provider only on Gemini and Vertex AI * fix(proxy): count a token_counter prompt sent next to an empty messages or contents list * fix(proxy): count a prompt next to messages on the local token count instead of answering 500 * fix(proxy): answer 400 for a token count prompt next to a conversation unless drop_params is set With drop_params the conversation is counted without the prompt. On the local count, a prompt sent with system or tools is counted as a user message with them, like the messages form. * test(proxy): count tools with a prompt in the token counter fallback test * test(proxy): cover prompt counting on /utils/token_counter in the Gemini count wire tests * test(proxy): name the token counter fallback test by what it checks (cherry picked from commit 2dc6aaf) * fix(count_tokens): apply context_management edits in the Gemini /v1/messages/count_tokens count (#46843) * fix(count_tokens): apply context_management edits in the Gemini /v1/messages/count_tokens count /v1/messages runs clear_tool_uses context edits before it sends an Anthropic body to a Gemini or Vertex AI deployment, but /v1/messages/count_tokens counted the body unedited, so a request with older tool results cleared counted about 2.8x what inference bills. The count now runs the same history and context-edit step inference runs, honors additional_drop_params on the deployment, and skips compact edits so a count never makes a paid summary call. * fix(count_tokens): match the Gemini count to inference for compact edits and drop opt-outs Run compact edits in the count without the summary call so trigger checks and history slicing match /v1/messages, honor a request-level additional_drop_params, keep the full body when any deployment in the model group drops context_management, and answer 400 naming a block Gemini cannot count when an edit trigger fails on it * fix(count_tokens): count the unedited body when an edit fails and honor deployment ids in the drop check * fix(count_tokens): log a failed edit in the count at debug, since the send already logs it * fix(count_tokens): resolve a deployment id before wildcard routes in the drop check, as the router does * fix(count_tokens): honor the router-wide additional_drop_params opt-out in the drop check The router merges default_litellm_params between the deployment and the request, so a router-wide context_management opt-out makes /v1/messages send the full history. The count now reads it in the same order. Adds the audit's wire tests for the count's context edits. * fix(count_tokens): read the opt-out of a deployment the router serves by its litellm model name * fix(count_tokens): read the opt-out and drop_params from the deployments the router and completion_model send to * fix(messages): drop an invalid context_management spec under drop_params so the send matches the count * fix(count_tokens): give Claude Code and Codex counts the drop_params default /v1/messages gives them The proxy turns on drop_params for Claude Code and Codex user agents on /v1/messages. The count now applies the same default, so an invalid context_management spec drops on both endpoints instead of the count answering 400 while the send answers 200. The wire test also covers default_fallbacks, model_group_alias, and completion_model routes. * test(count_tokens): cover a coding agent that turns drop_params off and stop two count tests running as Claude Code (cherry picked from commit f8217d2) * fix(proxy)!: answer 400 for malformed tools on count_tokens instead of crashing (#46583) * fix(proxy): answer 400 for malformed tools on count_tokens instead of crashing A non-list tools value crashed the vector store lookup during auth and the built-in tool cost lookup in the failure logging path, so the proxy answered an unhandled 500 and closed the keep-alive connection. count_tokens now answers a 400 invalid_request_error for a malformed body, drops malformed tools when drop_params is on, and both lookups skip values of the wrong shape. * fix(proxy): skip non-list tools in the tool allowlist check Also validate the count_tokens body without recursion, which the recursion detector rejects. * test(integration): restore the int tools case on count_tokens The proxy now answers a non-list tools value with a 400, so the case is deterministic again. * fix(proxy): reject malformed tools at the LLM route entry and keep vector store checks on malformed ids * fix(proxy): apply drop_params like core when dropping malformed tools, and reject malformed tool vector store ids Check tools after request setup so the Claude Code default and the logged call type apply, read the request, global, and model group drop_params the way core does, drop tool_choice and friends with tools, cover Gemini generateContent, and answer 400 for a malformed tools[].vector_store_ids with the strict flag off * fix(proxy): keep the request's call type when logging a gate rejection after request setup The body-shape fallback relabeled a /v1/messages rejection as acompletion and a list-input /v1/responses rejection as aembedding, so it now only applies when the logging object carries no known call type * fix(proxy): share the malformed tools check across tool routes and honor drop_params per entry * fix(proxy): accept null vector_store_ids, read every named store id in auth, check the responses websocket * refactor(proxy): leave the responses websocket out of the request-level tool check * fix(proxy): let a request's additional_drop_params replace the deployment list and keep compact's call type on rejections * fix(proxy): read router default drop lists and deployment ids in the malformed tools check * fix(proxy): leave malformed tools to the router when it can pick another deployment Fallbacks, auto-routers, model strings, comma batches and team model names let the router pick a deployment after the proxy checks the request, so the proxy now forwards a malformed tools field there as main does, and only rejects it when the deployment it checks is the one that serves. Token counting never reroutes, so count_tokens and input_tokens keep reading the group they count with. additional_drop_params names are read the way core reads them, so a list with a non-string entry still names its strings. * test(integration): cover malformed tools on reroutable models, router defaults and deployment ids * fix(proxy): resolve malformed tools at the deployment the router picks * fix(proxy): keep provider-repaired tool schemas, honor fallback_on_unsupported_params, skip cooldown on malformed tools Empty schemas and JSON-string schemas pass the tools check the way litellm's provider paths already read them. The rejection is a BadRequestError subclass carrying the deployment's provider, so fallback_on_unsupported_params: false keeps the 400, and the router never cools a deployment down for a request litellm rejected before calling it. Adds the audit's pre_call guardrail and cross-provider bridge cells. * test(integration): expect a 400 for an empty-string tools field on /v1/messages Real Anthropic rejects tools "" with a 400 on main too, so the case joins the malformed tools test * fix(router): keep web search routing for tools passed as a tuple * fix(router): keep a deployment's own tools when drop_params drops a malformed request tools * test(router): list _merged_tools as covered through the deployment tools merge tests * fix(router): drop the request's tool settings with its malformed tools when deployment tools replace them * fix(router): skip a tool whose type is not a string in the web search filter instead of raising TypeError * fix(prometheus): keep deployment health metrics clean on a malformed tools rejection * test: type the new malformed tools tests * test: mark new test locals Final and type kwargs dicts (cherry picked from commit d76ec3a) * ci(cost map): classify token_count_model as an object key in the schema generator (#47057) * ci(cost map): classify token_count_model as an object key in the schema generator * ci(cost map): require non-blank token_count_model strings and test the region rules (cherry picked from commit 6e191a5) * ci(cost map): remove the generated model prices JSON schema (#47064) * ci(cost map): remove the generated model prices JSON schema Co-Authored-By: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com> * test(cost map): keep schema-independent cost map tests after dropping the schema Co-Authored-By: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com> * ci(cost map): keep the schema file until main's guard stops requiring it Co-Authored-By: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com> * ci(cost map): let bot sync PRs keep touching the schema file until it is deleted Co-Authored-By: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com> --------- Co-authored-by: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com> (cherry picked from commit ae6f7f6) * fix(count_tokens)!: answer 400 for Vertex partner models without a count API and OpenAI-shaped provider errors on /v1/responses/input_tokens (#47163) * fix(count_tokens): answer 400 for Vertex partner models without a count API and OpenAI-shaped provider errors on /v1/responses/input_tokens * fix(count_tokens): answer 400 for Vertex Mistral counts and type the input_tokens error tests Vertex has no count-tokens route for Mistral or codestral models, so they now get the same 400 as other partner models without a count API instead of a 404 that points operators at IAM. * fix(count_tokens): unwrap prefixed provider errors on /v1/responses/input_tokens * fix(count_tokens): say LiteLLM, not Vertex, cannot count a Vertex partner model * fix(count_tokens): count a Vertex partner model with its configured custom_tokenizer and unwrap prefixed flat provider errors * fix(count_tokens): keep the 400 for contents-only Vertex partner counts with a custom_tokenizer * fix(count_tokens): pass through an OpenAI provider error that omits param or code * fix(count_tokens): keep the status-based type for Anthropic count errors on the Responses route * test(count_tokens): cover the Vertex partner count gate and Responses count error shapes on a real proxy * test(count_tokens): add regression tests for the Vertex partner count gate and Responses count error shapes (cherry picked from commit ef1d395) * feat(count_tokens)!: configurable token_count_framing and token_count_model, count source in the response (#46777) * feat(count_tokens): configurable token_count_framing and token_count_fallback_model, count source in the response Count endpoints now say where each number came from in litellm_count_source (provider, fallback_model, local_estimate) and name the fallback model in litellm_count_fallback_model. When the provider answers 400 or 404 for a model it cannot count, the proxy counts the same request with token_count_fallback_model. token_count_framing adds a per-model constant to local estimates. Both settings ship in the cost map for Bedrock Claude Sonnet/Haiku 5.5, Bedrock Kimi K3, and Databricks Kimi K3 and DeepSeek V4 Flash, and can be overridden in model_info. * test(count_tokens): classify the new cost map keys in the schema generator and expect count_source in exact-shape tests * test(count_tokens): e2e matrix against real inference and integration wire tests for count source, fallback and framing * fix(count_tokens): keep the provider error when local counting is disabled, name the fallback error, keep settings in cooldown Moves the cost map lookup off the event loop * ci(cost map): bound token_count_framing to non-negative and token_count_fallback_model to non-empty * fix(count_tokens): keep a failed fallback's own status, ship fallbacks only where they count, add system.ai framing A fallback model that answers 404 returns the requested model's error unchanged, and any other fallback failure answers with its own status and message. The eu, apac, au and jp Sonnet and Haiku 5.5 entries no longer ship the Opus 5.5 fallback, which AWS serves only in us-east-1. A configured empty token_count_fallback_model turns the shipped fallback off. Config framing accepts whole-number floats and rejects negatives. The Databricks system.ai Kimi K3 and DeepSeek V4 Flash names carry the same framing as their serving endpoint names, and the e2e matrix runs on Bedrock Haiku 5.5 too. * test(databricks): list the system.ai Kimi K3 and DeepSeek V4 Flash names with their published DBU rates * fix(count_tokens): skip a token count fallback model for an hour after it answers 404 on that deployment A us. or global. Sonnet 5.5 deployment outside us-east-1 paid two extra Bedrock calls and about 200 ms on every count, since Opus 5.5 cannot count there either. The Kimi K3 e2e also runs the large system prompt shape now. * test(count_tokens): use the shared integration port allocator in the fallback wire test * fix(cost map): keep the Databricks system.ai entries to framing only, so their spend stays as today * test(count_tokens): cover the fallback 404 skip, inference profile base_model, shipped framing, and deployment-scoped token count settings Adds integration cells for a fallback model that answers 404, an application inference profile ARN deployment whose base_model carries the shipped fallback, and the shipped Kimi K3 framing with token_count_framing 0 turning it off. Adds unit tests that keep token count settings off the shared backend cost map key and that store a token count setting on PATCH only when the operator changed it * fix(count_tokens): keep the counter's own 400 and the provider's error when a framed estimate cannot read the body A 400 the OpenAI or Gemini counter returns before calling the provider is the caller's answer, so it no longer tries the fallback model or a framed estimate. When the framed local estimate cannot read a content block, the client gets the provider's error instead of a 500. Adds /audit round 2's integration tests for the fallback leg's converted body, the Anthropic envelope on fallback failures, and both framing cases. * fix(count_tokens): answer the provider's error whenever a framed estimate raises A tool schema the local estimate cannot format, such as a boolean subschema or an array with no items, raised AttributeError or KeyError and answered a 500 on a framed deployment whose provider had already answered 400. Any estimate failure now answers the provider's own error. * fix(count_tokens): load the custom tokenizer inside the guarded framed estimate A framed deployment whose custom_tokenizer could not load answered a 500 or 503 where the provider had already answered 400, because the tokenizer was selected outside the estimate's error handling. Selecting it inside answers the provider's error, logs a warning with the estimate's error, and still raises the Rust extension's fork-guard errors. * fix(count_tokens): look up framing under the deployment's custom_llm_provider * fix(count_tokens): share one tokenizer download per worker and bound the wait after a provider error A framed deployment whose custom_tokenizer is not cached locally made every count wait out the Hugging Face hub's whole retry cycle when the hub could not be reached, and a burst of those loads held the default thread limiter that every count's cost map lookup also needs. Counts on a worker now share one download per minute, a failed download is reused for the rest of that minute, and after a provider error a count waits at most 5 s before answering the provider's error. The swallowed-estimate warning logs only the error type. * fix(count_tokens): keep one tokenizer download per key running and load the local route per request * test(count_tokens): type the scripted counter and wait on events instead of wall time where possible * fix(count_tokens): run framed tokenizer loads on their own capped threads and answer a tokenizer panic with the provider error Framed loads used anyio's default 40 threads, so a hub that drops packets let about 40 hanging loads stall every count on the worker. Loads now run on a per-worker pool of 4, and a count that finds 4 loads running answers the provider's error at once. Any finished load is reused for a minute after it finishes, so a load that fell back to tiktoken is not retried on every count. A pyo3 PanicException from the tokenizer, while loading or counting, now answers the provider's error instead of a plain 500 * feat(proxy): count tokens with token_count_model in its pinned region token_count_model {model, region} replaces token_count_fallback_model. Bedrock Sonnet and Haiku 5.5 count with Opus 5.5 in us-east-1, or Melbourne for au. profiles, and a failure names the region to enable * fix(count_tokens): use the renamed count model constant in the e2e test and list token_count_model with the object keys * fix(proxy): keep the upstream error envelope when adding the region hint * test(proxy): annotate the token count setting echo test * ci(cost map): require non-blank token_count_model strings and test the region rules * fix(count_tokens): answer the token_count_model's error even when framing is set * fix(count_tokens): keep the provider error for Google contents instead of a framed estimate * fix(count_tokens): estimate Google contents the route translated to messages * fix(count_tokens): keep the provider error for Google contents with non-text parts * test(proxy): drive tokenizer wait and cost map tests by events and a skippable loop clock * fix(count_tokens): check Google text-only parts without a KeysView comparison basedpyright flags * feat(proxy): count Bedrock Kimi K3 tokens exactly with its pinned tokenizer * test(bedrock): keep the Kimi K3 image check in-process * fix(count_tokens): join the region hint to an upstream message that already ends with a period Also pins that a blank token_count_model in config falls through to the cost map default * fix(count_tokens): count Gemini tool-call turns and Responses tools, and stop tokenizer retries from stalling counts The Google countTokens route estimates contents with functionCall, functionResponse and thoughtSignature parts again, and still answers the provider error for media, thought and unknown parts The Kimi K3 exact count renders Responses API and Anthropic tools through the chat tool translation the Vertex count already used, now shared from the prompt factory, and falls back to the estimate when the Converse body cannot carry a tool A failed Kimi K3 tokenizer load is retried in the background without making counts wait, and a load still running after the wait logs a warning * fix(count_tokens): count Kimi K3 tools the way Bedrock inference sends them A flat Responses API function or custom tool becomes the chat tool the Responses route sends to inference, and every other tool goes to the Converse body as is, so hosted tools Bedrock drops are left out of the count instead of being counted or turning it into an estimate. * test(count_tokens): annotate new token counter test locals with Final * fix(count_tokens): keep shipped count regions inside the deployment's geography A plain Bedrock Sonnet or Haiku 5.5 deployment in a non-US region no longer sends its count prompt to us-east-1. Global count models and configured token_count_model keep their pinned region. Also expect litellm_count_source in the Vertex Llama count test main added * fix(count_tokens): resolve count settings off the event loop (cherry picked from commit 75faaea) --------- Co-authored-by: Mateo Wang <277851410+mateo-berri@users.noreply.github.com> Co-authored-by: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com>
TLDR
Problem this solves:
/v1/messages/count_tokensanswers 500 to a non-listtoolsand drops the connectiongenerateContentanswer 500 to"tools": 5tooHow it solves it:
toolsanswer 400invalid_request_errorfor a malformed onetoolsskip a malformed oneIntentional product change: a falsy
tools({},"",false,0) that answered 200 on OpenAI chat,/v1/responses,generateContentand/v1/messagesfor non-Claude models now answers 400 withoutdrop_params. A client that sends one should drop the field or turn ondrop_paramsUser Flow
Before: a malformed
toolsgets a 500 and a dropped connection"tools": 5Connection reset by peerAfter: the same body answers a clean 400 and the connection stays open
"tools": 5invalid_request_errornamingtoolsPre-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).
Decisions
The chat,
/v1/responses,/v1/messagesand count_tokens routes answer 400invalid_request_errorwithparam: toolsto a malformed one, like OpenAIUnder
drop_params, read as core reads it, only the bad entries drop, sotool_choicestill worksThe LLM routes decide at the deployment the router picked, as core does
Edge decisions
Malformed means a
toolsthat is not a list, a non-object entry, afunctionthat is neither an object nornull, or aparametersorinput_schemathat is set but is neither an object nor a string holding one. An empty schema ("",[],false,0,{}) means none, as litellm's Anthropic, Gemini and Responses bridge paths already read it, and a JSON string holding an object passes on, since the OpenAI Responses path decodes itThe LLM routes read the picked deployment's own params. The 400 there is a
BadRequestErrorcarrying that deployment's provider, so a configured fallback that drops the field answers 200 unlessfallback_on_unsupported_paramsis false. The router never cools a deployment down for it and the dynamic rate limiter does not count it, since litellm rejected the request before calling one. For the same reason its Prometheus deployment metrics carry noapi_baseor deployment id and never mark the deployment down. Its failure log, spend row and the request-levellitellm_llm_api_failed_requests_metricname the picked deployment's id with an emptyapi_baseA
vector_store_idsthat is neither a list nornullis a malformed entry. A non-objectweb_search_optionsgets the same 400, andnullmeans noneA request's own
additional_drop_paramsreplaces the deployment's list and routerdefault_litellm_paramsfill in what the request leaves out, as core merges them.drop_paramsresolves the same way. Anadditional_drop_paramslist with a non-string entry still names the strings in it, as core reads itToken counting never calls a deployment, so it reads the deployments the model names. It rejects when none drops the field, drops when all do, and forwards unchanged when they disagree or the model names no deployment it can read (a team model name, a comma batch, an auto router), as on main
The router's web search filter and deployment tool merge skip a non-list
tools, so it reaches the check instead of crashing there. When the drop policy drops it and the deployment sets its owntools, the request's other tool settings drop with it, so the deployment'stoolsandtool_choicego out as if the request sent none, and the model can call a tool the client never sent. Chat guardrails only get a listA falsy
tools({},"",false,0) answered 200 on OpenAI chat,/v1/responses,generateContentand/v1/messagesfor non-Claude models and now answer 400 withoutdrop_params. A group whose deployment sets its owntoolsreads one as no tools, as on mainVector store auth reads every string id in a malformed
vector_store_ids, so it can only deny moreRejections log the route's call type, compact included, so a failure row matches its route's success rows. That convention settles the label, and #46570's dropped
intintegration case is backScreenshots / Proof of Fix
Both legs ran on a GCE box, with curl against 2 uvicorn workers with their own Postgres database, a vector store and Anthropic
claude-haiku-5-5, configs in this gist33b73207e3)f34b58a51b)5, then /v1/messages"","xxxxx",["get_weather"]5,drop_params: true5, 3 LLM routes5/v1/responses/input_tokensgenerateContenttypeEdge and control cases
33b73207e3)f34b58a51b)fallback_on_unsupported_params: false["get_weather"], 3 LLM routesweb_search_options: nulldrop_params: "true"{},false,0, then droppedtool_choice, droppedfailure, call typeweb_search_options: 5, then droppedadditional_drop_paramsvector_store_ids: nullacompact_responses55rejectmodel_idAK ran on a second proxy per leg whose config only adds
router_settings.fallback_on_unsupported_params: false, and AO on a third whose config only addslitellm_settings.callbacks: ["prometheus"]A. count_tokens with tools 5, then /v1/messages on the same connection
Before at
33b73207e3After at
f34b58a51bB. count_tokens with the other malformed tools values
Both legs' commands and output are in
gist_case_b.mdof the gistC. drop_params true drops malformed tools, compared with no tools
Both legs' commands and output are in
gist_case_c.mdof the gistD. a wrong key with malformed tools or web_search_options
Both legs' commands and output are in
gist_case_d.mdof the gistE. tools 5 on the three LLM routes, one keep-alive connection
Both legs' commands and output are in
gist_case_e.mdof the gistE2. tools ["get_weather"] on the three LLM routes
Both legs' commands and output are in
gist_case_e2.mdof the gistE3. tools 5 with drop_params true on the three LLM routes
Both legs' commands and output are in
gist_case_e3.mdof the gistF. control, well-formed tools on count_tokens and /v1/messages
Both legs' commands and output are in
gist_case_f.mdof the gistG. a key whose allowed_tools is ["get_weather"], tools 5 on count_tokens then /v1/chat/completions on one connection
Both legs' commands and output are in
gist_case_g.mdof the gistG control. the same key still rejects a tool outside its allowlist
Both legs' commands and output are in
gist_case_g_control.mdof the gistH. a key limited to vs_qa_count_tokens_store asks for another store as a string, then in a list with a non-string
Both legs' commands and output are in
gist_case_h.mdof the gistI. web_search_options null with a valid key on /v1/chat/completions
Both legs' commands and output are in
gist_case_i.mdof the gistJ. tools 5 on /v1/responses/input_tokens
Both legs' commands and output are in
gist_case_j.mdof the gistK. Claude Code's user agent sends tools 5 to /v1/messages without drop_params
Both legs' commands and output are in
gist_case_k.mdof the gistL. drop_params as the string "true" with tools 5 on the three LLM routes
Both legs' commands and output are in
gist_case_l.mdof the gistM. falsy non-list tools on the three LLM routes, without and then with drop_params
Both legs' commands and output are in
gist_case_m.mdof the gistN. tools 5 with a tool_choice and drop_params true on the three LLM routes
Both legs' commands and output are in
gist_case_n.mdof the gistO. tools 5 on Gemini generateContent
Both legs' commands and output are in
gist_case_o.mdof the gistP. a model group whose deployment sets drop_params true, tools 5 without drop_params in the request
Both legs' commands and output are in
gist_case_p.mdof the gistR. a wrong key with tools 5 on the three LLM routes
Both legs' commands and output are in
gist_case_r.mdof the gistS. a key limited to vs_qa_count_tokens_store names that store in malformed vector_store_ids
Both legs' commands and output are in
gist_case_s.mdof the gistT. call_type on the spend log rows of rejected tools 5 requests
Both legs' commands and output are in
gist_case_t.mdof the gistV. one bad entry next to a good tool, tool_choice required, drop_params true
Both legs' commands and output are in
gist_case_v.mdof the gistW. web_search_options 5 on /v1/chat/completions, without and then with drop_params
Both legs' commands and output are in
gist_case_w.mdof the gistX. tools 5 with additional_drop_params ["tools"] on the three LLM routes
Both legs' commands and output are in
gist_case_x.mdof the gistY. Claude Code's user agent sends tools 5 to /v1/messages/count_tokens
Both legs' commands and output are in
gist_case_y.mdof the gistZ. tools 5 on /v1/responses/compact and /v1beta/interactions
Both legs' commands and output are in
gist_case_z.mdof the gistAA. a tool whose schema is a string on the three LLM routes
Both legs' commands and output are in
gist_case_aa.mdof the gistAB. /v1/responses/input_tokens with tools "not-a-list", without and then with drop_params
Both legs' commands and output are in
gist_case_ab.mdof the gistAC. a key limited to vs_qa_count_tokens_store sends a string vector_store_ids to /v1/messages
Both legs' commands and output are in
gist_case_ac.mdof the gistAD. Responses websocket, response.create with tools 5, then with a good tool
Both legs' commands and output are in
gist_case_ad.mdof the gistAE. a tool entry carrying "vector_store_ids": null next to a good tool
Both legs' commands and output are in
gist_case_ae.mdof the gistAF. a request's own additional_drop_params list replaces the deployment's, which drops tools
Both legs' commands and output are in
gist_case_af.mdof the gistAG. call_type on the spend log row of a rejected /v1/responses/compact with tools 5
Both legs' commands and output are in
gist_case_ag.mdof the gistAH. a group with fallbacks to a group that drops tools, one tool with a string schema
Both legs' commands and output are in
gist_case_ah.mdof the gistAI. count_tokens on a group that drops tools and has fallbacks, tools 5
Both legs' commands and output are in
gist_case_ai.mdof the gistAJ. tools whose schema is empty or a JSON string, on the three LLM routes
Both legs' commands and output are in
gist_case_aj.mdof the gistAK. fallback_on_unsupported_params false, tools 5 to a group whose fallback drops tools
Both legs' commands and output are in
gist_case_ak.mdof the gistAL. tools 5 to a group whose fallback cools down on any 400, then well-formed calls to that fallback
Both legs' commands and output are in
gist_case_al.mdof the gistAM. a drop_params deployment that sets its own tools, request tools 5
Both legs' commands and output are in
gist_case_am.mdof the gistAN. a tool whose type is an object or a list, on the three LLM routes
Both legs' commands and output are in
gist_case_an.mdof the gistAO. Prometheus deployment metrics after a tools 5 rejection on /v1/chat/completions
$PORThere is a third proxy from the same tree, whose config only addslitellm_settings.callbacks: ["prometheus"]. It ran with 2 workers and its ownPROMETHEUS_MULTIPROC_DIR, so/metricsreads both workersBefore at
33b73207e3After at
f34b58a51bBefore at
33b73207e3After at
f34b58a51bBefore at
33b73207e3After at
f34b58a51bObservations from this run
type400 leaks a traceback, pre-existingserver_error, unchangedexception_classnames Anthropic, from this PRIntegration files at 8d3e2c0, c6f2fd7 and 9f5bb1c
At 9f5bb1c the malformed
toolswire file ran again with its new case, a drop group that sets its own toolsEarlier runs
The 467 include
test_messages_count_tokens_rejects_malformed_tools_without_calling_either_peer[int]. The one failure istest_worker_sigkill_mid_burst_leaves_the_sibling_counting, whose proxy missed its boot deadline on a loaded box. A second run at c6f2fd7 covers it again, with the caller tools file this PR edits and main's new tests that sendtoolsThe sigkill test, both pass-through credential tests and
[empty_string]pass there.tests/integration/mcp/test_interactions.pyruns in the requiredunitcheck's mcp-elicitation shardAudit round 4 of 3 at 5407d21, past the cap, FAIL on G3b only
Round 4 ran past the 3-round cap because round 3 found collateral 200-to-400 rows (RR4, UC2), which 294bced fixed. Base f14475e, head run twice with seed 46583 and one order. Both head runs collected the same 406 ids and failed the same 7, all in G3b. RR4, UC2, the 22 new B1 bridge cells and every well-formed cell are green twice. The full matrix and the G3b root cause are
audit_r4.mdin this gistG3b's 7 cells answer exactly what main answers, so it ships as the Medium caveat with its fix on a follow-up ticket. Of the 5 control reds, two are proxy boot timeouts on a loaded box that pass alone. A budget reset sweep test and an MCP test whose helper imports a class main's pinned
mcpremoved are red on the base too. The fifth is main's newtest_an_empty_string_tools_field_reaches_claude_as_sent, which pinned atools: ""that real Anthropic rejects with 400. It is now theempty_stringcase of the malformedtoolstest, red on the base and green on the head/live-pr-risk round 12 at f34b58a, PASS
PASS. The merge resolution in count_tokens is correct. It computes
auto_drop_paramsonce from"drop_params" in dataand both_token_count_fieldsand_count_tokens_body_optionsread the same value, so a Claude Code request with a malformed tool and an invalid context edit counts with both dropped, and an explicitdrop_params: falseturns both drops off. None of the main commits between the old base 2dc6aaf and the new base 33b7320 breaks on the PR's paths. All 31 cells answer the same as base or move from a base 500 or 400 to the 400 or 200 the PR names. The four head integration lanes pass 703 of 703. Every finding is Low, and none of them makes a request that worked on base fail on headRig. Base is the merge base 33b7320, head is f34b58a. Both ran on the GCE box through
remote_rig.pykind ab, each side with its own tree's.venv, its own fresh Postgres database, random free ports,--num_workers 2and its ownPROMETHEUS_MULTIPROC_DIR. Each proxy asserted its own tree'slitellm.__file__at launch. Real OpenAIgpt-5.4-mini, Anthropicclaude-haiku-5-5and Geminigemini-3.8-flash(the latest of each family) sat behind forwarding recorders on both sides. The same 31 cells ran in the same order throughremote_rig.py exec, with no tunnel. No provider answered 429What was re-walked. The new code from the merge resolution, which is the single
auto_drop_paramsvalue incount_tokensand its two readers. Main's edits to files the PR changes, which are #46843 (f8217d2a03, Gemini count_tokens context_management inendpoints.py), #41127 (7930c0e434, mid-stream continuation and_set_retry_policyinrouter.py), #43667 (86a91f35de, MCP auto-execute round billing inproxy/utils.pyandutils.py), #44939 (859529ccbc, a realtimedrop_paramsargument inutils.py) and #46156 (f81e657903, a video config lookup inutils.py). Also #44199 (d5ce7dbb8c, spend rowsession_id), because the PR's rejection writes a failure spend row that it now labels. #44939 and #46156 were traced only. The PR diff has no realtime or video code, and both edits are new branches in provider config lookups that the tool resolver never callsWhat carried from round 11 without a re-run, because no main commit in the range changed them or their readers. Prometheus deployment state and cooldown on a rejection (re-read here anyway and unchanged), the web search filter, vector store parsing, guardrail translation,
/cursorchat, embeddings forwarding, key lifecycle and the over-reach cells for real provider 400, 401 and 500. /qa's 42 cases (A to AO) were not redoneBreaking
None. Every cell ran on both sides. Where head differs, base answered 500 (or a 400 after a crash in tool parsing) and head answers the 400 or 200 that the PR names. The full cell table is under Commands and outputs
Backward incompatible
The fix itself, unchanged from round 11. A malformed tool entry is a local 400
tools.N: Input should be a valid dictionarywith no provider call, or it is dropped when every candidate deployment drops it. On count_tokens this now also holds for Gemini and Anthropic under the Claude Code auto drop (c3 head 200 with 6119 tokens and all 3 files kept, c12 head 200 with one Anthropic call carryingtools=1)A chat rejection no longer burns the router's default retries. c10 is a 400 on both sides, base in 3874 ms and head in 46 ms, and neither side calls OpenAI. A configured
BadRequestErrorRetriesstill retries it (c8, base 4394 ms, head 4727 ms, no provider call on either side), so a group with a retry policy pays about 4.7 s of backoff before the same 400On a group whose deployments disagree on
drop_params, the answer depends on which deployment the router picks. Without a retry policy, gem-mixed answered three different ways over three identical/v1/messagescalls on head. c6m1 picked the dropping deployment and forwardedtools=1, while c6m2 and c6m3 picked the other one and got the 400. WithBadRequestErrorRetries: 2, all three gpt-retry-mixed calls answered 200 (c9a to c9c), and two of them showx-litellm-attempted-retries: 1after a first pick rejected locally. Those two local rejections still add 2 tolitellm_deployment_failure_responses_total{model_group="gpt-retry-mixed",model_id=""}for requests the client saw as 200. Base answered every one of these 500 or 400, so nothing that worked before now failsRegression risk
Low, count_tokens on a wildcard group does not see the deployment's
drop_params._counted_drop_policiesfinds no named deployment forgemini/gemini-3.8-flashundergemini/*, so it falls back to the request's own policy. c5 and c5b answer 400tools.1on head, while/v1/messageson the same wildcard drops the entry (c5m forwardedtools=1). Main's context path from #46843 does see wildcards throughget_routable_deployments. Base answers 500 on all three, so this is a gap and not a regressionLow, a string
"true"drops tools but not invalid context edits on count_tokens. The PR'sdrop_policyreads it throughnormalize_drop_params, while main's_count_context_managementchecksdrop_params is True. c4 (string"true", bad tool, compact under minimum) answers 400compact_20260112.trigger.value must be at least 50000 tokenson head, and c4b with a valid edit answers 200 with 2156 tokens. Base answers 500 on both. Theis Trueside is main's code and was traced, not run in isolationLow, a Codex user agent gets the auto drop on
/v1/responsesbut not on/v1/responses/input_tokens. c11b answers 200 on head withtools=1on the wire, and c11 with the same body oninput_tokensanswers 400tools.1. Base answers 400 on both, and main did not changeinput_tokensin this rangeLow and already on base, not caused by this PR. A Gemini deployment with a custom
api_baseanswers 404 on/v1/messageson both sides, because inference builds{api_base}/models/...:generateContentwithout/v1betawhile count_tokens builds{api_base}/v1beta/models/...:countTokens. c7m is a 404 on both sides with identical wire. It made c5m and c6m1 end in a 404 after the PR's drop, and the wire still shows the dropped entry. It is worth its own SLP ticketNot reached by this delta. #41127 continuation after a partial stream, when the retried attempt hits the PR's rejection, needs a mid-stream fault. Its integration file passed at head with valid tools only. The same holds for #45136 (
8bb8ac7f18, on main after the base), which logs a superseded/v1/messagesstream attempt as a failureDependency graph
auto_drop_paramsin count_tokens_token_count_fields_count_tokens_body_options_set_retry_policy, update pathsession_id/metricsutils.pylookupsNot verified
No provider 429 was produced. The mid-stream fault cases for #41127 and #45136 were not run, since they need fault injection after a partial stream. Provider budgets (B1) and background interaction settlement (B2) ran only as integration tests, not as A/B cells. The SDK Router with deployment tools (S1) is covered by unit tests only. The
_set_retry_policyupdate path was traced, and the cells used the config init path. Slack alerting was not run. The scenarios were not re-run on a merged treeCommands and outputs
Count tokens cells, Gemini unless named.
[good, 5]is a validread_filetool plus the bare integer5[good, 5], clear[good, 5], cleartools.1[good, 5], bad compact[good, 5]tools.1"true",[good, 5], bad compact"true",[good, 5], clear[good, 5], cleartools.1[good, 5], bad compacttools.1[good, 5], cleartools.1[good, 5]Inference cells
[good, 5]tools=1senttools=1senttools.1tools.1tools=1sent55, dropThe merge resolution, read from the wire. c1 on head sent one
countTokenscall with one function declaration, and only one of the three tool results kept its text, so the drop and the clear edit both applied. c3 on head kept all three files, so the invalid compact edit was dropped along with the bad toolSpend rows and sessions. c10's failure row carries
session_idlpr12-sess-rejecton both sides, and c10b's row is a failure on base and a success on head, both underlpr12-sess-drop. The MCP cells bill the same way on both sides. m2 on head and m3 on both sides each wrote onearesponsesrow at 0.00031575 and 276 tokens, plus the MCP list and call rows, and round 2's input is identical after normalizing ids, with the tool output"5"Prometheus. Head rejections write
litellm_deployment_failure_responses_totalwith emptyapi_base,litellm_model_nameandmodel_id, and nolitellm_deployment_statesample. The only state and cooldown series on head come from the real Gemini 404s, which base writes the same way for its own 404. The request-levellitellm_proxy_failed_requests_metric_totalstill names the pickedmodel_id, as round 11 foundWire totals, including 10
GET /v1/modelscalls per side at startup. Base has OpenAI 13, Anthropic 1 and Gemini 2. Head has OpenAI 20, Anthropic 2 and Gemini 7. Every extra head call is a drop path that answered where base crashed, which is c9a to c9c, c10b, c11b and m2's two rounds on OpenAI, c12 on Anthropic, and c1, c3, c4b, c5m and c6m1 on GeminiTests at head. The legacy integration round ran the lanes that reach this delta, with
--base-on-head-reds. Head had no reds, so no base step ranMerge ref.
origin/mainis at 6530b32, 10 commits past the base. #45136 touchesrouter.pyand #44021 touchesutils.py, which are both files this PR changes.git merge-tree --write-tree f34b58a51b origin/mainis clean (tree b85bc3ef20). The scenarios were not re-run on a merged tree/live-pr-risk rounds 10 and 11 at d1e28ab and c557652, FAIL then PASS
Round 10 found a breaking item that c557652 fixed, and round 11 passed at c557652. Both write-ups are in
live_pr_risk_round_10.mdandlive_pr_risk_round_11.mdof the gist/live-pr-risk rounds 8 and 9 at d980697 and 23ed001, FAIL then PASS
Round 8 found one breaking item. A request with a malformed
toolsand atool_choicenaming one of its own tools, sent under a drop policy to a group that sets its owntools, went out at d980697 with the group's tools and the request'stool_choice, and the provider answered 400. 23ed001 drops the request's other tool settings with itstools, so the group'stoolsandtool_choicego out as if the request sent none (AM). Round 9 drove the same cells on main, d980697 and 23ed001 and found nothing that works on main breakingNothing is backward incompatible against main, which failed these requests before calling a provider. Against the earlier tips, a group that sets its own
toolsnow sends them in place of a malformed requesttoolsunder a drop policy, so the model can call a tool the client never sent, and the group's owntool_choicewins over the request's,noneincluded. The SDKRouternow sends the group's tools where it senttools: []Round 9 also found two gaps, both in the Low caveats with fixes on follow-up tickets. A falsy
toolson a group that sets its owntoolsreads as no tools, as on main. SDK calls made without the proxy and/v1/completionsskip the check, so a malformedtoolsgoes out as[]where main crashed. Merging main into 23ed001 conflicted only in the count_tokens endpoint's imports, and QA and the malformedtoolswire file ran again on the merged tip 9f5bb1c/live-pr-risk round 6 at c6f2fd7, FAIL, fixed in dba5a72
Round 6 found one breaking item. The web search deployment filter read only a list
tools, so an SDKRoutercall passing a tuple with a web_search tool could pick a deployment without web search, 6 of 8 calls at c6f2fd7 and none on main. dba5a72 reads a tuple too, and a re-run at dba5a72 sent all 8 tuple calls to the web search deployment, as main does. Round 6 also found the falsytoolscaveat missed/v1/messagesfor non-Claude models, now named, and the dynamic rate limiter change, now a decision/live-pr-risk round 5 at 5407d21, FAIL, fixed in b2c8553
Round 5 found three breaking items in the new 400, all fixed in b2c8553. First, shapes litellm's providers already repaired got a 400: a tuple of tools from the SDK, an empty schema, and a JSON string schema the OpenAI Responses path decodes. They pass again (AJ). Second, the 400 named no provider, so
fallback_on_unsupported_params: falsestill fell back. It now names the picked deployment's provider (AK). Third, a malformed request on a fallback hop cooled down a healthy deployment set to cool on any 400. The router now never cools a deployment for it, on any hop (AL). A deployment whose own config setstools: ""still answers 400, under the falsytoolscaveatThe backward incompatible items are the fix itself. Crashes that were a 500 are a 400
BadRequestErrorwith a coarserparam, and aretry_policywithBadRequestErrorRetriesstill retries it, now with no provider call. The failure callback, spend log row, Prometheus labels and Slack alert of a rejected request carry noapi_baseor deployment id, since no deployment was called. Fallbacks skip the primary's provider call/live-pr-risk round 4 and /audit round 3 at f447559, FAIL, fixed in 294bced
f447559 still read the requested group at the proxy. Fallbacks set in a key's or team's
router_settingsand auser_configmodel named like a group answered 200 on main, where the deployment that served dropstools, and 400 at f447559. 294bced moves the LLM-route decision into core's deployment hook, so it reads the params of the deployment the router actually picked, and a 400 there is a normalBadRequestErrorthe router falls back on. Context window and content policy fallbacks were flagged too, but a livegpt-5.4-minicall with a long prompt and a bad tool answers 400 on the tool schema before the context length check, so a real provider never reaches those fallbacks on main eitherEarlier rounds at 32a570e and 38ffa02 found router defaults, deployment ids, fallbacks, the complexity router, model strings, aliases, comma batches and team model names, all covered by the same move. The call type change also moves what reads that label. The daily spend endpoint key, Langfuse trace names (
litellm-acompletiontolitellm-anthropic_messages), OTELgen_ai.operation.name, the Datadog, Arize, mlflow and logfire span kinds, and cache analytics grouping now follow the route's call type, as they already do for that route's successesType
🐛 Bug Fix
Caveats (if any)
Medium
toolsbehind adefault_onpre_call guardrail still answers 500 on three routes, as on main, with a fix on a follow-up ticketLow
toolsgoes 200 to 400 on four routes, per thedrop_paramsconvention from feat(bedrock): serve gpt-5.6+ chat completions natively by default, with chat_completions/ opt-in for gpt-oss and grok #40775/v1/completionssend a malformedtoolsas[], where main crashed, with a fix on a follow-up ticket/v1/responsesrejects a badfile_searchentry beforedrop_params, as on maintool_choicenaming a dropped tool gets the provider's 400/v1/embeddingsforwards a malformedtools, where main answered 500toolson a rerouted request answers 400 when the deployment that serves keeps it/v1/responses/input_tokensanswer 400 where inference drops the entryAnalyze (python)job hits a query size limit, as on other PRs (run)osv-scanjob is red on an advisory that build(deps): bump claude-agent-sdk to 0.2.165 to unblock osv-scan #46971 fixed on main after this branch's last mergeFinal Attestation
The tests check the right things, including the edge cases, and regressions in the respective real-world customer use-cases are not possible after this PR
f34b58a passes /audit (cap: G3b shipped as a caveat, fix on a follow-up ticket)
c557652 passes /live-pr-risk
f34b58a passes /live-pr-risk
Bugbot summary