Skip to content

fix(count_tokens): count system and tools on Vertex Gemini, fall back to Mantle on Bedrock 404 - #46430

Merged
mrinal-berri merged 11 commits into
mainfrom
litellm_count_tokens_bedrock_404_gemini_system_tools
Oct 15, 2026
Merged

mrinal-berri merged 11 commits into
mainfrom
litellm_count_tokens_bedrock_404_gemini_system_tools

Conversation

@mrinal-berri

@mrinal-berri mrinal-berri commented Oct 14, 2026 •

Copy link
Copy Markdown
Contributor

TLDR

Problem this solves:

  • Vertex Gemini token counts left out the system prompt and tools
  • So /v1/messages/count_tokens came in 11 to 68% under inference
  • On Bedrock, Claude count calls that got a 404 skipped the Mantle fallback

How it solves it:

  • Vertex Gemini counts now send systemInstruction and function tools
  • They're converted with the same helpers inference uses
  • Bedrock Claude now falls back to Mantle on a runtime 404, like 400
  • Google :countTokens now reads and forwards systemInstruction and tools
  • Google AI Studio (gemini/) counts now send system and tools inside generateContentRequest, the only shape its :countTokens accepts them in
  • Vertex count calls now honor the deployment's api_base
Behavior On main With this PR
Vertex Gemini count with system/tools Already broken: both dropped, count stuck at 1011 Counted, within 1.6 to 3.2% of inference
Bedrock Claude count, runtime 404 Already broken: no Mantle fallback Falls back to Mantle
Bedrock Claude count, runtime 400 Already works: Mantle fallback Unchanged
Google :countTokens systemInstruction / tools Already broken: silently dropped Forwarded to every provider counter
/v1/messages/count_tokens with Anthropic tools on an OpenAI model Already broken: 400 Missing required parameter: 'tools[0].type' Converted to Responses tool shape
Google AI Studio (gemini/) count with system/tools Already broken: both dropped Sent in generateContentRequest, live count 377 equals inference promptTokenCount 377
OpenAI count of an Anthropic tool without strict n/a (tools were not converted) strict: false, same as inference
Vertex count of an Anthropic tool name over 64 chars n/a (tools were dropped) Truncated with truncate_tool_name, same as inference
Vertex count of an unnamed or Anthropic hosted tool Dropped from the count Counted as the same declaration inference sends, e.g. litellm_unnamed_tool_0
Vertex count with tools that can't be converted (non-list tools, non-object tool or schema) Silently counted without them 400 before any request
Vertex Gemini count, provider 400 / outage 500 for both 400 / 503

Intentional product change: Vertex Gemini count errors now return the provider's 400 or a 503 instead of 500. A malformed systemInstruction on :countTokens, or a non-text block in system for 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 them

User Flow

Before: a team that budgets prompts with /v1/messages/count_tokens gets a count far below what inference bills on Vertex Gemini

  1. They send POST https://litellm-domain/v1/messages/count_tokens for a Vertex Gemini model with a 1k-token system prompt and a 1k-token tool
  2. The response says "input_tokens": 1011, the same as with no system prompt or tool
  3. They send the same body to POST https://litellm-domain/v1/messages and usage.input_tokens comes back as 3157, 68% higher

After: the count matches what inference bills, within a few percent

  1. They send the same POST https://litellm-domain/v1/messages/count_tokens
  2. The response says "input_tokens": 3100
  3. The same body to POST https://litellm-domain/v1/messages comes back with usage.input_tokens 3157, 1.8% off

Linear ticket

Resolves LIT-9562 (parent LIT-9533)

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

Files changed

File Change
litellm/llms/bedrock/count_tokens/bedrock_token_counter.py Claude runtime 400 or 404 falls back to Mantle
litellm/llms/vertex_ai/count_tokens/context.py (new) Converts system into Gemini systemInstruction, and function tools into functionDeclarations with inference's own translate_anthropic_tools_to_openai, Responses tool converter and map_function. 400 on tools it can't convert
litellm/llms/vertex_ai/common_utils.py Vertex count entry point uses that context, keeps direct contents, maps errors to 400/503, ignores a deployment-level system_instruction so it cannot collide with the request's system
litellm/llms/vertex_ai/count_tokens/handler.py Honors deployment api_base, keeps the top-level body shape Vertex accepts
litellm/llms/gemini/count_tokens/handler.py Puts systemInstruction and tools in the count body, wrapped in generateContentRequest for AI Studio
litellm/llms/gemini/common_utils.py AI Studio count entry point uses the same system/tools context as Vertex, 400 on a non-text system
litellm/proxy/google_endpoints/endpoints.py Reads systemInstruction and functionDeclarations, lowercases Google SDK schema types ("OBJECT"), 400 on malformed input
litellm/llms/openai/responses/count_tokens/transformation.py Converts Anthropic-shaped tools (input_schema) to Responses function tools, keeping strict like inference

Tests

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_tool

Problem Test Red on
Bedrock Claude runtime 404 skips Mantle test_bedrock_mantle_count_tokens_wire.py::test_runtime_404_on_claude_falls_back_to_mantle main
Runtime 404 + Mantle 404 must surface the error, not a local count ::test_runtime_404_and_mantle_404_surface_provider_error main
Non-Claude 404 must not call Mantle (control) ::test_runtime_404_on_nova_does_not_call_mantle green on main and head
Google route drops system and tools ::test_google_count_tokens_forwards_system_and_tools_to_mantle main
Uppercase Google schema types rejected by Claude counters ::test_google_count_tokens_normalizes_uppercase_parameters_for_mantle previous commit (found by /live-pr-risk)
Vertex count body differs from inference body, 4 customer cases test_vertex_gemini_count_tokens_wire.py::test_messages_and_count_tokens_send_matching_gemini_context main*
Text-block system, Anthropic SDK, Google route, Responses flat tools, OpenAI chat tools on Vertex the other test_vertex_gemini_count_tokens_wire.py cases main*
No system/tools sends contents only (control) ::test_count_tokens_without_system_or_tools_sends_contents_only green on main* and head
Vertex peer 400 and outage between concurrent waves ::test_count_tokens_surfaces_peer_errors_and_rejects_non_text_system, ::test_concurrent_count_waves_recover_after_vertex_count_outage main* (500)
OpenAI count rejects Google-route tools test_openai_count_tokens_tools_wire.py::test_google_count_tokens_maps_anthropic_tools_to_openai previous commit (found by /live-pr-risk)
OpenAI count rejects Anthropic tools from /v1/messages/count_tokens ::test_messages_count_tokens_maps_anthropic_tools_to_openai previous commit
OpenAI count reaches the deployment api_base (rig check for the cells above) ::test_openai_count_tokens_uses_deployment_api_base not run red
AI Studio count drops system and tools (found by LiteReview) tests/unit/llms/gemini/test_gemini_common_utils.py::test_google_ai_studio_count_tokens_forwards_system_and_tools main
AI Studio count with an image in system must 400 before any request ::test_google_ai_studio_count_tokens_rejects_image_system_without_request main
Anthropic tool strict dropped (found by LiteReview) test_openai_count_tokens_transformation.py::test_transform_anthropic_tool_shapes[anthropic-strict] and the other Anthropic-shape cases previous commit
Long Anthropic tool name sent untruncated to Vertex count (found by LiteReview) tests/unit/llms/vertex_ai/count_tokens/test_context.py::test_long_anthropic_tool_name_is_truncated_for_vertex previous commit
Unnamed or hosted Anthropic tool dropped from Vertex count but sent by inference (found in review) test_context.py::test_anthropic_tools_count_the_same_declarations_inference_sends previous commit
Tools that can't be converted counted as if absent test_context.py::test_invalid_tools_return_an_error_value, test_vertex_gemini_count_tokens_wire.py::test_count_tokens_rejects_unconvertible_tools_without_request previous commit
Chat-shaped tools on /utils/token_counter keep converting (control) ::test_utils_token_counter_keeps_chat_tool_conversion green before and after

*main ignores a Vertex deployment's api_base on 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 green

Changed 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 removed

New 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 sets system_instruction still 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, parametersJsonSchema kept 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 with vertex_location: global

Before (bfcb0ff, merge base)

Vertex Gemini gemini-4-argon

  1. baseline: count 1011, inference 1135, 10.9% off, FAIL
  2. large_system: count 1011, inference 2135, 52.6% off, FAIL
  3. large_tool: count 1011, inference 2157, 53.1% off, FAIL
  4. large_system_and_tool: count 1011, inference 3157, 68.0% off, FAIL

Bedrock Claude Opus 4.8 (runtime 400 path, control)

  1. All 4 cases: count equals inference (1844 / 3541 / 3875 / 5571), PASS

Google :countTokens with a function tool on an OpenAI model

  1. POST /v1beta/models/oai:countTokens with one functionDeclarations entry returns 200 with totalTokens 8: the tool was dropped

/v1/messages/count_tokens with an Anthropic tool on an OpenAI model

  1. POST /v1/messages/count_tokens with one input_schema tool returns 400 Missing required parameter: 'tools[0].type'.

Google AI Studio gemini/gemini-2.5-flash (direct counter call, 2,016-char system plus 1 tool)

  1. Count with context is 2, the same as with no context: system and tools dropped

After (5572476 for the customer cases, 76ffef8 for the rest)

Vertex Gemini gemini-4-argon

  1. baseline: count 1099, inference 1135, 3.2% off, PASS
  2. large_system: count 2096, inference 2131, 1.6% off, PASS
  3. large_tool: count 2099, inference 2154, 2.6% off, PASS
  4. large_system_and_tool: count 3100, inference 3157, 1.8% off, PASS

Bedrock Claude Opus 4.8 (runtime 400 path, control)

  1. All 4 cases: count equals inference (1840 / 3541 / 3880 / 5575), PASS

Google :countTokens with a function tool on an OpenAI model

  1. The same request returns 200 with totalTokens 46: the tool is counted

Google AI Studio gemini/gemini-2.5-flash (88b7313)

  1. Count with context is 377, and generateContent with the same input reports promptTokenCount 377. With no context it stays at 2

/v1/messages/count_tokens with an Anthropic tool on an OpenAI model

  1. The same request returns 200 with {"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:

Scenario main tip
Image block in system on Vertex Gemini 200, image ignored 400 "system instructions only support text blocks"
:countTokens with an inline image in systemInstruction, or systemInstruction / tools of the wrong type (int, list, empty string, plain string) 200, field ignored 400 "Invalid Google countTokens request body"

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

  • Live Bedrock runtime 404 not reproduced on our AWS account
    • The customer's exact model ids return 400 today, which main already handles
    • The 404 path is proven only by the scripted-upstream integration tests

Low

  • Already on main: a Bedrock 400 from a bad request still falls back to Mantle
    • A model Mantle lacks then surfaces a confusing 404
  • Non-function tools and PDF/base64 blocks still aren't counted on Vertex (LIT-9586)
  • Vertex Gemini live checks only worked with vertex_location: global on our project

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

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 countTokens returns 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 → Gemini systemInstruction / functionDeclarations). Vertex sends them on the top-level count body; AI Studio wraps them in generateContentRequest. 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 forwards systemInstruction and 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.

mrinal-berri and others added 3 commits October 14, 2026 02:32
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>
@devin-ai-integration

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 14, 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

✅ 31 untouched benchmarks


Comparing litellm_count_tokens_bedrock_404_gemini_system_tools (930237c) with main (958cba7)

Open in CodSpeed

Co-Authored-By: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com>
@codecov

codecov Bot commented Oct 14, 2026 •

Copy link
Copy Markdown

Codecov Report

❌ Patch coverage is 96.77419% with 5 lines in your changes missing coverage. Please review.

Files with missing lines Patch % Lines
litellm/proxy/google_endpoints/endpoints.py 93.33% 3 Missing ⚠️
litellm/llms/vertex_ai/common_utils.py 77.77% 2 Missing ⚠️

📢 Thoughts on this report? Let us know!

@mrinal-berri

Copy link
Copy Markdown
Contributor Author

bugbot run

@mrinal-berri

Copy link
Copy Markdown
Contributor Author

@litereview code-review-v2

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

Comment thread litellm/llms/vertex_ai/common_utils.py Resolved
@litereview

litereview Bot commented Oct 14, 2026 •

Copy link
Copy Markdown

✅ code-review-v2

5/5 · Ready for human review

Scope: full · Full PR review.

No correctness findings.

Both open findings from the last review are fixed at head 9d65a284. I rejected the Code drift branch's OpenAI tool-name claim. It compares the count path with the chat-completions inference path, but OpenAI /v1/messages inference uses the Responses adapter by default (_RESPONSES_API_PROVIDERS = {"openai"}). That adapter forwards the tool name untruncated, and the count converter does the same, so the count request matches default inference.

Checks and execution details
  • Passed · Vertex count context unit tests (optional): Ran uv run --frozen pytest -q tests/unit/llms/vertex_ai/count_tokens/test_context.py: 13 passed.
  • Passed · OpenAI long tool-name claim (Code drift branch) (optional): Rejected after checking the source. litellm/llms/anthropic/pass_through/messages/handler.py:44,80-83 sends openai /v1/messages traffic to the Responses API unless use_chat_completions_url_for_anthropic_messages is set. responses_adapters/transformation.py:392-418 (translate_tools_to_responses_api) forwards tool_name without truncate_tool_name. That matches the count converter in openai/responses/count_tokens/transformation.py:179-187. The branch's failing comparison used the chat-completions adapter, which only runs when you opt out.
  • Passed · Real testing evidence for count-token translation changes (required): This verdict comes from the LLM translation evidence branch. It ran tests/integration/run.py providers against a real proxy with scripted upstreams for the OpenAI, Vertex Gemini and Bedrock Mantle count-token wire suites at head 9d65a284, with 93 passed. It also cited live before/after results from earlier commits for Vertex, AI Studio, Bedrock and OpenAI. Nobody reproduced a live Bedrock runtime 404, and the PR says so. Scripted wire tests cover that status branch.
  • Passed · Material review coverage (optional): The diff, the PR description, the branch reports and focused source checks were enough to assess the changed count-token paths. The UI drift branch skipped because no changed file matched its paths, so that policy does not apply here.

View review · Reviewed 9d65a284693b

…kens

Co-Authored-By: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com>
@mrinal-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.

… strict on Anthropic tools

Co-Authored-By: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com>
@mrinal-berri

Copy link
Copy Markdown
Contributor Author

@litereview code-review-v2

Co-Authored-By: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com>
mrinal-berri and others added 2 commits October 14, 2026 19:49
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>
@mrinal-berri

Copy link
Copy Markdown
Contributor Author

bugbot run

@mrinal-berri

Copy link
Copy Markdown
Contributor Author

@litereview code-review-v2

@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 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
@greptile-apps

greptile-apps Bot commented Oct 15, 2026

Copy link
Copy Markdown
Contributor

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

@joshua-berri joshua-berri 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.

lgtm

@mrinal-berri
mrinal-berri merged commit 08a24d3 into main Oct 15, 2026
90 checks passed
@mrinal-berri
mrinal-berri deleted the litellm_count_tokens_bedrock_404_gemini_system_tools branch October 15, 2026 14:36
mateo-berri added a commit that referenced this pull request Oct 19, 2026
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.
pamanseau pushed a commit to KubeTEE-AI/litellm that referenced this pull request Oct 25, 2026
…BerriAI#46430)

(cherry picked from commit 08a24d3)
Co-Authored-By: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com>
Cartofante pushed a commit to CartoDB/litellm that referenced this pull request Oct 26, 2026
…BerriAI#46430)

(cherry picked from commit 08a24d3)
Co-Authored-By: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com>
haowang1013 pushed a commit to directivegames/litellm that referenced this pull request Nov 3, 2026
…BerriAI#46430)

(cherry picked from commit 08a24d3)
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

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants