Browse docs

SDK

Tap to expand

Contribute

SDKUpdated 2026-03-18

Session Module Guide

Scope memories to a specific conversation using db.user(id).session(id).

Applies to: @retaindb/sdk

A session is a conversation or run scoped under a user. Use db.user(id).session(id) to isolate memories to one thread.


Overview

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

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

const session = db.user("user@example.com").session("chat-123");

Session operations

Store a memory in a session

typescript
await session.remember("User is asking about billing");

Dump a full conversation

typescript
await session.remember([
  { role: "user", content: "My invoice is wrong" },
  { role: "assistant", content: "I can help with that — which invoice?" },
]);

Retrieve context for the session

typescript
const { context } = await session.getContext("What is the current issue?");

Run a full turn

typescript
const { response } = await session.runTurn({
  messages,
  generate: (ctx) => openai.chat.completions.create({
    model: "gpt-4o",
    messages: ctx.messages,
  }),
});

When to use sessions vs user-level memory

Use session scopeUse user scope
Debugging one conversationStoring durable preferences
Tracking what happened in a specific runLong-term facts about a user
Isolating a thread from the restAnything that should survive all sessions

User-level memories persist forever. Session memories are retrievable with the session ID.


Stable session IDs

Use IDs that are meaningful and stable within your app. The session ID is how you retrieve or debug a specific conversation later.

typescript
// Good — tied to your app's conversation model
const sessionId = `chat-${conversationId}`;

// Good — scoped to user + time
const sessionId = `${userId}-${Date.now()}`;

Complete example

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

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

export async function handleMessage(
  userId: string,
  sessionId: string,
  messages: Array<{ role: string; content: string }>
) {
  const { response } = await db.user(userId).session(sessionId).runTurn({
    messages,
    generate: (ctx) =>
      openai.chat.completions.create({
        model: "gpt-4o",
        messages: ctx.messages,
      }),
  });

  return response;
}

Next step

Was this page helpful?

Your feedback helps us prioritize docs improvements weekly.