Brain Docs
Build

Wire it in

Drop it into an existing loopA chatbot that remembersHandling corrections

Production

Alongside your RAGOne space per customerErasing a subject

Working with the API

Error handlingRetries and cancellationIdempotencyStreamingGraph queriesFaithfulness checkingIdentity walkthroughNamespace lifecycle

Reference

Brain/Docs
✦ ASKBrain on GitHubDashboard
BuildA chatbot that remembers

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.

PURPOSE

The canonical case: a user comes back next week and the agent still knows who they are, without you re-sending the last six conversations.

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 reply

Two timescales, two mechanisms

This is the distinction that makes the pattern work:

Within one session
Across sessions
Carried by
The message list in the prompt
recall, on the current cue
Why
Pronouns, immediate corrections, the thread of this exchange — all need literal recency
Durable claims about the user, retrieved only when relevant
Size
Bounded window you control — last N turns
Bounded by max_results, regardless of how long they've been a customer

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:

WantUse
"What happened in that conversation?"GET /v1/memories, or a session filter
Clean up one conversation's writesDELETE /v1/sessions/{id}
Group memories for a later auditThe session tag itself
Filtering by session is possible — and usually wrong

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:

OptionTypeDefault / Env
Write itdurable, about the user

Stated 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 exchange

Pleasantries, 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.

On this page

What not to doThe shape that worksTwo timescales, two mechanismsSessions group, they don't isolateWhat to write, and whenTry it
Suggest an editOpen in Playground