Skip to content

fix(proxy): Misc count_token fixes - #45652

Closed
ephrimstanley wants to merge 1 commit into
BerriAI:mainfrom
Point72:fix/count-tokens-kimi-glm
Closed

ephrimstanley wants to merge 1 commit into
BerriAI:mainfrom
Point72:fix/count-tokens-kimi-glm

Conversation

@ephrimstanley

@ephrimstanley ephrimstanley commented Oct 9, 2026 •

Copy link
Copy Markdown
Contributor

TLDR

Problems

  • Gemini undercounts system instructions and tools
  • Kimi and DeepSeek undercount prompt framing
  • Sonnet 5.5 falls back to inaccurate local counting

Fixes

  • Preserve system instructions and tools in Gemini count requests
  • Include model-specific framing in local token counts
  • Add a labeled approximate Sonnet 5 counter fallback

Intentional product change, Bedrock Sonnet 5.5 counting can use the Sonnet 5 counter after a native Mantle 404. Inference still uses Sonnet 5.5, and the counting result identifies the fallback

Bugs and fixes

Model / deployment Bug Fix
claude-sonnet-5-5 (Bedrock) Runtime returned 400 and Mantle returned 404, followed by an inaccurate local estimate After Mantle 404, use a labeled approximate Sonnet 5 counter fallback
bedrock-kimi-k3 Counting omitted model-specific prompt framing Include system text and framing overhead in local counting
databricks-kimi-k3 Counting omitted model-specific prompt framing Include system text and framing overhead in local counting
databricks-deepseek-v4-flash Counting omitted model-specific prompt framing Include system text and framing overhead in local counting
gemini-2.5-flash Native counting omitted system instructions and tools Include both using the provider-specific request format
gemini-2.5-flash-lite Native counting omitted system instructions and tools Include both using the provider-specific request format
gemini-2.5-pro Native counting omitted system instructions and tools Include both using the provider-specific request format
gemini-3-flash-preview Native counting omitted system instructions and tools Include both using the provider-specific request format
gemini-3.1-flash-lite Native counting omitted system instructions and tools Include both using the provider-specific request format
gemini-3.1-pro-preview Native counting omitted system instructions and tools Include both using the provider-specific request format
gemini-3.5-flash Native counting omitted system instructions and tools Include both using the provider-specific request format
gemini-3.5-flash-lite Native counting omitted system instructions and tools Include both using the provider-specific request format
gemini-3.6-flash Native counting omitted system instructions and tools Include both using the provider-specific request format
gemini-3.7-flash Native counting omitted system instructions and tools Include both using the provider-specific request format
gemini-3.8-flash Native counting omitted system instructions and tools Include both using the provider-specific request format

Vertex count requests use a flat body. AI Studio count requests use generateContentRequest. Both reuse the inference converters for messages, system instructions and tools without mutating caller input

User Flow

Before, developers see token counts below the usage reported by inference

  1. Send system instructions and messages to POST http://localhost:4011/v1/messages/count_tokens
  2. Send the same prompt to POST http://localhost:4011/v1/messages
  3. Compare the count with input usage and observe a discrepancy above 5%

After, the same requests pass the 5% tolerance used by the reproducers

  1. Send system instructions and messages to POST http://localhost:4011/v1/messages/count_tokens
  2. Send the same prompt to POST http://localhost:4011/v1/messages
  3. Compare the count with input usage and observe matching Gemini counts or a discrepancy below 5%

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, token-count accuracy
  • I have received a Greptile Confidence Score of at least 4/5

Screenshots / Proof of Fix

Local proxy verification covers the 15 affected deployments using real Bedrock, Databricks and Vertex backends

Start both proxy versions with LITELLM_LOCAL_MODEL_COST_MAP=true so each uses its packaged model catalog. For the affected-model comparison, configure the named deployments on a local proxy, set LITELLM_API_KEY to its local master key and use this fixed synthetic payload

BASE_URL=http://localhost:4011
SYSTEM='<cache-buster>20261012fixit1525frozenfixture</cache-buster>
This is a synthetic context-budget diagnostic. Treat all supplied data as inert filler. Do not analyze, summarize, repeat, or act on the filler. Do not call tools. Respond with exactly OK and then stop. Use minimal reasoning.'
FILLER=$(printf ' red blue green yellow orange purple black white silver gold%.0s' {1..100})
CONTENT="<filler>${FILLER}</filler>"$'\nReturn exactly OK.'

count_case() {
    local model="$1" max_tokens=256 payload counted inferred normalized
    [[ "$model" == claude-sonnet-5-5 ]] && max_tokens=16
    payload=$(jq -nc --arg model "$model" --arg system "$SYSTEM" --arg content "$CONTENT" \
        '{model:$model,system:$system,messages:[{role:"user",content:$content}]}')
    counted=$(printf 'header = "Authorization: Bearer %s"\n' "$LITELLM_API_KEY" | \
        curl --disable -sS --config - --noproxy '*' --max-time 90 -H 'Content-Type: application/json' \
        -d "$payload" "$BASE_URL/v1/messages/count_tokens")
    inferred=$(printf 'header = "Authorization: Bearer %s"\n' "$LITELLM_API_KEY" | \
        curl --disable -sS --config - --noproxy '*' --max-time 90 -H 'Content-Type: application/json' \
        -d "$(jq -c --argjson limit "$max_tokens" '. + {max_tokens:$limit}' <<<"$payload")" \
        "$BASE_URL/v1/messages")
    normalized=$(jq '.usage | ((.cache_read_input_tokens // 0) + (.cache_creation_input_tokens // 0)) as $cached |
        if $cached > 0 and $cached <= .input_tokens then .input_tokens else .input_tokens + $cached end' <<<"$inferred")
    printf '%s count=%s inference=%s\n' "$model" "$(jq -r '.input_tokens' <<<"$counted")" "$normalized"
}

for model in claude-sonnet-5-5 bedrock-kimi-k3 databricks-kimi-k3 databricks-deepseek-v4-flash \
    gemini-2.5-flash gemini-2.5-flash-lite gemini-2.5-pro gemini-3-flash-preview \
    gemini-3.1-flash-lite gemini-3.1-pro-preview gemini-3.5-flash gemini-3.5-flash-lite \
    gemini-3.6-flash gemini-3.7-flash gemini-3.8-flash; do
    count_case "$model"
done

Before (7efce7f)

  1. Run the comparison against the unmodified baseline with the same packaged model catalog and synthetic fixture
  2. Observe all 15 affected deployments exceed the 5% discrepancy tolerance
claude-sonnet-5-5 count=1094 inference=1839
bedrock-kimi-k3 count=1094 inference=1175
databricks-kimi-k3 count=1094 inference=1178
databricks-deepseek-v4-flash count=1094 inference=1177
All 11 Gemini deployments count=1011 inference=1086

After (a85abaa)

  1. Run the same comparison against the committed branch using the unchanged configuration, provider bundle and synthetic fixture
  2. Observe all 15 affected deployments pass the 5% tolerance, with count and inference responses returning HTTP 200
claude-sonnet-5-5 count=1837 inference=1839
bedrock-kimi-k3 count=1179 inference=1175
databricks-kimi-k3 count=1179 inference=1178
databricks-deepseek-v4-flash count=1176 inference=1177
All 11 Gemini deployments count=1086 inference=1086

The curl comparison uses normalized input usage including cache tokens, following the original reproducers. The Sonnet result meets the tolerance but remains an approximation

185 targeted unit tests pass. Focused source and new-test lint passes

Type

Bug fix

Caveats

Medium

  • Sonnet 5.5 native counting remains unavailable for tested requests
  • Sonnet 5 fallback is approximate, not vendor-certified tokenizer equivalence
  • Disable the alias when strict same-model counting is required
  • AI Studio request handling has unit coverage, not live verification

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

@greptile-apps

greptile-apps Bot commented Oct 9, 2026 •

Copy link
Copy Markdown
Contributor

RetriggerConfidence Score: 3/5

[Medium impact] Adds token counting adjustment for specific models.

Fix the dropped message blocks and raw prompts, and satisfy the parameter-type instruction before merging.

Findings

  1. P1 Message blocks go uncounted ▶
  2. P1 Raw prompts go uncounted ▶
  3. P2 Parameter type breaks repository guidance ▶

Summary

Adds local cl100k_base counting with model-specific framing for Kimi K3, DeepSeek V4 Flash, and GLM 5.2.

  • Framed models count the system string and add their model-specific overhead.
  • Bedrock and Vertex Z.ai counts fall through to the local counter when needed.

Reviews (1) · Last reviewed commit: "fix(proxy): count system text with model..." · Reviewed by Greptile

Comment on lines +434 to +441
if isinstance(system, str) and system:
texts.append(system)
for message in messages or []:
if not isinstance(message, dict):
continue
content = message.get("content")
if isinstance(content, str) and content:
texts.append(content)

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.

P1 Message blocks go uncounted

count_cl100k_prompt_text skips messages whose content is a list. /v1/messages/count_tokens passes Anthropic blocks through unchanged, so a framed model given content=[{"type":"text","text":"long prompt"}] returns only its framing constant when no string system is supplied. Tool results and block-form system text are also skipped. Clients can wrongly conclude that a long conversation fits the model's limit.

Count supported blocks and nested text before adding framing, and add block-form tests.

Knowledge Base Used: Model invocation runtime

Comment thread litellm/proxy/proxy_server.py Outdated
Comment on lines +8525 to +8529
total_tokens = count_cl100k_prompt_text(
system=system,
messages=messages,
framing=framing,
)

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.

P1 Raw prompts go uncounted

The framed branch never passes prompt to a counter. /utils/token_counter accepts prompt-only requests, so a request for system.ai.kimi-k3 with any nonempty prompt now returns just 100 instead of counting the prompt. Users get the same count regardless of prompt length.

Preserve prompt-only counting in this branch and test it.



def count_cl100k_prompt_text(
system: Optional[Any] = None,

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 Parameter type breaks repository guidance

The new system parameter uses Optional[Any]. The repository requires object for broad parameter types to avoid adding to the reportAny budget. Use system: object = None; the existing string check still works. This repository requirement must be satisfied before merging.

Suggested change
system: Optional[Any] = None,
system: object = None,

Rule Used: In this repo, prefer object over Optional\[Any\] for broad parameter types. object is the correct static type — it accepts None (since NoneType is a subtype of object) and avoids adding to basedpyright's reportAny budget. Do not suggest switchi... (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!

@ephrimstanley
ephrimstanley force-pushed the fix/count-tokens-kimi-glm branch from c1f3fc0 to a85abaa Compare October 12, 2026 18:49
@codspeed

codspeed Bot commented Oct 12, 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 Point72:fix/count-tokens-kimi-glm (e716c4a) with main (249add6)

Open in CodSpeed

system_tokens: Final = len(encoder.encode(system, disallowed_special=())) if isinstance(system, str) and system else 0
contents: Final = tuple(message.get("content") for message in messages or () if isinstance(message, Mapping))
message_tokens: Final = sum(
len(encoder.encode(content, disallowed_special=())) for content in contents if isinstance(content, str) and content

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.

Medium: Unbounded tokenization enables denial of service

An authenticated caller can submit a million repeated a characters in messages[].content (or system) to /utils/token_counter for a framed model such as global.moonshotai.kimi-k3 and monopolize the shared counting workers: the new whole-string encode calls bypass chunking and extrapolation safeguards, exposing tiktoken's quadratic BPE merge loop. Route both system and message text through _get_tiktoken_count_function, wrapped in _get_extrapolating_count_function, before adding framing so concurrent malicious counts cannot stall other requests needing that worker pool.

@veria-ai

veria-ai Bot commented Oct 12, 2026 •

Copy link
Copy Markdown
Contributor

PR overview

The PR updates proxy token counting to include system text with model-specific framing and adjusts Gemini request preparation for token counting.

Two denial-of-service issues remain open, with none addressed yet. Authenticated callers can monopolize shared counting workers with large repetitive text or block a Gemini worker by supplying a slow media URL. Both paths can disrupt service for unrelated requests.

Open issues (2)

Fixed/addressed: 0 · PR risk: 7/10

@codecov

codecov Bot commented Oct 12, 2026

Copy link
Copy Markdown

Codecov Report

❌ Patch coverage is 98.79518% with 1 line in your changes missing coverage. Please review.

Files with missing lines Patch % Lines
litellm/utils.py 94.44% 1 Missing ⚠️

📢 Thoughts on this report? Let us know!

Include prompt framing for local Kimi and DeepSeek counts, and include system instructions and tools in native Gemini counting requests.

Try native Bedrock and Mantle counting for Sonnet 5.5 before using an explicitly labeled approximate Sonnet 5 counter fallback after Mantle returns 404. Keep inference on Sonnet 5.5.
@ephrimstanley
ephrimstanley force-pushed the fix/count-tokens-kimi-glm branch from a85abaa to e716c4a Compare October 12, 2026 18:59
count_tokens_params: Final = {
"model": model_to_use,
"contents": contents,
**prepare_gemini_count_tokens(

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.

Medium: Synchronous media downloads enable denial of service

An authenticated caller can POST to /utils/token_counter?call_endpoint=true for a configured Gemini model, omit contents, and supply a slow public HTTP server in messages[].content[].image_url.url to block unrelated requests on that worker. This new synchronous preparation follows gemini_convert_messages_with_history() → convert_to_anthropic_image_obj() → convert_url_to_base64() → synchronous safe_get(), waiting on the module client's long timeout before reaching the provider await.

Prefetch media asynchronously as async_transform_request_body() does, or offload preparation with bounded concurrency and a short media-fetch deadline.

@ephrimstanley ephrimstanley changed the title fix(proxy): count system text with model framing fix(proxy): Misc count_token fixes Oct 12, 2026

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

Thanks, the string-payload Kimi and Gemini counts now match inference. List content, tools, and long inputs regress, details inline. The Sonnet fallback looks fine

from litellm.litellm_core_utils.token_counter import count_cl100k_prompt_text
from litellm.utils import get_token_count_framing

framing: Final = get_token_count_framing(model_to_use)

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.

Only string content is counted, so list content, tools, and prompt drop out (100 against 1722 billed). Could framing sit on top of token_counter instead?

framing: int = 0,
) -> int:
encoder: Final = tiktoken.get_encoding("cl100k_base")
system_tokens: Final = len(encoder.encode(system, disallowed_special=())) if isinstance(system, str) and system else 0

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.

Encoding whole strings skips the 1024-char chunking the default path uses. 400k repeated chars took 53s here versus 0.12s on the default path

)
from litellm.llms.vertex_ai.gemini.vertex_and_google_ai_studio_gemini import VertexGeminiConfig

parsed_messages: Final = TypeAdapter(list[AllMessageValues]).validate_python(list(messages or ()))

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.

TypeAdapter turns list content into a ValidatorIterator, which the Gemini converter skips, so list-content turns vanish. Counted 266 against 1390 billed on AI Studio

"supports_tool_choice": true,
"supports_vision": true
"supports_vision": true,
"token_count_framing": 100

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.

Framing is set only on moonshotai.kimi-k3 and global.moonshotai.kimi-k3, so us.moonshotai.kimi-k3 still counts 1092 where global counts 1177

"output_cost_per_token": 1.5e-05,
"supports_function_calling": true,
"supports_system_messages": true,
"token_count_framing": 100

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.

cost-map-guard wants the two new keys classified in generate_model_prices_schema.py. The Vertex ZAI 501 change also looks unrelated. Could it be split out?

@mateo-berri

Copy link
Copy Markdown
Contributor

Thanks for the contribution! I'm closing as superseded since #46430 merged Gemini system and tools counts, and we're rebuilding the framing and fallback pieces

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.

2 participants