Tutorials

Browse docs

Tutorials

Tap to expand
TutorialsUpdated 2026-05-25

Build a User Memory Chatbot

A complete server-side chat loop that retrieves and stores RetainDB user memory.

This tutorial builds the standard production loop for a memory-enabled assistant.

1. Create clients

ts
import OpenAI from "openai";
import { RetainDB } from "@retaindb/sdk";

const openai = new OpenAI({ apiKey: process.env.OPENAI_API_KEY });
const db = new RetainDB({
  apiKey: process.env.RETAINDB_API_KEY,
  project: "production"
});

2. Handle a chat message

ts
export async function answerUser(input: {
  userId: string;
  sessionId: string;
  message: string;
}) {
  const session = db.user(input.userId).session(input.sessionId);

  const { context } = await session.getContext(input.message);

  const completion = await openai.chat.completions.create({
    model: "gpt-4o-mini",
    messages: [
      {
        role: "system",
        content: `Use this memory only when relevant:\n${context}`
      },
      {
        role: "user",
        content: input.message
      }
    ]
  });

  const answer = completion.choices[0]?.message?.content ?? "";

  await session.remember([
    { role: "user", content: input.message },
    { role: "assistant", content: answer }
  ]);

  return { answer };
}

3. Keep the loop small

Do not paste every old conversation into the model. RetainDB retrieves a small relevant memory context, which keeps prompts smaller and more focused.

4. Add user-visible controls

For production apps, expose a way to:

  • show remembered facts
  • delete a memory
  • disable memory for sensitive chats
  • explain that memory is used for personalization

Next: User and session memory.

Was this page helpful?

Your feedback helps us prioritize docs improvements weekly.