Memory
A Memory decides what the model sees of a conversation on each send. The storage backend keeps every turn, and the memory chooses which of them, or what in their place, goes into the request. Freyja ships Window::last, Window::tokens and Window::summarize. Write your own for a rule they do not cover, such as keeping the turns that mention open tasks, or retrieving the older turns that match the new question.
This page is the contract for an implementation. Memory covers the built-in memories and how turn groups work.
The trait
pub type MemoryError = Box<dyn std::error::Error + Send + Sync>;
pub type MemoryFuture<'a, T> = Pin<Box<dyn Future<Output = Result<T, MemoryError>> + Send + 'a>>;
pub trait Memory: Send + Sync {
fn recall<'a>(
&'a self,
messages: &'a [Message],
state: &'a mut State<'_>,
) -> MemoryFuture<'a, Vec<Message>>;
fn compact<'a>(
&'a self,
messages: &'a [Message],
state: &'a mut State<'_>,
keep: Option<usize>,
) -> MemoryFuture<'a, ()> {
Box::pin(async { Err("this memory does not summarize, so it cannot compact".into()) })
}
}
Set one with Agent::memory. The last one set is the one used, and without one every stored turn is sent. Any memory works with any Storage.
A memory keeps nothing in itself
One memory value belongs to the agent and serves every conversation the agent starts, possibly at the same time. Anything it needs to remember about one conversation therefore goes in that conversation's state slot, through the State handle it is given, never in its own fields. Its fields hold configuration only, such as how many turns to keep or the model to summarize with.
recall
Called on every send, before the request is built. messages is the whole stored conversation, oldest first, and the returned vector is what the model sees of it. The user's new turn is added after recall returns, and the agent's system instruction is put in front, so a memory never has to keep either.
What recall returns is only what is sent. Storage keeps every turn regardless, so a memory that drops a turn today can bring it back on the next send.
A cut does not have to respect tool pairs. The conversation repairs what recall returns, dropping a tool call whose result was cut off and a result whose call was. A memory that wants to keep pairs whole cuts with window_by_groups or window_by_tokens, which count turn groups and never split one.
Returning Err fails the send with no request made. Return an error only when sending would be wrong, and fall back to sending more rather than failing when a lookup the memory relies on is missing.
compact
Called by Conversation::compact, which a caller uses to shrink a conversation now rather than when the window would. keep is the number of newest turn groups to leave as they are, or None to let the memory choose. It records in the state slot what the next recall should do differently, and sends nothing itself.
The default refuses with an error, which Conversation::compact returns to its caller. Override it only if the memory can do something meaningful, such as summarizing or moving a cut.
State
State reads and writes the conversation's state slot.
| Method | Returns |
|---|---|
state.get(key).await? | Option<serde_json::Value>, the value under key if there is one |
state.set(key, value).await? | (), after storing value under key |
Reads go to the backend first and fall back to a cache that lives as long as the Conversation, so a value set during one conversation is there for its next send even on a backend that keeps no state. A backend that keeps state lets the value outlive the process.
A value can always be missing: on a new conversation, after a clear, or after a restart on a backend that keeps no state. A memory treats a missing value as the starting point and rebuilds from there.
Prefix your keys with your crate's name. Keys starting with freyja. belong to Freyja, and the built-in summary is stored under one.
Example: a memory that forgets on request
Checkpoint sends the whole conversation until the caller compacts it. Compacting records a cut in the state slot, and from then on recall sends only what comes after the cut. Nothing is summarized, so compacting costs no model call. It is a way to start a fresh context in a long conversation without losing the stored history.
use freyja::{Memory, MemoryFuture, Message, State, window_by_groups};
use serde_json::json;
const CUT: &str = "app.checkpoint.cut";
struct Checkpoint {
keep: usize,
}
impl Memory for Checkpoint {
fn recall<'a>(
&'a self,
messages: &'a [Message],
state: &'a mut State<'_>,
) -> MemoryFuture<'a, Vec<Message>> {
Box::pin(async move {
let cut = state
.get(CUT)
.await?
.and_then(|value| value.as_u64())
.unwrap_or(0) as usize;
Ok(messages[cut.min(messages.len())..].to_vec())
})
}
fn compact<'a>(
&'a self,
messages: &'a [Message],
state: &'a mut State<'_>,
keep: Option<usize>,
) -> MemoryFuture<'a, ()> {
Box::pin(async move {
let kept = window_by_groups(messages, keep.unwrap_or(self.keep));
let cut = messages.len() - kept.len();
state.set(CUT, json!(cut)).await?;
Ok(())
})
}
}
compact uses window_by_groups to find where the newest keep groups start, so the cut never separates a tool call from its result. window_by_groups also keeps every System and Developer turn wherever it sits, which would make this count wrong for a transcript holding them. A transcript written by an agent holds none, because Agent::system is added to each request and never stored.
recall clamps the cut to the length of what it was given. A backend that keeps no state loses the cut on restart, and one that trims in load can return fewer messages than were stored, and both must still send something sensible.
Use it like any memory:
let agent = Agent::new(client).memory(Checkpoint { keep: 4 });
let mut chat = agent.conversation(InMemoryStorage::new());
chat.send("Let's plan the launch.").await?;
// ... a long conversation ...
chat.compact().keep(2).await?;
chat.send("Now the budget.").await?;
After the compact, the model sees the last two groups and the new message. chat.storage().messages() still holds every turn.
Testing it
State::new(&mut storage) builds a state handle over any backend, with a cache of its own, so a test calls recall and compact with no agent and no model. Vec<Message> is a backend that keeps no state, so this also checks that the memory works through the cache:
#[tokio::test]
async fn recall_sends_everything_until_compact_moves_the_cut() {
let mut storage: Vec<Message> = (0..6)
.map(|n| Message::text(Role::User, format!("turn {n}")))
.collect();
let messages = storage.clone();
let mut state = State::new(&mut storage);
let memory = Checkpoint { keep: 4 };
assert_eq!(memory.recall(&messages, &mut state).await.unwrap().len(), 6);
memory.compact(&messages, &mut state, Some(2)).await.unwrap();
let sent = memory.recall(&messages, &mut state).await.unwrap();
assert_eq!(sent, messages[4..].to_vec());
}
Through an agent, a ScriptedModel records each request, so a test checks exactly what was sent:
let model = Arc::new(ScriptedModel::new().text("a").text("b").text("c"));
let agent = Agent::new(model.clone()).memory(Checkpoint { keep: 4 });
let mut chat = agent.conversation(InMemoryStorage::new());
chat.send("one").await?;
chat.send("two").await?;
chat.compact().keep(1).await?;
chat.send("three").await?;
// The third request holds the kept "b" and the new "three".
assert_eq!(model.requests()[2].messages.len(), 2);
assert_eq!(chat.storage().messages().len(), 6);
Stability
Memory stays usable as dyn Memory, which is how an agent holds it. A method added to it later comes with a default, as compact has, so an implementation written today keeps compiling.
See also
- Memory for
Window, turn groups and summaries - TokenCounter for the counter
Window::tokenstakes - Storage for the backend side of the state slot
- Conversations for
compact,clearand what a send does