Brain Docs

Reference

RecipesSupport bot with memorySession summaryIdentity from a session JWTTune salience decayWalk the entity graphManual rate-limit backoff
Brain/Docs
✦ ASKBrain on GitHubDashboard
RecipesSupport bot with memory

Support bot with memory

A minimal chatbot loop that encodes the user turn, recalls prior context before responding, and encodes the assistant reply back.

PURPOSE

A working skeleton of a support-bot loop: encode the user turn, recall prior memories relevant to it, build a system prompt from what came back, call your LLM, then encode the assistant turn so the next turn is informed.

The pattern is recall first, then write — and write less than you think:

  1. recall — get the memories that answer the current cue
  2. Build the prompt and call your LLM
  3. encode — store what the turn taught you, if anything
Recall before you encode, not after

Encoding the user's message and then recalling with that same message as the cue retrieves the sentence you just wrote. You get a confident top hit that is the user's own words echoed back, which tells the model nothing and crowds out the memories that would have. Recall against the space as it stood before this turn.

Do not store the assistant's reply

A model's output is not an observation about the user. Writing it back feeds the next recall its own words, and a wrong answer stored becomes a "fact" the next turn retrieves and repeats. Write what the user told you.

Brain has no server-side "context builder" — recall returns a membership verdict (Single / Many / None) with the supporting memories, and you assemble the prompt from their text. Absence is explicit: on None there is nothing to inject, so you fall back to a plain prompt.

import { BrainHttpClient } from '@brain-db/sdk';
import OpenAI from 'openai';

const brain = new BrainHttpClient({
  apiKey: process.env.BRAIN_API_KEY!,
  baseUrl: process.env.BRAIN_BASE_URL, // defaults to http://127.0.0.1:8080
});

const openai = new OpenAI();

async function handleTurn(userMessage: string): Promise<string> {
  // 1. Recall FIRST, against the space as it stood before this turn.
  const answer = await brain.recall({ query: userMessage, maxResults: 6 });

  const context =
    answer.answerKind === 'none'
      ? ''
      : answer.memories.map((m) => `- ${m.text}`).join('\n');

  // 3. Call the LLM with the recalled memories as the system prompt prefix.
  const completion = await openai.chat.completions.create({
    model: 'gpt-4o-mini',
    messages: [
      {
        role: 'system',
        content: context
          ? `You are a support agent. Relevant memory about this user:\n\n${context}`
          : 'You are a support agent.',
      },
      { role: 'user', content: userMessage },
    ],
  });

  const reply = completion.choices[0]?.message?.content ?? '';

  // 3. Write only what the user told you, and only if it is durable.
  //    `encode` is on the SDK's idempotent-retry list, and the memory is
  //    semantically searchable as soon as it is acked.
  if (isDurable(userMessage)) {
    await brain.encode({ text: userMessage });
  }

  return reply;
}
import os
from openai import OpenAI
from brain_db_sdk import BrainHttpClient

brain = BrainHttpClient(
    os.environ['BRAIN_API_KEY'],
    base_url=os.environ.get('BRAIN_BASE_URL', 'http://127.0.0.1:8080'),
)
openai = OpenAI()


def handle_turn(user_message: str) -> str:
    # 1. Recall FIRST, against the space as it stood before this turn.
    answer = brain.recall(user_message, max_results=6)
    context = (
        ''
        if answer.answer_kind == 'none'
        else '\n'.join(f'- {m.text}' for m in answer.memories)
    )

    # 3. Ask the LLM.
    system = (
        f'You are a support agent. Relevant memory about this user:\n\n{context}'
        if context
        else 'You are a support agent.'
    )
    completion = openai.chat.completions.create(
        model='gpt-4o-mini',
        messages=[
            {'role': 'system', 'content': system},
            {'role': 'user', 'content': user_message},
        ],
    )
    reply = completion.choices[0].message.content or ''

    # 3. Write only what the user told you, and only if it is durable.
    if is_durable(user_message):
        brain.encode(user_message)

    return reply

recall fans out to three retrievers (semantic, lexical, entity-graph) and fuses their ranks behind the scenes — you don't pick a strategy. max_results is a safety ceiling on a Many answer, not a ranking knob: the relevance band decides membership, so lowering it truncates rather than sharpens.

Don't treat a none verdict as an error. It means Brain genuinely has nothing relevant yet — early in a conversation that's expected. Fall back to a plain prompt rather than blocking the turn.

What isDurable should be

The recipe leaves it as a hole on purpose, because it is the decision that determines whether the space stays useful. Three shapes that work, in increasing order of effort:

OptionTypeDefault / Env
A rulecheapest

Write when the message states a preference, a correction, or a fact about the user's setup. Skip pleasantries, questions, and anything whose tense is relative to now.

A second model callmost common

Ask a small model "is there a durable fact about the user here? If so, restate it as one sentence in the third person." Write the restatement, not the raw turn — which also resolves "last month" into a date.

An explicit signalmost reliable

A "remember this" affordance in the product. Low recall, perfect precision, and the user knows what you stored.

Writing every turn is the default that looks like it works and degrades quietly: the space fills with conversation-shaped text that has no clean subject, so extraction cannot type it and recall has to rank around it. See What to write.

Where the three calls go instead

If you do want the assistant's turn on record for audit or replay, that is a transcript, and a transcript belongs in your own store. Brain is for the claims the transcript produced.

See also
Session summaryEnd-of-session aggregation pattern.recall() referenceThe membership verdict and every option.Read pipelineHow recall fuses three retrievers into one answer.

Was this page helpful?

Recipes

Copy-runnable Brain recipes — one concrete problem each, in TypeScript and Python, with the failure modes the happy path leaves out.

Session summary

At session end, recall the salient memories, summarize them with your LLM, and encode the summary back as one durable memory.

On this page

What isDurable should beWhere the three calls go instead
Suggest an editOpen in Playground