Drop it into an existing loop
Where recall and encode go in an agent loop you have already written, what to do with the answer, and why writing every turn is the wrong default.
The loop you have
Most agent loops look like this, whatever framework is underneath:
user message
→ build the prompt (system + history + this message)
→ call the model
→ return the replyMemory adds one step before, and one conditional step after:
user message
→ recall(user message) ← new
→ build the prompt (system + recalled facts + this message)
→ call the model
→ return the reply
→ encode(...) if anything durable was learned ← newReading: what to do with the answer
recall gives you an answer kind and a list of hits. Branch on the kind
rather than on whether the list is empty:
const answer = await brain.recall({ query: userMessage, maxResults: 5 });
const context =
answer.answerKind === "none"
? "" // it doesn't know — say nothing
: "What you know about this user:\n" +
answer.memories.map(m => `- ${m.text}`).join("\n");
const prompt = [systemPrompt, context, userMessage].filter(Boolean).join("\n\n");answer = brain.recall(query=user_message, max_results=5)
if answer.answer_kind == "none":
context = "" # it doesn't know — say nothing
else:
lines = "\n".join(f"- {m.text}" for m in answer.memories)
context = f"What you know about this user:\n{lines}"
prompt = "\n\n".join(p for p in (system_prompt, context, user_message) if p)let answer = brain.recall(&RecallInput { query: user_message.clone(), max_results: Some(5), ..Default::default() }).await?;
let context = if answer.answer_kind == "none" {
String::new() // it doesn't know — say nothing
} else {
let lines: Vec<_> = answer.memories.iter().map(|m| format!("- {}", m.text)).collect();
format!("What you know about this user:\n{}", lines.join("\n"))
};Emitting an empty string on None matters more than it looks. A header like
"What you know about this user:" followed by nothing invites the model to
invent the list — you've told it such knowledge exists and then shown it none.
Where in the prompt
Put recalled memories in a stable position — a fixed block in the system prompt, not interleaved into the conversation.
Caching is prefix-based, so anything you mutate invalidates the cache for everything after it. A memory block that reorders itself every turn silently throws away the discount on the entire prompt below it. A fixed slot whose contents change costs you only that slot.
Writing: not every turn
The temptation is encode(userMessage) at the end of every loop. Resist it —
most turns contain nothing durable, and you'll bury the signal. What to
write has the full argument; the short version:
Write on signal. When the user states a preference, makes a decision, corrects something, or asserts a fact about themselves or their setup.
if (looksDurable(userMessage)) {
await brain.encode({ text: userMessage });
}looksDurable can start as a keyword check and become a cheap classifier call
later. Either beats writing everything.
encode is idempotent on identical content by default — writing the same
sentence twice is a no-op, and the response tells you via
was_deduplicated. So a slightly over-eager writer degrades gracefully
instead of duplicating.
Two decisions that are yours
What counts as durable. No library can decide this for your product.
Who the memory is about. If your agent serves one user per space, you're
done — the key's scope handles it. If one space serves many subjects, pass
subject on recall so you retrieve claims about the right person. See
one space per customer.
Try it
Point the two calls at your own deployment — there is no public hosted endpoint yet, so run one yourself — then run your existing agent and ask it something it was told in a previous session.
If it answers, you're done — that's the whole feature. Everything else in this section is about doing it well under load, across tenants, and when the user changes their mind.
Two decisions that are yours
When to write. Not every turn. The cheapest rule that works: write when the user states something durable about themselves, their setup, or their preferences — and when they correct you. Everything else is the exchange, not a memory. What to write has the longer version.
What none means in your product. Brain answering none is Brain telling
you it holds nothing relevant. That is information, and it is not an error. An
agent that says "I don't have anything on that yet" is more trustworthy than one
that pads the prompt with weak matches — and padding is exactly what happens if
you ignore the verdict and splice in whatever came back.
Don't block the turn on the write
encode returns at the durability barrier, not when derivation finishes, so it
is already fast. Even so, the write is about the turn that just happened — the
reply does not depend on it. Fire it after you have responded, and handle its
failure out of band.
A failed write is a lost memory, not a failed turn. Retry it with the same
request object rather than rebuilding it: the builders mint a fresh request id
on every build(), so re-building is not retrying — it produces a second,
distinct write. See Idempotency.
Was this page helpful?
Build
Task recipes for an agent you have already written — wiring in recall, handling corrections, combining with RAG, isolating tenants, and erasing a subject.
A chatbot that remembers
Give a chat agent continuity across sessions by recalling on the cue rather than replaying the transcript — bounded context that does not grow with history.