Conversations
A conversation is an agent plus a transcript that persists between messages. You send a message, the agent runs its loop, and the turns it produced are written to a storage backend, so the next message continues where the last one stopped. This guide covers sending, streaming, what gets stored, and the operations that manage a transcript.
Starting one
use freyja::InMemoryStorage;
let mut chat = agent.conversation(InMemoryStorage::new());
let run = chat.send("What is 20 + 22?").await?;
println!("{}", run.answer);
Agent::conversation(storage) always takes the backend, so nothing chooses one for you. InMemoryStorage lives as long as the process, JsonlStorage::open(path)? lives in a file, the freyja-sqlx crate's PgStorage, MySqlStorage and SqliteStorage live in a database, and &mut history runs over a Vec<Message> you already hold. See Storage for the backends.
A Conversation owns its storage and is deliberately not Clone. Every send takes &mut self, so two sends on one conversation cannot overlap, and the compiler refuses the attempt. One agent hands out as many conversations as you like.
The examples on this page call a real provider, so they need a key and network access.
Sending a message
send(message) takes anything that converts into a Message, such as a &str or a String, and returns a Run. Each send does the following, in order:
- Loads the transcript from storage.
- Passes it through the agent's memory, if one is set.
- Repairs tool calls and results that were cut apart.
- Appends your message and runs the tool-calling loop.
- Writes the turns the run produced back to storage.
Per-run context
.context(&cx) attaches a Context to a send. The context reaches every tool, guard and hook of that run, and holds what exists only once a request arrives, such as a user id. Without it a send runs with an empty context.
use freyja::Context;
struct UserId(String);
let mut cx = Context::new();
cx.insert(UserId("u_42".to_string()));
let run = chat.send("What's my balance?").context(&cx).await?;
Context is keyed by type, so give distinct values distinct newtypes. See Tool calling.
Streaming
.stream(on_event) runs the same loop with every request streamed, and calls on_event with each AgentEvent as it happens. It returns the same Run and stores the same turns as a plain send, and combines with .context.
use freyja::{AgentEvent, StreamEvent};
let run = chat
.send("Count to three")
.stream(|event| match event {
AgentEvent::Model(StreamEvent::TextDelta(text)) => print!("{text}"),
AgentEvent::ToolResult { name, output, .. } => println!("[{name}: {output}]"),
AgentEvent::Handoff { from, to } => println!("[{from} -> {to}]"),
_ => {}
})
.await?;
AgentEvent is #[non_exhaustive], so keep the trailing _ arm. Model wraps what the model streamed, including a tool call before it runs. ToolResult arrives once every call of a turn has finished. Handoff appears only inside a team.
What is stored and when
The backend holds your message and every turn the run produced after it: the assistant's replies, its tool calls and the tool results. It does not hold the agent's system instruction, which is added to each request and never saved.
Storage is written last, after the run ends. A run that fails with an Err, for example because a request returned an error, stores nothing, and the conversation is exactly as it was before the send. A run that ends with an Ok stores its turns whatever its StopReason. That includes MaxTurns and Refused, and also a run a hook stopped before the first request, which stores your message with no reply.
A window set with Agent::memory shapes what is sent and never what is stored. The backend keeps every turn.
Reading and resetting
storage() returns a reference to the backend. For InMemoryStorage, messages() on it borrows the whole transcript, which is how you check what has accumulated rather than what was last sent.
println!("{} turns stored", chat.storage().messages().len());
clear().await? empties the transcript, the state slot and the cached summary, in the backend as well as in the handle. The conversation stays usable, so the next send starts from nothing with the same agent, backend and memory. Dropping a Conversation is not a substitute for a backend that persists, because the rows outlive the value and a new conversation over the same id loads them straight back. A failed clear can leave a backend half emptied, so call it again, which every Storage must accept on an empty conversation.
Summaries and compaction
When the agent's memory is Window::summarize, the conversation keeps a summary of what the window dropped.
summary().await? returns Result<Option<String>, Error>, the text of the summary last made, or None when the memory does not summarize or has not needed to yet.
compact() summarizes now instead of waiting for the window to need it. It returns a Compact that runs when awaited, and keep(n) on it leaves the newest n turn groups as they are.
chat.compact().keep(4).await?;
println!("{:?}", chat.summary().await?);
The next send carries the summary in place of the summarized turns, and every turn stays in storage. A memory that does not summarize, or no memory, returns an error and makes no request. See Memory.
Waiting calls and resuming
When the guard answers Decision::Ask, the run ends with StopReason::Paused before any tool of that turn runs. pending().await? returns the tool calls still waiting, read from storage, so it works in a new process that reopens the same backend. resume(decide) settles them, with Allow running a call and Deny(reason) telling the model why not, and carries the conversation on as a new run. It takes .context and .stream as send does.
use freyja::{Decision, StopReason};
let run = chat.send("Email the report to Sam").await?;
if run.stop == StopReason::Paused {
for call in chat.pending().await? {
println!("{} wants {}", call.name, call.arguments);
}
chat.resume(|_call| Decision::Allow).await?;
}
The full flow, including what survives a restart, is in Human approval.
Repair of broken tool call pairs
Every provider rejects a tool call with no result, and a result with no call. A backend that trims on the wrong boundary, or a process killed mid-write, can produce either. So send runs a repair pass over what storage and memory return, before building the request. It drops a tool result whose call is absent or comes later, and a call whose result is absent, and removes any message left empty. Only the broken pair is lost, and storage itself is not changed. The repair is unconditional, so a backend or a memory that knows nothing about tool pairing cannot produce a request that fails this way.
Limits
send always adds a turn before running the loop, so a run that stopped at MaxTurns cannot be continued with an empty send. Send a short nudge such as "continue" instead.
Two Conversation values over one shared backend can still interleave their sends, because &mut self only guards one handle. A backend built to allow that has to serialize writes itself.
See also
- Agents for building the agent a conversation runs
- Memory for windows and summaries
- Storage for backends and writing your own
- Human approval for pausing and resuming in full
- Hooks for code that runs around every call
- Multi-agent for teams, whose conversations carry on across a handoff
- Testing for running a conversation with no key
- Tool calling for
Contextand guards