kimi-code
kimi-code copied to clipboard
estimateTokens counts every non-ASCII char as one token — ~2× overestimate for Cyrillic
Environment
- kimi-code (Node) v2.1.1, macOS arm64
- Workload: sessions with Cyrillic-heavy content (Russian)
- Serving: vLLM-style endpoint
Component
agent-core-v2/src/llm-adapter/contract/tokens.ts (estimateTokens; bundle ~191702 and ~323353): ceil(ascii/4) + nonAsciiCount.
Mechanism
The heuristic is calibrated for CJK (one ideograph ≈ one token), but Cyrillic actually tokenizes at ~2–2.5 characters per token. preShrinkHistoryToWindowBudget uses this estimate, while the compaction trigger counts measured tokens — the mixed units cause extra / overly deep head trimming of the history for any non-CJK, non-English language.
Facts
- 480K real tokens vs an 806K estimate (×1.68).
- A Russian-language session was trimmed on the very first trigger firing even though the history actually fit the call budget.
Expected
Calibrate non-ASCII (e.g. /2.5 for Cyrillic ranges) or reuse the measured token counter; at minimum, use consistent units between the trigger and the pre-shrink.
Reproduction
- A session with Cyrillic-heavy content on a large-window model.
- Compare
estimateTokensoutput with the measured token count of the same messages (we saw 480K measured vs 806K estimated, ×1.68). - Observe the history being head-trimmed by
preShrinkHistoryToWindowBudgetalthough the measured size fits the call budget.
Related issues:
- https://github.com/MoonshotAI/kimi-code/issues/4202
- https://github.com/MoonshotAI/kimi-code/issues/4204
- https://github.com/MoonshotAI/kimi-code/issues/4205