Repository navigation
fix(count_tokens): backport Bedrock Mantle count_tokens fallback to stable/1.104.x - #47634
mateo-berri merged 10 commits into
Conversation
Minimal prerequisite from #43646 for stable/1.104.x. 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>
|
I'll fix CI failures and address comments from users with write access. I'll skip comments containing "(aside)".
|
|
@litereview code-review |
|
[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
SummaryBackports Bedrock Mantle token counting to stable
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 |
|
bugbot run |
|
|
|
@litereview code-review |
|
@greptileai review |
|
bugbot run |
There was a problem hiding this comment.
Cursor Bugbot has reviewed your changes using default effort and found 1 potential issue.
❌ 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.
| type="invalid_request_error", | ||
| param="model", | ||
| code=400, | ||
| ) |
There was a problem hiding this comment.
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)
Reviewed by Cursor Bugbot for commit 55bb1ae. Configure here.
| 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 () | ||
| ) |
55bb1ae to
041deed
Compare
| if isinstance(ladder, TokenCountResponse): | ||
| return ladder | ||
|
|
||
| if call_endpoint is True: |
There was a problem hiding this comment.
Medium · Throttled or failed count on a PDF request returns a permanent 400 instead of the provider error
- 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. - A caller sends
POST /v1/messages/count_tokenswith a base64 PDFdocumentblock. Bedrock answers 429 (throttled), 500 or 503, or the connection fails. _provider_token_countreturns aProviderCountFailurewith that status.count_request_tokensthen callsunreliable_local_estimate. That function returns a reason for any document block, whatever the failure status or provider.- The caller gets HTTP 400
invalid_request_error, and the message says the model has no server-sidecount_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
| if isinstance(ladder, TokenCountResponse): | ||
| return ladder | ||
|
|
||
| if call_endpoint is True: |
There was a problem hiding this comment.
Low · Intentional 200→400 change for count_tokens ships without a breaking-change marker
- A caller uses
POST /v1/messages/count_tokensor/utils/token_counter?call_endpoint=true. The request either has adocument/filecontent 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. - On the stable 1.104.4 line these requests return HTTP 200 with a local estimate.
- This PR adds the
unreliable_local_estimateguard incount_request_tokens. - 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 titlefix(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


TLDR
Problem this solves:
/v1/messages/count_tokensthen falls back to a local estimate that undercountsHow it solves it:
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 sweepUser Flow
Before: a team counting Claude Opus 4.8 tokens on Bedrock gets a number far below what inference bills
"model": "opus-4-8"and one short user messageinput_tokens: 27withlitellm_count_source: local_estimateusage.input_tokens: 42After: the same count matches what inference bills
input_tokens: 42counted byglobal.anthropic.claude-opus-4-8usage.input_tokens: 42Linear ticket
Resolves LIT-9563
Pre-Submission checklist
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
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-minisurvived 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
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 newBedrockMantleCountTokensHandler. Responses reportbedrock_apivsbedrock_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), newunreliable_local_estimaterules 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.