mem0

Mem0 Platform SDK for adding persistent memory to AI applications. TRIGGER when: user mentions "mem0", "MemoryClient", "memory layer", "remember user preferences", "persistent context", "personalization", or needs to add long-term memory to chatbots, agents, or AI apps. Covers Python SDK (mem0ai), TypeScript SDK (mem0ai), and framework integrations (LangChain, CrewAI, OpenAI Agents SDK, Pipecat, LlamaIndex, AutoGen, LangGraph). Also covers the open-source self-hosted Memory class. This is the DEFAULT mem0 skill for ambiguous queries. DO NOT TRIGGER when: user asks about CLI commands, terminal usage, or shell scripts (use mem0-cli), or Vercel AI SDK / @mem0/vercel-ai-provider / createMem0 (use mem0-vercel-ai-sdk).

Install
npx skills add 'https://github.com/mem0ai/mem0/tree/main/skills/mem0'
Download bundle ↓
main · 0df3e4bScanned 2026-09-17

Contributors

GitHub-linked commit authors for this SKILL.md at the saved revision. Co-authors and history before file renames are not included.

File history ↗
View on GitHub
← Back to SKILL.md

Mem0 Node.js / TypeScript SDK Reference

Complete reference for the mem0ai npm package. Covers both the Platform client (managed API) and the Open Source self-hosted variant.


Platform Client

Installation

npm install mem0ai
export MEM0_API_KEY="m0-your-api-key"

MemoryClient

import MemoryClient from 'mem0ai';

const client = new MemoryClient({ apiKey: 'm0-xxx' });

Constructor: new MemoryClient({ apiKey }). If apiKey is not provided, reads from MEM0_API_KEY environment variable.

  • HTTP library: axios
  • Timeout: 60 seconds
  • Base URL: https://api.mem0.ai
  • All methods are async (return Promise)

Memory Methods

add(messages, options?)

Store new memories from messages.

const messages = [
    { role: 'user', content: "I'm a vegetarian and allergic to nuts." },
    { role: 'assistant', content: "Got it! I'll remember that." },
];
await client.add(messages, { userId: 'alice' });
ParameterTypeDescription
messagesMessage[]Array of {role, content} objects
options.userIdstringUser identifier
options.agentIdstringAgent identifier
options.appIdstringApplication identifier
options.runIdstringSession identifier
options.metadataobjectCustom key-value pairs
options.inferbooleanIf false, store raw text (default: true)

Returns: Promise<any> -- list of events

search(query, options?)

Search memories by semantic similarity.

const results = await client.search('dietary preferences', { filters: { user_id: 'alice' }, topK: 20 });
for (const mem of results.results) {
    console.log(mem.memory, mem.score);
}
ParameterTypeDescription
querystringNatural language search query
options.filtersobjectFilter object with entity IDs (user_id, agent_id, etc.) and/or AND/OR/NOT conditions
options.topKnumberNumber of results (default: 20)
options.rerankbooleanEnable semantic reranking (default: false)
options.thresholdnumberMinimum similarity (default: 0.1)

Returns: Promise<SearchResult> -- {results: [{id, memory, score, ...}]}

get(memoryId)

const memory = await client.get('ea925981-...');

getAll(options?)

Retrieve all memories. Requires at least one entity identifier in filters.

const memories = await client.getAll({ filters: { user_id: 'alice' } });
// With filters
const filtered = await client.getAll({
    filters: { AND: [{ user_id: 'alice' }, { categories: { contains: 'health' } }] },
});
ParameterTypeDescription
options.filtersobjectFilter object with entity IDs (user_id, agent_id, etc.) and/or AND/OR/NOT conditions
options.pagenumberPage number
options.pageSizenumberResults per page

update(memoryId, data)

await client.update('ea925981-...', { text: 'Updated: vegan since 2024' });
await client.update('ea925981-...', { text: 'Updated', metadata: { verified: true } });
ParameterTypeDescription
memoryIdstringMemory ID
data.textstringNew content
data.metadataobjectNew metadata
data.timestampstringNew timestamp

delete(memoryId)

await client.delete('ea925981-...');

deleteAll(options?)

await client.deleteAll({ userId: 'alice' });

history(memoryId)

const history = await client.history('ea925981-...');
// Returns: [{previousValue, newValue, action, timestamps}]

Batch Methods

batchUpdate(memories)

await client.batchUpdate([
    { memoryId: 'uuid-1', text: 'Updated text' },
    { memoryId: 'uuid-2', text: 'Another update' },
]);

batchDelete(memories)

await client.batchDelete(['uuid-1', 'uuid-2', 'uuid-3']);

User/Entity Management

users()

const users = await client.users();
// Returns: {results: [{type: "user", name: "alice"}, ...]}

deleteUser(data) / deleteUsers(data)

await client.deleteUser({ userId: 'alice' });  // Single entity
await client.deleteUsers({ agentId: 'bot-1' }); // Flexible

Project Management

// Get project config
const config = await client.getProject({ fields: ['customCategories'] });

// Update project settings
await client.updateProject({
    customInstructions: 'Extract dietary preferences and health info',
    customCategories: [{ health: 'Medical and dietary info' }],
});

Webhooks

// List
const webhooks = await client.getWebhooks({ projectId: 'proj_123' });

// Create
const webhook = await client.createWebhook({
    url: 'https://your-app.com/webhook',
    name: 'Memory Logger',
    projectId: 'proj_123',
    eventTypes: ['memory_add', 'memory_update'],
});

// Update
await client.updateWebhook({
    webhookId: 'wh_123',
    name: 'Updated Logger',
    url: 'https://new-url.com',
});

// Delete
await client.deleteWebhook({ webhookId: 'wh_123' });

Feedback

await client.feedback({
    memoryId: 'mem-123',
    feedback: 'POSITIVE',
    feedbackReason: 'Accurately captured preference',
});

Export

const exportReq = await client.createMemoryExport({
    schema: JSON.stringify({ type: 'object', properties: { name: { type: 'string' } } }),
    filters: { user_id: 'alice' },
});

const result = await client.getMemoryExport({ memoryExportId: exportReq.id });

TypeScript Types

Key interfaces from mem0.types.ts:

interface Message { role: string; content: string; }
interface Memory { id: string; memory: string; userId: string; categories: string[]; score?: number; /* ... */ }
interface MemoryOptions { userId?: string; agentId?: string; appId?: string; runId?: string; metadata?: object; /* ... */ }
interface SearchOptions { filters?: object; topK?: number; rerank?: boolean; threshold?: number; /* ... */ }
interface MemoryHistory { id: string; memoryId: string; previousValue: string; newValue: string; action: string; /* ... */ }
interface FeedbackPayload { memoryId: string; feedback: string; feedbackReason?: string; }
interface WebhookCreatePayload { url: string; name: string; projectId: string; eventTypes: string[]; }

Open Source / Self-Hosted

Installation

npm install mem0ai

Memory Class

import { Memory } from 'mem0ai/oss';

const m = new Memory();  // Uses default config

Import: from 'mem0ai/oss' (NOT the default export -- that is MemoryClient for Platform)

Configuration

const config = {
    llm: {
        provider: 'openai',        // openai, groq, anthropic, google, ollama, lmstudio, mistral, azure
        config: {
            model: 'gpt-5-mini',
            apiKey: 'sk-xxx',
        },
    },
    embedder: {
        provider: 'openai',        // openai, ollama, lmstudio, google, azure, langchain, anthropic
        config: {
            model: 'text-embedding-3-small',
            apiKey: 'sk-xxx',
        },
    },
    vectorStore: {
        provider: 'qdrant',        // memory, qdrant, redis, supabase, langchain, azure_ai_search, pgvector
        config: {
            collectionName: 'my_memories',
            host: 'localhost',
            port: 6333,
        },
    },
    historyDbPath: 'history.db',
    customInstructions: '...',
    disableHistory: false,
};

const m = new Memory(config);
// Or from dict with validation:
const m2 = Memory.fromConfig(config);

Methods

All methods are async (return Promise):

add(messages, config)

await m.add('I prefer dark mode', { userId: 'alice' });
await m.add([
    { role: 'user', content: 'I like hiking' },
    { role: 'assistant', content: 'Great outdoor activity!' },
], { userId: 'alice' });
ParameterTypeDescription
messagesstring | Message[]Content to store
config.userIdstringUser identifier (at least one scope required)
config.agentIdstringAgent identifier
config.runIdstringSession identifier
config.metadataobjectCustom key-value pairs
config.filtersobjectAdditional filters
config.inferbooleanLLM inference (default: true)

Returns: Promise<{results: [...], relations?: [...]}>

search(query, config)

const results = await m.search('dietary preferences', { filters: { user_id: 'alice' }, topK: 5 });
ParameterTypeDescription
querystringSearch query
config.filtersobjectFilter object with entity IDs (user_id, agent_id, run_id, etc.)
config.topKnumberMax results (default: 20)

get(memoryId) / getAll(config) / update(memoryId, data) / delete(memoryId) / deleteAll(config) / history(memoryId)

Same interface patterns. Note: OSS update takes a string for data, not an object.

await m.update('mem-id', 'new content');

reset()

Clear the entire vector store and history.

await m.reset();

Key Differences: Platform vs OSS

AspectPlatform (MemoryClient)OSS (Memory)
Importimport MemoryClient from 'mem0ai'import { Memory } from 'mem0ai/oss'
AuthAPI key required (MEM0_API_KEY)No API key -- config-based
ExecutionAPI calls to api.mem0.aiLocal execution
InfrastructureFully managedSelf-managed vector DB, embedder, LLM
Param styleTop-level: camelCase (userId, topK), filter keys: snake_case (user_id)Top-level: camelCase (userId, topK), filter keys: snake_case (user_id)
Batch opsbatchUpdate, batchDeleteNot available
WebhooksFull CRUDNot available
ExportcreateMemoryExportNot available
Feedbackfeedback()Not available
Project mgmtgetProject, updateProjectNot available
User listingusers(), deleteUser()Not available
HistoryPlatform-managedSQLite (configurable)

v2 Compatibility

If you're using SDK v2.x:

Naming Changes:

  • Top-level params now use camelCase: topK, rerank (not top_k)
  • Filter keys use snake_case: user_id, agent_id
  • OSS: limit renamed to topK

API Changes:

// v2 - top-level entity IDs, snake_case
await client.search("query", { user_id: "alice", top_k: 20 });

// v3 - filters object with snake_case keys, camelCase top-level params
await client.search("query", { filters: { user_id: "alice" }, topK: 20 });

Default Changes:

Paramv2v3
topK10020
thresholdnone0.1
reranktruefalse

Removed:

  • OutputFormat and API_VERSION enums
  • organizationId, projectId from constructor
  • enableGraph, asyncMode, outputFormat, immutable, expirationDate, filterMemories, batchSize, forceAddOnly, includes, excludes, keywordSearch

See the v2 to v3 migration guide for details.

Referenced from SKILL.md