You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
{{ message }}
Repository navigation
Python: [Bug]: Token count used in Compaction much differ from usage from LLM #7022
TokenBudgetComposedStrategy estimates the token count of the LLM input, but its estimate differs significantly from the actual token usage reported by the LLM API.
However, this is not an accurate way to estimate the number of input tokens.
The reason is that tokenizer.count_tokens() is tokenizing the serialized JSON string rather than the actual message text that the API sends to the model. The serialized JSON contains escaped Unicode sequences such as "\u3053\u3093\u306b\u3061\u306f", whereas the model tokenizes the original text ("こんにちは").
As a result, when the input contains Japanese or other non-ASCII characters, ensure_ascii=True can significantly overestimate the token count. For example, Japanese text may be estimated as requiring roughly three times as many tokens as the actual API usage.
So #7124 solves this for non-ascii characters, but keep in mind that 1) you can define your own tokenizers, by default is uses the heuristic character_count / 4, which is imprecise, but fast and cheap, you can also add a proper tokenizer, like TikToken to do the work, in which case you get a better count, but we only count messages, not things like tools, so the count internally is always going to be different then the usage you get back from API's.
Activity
eavanvalkenburg commentedon Jul 17, 2026
So #7124 solves this for non-ascii characters, but keep in mind that 1) you can define your own tokenizers, by default is uses the heuristic
character_count / 4, which is imprecise, but fast and cheap, you can also add a proper tokenizer, like TikToken to do the work, in which case you get a better count, but we only count messages, not things like tools, so the count internally is always going to be different then the usage you get back from API's.