Skip to content

fix(token_counter): cut tiktoken chunks at whitespace so long prompts are not overcounted - #54477

Open
kerry-berri wants to merge 3 commits into
mainfrom
litellm_token_counter_whitespace_chunks
Open

kerry-berri wants to merge 3 commits into
mainfrom
litellm_token_counter_whitespace_chunks

Conversation

@kerry-berri

@kerry-berri kerry-berri commented Nov 25, 2026 •

Copy link
Copy Markdown
Contributor

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:

  • Chunks now end at whitespace instead of mid-word
  • Chunk size cap and linear cost are unchanged
  • The cost map limit stays at 272000

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

  1. The proxy admin sets enable_pre_call_checks: true under router_settings
  2. The developer sends POST http://localhost:4101/v1/chat/completions with a 271,296 token prompt to chat-latest
  3. They get 400 Context Window exceeded ... Max Input Tokens=272000, Got=272731
  4. The same body sent to https://api.openai.com/v1/chat/completions returns 200

After: the same request goes through, and a prompt really over the limit is still refused

  1. The proxy admin sets enable_pre_call_checks: true under router_settings
  2. The developer sends the same POST with the 271,296 token prompt
  3. They get 200 with prompt_tokens: 271296
  4. A 272,016 token prompt still gets 400 Max Input Tokens=272000, Got=272017, and OpenAI refuses it too

Affected release

Regression from #54260, which lowered chat-latest max_input_tokens to the enforced 272000. The overcount itself is older (#37697).

Pre-Submission checklist

  • 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

Screenshots / 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.

# config.yaml
model_list:
  - model_name: chat-latest
    litellm_params:
      model: openai/chat-latest
      api_key: os.environ/OPENAI_API_KEY
router_settings:
  enable_pre_call_checks: true
  num_retries: 0
litellm_settings:
  num_retries: 0
general_settings:
  master_key: os.environ/LITELLM_MASTER_KEY
# env: OPENAI_API_KEY, LITELLM_MASTER_KEY
python litellm/proxy/proxy_cli.py --config config.yaml --port 4101
python mkprompt.py 271290 req.json    # whole-text o200k count 271290, 1,386,713 chars
python mkprompt.py 272010 over.json   # whole-text o200k count 272010, 1,390,460 chars
curl -s -w "HTTP %{http_code}\n" localhost:4101/v1/chat/completions -H "Authorization: Bearer $LITELLM_MASTER_KEY" -H "Content-Type: application/json" -d @req.json
curl -s -w "HTTP %{http_code}\n" https://api.openai.com/v1/chat/completions -H "Authorization: Bearer $OPENAI_API_KEY" -H "Content-Type: application/json" -d @req.json
mkprompt.py
import json, random, sys, tiktoken
enc = tiktoken.get_encoding("o200k_base")
target = int(sys.argv[1]); out = sys.argv[2]
random.seed(7)
import litellm, inspect, pathlib
words = list({w for w in pathlib.Path(inspect.getfile(litellm)).read_text().split() if w.isalpha()})
parts = []
while True:
    parts.extend(random.choice(words) for _ in range(2000))
    text = " ".join(parts)
    if len(enc.encode(text)) >= target: break
text = enc.decode(enc.encode(text)[:target])
print("whole-text tokens", len(enc.encode(text)), "chars", len(text))
json.dump({"model": "chat-latest", "messages": [{"role": "user", "content": text}], "max_completion_tokens": 16}, open(out, "w"))

Before (54e0e70)

Prompt under the limit (req.json)

  1. Proxy: HTTP 400, litellm.ContextWindowExceededError ... Model=openai/chat-latest, Max Input Tokens=272000, Got=272731
  2. OpenAI direct: HTTP 200, prompt_tokens: 271296, completion_tokens: 16, total_tokens: 271312

After (a40026b, the two later commits only reword a test docstring and add a lint reason comment)

Prompt under the limit (req.json)

  1. Proxy: HTTP 200, prompt_tokens: 271296, completion_tokens: 16, total_tokens: 271312
  2. OpenAI direct: HTTP 200, prompt_tokens: 271296, completion_tokens: 16, total_tokens: 271312

Prompt over the limit (over.json)

  1. Proxy: HTTP 400, Model=openai/chat-latest, Max Input Tokens=272000, Got=272017
  2. OpenAI direct: HTTP 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_counter run 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.

Input Model Chars Whole count Old extra New extra New s Old s
repro prompt chat-latest 1,386,713 271,290 +1434 0 0.397 0.414
repro prompt gpt-4 1,386,713 279,822 +1467 0 0.077 0.077
English prose, spaces chat-latest 2,429,915 704,484 +2143 0 0.138 0.137
English prose, spaces gpt-4 2,429,915 693,878 +2237 0 0.184 0.182
prose, newlines only chat-latest 2,429,915 786,226 +2013 0 0.162 0.157
prose, tabs only chat-latest 2,429,915 845,963 +1861 0 0.182 0.174
prose, double spaces and CRLF chat-latest 2,482,688 753,777 +2053 0 0.155 0.150
Python code (litellm/utils.py x3) chat-latest 1,658,274 357,654 +1545 +5 0.074 0.070
Python code gpt-4 1,658,274 356,106 +1562 +5 0.109 0.104
minified JSON, no whitespace chat-latest 3,464,149 1,114,771 +2420 +2420 0.208 0.185
base64, no whitespace chat-latest 1,200,000 819,082 +220 +220 0.111 0.113
hex, no whitespace chat-latest 1,000,000 569,305 +300 +300 0.084 0.076
CJK, no whitespace chat-latest 400,000 767,760 0 0 0.065 0.062
CJK, no whitespace gpt-4 400,000 942,579 0 0 0.052 0.051
CJK with spaces chat-latest 476,462 868,685 +20 0 0.077 0.074
emoji with spaces chat-latest 560,000 720,001 +78 0 0.068 0.065
"x " * 500000 chat-latest 1,000,000 500,001 +976 0 0.046 0.045
(" " + "x" * 1023) * 1000 chat-latest 1,024,000 130,000 0 0 0.092 0.081
dot leaders, ("Chapter" + "." * 3000 + " 12\n") * 400 chat-latest 1,204,400 20,800 +793 +1200 0.133 0.118
63 messages (system, text parts, tool call, tool result) and 40 tools chat-latest 543,985 +1600 +1 0.113 0.111
same payload gpt-4 536,161 +1657 0 0.145 0.144
same payload, HuggingFace tokenizer claude-sonnet-4-5 647,612 0 0 0.704 0.699

Long 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:

Run of Count at 2M, old and new Old s New s
. 31,250 0.051, 0.098, 0.215, 0.426 0.051, 0.100, 0.202, 0.410
space 15,625 0.062, 0.114, 0.232, 0.748 0.057, 0.119, 0.235, 0.467
newline 125,000 0.096, 0.090, 0.182, 0.358 0.048, 0.096, 0.192, 0.390
0 667,969 0.024, 0.048, 0.097, 0.193 0.025, 0.055, 0.099, 0.197
a 250,000 0.041, 0.079, 0.158, 0.315 0.040, 0.079, 0.159, 0.318

Can 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.py mixed 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.

Encoding New below whole Old below whole Lowest against whole New equal to whole Old extra tokens in total New extra tokens in total
o200k_base 1 of 3000 1 of 3000 -1 2997 50,000 1
cl100k_base 0 of 3000 0 of 3000 0 2995 51,040 5

What else reads this counter

Everything that calls litellm.token_counter on 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.

  • Router pre-call context window check, the case fixed here
  • TPM rate limit estimates made before the provider answers (parallel request limiter v3, the input/output token rate limit check, model capacity) and budget reservations. They reserve up to about 0.5% fewer tokens on long prompts. Usage reported by the provider still replaces the estimate afterwards
  • Usage and cost when the provider returns no usage, such as rebuilt streams and providers that never report tokens. Logged prompt tokens and spend for those calls drop by the same margin on long prompts
  • /utils/token_counter and litellm.token_counter() called directly
  • trim_messages, prompt compression and the Anthropic context management editors, which keep slightly more text for the same budget
  • Prompt caching minimum-size checks and the complexity router

Not 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_text fails 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 -q gives 833 passed at a40026b.

Type

🐛 Bug Fix

Caveats (if any)

Medium

  • Text with no whitespace still overcounts as before (minified JSON, base64)
  • Estimated tokens and fallback spend drop up to 0.5% on long prompts

Low

  • Long punctuation runs between words overcount more (dot leaders +1200 against +793)
    • Over 256 dot-leader shapes the new cut adds 36,900 extra tokens against 34,494 (about 7% more)
    • Worse on 131, better on 118, equal on 7
    • Open Greptile finding, left for the owner to decide
  • Count can be one token under tiktoken's, as before
  • Proof ran with one worker and no Redis

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

kerry-berri and others added 2 commits November 25, 2026 18:12
… 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>
@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

@veria-ai

veria-ai Bot commented Nov 25, 2026 •

Copy link
Copy Markdown
Contributor

PR overview

No security issues were found in this pull request.

Reviews

Co-Authored-By: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com>
@greptile-apps

greptile-apps Bot commented Nov 25, 2026 •

Copy link
Copy Markdown
Contributor

RetriggerView in GreptileConfidence Score: 4/5

[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

  1. P2 Dot leaders overcount more ▶
  2. P2 Loop violates local-variable rules ▶

Summary

The PR cuts tiktoken text at whitespace while keeping each chunk within the configured size.

  • Long prompts are counted closer to their whole-text tiktoken total.

The supplied description from kerry-berri identifies lower estimates as intentional and acknowledges existing whitespace-free drift and occasional undercounts. Those are not separate findings. Its dot-leader caveat remains reported because the change makes that count worse.

Reviews (2) · Last reviewed commit: "fix(token_counter): give the chunk curso..." · Reviewed by Greptile

Comment on lines +861 to +866
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

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.

P2 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!

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.

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)

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.

P2 Dot leaders overcount more

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)

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.

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.

This branch has not been deployed

No deployments
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.

1 participant