Repository navigation
fix(count_tokens): count system and tools on Vertex Gemini, fall back to Mantle on Bedrock 404 - #46430
Conversation
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>
…r accepts Co-Authored-By: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com>
|
I'll fix CI failures and address comments from users with write access. I'll skip comments containing "(aside)".
|
Merging this PR will not alter performance
|
Co-Authored-By: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com>
Codecov Report❌ Patch coverage is
📢 Thoughts on this report? Let us know! |
|
bugbot run |
|
@litereview code-review-v2 |
✅ code-review-v25/5 · Ready for human reviewScope: full · Full PR review. No correctness findings. Both open findings from the last review are fixed at head Checks and execution details
View review · Reviewed |
…kens Co-Authored-By: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com>
|
bugbot run |
… strict on Anthropic tools Co-Authored-By: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com>
|
@litereview code-review-v2 |
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>
…, update stale strict test expectations Co-Authored-By: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com>
|
bugbot run |
|
@litereview code-review-v2 |
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 9d65a28. Configure here.
Put the Vertex Gemini count branch back in the same shape as main and the partner model branch, keeping only the system and tools context, the provider error mapping and the gemini tokenizer default Share one error response helper between the Vertex and AI Studio callers, drop the unread kind fields and the extra validation of map_function output, and say Gemini instead of Vertex AI in the error that AI Studio users also see Tighten the tests by removing a stray parametrize on a helper, sharing the SDK count args, asserting the exact forwarded system and tools, and folding the Anthropic tool shape tests into one table
|
Automatic reviews are disabled for this repository. |
… count Vertex and AI Studio count now convert tools with the same functions inference uses, translate_anthropic_tools_to_openai and the Responses tool converter, before VertexGeminiConfig.map_function. Unnamed and Anthropic hosted tools now count the same declarations inference sends instead of being dropped Tools that cannot be converted, such as a non list tools value, a non object tool or a schema that is not a JSON object, now return a 400 before any request instead of being counted without them
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.
…BerriAI#46430) (cherry picked from commit 08a24d3) Co-Authored-By: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com>
…BerriAI#46430) (cherry picked from commit 08a24d3) Co-Authored-By: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com>
…BerriAI#46430) (cherry picked from commit 08a24d3) Co-Authored-By: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com>
TLDR
Problem this solves:
/v1/messages/count_tokenscame in 11 to 68% under inferenceHow it solves it:
systemInstructionand function tools:countTokensnow reads and forwardssystemInstructionandtoolsgemini/) counts now send system and tools insidegenerateContentRequest, the only shape its:countTokensaccepts them inapi_base:countTokenssystemInstruction/tools/v1/messages/count_tokenswith Anthropic tools on an OpenAI modelMissing required parameter: 'tools[0].type'gemini/) count with system/toolsgenerateContentRequest, live count 377 equals inferencepromptTokenCount377strictstrict: false, same as inferencetruncate_tool_name, same as inferencelitellm_unnamed_tool_0tools, non-object tool or schema)Intentional product change: Vertex Gemini count errors now return the provider's 400 or a 503 instead of 500. A malformed
systemInstructionon:countTokens, or a non-text block insystemfor Vertex Gemini, now returns 400 where main silently ignored it. Vertex Gemini count with tools it can't convert also returns 400 instead of counting without themUser Flow
Before: a team that budgets prompts with
/v1/messages/count_tokensgets a count far below what inference bills on Vertex Gemini"input_tokens": 1011, the same as with no system prompt or toolusage.input_tokenscomes back as 3157, 68% higherAfter: the count matches what inference bills, within a few percent
"input_tokens": 3100usage.input_tokens3157, 1.8% offLinear ticket
Resolves LIT-9562 (parent LIT-9533)
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).
Files changed
litellm/llms/bedrock/count_tokens/bedrock_token_counter.pylitellm/llms/vertex_ai/count_tokens/context.py(new)systemInstruction, and function tools intofunctionDeclarationswith inference's owntranslate_anthropic_tools_to_openai, Responses tool converter andmap_function. 400 on tools it can't convertlitellm/llms/vertex_ai/common_utils.pycontents, maps errors to 400/503, ignores a deployment-levelsystem_instructionso it cannot collide with the request's systemlitellm/llms/vertex_ai/count_tokens/handler.pyapi_base, keeps the top-level body shape Vertex acceptslitellm/llms/gemini/count_tokens/handler.pysystemInstructionandtoolsin the count body, wrapped ingenerateContentRequestfor AI Studiolitellm/llms/gemini/common_utils.pylitellm/proxy/google_endpoints/endpoints.pysystemInstructionandfunctionDeclarations, lowercases Google SDK schema types ("OBJECT"), 400 on malformed inputlitellm/llms/openai/responses/count_tokens/transformation.pyinput_schema) to Responses function tools, keepingstrictlike inferenceTests
All integration tests run a real proxy against scripted upstreams. The Vertex Gemini cases come from the customer's count-token suite:
baseline,large_system,large_tool,large_system_and_tooltest_bedrock_mantle_count_tokens_wire.py::test_runtime_404_on_claude_falls_back_to_mantle::test_runtime_404_and_mantle_404_surface_provider_error::test_runtime_404_on_nova_does_not_call_mantle::test_google_count_tokens_forwards_system_and_tools_to_mantle::test_google_count_tokens_normalizes_uppercase_parameters_for_mantletest_vertex_gemini_count_tokens_wire.py::test_messages_and_count_tokens_send_matching_gemini_contexttest_vertex_gemini_count_tokens_wire.pycasescontentsonly (control)::test_count_tokens_without_system_or_tools_sends_contents_only::test_count_tokens_surfaces_peer_errors_and_rejects_non_text_system,::test_concurrent_count_waves_recover_after_vertex_count_outagetest_openai_count_tokens_tools_wire.py::test_google_count_tokens_maps_anthropic_tools_to_openai/v1/messages/count_tokens::test_messages_count_tokens_maps_anthropic_tools_to_openaiapi_base(rig check for the cells above)::test_openai_count_tokens_uses_deployment_api_basetests/unit/llms/gemini/test_gemini_common_utils.py::test_google_ai_studio_count_tokens_forwards_system_and_toolssystemmust 400 before any request::test_google_ai_studio_count_tokens_rejects_image_system_without_requeststrictdropped (found by LiteReview)test_openai_count_tokens_transformation.py::test_transform_anthropic_tool_shapes[anthropic-strict]and the other Anthropic-shape casestests/unit/llms/vertex_ai/count_tokens/test_context.py::test_long_anthropic_tool_name_is_truncated_for_vertextest_context.py::test_anthropic_tools_count_the_same_declarations_inference_sendstest_context.py::test_invalid_tools_return_an_error_value,test_vertex_gemini_count_tokens_wire.py::test_count_tokens_rejects_unconvertible_tools_without_request/utils/token_counterkeep converting (control)::test_utils_token_counter_keeps_chat_tool_conversion*main ignores a Vertex deployment's
api_baseon the count path, so these cells ran against main plus only that one-line passthrough. Without it they 401 against public Vertex and prove nothing. With it, 11 are red and 2 greenChanged tests: in
tests/unit/llms/bedrock/count_tokens/test_bedrock_token_counter.py, one Mantle fallback case now uses a runtime 404 instead of 400, and two new no-fallback cases cover a Claude 401 and a Nova 404. A new test checks that a Claude 404 retry sends system and tools to Mantle. No tests removedNew unit tests:
tests/unit/llms/vertex_ai/test_vertex_ai_common_utils.py(non-text system rejected with 400 before any request; a deployment that setssystem_instructionstill counts, with the request's system winning, which was a TypeError/500 before the fix),tests/unit/llms/vertex_ai/count_tokens/test_context.py,tests/unit/llms/gemini/test_gemini_common_utils.py,tests/unit/proxy/google_endpoints/test_endpoints.py(schema lowercasing,parametersJsonSchemakept verbatim),tests/unit/llms/openai/responses/test_openai_count_tokens_transformation.py(Anthropic shape,type: custom, built-in tools passed through, chat shape unchanged)Local runs at the tip: 162 integration tests passed across the four count-token wire files, 6901 unit tests passed across the Vertex, Gemini, OpenAI responses, Google endpoint, Bedrock, Mantle and Anthropic unit folders, and all five lint gates pass
Screenshots / Proof of Fix
Real proxy, real Vertex and Bedrock, the customer suite's prompts and its 5% threshold: each case sends the same body to POST /v1/messages/count_tokens and to POST /v1/messages and compares
input_tokens. Vertex runs withvertex_location: globalBefore (bfcb0ff, merge base)
Vertex Gemini
gemini-4-argonbaseline: count 1011, inference 1135, 10.9% off, FAILlarge_system: count 1011, inference 2135, 52.6% off, FAILlarge_tool: count 1011, inference 2157, 53.1% off, FAILlarge_system_and_tool: count 1011, inference 3157, 68.0% off, FAILBedrock Claude Opus 4.8 (runtime 400 path, control)
Google
:countTokenswith a function tool on an OpenAI modelfunctionDeclarationsentry returns 200 withtotalTokens8: the tool was dropped/v1/messages/count_tokenswith an Anthropic tool on an OpenAI modelinput_schematool returns 400Missing required parameter: 'tools[0].type'.Google AI Studio
gemini/gemini-2.5-flash(direct counter call, 2,016-char system plus 1 tool)After (5572476 for the customer cases, 76ffef8 for the rest)
Vertex Gemini
gemini-4-argonbaseline: count 1099, inference 1135, 3.2% off, PASSlarge_system: count 2096, inference 2131, 1.6% off, PASSlarge_tool: count 2099, inference 2154, 2.6% off, PASSlarge_system_and_tool: count 3100, inference 3157, 1.8% off, PASSBedrock Claude Opus 4.8 (runtime 400 path, control)
Google
:countTokenswith a function tool on an OpenAI modeltotalTokens46: the tool is countedGoogle AI Studio
gemini/gemini-2.5-flash(88b7313)promptTokenCount377. With no context it stays at 2/v1/messages/count_tokenswith an Anthropic tool on an OpenAI model{"input_tokens":1118}The tip commit 76ffef8 only touches the Google route and the OpenAI tool transform, not the Vertex or Bedrock paths in the customer cases
/live-pr-risk at the tip (bfcb0ff vs 76ffef8)
35 scenarios on real proxies with real Postgres, Redis, Vertex, Bedrock, Anthropic and OpenAI, no mocks. All ran on both sides. The only rows where main returned 200 and the tip does not are the intentional malformed-input 400s:
systemon Vertex Gemini:countTokenswith an inline image insystemInstruction, orsystemInstruction/toolsof the wrong type (int, list, empty string, plain string)Every other row returns the same status on both sides, with higher counts on the tip where system or tools are now included. Google route tools on OpenAI, Anthropic and Bedrock models, uppercase schema types, unauthenticated requests (401) and unknown models (404) behave the same as main or better
Type
🐛 Bug Fix
Caveats (if any)
Medium
Low
vertex_location: globalon our projectFinal Attestation
Link to Devin session: https://app.devin.ai/sessions/03715130ba494e89a7b116ab4975fda6
Open in Devin Desktop: https://app.devin.ai/desktop/session/03715130ba494e89a7b116ab4975fda6?variant=devin
Requested by: @mrinal-berri
Note
Medium Risk
Changes shared token-count request shaping across Vertex, Gemini, Google proxy, OpenAI, and Bedrock fallback paths; malformed system/tools now 400 where they were previously ignored, which can break lenient clients.
Overview
Fixes under-counting on Vertex/Google Gemini and missing Bedrock Mantle fallback when runtime
countTokensreturns 404.Vertex & Google AI Studio: Token counting now builds the same system prompt and function tools as inference via
vertex_gemini_count_context(Anthropic/OpenAI/Responses tool shapes → GeminisystemInstruction/functionDeclarations). Vertex sends them on the top-level count body; AI Studio wraps them ingenerateContentRequest. Invalid non-text system blocks return 400 instead of being ignored; provider errors surface with the real status code.Proxy Google
:countTokens: Validates the body and forwardssystemInstructionand tools (including schema normalization for Mantle/OpenAI paths).OpenAI Responses count: Maps Anthropic-style tools (
input_schema,type: custom) to Responses function tools so mixed-format count requests succeed.Bedrock: Claude models retry on bedrock-mantle when runtime returns 400 or 404 (not 404-only before for some paths).
Reviewed by Cursor Bugbot for commit 9d65a28. Bugbot is set up for automated code reviews on this repo. Configure here.