Skip to main content

base/interface/
token_counter.rs

1//! `TokenCounter` — how the engine decides how big a conversation is.
2//!
3//! Every budget decision rests on one number: how many tokens the context
4//! currently holds. Compaction triggers on it, strategies choose what to drop
5//! by it, and the warning shown to the user quotes it. That number came from
6//! one hardcoded algorithm — a local character-class estimate standing in for
7//! Anthropic's tokenizer, which nobody publishes — with no way for a host to
8//! supply a better one.
9//!
10//! A better one is not hypothetical. A host talking to a provider with a
11//! published tokenizer can count exactly. A host willing to spend a call on
12//! `/v1/messages/count_tokens` can be exact for Anthropic too. Both are
13//! strictly more accurate than an estimate documented to be off by up to ~12%, and
14//! neither could be plugged in.
15//!
16//! # An estimate, not a measurement
17//!
18//! Implementations are not required to be exact, and callers must not treat
19//! the result as if they were: it decides when to compact, not what is billed.
20//! An implementation that is *cheap* and slightly wrong is a better default
21//! than one that is exact and costs a network round-trip per turn, which is
22//! why the shipped default is the local estimate.
23
24use crate::interface::model::{
25    document_token_estimate, ModelContentBlock, ModelMessage, IMAGE_TOKEN_ESTIMATE,
26};
27use std::sync::OnceLock;
28
29/// Counts the tokens a piece of conversation will cost.
30pub trait TokenCounter: Send + Sync {
31    /// Tokens in a plain string.
32    fn count_text(&self, text: &str) -> usize;
33
34    /// Tokens in one content block, including whatever that block type costs
35    /// beyond its text.
36    fn count_block(&self, block: &ModelContentBlock) -> usize;
37
38    /// Tokens in a conversation.
39    ///
40    /// Content only: per-message API framing (role, JSON punctuation) is a
41    /// handful of tokens per message and is deliberately not modelled, so an
42    /// implementation that ignores it agrees with the default.
43    fn count_messages(&self, messages: &[ModelMessage]) -> usize {
44        messages
45            .iter()
46            .flat_map(|m| &m.content)
47            .map(|b| self.count_block(b))
48            .sum()
49    }
50}
51
52/// Charges a fixed number of tokens per block and per character.
53///
54/// The second implementation, and the one tests want: a budget test that has
55/// to reach a compaction threshold should say so in one line rather than by
56/// generating enough prose to trip a real tokenizer, and a test asserting
57/// *which* strategy ran should not change its answer when the tokenizer's
58/// table does.
59pub struct FixedTokenCounter {
60    pub per_char: usize,
61    pub per_block: usize,
62}
63
64impl FixedTokenCounter {
65    pub fn new(per_char: usize, per_block: usize) -> Self {
66        Self {
67            per_char,
68            per_block,
69        }
70    }
71}
72
73impl TokenCounter for FixedTokenCounter {
74    fn count_text(&self, text: &str) -> usize {
75        text.len() * self.per_char
76    }
77
78    fn count_block(&self, block: &ModelContentBlock) -> usize {
79        let text = match block {
80            ModelContentBlock::Text { text } => text.len(),
81            ModelContentBlock::Thinking { text, .. } => text.len(),
82            ModelContentBlock::RedactedThinking { data, .. } => data.len(),
83            ModelContentBlock::ToolResult {
84                tool_use_id,
85                content,
86                ..
87            } => tool_use_id.len() + content.len(),
88            ModelContentBlock::ToolUse { id, name, input } => {
89                id.len() + name.len() + input.to_string().len()
90            }
91            ModelContentBlock::Image { .. } | ModelContentBlock::Document { .. } => 0,
92        };
93        self.per_block + text * self.per_char
94    }
95}
96
97const SHORT_WORD: usize = 12;
98const CHARS_PER_WORD_TOKEN: usize = 5;
99const DIGITS_PER_TOKEN: usize = 3;
100const PUNCT_PER_TOKEN: usize = 3;
101
102fn is_cjk(c: char) -> bool {
103    matches!(c as u32,
104        0x3000..=0x303F
105        | 0x3040..=0x30FF
106        | 0x3400..=0x4DBF
107        | 0x4E00..=0x9FFF
108        | 0xAC00..=0xD7AF
109        | 0xF900..=0xFAFF
110        | 0xFF00..=0xFFEF
111        | 0x20000..=0x2FFFF)
112}
113
114fn is_word_char(c: char) -> bool {
115    c.is_ascii_alphabetic() || (!c.is_ascii() && c.is_alphabetic() && !is_cjk(c))
116}
117
118fn run_len(
119    chars: &mut std::iter::Peekable<std::str::Chars<'_>>,
120    pred: impl Fn(char) -> bool,
121) -> usize {
122    let mut len = 1;
123    while chars.next_if(|&d| pred(d)).is_some() {
124        len += 1;
125    }
126    len
127}
128
129/// Estimated token count of `s`.
130pub fn count_text(s: &str) -> usize {
131    let mut n = 0usize;
132    let mut chars = s.chars().peekable();
133    while let Some(c) = chars.next() {
134        if is_word_char(c) {
135            let mut len = 1;
136            let mut ascii = c.is_ascii();
137            while let Some(d) = chars.next_if(|&d| is_word_char(d)) {
138                ascii &= d.is_ascii();
139                len += 1;
140            }
141            n += match (ascii, len) {
142                (true, l) if l <= SHORT_WORD => 1,
143                (true, l) => l.div_ceil(CHARS_PER_WORD_TOKEN),
144                (false, l) => l.div_ceil(2),
145            };
146        } else if c.is_ascii_digit() {
147            n += run_len(&mut chars, |d| d.is_ascii_digit()).div_ceil(DIGITS_PER_TOKEN);
148        } else if c == ' ' || c == '\t' {
149            // cl100k folds spaces into the next token, indentation included.
150            run_len(&mut chars, |d| d == ' ' || d == '\t');
151        } else if c == '\n' || c == '\r' {
152            run_len(&mut chars, |d| d == '\n' || d == '\r');
153            n += 1;
154        } else if is_cjk(c) {
155            n += 1;
156        } else if c.is_ascii() {
157            n += run_len(&mut chars, |d| d.is_ascii_punctuation()).div_ceil(PUNCT_PER_TOKEN);
158        } else {
159            n += 2;
160        }
161    }
162    n
163}
164
165/// Estimate input tokens for a slice of [`ModelMessage`]s — the protocol-agnostic
166/// message type that `session` and `compaction` operate on.
167///
168/// This is the default counter's implementation. A session counts with the
169/// `TokenCounter` it was built with, and compaction is handed that same
170/// counter, so the number that trips compaction, the number that decides which
171/// rounds to drop and the number reported in telemetry are the same number.
172///
173/// Counts message *content* only. Per-message API framing (role, JSON
174/// punctuation) is a handful of tokens per message and is deliberately not
175/// modelled — same omission as [`estimate_input_tokens`].
176pub fn estimate_message_tokens(messages: &[ModelMessage]) -> usize {
177    messages
178        .iter()
179        .flat_map(|m| &m.content)
180        .map(estimate_model_block_tokens)
181        .sum()
182}
183
184/// Estimate input tokens for a single [`ModelContentBlock`].
185pub fn estimate_model_block_tokens(block: &ModelContentBlock) -> usize {
186    match block {
187        ModelContentBlock::Text { text } => count_text(text),
188        // Flat estimate. Counting the base64 payload would read a 1 MB
189        // screenshot as hundreds of thousands of tokens and trip compaction on
190        // the first image the user pastes — see `IMAGE_TOKEN_ESTIMATE`.
191        ModelContentBlock::Image { .. } => IMAGE_TOKEN_ESTIMATE,
192        ModelContentBlock::Document { data, .. } => document_token_estimate(data.len()),
193        // Thinking is billed as text. The signature is an opaque blob that the
194        // API requires us to echo back; it is not counted.
195        ModelContentBlock::Thinking { text, .. } => count_text(text),
196        ModelContentBlock::RedactedThinking { data, .. } => count_text(data),
197        ModelContentBlock::ToolResult {
198            tool_use_id,
199            content,
200            ..
201        } => count_text(tool_use_id) + count_text(content),
202        ModelContentBlock::ToolUse { id, name, input } => {
203            count_text(id) + count_text(name) + count_text(&input.to_string())
204        }
205    }
206}
207
208/// The engine's default [`TokenCounter`]: everything above, behind the
209/// contract, so a host with a better answer can supply one.
210///
211/// Stateless, so constructing one costs nothing and any number of them agree.
212#[derive(Debug, Default, Clone, Copy)]
213pub struct HeuristicCounter;
214
215impl TokenCounter for HeuristicCounter {
216    fn count_text(&self, text: &str) -> usize {
217        count_text(text)
218    }
219
220    fn count_block(&self, block: &ModelContentBlock) -> usize {
221        estimate_model_block_tokens(block)
222    }
223
224    fn count_messages(&self, messages: &[ModelMessage]) -> usize {
225        estimate_message_tokens(messages)
226    }
227}
228
229/// The counter used wherever nothing more specific was supplied.
230pub fn default_counter() -> std::sync::Arc<dyn TokenCounter> {
231    static C: OnceLock<std::sync::Arc<dyn TokenCounter>> = OnceLock::new();
232    C.get_or_init(|| std::sync::Arc::new(HeuristicCounter))
233        .clone()
234}
235
236#[cfg(test)]
237mod tests {
238    use super::*;
239
240    #[test]
241    fn the_message_count_is_the_sum_of_its_blocks() {
242        let counter = FixedTokenCounter::new(1, 10);
243        let messages = vec![ModelMessage {
244            role: crate::interface::model::MessageRole::User,
245            content: vec![
246                ModelContentBlock::Text {
247                    text: "abcd".into(),
248                },
249                ModelContentBlock::Text { text: "ef".into() },
250            ],
251        }];
252        assert_eq!(counter.count_messages(&messages), (10 + 4) + (10 + 2));
253    }
254
255    fn model_user(blocks: Vec<ModelContentBlock>) -> ModelMessage {
256        ModelMessage {
257            role: crate::interface::model::MessageRole::User,
258            content: blocks,
259        }
260    }
261
262    #[test]
263    fn message_tokens_are_real_tokens_not_char_quarters() {
264        // "len() / 4" would call this 7; a long word is several tokens, not one.
265        let msgs = vec![model_user(vec![ModelContentBlock::Text {
266            text: "antidisestablishmentarianism".into(),
267        }])];
268        let n = estimate_message_tokens(&msgs);
269        assert!(n >= 4, "expected real tokenization, got {n}");
270    }
271
272    #[test]
273    fn image_block_is_flat_estimate_not_base64_length() {
274        // A ~1 MB base64 payload. Under `len() / 4` this reads as ~250_000
275        // tokens, which trips compaction on the first pasted screenshot.
276        let msgs = vec![model_user(vec![ModelContentBlock::Image {
277            media_type: "image/png".into(),
278            data: "A".repeat(1_000_000),
279        }])];
280        assert_eq!(estimate_message_tokens(&msgs), IMAGE_TOKEN_ESTIMATE);
281    }
282
283    #[test]
284    fn empty_messages_are_zero_tokens() {
285        assert_eq!(estimate_message_tokens(&[]), 0);
286    }
287
288    #[test]
289    fn tool_use_counts_its_serialized_input() {
290        let small = vec![model_user(vec![ModelContentBlock::ToolUse {
291            id: "toolu_1".into(),
292            name: "Bash".into(),
293            input: serde_json::json!({}),
294        }])];
295        let large = vec![model_user(vec![ModelContentBlock::ToolUse {
296            id: "toolu_1".into(),
297            name: "Bash".into(),
298            input: serde_json::json!({"command": "grep -rn pattern ./src --include='*.rs'"}),
299        }])];
300        assert!(
301            estimate_message_tokens(&large) > estimate_message_tokens(&small),
302            "tool input must contribute tokens"
303        );
304    }
305
306    #[test]
307    fn estimates_track_the_shape_of_text() {
308        assert_eq!(count_text(""), 0);
309        assert_eq!(count_text("hello world"), 2);
310        assert_eq!(count_text("1234567"), 3);
311        assert_eq!(count_text("这是中文"), 4);
312        assert_eq!(count_text("fn main() {}"), 4);
313        assert_eq!(count_text("    indented"), count_text("indented"));
314        assert_eq!(count_text("a\n\n\nb"), 3);
315    }
316
317    #[test]
318    fn multibyte_text_does_not_panic_and_costs_tokens() {
319        let msgs = vec![model_user(vec![ModelContentBlock::Text {
320            text: "这是一段用于测试的中文内容".repeat(100),
321        }])];
322        assert!(estimate_message_tokens(&msgs) > 0);
323    }
324}
325
326#[cfg(test)]
327mod counter_contract_tests {
328    use super::*;
329
330    /// The contract's default implementation must be the algorithm the free
331    /// functions already use — otherwise "the number that trips compaction
332    /// and the number that decides what to drop are the same number" stops
333    /// being true the moment a caller moves to the trait.
334    #[test]
335    fn the_default_counter_agrees_with_the_free_functions() {
336        let counter = HeuristicCounter;
337        let messages = vec![ModelMessage {
338            role: crate::interface::model::MessageRole::User,
339            content: vec![
340                ModelContentBlock::Text {
341                    text: "a moderately long piece of prose, long enough to matter".repeat(20),
342                },
343                ModelContentBlock::ToolUse {
344                    id: "t1".into(),
345                    name: "Bash".into(),
346                    input: serde_json::json!({"command": "git status"}),
347                },
348                ModelContentBlock::Image {
349                    media_type: "image/png".into(),
350                    data: "AAAA".into(),
351                },
352            ],
353        }];
354
355        assert_eq!(
356            counter.count_messages(&messages),
357            estimate_message_tokens(&messages)
358        );
359        for block in &messages[0].content {
360            assert_eq!(
361                counter.count_block(block),
362                estimate_model_block_tokens(block)
363            );
364        }
365        assert_eq!(counter.count_text("hello there"), count_text("hello there"));
366    }
367
368    #[test]
369    fn the_default_counter_is_the_one_handed_out() {
370        let messages = vec![ModelMessage {
371            role: crate::interface::model::MessageRole::User,
372            content: vec![ModelContentBlock::Text {
373                text: "hello".into(),
374            }],
375        }];
376        assert_eq!(
377            default_counter().count_messages(&messages),
378            estimate_message_tokens(&messages)
379        );
380    }
381}