Browse docs

SDK

Tap to expand

Contribute

SDKUpdated 2026-03-18

SDK Quickstart

Add persistent memory to your AI app in minutes with the RetainDB SDK.

Applies to: @retaindb/sdk

Install, set your key, and your LLM has memory.

Install

bash
npm install @retaindb/sdk

Set your key

bash
export RETAINDB_KEY="rdb_..."

That's it. No project setup required — a default project is created automatically on first use.


Automatic mode

runTurn handles everything: retrieve context → inject into LLM → store the conversation.

typescript
import { RetainDB } from "@retaindb/sdk";

const db = new RetainDB({ apiKey: process.env.RETAINDB_KEY });

// Every message goes through here
const { response } = await db.user(userId).runTurn({
  messages,
  generate: (ctx) => openai.chat.completions.create({
    model: "gpt-4o",
    messages: ctx.messages, // context already injected
  }),
});

ctx.messages is your messages array with user memory prepended as a system message. The conversation is stored after every turn without any extra code.


Manual mode

When you want explicit control:

typescript
const user = db.user(userId);

// 1. Get context for the current query
const { context } = await user.getContext("How should I respond to this user?");

// 2. Call your LLM with it
const reply = await openai.chat.completions.create({
  model: "gpt-4o",
  messages: [
    { role: "system", content: context },
    ...messages,
  ],
});

// 3. Store what happened
await user.remember(messages);

Session scoping

Use session() when you want memories scoped to a specific conversation:

typescript
const { response } = await db.user(userId).session(sessionId).runTurn({
  messages,
  generate: (ctx) => llm.chat(ctx),
});

Storing individual facts

typescript
await db.user(userId).remember("Prefers TypeScript over JavaScript");

Removing a memory

typescript
await db.user(userId).forget(memoryId);

Environment variables

VariableRequiredDescription
RETAINDB_KEYYesYour API key
RETAINDB_PROJECTNoProject slug. Defaults to default, auto-created.

If something fails

  • No results after remember: pass include_pending: true when using getContext directly — async writes land within seconds but context retrieval includes them immediately.
  • Wrong memories returned: make sure userId is stable. A different string = a different user's memories.
  • 401/403: confirm RETAINDB_KEY is set in the environment where your server runs, not the browser.

Next step

Was this page helpful?

Your feedback helps us prioritize docs improvements weekly.