Skip to main content

Long conversations

A chat that lasts days, across restarts, with one conversation per user. Freyja keeps a conversation in whatever storage you give it, and a storage that outlives the process is all it takes.

use freyja::{Agent, JsonlStorage, Message, Window};

/// Answers one message from `user_id`, in the conversation kept for them.
async fn reply(agent: &Agent, user_id: u64, message: Message) -> Result<String, Box<dyn std::error::Error>> {
let mut chat = agent.conversation(JsonlStorage::open(format!("chats/{user_id}.jsonl"))?);
let run = chat.send(message).await?;
Ok(run.answer)
}

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

JsonlStorage::open creates the file the first time and continues it every time after, so a request on Monday and one on Thursday are the same conversation. Nothing has to be loaded or saved by hand: send reads the transcript and appends the new turns.

A web server opens the conversation per request. Two requests for the same user at once would write to one file together, so send them one at a time per user.

Several servers​

A file lives on one machine. With more than one server, keep conversations in the database instead, with freyja-sqlx:

use freyja_sqlx::PgStorage;

PgStorage::migrate(&pool).await?;
let mut chat = agent.conversation(PgStorage::new(pool.clone(), format!("user-{user_id}")));

SQLite and MySQL work the same way. See Storage.

Keeping it bounded​

Storage keeps every turn. What the model is sent is up to the memory. Window::last(20) sends the latest twenty turns, Window::tokens sends what fits a token budget, and .summarize(...) folds older turns into a summary instead of dropping them. See Memory.

A long system prompt stays cached on Anthropic as the window slides, since it comes first and never changes.

Pausing for a person​

A run that stops for approval waits in the transcript, so a reply that comes days later resumes it, even in another process. See Surviving a restart.