Repository navigation
fix(proxy): Misc count_token fixes - #45652
ephrimstanley wants to merge 1 commit into
Conversation
|
| 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) |
There was a problem hiding this comment.
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
| total_tokens = count_cl100k_prompt_text( | ||
| system=system, | ||
| messages=messages, | ||
| framing=framing, | ||
| ) |
There was a problem hiding this comment.
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, |
There was a problem hiding this comment.
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.
| 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!
c1f3fc0 to
a85abaa
Compare
Merging this PR will not alter performance
|
| 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 |
There was a problem hiding this comment.
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.
PR overviewThe 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 Report❌ Patch coverage is
📢 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.
a85abaa to
e716c4a
Compare
| count_tokens_params: Final = { | ||
| "model": model_to_use, | ||
| "contents": contents, | ||
| **prepare_gemini_count_tokens( |
There was a problem hiding this comment.
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.
mateo-berri
left a comment
There was a problem hiding this comment.
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) |
There was a problem hiding this comment.
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 |
There was a problem hiding this comment.
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 ())) |
There was a problem hiding this comment.
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 |
There was a problem hiding this comment.
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 |
There was a problem hiding this comment.
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?
|
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 |
TLDR
Problems
Fixes
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
claude-sonnet-5-5(Bedrock)bedrock-kimi-k3databricks-kimi-k3databricks-deepseek-v4-flashgemini-2.5-flashgemini-2.5-flash-litegemini-2.5-progemini-3-flash-previewgemini-3.1-flash-litegemini-3.1-pro-previewgemini-3.5-flashgemini-3.5-flash-litegemini-3.6-flashgemini-3.7-flashgemini-3.8-flashVertex 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 inputUser Flow
Before, developers see token counts below the usage reported by inference
POST http://localhost:4011/v1/messages/count_tokensPOST http://localhost:4011/v1/messagesAfter, the same requests pass the 5% tolerance used by the reproducers
POST http://localhost:4011/v1/messages/count_tokensPOST http://localhost:4011/v1/messagesPre-Submission checklist
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=trueso each uses its packaged model catalog. For the affected-model comparison, configure the named deployments on a local proxy, setLITELLM_API_KEYto its local master key and use this fixed synthetic payloadBefore (7efce7f)
After (a85abaa)
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
Final Attestation