Capi

API Reference

Complete technical reference for all CAPI endpoints for integrating intelligent long-term memory into your AI applications.

API Reference

Welcome to the Capi API Reference. Here you'll find comprehensive details on integrating powerful, semantic memory into your AI applications.

Overview

Capi provides a simple set of HTTP endpoints to store, retrieve, and manage personalized memories for your users.

Base URL

All API requests should be made to: https://capi.dev/api/

Authentication

All requests require your unique API key, sent in the X-CAPI-API-Key HTTP header.

X-CAPI-API-Key: your_api_key_here

You can obtain your API key from your Capi Dashboard.

Rate Limiting

API requests are subject to rate limits based on your subscription plan. If you exceed your plan's limits, you will receive a 429 Too Many Requests response.

Please implement retry logic with exponential backoff if you anticipate hitting limits during bursts of activity.

Error Handling

API errors are returned with appropriate HTTP status codes and a JSON body containing details about the error.

CodeTypeDescription
400Bad RequestInvalid request parameters (e.g., missing required fields, invalid format).
401UnauthorizedMissing or invalid X-CAPI-API-Key header.
403ForbiddenInsufficient permissions (e.g., trying to use a Pro-tier feature on a Free plan, or exceeding tier-specific feature limits).
429Too Many RequestsYou have exceeded your plan's rate limits for API operations, active users, or memories stored.
500Server ErrorAn unexpected internal error occurred on our servers. Please report this if it persists.

Error response format:

{
  "error": "A descriptive error message explaining what went wrong.",
  "code": "specific_error_code", // e.g., "validation_error", "rate_limit_exceeded", "unauthorized_tier"
  "details": {
    "field": "specific validation error details for a parameter (optional)",
    "limit_type": "api_calls_monthly",
    "limit_value": 100000,
    "current_usage": 100001
  }
}

POST /addMemory

Stores a piece of information (memory) associated with a specific end-user. This memory is then available for semantic retrieval.

Parameters

ParameterTypeRequiredDescription
userIdstringYour internal unique identifier for the end-user (e.g., user_id_from_your_db).
textstringThe content to store as memory. Max 10,000 characters. Consider strategy for larger texts.
metadataobjectOptional JSON object for additional context. Max 1KB. Useful for filtering and analytics. Example: { "source": "chat", "session_id": "xyz" }.
strategystringProcessing strategy for text (default: "raw"):
- "raw": Stores text as-is.
- "summarize_if_long" (Pro+): Capi will summarize text if it exceeds ~500 tokens before embedding/storing. Ideal for long conversations.
- "extract_facts" (Pro+): Capi uses AI to extract key facts/entities from text and stores only those. Ideal for preferences or key takeaways.

Request Examples

cURL

curl -X POST https://capi.dev/api/v1/addMemory \
  -H "Content-Type: application/json" \
  -H "X-CAPI-API-Key: your-api-key" \
  -d '{
    "userId": "user-123",
    "text": "User prefers Spanish language interface and likes notifications via email.",
    "metadata": {
      "source": "settings_page",
      "timestamp": 1640995200
    },
    "strategy": "extract_facts"
  }'

Node.js (using fetch)

const response = await fetch('https://capi.dev/api/v1/addMemory', {
  method: 'POST',
  headers: {
    'Content-Type': 'application/json',
    'X-CAPI-API-Key': 'your-api-key'
  },
  body: JSON.stringify({
    userId: 'user-123',
    text: 'User prefers Spanish language interface and likes notifications via email. They asked about privacy settings multiple times.',
    metadata: { source: 'onboarding_flow' },
    strategy: 'summarize_if_long'
  })
});

const data = await response.json();
if (response.ok) {
  console.log('Memory stored successfully:', data.memoryId);
  console.log('Processed text stored:', data.processedText);
  console.log('Strategy used:', data.strategyUsed);
} else {
  console.error('Failed to add memory:', data.error, data.code);
}

Python

import requests

response = requests.post(
  'https://capi.dev/api/v1/addMemory',
  headers={
    'Content-Type': 'application/json',
    'X-CAPI-API-Key': 'your-api-key'
  },
  json={
    'userId': 'user-123',
    'text': 'User prefers Spanish language interface and likes notifications via email.',
    'metadata': {'source': 'settings_page'},
    'strategy': 'raw'
  }
)

if response.status_code == 200:
    data = response.json()
    print(f"Memory stored: {data['memoryId']}")
    print(f"Processed text stored: {data['processedText']}")
    print(f"Strategy used: {data['strategyUsed']}")
else:
    print(f"Failed to add memory: {response.json()['error']}")

Response

Success (200 OK)

Returns the ID of the newly stored memory and the final processed text/strategy.

{
  "success": true,
  "memoryId": "mem_abc123",
  "processedText": "User prefers Spanish UI and email notifications.",
  "strategyUsed": "extract_facts"
}

Error (400, 401, 403, 429, 500)

See Error Handling for general error response format.


POST /retrieveContext

Retrieves semantically relevant memories for a given user, based on a new query.

Parameters

ParameterTypeRequiredDescription
userIdstringYour internal user identifier.
querystringThe current context or question for which to search for relevant memories (e.g., "What are their preferences?").
limitnumberMaximum number of semantically relevant memories to return (min: 1, max: 10, default: 3).
metadataFilterobject(Pro+) Optional. Filter memories by specific metadata key-value pairs (e.g., { "source": "settings_page" }). All provided key-value pairs must match.

Request Examples

cURL

curl -X POST https://capi.dev/api/v1/retrieveContext \
  -H "Content-Type: application/json" \
  -H "X-CAPI-API-Key: your-api-key" \
  -d '{
    "userId": "user-123",
    "query": "What language should the UI use for this user?",
    "limit": 3,
    "metadataFilter": {
      "source": "settings_page"
    }
  }'

Node.js

const response = await fetch('https://capi.dev/api/v1/retrieveContext', {
  method: 'POST',
  headers: {
    'Content-Type': 'application/json',
    'X-CAPI-API-Key': 'your-api-key'
  },
  body: JSON.stringify({
    userId: 'user-123',
    query: 'What language should the UI use?',
    limit: 3
  })
});

const data = await response.json();
if (response.ok) {
  console.log(`Found ${data.count} relevant memories:`);
  data.memories.forEach(memory => {
    console.log(`  - "${memory.text}" (Score: ${memory.score.toFixed(2)}, From: ${memory.metadata?.source || 'N/A'})`);
  });
} else {
  console.error('Failed to retrieve context:', data.error, data.code);
}

Response

Success (200 OK)

Returns an array of memories sorted by relevance score (highest first).

{
  "memories": [
    {
      "memoryId": "mem_abc123",
      "text": "User prefers Spanish language interface",
      "metadata": {
        "source": "settings_page"
      },
      "score": 0.92, // Semantic similarity score (0.0 - 1.0)
      "createdAt": 1640995200 // Timestamp when memory was added
    }
  ],
  "query": "What language should the UI use for this user?", // The query that was processed
  "count": 1 // Number of memories returned
}

Error (400, 401, 403, 429, 500)

See Error Handling for general error response format. 404 Not Found is not typically returned; instead, count will be 0 if no memories are found.


POST /forgetMemory

Removes or archives specific memories from a user's profile. This is crucial for data privacy and managing storage costs.

Parameters

You must provide userId and one of: memoryId, olderThanDays, or metadataFilter.

ParameterTypeRequiredDescription
userIdstringThe unique identifier of the end-user whose memories are being managed.
memoryIdstringThe specific ID of the memory to remove. Find this from addMemory response or Memory Browser.
olderThanDaysnumber(Pro+) Remove all non-archived memories for userId that were created more than X days ago.
metadataFilterobject(Pro+) Remove all non-archived memories for userId that match ALL provided metadata key-value pairs (e.g., { "source": "temp_session" }).

Request Examples

cURL (Single Memory)

curl -X POST https://capi.dev/api/v1/forgetMemory \
  -H "Content-Type: application/json" \
  -H "X-CAPI-API-Key: your-api-key" \
  -d '{
    "userId": "user-123",
    "memoryId": "mem_abc123"
  }'

Python (Bulk by Age)

import requests

response = requests.post(
  'https://capi.dev/api/v1/forgetMemory',
  headers={
    'Content-Type': 'application/json',
    'X-CAPI-API-Key': 'your-api-key'
  },
  json={
    'userId': 'user-123',
    'olderThanDays': 30
  }
)

if response.status_code == 200:
    data = response.json()
    print(f"{data['count']} memories removed: {data['message']}")
else:
    print(f"Failed to remove memories: {response.json()['error']}")

Node.js (Bulk by Metadata)

const response = await fetch('https://capi.dev/api/v1/forgetMemory', {
  method: 'POST',
  headers: {
    'Content-Type': 'application/json',
    'X-CAPI-API-Key': 'your-api-key'
  },
  body: JSON.stringify({
    userId: 'user-456',
    metadataFilter: { source: 'temp_session_data' }
  })
});

const data = await response.json();
if (response.ok && data.success) {
  console.log(`Successfully removed ${data.count} memories: ${data.message}`);
} else {
  console.error('Failed to remove memories:', data.error, data.code);
}

Response

Success (200 OK)

{
  "success": true,
  "count": 5, // Number of memories affected
  "message": "5 memories successfully archived." // A human-readable message
}

Error (400, 401, 403, 429, 500)

See Error Handling for general error response format. Specific validation errors will guide on missing parameters.


Best Practices

  1. Choosing Your Ingestion Strategy: Select raw for precise control over short, critical facts. Use summarize_if_long or extract_facts (Pro+ tiers) for verbose inputs like chat logs or document chunks to optimize storage and retrieval.
  2. Efficient Context Retrieval: Use the limit parameter to fetch only the necessary number of memories for your LLM's context window. Consider metadataFilter (Pro+ tiers) to narrow search results when you know the source or type of memory you need.
  3. Regular Memory Management: Implement automated processes using forgetMemory (e.g., daily purges of old session data, or archiving memories tied to resolved support tickets) to keep your memory clean and within plan limits.
  4. Robust Error Handling: Always wrap your API calls in try...catch blocks. Implement retry logic for 429 Too Many Requests errors using exponential backoff.
  5. Secure API Key Usage: Never expose your X-CAPI-API-Key in client-side code (e.g., frontend JavaScript). Always route API calls through a secure backend (e.g., Next.js API Routes, serverless functions).