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
npm install @retaindb/sdkSet your key
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.
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:
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:
const { response } = await db.user(userId).session(sessionId).runTurn({
messages,
generate: (ctx) => llm.chat(ctx),
});Storing individual facts
await db.user(userId).remember("Prefers TypeScript over JavaScript");Removing a memory
await db.user(userId).forget(memoryId);Environment variables
| Variable | Required | Description |
|---|---|---|
RETAINDB_KEY | Yes | Your API key |
RETAINDB_PROJECT | No | Project slug. Defaults to default, auto-created. |
If something fails
- No results after
remember: passinclude_pending: truewhen usinggetContextdirectly — async writes land within seconds but context retrieval includes them immediately. - Wrong memories returned: make sure
userIdis stable. A different string = a different user's memories. - 401/403: confirm
RETAINDB_KEYis set in the environment where your server runs, not the browser.
Next step
- User and Session Scoping — understand
user()andsession()chains - runTurn in depth — what happens inside each turn
- Migration from RetainDBClient — upgrading from the old SDK
Was this page helpful?
Your feedback helps us prioritize docs improvements weekly.