Skip to content

Memory API

Store and retrieve long-term knowledge with semantic search capabilities.

Overview

The Memory API enables persistent storage of facts, preferences, and knowledge that should be retained across dialogues. Unlike dialogue state (which is temporary and scoped to one conversation), memories are designed for long-term retention and are searchable by meaning.

Key characteristics:

  • Stored indefinitely until explicitly deleted
  • Automatically searchable by meaning
  • Can store strings, numbers, booleans, objects, or arrays
  • Scoped to your project with optional namespace isolation

Create Memory

Store a new piece of information.

Endpoint

http
POST /memory

Authentication

Bearer token (via Authorization header)

Request Body

FieldTypeRequiredDescription
valuestring | number | boolean | object | arrayYesThe memory content to store
idstringNoCustom identifier - auto-generated if not provided
namespacestringNoOptional namespace for isolation (e.g., userId)
labelstringNoHuman-readable label
descriptionstringNoDetailed description of this memory
tagsstring[]NoTags for categorization
metadataobjectNoCustom metadata (can't be changed after creation)

Response

typescript
{
  id: string;              // Unique identifier
  namespace?: string;       // Namespace if provided
  label?: string;
  description?: string;
  value: any;              // The stored value
  tags: string[];
  metadata: Record<string, any>;
  created: string;         // ISO 8601 timestamp
  modified: string;        // ISO 8601 timestamp
}

Behavior

  • Memory id is auto-generated if not provided
  • Custom IDs allow you to use your own identifiers (e.g., user_123_preferences)
  • ID uniqueness: ID is unique per project. Creating with same ID in the same project returns DUPLICATE_ID error (no upsert).
  • Value type is automatically detected and indexed
  • Content is indexed for search
  • Namespace enables multi-tenant isolation

Which Fields Can Be Changed?

Can be set on creation:

  • id (optional, user-defined or auto-generated)
  • namespace (optional)
  • label
  • description
  • value
  • tags
  • metadata

Can be updated:

  • tags - Can be updated via PUT /memory/

Can't be changed after creation:

  • id - Cannot be changed
  • namespace - Cannot be changed
  • value - Cannot be modified after creation
  • description - Cannot be modified after creation
  • label - Cannot be modified after creation
  • metadata - Cannot be modified System-managed (read-only):
  • created
  • modified

Value Type Handling

DialogueDB automatically detects and indexes the value type:

typescript
// String memory
{ value: "User prefers dark mode" }
// → type: "string"

// Number memory
{ value: 42 }
// → type: "number"

// Boolean memory
{ value: true }
// → type: "boolean"

// Object memory
{ value: { theme: "dark", language: "en" } }
// → type: "object"

// Array memory
{ value: ["feature_a", "feature_b"] }
// → type: "array"

Use Cases

  • User preferences: Store settings across sessions
  • Facts and knowledge: Remember information mentioned in conversations
  • Entity relationships: Store structured data about users, products, etc.
  • Feature flags: Per-user or per-namespace configuration
  • Historical context: Long-term information that persists beyond individual conversations

Errors

StatusError CodeDescription
400MISSING_PARAMETERMissing required value field
400INVALID_INPUTInvalid value format or type
400DUPLICATE_IDMemory with this id already exists
401N/AUnauthorized - invalid or missing API key
429RATE_LIMIT_EXCEEDEDToo many requests - retry with backoff
500INTERNAL_ERRORServer error - contact support with requestId

See Error Handling for complete error reference.

Examples

bash
curl -X POST https://api.dialoguedb.com/memory \
  -H "Authorization: Bearer DIALOGUE_DB_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{
    "id": "user_789_theme",
    "value": { "theme": "dark", "fontSize": 16 },
    "label": "UI Preferences",
    "namespace": "user_789",
    "tags": ["preferences", "notifications"]
  }'
typescript
const response = await fetch('https://api.dialoguedb.com/memory', {
  method: 'POST',
  headers: {
    'Authorization': 'Bearer DIALOGUE_DB_API_KEY',
    'Content-Type': 'application/json'
  },
  body: JSON.stringify({
    value: 'User is allergic to peanuts',
    label: 'Dietary Restriction',
    description: 'Critical health information',
    tags: ['health', 'dietary'],
    metadata: {
      severity: 'critical',
      verified: true
    }
  })
});

const memory = await response.json();
console.log('Memory id:', memory.id);
python
import requests


response = requests.post(
    "https://api.dialoguedb.com/memory",
    headers={
        "Authorization": "Bearer DIALOGUE_DB_API_KEY",
        "Content-Type": "application/json"
    },
    json={
        "value": {
            "firstName": "Jane",
            "lastName": "Doe",
            "company": "Acme Corp"
        },
        "label": "User Profile",
        "namespace": "user_456",
        "tags": ["profile", "customer"]
    }
)

memory = response.json()
print("Memory id:", memory["id"])
typescript
import { DialogueDB } from 'dialogue-db';

const db = new DialogueDB({ apiKey: 'DIALOGUE_DB_API_KEY' });

const memory = await db.createMemory({
  value: {
    firstName: 'Jane',
    lastName: 'Doe',
    company: 'Acme Corp'
  },
  label: 'User Profile',
  namespace: 'user_456',
  tags: ['profile', 'customer']
});

Get Memory

Retrieve a memory by its id.

Endpoint

http
GET /memory/{id}

Authentication

Bearer token (via Authorization header)

Path Parameters

ParameterTypeRequiredDescription
idstringYesMemory identifier

Response

typescript
{
  id: string;
  namespace?: string;
  label?: string;
  description?: string;
  value: any;
  tags: string[];
  metadata: Record<string, any>;
  created: string;
  modified: string;
}

Errors

StatusError CodeDescription
400MISSING_PARAMETERMissing required parameter
401N/AUnauthorized - invalid or missing API key
404MEMORY_NOT_FOUNDMemory does not exist
429RATE_LIMIT_EXCEEDEDToo many requests - retry with backoff
500INTERNAL_ERRORServer error - contact support with requestId

Examples

bash
curl -X GET https://api.dialoguedb.com/memory/user_789_theme \
  -H "Authorization: Bearer DIALOGUE_DB_API_KEY"
typescript
const response = await fetch(
  `https://api.dialoguedb.com/memory/${memoryId}`,
  {
    headers: {
      'Authorization': 'Bearer DIALOGUE_DB_API_KEY'
    }
  }
);

const memory = await response.json();
python
import requests


response = requests.get(
    "https://api.dialoguedb.com/memory/user_789_theme",
    headers={
        "Authorization": "Bearer DIALOGUE_DB_API_KEY"
    }
)

memory = response.json()
print(memory["value"])  # { "theme": "dark", "fontSize": 16 }
typescript
import { DialogueDB } from 'dialogue-db';

const db = new DialogueDB({ apiKey: 'DIALOGUE_DB_API_KEY' });

const memory = await db.getMemory('user_789_theme');
console.log(memory.value); // { theme: "dark", fontSize: 16 }

List Memories

Retrieve memories with filtering and pagination.

Endpoint

http
GET /memory

Authentication

Bearer token (via Authorization header)

Query Parameters

ParameterTypeRequiredDescription
namespacestringNoFilter by namespace
limitnumberNoMaximum items per page (default: 50)
orderstringNoSort order: "asc" or "desc" (default: "desc")
nextstringNoPagination token from previous response
createdstringNoFilter by exact creation date (ISO 8601)
startDatestringNoFilter memories created after this date
endDatestringNoFilter memories created before this date

Response

typescript
{
  items: Memory[];
  next?: string;  // Pagination token if more results exist
}

Behavior

  • Results sorted by creation date
  • Automatically scoped to your project
  • Use namespace for multi-tenant filtering
  • Paginated - use next token for additional pages

Errors

StatusError CodeDescription
400INVALID_PARAMETERInvalid filter or pagination parameters
401N/AUnauthorized - invalid or missing API key
429RATE_LIMIT_EXCEEDEDToo many requests - retry with backoff
500INTERNAL_ERRORServer error - contact support with requestId

Examples

bash
curl -X GET "https://api.dialoguedb.com/memory?namespace=user_789&limit=50" \
  -H "Authorization: Bearer DIALOGUE_DB_API_KEY"
typescript
const response = await fetch(
  'https://api.dialoguedb.com/memory?limit=20&order=desc',
  {
    headers: {
      'Authorization': 'Bearer DIALOGUE_DB_API_KEY'
    }
  }
);

const { items, next } = await response.json();

// Paginate if needed
if (next) {
  const nextPage = await fetch(
    `https://api.dialoguedb.com/memory?limit=20&next=${next}`,
    { headers: { 'Authorization': 'Bearer DIALOGUE_DB_API_KEY' } }
  );
}
python
import requests

response = requests.get(
    "https://api.dialoguedb.com/memory",
    headers={
        "Authorization": "Bearer DIALOGUE_DB_API_KEY"
    },
    params={
        "namespace": "user_789",
        "limit": 50
    }
)

data = response.json()
items = data["items"]
next_token = data.get("next")

print(f"Found {len(items)} memories")

# Paginate if needed
if next_token:
    next_response = requests.get(
        "https://api.dialoguedb.com/memory",
        headers={"Authorization": "Bearer DIALOGUE_DB_API_KEY"},
        params={"namespace": "user_789", "limit": 50, "next": next_token}
    )
typescript
import { DialogueDB } from 'dialogue-db';

const db = new DialogueDB({ apiKey: 'DIALOGUE_DB_API_KEY' });

const { items, next } = await db.listMemories({
  namespace: 'user_789',
  limit: 50
});

console.log(`Found ${items.length} memories`);

Update Memory

Update an existing memory's tags.

Endpoint

http
PUT /memory/{id}

Authentication

Bearer token (via Authorization header)

Path Parameters

ParameterTypeRequiredDescription
idstringYesMemory identifier

Request Body

FieldTypeRequiredDescription
tagsstring[]YesUpdated tags (replaces existing)

Response

typescript
{
  id: string;
  namespace?: string;
  label?: string;
  description?: string;
  value: any;
  tags: string[];
  metadata: Record<string, any>;
  created: string;
  modified: string;
}

Behavior

  • Only tags can be updated after creation
  • Tags are replaced entirely (not merged)
  • Value, description, label, id, and metadata can't be changed after creation

Errors

StatusError CodeDescription
400MISSING_PARAMETERMissing required id or tags parameter
400INVALID_INPUTInvalid tags format
401N/AUnauthorized - invalid or missing API key
404MEMORY_NOT_FOUNDMemory does not exist
429RATE_LIMIT_EXCEEDEDToo many requests - retry with backoff
500INTERNAL_ERRORServer error - contact support with requestId

Examples

bash
curl -X PUT https://api.dialoguedb.com/memory/01HX5ZQXQY9J8K7F6E5D4C3B2A \
  -H "Authorization: Bearer DIALOGUE_DB_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{
    "tags": ["preferences", "ui-settings", "active"]
  }'
typescript
const response = await fetch(
  `https://api.dialoguedb.com/memory/${memoryId}`,
  {
    method: 'PUT',
    headers: {
      'Authorization': 'Bearer DIALOGUE_DB_API_KEY',
      'Content-Type': 'application/json'
    },
    body: JSON.stringify({
      tags: ['preferences', 'ui-settings', 'active']
    })
  }
);

const memory = await response.json();
python
import requests

response = requests.put(
    f"https://api.dialoguedb.com/memory/{memory_id}",
    headers={
        "Authorization": "Bearer DIALOGUE_DB_API_KEY",
        "Content-Type": "application/json"
    },
    json={
        "tags": ["preferences", "ui-settings", "active"]
    }
)

memory = response.json()
typescript
import { DialogueDB } from 'dialogue-db';

const db = new DialogueDB({ apiKey: 'DIALOGUE_DB_API_KEY' });

const memory = await db.getMemory(memoryId);
await memory.saveTags(['preferences', 'ui-settings', 'active']);

Delete Memory

Permanently remove a memory.

Endpoint

http
DELETE /memory/{id}

Authentication

Bearer token (via Authorization header)

Path Parameters

ParameterTypeRequiredDescription
idstringYesMemory identifier

Response

typescript
{
  success: boolean;
  id: string;
}

Behavior

  • Permanently deletes the memory
  • Removes from search results
  • This operation cannot be undone

Warnings

  • Irreversible: Deleted memories cannot be recovered
  • Search impact: Memory immediately removed from search results
  • Consider soft deletion: Use metadata flags instead if you need audit trails

Errors

StatusError CodeDescription
400MISSING_PARAMETERMissing required value parameter
401N/AUnauthorized - invalid or missing API key
404MEMORY_NOT_FOUNDMemory does not exist
429RATE_LIMIT_EXCEEDEDToo many requests - retry with backoff
500INTERNAL_ERRORServer error - contact support with requestId

Examples

bash
curl -X DELETE https://api.dialoguedb.com/memory/user_789_theme \
  -H "Authorization: Bearer DIALOGUE_DB_API_KEY"
typescript
const response = await fetch(
  `https://api.dialoguedb.com/memory/${memoryId}`,
  {
    method: 'DELETE',
    headers: {
      'Authorization': 'Bearer DIALOGUE_DB_API_KEY'
    }
  }
);

const result = await response.json();
python
import requests

response = requests.delete(
    "https://api.dialoguedb.com/memory/user_789_theme",
    headers={
        "Authorization": "Bearer DIALOGUE_DB_API_KEY"
    }
)

result = response.json()
typescript
import { DialogueDB } from 'dialogue-db';

const db = new DialogueDB({ apiKey: 'DIALOGUE_DB_API_KEY' });

await db.deleteMemory('user_789_theme');

Search memories using natural language queries. See the Search API documentation for details.

typescript
// Search for memories by meaning
const results = await fetch(
  'https://api.dialoguedb.com/search',
  {
    method: 'POST',
    headers: {
      'Authorization': 'Bearer DIALOGUE_DB_API_KEY',
      'Content-Type': 'application/json'
    },
    body: JSON.stringify({
      query: 'user preferences',
      object: 'memory'
    })
  }
);

Best Practices

Namespace for Multi-Tenancy

Use namespaces to isolate memories by user or organization:

typescript
// Store user-specific memory
await db.createMemory({
  value: 'Prefers morning appointments',
  namespace: 'user_456',
  label: 'Scheduling Preference'
});

// Retrieve only this user's memories
const { items } = await db.listMemories({
  namespace: 'user_456'
});

Custom Keys for Predictable Access

Use custom ids when you need deterministic identifiers:

typescript
// Instead of an auto-generated ID
await db.createMemory({
  id: `user_${userId}_theme`,
  value: { theme: 'dark' }
});

// Easy retrieval without database lookup
const theme = await db.getMemory(`user_${userId}_theme`);

Updating Memory Tags

Memory tags can be updated via the Memory class:

typescript
// Update memory tags
const memory = await db.getMemory(memoryId);
await memory.saveTags(['preferences', 'updated']);

Tagging for Organization

Use tags for categorization and filtering:

typescript
await db.createMemory({
  value: 'Vegetarian diet',
  tags: ['dietary', 'preferences', 'health'],
  label: 'Dietary Restriction'
});

// Search by tags using semantic search
const results = await fetch(
  'https://api.dialoguedb.com/search',
  {
    method: 'POST',
    headers: {
      'Authorization': 'Bearer DIALOGUE_DB_API_KEY',
      'Content-Type': 'application/json'
    },
    body: JSON.stringify({
      query: 'dietary preferences',
      object: 'memory'
    })
  }
);

Metadata for Context

Store permanent context with metadata:

typescript
await db.createMemory({
  value: 'Enterprise account',
  metadata: {
    tier: 'enterprise',
    signupDate: '2025-01-15',
    verified: true
  }
});

Memory vs. State vs. Messages

Understanding when to use each storage type:

FeatureMemoryStateMessages
LifespanIndefinitePer-dialoguePer-dialogue
SearchSearchableNot searchableSearchable
UpdatesTags only (PUT)Full replace (PUT)Tags only (PUT)
Use CaseLong-term factsConversation contextTurn-by-turn dialogue
ScopeGlobal or namespaceDialogue-specificDialogue-specific

Use Memory when:

  • Information should persist across multiple dialogues
  • You need semantic search capabilities
  • Storing facts, preferences, or knowledge

Use State when:

  • Tracking conversation-specific context
  • Need to update frequently
  • Temporary session data

Use Messages when:

  • Recording actual conversation turns
  • Need chronological conversation history
  • Building context for LLM prompts

Built with DialogueDB