Skip to content

fix(proxy)!: answer 400 for malformed tools on count_tokens instead of crashing - #46583

Merged
mateo-berri merged 32 commits into
mainfrom
litellm_fix_count_tokens_malformed_tools
Oct 16, 2026
Merged

mateo-berri merged 32 commits into
mainfrom
litellm_fix_count_tokens_malformed_tools

Conversation

@mateo-berri

@mateo-berri mateo-berri commented Oct 15, 2026 •

Copy link
Copy Markdown
Contributor

TLDR

Problem this solves:

  • /v1/messages/count_tokens answers 500 to a non-list tools and drops the connection
  • The LLM routes and generateContent answer 500 to "tools": 5 too

How it solves it:

  • Routes taking tools answer 400 invalid_request_error for a malformed one
  • Helpers reading tools skip a malformed one

Intentional product change: a falsy tools ({}, "", false, 0) that answered 200 on OpenAI chat, /v1/responses, generateContent and /v1/messages for non-Claude models now answers 400 without drop_params. A client that sends one should drop the field or turn on drop_params

User Flow

Before: a malformed tools gets a 500 and a dropped connection

  1. A developer on a proxy with a vector store sends POST https://litellm-domain/v1/messages/count_tokens with "tools": 5
  2. It answers 500 and closes the connection
  3. Their next POST https://litellm-domain/v1/messages on that connection fails with Connection reset by peer

After: the same body answers a clean 400 and the connection stays open

  1. A developer on a proxy with a vector store sends POST https://litellm-domain/v1/messages/count_tokens with "tools": 5
  2. It answers 400 invalid_request_error naming tools
  3. Their next POST https://litellm-domain/v1/messages on that connection answers 200

Pre-Submission checklist

Please complete all items before asking a LiteLLM maintainer to review your PR

  • I have added meaningful tests
  • The handful of test files covering my change pass locally, e.g. 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 more
  • My PR passes all required CI/CD checks (e.g., lint, schema.d.ts sync check, etc.)
  • My PR's scope is as isolated as possible; it only solves 1 specific problem
  • Every automated review on my PR's latest commit has finished, and I have addressed or replied to each of its findings before requesting a maintainer review

Delays 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/messages and count_tokens routes answer 400 invalid_request_error with param: tools to a malformed one, like OpenAI

Under drop_params, read as core reads it, only the bad entries drop, so tool_choice still works

The LLM routes decide at the deployment the router picked, as core does

Edge decisions

Malformed means a tools that is not a list, a non-object entry, a function that is neither an object nor null, or a parameters or input_schema that 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 it

The LLM routes read the picked deployment's own params. The 400 there is a BadRequestError carrying that deployment's provider, so a configured fallback that drops the field answers 200 unless fallback_on_unsupported_params is 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 no api_base or deployment id and never mark the deployment down. Its failure log, spend row and the request-level litellm_llm_api_failed_requests_metric name the picked deployment's id with an empty api_base

A vector_store_ids that is neither a list nor null is a malformed entry. A non-object web_search_options gets the same 400, and null means none

A request's own additional_drop_params replaces the deployment's list and router default_litellm_params fill in what the request leaves out, as core merges them. drop_params resolves the same way. An additional_drop_params list with a non-string entry still names the strings in it, as core reads it

Token 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 own tools, the request's other tool settings drop with it, so the deployment's tools and tool_choice go out as if the request sent none, and the model can call a tool the client never sent. Chat guardrails only get a list

A falsy tools ({}, "", false, 0) answered 200 on OpenAI chat, /v1/responses, generateContent and /v1/messages for non-Claude models and now answer 400 without drop_params. A group whose deployment sets its own tools reads one as no tools, as on main

Vector store auth reads every string id in a malformed vector_store_ids, so it can only deny more

Rejections 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 int integration case is back

Screenshots / 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 gist

Case Before (33b73207e3) After (f34b58a51b)
A. count_tokens 5, then /v1/messages 500, closed 400, reused, 200
B. "", "xxxxx", ["get_weather"] 500 400
C. 5, drop_params: true 500 200
D. wrong key, malformed fields 500 or 401 401
E. 5, 3 LLM routes 500, closed 400, reused
E3. E, dropped 500, closed 200
G. allowlisted key, 5 500, closed 400, reused
J. /v1/responses/input_tokens 500 400
O. Gemini generateContent 500 400
Y. Claude Code, count_tokens 500 200
AL. fallback that cools on a 400 500, then 200 400, then 200, no cooldown
AN. object or list tool type 400 400, as on main
Edge and control cases
Case Before (33b73207e3) After (f34b58a51b)
Z. compact, interactions 500 400
AK. fallback_on_unsupported_params: false 500 400
E2. ["get_weather"], 3 LLM routes 500 or 400 400
F. well-formed tools 200 200
G control. allowlist control 403 403
H. store-limited key, other store 401 401
I. web_search_options: null 500 200
K. Claude Code user agent 500 200
L. drop_params: "true" 500 200
M. {}, false, 0, then dropped 200, 400 or 500 400, then 200
N. tool_choice, dropped 500 200
P. group drops params 500 200
R. wrong key, 3 LLM routes 500 401
S. store-limited key, malformed ids 401 400
T. rejected call's spend log none failure, call type
V. one bad entry, dropped 401 200, tool kept
W. web_search_options: 5, then dropped 500 400, then 200
X. additional_drop_params 500 200
AA. string tool schema 400 or 500 400
AB. input_tokens, then dropped 400 dump 400, then 200
AC. store-limited key, string ids 401 400
AD. websocket frame error frame error frame
AE. vector_store_ids: null 401 200
AF. request list over the group's 401 400, then 200
AG. compact rejection's log none acompact_responses
AH. bad schema, fallback group 200 200
AI. token counts with fallbacks 500 200
AJ. empty or JSON-string schema 200, 400 or 500 same codes
AM. group with its own tools drops 5 500 200, its tool
AO. Prometheus after a 5 reject 500, no outage 400, no outage or model_id

AK 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 adds litellm_settings.callbacks: ["prometheus"]

A. count_tokens with tools 5, then /v1/messages on the same connection

$ curl -sv --http1.1 http://127.0.0.1:$PORT/v1/messages/count_tokens -H "Authorization: Bearer $VK" -H "Content-Type: application/json" -d '{"model":"claude-haiku-5-5","messages":[{"role":"user","content":"Count this message"}],"tools":5}' -w '\n' --next -sv --http1.1 http://127.0.0.1:$PORT/v1/messages -H "Authorization: Bearer $VK" -H "Content-Type: application/json" -d '{"model":"claude-haiku-5-5","max_tokens":16,"messages":[{"role":"user","content":"Say hi"}]}' -w '\n' 2>&1 | grep -E "^< HTTP|Re-using|left intact|Closing connection|^\{"

Before at 33b73207e3

< HTTP/1.1 500 Internal Server Error
{ [76 bytes data]
* Connection #0 to host 127.0.0.1 left intact
{"error":{"message":"Internal server error","type":"internal_server_error"}}* Found bundle for host: 0x594e0a861b80 [serially]
* Closing connection
< HTTP/1.1 200 OK
{ [577 bytes data]
* Connection #1 to host 127.0.0.1 left intact
{"model":"claude-haiku-5-5","id":"msg_011Cg6aL2YkD6esNBThiXLa9","type":"message","role":"assistant","content":[{"type":"text","text":"Hi there! How can I help you today?"}],"container":null,"stop_reason":"end_turn","stop_sequence":null,"stop_details":null,"usage":{"input_tokens":12,"cache_creation_input_tokens":0,"cache_read_input_tokens":0,"cache_creation":{"ephemeral_5m_input_tokens":0,"ephemeral_1h_input_tokens":0},"output_tokens":14,"output_tokens_details":{"thinking_tokens":0},"service_tier":"standard","inference_geo":"global","speed":"standard"},"diagnostics":null}

After at f34b58a51b

< HTTP/1.1 400 Bad Request
{ [105 bytes data]
* Connection #0 to host 127.0.0.1 left intact
{"type":"error","error":{"type":"invalid_request_error","message":"tools: Input should be a valid list"}}* Found bundle for host: 0x58396494bb80 [serially]
* Re-using existing connection with host 127.0.0.1
< HTTP/1.1 200 OK
{ [577 bytes data]
* Connection #0 to host 127.0.0.1 left intact
{"model":"claude-haiku-5-5","id":"msg_011Cg6atxExMDV5xsVWY9Jk1","type":"message","role":"assistant","content":[{"type":"text","text":"Hi there! How can I help you today?"}],"container":null,"stop_reason":"end_turn","stop_sequence":null,"stop_details":null,"usage":{"input_tokens":12,"cache_creation_input_tokens":0,"cache_read_input_tokens":0,"cache_creation":{"ephemeral_5m_input_tokens":0,"ephemeral_1h_input_tokens":0},"output_tokens":14,"output_tokens_details":{"thinking_tokens":0},"service_tier":"standard","inference_geo":"global","speed":"standard"},"diagnostics":null}
B. count_tokens with the other malformed tools values

Both legs' commands and output are in gist_case_b.md of the gist

C. drop_params true drops malformed tools, compared with no tools

Both legs' commands and output are in gist_case_c.md of the gist

D. a wrong key with malformed tools or web_search_options

Both legs' commands and output are in gist_case_d.md of the gist

E. tools 5 on the three LLM routes, one keep-alive connection

Both legs' commands and output are in gist_case_e.md of the gist

E2. tools ["get_weather"] on the three LLM routes

Both legs' commands and output are in gist_case_e2.md of the gist

E3. tools 5 with drop_params true on the three LLM routes

Both legs' commands and output are in gist_case_e3.md of the gist

F. control, well-formed tools on count_tokens and /v1/messages

Both legs' commands and output are in gist_case_f.md of the gist

G. 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.md of the gist

G control. the same key still rejects a tool outside its allowlist

Both legs' commands and output are in gist_case_g_control.md of the gist

H. 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.md of the gist

I. web_search_options null with a valid key on /v1/chat/completions

Both legs' commands and output are in gist_case_i.md of the gist

J. tools 5 on /v1/responses/input_tokens

Both legs' commands and output are in gist_case_j.md of the gist

K. Claude Code's user agent sends tools 5 to /v1/messages without drop_params

Both legs' commands and output are in gist_case_k.md of the gist

L. drop_params as the string "true" with tools 5 on the three LLM routes

Both legs' commands and output are in gist_case_l.md of the gist

M. 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.md of the gist

N. 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.md of the gist

O. tools 5 on Gemini generateContent

Both legs' commands and output are in gist_case_o.md of the gist

P. 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.md of the gist

R. a wrong key with tools 5 on the three LLM routes

Both legs' commands and output are in gist_case_r.md of the gist

S. 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.md of the gist

T. call_type on the spend log rows of rejected tools 5 requests

Both legs' commands and output are in gist_case_t.md of the gist

V. one bad entry next to a good tool, tool_choice required, drop_params true

Both legs' commands and output are in gist_case_v.md of the gist

W. web_search_options 5 on /v1/chat/completions, without and then with drop_params

Both legs' commands and output are in gist_case_w.md of the gist

X. tools 5 with additional_drop_params ["tools"] on the three LLM routes

Both legs' commands and output are in gist_case_x.md of the gist

Y. Claude Code's user agent sends tools 5 to /v1/messages/count_tokens

Both legs' commands and output are in gist_case_y.md of the gist

Z. tools 5 on /v1/responses/compact and /v1beta/interactions

Both legs' commands and output are in gist_case_z.md of the gist

AA. a tool whose schema is a string on the three LLM routes

Both legs' commands and output are in gist_case_aa.md of the gist

AB. /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.md of the gist

AC. 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.md of the gist

AD. Responses websocket, response.create with tools 5, then with a good tool

Both legs' commands and output are in gist_case_ad.md of the gist

AE. a tool entry carrying "vector_store_ids": null next to a good tool

Both legs' commands and output are in gist_case_ae.md of the gist

AF. 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.md of the gist

AG. 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.md of the gist

AH. 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.md of the gist

AI. count_tokens on a group that drops tools and has fallbacks, tools 5

Both legs' commands and output are in gist_case_ai.md of the gist

AJ. tools whose schema is empty or a JSON string, on the three LLM routes

Both legs' commands and output are in gist_case_aj.md of the gist

AK. fallback_on_unsupported_params false, tools 5 to a group whose fallback drops tools

Both legs' commands and output are in gist_case_ak.md of the gist

AL. 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.md of the gist

AM. a drop_params deployment that sets its own tools, request tools 5

Both legs' commands and output are in gist_case_am.md of the gist

AN. 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.md of the gist

AO. Prometheus deployment metrics after a tools 5 rejection on /v1/chat/completions

$PORT here is a third proxy from the same tree, whose config only adds litellm_settings.callbacks: ["prometheus"]. It ran with 2 workers and its own PROMETHEUS_MULTIPROC_DIR, so /metrics reads both workers

$ curl -s -w '\n HTTP %{http_code}\n' http://127.0.0.1:$PORT/v1/chat/completions -H "Authorization: Bearer $VK" -H "Content-Type: application/json" -d '{"model":"claude-haiku-5-5","max_tokens":16,"messages":[{"role":"user","content":"Say hi"}],"tools":5}' | cut -c1-160

Before at 33b73207e3

{"error":{"message":"Internal server error","type":"internal_server_error"}}
 HTTP 500

After at f34b58a51b

{"error":{"message":"litellm.BadRequestError: tools: Input should be a valid list\n\nLiteLLM: model group 'claude-haiku-5-5' failed with the error above and no 
 HTTP 400
$ curl -s -o /dev/null -w ' HTTP %{http_code}\n' http://127.0.0.1:$PORT/v1/chat/completions -H "Authorization: Bearer $VK" -H "Content-Type: application/json" -d '{"model":"claude-haiku-5-5","max_tokens":16,"messages":[{"role":"user","content":"Say hi"}]}'

Before at 33b73207e3

 HTTP 200

After at f34b58a51b

 HTTP 200
$ sleep 5; curl -sL http://127.0.0.1:$PORT/metrics -H "Authorization: Bearer $LITELLM_MASTER_KEY" | grep -E '^litellm_deployment_(state|failure_responses_total)\{'

Before at 33b73207e3

litellm_deployment_state{api_base="https://api.anthropic.com/v1/messages",api_provider="anthropic",litellm_model_name="claude-haiku-5-5",model_id="ccd1feed8a4dd005739cf7b6639a779868a04e3b72e60a1489d0e88e2660b22d",pid="679925"} 0.0

After at f34b58a51b

litellm_deployment_failure_responses_total{api_base="",api_key_alias="None",api_provider="",client_ip="127.0.0.1",exception_class="Anthropic.MalformedRequestFieldError",exception_status="400",hashed_api_key="3b28cd3863024248bd60634e276255675b10df5c967a963867ff8f2034e144e4",litellm_model_name="",model_group="claude-haiku-5-5",model_id="",requested_model="claude-haiku-5-5",team="None",team_alias="None",user_agent="curl/8.5.0"} 1.0
litellm_deployment_state{api_base="https://api.anthropic.com/v1/messages",api_provider="anthropic",litellm_model_name="claude-haiku-5-5",model_id="ccd1feed8a4dd005739cf7b6639a779868a04e3b72e60a1489d0e88e2660b22d",pid="680015"} 0.0
Observations from this run
  • Object tool type 400 leaks a traceback, pre-existing
  • JSON-string schemas 500 on chat and responses, pre-existing
  • Websocket 400 frame says server_error, unchanged
  • AO's exception_class names Anthropic, from this PR
  • Router 400s append a long fallback hint, pre-existing
Integration files at 8d3e2c0, c6f2fd7 and 9f5bb1c

At 9f5bb1c the malformed tools wire file ran again with its new case, a drop group that sets its own tools

$ python3 scripts/gate_slot_lock.py .venv/bin/python tests/integration/run.py providers --workers 2 --results "$RESULTS" tests/integration/providers/test_malformed_tools_wire.py
================= 382 passed, 2 warnings in 434.45s (0:07:14) ==================

Earlier runs

$ python3 scripts/gate_slot_lock.py .venv/bin/python tests/integration/run.py providers --workers 2 --results "$RESULTS" tests/integration/providers/test_bedrock_mantle_count_tokens_wire.py tests/integration/providers/test_malformed_tools_wire.py tests/integration/providers/test_malformed_tools_chaos.py
============ 1 failed, 467 passed, 2 warnings in 908.59s (0:15:08) =============

The 467 include test_messages_count_tokens_rejects_malformed_tools_without_calling_either_peer[int]. The one failure is test_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 send tools

$ python3 scripts/gate_slot_lock.py .venv/bin/python tests/integration/run.py providers --workers 2 --results "$RESULTS" tests/integration/messages_endpoint/test_anthropic_messages_caller_tools_wire.py tests/integration/streaming/test_interception_converted_stream_options.py tests/integration/providers/test_anthropic_passthrough_wire.py tests/integration/providers/test_bedrock_mantle_count_tokens_wire.py::test_worker_sigkill_mid_burst_leaves_the_sibling_counting
================== 69 passed, 1 skipped in 443.19s (0:07:23) ===================

The sigkill test, both pass-through credential tests and [empty_string] pass there. tests/integration/mcp/test_interactions.py runs in the required unit check's mcp-elicitation shard

Audit 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.md in this gist

Row Scenario Cells Base Head 1 Head 2 Result
59 rows malformed, dropped, routed 364 red 283 green green PASS
G3a guardrail, good tools 4 green green green PASS
B1 bridge to another provider 22 green green green PASS
G3b guardrail, bad tools 16 red 16/16 red 7/16 red 7/16 FAIL, caveat
CTL controls in 5 lanes 1192 reds only 5 red, rest green not run see below

G3b'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 mcp removed are red on the base too. The fifth is main's new test_an_empty_string_tools_field_reaches_claude_as_sent, which pinned a tools: "" that real Anthropic rejects with 400. It is now the empty_string case of the malformed tools test, 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_params once from "drop_params" in data and both _token_count_fields and _count_tokens_body_options read the same value, so a Claude Code request with a malformed tool and an invalid context edit counts with both dropped, and an explicit drop_params: false turns 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 head

Rig. Base is the merge base 33b7320, head is f34b58a. Both ran on the GCE box through remote_rig.py kind ab, each side with its own tree's .venv, its own fresh Postgres database, random free ports, --num_workers 2 and its own PROMETHEUS_MULTIPROC_DIR. Each proxy asserted its own tree's litellm.__file__ at launch. Real OpenAI gpt-5.4-mini, Anthropic claude-haiku-5-5 and Gemini gemini-3.8-flash (the latest of each family) sat behind forwarding recorders on both sides. The same 31 cells ran in the same order through remote_rig.py exec, with no tunnel. No provider answered 429

What was re-walked. The new code from the merge resolution, which is the single auto_drop_params value in count_tokens and its two readers. Main's edits to files the PR changes, which are #46843 (f8217d2a03, Gemini count_tokens context_management in endpoints.py), #41127 (7930c0e434, mid-stream continuation and _set_retry_policy in router.py), #43667 (86a91f35de, MCP auto-execute round billing in proxy/utils.py and utils.py), #44939 (859529ccbc, a realtime drop_params argument in utils.py) and #46156 (f81e657903, a video config lookup in utils.py). Also #44199 (d5ce7dbb8c, spend row session_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 calls

What 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, /cursor chat, 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 redone

Breaking

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 dictionary with 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 carrying tools=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 BadRequestErrorRetries still 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 400

On 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/messages calls on head. c6m1 picked the dropping deployment and forwarded tools=1, while c6m2 and c6m3 picked the other one and got the 400. With BadRequestErrorRetries: 2, all three gpt-retry-mixed calls answered 200 (c9a to c9c), and two of them show x-litellm-attempted-retries: 1 after a first pick rejected locally. Those two local rejections still add 2 to litellm_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 fails

Regression risk

Low, count_tokens on a wildcard group does not see the deployment's drop_params. _counted_drop_policies finds no named deployment for gemini/gemini-3.8-flash under gemini/*, so it falls back to the request's own policy. c5 and c5b answer 400 tools.1 on head, while /v1/messages on the same wildcard drops the entry (c5m forwarded tools=1). Main's context path from #46843 does see wildcards through get_routable_deployments. Base answers 500 on all three, so this is a gap and not a regression

Low, a string "true" drops tools but not invalid context edits on count_tokens. The PR's drop_policy reads it through normalize_drop_params, while main's _count_context_management checks drop_params is True. c4 (string "true", bad tool, compact under minimum) answers 400 compact_20260112.trigger.value must be at least 50000 tokens on head, and c4b with a valid edit answers 200 with 2156 tokens. Base answers 500 on both. The is True side is main's code and was traced, not run in isolation

Low, a Codex user agent gets the auto drop on /v1/responses but not on /v1/responses/input_tokens. c11b answers 200 on head with tools=1 on the wire, and c11 with the same body on input_tokens answers 400 tools.1. Base answers 400 on both, and main did not change input_tokens in this range

Low and already on base, not caused by this PR. A Gemini deployment with a custom api_base answers 404 on /v1/messages on both sides, because inference builds {api_base}/models/...:generateContent without /v1beta while 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 ticket

Not 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/messages stream attempt as a failure

Dependency graph

Dependent Entry Status
auto_drop_params in count_tokens c3, c3b, c3c, c3d verified live
_token_count_fields count_tokens, Gemini verified live
_count_tokens_body_options count_tokens, Gemini verified live
#46843 context edits c1, c3, c4, c4b verified live
Anthropic count path c12, c12b verified live
wildcard deployment policy c5, c5b, c5m live, Low gap
mixed group policy c6, c6m1 to c6m3 live, pick dependent
retry policy, init path c8, c9a to c9c verified live
_set_retry_policy, update path update_settings traced only
#44199 spend session_id c10, c10b, c10c verified live
#43667 MCP round billing m1, m2, m3 verified live
Codex auto drop c11, c11b live, Low gap
Prometheus failure and state /metrics verified live
#41127 continuation integration lane tested, valid tools only
#44939 realtime, #46156 video utils.py lookups traced, unreachable
B1 budgets, B2 background integration lanes tested only
S1 SDK Router tools unit tests tested only

Not 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_policy update 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 tree

Commands and outputs

Count tokens cells, Gemini unless named. [good, 5] is a valid read_file tool plus the bare integer 5

Cell Request Base Head
c1 gem-drops, [good, 5], clear 500 200, 2155
c2 gem, [good, 5], clear 500 400 tools.1
c3 Claude Code, [good, 5], bad compact 500 200, 6119
c3b Claude Code, good, bad compact 200, 6122 200, 6122
c3c Claude Code, false, bad compact 400 compact 400 compact
c3d Claude Code, false, [good, 5] 500 400 tools.1
c4 "true", [good, 5], bad compact 500 400 compact
c4b "true", [good, 5], clear 500 200, 2156
c5 wildcard, [good, 5], clear 500 400 tools.1
c5b wildcard, [good, 5], bad compact 500 400 tools.1
c6 gem-mixed, [good, 5], clear 500 400 tools.1
c7 string schema, clear 400 400
c12 claude, Claude Code, [good, 5] 500 200, 8141
c12b claude, good, clear 200, 8144 200, 8144

Inference cells

Cell Request Base Head
c5m messages, wildcard, [good, 5] 500 404, tools=1 sent
c6m1 messages, gem-mixed 500 404, tools=1 sent
c6m2, c6m3 messages, gem-mixed 500 400 tools.1
c7m messages, string schema 404 404
c8 chat, gpt-retry 400, 4394 ms 400, 4727 ms
c9a to c9c chat, gpt-retry-mixed 400 x3 200 x3
c10 chat, gpt, session 400, 3874 ms 400, 46 ms
c10b chat, gpt-drops, session 400 200
c10c chat, gpt, good tool 200 200
c11 input_tokens, Codex 400 400 tools.1
c11b responses, Codex 400 200, tools=1 sent
m1 responses, MCP + 5 400, 4 s 400, 44 ms
m2 responses, MCP + 5, drop 400 200, 2 rounds
m3 responses, MCP only 200, 2 rounds 200, 2 rounds

The merge resolution, read from the wire. c1 on head sent one countTokens call 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 tool

=== c1_count_gem_drops_bad_tool_clear
  base: 500 152ms err: 1 validation error for TokenCountRequest tools.1 Input should be a valid dictionary [type=dict_type, input_value=5, input_type=int]
  head: 200 1536ms input_tokens=2155
      wire gem: POST /v1beta/models/gemini-3.8-flash:countTokens status=200 keys=['generateContentRequest']
=== c4_count_gem_strtrue_bad_compact
  base: 500 14ms err: 1 validation error for TokenCountRequest tools.1
  head: 400 7ms err: context_management.compact_20260112.trigger.value must be at least 50000 tokens
=== c5_count_wildcard_bad_clear
  base: 500 13ms err: 1 validation error for TokenCountRequest tools.1
  head: 400 14ms err: tools.1: Input should be a valid dictionary

Spend rows and sessions. c10's failure row carries session_id lpr12-sess-reject on both sides, and c10b's row is a failure on base and a success on head, both under lpr12-sess-drop. The MCP cells bill the same way on both sides. m2 on head and m3 on both sides each wrote one aresponses row 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"

=== c9a_chat_gpt_retry_mixed_bad
  base: 400 52ms err: Invalid request format: 'int' object has no attribute 'get'
      spend: call=acompletion group=gpt-retry-mixed status=failure spend=0 tokens=0
  head: 200 1273ms chat text='ok' hdr={'x-litellm-attempted-retries': '1', 'x-litellm-max-retries': '2', 'x-litellm-model-id': 'af384e35...'}
      wire oai: POST /v1/chat/completions status=200 tools=1 messages=1
=== m2_responses_mcp_bad_drop
  base: 400 5495ms err: Invalid request format: 'int' object has no attribute 'get'
  head: 200 6009ms
      wire oai: POST /v1/responses status=200 tools=1 input_items=str keys=['model', 'stream']
      wire oai: POST /v1/responses status=200 tools=1 input_items=3 keys=['model', 'previous_response_id', 'stream']

Prometheus. Head rejections write litellm_deployment_failure_responses_total with empty api_base, litellm_model_name and model_id, and no litellm_deployment_state sample. 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-level litellm_proxy_failed_requests_metric_total still names the picked model_id, as round 11 found

head litellm_deployment_failure_responses_total{api_base="",exception_class="Openai.MalformedRequestFieldError",litellm_model_name="",model_group="gpt-retry-mixed",model_id=""} 2.0
head litellm_deployment_failure_responses_total{api_base="",exception_class="Gemini.MalformedRequestFieldError",litellm_model_name="",model_group="gem-mixed",model_id=""} 2.0
head litellm_deployment_cooled_down_total{api_base="http://127.0.0.1:22042",exception_status="404",litellm_model_name="gem",...} 1.0
(no litellm_deployment_state line with exception MalformedRequestFieldError on either side)

Wire totals, including 10 GET /v1/models calls 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 Gemini

Tests 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 ran

$ remote_rig.py round --name slp1084lpri --base-on-head-reds lanes.json
providers   head exit=0  573 collected, 573 passed   (mid-stream continuation, fake stream reasoning, Vertex and Bedrock Mantle count_tokens wire, malformed tools wire and chaos, messages caller tools)
accounting  head exit=0  75 collected, 75 passed     (spend log caller session, background interaction settlement)
mcp         head exit=0  47 collected, 47 passed     (MCP LLM endpoints)
sdk         head exit=0  8 collected, 8 passed       (responses bridge sync reasoning, router budget limiter wire)

Merge ref. origin/main is at 6530b32, 10 commits past the base. #45136 touches router.py and #44021 touches utils.py, which are both files this PR changes. git merge-tree --write-tree f34b58a51b origin/main is 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.md and live_pr_risk_round_11.md of 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 tools and a tool_choice naming one of its own tools, sent under a drop policy to a group that sets its own tools, went out at d980697 with the group's tools and the request's tool_choice, and the provider answered 400. 23ed001 drops the request's other tool settings with its tools, so the group's tools and tool_choice go 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 breaking

Nothing is backward incompatible against main, which failed these requests before calling a provider. Against the earlier tips, a group that sets its own tools now sends them in place of a malformed request tools under a drop policy, so the model can call a tool the client never sent, and the group's own tool_choice wins over the request's, none included. The SDK Router now sends the group's tools where it sent tools: []

Round 9 also found two gaps, both in the Low caveats with fixes on follow-up tickets. A falsy tools on a group that sets its own tools reads as no tools, as on main. SDK calls made without the proxy and /v1/completions skip the check, so a malformed tools goes out as [] where main crashed. Merging main into 23ed001 conflicted only in the count_tokens endpoint's imports, and QA and the malformed tools wire 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 SDK Router call 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 falsy tools caveat missed /v1/messages for 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: false still 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 sets tools: "" still answers 400, under the falsy tools caveat

The backward incompatible items are the fix itself. Crashes that were a 500 are a 400 BadRequestError with a coarser param, and a retry_policy with BadRequestErrorRetries still retries it, now with no provider call. The failure callback, spend log row, Prometheus labels and Slack alert of a rejected request carry no api_base or 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_settings and a user_config model named like a group answered 200 on main, where the deployment that served drops tools, 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 normal BadRequestError the router falls back on. Context window and content policy fallbacks were flagged too, but a live gpt-5.4-mini call 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 either

Earlier 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-acompletion to litellm-anthropic_messages), OTEL gen_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 successes

Type

🐛 Bug Fix

Caveats (if any)

Medium

  • A malformed tools behind a default_on pre_call guardrail still answers 500 on three routes, as on main, with a fix on a follow-up ticket

Low

  • Falsy tools goes 200 to 400 on four routes, per the drop_params convention from feat(bedrock): serve gpt-5.6+ chat completions natively by default, with chat_completions/ opt-in for gpt-oss and grok #40775
  • SDK calls without the proxy and /v1/completions send a malformed tools as [], where main crashed, with a fix on a follow-up ticket
  • Every post-setup rejection logs its route's call type
  • /v1/responses rejects a bad file_search entry before drop_params, as on main
  • A Responses websocket frame skips the check and gets an error frame, as on main
  • tool_choice naming a dropped tool gets the provider's 400
  • /v1/embeddings forwards a malformed tools, where main answered 500
  • A malformed tools on a rerouted request answers 400 when the deployment that serves keeps it
  • count_tokens on a wildcard group and Codex's /v1/responses/input_tokens answer 400 where inference drops the entry
  • The optional CodeQL Analyze (python) job hits a query size limit, as on other PRs (run)
  • The optional osv-scan job 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 merge

Final 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

[!NOTE]
Medium Risk
Changes request validation, router tool merging, fallbacks, and metrics on a hot proxy path; falsy tools and drop-policy edge cases can alter which tools reach providers versus main.

Overview
Adds centralized validation for tools, related tool fields, and web_search_options, so malformed payloads are rejected or stripped before upstream calls instead of causing proxy 500s and dropped connections.

Validation and errors. New tool_fields logic validates tool lists and entries (and strict web_search_options), honors drop_params / additional_drop_params and deployment/router drop policies, and either returns cleaned kwargs or a MalformedField / raises MalformedRequestFieldError (400 invalid_request_error with param). The pre-call deployment hook runs this after a deployment is picked; token-count routes (/v1/messages/count_tokens, /v1/responses/input_tokens) resolve fields via router deployments without calling a provider.

Router and observability. Deployment tool merge skips or drops malformed request tools when policy says so, merges deployment tools safely, and avoids cooling down deployments on these client-side rejects. Prometheus treats MalformedRequestFieldError like a pre-provider reject (no deployment outage labels). Guardrails, allowlists, vector-store parsing, and built-in tool cost lookups use safe list_field / type checks so bad shapes do not crash readers.

Behavior change. Invalid non-list or structurally bad tools (and bad web_search_options) now 400 on LLM and count-token paths where they previously 500’d; with drop policies, only bad entries or fields are removed. Falsy tools values that used to pass on some routes now 400 unless dropped.

Reviewed by Cursor Bugbot for commit 0288382. Bugbot is set up for automated code reviews on this repo. Configure here.

… 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.
@devin-ai-integration

devin-ai-integration Bot commented Oct 15, 2026 •

Copy link
Copy Markdown
Contributor

I'll fix CI failures and address comments from users with write access. I'll skip comments containing "(aside)".

  • Disable automatic comment, CI, and merge conflict monitoring

@codspeed

codspeed Bot commented Oct 15, 2026 •

Copy link
Copy Markdown
Contributor

Merging this PR will not alter performance

⚠️ 1 benchmark spent significant time in system calls

System calls cannot be consistently instrumented, so they are not included in the measure, which understates the real cost. Please switch to the Walltime instrument to accurately measure system calls.

Measurement and system calls

✅ 32 untouched benchmarks


Comparing litellm_fix_count_tokens_malformed_tools (f34b58a) with main (d6b54ae)

Open in CodSpeed

@codecov

codecov Bot commented Oct 15, 2026 •

Copy link
Copy Markdown

Codecov Report

❌ Patch coverage is 97.34848% with 7 lines in your changes missing coverage. Please review.

Files with missing lines Patch % Lines
litellm/proxy/response_api_endpoints/endpoints.py 76.92% 3 Missing ⚠️
litellm/utils.py 82.35% 3 Missing ⚠️
litellm/proxy/common_request_processing.py 96.96% 1 Missing ⚠️

📢 Thoughts on this report? Let us know!

Also validate the count_tokens body without recursion, which the recursion detector rejects.
The proxy now answers a non-list tools value with a 400, so the case is deterministic again.
@mateo-berri

Copy link
Copy Markdown
Contributor Author

bugbot run

@mateo-berri

Copy link
Copy Markdown
Contributor Author

@litereview code-review

@cursor cursor Bot left a comment •

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Stale Bugbot comment from a previous run.

@litereview

litereview Bot commented Oct 15, 2026 •

Copy link
Copy Markdown

✅ code-review

5/5 · Ready for human review

Scope: full · Full PR review.

No correctness findings.

The PR title includes the breaking-change marker (fix(proxy)!:). The description explains that falsy tools now return 400 without drop_params and tells clients how to migrate. I ran the PR's integration suite locally: 477 tests passed. Ten fallback and team-model cases errored during setup because /model/new requires LITELLM_LICENSE. CI forwards that license, so those errors come from my environment and do not point to a code defect.

Checks and execution details
  • Passed · Real testing evidence (required): Scoped paths changed: litellm/llms/{anthropic,openai}/chat/guardrail_translation/handler.py, litellm/llms/openai/responses/guardrail_translation/handler.py and litellm/llms/base_llm/guardrail_translation/utils.py.

These edits only change how the guardrail and allowlist code reads tools:

  • list_field returns () for a non-sequence tools instead of crashing.
  • Chat guardrails pass inputs["tools"] only when tools is a list.

No provider request, response, streaming or usage translation changed.

I ran the PR's real-proxy integration suite: tests/integration/run.py providers --workers 4 against local Postgres and Redis with a scripted upstream, on the files test_malformed_tools_wire.py, test_malformed_tools_chaos.py, test_bedrock_mantle_count_tokens_wire.py and test_anthropic_messages_caller_tools_wire.py. Result: 477 passed and 10 errors. These cases passed:

  • test_a_pre_call_guardrail_passes_well_formed_tools_through_to_the_provider[*]
  • the guardrail cases that receive tools as sent
  • the allowlist cases
  • the count_tokens cases

All 10 errors happened in fixture setup at POST /model/new, which returned 403 because no LITELLM_LICENSE was set. CircleCI forwards LITELLM_LICENSE (.circleci/config.yml:883-888).

  • Passed · Compatibility requirements (required): Breaking change: a falsy tools ({}, "", false, 0) used to return 200 on chat, /v1/responses, generateContent and /v1/messages. Without drop_params it now gets 400 invalid_request_error. The path is async_pre_call_deployment_hook → resolve_deployment_tool_fields → _malformed_tools. _TOOLS rejects a non-list.

The notice is complete:

  • The title carries the fix(proxy)!: marker.
  • The description names the affected routes and values.
  • The migration is to drop the field or enable drop_params.

SDK callers outside the proxy see no change, because the check requires proxy_server_request in kwargs.

  • Passed · Changed behavior and result consistency (required): Standards: I read tests/AGENTS.md, tests/integration/AGENTS.md and README.md.

Traced paths:

  1. count_tokens: count_tokens → _token_count_fields → resolve_counted_tool_fields → _counted_drop_policies. This reads the named deployments, with special handling for deployment ids, aliases, routing groups and auto routers, then calls TokenCountRequest.model_validate.
  2. /v1/responses/input_tokens: the same resolver feeds token_fields.get("tools").
  3. LLM routes: @​client → async_pre_call_deployment_hook raises MalformedRequestFieldError. Cooldown is skipped in _should_run_cooldown_logic, and Prometheus deployment_selected is false.
  4. Router: _merge_tools_from_deployment with default params handles falsy and non-list tools.

Boundary checks I ran directly:

  • list_field returns () for "abc" and 5, and keeps tuples.
  • A tool given as a pydantic model is rejected (tools.0).
  • An extra key in a tool entry passes.
  • A JSON-string parameters passes.
  • A tuple vector_store_ids is rejected.
  • Under drop_params, a bad entry drops while tool_choice stays.

Unit tests: the 9 touched unit files plus a filtered router run gave 494+109 passed. There were 7 initial failures in response_api_endpoints/test_endpoints.py, caused by an ungenerated Prisma client (cannot import name 'Json' from 'prisma'). After prisma generate they passed. The integration results are in the real-testing-evidence check.

  • Passed · Touched unit tests (optional): pytest on test_tool_fields.py, anthropic_endpoints/test_endpoints.py, response_api_endpoints/test_endpoints.py, test_tools_allowlist_enforcement.py, test_router_utils_common_utils.py, test_vector_store_registry.py, test_tool_call_cost_tracking.py, test_prometheus_deployment_state_proxy_rejects.py, test_post_call_failure_hook.py, and a filtered test_router.py. Everything passed after Prisma client generation.

View review · Reviewed f34b58a51bb6

@mateo-berri

Copy link
Copy Markdown
Contributor Author

@litereview code-review

@mateo-berri

Copy link
Copy Markdown
Contributor Author

bugbot run

@cursor cursor Bot left a comment •

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Stale Bugbot comment from a previous 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
@mateo-berri

Copy link
Copy Markdown
Contributor Author

@litereview code-review

…ens_malformed_tools

# Conflicts:
#	litellm/llms/openai/chat/guardrail_translation/handler.py
@mateo-berri

Copy link
Copy Markdown
Contributor Author

@litereview code-review

@mateo-berri

Copy link
Copy Markdown
Contributor Author

@litereview code-review

@mateo-berri

Copy link
Copy Markdown
Contributor Author

@litereview code-review

1 similar comment
@mateo-berri

Copy link
Copy Markdown
Contributor Author

@litereview code-review

@litereview

litereview Bot commented Oct 15, 2026

Copy link
Copy Markdown

Review already requested

code-review is already reviewing 2f166969644b. View existing review.

@mateo-berri

Copy link
Copy Markdown
Contributor Author

bugbot run

@mateo-berri

Copy link
Copy Markdown
Contributor Author

@litereview code-review

@mateo-berri

Copy link
Copy Markdown
Contributor Author

@greptileai

Comment thread tests/unit/test_router/test_router.py Resolved
@mateo-berri

Copy link
Copy Markdown
Contributor Author

@litereview code-review

@mateo-berri

Copy link
Copy Markdown
Contributor Author

bugbot run

@mateo-berri

Copy link
Copy Markdown
Contributor Author

@greptileai

@cursor cursor Bot left a comment •

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Stale Bugbot comment from a previous run.

@mateo-berri

Copy link
Copy Markdown
Contributor Author

@litereview code-review

@mateo-berri

Copy link
Copy Markdown
Contributor Author

bugbot run

@mateo-berri

Copy link
Copy Markdown
Contributor Author

@greptileai

@cursor cursor Bot left a comment •

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Stale Bugbot comment from a previous run.

# Conflicts:
#	litellm/proxy/anthropic_endpoints/endpoints.py
@mateo-berri

Copy link
Copy Markdown
Contributor Author

@litereview code-review

@mateo-berri

Copy link
Copy Markdown
Contributor Author

@litereview code-review

@mateo-berri

Copy link
Copy Markdown
Contributor Author

@greptileai

@mateo-berri

Copy link
Copy Markdown
Contributor Author

bugbot run

@cursor cursor Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

✅ 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.

@mateo-berri

Copy link
Copy Markdown
Contributor Author

@litellm-stampbot

@mateo-berri
mateo-berri merged commit d76ec3a into main Oct 16, 2026
107 of 109 checks passed
@mateo-berri
mateo-berri deleted the litellm_fix_count_tokens_malformed_tools branch October 16, 2026 21:57
yuneng-berri added a commit that referenced this pull request Oct 18, 2026
…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>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

risk:high Sensitive, broad, or high-risk change

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants