Skip to content

fix(proxy): raise on provider count_tokens errors instead of falling back to tiktoken - #46121

Merged
yuneng-berri merged 2 commits into
mainfrom
litellm_count_tokens_raise_on_provider_error
Oct 13, 2026
Merged

yuneng-berri merged 2 commits into
mainfrom
litellm_count_tokens_raise_on_provider_error

Conversation

@krrish-berri-2

Copy link
Copy Markdown
Contributor

TLDR

Problem this solves:

  • count_tokens hides provider errors behind a local tiktoken estimate
  • A bad key or provider outage returns 200 with a wrong count

How it solves it:

  • A failed provider counting call now raises with the provider's status and message
  • Providers with no counting API still count locally, as before

Intentional product change: when a provider's count_tokens API is called and fails, /v1/messages/count_tokens, /v1/responses/input_tokens and the Gemini countTokens route return that error instead of a local tiktoken count. Callers who relied on always getting a number now get a 4xx or 5xx

User Flow

Before: a Claude Code user behind the proxy gets a made-up token count when the Anthropic call fails

  1. The admin configures an Anthropic model whose key is invalid
  2. The user sends POST http://localhost:4000/v1/messages/count_tokens with that model
  3. They get 200 {"input_tokens":11}, a tiktoken estimate, while the real Anthropic count is 14

After: the same request returns Anthropic's own error

  1. The admin configures an Anthropic model whose key is invalid
  2. The user sends POST http://localhost:4000/v1/messages/count_tokens with that model
  3. They get 401 with Anthropic's authentication_error "invalid x-api-key"

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

Screenshots / Proof of Fix

Config, real Anthropic API, one deployment with a working key and one with a bogus key

model_list:
  - model_name: claude-good
    litellm_params:
      model: anthropic/claude-sonnet-5-5
      api_key: os.environ/ANTHROPIC_API_KEY
  - model_name: claude-bad
    litellm_params:
      model: anthropic/claude-sonnet-5-5
      api_key: sk-ant-bogus
general_settings:
  master_key: sk-1234
  dangerously_permit_weak_or_unset_master_key: true

Before (aa52927)

Working key

  1. curl -sS -w "\nHTTP %{http_code}\n" http://localhost:4100/v1/messages/count_tokens -H "Authorization: Bearer sk-1234" -H "Content-Type: application/json" -d '{"model":"claude-good","messages":[{"role":"user","content":"count these tokens please"}]}'
  2. Output
{"input_tokens":14}
HTTP 200

Bogus key

  1. Same curl with "model":"claude-bad"
  2. Output, a silent tiktoken estimate that does not match the real count
{"input_tokens":11}
HTTP 200

After (9576dcd)

Working key

  1. curl -sS -w "\nHTTP %{http_code}\n" http://localhost:4101/v1/messages/count_tokens -H "Authorization: Bearer sk-1234" -H "Content-Type: application/json" -d '{"model":"claude-good","messages":[{"role":"user","content":"count these tokens please"}]}'
  2. Output
{"input_tokens":14}
HTTP 200

Bogus key

  1. Same curl with "model":"claude-bad"
  2. Output, Anthropic's own error
{"detail":{"type":"error","error":{"type":"authentication_error","message":"invalid x-api-key"},"request_id":"req_011CfyJj7Wf3rD6YuqpVULv3"}}
HTTP 401

Type

🐛 Bug Fix

Caveats (if any)

Severe

  • Deliberate behavior change for every provider with a counting API
    • Anthropic, Bedrock and Mantle, Vertex, Gemini, Azure AI, OpenAI responses
    • Outages and rate limits now fail count_tokens instead of estimating
  • Bedrock non-Claude models the runtime cannot count (e.g. Nova) now error
  • Requests whose messages are all system now return the provider's 400

Medium

  • A malformed system message the counter rejects locally now returns 500, not 400

Low

  • disable_token_counter now only matters for providers without a counting API
  • SDK litellm.acount_tokens is unchanged and still falls back locally

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/bd6127a6332c497a88fb4006154cf458
Open in Devin Desktop: https://app.devin.ai/desktop/session/bd6127a6332c497a88fb4006154cf458?variant=devin
Requested by: @krrish-berri-2

…back to tiktoken

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

@CLAassistant

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 sign our Contributor License Agreement before we can accept your contribution.
You have signed the CLA already but the status is still pending? Let us recheck it.

@chatgpt-codex-connector

chatgpt-codex-connector Bot commented Oct 13, 2026 •

Copy link
Copy Markdown

Codex Review Summary

This comment shows the latest Codex review activity on this pull request.

Review Status Commit Review trigger
📝 Code Review ✅ Completed 2026-10-13T00:53:30.046263Z 9576dcd PR opened
ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review" or "@codex security review".

Codex reacts with 👀 while any review is running, comments if it has suggestions, and reacts with 👍 once all reviews finish with no findings.

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: 9576dcd32b

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

response: Final = _count(gateway, body)
assert _payload(response) == {"input_tokens": local}, response.text
assert response.status_code == status, response.text
assert "input_tokens" not in response.text, response.text

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P1 Badge Assert the propagated provider message

When the provider rejects a request, this still passes if LiteLLM replaces its message with a generic error. Assert REJECTION instead

AGENTS.md reference: AGENTS.md:L28-L28

Useful? React with 👍 / 👎.

assert response.request_model == "claude-test"
assert response.model_used == "claude-3-sonnet-20240229"
assert response.total_tokens > 0
# The provider counter is engaged: its API error surfaces instead of a local count

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P1 Badge Remove the redundant test comment

Remove this narration because the test name and assertion already explain it, while repository rules permit comments only for exceptional cases

AGENTS.md reference: AGENTS.md:L1-L7

Useful? React with 👍 / 👎.

),
call_endpoint=True,
)
with patch("litellm.token_counter") as mock_local_counter:

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P1 Badge Avoid patching LiteLLM's local counter

Remove this LiteLLM function patch. The raised provider error already proves the fallback path was skipped without doubling our own code

AGENTS.md reference: tests/unit/AGENTS.md:L17-L17

Useful? React with 👍 / 👎.

@codspeed

codspeed Bot commented Oct 13, 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_raise_on_provider_error (a2cb20d) with main (784581b)

Open in CodSpeed

@codecov

codecov Bot commented Oct 13, 2026

Copy link
Copy Markdown

Codecov Report

✅ All modified and coverable lines are covered by tests.

📢 Thoughts on this report? Let us know!

@yuneng-berri
yuneng-berri enabled auto-merge (squash) October 13, 2026 18:56
@yuneng-berri
yuneng-berri merged commit 719c44d into main Oct 13, 2026
108 of 109 checks passed
@yuneng-berri
yuneng-berri deleted the litellm_count_tokens_raise_on_provider_error branch October 13, 2026 19:08
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.
mateo-berri added a commit that referenced this pull request Oct 19, 2026
Defer the breaking error policy from #46121. Adapt the #46777 count settings flow to attempt a labelled local estimate for provider failures across providers and configured count models.

Keep provider errors when local counting is disabled or cannot estimate the request, and test the shared behavior across HTTP error statuses.

This branch had an error being deployed

1 failed deployment
e2e-changed — a2cb20d8 Deployed Oct 13, 2026 by yuneng-berri via oauth #4772
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.

5 participants