Skip to main content

Module token_counter

Module token_counter 

Source
Expand description

TokenCounter — how the engine decides how big a conversation is.

Every budget decision rests on one number: how many tokens the context currently holds. Compaction triggers on it, strategies choose what to drop by it, and the warning shown to the user quotes it. That number came from one hardcoded algorithm — a local character-class estimate standing in for Anthropic’s tokenizer, which nobody publishes — with no way for a host to supply a better one.

A better one is not hypothetical. A host talking to a provider with a published tokenizer can count exactly. A host willing to spend a call on /v1/messages/count_tokens can be exact for Anthropic too. Both are strictly more accurate than an estimate documented to be off by up to ~12%, and neither could be plugged in.

§An estimate, not a measurement

Implementations are not required to be exact, and callers must not treat the result as if they were: it decides when to compact, not what is billed. An implementation that is cheap and slightly wrong is a better default than one that is exact and costs a network round-trip per turn, which is why the shipped default is the local estimate.

Structs§

FixedTokenCounter
Charges a fixed number of tokens per block and per character.
HeuristicCounter
The engine’s default TokenCounter: everything above, behind the contract, so a host with a better answer can supply one.

Traits§

TokenCounter
Counts the tokens a piece of conversation will cost.

Functions§

count_text
Estimated token count of s.
default_counter
The counter used wherever nothing more specific was supplied.
estimate_message_tokens
Estimate input tokens for a slice of ModelMessages — the protocol-agnostic message type that session and compaction operate on.
estimate_model_block_tokens
Estimate input tokens for a single ModelContentBlock.