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.
What not to do
The obvious implementation is to store the transcript and replay it. It works for a week, then:
- the prompt grows without bound, and cost grows with it
- quality falls as the window fills (why)
- old statements the user has since contradicted are still in there, competing
Replaying history is the thing memory replaces, not the thing it stores.
The shape that works
Recall on the current cue, not on the conversation. You want the three things relevant to what was just asked, not the last three hundred turns.
async function handleTurn(userMessage: string, sessionId: bigint) {
// 1. what do we know that bears on THIS message?
const answer = await brain.recall({ query: userMessage, maxResults: 5 });
const known = answer.answerKind === "none"
? ""
: answer.memories.map(m => `- ${m.text}`).join("\n");
// 2. short-term continuity stays in the prompt; long-term comes from recall
const reply = await model.complete({
system: known ? `${systemPrompt}\n\nAbout this user:\n${known}` : systemPrompt,
messages: recentTurns, // just this session, a bounded window
user: userMessage,
});
// 3. write only what should outlive the session
if (looksDurable(userMessage)) {
await brain.encode({ text: userMessage, session: sessionId });
}
return reply;
}def handle_turn(user_message: str, session_id: int) -> str:
# 1. what do we know that bears on THIS message?
answer = brain.recall(query=user_message, max_results=5)
known = "" if answer.answer_kind == "none" else "\n".join(
f"- {m.text}" for m in answer.memories
)
# 2. short-term continuity stays in the prompt; long-term comes from recall
system = f"{SYSTEM_PROMPT}\n\nAbout this user:\n{known}" if known else SYSTEM_PROMPT
reply = model.complete(system=system, messages=recent_turns, user=user_message)
# 3. write only what should outlive the session
if looks_durable(user_message):
brain.encode(text=user_message, session=session_id)
return replyTwo timescales, two mechanisms
This is the distinction that makes the pattern work:
Trying to serve both with one mechanism is the mistake. A transcript can't do the second without growing forever; recall can't do the first, because "what did you just say?" has no durable subject to retrieve on.
Sessions group, they don't isolate
Passing session on encode tags the memory with the
conversation it came from. It is a grouping label, not a boundary — recall
spans the space by default, which is the point. A preference stated in March
should surface in December.
Session ids are caller-assigned, not server-generated, so derive one from an id
you already hold — a thread id, a ticket number — and there is no mapping table
to keep in sync. You do not have to create a session before writing to it;
createSession exists to give it a title and to
read its counters back.
What a session is good for:
| Want | Use |
|---|---|
| "What happened in that conversation?" | GET /v1/memories, or a session filter |
| Clean up one conversation's writes | DELETE /v1/sessions/{id} |
| Group memories for a later audit | The session tag itself |
The wire RecallBuilder does expose .sessions([...]), so you can narrow
retrieval to one conversation. Reach for it only when the question is
genuinely about that conversation. Using it as the default turns durable
memory back into per-thread history and throws away the thing you adopted
Brain for.
What to write, and when
The write is the decision, not the call. A rough rule that holds up:
Write itdurable, about the userStated preferences, corrections, facts about their setup, decisions with consequences. Anything you would want a colleague to have read before the next conversation.
Don't write ittransient or about the exchangePleasantries, the model's own replies, restatements of what the user just said, and anything whose tense is relative to this moment. See What to write.
Writing every turn is the common failure: it fills the space with conversation-shaped text that has no clean subject, which extraction cannot type and recall then has to rank around.
Try it
Run two separate sessions in the playground against the same space — write something in the first, then start a new session and read.
The second session recalls what the first one learned, and you never passed it any history.
Was this page helpful?
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.
Handling corrections
When a user says "actually, no" — the highest-value write an agent can make, and why it needs no special API, only a timely encode.