Repository navigation
fix(token_counter): cut tiktoken chunks at whitespace so long prompts are not overcounted - #54477
kerry-berri wants to merge 3 commits into
Conversation
… are not overcounted 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)".
|
PR overviewNo security issues were found in this pull request. Reviews
|
Co-Authored-By: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com>
[Medium impact] Long-text token estimates change across Python tiktoken callers. The dot-leader regression should be addressed before merging to satisfy the repository’s requirement to surface and resolve harmful caveats. Findings
|
| start = 0 | ||
| while start < len(text): | ||
| window = text[start : start + chunk_size] | ||
| length = len(window) if start + chunk_size >= len(text) else _whitespace_cut(window) | ||
| yield window[:length] | ||
| start += length |
There was a problem hiding this comment.
Loop violates local-variable rules
The new loop reassigns start and leaves start, window, and length unannotated. AGENTS.md requires Final annotations and a justified rebind-ok exception for unavoidable reassignment. Satisfy these requirements before merging.
Context Used: AGENTS.md (source)
Note: If this suggestion doesn't match your team's coding style, reply to this and let me know. I'll remember it for next time!
There was a problem hiding this comment.
Fixed in f1fd8b6. start now carries # rebind-ok with its reason, since the cursor advances by a cut whose length depends on the text. window and length are assigned inside the while body, where pyright rejects Final and the type discipline gate does not ask for it, and the gate passes at this head.
| start = 0 # rebind-ok: cursor that advances by each cut, whose length depends on the text | ||
| while start < len(text): | ||
| window = text[start : start + chunk_size] | ||
| length = len(window) if start + chunk_size >= len(text) else _whitespace_cut(window) |
There was a problem hiding this comment.
The supplied benchmark for ("Chapter" + "." * 3000 + " 12\n") * 400 now counts 22,000 tokens instead of 21,593, against 20,800 whole-text tokens. Moving the cuts makes valid prompts more likely to hit a false context-limit refusal. The repository requires harmful caveats to be surfaced rather than treated as accepted tradeoffs. Address this regression and add coverage before merging.
Rule Used: What: do not treat the caveats mentioned in the PR description as acceptable tradeoffs that some human has read and signed off on. Why: almost every time, the PR description is AI-generated, and in fact, many times, the PR description is very long. ... (source)
There was a problem hiding this comment.
The number is right and I am leaving this open for the owner instead of calling it settled. I measured the shape more widely to see how big it is. Over 256 dot-leader texts (word of 1 to 64 characters, then 500, 1500, 3000 or 5000 dots, then 12\n, repeated 100 times, o200k_base) the old cut adds 34,494 tokens in total over the whole-text count and the new cut adds 36,900, about 7% more. The new cut is worse on 131 of them, better on 118 and equal on 7, so the row in the description is one of the worse shapes and the direction depends on where the run falls against the 1024 boundary.
The cause is that a cut at whitespace starts the next chunk at the head of the punctuation run, so the run is cut at offsets that are no longer multiples of 1024, and a dot run tokenizes in blocks of 64. Removing it needs a different cut rule for punctuation runs, which is a change to how the shared counter behaves and not something I will pick on my own in this PR. I have added these numbers to the Caveats section and flagged it to the owner as an open decision.
Handwritten 1-3 sentence description
Long prompts were counted a little too high because we split the text every 1024 characters, even in the middle of a word. We now split at whitespace, so a prompt just under a model's limit is no longer refused when the provider would take it.
Details
Link to Devin session: https://app.devin.ai/sessions/8f805638708c4fc28d3a5a52be525db6
Open in Devin Desktop: https://app.devin.ai/desktop/session/8f805638708c4fc28d3a5a52be525db6?variant=devin
Requested by: @kerry-berri
TLDR
Problem this solves:
How it solves it:
Intentional product change: every count from the Python tiktoken counter for text longer than 1024 characters drops by up to about one token per 1024 characters, toward the true tiktoken count. See "What else reads this counter" below.
User Flow
Before: a developer sending a prompt just under chat-latest's limit is refused by the proxy although OpenAI accepts it
enable_pre_call_checks: trueunderrouter_settingschat-latestContext Window exceeded ... Max Input Tokens=272000, Got=272731After: the same request goes through, and a prompt really over the limit is still refused
enable_pre_call_checks: trueunderrouter_settingsprompt_tokens: 271296Max Input Tokens=272000, Got=272017, and OpenAI refuses it tooAffected release
Regression from #54260, which lowered
chat-latestmax_input_tokensto the enforced 272000. The overcount itself is older (#37697).Pre-Submission checklist
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 moreScreenshots / Proof of Fix
Shared setup. One worker, no Redis and no database, because the count is made per request and shares no state between workers.
mkprompt.py
Before (54e0e70)
Prompt under the limit (req.json)
HTTP 400,litellm.ContextWindowExceededError ... Model=openai/chat-latest, Max Input Tokens=272000, Got=272731HTTP 200,prompt_tokens: 271296, completion_tokens: 16, total_tokens: 271312After (a40026b, the two later commits only reword a test docstring and add a lint reason comment)
Prompt under the limit (req.json)
HTTP 200,prompt_tokens: 271296, completion_tokens: 16, total_tokens: 271312HTTP 200,prompt_tokens: 271296, completion_tokens: 16, total_tokens: 271312Prompt over the limit (over.json)
HTTP 400,Model=openai/chat-latest, Max Input Tokens=272000, Got=272017HTTP 400,Input tokens exceed the configured limit of 272000 tokens. Your messages resulted in 272016 tokens.New count against the whole-text tiktoken count
litellm.token_counterrun in three separate processes at a40026b: with the old fixed cut, with the new cut, and with no chunking at all (whole). "Extra" is tokens over the whole-text count. chat-latest uses o200k_base and gpt-4 uses cl100k_base. Seconds are one run each on a shared box, so differences of a few hundredths are noise.litellm/utils.pyx3)"x " * 500000(" " + "x" * 1023) * 1000("Chapter" + "." * 3000 + " 12\n") * 400Long single-character runs are the inputs the chunking was added for. Old and new give the same count, and the time doubles when the length doubles in both. Seconds on chat-latest for 0.5M, 1M, 2M and 4M characters, one run each:
.0aCan the new count land below the whole-text count? Yes, by one token, and the old count does the same. A fuzz of 3,000 random texts per encoding (words from
litellm/utils.pymixed with whitespace runs, punctuation, CJK, emoji, digit and dot runs, about 14M tokens per encoding) gave the following. Every chunk stayed within 1024 characters and the new count never went more than one token per cut over the whole-text count.What else reads this counter
Everything that calls
litellm.token_counteron a tiktoken-counted model shares this function, so all of these get the lower, closer count for text longer than 1024 characters. Text of 1024 characters or less is one chunk and its count does not change./utils/token_counterandlitellm.token_counter()called directlytrim_messages, prompt compression and the Anthropic context management editors, which keep slightly more text for the same budgetNot affected: token counts a provider returns in its own usage block, models counted with a HuggingFace tokenizer such as claude-sonnet-4-5 in the table above, and the Rust request counter, which already counts the whole text. Models with no tokenizer of their own fall back to tiktoken and do move.
Regression test
test_token_counter_long_text_with_whitespace_counts_the_same_as_the_whole_textfails 18 of 18 cases with the old fixed cut and passes with the new one.pytest tests/unit/litellm_core_utils/test_token_counter.py tests/unit/rust_bridge/test_token_counter.py tests/unit/router_rust -qgives 833 passed at a40026b.Type
🐛 Bug Fix
Caveats (if any)
Medium
Low
Final Attestation