How to Integrate Supermemory with Other Tools: SDKs, APIs, and Frameworks

You can integrate Supermemory with any environment that supports HTTP requests using the official TypeScript or Python SDKs, or by calling the REST endpoints directly with standard authentication headers.

Supermemory exposes a unified memory layer through a RESTful HTTP API, enabling you to add persistent context to AI applications built with any framework. The repository provides first-class SDKs that wrap the raw API defined in packages/lib/api.ts, making it straightforward to integrate Supermemory with other tools like Vercel AI SDK, LangChain, and CrewAI.

Understanding the Core API Architecture

All public routes are centralized in packages/lib/api.ts, which uses better-fetch to declare strongly-typed request and response schemas. This file exposes the fundamental memory operations that every integration method uses under the hood.

// packages/lib/api.ts
"@post/documents": {               // ←  [Add memory]
  input: MemoryAddSchema,
  output: MemoryResponseSchema,
},
"@post/search": {                  // ←  [Semantic search]
  input: SearchRequestSchema,
  output: SearchResponseSchema,
},

The base URL defaults to https://api.supermemory.ai/v3 but can be overridden when initializing clients. The exact request contracts are enforced by Zod schemas located in packages/validation/api.ts, ensuring type safety across all integration methods.

Authentication Methods

Supermemory supports two authentication mechanisms: API key authentication for server-to-server communication, and session cookie authentication for browser-based clients.

The authentication logic lives in packages/lib/auth.ts, which implements a better-auth client supporting API keys and magic links:

// packages/lib/auth.ts
export const authClient = createAuthClient({
  baseURL: process.env.NEXT_PUBLIC_BACKEND_URL ?? "https://api.supermemory.ai",
  fetchOptions: { credentials: "include", throw: true },
  plugins: [ usernameClient(), magicLinkClient(), apiKeyClient(), … ],
});

When using the raw API, include the header x-api-key: YOUR_KEY in your requests. When using the SDKs, pass the key during initialization and the client handles header injection automatically.

Data Isolation with Container Tags

Every memory operation supports a containerTag parameter that creates isolated data partitions. This enables multi-tenant architectures where user data remains strictly separated.

await client.add({ content: "...", containerTag: "user_123" });

When querying, passing the same tag to profile or search.memories scopes results to that specific container. This pattern is essential when you integrate Supermemory with other tools that serve multiple users or projects from a single backend.

Integration Approaches

Choose the integration method that matches your technology stack:

  • Official TypeScript SDK – Best for Node.js or frontend applications requiring full TypeScript support and built-in retry logic.
  • Official Python SDK – Ideal for backend services, data science notebooks, and async workflows.
  • Direct HTTP Calls – Use for languages without an SDK or when you need custom low-level control over requests.

All approaches share identical payload shapes defined in the validation schemas, ensuring consistent behavior across implementations.

SDK Implementation Examples

TypeScript SDK Integration

Install the SDK via npm (npm install supermemory), then initialize the client with your API key:

import { Supermemory } from "supermemory";

const client = new Supermemory({
  apiKey: process.env.SUPERMEMORY_API_KEY,   // optional if env var set
  baseURL: "https://api.supermemory.ai",      // defaults to this
});

// Store a memory with metadata
await client.add({
  content: "User prefers dark mode and TypeScript",
  containerTag: "user_123",
  metadata: { source: "preferences", timestamp: new Date().toISOString() },
});

// Retrieve contextual profile
const profile = await client.profile({
  containerTag: "user_123",
  q: "What are the user's recent preferences?",
});

Python SDK Integration

Install with pip (pip install supermemory) for synchronous support, or pip install supermemory[aiohttp] for async:

import os
from supermemory import Supermemory

client = Supermemory(
    api_key=os.getenv("SUPERMEMORY_API_KEY"),
    base_url="https://api.supermemory.ai",
)

# Store a memory

client.add(
    content="User prefers dark mode and Python",
    container_tag="user_456",
    metadata={"source": "preferences", "timestamp": "2024-09-01T12:00:00Z"},
)

# Search with context

profile = client.profile(container_tag="user_456", q="recent settings")
print(profile)

Direct HTTP Integration

For environments without SDK support, call the endpoints directly using standard HTTP clients:


# Add a memory

curl -X POST https://api.supermemory.ai/v3/documents \
  -H "Content-Type: application/json" \
  -H "x-api-key: $SUPERMEMORY_API_KEY" \
  -d '{
        "content": "User likes pizza",
        "containerTag": "user_789",
        "metadata": {"source":"chat"}
      }'

# Semantic search

curl -X POST https://api.supermemory.ai/v3/search \
  -H "Content-Type: application/json" \
  -H "x-api-key: $SUPERMEMORY_API_KEY" \
  -d '{
        "q": "food preferences",
        "containerTag": "user_789",
        "limit": 5,
        "threshold": 0.4
      }'

Framework-Specific Integrations

Vercel AI SDK

When using the Vercel AI SDK, wrap Supermemory calls inside your tool definitions to inject contextual memories before generation:

import { Supermemory } from "supermemory";
import { openai } from "@ai-sdk/openai";
import { generateText } from "ai";

const memory = new Supermemory();

async function chat(userId: string, prompt: string) {
  // Pull contextual memories
  const ctx = await memory.profile({ containerTag: userId, q: prompt });

  const { text } = await generateText({
    model: openai("gpt-4"),
    system: `User profile: ${JSON.stringify(ctx.profile)}\nRelevant memories: ${JSON.stringify(
      ctx.memories ?? {}
    )}`,
    prompt,
  });

  // Store the exchange for future context
  await memory.add({
    content: `User: ${prompt}\nAssistant: ${text}`,
    containerTag: userId,
  });

  return text;
}

LangChain Integration

For LangChain applications, use Supermemory to hydrate the system message with relevant context before invoking the model:

import { Supermemory } from "supermemory";
import { ChatOpenAI } from "@langchain/openai";
import { HumanMessage, SystemMessage } from "@langchain/core/messages";

const memory = new Supermemory();
const llm = new ChatOpenAI({ model: "gpt-4" });

async function chatWithMemory(userId: string, userMsg: string) {
  const ctx = await memory.profile({ containerTag: userId, q: userMsg });

  const msgs = [
    new SystemMessage(`Context: ${JSON.stringify(ctx)}`),
    new HumanMessage(userMsg),
  ];

  const response = await llm.invoke(msgs);

  await memory.add({
    content: `${userMsg}\n${response.content}`,
    containerTag: userId,
  });

  return response.content;
}

CrewAI Integration

In Python-based CrewAI workflows, initialize agents with profiles retrieved from Supermemory:

from supermemory import Supermemory
from crewai import Agent, Task, Crew

memory = Supermemory()

def create_memory_agent(user_id: str):
    ctx = memory.profile(container_tag=user_id, query="user preferences")
    return Agent(
        role="Personal Assistant",
        goal="Help the user with personalized assistance",
        backstory=f"User context: {ctx['profile']}\nRecent memory: {ctx.get('memories')}",
        verbose=True,
    )

assistant = create_memory_agent("user_123")
task = Task(
    description="Suggest a TypeScript project structure for a new app",
    agent=assistant,
)
crew = Crew(agents=[assistant], tasks=[task])
result = crew.kickoff()

Best Practices for Production

When you integrate Supermemory with other tools in production environments, follow these guidelines:

  • Maintain consistent container tags – Use deterministic naming schemes like user_<id> or org_<id>_proj_<id> to ensure proper data isolation between tenants.
  • Leverage rich metadata – Include searchable fields such as source, type, and timestamps to enable advanced filtering and audit trails.
  • Implement idempotent writes – Provide customId when adding memories to prevent duplicates during retries and simplify updates.
  • Tune search thresholds – Start with the default 0.5 threshold for balanced recall; increase to 0.7 or higher when precision is critical.
  • Handle error codes – Watch for 401 (invalid API key) and 429 (rate limiting) when using direct HTTP integration.
  • Cache profile responses – Cache profile() results for short TTLs (seconds) when querying the same user repeatedly to reduce latency.

Summary

  • Integrate Supermemory using the TypeScript SDK, Python SDK, or direct HTTP calls to https://api.supermemory.ai/v3 depending on your stack.
  • Authenticate via the x-api-key header or session cookies as implemented in packages/lib/auth.ts.
  • Use containerTag to isolate data between users or projects, enabling secure multi-tenant architectures.
  • Framework wrappers for Vercel AI SDK, LangChain, and CrewAI follow the same pattern: retrieve context with profile(), generate a response, then store the exchange with add().
  • Reference the Zod schemas in packages/validation/api.ts and route definitions in packages/lib/api.ts for exact payload specifications.

Frequently Asked Questions

What is the default base URL for Supermemory API calls?

The default base URL is https://api.supermemory.ai/v3, as defined in the SDK initialization and packages/lib/api.ts. You can override this by passing a custom baseURL (TypeScript) or base_url (Python) when instantiating the client, which is useful for self-hosted or enterprise deployments.

How do I keep different users' memories separate in Supermemory?

Use the containerTag parameter on every add, search, and profile operation. This arbitrary string acts as a namespace that completely isolates data. For example, using containerTag: "user_123" ensures that queries for "user_456" will never return memories from "user_123".

Can I use Supermemory without the official SDKs?

Yes. The API is fully accessible via standard HTTP requests to endpoints like POST /v3/documents and POST /v3/search. Set the Content-Type: application/json and x-api-key headers as shown in the curl examples, and structure your payloads according to the Zod schemas in packages/validation/api.ts.

Which AI frameworks support direct Supermemory integration?

Supermemory works with any framework that can execute HTTP requests or JavaScript/Python code, including Vercel AI SDK, LangChain (TypeScript and Python), CrewAI, and custom agent frameworks. The integration pattern remains consistent: fetch relevant context using profile(), inject it into the prompt, and persist the interaction using add().

Have a question about this repo?

These articles cover the highlights, but your codebase questions are specific. Give your agent direct access to the source. Share this with your agent to get started:

Share the following with your agent to get started:
curl -s "https://instagit.com/install.md"

Works with
Claude Codex Cursor VS Code OpenClaw Any MCP Client

Maintain an open-source project? Get it listed too →