litellm/tests/integration/_support/deepseek_tokens.py
mateo-berri 82a87bbbb9 fix(token_counter): count DeepSeek V4 text with DeepSeek's own tokenizer (#47353)
Backport of #47353 to stable/1.104.x.
Cherry-picked from 2d181e6633 (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.
2026-10-20 16:30:19 -07:00

35 lines
1.3 KiB
Python

from collections.abc import Callable
from functools import cache
from importlib import resources
from typing import Final
from litellm.litellm_core_utils.default_encoding import encoding as cl100k_base
from tokenizers import Tokenizer
CHINESE_TEXT: Final = "深度求索的分词器会把这段中文切成更少的词元。" * 20
SHORT_TEXT: Final = "Find record 14."
@cache
def _deepseek_tokenizer() -> Tokenizer:
bundled: Final = resources.files("litellm.litellm_core_utils.tokenizers").joinpath("deepseek_tokenizer.json")
return Tokenizer.from_str(bundled.read_text(encoding="utf-8"))
def deepseek_tokens(text: str) -> int:
return len(_deepseek_tokenizer().encode(text).ids)
def cl100k_tokens(text: str) -> int:
return len(cl100k_base.encode(text))
def chinese_minus_short(tokens: Callable[[str], int]) -> int:
return tokens(CHINESE_TEXT) - tokens(SHORT_TEXT)
def assert_counted_with_deepseek(counted: int, expected: Callable[[Callable[[str], int]], int]) -> None:
cl100k_count: Final = expected(cl100k_tokens)
assert counted != cl100k_count, f"counted {counted}, the cl100k_base count, not DeepSeek's tokenizer"
deepseek_count: Final = expected(deepseek_tokens)
assert counted == deepseek_count, f"counted {counted}, DeepSeek's tokenizer counts {deepseek_count}"