Repository navigation
fix(count_tokens): return a 400 naming Anthropic blocks the OpenAI and Gemini count can't convert - #46772
Conversation
…ounter the way inference does
…anthropic_openai_gemini
…input /v1/messages inference sends
…nd sync dashboard API types
… /v1/messages inference converts them
…d Gemini count can't convert
|
@litereview code-review |
✅ code-review5/5 · Ready for human reviewScope: full · Full PR review. No correctness findings. Checks and execution details
Integration tests drive the real proxy through
Both tests assert a 400, the named labels (including I ran The PR also links manual E2E evidence (gist) with real
When a provider counter returns The PR description documents the error-shape change from View review · Reviewed |
| return f"{block_type} with an untyped source" | ||
|
|
||
|
|
||
| def _block_label(block: JsonValue, convertible: frozenset[str]) -> str | None: |
There was a problem hiding this comment.
Medium · Search results returned inside tool_result still get a silently low count
- A client runs a RAG tool and replays its output the usual Anthropic way: a user turn with a
tool_resultwhosecontentholds asearch_resultblock. The deployment isopenai/...,vertex_ai/gemini-...orgemini/.... - The client calls
POST /v1/messages/count_tokensfor that body. _block_labelsees only the top-leveltool_result. That type is in the allowed set, so the new check returns no labels and the count proceeds.- Both adapters reduce the nested
search_resultto an empty tool output ('output': ''for Responses,'content': ''for chat). The count returns 200 without the search-result text, which is the undercount LIT-9586 asked to turn into a 400.
The PR description says the check reads only top-level blocks. That explains the gap but does not close it. To fix it, run the same labelling over list content inside tool_result blocks. Keep text, tool_reference, and image/document blocks with a valid base64 or url source.
Evidence
Reproducer (uv run python /tmp/r.py at head 856ba4d):
sr = {"type":"search_result","source":"https://example.com/notes","title":"Notes","content":[{"type":"text","text":"The notes say the launch is on Tuesday."}]}
msgs = [{"role":"assistant","content":[{"type":"tool_use","id":"toolu_01","name":"kb","input":{}}]},
{"role":"user","content":[{"type":"tool_result","tool_use_id":"toolu_01","content":[sr]},{"type":"text","text":"When is launch?"}]}]Output:
check: None
chat: [... {'role': 'tool', 'tool_call_id': 'toolu_01', 'content': ''}, ...]
resp: [... {'type': 'function_call_output', 'call_id': 'toolu_01', 'output': ''}, ...]
LiteLLMAnthropicMessagesAdapter._tool_result_part keeps only text, image/document and tool_reference parts and returns None for anything else (adapters/transformation.py ~L1324-1341).
translate_messages_to_responses_input keeps only nested text and document items from tool_result content (responses_adapters/transformation.py ~L369-395).
A document with a text source nested in tool_result hits the same gap: _translate_anthropic_document_block_to_file_part returns None for non-base64 and non-url sources.
Latest summary by code-review · View this review · Reviewed 856ba4dfca6f
There was a problem hiding this comment.
Fixed in 3313dcd. A search_result or text-source document inside a tool_result now gets the 400, with unit and wire tests covering it
There was a problem hiding this comment.
Finding withdrawn
The fix is verified. _content_labels now chains _tool_result_labels, which labels any block inside a tool_result that both adapters would drop. A search_result or a text-source document nested in a tool_result now makes /v1/messages/count_tokens return a 400 instead of a low 200. Valid nested text, tool_reference and base64/url image or document blocks still pass. The OpenAI and Vertex Gemini wire tests now assert the nested label.
Evidence
litellm/llms/anthropic/pass_through/convertible_blocks.py: _TOOL_RESULT_BLOCK_TYPES = {text, image, document, tool_reference}. _tool_result_labels runs _block_label over list content and appends inside a tool_result. _content_labels chains it into each message's labels.
Reproducer output at head 3313dcd:
count_tokens can't convert these content blocks for this model, so the count would leave them out: search_result inside a tool_result
count_tokens can't convert these content blocks for this model, so the count would leave them out: document with a text source inside a tool_result
None # nested text block
None # string content
Tests: tests/unit/llms/anthropic/pass_through/test_convertible_blocks.py:108-110, tests/integration/providers/test_openai_count_tokens_tools_wire.py:312 and tests/integration/providers/test_vertex_gemini_count_tokens_wire.py:300 assert the ... inside a tool_result label.
GitHub does not allow this App to resolve this thread. A repository maintainer must do it manually.
Reviewed 3313dcd17d4c · View follow-up
Codecov Report❌ Patch coverage is 📢 Thoughts on this report? Let us know! |
…ropic_format' into litellm_count_tokens_gemini_anthropic_format
…llm_count_tokens_reject_unconvertible_blocks
|
@litereview code-review |
…nce sends them to OpenAI Unwrap affinity-encoded reasoning, count the structured-output schema, flatten replayed web search results, join a list system prompt, and answer a message without a role with a 400 before calling OpenAI. messages_format is now internal to the Anthropic count route instead of a public /utils/token_counter field.
…//github.com/BerriAI/litellm into litellm_count_tokens_openai_anthropic_format # Conflicts: # tests/unit/test_count_tokens_public_api.py
…openai_anthropic_format
…ropic_format' into litellm_count_tokens_gemini_anthropic_format
…llm_count_tokens_reject_unconvertible_blocks
|
@litereview code-review |
|
bugbot run |
…ted Any On Python 3.10 to 3.13 the annotation is evaluated at import, so the proxy failed to start with NameError
…//github.com/BerriAI/litellm into litellm_count_tokens_gemini_anthropic_format
…ropic_format' into litellm_count_tokens_gemini_anthropic_format
…ropic_format' into litellm_count_tokens_gemini_anthropic_format
|
@litereview code-review |
… with a text-block system
…llm_count_tokens_reject_unconvertible_blocks
|
@litereview code-review |
| else None | ||
| ) | ||
| if malformed_error is not None: | ||
| request_error: Final = malformed_error or unconvertible_blocks_error(messages, messages_format) |
There was a problem hiding this comment.
Medium · OpenAI count_tokens rejects a compaction history that /v1/messages accepts and bills
- A client keeps a history with an assistant turn containing a replayed
compactionblock, for example{"type": "compaction", "content": "Summary of the earlier turns..."}. The model deployment isopenai/.... - The client sends
POST /v1/messages/count_tokenswith that body. OpenAITokenCounter.count_tokenspasses the raw messages tounconvertible_blocks_error. That function only appliesnormalize_native_messages, so thecompactionblock stays in the history.compactionis missing from the assistant allow-list, so the check labels it.- The count returns 400 with
... would leave them out: compaction, and no provider call happens./v1/messagesserves the same body with a 200. The Responses adapter drops the block on that path too, so the earlier count matched the billed tokens (659 = 659 in the author's gist before this PR). The PR is meant to catch undercounts, and this case had no undercount.
The Gemini paths avoid this case because inference_request_view runs _client_compaction before the check. Only the OpenAI path breaks. The smallest fix is to stop labelling compaction on the OpenAI path, for example by adding it to the assistant set there. Alternatively, run the check on the same view the Responses inference builds.
Evidence
Reproducer at head 0dbb5dc, run in the local uv env with the gist body compaction.count-tokens-openai.count.json (user string / assistant [compaction] / user string):
unconvertible_blocks_error(messages, 'anthropic') -> "count_tokens can't convert these content blocks for this model, so the count would leave them out: compaction"
OpenAITokenCounter().count_tokens(..., messages_format='anthropic') -> status_code=400, same message (no HTTP call made)
inference_request_view(...) then unconvertible_messages_error(...) -> None # Gemini path: client compaction strips the block first
Real-provider evidence from the author's gist, after_pr1_c6d410b039.txt (before this PR): count-tokens-openai compaction count {"input_tokens":659} [HTTP 200], /v1/messages usage input_tokens: 659. The after-PR runs (after_pr3_c9b14a6a94.txt) do not include the compaction case.
LiteLLMAnthropicToResponsesAPIAdapter._assistant_group_to_input_items returns () for non-thinking and non-tool_use blocks, so /v1/messages sends nothing for compaction on the Responses route (responses_adapters/transformation.py ~L280-296). messages/handler.py:608 routes to that path when no compaction kwarg is set.
_CONVERTIBLE_BLOCK_TYPES['assistant'] = {text, tool_use, thinking, redacted_thinking} in convertible_blocks.py:15 has no compaction entry.
Latest summary by code-review · View this review · Reviewed 0dbb5dcea0eb
There was a problem hiding this comment.
By design. The ticket asks for a 400 naming any block the conversion drops, and the Responses conversion drops compaction, so the count names it
There was a problem hiding this comment.
Finding withdrawn
The reply holds up against the code. My finding said the 400 was wrong because the count of 659 matched the billed 659, so nothing was undercounted. The PR doesn't use that test, though. Its own OpenAI unconvertible blocks row shows a count of 58, a bill of 58 and an intended HTTP 400. The PR rejects blocks whose content /v1/messages silently drops, even when count and bill agree.
compaction falls in that group on the OpenAI path:
/v1/messagessends OpenAI models toLiteLLMMessagesToResponsesAPIHandlerwhen nocompactionkwarg is set. That handler never callsapply_client_compaction_block_history, so nothing moves the summary intosystem._assistant_group_to_input_itemsreturns()for acompactionblock, so the provider never sees the summary text.- The PR says the check runs after the history rewrites that
/v1/messagesapplies. The Responses route applies no compaction rewrite, so the check correctly names the dropped block.
The Gemini path differs because its inference path does fold the summary into system, and inference_request_view mirrors that rewrite. The OpenAI 400 is consistent with the stated LIT-9586 requirement, so it isn't a defect.
Evidence
Ran at head 0dbb5dc in the local uv env, with history user hi / assistant [{type: compaction, content: 'SUMMARY TEXT'}] / user go on:
LiteLLMAnthropicToResponsesAPIAdapter().translate_messages_to_responses_input(m)
-> [{'type': 'message', 'role': 'user', 'content': [{'type': 'input_text', 'text': 'hi'}]}, {'type': 'message', 'role': 'user', 'content': [{'type': 'input_text', 'text': 'go on'}]}]
unconvertible_blocks_error(m, 'anthropic')
-> "count_tokens can't convert these content blocks for this model, so the count would leave them out: compaction"
The summary text never reaches the Responses input.
litellm/llms/anthropic/pass_through/messages/handler.py:608 routes OpenAI to LiteLLMMessagesToResponsesAPIHandler when kwargs.get("compaction") is None. grep compaction finds no match in responses_adapters/handler.py. apply_client_compaction_block_history is called only from adapters/handler.py (the chat-completions adapter) and from vertex_ai/count_tokens/context.py.
PR description, OpenAI row unconvertible blocks | Before 58 | After HTTP 400 | Expected HTTP 400 | Billed 58. Count and bill matched there, and the PR still rejects the body. The PR also says it 400s on "blocks the conversion drops", with no opt-out (LIT-9586).
GitHub does not allow this App to resolve this thread. A repository maintainer must do it manually.
Reviewed 0dbb5dcea0eb · View follow-up
|
@litereview code-review |
|
bugbot run |
[Medium impact] The PR appears safe to merge; no blocking issue was found. Summary
Reviews (2) · Last reviewed commit: "Merge branch 'main' into litellm_count_t..." · Reviewed by Greptile |
|
@litellm-stampbot |
litellm-stampbot: risk lowApproved at Rules (
Judge (gpt-6-luna): low, probability of high 0.09 (high at or above 0.75)
Pushes do not re-run this check. Comment |
kerry-berri
left a comment
There was a problem hiding this comment.
Low risk by rule and by judgement at 0dbb5dc
…ocks # Conflicts: # litellm/llms/gemini/common_utils.py # litellm/llms/openai/responses/count_tokens/token_counter.py # litellm/llms/vertex_ai/common_utils.py # tests/integration/providers/test_openai_count_tokens_tools_wire.py # tests/integration/providers/test_vertex_gemini_count_tokens_wire.py
Merging this PR will not alter performance
|
|
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 610d0a7. Configure here.
…overloaded_error count_tokens errors now use main's top-level Anthropic envelope from #46772, still mapped 503 to 529, and its tests read that envelope
Keep #43900, #45301, #46121, #46784, #46759, #46767, #46772, #46815, #47057 and #46777. Port only the Gemini prerequisites from #46430. Remove the deferred Bedrock Mantle behavior and unrelated picks from the final tree. Restore the PDF test provider fixture and deployment, and retain required test imports.
TLDR
Problem this solves:
/v1/messages/count_tokensskipped blocks it couldn't convert for OpenAI and Gemini, so counts came back low with a 200How it solves it:
Intentional product change: these bodies now get a 400, with no setting to turn it off
User Flow
Before
documentand asearch_resultinput_tokensthat only covers the textAfter
Linear ticket
Resolves LIT-9586
Pre-Submission checklist
Please complete all items before asking a LiteLLM maintainer to review your PR
uv run pytest tests/unit/<your_test_file>.py -v. Leave the suites (make test-unit-*,make test-unit) to CI: it finishes in ~15 minutes where a laptop takes an hour or moreDelays in PR merge?
If you're seeing a delay in your PR being merged, ping the LiteLLM Team on Slack (#pr-review).
Design decisions
The ticket asks for a 400 as a new default with no opt-out. Tying it to
drop_paramswould bring back the silent low count, so the 400 holds either wayThe check runs after the history rewrites
/v1/messagesapplies, so a replayed web search flattened to text passes. A block passes when both conversions send it:text,image,documentandtool_resultin user turns, plustext,tool_use,thinkingandredacted_thinkingin assistant turns. Inside atool_resultonlytext,imageanddocumentpass, so a nestedsearch_resultortool_referenceis named too. Unit tests check these lists against what both counters send. Only/v1/messages/count_tokenschecks. Its errors now use the Anthropic shape/v1/messagesreturns, not{"detail": ...}, so a provider 429 there changes shape tooScreenshots / Proof of Fix
Both legs sent the same bodies with curl to a
--num_workers 2proxy on realgpt-6.1-solandgemini-4-argoncalls. Count isPOST /v1/messages/count_tokens, and Billed is theusageof the same body onPOST /v1/messages. Everything is in the gistBefore, the body with a
search_resultblock and a text-sourcedocumentblock counted the same as that body with both blocks removed (58, 60, 96), so they added nothing, while the same content as text blocks counts 463, 466 and 500. After, each count answers 400 in Anthropic's error shape and names both blocks. The two controls and a replayed web search count the same as before, and so do the other 19 cases in the full runsDeployments are
openai/gpt-6.1-sol,vertex_ai/gemini-4-argonandgemini/gemini-4-argon. Eachunconvertible.count.jsonholds a system string and a user turn with a text block, a text-sourcedocumentblock and asearch_resultblock. Before ran at dba86be, this PR's merge base on mainBefore (dba86be)
Vertex, unconvertible blocks
Count the request
Send the same body for real and read its usage
Other cases
OpenAI, unconvertible blocks
Count the request
Send the same body for real and read its usage
OpenAI, same body without those blocks
Count the request
Send the same body for real and read its usage
OpenAI, same content as text blocks
Count the request
Send the same body for real and read its usage
OpenAI, replayed web search
Count the request
Send the same body for real and read its usage
Vertex, same body without those blocks
Count the request
Send the same body for real and read its usage
Vertex, same content as text blocks
Count the request
Send the same body for real and read its usage
Vertex, replayed web search
Count the request
Send the same body for real and read its usage
AI Studio, unconvertible blocks
Count the request
Send the same body for real and read its usage
AI Studio, same body without those blocks
Count the request
Send the same body for real and read its usage
AI Studio, same content as text blocks
Count the request
Send the same body for real and read its usage
AI Studio, replayed web search
Count the request
Send the same body for real and read its usage
After (610d0a7)
Vertex, unconvertible blocks
Count the request
Send the same body for real and read its usage
Other cases
OpenAI, unconvertible blocks
Count the request
Send the same body for real and read its usage
OpenAI, same body without those blocks
Count the request
Send the same body for real and read its usage
OpenAI, same content as text blocks
Count the request
Send the same body for real and read its usage
OpenAI, replayed web search
Count the request
Send the same body for real and read its usage
Vertex, same body without those blocks
Count the request
Send the same body for real and read its usage
Vertex, same content as text blocks
Count the request
Send the same body for real and read its usage
Vertex, replayed web search
Count the request
Send the same body for real and read its usage
AI Studio, unconvertible blocks
Count the request
Send the same body for real and read its usage
AI Studio, same body without those blocks
Count the request
Send the same body for real and read its usage
AI Studio, same content as text blocks
Count the request
Send the same body for real and read its usage
AI Studio, replayed web search
Count the request
Send the same body for real and read its usage
What surprised the run
/v1/messagesalso bills these bodies without the two blocks, so inference drops them tooType
🐛 Bug Fix
Caveats (if any)
Severe
/v1/messagesserves and billsFinal Attestation
Note
Medium Risk
Intentional breaking change: some bodies that still succeed on
/v1/messageswill get 400 on count_tokens, and count_tokens error shapes for provider failures now match Anthropic format.Overview
/v1/messages/count_tokensno longer returns a lowinput_tokenswhen OpenAI or Gemini backends would drop Anthropic content blocks during conversion. Those requests now fail with HTTP 400 before any providercountTokens/input_tokenscall, listing the blocks that would be omitted (e.g.search_result,document with a text source, nested blocks insidetool_result).A new
convertible_blockshelper walks normalized Anthropic messages and names blocks that neither the chat nor Responses conversion paths would send. OpenAI, Vertex Gemini, and Google AI Studio token counters call this (viaunconvertible_messages_error) alongside existing malformed-message checks.The Anthropic proxy
count_tokensroute now returns errors in the same Anthropic JSON error envelope as/v1/messages(via_anthropic_error_json_response) instead of raising FastAPIHTTPExceptionwith adetailobject. Successful counts still return{"input_tokens": ...}.Reviewed by Cursor Bugbot for commit 610d0a7. Bugbot is set up for automated code reviews on this repo. Configure here.