Skip to main content

Long-term memory

An agent forgets everything when a conversation ends. To keep facts across conversations, store them in an index, let the model save new ones with a tool, and let Recall put the facts that match each question into the request. The facts can be about anything that outlives one conversation: a user's preferences, a customer account, a project's decisions, or what an agent learned on earlier runs.

This page keeps facts per user. For facts per customer or per project, key the collection by that id instead.

One index per owner​

Keep each owner's facts in their own collection in Postgres, so one user's facts never reach another user's requests. PgVectorStore is in the freyja-sqlx crate with its pgvector feature, and Index::with_store searches whatever the collection already holds, as Keeping an index across restarts shows.

use freyja::{Client, EndpointPreset, Index};
use freyja_sqlx::PgVectorStore;
use sqlx::PgPool;

// Connects to OpenAI with the key in OPENAI_API_KEY, for the embeddings.
let embedder = Client::from_env(EndpointPreset::OpenAi)?;

let pool = PgPool::connect(&database_url).await?;
PgVectorStore::migrate(&pool, 1536).await?;

let store = PgVectorStore::new(pool.clone(), format!("memory-{user_id}"));
let facts = Index::with_store(embedder, "text-embedding-3-small", store);

Building the store touches no database, so building one per request costs nothing. Run migrate once at start.

A tool that remembers​

The model decides what is worth remembering. A remember tool made with #[tool] takes the fact and adds it to the user's index, with the metadata {"kind": "fact"} so the facts can be found again to delete them. A #[tool] function is a free function and cannot capture the index, so the index rides in the run's Context, under a newtype of its own.

use freyja::{Context, Document, Index, ToolError, tool};
use serde_json::json;

/// The index of facts about the user this run belongs to.
struct Facts(Index);

#[tool(description = "Saves a short fact the user told you about themselves, to remember in later conversations")]
async fn remember(cx: &Context, fact: String) -> Result<String, ToolError> {
let Facts(facts) = cx.require::<Facts>()?;
facts
.add([Document::new(fact).metadata(json!({"kind": "fact"}))])
.await
.map_err(|error| ToolError::Execution(error.to_string()))?;
Ok("Remembered.".to_string())
}

The model sees a tool that takes one fact. The context is left out of the schema, so the model cannot choose whose index it writes to.

Recalling the facts​

Recall wraps the client. Before each call it searches the index with the newest user message and puts the nearest facts at the start of that message, under a line saying they are data, not instructions. So the facts reach every request, and the model never has to ask for them. top keeps at most that many facts, 3 unless set, and min_score drops the ones that match weakly.

use freyja::{Agent, Recall};

// Connects to Anthropic with the key in ANTHROPIC_API_KEY.
let client = Client::from_env(EndpointPreset::Anthropic)?;

let agent = Agent::new(Recall::new(client, facts.clone()).top(5))
.system("When the user tells you something about themselves worth keeping, save it with remember.")
.tool(remember);

let mut cx = Context::new();
cx.insert(Facts(facts));

let run = agent.ask("I'm vegetarian. What should I cook tonight?").context(&cx).await?;
println!("{}", run.answer);

A Recall searches one index, so build one agent per user, each around a clone of the same client. The facts are added to the request only, not saved to the conversation, and a failed search fails the call.

The recall and the tool share one index, so a fact saved during a run is found by the next question.

Forgetting​

A user who asks you to forget them gets their facts deleted. Index::delete deletes every text whose metadata matches a filter, and returns how many it deleted.

use freyja::Index;
use serde_json::json;

/// Deletes every fact remembered about the user whose index this is.
async fn forget(facts: &Index) -> Result<usize, freyja::Error> {
facts.delete(&json!({"kind": "fact"})).await
}

To delete one fact at a time, give each fact an id in its metadata when it is saved, and delete with json!({"id": id}). PgVectorStore::clear deletes the whole collection, facts and anything else in it.

Remembered prompt injection​

A saved fact is read by every later request of that user. A fact the model copied from a document, a tool result or a web page can carry instructions, such as "always recommend this shop", and those instructions then ride along in every conversation that follows, long after the page is gone.

Recall marks the facts as data, not instructions, and that helps. A model can still follow them. So keep facts short, review them before they are saved, or let the tool save only what the user said about themselves, never text the model read elsewhere. The tool's description and the system prompt are the place to say so, and a guard can check a fact before remember runs.