Skip to content

fix(count_tokens): backport Bedrock Mantle count_tokens fallback to stable/1.104.x - #47634

Merged
mateo-berri merged 10 commits into
stable/1.104.xfrom
litellm_backport_bedrock_mantle_count_stable_1_104_x
Oct 21, 2026
Merged

mateo-berri merged 10 commits into
stable/1.104.xfrom
litellm_backport_bedrock_mantle_count_stable_1_104_x

Conversation

@mateo-berri

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

Copy link
Copy Markdown
Contributor

TLDR

Problem this solves:

  • Bedrock Runtime CountTokens rejects newer Claude models on stable 1.104
  • /v1/messages/count_tokens then falls back to a local estimate that undercounts

How it solves it:

  • Try Bedrock Runtime first, as before
  • On a 400 or 404 for a Claude model, count on the Bedrock Mantle Anthropic endpoint
  • If Mantle also fails, keep the existing local estimate fallback. Non-Claude models never call Mantle

Backport of #45317 plus the Bedrock part of #46430 onto stable/1.104.x, bumped to 1.104.5. Also carries an aiohttp lock bump from the grype sweep

User Flow

Before: a team counting Claude Opus 4.8 tokens on Bedrock gets a number far below what inference bills

  1. They send POST http://localhost:4000/v1/messages/count_tokens with "model": "opus-4-8" and one short user message
  2. The response says input_tokens: 27 with litellm_count_source: local_estimate
  3. The same message on POST http://localhost:4000/v1/messages bills usage.input_tokens: 42

After: the same count matches what inference bills

  1. They send the same POST http://localhost:4000/v1/messages/count_tokens
  2. The response says input_tokens: 42 counted by global.anthropic.claude-opus-4-8
  3. The same message on POST http://localhost:4000/v1/messages bills usage.input_tokens: 42

Linear ticket

Resolves LIT-9563

Pre-Submission checklist

  • I have added meaningful tests
  • The handful of test files covering my change pass locally
  • 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
  • I have received a Greptile Confidence Score of at least 4/5 before requesting a maintainer review

Screenshots / Proof of Fix

Two proxies with the same config and real AWS credentials, stable base on port 4001 and this branch on port 4002

curl -sS -X POST http://127.0.0.1:4001/v1/messages/count_tokens -H 'Authorization: Bearer sk-1234' -H 'Content-Type: application/json' \
  -d '{"model":"opus-4-8","messages":[{"role":"user","content":"The quick brown fox jumps over the lazy dog. The quick brown fox jumps over the lazy dog."}]}'
# base:   input_tokens 27, litellm_count_source local_estimate, HTTP 200
# branch: input_tokens 42, litellm_count_source token_count_model, litellm_count_model global.anthropic.claude-opus-4-8, HTTP 200

curl -sS -X POST http://127.0.0.1:4001/v1/messages -H 'Authorization: Bearer sk-1234' -H 'Content-Type: application/json' \
  -d '{"model":"opus-4-8","max_tokens":16,"messages":[{"role":"user","content":"The quick brown fox jumps over the lazy dog. The quick brown fox jumps over the lazy dog."}]}'
# base and branch: usage.input_tokens 42, HTTP 200

Sonnet 4.6 (runtime counts it) and Nova Lite (non-Claude, local estimate) return the same counts on both lines, so neither path changed

A customer's count-vs-usage suite over 60 Bedrock, Vertex and Databricks deployments went from 122 to 157 passing rows. All 42 newly passing rows are Claude Opus 4.7 to 5.5 and Sonnet 5 to 5.5, now matching billed usage exactly. The one row that flipped the other way (Sonnet 4.6 large system plus tool) did not reproduce on a focused rerun

The Mantle wire integration test passes 49 of 49 here and fails 33 of 49 on the stable base. /gauntlet-mini survived 5 of 5 lenses at f0aa9d5 (run 618fb3ad5635)

Caveats

A customer's count-vs-usage suite still fails these rows on both the stable base and this branch, so none of them are regressions from this PR. Bedrock and Vertex rows ran on the Devin rig. Azure, Azure AI, OpenAI and Databricks rows ran on a second machine with same-model substitutes for private customer hosts, plus three retry passes. No row passed on base and failed on the branch

Root cause Provider Rows Example Real LiteLLM bug
Non-Claude base64 PDF, local estimate ignores the document bedrock 12 Llama 4 Maverick counts 193 vs 10,976 billed for 12 pages Yes, main has #47613 in flight
Nova 2 Lite undercounts large tool payloads bedrock 2 2,131 counted vs 2,974 billed Yes, no fix yet
Local estimate off by more than 5% azure_ai 8 DeepSeek V4 large_tool 2,129 vs 2,344, Grok baseline 1,104 vs 937 Yes, local tokenizer gap, no fix yet
Sonnet 4.6 large system plus tool, full run only bedrock 1 3,142 vs 3,641, focused rerun matched Likely flake
Vertex HTTP 500 from our test rig vertex_ai 77 gemini-2.5-flash on every case No, rig credentials or region
Serving endpoint not deployed in the workspace (ENDPOINT_NOT_FOUND) databricks 56 every case on 8 endpoints No, endpoints absent
Base64 PDF rejected as invalid image URL (HTTP 400) azure 16 gpt-4.1, gpt-5.1, gpt-5.2 PDF cases No, provider capability
PDF rejected by a text-only model (HTTP 400) azure_ai 6 DeepSeek V4 Pro, Grok PDF cases No, provider capability
large_user exceeds the 272k context, suite records FAIL azure 5 gpt-5.1, gpt-5.2 large_user No, suite design
Invalid or retired Bedrock model ids in the config bedrock 9 No, config
Bedrock models rejecting PDF input or a request param bedrock 8 No, provider limits
Vertex GLM needs google-cloud-aiplatform installed vertex_ai 7 No, rig dependency
Bedrock 429 throttling or unknown provider error bedrock 6 No, transient
Persistent 429 after retries azure_ai 4 DeepSeek V4, Grok, Kimi large_user No, provider quota
large_user exceeds context, suite skips openai, azure 15 o3, o4-mini, gpt-5.4-mini No, suite design
Azure version is retiring and cannot be deployed (ServiceModelDeprecating) azure 7 deployments gpt-4o-2024-08-06, o3-2025-04-16 No, not run

Embeddings, mocks, responses-only models and auto-routers are excluded by the suite itself

Link to Devin session: https://app.devin.ai/sessions/7663d25bd05a4d06b8871043e834b3a0
Open in Devin Desktop: https://app.devin.ai/desktop/session/7663d25bd05a4d06b8871043e834b3a0?variant=devin
Requested by: @mateo-berri


Note

Medium Risk
Changes token-count routing for Bedrock Claude (new Mantle API path) and alters proxy responses from 200 with wrong local counts to 400 for known-bad estimates, which may break callers relying on those numbers.

Overview
Bedrock token counting now tries bedrock-runtime CountTokens first, then on 400/404 for Claude models falls back to bedrock-mantle (/anthropic/v1/messages/count_tokens) via a new BedrockMantleCountTokensHandler. Responses report bedrock_api vs bedrock_mantle_api; other runtime failures are not retried on Mantle.

Proxy behavior: when provider counting fails and the path would use a local estimate (call_endpoint=True), new unreliable_local_estimate rules return HTTP 400 instead of misleading counts—for document/file content, Bedrock Nova 2 Lite with tools, and selected Azure AI models—while successful provider counts are unchanged.

Version 1.104.5; broad unit, wire, and e2e coverage for Mantle fallback and the estimate guard.

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

mateo-berri and others added 10 commits October 20, 2026 17:45
Minimal prerequisite from #43646 for stable/1.104.x.

Co-Authored-By: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com>
…not count a Claude model (#45317)

Backport of #45317 to stable/1.104.x.
Cherry-picked from 577d74c (main).

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

Backport of #46430 to stable/1.104.x.
Cherry-picked from 08a24d3 (main), Bedrock changes only.

Co-Authored-By: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com>
Replace the main-only Bedrock runtime peer helper with stable-compatible test-local handlers and add the missing Mapping import.

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

@mateo-berri

Copy link
Copy Markdown
Contributor Author

@litereview code-review

@mateo-berri

Copy link
Copy Markdown
Contributor Author

@greptileai

@litereview

litereview Bot commented Oct 20, 2026 •

Copy link
Copy Markdown

New commits were pushed. This review covers 55bb1ae3f379.

⚠️ code-review

3/5 · Changes needed

Scope: full · Full PR review.

Completed · Checks failed.

Two blockers:

  • The new document guard reports provider outages and throttling as a permanent client 400.
  • The PR makes an intentional 200 → 400 change, but the title has no breaking-change marker.

The Mantle fallback itself passed its wire integration suite locally (49/49).

Checks and execution details
  • Passed · Real testing evidence (required): Scope: the translation changes are under litellm/llms/bedrock/count_tokens/**. They include the new Mantle request transform, the runtime-to-Mantle fallback on 400/404 for Claude only, and the response and error mapping.

  • Integration: I ran tests/integration/providers/test_bedrock_mantle_count_tokens_wire.py locally through tests/integration/run.py providers against a real proxy, Postgres, Redis and local SigV4 wire peers. Result: 49 passed. The tests assert the literal Mantle body (system string and blocks, tools, empty fields omitted). They cover runtime 400/404 → Mantle, Nova 404 with no Mantle call, Claude 403 with no Mantle call, Mantle 400/403/404/500/503, missing input_tokens, unreachable and timeout → local fallback, and disable_token_counter surfacing the Mantle error. The SDK, responses and Gemini surfaces are covered too. Peer replies are scripted.

  • Real-value evidence: The PR shows two proxies with real AWS credentials. Base returns 27 local_estimate; the branch returns 42 token_count_model global.anthropic.claude-opus-4-8, matching billed usage.input_tokens: 42. The runtime rejection text in the fixtures is Bedrock's real message.

  • Live e2e: tests/e2e/llm_translation/test_messages_count_tokens_bedrock_e2e.py asserts count within 5% of billed. I did not run it here because it needs AWS credentials.

The unreliable_local_estimate 400 guard lives in litellm/proxy/**, outside this rule's scope.

  • Failed · Compatibility requirements (required): Before: /v1/messages/count_tokens with a document block on a model with no server-side counter, or Nova 2 Lite with tools, Azure AI DeepSeek V4 with tools, or Azure AI Grok 4 without tools, returned HTTP 200 with a local estimate.

After: the same requests return HTTP 400 invalid_request_error.

The PR body describes the impact, but the title fix(count_tokens): ... has no ! and the body gives no migration guidance. Reported as a finding.

  • Passed · Changed behavior and result consistency (required): Read root AGENTS.md, tests/integration/AGENTS.md/README.md and tests/e2e/AGENTS.md.

Paths traced:

  • Mantle fallback: anthropic_endpoints/endpoints.py → count_request_tokens → _get_provider_token_counter (BedrockModelInfo) → _provider_token_count → BedrockTokenCounter.count_tokens → runtime handler → _runtime_rejected_claude_model → Mantle handler (build_mantle_messages_url, AnthropicCountTokensConfig, SigV4) → TokenCountResponse/ProviderCountFailure → local fallback.
  • New guard: ladder failure or None → unreliable_local_estimate → ProxyException 400.

Boundaries checked: runtime 400/404/403/5xx, non-Claude models, Mantle errors, empty system/tools, disable_token_counter, and a transient provider failure combined with a document block. The last one is a defect, reproduced with a stubbed 429 and reported as a finding.

Unit suites tests/unit/llms/bedrock/count_tokens/ and tests/unit/proxy/test_proxy_token_counter.py: 211 passed.

  • Passed · Unit tests for count_tokens (optional): pytest tests/unit/llms/bedrock/count_tokens/ tests/unit/proxy/test_proxy_token_counter.py → 211 passed.
  • Not run · Live Bedrock e2e test (optional): tests/e2e/llm_translation/test_messages_count_tokens_bedrock_e2e.py needs real AWS credentials, which are not available in this sandbox.

View review · Reviewed 55bb1ae3f379

@greptile-apps

greptile-apps Bot commented Oct 20, 2026 •

Copy link
Copy Markdown
Contributor

RetriggerView in GreptileConfidence Score: 4/5

[Medium impact] The PR changes token-count results and errors across bounded provider-count workflows.

Fix the nested-document check before merging so PDFs returned by tools cannot receive known-wrong local counts

Findings

  1. P1 Tool PDFs get wrong counts ▶

Summary

Backports Bedrock Mantle token counting to stable 1.104.5

  • Claude token counts use Bedrock Mantle when Runtime rejects them.
  • Known-unreliable local token estimates now return a clear error.
  • The stable release is versioned as 1.104.5.

mateo-berri accepted the existing Mantle system-message and region-signing limitations because this backport matches main and preserves stable’s local fallback. Both fixes were deferred to main first

Reviews (3) · Last reviewed commit: "fix(count_tokens): verify azure provider..." · Reviewed by Greptile

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

Stale Bugbot comment from a previous run.

@CLAassistant

CLAassistant commented Oct 20, 2026 •

Copy link
Copy Markdown

CLA assistant check
Thank you for your submission! We really appreciate it. Like many open source projects, we ask that you all sign our Contributor License Agreement before we can accept your contribution.
2 out of 3 committers have signed the CLA.

✅ mrinal-berri
✅ mateo-berri
❌ devin-ai-integration[bot]
You have signed the CLA already but the status is still pending? Let us recheck it.

@mateo-berri

Copy link
Copy Markdown
Contributor Author

@litereview code-review

@mateo-berri

Copy link
Copy Markdown
Contributor Author

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

Cursor Bugbot has reviewed your changes using default effort and found 1 potential issue.

Fix All in Cursor

❌ Bugbot Autofix is OFF. To automatically fix reported issues with cloud agents, enable autofix in the Cursor dashboard.

Reviewed by Cursor Bugbot for commit 55bb1ae. Configure here.

Comment thread litellm/proxy/proxy_server.py Outdated
type="invalid_request_error",
param="model",
code=400,
)

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.

Hard 400 hides provider count failures

Medium Severity

The unreliable-local-estimate guard runs after every unsuccessful provider count, including rate limits and 5xx errors. Those requests get a client 400 that says there is no server-side count, so a retryable upstream failure is rewritten as a permanent invalid request and the original status is dropped.

Additional Locations (1)
Fix in Cursor Fix in Web

Reviewed by Cursor Bugbot for commit 55bb1ae. Configure here.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Hard 400 moved to #47705 and fixed in 026df91. A provider 429 or 5xx now keeps its own status, and only 400 or 404 gets the hard 400

Comment on lines +113 to +116
def _has_document_content_block(messages: Sequence[object] | None) -> bool:
return any(
any(_is_document_content_block(block) for block in _content_blocks(message)) for message in messages or ()
)

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.

P1 Tool PDFs get wrong counts

PDFs inside tool_result.content bypass this check after provider counting fails, returning the same wrong local count. Scan nested blocks before allowing fallback

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Hard 400 moved to #47705 and fixed in 026df91. Document detection now recurses into nested content, so a PDF inside tool_result content is caught

Comment thread litellm/proxy/proxy_server.py Outdated
if isinstance(ladder, TokenCountResponse):
return ladder

if call_endpoint is True:

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Medium · Throttled or failed count on a PDF request returns a permanent 400 instead of the provider error

  1. A Bedrock deployment points at us.anthropic.claude-sonnet-4-6. bedrock-runtime CountTokens supports this model, and the PR's own Sonnet PDF transcript shows a server-side count of 2708.
  2. A caller sends POST /v1/messages/count_tokens with a base64 PDF document block. Bedrock answers 429 (throttled), 500 or 503, or the connection fails.
  3. _provider_token_count returns a ProviderCountFailure with that status. count_request_tokens then calls unreliable_local_estimate. That function returns a reason for any document block, whatever the failure status or provider.
  4. The caller gets HTTP 400 invalid_request_error, and the message says the model has no server-side count_tokens. Clients treat 400 as non-retryable, so a transient throttle becomes a permanent rejection with a false explanation. Before this PR the same request got a 200 local estimate.

Smallest fix: run the document guard only when ladder is None or ladder.cannot_count_model (400/404 from the provider). For other failures, answer with ladder.to_proxy_exception() so the real status reaches the caller.

Evidence

Reproducer (code path executed with _provider_token_count stubbed to a 429 ProviderCountFailure, Router deployment bedrock/us.anthropic.claude-sonnet-4-6, PDF document block): RAISED 400 invalid_request_error us.anthropic.claude-sonnet-4-6 returned no server-side token count and LiteLLM cannot count document content locally

With only unreliable_local_estimate patched out, the same input returns total_tokens=95 count_source='local_estimate' (the previous behavior).

token_count_settings.py:15: CANNOT_COUNT_MODEL_STATUSES = frozenset({400, 404}) and ProviderCountFailure.cannot_count_model already exist to mean 'the provider cannot count this model', but the new guard does not consult them.

The same path applies when bedrock-runtime returns 400 for a Claude model and Mantle then returns 429/5xx (_runtime_rejected_claude_model → Mantle outcome → CountTokensFailure).

Latest summary by code-review · View this review · Reviewed 55bb1ae3f379

Comment thread litellm/proxy/proxy_server.py Outdated
if isinstance(ladder, TokenCountResponse):
return ladder

if call_endpoint is True:

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Low · Intentional 200→400 change for count_tokens ships without a breaking-change marker

  1. A caller uses POST /v1/messages/count_tokens or /utils/token_counter?call_endpoint=true. The request either has a document/file content block on a model with no server-side count (for example Bedrock Llama 4 Maverick), or targets Bedrock Nova 2 Lite with tools, Azure AI DeepSeek V4 with tools, or Azure AI Grok 4 without tools.
  2. On the stable 1.104.4 line these requests return HTTP 200 with a local estimate.
  3. This PR adds the unreliable_local_estimate guard in count_request_tokens.
  4. The same requests now return HTTP 400 invalid_request_error, which breaks any caller that consumed the number. The PR body states this as an intentional product change, but the title fix(count_tokens): ... has no !. The body gives no migration path either, such as a flag to keep the estimate.

Fix: retitle as fix(count_tokens)!: ... and add a short migration note, for example that callers needing a number should send models with a server-side counter or set token_count_model.

Evidence

PR body: "Intentional product change: those requests used to get HTTP 200 with a wrong local count. They now get HTTP 400 ... Callers that relied on the wrong number lose it"

Unit test test_count_request_tokens_rejects_only_known_unreliable_estimates asserts code == "400" for bedrock/meta.llama4-maverick + document, bedrock/us.amazon.nova-2-lite + tools, azure_ai/deepseek-v4-pro + tools, azure_ai/grok-4-1-fast-reasoning without tools.

Target branch is a stable patch line (version bump 1.104.4 → 1.104.5).

Latest summary by code-review · View this review · Reviewed 55bb1ae3f379

This branch was previously deployed

1 inactive deployment
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.

4 participants