Skip to content

fix(count_tokens): backport #47173 and #47353 to stable/1.104.x for v1.104.5 - #47685

Merged
yuneng-berri merged 8 commits into
stable/1.104.xfrom
litellm_backport_count_tokens_1_104_5_stable_1_104_x
Oct 21, 2026
Merged

yuneng-berri merged 8 commits into
stable/1.104.xfrom
litellm_backport_count_tokens_1_104_5_stable_1_104_x

Conversation

@mateo-berri

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

Copy link
Copy Markdown
Contributor

This backports the two count_tokens fixes still missing from 1.104, so DeepSeek V4 and Qwen3.5 counts come out close to what the request bills. Tool definitions are counted the way those models' chat templates render them, and DeepSeek V3 and V4 text is counted with DeepSeek's own tokenizer, which v1.104.5 ships with

On main both fixes also moved budget, rate limit, and context-management estimates, which could turn a request v1.104.4 admits into a 429. On this line they apply only to the count routes, so everything else counts as v1.104.4 does

/stupid

Original

p0-regression: LIT-9960

TLDR

Problem this solves:

  • DeepSeek V4 and Qwen3.5 counts run about 30% low with a large tool
  • DeepSeek text counts run up to twice the bill for Chinese text

How it solves it:

Intentional product change: /v1/messages/count_tokens, /utils/token_counter, /v1/responses/input_tokens and Google countTokens answer different numbers for DeepSeek V3 and V4 and Qwen3.5 models. Budgets, rate limits, context management, spend rows and the SDK token_counter keep v1.104.4's numbers

User Flow

Before: a team that checks DeepSeek V4 prompt size before sending gets a count far below what the request bills

  1. They send POST http://localhost:4000/v1/messages/count_tokens with "model": "deepseek-v4-flash" and one tool with 60 fields
  2. The response says input_tokens: 1688
  3. The same body on POST http://localhost:4000/v1/messages bills usage.input_tokens: 2434

After: the same count lands within a few tokens of the bill

  1. They send the same POST http://localhost:4000/v1/messages/count_tokens
  2. The response says input_tokens: 2433
  3. The same body on POST http://localhost:4000/v1/messages bills usage.input_tokens: 2434

Linear ticket

Resolves LIT-9960

Picks

Both picks applied after conflicts in litellm/utils.py, litellm/proxy/proxy_server.py and the wire test file, each resolved toward the count-route-only scope above. The merge took the line's uv.lock, whose only conflict was its exclude-newer timestamp

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

Screenshots / Proof of Fix

Same body sent to the count route and to inference on the line's proxy, with real Azure AI Foundry, Databricks and DeepSeek keys. Before is 5346a40 (v1.104.4), After is 6e23ab2f90, whose count code matches the tip apart from comments

Case Billed Before After
V4 Flash, large tool 2434 1688 2433
Qwen3.5, large tool 2529 1688 2427
V4 Flash, German 806 851 813
V4 Flash, Chinese 427 860 434
V4 Pro, German 885 851 813
V4 Pro, Chinese 506 860 434

The customer's own count suite ran on both trees. Of 24 cells, 6 go from fail to pass and none from pass to fail. The rows red on both are the intended 400s and the grok-4-1 and V4 Pro gaps below

Config and commands

Each run boots the line's proxy on a random port with the config below and real Azure AI Foundry, Databricks and DeepSeek keys, sends the same body to the count route and to inference, and compares the count with the billed input tokens

model_list:
  - model_name: deepseek-v4-flash
    litellm_params: {model: azure_ai/DeepSeek-V4-Flash-0731, api_base: os.environ/AZURE_FOUNDRY_API_BASE, api_key: os.environ/AZURE_FOUNDRY_API_KEY}
  - model_name: deepseek-v4-pro
    litellm_params: {model: deepseek/deepseek-v4-pro, api_key: os.environ/DEEPSEEK_API_KEY}
  - model_name: databricks-qwen3.5
    litellm_params: {model: databricks/databricks-qwen35-122b-a10b, api_base: os.environ/DATABRICKS_API_BASE, api_key: os.environ/DATABRICKS_API_KEY}
for model in deepseek-v4-flash databricks-qwen3.5; do
  BODY=$(jq -n --slurpfile t tool.json --arg m $model '{model: $m, tools: $t, messages: [{role: "user", content: "Reply with OK and do not call any tool."}]}')
  curl -s localhost:$PORT/v1/messages/count_tokens -H "x-api-key: $KEY" -H 'content-type: application/json' -d "$BODY" | jq .input_tokens
  curl -s localhost:$PORT/v1/messages -H "x-api-key: $KEY" -H 'content-type: application/json' -d "$(jq -c '. + {max_tokens: 16}' <<< "$BODY")" | jq .usage.input_tokens
done

tool.json is one submit_order tool with 60 string fields. The text case sends the same shape with a 3 KB German news text or a 2 KB Chinese one as the user message and no tools

Gauntlet-mini: SURVIVED, 5/5 lenses, 0 confirmed, run b3ecf2bd26ba, reviewed 9826be4, with the version bump 48544d3 on top. A re-run on 2de6c76 and the line merge ce19cf4 SURVIVED, 5/5 lenses, 0 confirmed, run 070741a4bc7d. Earlier rounds confirmed 7 findings, all fixed in the picks: two count changes outside the count routes, three test coverage gaps, and two test isolation gaps (run b03e97064567)

Rejected review findings and the strongest dissent
  • A tokenizer panic forced by hand gives a 500 on the count routes. v1.104.4's Anthropic tokenizer path does the same, and the bundled JSON cannot fail to parse
  • Google countTokens moves to the new counting with the other count routes. It shares the same code path, and the TLDR says so
  • With disable_hf_tokenizer_download set, tools still get the chat-template framing, which is how main behaves
  • A failed DeepSeek tokenizer load is retried on the next count and not cached. It falls back to tiktoken each time, so the count still answers 200
  • The custom tokenizer test checks the loader call by keyword, so an equivalent positional call would fail it. The same assertion shape was there before and the code calls it by keyword
  • /utils/token_counter now reports tokenizer_type as huggingface_tokenizer for DeepSeek V3 and V4, a value the field already uses for other models
  • For Qwen3.5, an Anthropic-shaped tool and the same tool in OpenAI shape count up to 10 tokens apart, since each keeps the key order inference sends
  • Malformed tools (a non-list function_declarations, a string function) count differently from v1.104.4 and still answer 200, as on main
  • Strongest dissent of the re-run: the first DeepSeek tokenizer load on a provider-error fallback took up to 1.35 s on a loaded box, inside the 5 s wait. A burst of 8 first counts did no worse than the line
  • Two defects already on the line before this PR, in the Bedrock Mantle retry's endpoint and in a 200 count with no input_tokens, are tracked separately
  • Strongest dissent: git bisect can stop at the fix(count_tokens)!: count tools the way DeepSeek V4 and Qwen3.5 chat templates render them #47173 or fix(token_counter): count DeepSeek V4 text with DeepSeek's own tokenizer #47353 pick before the openai_wire helper commit, where the wire test cannot import. The unit tests pass at every commit, and the PR merges as one unit

Type

🐛 Bug Fix

Caveats (if any)

Copied from #47173 and #47353, with the lines that main and this line do not share marked

Medium

  • DeepSeek's own API bills about 70 extra tokens per request, so V4 Pro text counts 8% to 14% low there. German ran 4% low before and Chinese 70% high
  • Under tool_choice "none", Databricks and DeepSeek's API drop the tools, so the count runs 200 to 260 tokens over the bill
  • DeepSeek V4.1 gets DeepSeek's tokenizer but keeps the old tool count, about 80% low on one short tool. A follow-up
  • grok-4-1 still counts about 6% to 9% low, unchanged from v1.104.4
  • A deployment whose name hides the DeepSeek model keeps cl100k_base. A follow-up
  • Thinking-on DeepSeek API requests count about 10% low on deepseek-v4-pro. A follow-up

Low

12 Low caveats
  • On this line only: budgets, rate limits and context management keep v1.104.4's numbers for these models, so they still undercount large tools the way the count routes did before
  • On this line only: no unit test pins the proxy count routes to the new tokenizer and tool count. The line-rig wire tests (26 passed) and the live legs above cover it
  • The first DeepSeek count per worker loads the tokenizer, about 300 ms and 75 MB
  • DeepSeek counts take about 3 times the CPU and skip the Rust counter
  • The bundled tokenizer adds 1.7 MB to the wheel
  • R1 and R1-0528 keep cl100k_base. A follow-up
  • Messages with tool calls and results still count about 10% low on V4 Flash, against 39% before
  • Only Azure, DeepSeek and Databricks were sent live on this line
  • test_token_counter_fallback_prompt_with_tools_does_not_500 in test_routes_utils.py is red on v1.104.4 and stays red
  • fix(count_tokens): backport Bedrock Mantle count_tokens fallback to stable/1.104.x #47634's Mantle wire file fails locally when a .env reaches its proxies, on the line's tip too. With CI's environment it passes 49 of 49
  • The dashboard API types file is already stale on v1.104.4 for routes the picks never touch, so it is left as the line has it
  • grype still reports claude-agent-sdk (dev only), mlflow and diskcache, which have no fixed release
  • The integration wire test cannot import at the two pick commits, since its helper comes after them

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

Note

Medium Risk
Changes how input tokens are estimated for specific models when count routes enable the new flag; incorrect regex or preamble constants could still mis-estimate prompts with tools, though default-off behavior limits blast radius outside explicit count APIs.

Overview
Adds optional chat-template-aware tool token counting so DeepSeek V4 and Qwen3.5 prompts with large tool schemas align much closer to provider billing when callers opt in.

A new chat_template_tools flag on token_counter (default false) looks up per-model rules in chat_template_tools.py: fixed preamble/implicit-system overhead plus JSON serialization that matches each family’s template (newline-joined function objects for DeepSeek V4, wrapped {"type":"function","function":…} lines for Qwen3.5). When a known section applies, tool definitions are counted from those rendered schemas instead of the legacy OpenAI “namespace functions” string, and tool_choice overhead is skipped.

Tool handling is refactored into helpers that normalize OpenAI, Anthropic (input_schema), and Gemini-style tool payloads, skip Anthropic web_search stubs, and preserve extra Anthropic keys in parameters for counting. The legacy OpenAI framing (+9 tokens, system-message discount, separate tool_choice math) remains the path when chat_template_tools is off.

A bundled deepseek_tokenizer.json is added under tokenizers/ (supporting the broader stable-line backport described in the PR; the counting logic in this diff is the template-tools piece).

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

…templates render them (#47173)

Backport of #47173 to stable/1.104.x.
Cherry-picked from c82e824 (main), applied through the line's earlier resolution c3d07e7.
Adapted to the line: the default tool count keeps the line's formatter, since #43417 is not on the line, and only the chat-template path gets the function-definition helpers.
Adapted to the stable compatibility rule: the chat-template tool count is opt-in through token_counter(chat_template_tools=True), which only the proxy count routes pass, so ITPM, budget reservation and context-management estimates keep the line's OpenAI tool framing and a request they admitted on v1.104.4 is still admitted. The tests that asserted the new framing on those paths now assert the line's framing is kept.
…zer (#47353)

Backport of #47353 to stable/1.104.x.
Cherry-picked from 2d181e6 (main).
Adapted to the stable compatibility rule: the bundled DeepSeek tokenizer is selected only on the proxy count routes, through select_count_route_tokenizer, so token_counter, encode and decode, budget reservation, ITPM, context-management triggers and failed-request spend rows keep the line's tokenizer and a request admitted on v1.104.4 is still admitted. A DeepSeek tokenizer that fails to load falls back to tiktoken on the count routes, the way every other bundled tokenizer does. The wire tests read the line's proxy_config.yaml, which has no general_settings or router_settings, and use azure_ai/grok-4 as the control model, since the line's azure_ai/grok-4-1 entry rejects tool_choice. The failed-dispatch spend test is left out, and the wire tests that asserted the DeepSeek tokenizer on those paths now assert the line's count is kept.
…plate wire test imports

Copied unchanged from main. The line had this file from #47389's first attempt until 828ddf0 narrowed that backport and removed it.
Lock-only. aiohttp 3.14.4 requires yarl>=1.25.1, so yarl moves from 1.23.0 to 1.25.1 with it. main already resolves both at or above these versions.
The backported Hugging Face download test sends HEAD to the wire peer, which the line only answered for POST, PUT, GET and DELETE.
Hand-ported from the wire.py part of 2c3866e (#43914, main), leaving out its keep-alive and connection counting.
@mateo-berri
mateo-berri requested a review from a team October 21, 2026 00:05
@mateo-berri

Copy link
Copy Markdown
Contributor Author

@litellm-stampbot

@mateo-berri

Copy link
Copy Markdown
Contributor Author

@litereview guide

@kerry-berri

kerry-berri commented Oct 21, 2026 •

Copy link
Copy Markdown
Contributor

litellm-stampbot: risk high

Not approved at ce19cf4. risk is high, a human reviewer is needed.

Rules (stampbot/risk_rules.yml):

  • low: no rule flagged it

Cursor Bugbot: Medium Risk at ce19cf4. Changes how input tokens are estimated for specific models when count routes enable the new flag; incorrect regex or preamble constants could still mis-estimate prompts with tools, though default-off behavior limits blast radius outside explicit count APIs.
Bugbot Low is low, Medium and High are high. The judge model was not called.

Pushes do not re-run this check. Comment @litellm-stampbot again to re-check the new head.

@kerry-berri kerry-berri added the risk:high Sensitive, broad, or high-risk change label Oct 21, 2026
@mateo-berri

Copy link
Copy Markdown
Contributor Author

@litereview code-review

@litereview

litereview Bot commented Oct 21, 2026

Copy link
Copy Markdown

⚠️ guide

Open preview

Scope: full · Full PR review.

Completed · Some checks not run.

Today a caller who asks /v1/messages/count_tokens how big a DeepSeek V4 or Qwen3.5 request is gets a number far below the bill. In the PR's live run, a 60-field tool counted 1688 tokens and billed 2434.

Walkthrough, one count_tokens call for deepseek-v4-flash with one tool:

  1. Caller asks for a count: the request is the same before and after.
  2. Proxy counts locally: same both ways. The answer is a local_estimate, and no request reaches the provider.
  3. Pick a tokenizer: today DeepSeek text is split with OpenAI's cl100k_base. After the fix, DeepSeek V3 and V4 use DeepSeek's bundled tokenizer, on the count routes only.
  4. Count the tools: breaks here, fixed here. Today tools get the short OpenAI summary plus 9 tokens. After the fix they get the chat template's block (222 tokens for V4, 196 for Qwen3.5) plus the tool as JSON.
  5. Answer the caller: the small example goes from 42 to 270, from a real run on this PR's proxy. The large tool goes from 1688 to 2433 against a 2434 bill, from the PR's live run.
  6. Budgets and rate limits: same both ways on purpose. ITPM limits, context checks and the SDK token_counter keep v1.104.4's numbers.

What changes for the caller: /v1/messages/count_tokens, /utils/token_counter, /v1/responses/input_tokens and Google countTokens now return counts close to the bill for these models. Nothing that decides whether a request is admitted changes.

Tests added: one integration file drives a real proxy against a scripted upstream. It covers DeepSeek and Qwen3.5 tool counts, the DeepSeek text tokenizer, and the unchanged budget, ITPM and context numbers. New unit tests check model-name matching, recorded bills (within 5%) and tokenizer fallback. I ran the unit files locally: 220 passed, 1 skipped.

Black box coverage: Nay. The three HTTP count routes and the unchanged admission path are covered. Google countTokens is not tested for these models.

Checks and execution details
  • Passed · Unit tests for the token counter and chat template tools (optional): Ran .venv/bin/python -m pytest tests/unit/litellm_core_utils/test_token_counter.py tests/unit/litellm_core_utils/prompt_templates/test_litellm_core_utils_prompt_templates_chat_template_tools.py: 220 passed, 1 skipped.
  • Passed · Live count route on this PR's proxy (optional): Started the proxy with azure_ai/DeepSeek-V4-Flash-0731 and a fake upstream key. /v1/messages/count_tokens returned 12 with no tools and 270 with one lookup tool. /utils/token_counter returned 270 with tokenizer_type: huggingface_tokenizer. The Chinese sample returned 307. The SDK token_counter with default settings still returns 42 and 547, which shows that only the count routes changed.
  • Not run · Integration wire tests (optional): These need the CircleCI integration rig (Postgres, Redis, INTEGRATION_PROXY_URL and a scripted upstream). I read them for the coverage verdict but did not run them.
  • Not run · Live provider billing comparison (optional): No provider keys were available. The billed numbers on the page come from the PR description and are labeled that way.

View review · Reviewed 48544d32db66

@litereview

litereview Bot commented Oct 21, 2026 •

Copy link
Copy Markdown

✅ code-review

5/5 · Ready for human review

Scope: full · Full PR review.

No correctness findings.

The DeepSeek tokenizer and chat-template tool framing are only reached from the proxy count routes. The routes call select_count_route_tokenizer and token_counter(..., chat_template_tools=True) from both _local_token_estimate and the provider-failure fallback through _loaded_tokenizer. The budget, ITPM, context-management and SDK paths still use _select_tokenizer and chat_template_tools=False. I ran the new wire suite against a locally started proxy with Postgres and Redis, and it passed.

Checks and execution details
  • Passed · Real testing evidence (required): Scope: litellm/litellm_core_utils/prompt_templates/chat_template_tools.py is new. It renders tool schemas only to estimate token counts. Nothing it produces goes to a provider, and it changes no request, response, stream or usage translation. That makes this rule not applicable: no LLM translation changes in the scoped paths.

Count-route evidence anyway: I ran tests/integration/providers/test_chat_template_tool_count_wire.py through tests/integration/run.py providers. The run used a locally started integration._support.proxy with Postgres 15, Redis and the owned upstream. Result: 26 passed in 36.04s.

Coverage includes:

  • DeepSeek V4 tool framing on /v1/messages/count_tokens, /utils/token_counter and /v1/responses/input_tokens
  • DeepSeek text counted with the bundled tokenizer
  • Qwen3.5 framing with and without a system turn
  • Skipping web_search and counting unmapped Anthropic keys
  • Unchanged OpenAI framing for grok
  • Unchanged budget reservation, ITPM and context-management counts for DeepSeek V4
  • Concurrent first loads

The expected values come from the bundled DeepSeek tokenizer (MIT license file included) and from cl100k.

  • Passed · Compatibility requirements (required): No previously accepted input is now rejected.

  • token_counter gains a keyword-defaulted trailing chat_template_tools=False parameter, in both the litellm.utils and core versions.

  • _select_tokenizer_helper and _return_huggingface_tokenizer gain keyword-only defaults.

  • With the defaults, SDK token_counter, budget reservation (spend_tracking/input_tokens.py), the Rust rust_tokenizer path and proxy/utils.py estimates keep v1.104.4 behavior.

The count routes now return different numbers for DeepSeek V3/V4 and Qwen3.5. /utils/token_counter also reports tokenizer_type=huggingface_tokenizer for DeepSeek, a value the field already uses for other models. The response schema is unchanged and the PR documents this as an estimate-accuracy change. No breaking marker is needed.

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

Paths traced:

  • Proxy token_counter: _local_token_estimate → select_count_route_tokenizer → _select_tokenizer_helper(count_route=True) → _load_huggingface_tokenizer('deepseek') from package resources.
  • On load failure, the except in _select_tokenizer_helper falls back to tiktoken. A unit test covers this.
  • The provider-failure path goes through _tokenizer_after_provider_error → _loaded_tokenizer, which is also switched to the count-route selector.
  • A custom_tokenizer takes precedence over the DeepSeek pick.
  • disable_hf_tokenizer_download keeps cl100k, which a unit test checks.
  • Google countTokens and Responses input_tokens reach the same internal token_counter.

Boundaries checked:

  • Non-count callers of litellm.token_counter (budget reservation, proxy/utils.py, passthrough logging) do not set chat_template_tools.
  • rust_tokenizer still uses huggingface_tokenizer_kind, which has no deepseek branch.
  • Tools that resolve to no named functions return 0 instead of OpenAI framing, and the web-search wire test checks this.

Tests run:

  • Unit: tests/unit/litellm_core_utils/test_token_counter.py and the chat-template-tools unit file, 220 passed and 1 skipped.
  • SDK: tests/integration/sdk/test_huggingface_tokenizer_downloads_sdk.py, 1 passed.
  • Wire suite: 26 passed.

I found no unresolved defects to carry into findings.


View review · Reviewed ce19cf4b61d7

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

…kport_count_tokens_1_104_5_stable_1_104_x

# Conflicts:
#	uv.lock
@mateo-berri

Copy link
Copy Markdown
Contributor Author

@litereview code-review

@mateo-berri

Copy link
Copy Markdown
Contributor Author

bugbot run

@mateo-berri

Copy link
Copy Markdown
Contributor Author

@litellm-stampbot

@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 ce19cf4. Configure here.

@yuneng-berri
yuneng-berri merged commit 9372fc0 into stable/1.104.x Oct 21, 2026
15 checks passed
@yuneng-berri
yuneng-berri deleted the litellm_backport_count_tokens_1_104_5_stable_1_104_x branch October 21, 2026 07:53

This branch was previously deployed

1 inactive deployment
e2e-changed — ce19cf4b Deployed Oct 21, 2026 by mateo-berri via oauth #6000
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

risk:high Sensitive, broad, or high-risk change

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants