TokenCounter
A TokenCounter estimates how many tokens one message adds to a request. Window::tokens and window_by_tokens use it to decide how much of a conversation fits a budget. Counting exactly depends on the provider's tokenizer, and Freyja depends on none, so the built-in HeuristicCounter estimates from byte length. Write your own to use a real tokenizer, or to correct the estimate for content it gets wrong.
The trait
pub trait TokenCounter: Send {
fn count(&self, message: &Message) -> usize;
}
impl<F: Fn(&Message) -> usize + Send> TokenCounter for F { /* calls the closure */ }
Any closure of that shape is already a counter, so a struct is only needed for a counter with fields or more than a few lines of logic.
window_by_tokens borrows a counter for one call and needs only Send. Window::tokens keeps the counter inside the agent's memory, which all of the agent's conversations share, so it also needs Sync and 'static.
count
Returns the estimated tokens message adds to a request, including the few tokens every provider spends marking where a turn starts and who wrote it.
It must be cheap. A window calls it on each message, newest first, every time it decides what to keep, which is on every send.
It cannot fail. A window cannot ask anyone what to do with a failed count, and failing a send over an estimate is worse than a rough estimate, so a counter whose tokenizer can fail returns a guess instead, such as what HeuristicCounter would say.
It counts one message at a time, never a whole transcript. That lets a window stop as soon as the budget is spent. It also means a counter never sees a partial transcript, such as a tool result whose call was trimmed, which some providers' counting endpoints reject.
A message holds a list of InputContent parts: Text, ImageUrl, ToolCall, ToolResult and Reasoning. A counter that skips a kind counts it as free, and a window then keeps more than fits. Count every kind, even roughly.
What HeuristicCounter does
It counts four bytes of UTF-8 as one token, across the text, tool calls and results of the message, and adds four for the turn itself. That is close for English prose. It undercounts code, JSON and Chinese, Japanese or Korean text, which spend more tokens per byte, so a budget used with it needs a margin below the model's real limit.
Media is counted by what it shows, not by its bytes, since a provider charges by pixels and pages. An image or a file counts as 1,600 tokens, whatever its URL, which is about one image or one PDF page on Anthropic, where a 1024 by 768 PNG cost 1,047 and a one-page PDF about 1,620. Audio counts about 32 tokens a second. A long PDF still counts as one page, which is where it is furthest off.
Example: images at your provider's cost
ImageAware counts each image at a figure you choose instead of 1,600, and leaves the rest of the message to HeuristicCounter:
use freyja::{HeuristicCounter, InputContent, Message, TokenCounter};
struct ImageAware {
per_image: usize,
}
impl TokenCounter for ImageAware {
fn count(&self, message: &Message) -> usize {
let images = message
.content
.iter()
.filter(|part| matches!(part, InputContent::ImageUrl(_)))
.count();
let text: Vec<InputContent> = message
.content
.iter()
.filter(|part| !matches!(part, InputContent::ImageUrl(_)))
.cloned()
.collect();
let rest = HeuristicCounter.count(&Message::new(message.role.clone(), text));
rest + images * self.per_image
}
}
Use the figure your provider documents for the image sizes you send. For GPT-4o, OpenAI documents a high-detail image of 1024 by 1024 pixels as 765 tokens:
let agent = Agent::new(client).memory(Window::tokens(
8_000,
ImageAware { per_image: 765 },
));
The budget covers the stored conversation only. The system instruction, every tool's schema and the model's reply come on top of it, so subtract all three from the model's context limit when you choose it.
Example: a real tokenizer
A tokenizer gives the exact count for one provider's models. This closure uses the tiktoken-rs crate, which is not a Freyja dependency, for OpenAI models. Its names are that crate's own, so check them against the version you install:
use freyja::{InputContent, Message, Window};
let bpe = tiktoken_rs::cl100k_base()?;
let counter = move |message: &Message| {
let tokens: usize = message
.content
.iter()
.map(|part| match part {
InputContent::Text(text) => bpe.encode_with_special_tokens(text).len(),
InputContent::ToolCall { arguments, .. } => bpe.encode_with_special_tokens(arguments).len(),
InputContent::ToolResult { output, .. } => bpe.encode_with_special_tokens(output).len(),
InputContent::ImageUrl(_) => 765,
InputContent::Reasoning { data } => data.to_string().len() / 4,
// Files, audio, and any kind added later.
_ => 1_600,
})
.sum();
tokens + 4
};
let agent = Agent::new(client).memory(Window::tokens(4_000, counter));
Reasoning is an opaque JSON value the provider gave back, and a tokenizer cannot read it, so it falls back to the byte estimate. InputContent is non_exhaustive, so the match needs a last arm, and a kind added later lands there at a flat cost rather than counted as free.
Using a counter in your own code
window_by_tokens(history, budget, &counter) applies the same rule as Window::tokens to any slice, outside an agent. A storage backend can call it inside load to trim what it returns, and a test can check a counter with it. It keeps every System and Developer turn and the newest turn group even when they alone exceed the budget, because a request that is too large may fail but an empty one certainly does.
Testing it
A counter is a plain function of one message, so a test builds messages and compares counts:
#[test]
fn an_image_costs_the_same_whatever_its_url() {
let counter = ImageAware { per_image: 765 };
let short = Message::new(Role::User, vec![InputContent::ImageUrl("https://a.example/x.png".into())]);
let long = Message::new(
Role::User,
vec![InputContent::ImageUrl(format!("data:image/png;base64,{}", "A".repeat(40_000)))],
);
assert_eq!(counter.count(&short), counter.count(&long));
}
#[test]
fn a_window_keeps_what_fits() {
let counter = ImageAware { per_image: 765 };
let history = vec![
Message::new(Role::User, vec![InputContent::ImageUrl("https://a.example/x.png".into())]),
Message::text(Role::Assistant, "a cat"),
Message::text(Role::User, "and the colour?"),
];
assert_eq!(window_by_tokens(&history, 100, &counter).len(), 2);
}
Stability
TokenCounter has one method and a blanket implementation for closures. A method added to it later comes with a default. InputContent is not #[non_exhaustive], so a match over every kind, as above, becomes a compile error when a new kind is added rather than silently counting it as zero.
See also
- Memory for
Window::tokensand the word-count closure - Memory for a memory with a rule of its own
- Messages and content for every
InputContentkind - Observability for the tokens a provider actually reports