Repository navigation
fix(count_tokens): backport #47173 and #47353 to stable/1.104.x for v1.104.5 - #47685
yuneng-berri merged 8 commits into
Conversation
…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.
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.
|
@litellm-stampbot |
|
@litereview guide |
litellm-stampbot: risk highNot approved at Rules (
Cursor Bugbot: Medium Risk at Pushes do not re-run this check. Comment |
|
@litereview code-review |
|
✅ code-review5/5 · Ready for human reviewScope: 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 Checks and execution details
Count-route evidence anyway: I ran Coverage includes:
The expected values come from the bundled DeepSeek tokenizer (MIT license file included) and from cl100k.
The count routes now return different numbers for DeepSeek V3/V4 and Qwen3.5.
Paths traced:
Boundaries checked:
Tests run:
I found no unresolved defects to carry into findings. View review · Reviewed |
|
bugbot run |
…ine reasons on stable/1.104.x
…kport_count_tokens_1_104_5_stable_1_104_x # Conflicts: # uv.lock
|
@litereview code-review |
|
bugbot run |
|
@litellm-stampbot |
There was a problem hiding this comment.
✅ 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.
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:
How it solves it:
Intentional product change:
/v1/messages/count_tokens,/utils/token_counter,/v1/responses/input_tokensand GooglecountTokensanswer different numbers for DeepSeek V3 and V4 and Qwen3.5 models. Budgets, rate limits, context management, spend rows and the SDKtoken_counterkeep v1.104.4's numbersUser Flow
Before: a team that checks DeepSeek V4 prompt size before sending gets a count far below what the request bills
"model": "deepseek-v4-flash"and one tool with 60 fieldsinput_tokens: 1688usage.input_tokens: 2434After: the same count lands within a few tokens of the bill
input_tokens: 2433usage.input_tokens: 2434Linear ticket
Resolves LIT-9960
Picks
chat_template_tools=True), so budget, ITPM, context management and spend rows keep OpenAI tool framingselect_count_route_tokenizer, and a tokenizer that fails to load falls back to tiktoken like every other bundled tokenizer. The failed-dispatch spend test is left out, and the wire tests that asserted the DeepSeek tokenizer on other paths now assert the line's count is keptopenai_wireintegration helper the fix(count_tokens)!: count tools the way DeepSeek V4 and Qwen3.5 chat templates render them #47173 wire test imports, copied unchanged from mainBoth picks applied after conflicts in
litellm/utils.py,litellm/proxy/proxy_server.pyand the wire test file, each resolved toward the count-route-only scope above. The merge took the line'suv.lock, whose only conflict was itsexclude-newertimestampPre-Submission checklist
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
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
tool.jsonis onesubmit_ordertool 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 toolsGauntlet-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
countTokensmoves to the new counting with the other count routes. It shares the same code path, and the TLDR says sodisable_hf_tokenizer_downloadset, tools still get the chat-template framing, which is how main behaves/utils/token_counternow reportstokenizer_typeashuggingface_tokenizerfor DeepSeek V3 and V4, a value the field already uses for other modelsfunction_declarations, a stringfunction) count differently from v1.104.4 and still answer 200, as on maininput_tokens, are tracked separatelygit bisectcan 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 theopenai_wirehelper commit, where the wire test cannot import. The unit tests pass at every commit, and the PR merges as one unitType
🐛 Bug Fix
Caveats (if any)
Copied from #47173 and #47353, with the lines that main and this line do not share marked
Medium
tool_choice"none", Databricks and DeepSeek's API drop the tools, so the count runs 200 to 260 tokens over the billcl100k_base. A follow-updeepseek-v4-pro. A follow-upLow
12 Low caveats
cl100k_base. A follow-uptest_token_counter_fallback_prompt_with_tools_does_not_500intest_routes_utils.pyis red on v1.104.4 and stays red.envreaches its proxies, on the line's tip too. With CI's environment it passes 49 of 49Final Attestation
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_toolsflag ontoken_counter(default false) looks up per-model rules inchat_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, andtool_choiceoverhead is skipped.Tool handling is refactored into helpers that normalize OpenAI, Anthropic (
input_schema), and Gemini-style tool payloads, skip Anthropicweb_searchstubs, and preserve extra Anthropic keys in parameters for counting. The legacy OpenAI framing (+9 tokens, system-message discount, separatetool_choicemath) remains the path whenchat_template_toolsis off.A bundled
deepseek_tokenizer.jsonis added undertokenizers/(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.