Skip to main content

Memory

A conversation grows with every message, and a model can only read so much. Memory decides what the model sees of a conversation on each send, for example only the last few exchanges, only what fits a token budget, or a summary of the older turns plus the recent ones. This guide covers the memories Freyja ships and how to write your own.

Memory is not storage​

Storage is where the whole conversation lives. Memory is what part of it, or what in place of it, reaches the model. The two are independent, so any memory works with any backend.

The backend keeps every turn. On each send the conversation loads the whole stored transcript, hands it to the memory, and sends what Memory::recall returns. A window therefore discards nothing: chat.storage().messages().len() still sees every turn. Without a memory the whole transcript is sent. Agent::memory replaces any memory set before it.

use freyja::{Agent, InMemoryStorage, Window};

let agent = Agent::new(client).memory(Window::last(20));
let mut chat = agent.conversation(InMemoryStorage::new());

Memory runs before the repair pass, so a cut that separates a tool call from its result loses only that pair. The examples on this page that build a Client or call a model need a key and network access.

Turn groups​

Windows count turn groups, not messages. A group is one message, except that an assistant turn requesting tools and the results answering it form one group. An exchange without tools is two groups and one with a tool call is three or more. Window::last(20) therefore keeps roughly seven exchanges for a tool-using agent, not twenty.

Trimming what a tool returns bounds the cost of one round. Every tool result becomes part of the prompt on the next round and is billed as input tokens on every round after that, so a verbose tool is a recurring cost, and a tool should return what the model needs and nothing more. It does not bound the conversation, which grows until the provider rejects it outright, and that is the job of a window. A tool that occasionally returns something large is what Window::last handles badly, since one oversized group still counts as one group. Window::tokens bounds by an estimated token budget instead, so a group's size affects whether it survives the cut.

Pinned turns, which are the System and Developer ones, are always sent whatever the window.

Window::last​

Window::last(n) keeps the newest n turn groups plus the pinned turns.

let agent = Agent::new(client).memory(Window::last(20));

Window::tokens​

Window::tokens(budget, counter) keeps the newest groups that fit an estimated token budget.

use freyja::{HeuristicCounter, Window};

let agent = Agent::new(client).memory(Window::tokens(4_000, HeuristicCounter));

The budget covers the stored transcript only. The system instruction, the tool schemas, the model's reply and the provider's own envelope ride on top, so subtract them yourself when you choose a number. Two guarantees make the budget a target rather than a cap. Every pinned turn survives at any budget, including zero, and the newest group survives even when it alone is over budget, because a request that is too large may still succeed while an empty one certainly fails.

Counting tokens​

counter is anything that implements TokenCounter, a trait with one method, count(&self, message: &Message) -> usize. Counting exactly depends on the provider, and Freyja takes no tokenizer dependency, so the count comes from you.

HeuristicCounter is the built-in estimate, roughly four bytes of text per token plus a small constant per message, and 1,600 tokens for an image or a file. It undercounts code, JSON and CJK text, so leave a margin.

Any closure Fn(&Message) -> usize + Send is a counter. This one counts words:

use freyja::{InputContent, Message, Window};

let words = |message: &Message| {
message
.content
.iter()
.map(|part| match part {
InputContent::Text(text) => text.split_whitespace().count(),
_ => 0,
})
.sum::<usize>()
};

let agent = Agent::new(client).memory(Window::tokens(3_000, words));

A struct works the same way, and suits a counter that carries state such as a tokenizer. Window::tokens also needs Sync, because the window belongs to an agent that its conversations share.

use freyja::{Message, TokenCounter};

struct PerPart(usize);

impl TokenCounter for PerPart {
fn count(&self, message: &Message) -> usize {
self.0 * message.content.len()
}
}

A real tokenizer is the closest to exact. This example uses the external tiktoken-rs crate, which is not a Freyja dependency, and its names are the 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 text: 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(),
_ => 0,
})
.sum();
text + 4
};

let agent = Agent::new(client).memory(Window::tokens(4_000, counter));

A counter must be cheap, since it runs over the history each time a window decides what to keep, and it cannot fail. One that could fail should return its own guess instead.

Summarizing what the window drops​

Window::summarize(summarizer) returns a Summarize, a memory that turns what the window drops into one summary instead of losing it. It works over either kind of window.

use freyja::{Summarizer, Window};

let agent = Agent::new(client.clone()).memory(
Window::last(20).summarize(Summarizer::new(client)),
);

The dropped turns, minus the pinned ones, go to the summarizer. The result is sent as one user message headed "Summary of the earlier conversation:", after the pinned turns and before the turns still in view. The backend still holds every raw turn.

Each summary costs one extra model call, so it is made at a deeper cut than the window needs, at half the window. That leaves room for the next several turns, and the summary is reused until the window needs to drop more than it covers. A very small window has little room to give and summarizes again on nearly every turn. A new summary is built from the raw turns, never from the previous summary, so detail does not decay, at the price of a longer summarizing input as the conversation grows. The summary rides on top of a token budget rather than inside it. If the summarizing call fails, the plain window is sent and the conversation carries on.

The summary is kept in the state slot under the key freyja.summary. A backend that keeps no state still reuses it within one Conversation, and one that persists state, as JsonlStorage does, lets a later process reuse it too. Read it with Conversation::summary, and summarize ahead of time with Conversation::compact and Compact::keep. See Conversations.

Summarizer​

Summarizer::new(model) takes any Model and owns it, so the summary is made with no help from the conversation. Nothing carries over: not the agent's system instruction, tools or token cap. Three builder methods set its own, model(name), prompt(text) and max_tokens(n), so you can summarize with a cheaper model than the one that answers.

let summarizer = Summarizer::new(client)
.model("gpt-4o-mini")
.max_tokens(400);

It sends the dropped turns as one block of text under its own instruction rather than replaying them as a conversation, which would make the model answer the last turn instead of summarizing it. Reasoning parts are left out, since they may be dropped but never summarized. A reply that was cut short, or has no text, is an Error::InvalidResponse.

A memory of your own can call summarizer.summarize(&messages).await?, which returns the summary text.

Windowing in your own code​

window_by_groups(history, keep) and window_by_tokens(history, budget, &counter) are the rules Window applies, published as functions. Use them inside your own Memory, or inside a Storage::load, to get the same group-aware cut. Both return a new Vec<Message>, and both keep pinned turns first.

use freyja::{HeuristicCounter, window_by_tokens};

let kept = window_by_tokens(&history, 4_000, &HeuristicCounter);

Writing a Memory​

Memory has one required method, recall, which takes the whole stored conversation, oldest first, and returns what to send. Your new message is added after it returns. It returns a MemoryFuture, a boxed future that resolves to Result<_, MemoryError>, and MemoryError is a boxed standard error.

use freyja::{Memory, MemoryFuture, Message, State};

struct LastTen;

impl Memory for LastTen {
fn recall<'a>(
&'a self,
messages: &'a [Message],
_state: &'a mut State<'_>,
) -> MemoryFuture<'a, Vec<Message>> {
Box::pin(async move {
let from = messages.len().saturating_sub(10);
Ok(messages[from..].to_vec())
})
}
}

let agent = Agent::new(client).memory(LastTen);

This cut is by message, so it may land between a tool call and its result. The repair pass drops the stranded half, so a memory does not need to know about pairing.

A memory keeps nothing in itself. One value serves every conversation an agent starts, so what it needs between sends goes in the conversation's state slot through State. state.get(key).await? returns an Option<serde_json::Value>, and state.set(key, value).await? stores one. Use your own key prefix, since freyja. belongs to the built-in summary.

use serde_json::json;

struct Counting;

impl Memory for Counting {
fn recall<'a>(
&'a self,
messages: &'a [Message],
state: &'a mut State<'_>,
) -> MemoryFuture<'a, Vec<Message>> {
Box::pin(async move {
let seen = state
.get("app.sends")
.await?
.and_then(|value| value.as_u64())
.unwrap_or(0);
state.set("app.sends", json!(seen + 1)).await?;
Ok(messages.to_vec())
})
}
}

Reads come from the backend first and fall back to a cache that lives as long as the Conversation, so a backend that keeps no state still serves the value within one conversation. A backend that persists state lets it outlive the process. A memory must cope with finding nothing, since state may be missing, and rebuild it.

An error from recall fails the send, so return Err only when the send should not go ahead. compact has a default that refuses with an error, and a memory that can summarize overrides it. See Storage for what a backend must do to keep state.

State::new(&mut storage) builds a handle with its own cache, for testing a memory outside a conversation.

See also​