Support bot with memory
A minimal chatbot loop that encodes the user turn, recalls prior context before responding, and encodes the assistant reply back.
The pattern is recall first, then write — and write less than you think:
recall— get the memories that answer the current cue- Build the prompt and call your LLM
encode— store what the turn taught you, if anything
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.
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 replyrecall 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:
A rulecheapestWrite 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 commonAsk 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 reliableA "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.
Was this page helpful?