Compare commits

..
Author SHA1 Message Date
mintlify[bot] 2a87b506e8 Fix broken link to removed expiration-date page
Generated-By: mintlify-agent
2026-04-17 00:08:29 +00:00
37 changed files with 916 additions and 1107 deletions
-45
View File
@@ -1,45 +0,0 @@
name: docs - llms.txt check
# Blocks PRs that introduce new .mdx pages without a matching entry in
# docs/llms.txt, or that link to pages that no longer exist. Contributors
# must update docs/llms.txt in the same PR. Run locally with:
# python scripts/check-llms-txt-coverage.py # read-only
# python scripts/check-llms-txt-coverage.py --write # scaffold placeholders
on:
pull_request:
paths:
- 'docs/**/*.mdx'
- 'docs/llms.txt'
- 'scripts/check-llms-txt-coverage.py'
- 'scripts/llms-txt-ignore.txt'
workflow_dispatch: {}
permissions:
contents: read
jobs:
check-llms-txt:
runs-on: ubuntu-24.04-arm
timeout-minutes: 2
steps:
- uses: actions/checkout@v4
- name: Verify docs/llms.txt coverage
run: |
if ! python3 scripts/check-llms-txt-coverage.py; then
echo ""
echo "::error title=llms.txt out of sync::docs/llms.txt does not match docs/**/*.mdx."
echo ""
echo "To fix:"
echo " 1. Run locally: python scripts/check-llms-txt-coverage.py --write"
echo " This appends placeholder entries under '## Unclassified - needs triage'."
echo " 2. For each placeholder:"
echo " - replace [TODO: Platform|OSS|Both] with the correct scope tag"
echo " - rewrite the description as 'Use when ...'"
echo " - move the entry into the appropriate section"
echo " - delete the '## Unclassified - needs triage' heading once empty"
echo " 3. Resolve any stale URLs listed above by updating or removing the link."
echo " 4. Commit the updated docs/llms.txt to this PR."
exit 1
fi
-3
View File
@@ -35,7 +35,6 @@ This is a **polyglot monorepo** containing Python and TypeScript packages, CLIs,
| `cookbooks/` | Jupyter notebooks — customer support chatbot, AutoGen integration | | `cookbooks/` | Jupyter notebooks — customer support chatbot, AutoGen integration |
| `embedchain/` | Legacy Embedchain RAG framework (maintained separately, Poetry-based) | | `embedchain/` | Legacy Embedchain RAG framework (maintained separately, Poetry-based) |
| `pr-reviews/` | Pull request review materials | | `pr-reviews/` | Pull request review materials |
| `scripts/` | Repo-wide utility scripts (e.g., `check-llms-txt-coverage.py` for docs/llms.txt sync) |
### Core Package Dependencies ### Core Package Dependencies
@@ -434,7 +433,6 @@ To add a new LLM, embedding, vector store, or reranker provider:
|----------|------|---------| |----------|------|---------|
| Issue Labeler | `issue-labeler.yml` | Automatic issue labeling | | Issue Labeler | `issue-labeler.yml` | Automatic issue labeling |
| Stale Bot | `stale.yml` | Marks stale issues and PRs | | Stale Bot | `stale.yml` | Marks stale issues and PRs |
| llms.txt Check | `docs-llms-txt-check.yml` | Blocks PRs touching `docs/**/*.mdx` when `docs/llms.txt` is out of sync. Fix locally with `python scripts/check-llms-txt-coverage.py --write`. |
## Task Completion Guidelines ## Task Completion Guidelines
@@ -453,7 +451,6 @@ These guidelines outline typical artifacts for different task types. Use judgmen
2. **Unit tests**: Comprehensive test coverage for new functionality 2. **Unit tests**: Comprehensive test coverage for new functionality
3. **Documentation**: Update relevant docs in `docs/` for public APIs 3. **Documentation**: Update relevant docs in `docs/` for public APIs
4. **Examples**: Add usage examples if the feature introduces new user-facing behavior 4. **Examples**: Add usage examples if the feature introduces new user-facing behavior
5. **llms.txt**: Any new `.mdx` page under `docs/` must be linked in `docs/llms.txt` with a scope tag (`[Platform]` / `[OSS]` / `[Both]`) and a `Use when ...` description. The `docs-llms-txt-check.yml` workflow runs on every PR that touches docs and **fails the check** if the index is out of sync. To fix: run `python scripts/check-llms-txt-coverage.py --write` locally to scaffold placeholders under `## Unclassified - needs triage`, then replace the `[TODO: ...]` tags, rewrite descriptions as `Use when ...`, move entries into the right section, and delete the triage heading when empty.
### New Provider (LLM / Embedding / Vector Store / Reranker) ### New Provider (LLM / Embedding / Vector Store / Reranker)
+3
View File
@@ -0,0 +1,3 @@
<Note type="info">
<strong>🎉 Mem0 1.0.0 is here!</strong> Enhanced filtering, reranking, and smarter memory management.
</Note>
@@ -216,7 +216,7 @@ memory.delete_all(user_id="alice")
## Put it into practice ## Put it into practice
- Review the <Link href="/api-reference/memory/delete-memory">Delete Memory API reference</Link>, plus <Link href="/api-reference/memory/batch-delete">Batch Delete</Link> and <Link href="/api-reference/memory/delete-memories">Filtered Delete</Link>. - Review the <Link href="/api-reference/memory/delete-memory">Delete Memory API reference</Link>, plus <Link href="/api-reference/memory/batch-delete">Batch Delete</Link> and <Link href="/api-reference/memory/delete-memories">Filtered Delete</Link>.
- Pair deletes with <Link href="/platform/features/expiration-date">Expiration Policies</Link> to automate retention. - Pair deletes with <Link href="/platform/features/entity-scoped-memory">Entity-Scoped Memory</Link> to manage retention per user, agent, or session.
## See it live ## See it live
@@ -233,9 +233,9 @@ memory.delete_all(user_id="alice")
href="/core-concepts/memory-operations/add" href="/core-concepts/memory-operations/add"
/> />
<Card <Card
title="Enable Expiration Policies" title="Scope memories by entity"
description="Automate retention with the platform’s expiration feature." description="Manage retention per user, agent, or session with entity-scoped memory."
icon="clock" icon="clock"
href="/platform/features/expiration-date" href="/platform/features/entity-scoped-memory"
/> />
</CardGroup> </CardGroup>
+248 -420
View File
@@ -1,474 +1,302 @@
# Mem0 # Mem0
> Mem0 is a memory layer for LLM agents - persistent, self-improving context that survives across sessions. Two products share one mental model: Mem0 Platform (managed) and Mem0 Open Source (self-hosted). Every link below is tagged `[Platform]`, `[OSS]`, or `[Both]` so you can load only what the current user needs. > Mem0 is a self-improving memory layer for LLM applications, enabling personalized AI experiences that retain context across sessions, adapt over time, and reduce costs by intelligently storing and retrieving relevant information.
## For agents reading this file Mem0 provides both a managed platform and open-source solutions for adding persistent memory to AI agents and applications. Unlike traditional RAG systems that are stateless, Mem0 creates stateful agents that remember user preferences, learn from interactions, and evolve behavior over time.
- Use `MemoryClient` (Python) / `mem0ai` (npm) when the user has a Mem0 Platform API key. Docs under `/platform/` and `/api-reference/` apply; the managed product handles providers server-side, so you can ignore `## Optional` below. Key differentiators:
- Use `Memory` (Python) / `mem0ai/oss` (npm) when the user self-hosts. Docs under `/open-source/` and `/components/` apply; Platform-only features (entity filters v2, custom categories, webhooks, advanced retrieval) may not be available. - **Stateful vs Stateless**: Retains context across sessions rather than forgetting after each interaction
- Scope tag reference: `[Platform]` = managed only, `[OSS]` = self-hosted only, `[Both]` = same API surface on both. - **Intelligent Memory Management**: Uses LLMs to extract, filter, and organize relevant information
- OpenAPI spec: https://docs.mem0.ai/openapi.json - **Dual Storage Architecture**: Combines vector embeddings with graph databases for comprehensive memory
- Live MCP server: https://mcp.mem0.ai (see `platform/mem0-mcp`). - **Sub-50ms Retrieval**: Lightning-fast memory lookups for real-time applications
- Source repo: https://github.com/mem0ai/mem0 - **Multimodal Support**: Handles text, images, and documents seamlessly
## Install
- Python SDK: `pip install mem0ai`
- Node SDK: `npm install mem0ai`
- Python CLI: `pip install mem0-cli`
- Node CLI: `npm install -g @mem0/cli`
## Identify the User's Setup
Look at the user's imports first - they determine which product (Platform vs OSS) and which language you should quote docs from. **Mem0 Platform (managed) is the recommended path** - 4-line integration, sub-50ms retrieval, no infra. Route to OSS only when the user has an explicit self-hosting requirement.
### Platform - Python [Platform]
Import signature: `from mem0 import MemoryClient`
```python
from mem0 import MemoryClient
client = MemoryClient(api_key="your-api-key")
# Create
client.add(
[{"role": "user", "content": "I love hiking on weekends"}],
user_id="alice",
)
# Read
client.search("What does Alice like to do?", user_id="alice")
client.get_all(user_id="alice")
client.get(memory_id="<id>")
# Update
client.update(memory_id="<id>", data="Alice loves mountain hiking")
# Delete
client.delete(memory_id="<id>")
client.delete_all(user_id="alice")
```
Relevant docs: `platform/quickstart`, `platform/features/*`, `api-reference/*`.
### Platform - TypeScript / JavaScript [Platform]
Import signature: `import MemoryClient from "mem0ai"`
```ts
import MemoryClient from "mem0ai";
const client = new MemoryClient({ apiKey: "your-api-key" });
// Create
await client.add(
[{ role: "user", content: "I love hiking on weekends" }],
{ user_id: "alice" },
);
// Read
await client.search("What does Alice like to do?", { user_id: "alice" });
await client.getAll({ user_id: "alice" });
await client.get("<memory_id>");
// Update
await client.update("<memory_id>", { text: "Alice loves mountain hiking" });
// Delete
await client.delete("<memory_id>");
await client.deleteAll({ user_id: "alice" });
```
Relevant docs: same as Platform Python.
### OSS - Python [OSS]
Import signature: `from mem0 import Memory`
```python
from mem0 import Memory
m = Memory() # needs OPENAI_API_KEY; see components/ for custom providers
# Create
m.add("I love hiking on weekends", user_id="alice")
# Read
m.search("What does Alice like to do?", user_id="alice")
m.get_all(user_id="alice")
m.get(memory_id="<id>")
# Update
m.update(memory_id="<id>", data="Alice loves mountain hiking")
# Delete
m.delete(memory_id="<id>")
m.delete_all(user_id="alice")
```
Relevant docs: `open-source/*` plus provider pages under `## Optional`.
### OSS - Node [OSS]
Import signature: `import { Memory } from "mem0ai/oss"`
```ts
import { Memory } from "mem0ai/oss";
const memory = new Memory();
// Create
await memory.add("I love hiking on weekends", { userId: "alice" });
// Read
await memory.search("What does Alice like to do?", { userId: "alice" });
await memory.getAll({ userId: "alice" });
await memory.get("<memory_id>");
// Update
await memory.update("<memory_id>", "Alice loves mountain hiking");
// Delete
await memory.delete("<memory_id>");
await memory.deleteAll({ userId: "alice" });
```
Relevant docs: same as OSS Python.
### Version Probes
Once you know which product, check the installed version - v2 vs v3 APIs differ in both OSS and Platform. Current published versions: Python `mem0ai` 2.x, TypeScript `mem0ai` 3.x, Node CLI `@mem0/cli` 0.2.x.
```bash
pip show mem0ai | grep -i ^version
npm list mem0ai --depth 0 2>/dev/null | grep mem0ai
mem0 --version # Python or Node CLI, whichever is on PATH
```
If the user is on a pre-current major (Python < 2, TS < 3, or Platform `output_format: "v1.1"`), route them through the matching migration guide in the Platform section before quoting current docs. If no Mem0 package is installed, recommend `pip install mem0ai` or `npm install mem0ai` and the corresponding quickstart above.
## Getting Started ## Getting Started
- [Introduction](https://docs.mem0.ai/introduction) [Both]: Use when the user wants a one-page overview of how memory fits between the LLM and the app. - [Introduction](https://docs.mem0.ai/introduction): Overview of Mem0's memory layer for AI agents, including stateless vs stateful agents and how memory fits in the agent stack
- [Vibe Code with Mem0](https://docs.mem0.ai/vibecoding) [Both]: Use when the user is in Claude Code, Cursor, or Windsurf and wants memory wired into their editor. - [Platform Overview](https://docs.mem0.ai/platform/overview): Managed solution with 4-line integration, sub-50ms latency, and intuitive dashboard
- [Platform Overview](https://docs.mem0.ai/platform/overview) [Platform]: Use when the user picks the managed product - 4-line integration, sub-50ms retrieval, dashboard. - [Vibe Code with Mem0](https://docs.mem0.ai/vibecoding): Single entry point for developers using AI coding tools (Claude Code, Cursor, Windsurf) with Mem0
- [Platform vs Open Source](https://docs.mem0.ai/platform/platform-vs-oss) [Both]: Use when the user is deciding between managed and self-hosted. - [Mem0 MCP Server](https://docs.mem0.ai/platform/mem0-mcp): Model Context Protocol server for integrating Mem0 with AI coding assistants
- [Platform Quickstart](https://docs.mem0.ai/platform/quickstart) [Platform]: Use for the first Platform integration - API key plus `MemoryClient.add/search`. - [Platform vs Open Source](https://docs.mem0.ai/platform/platform-vs-oss): Compare managed platform vs self-hosted options
- [Platform CLI](https://docs.mem0.ai/platform/cli) [Platform]: Use when the user wants to manage Platform memories from the terminal. - [Platform Quickstart](https://docs.mem0.ai/platform/quickstart): Get started with Mem0 Platform (managed) in minutes
- [Mem0 MCP Server](https://docs.mem0.ai/platform/mem0-mcp) [Platform]: Use when connecting memory to AI coding tools over MCP. - [Open Source Overview](https://docs.mem0.ai/open-source/overview): Self-hosted solution with full infrastructure control and customization
- [Open Source Overview](https://docs.mem0.ai/open-source/overview) [OSS]: Use when the user needs full infra control and custom provider wiring. - [Open Source Python Quickstart](https://docs.mem0.ai/open-source/python-quickstart): Get started with Mem0 Open Source using Python
- [Open Source Configuration](https://docs.mem0.ai/open-source/configuration) [OSS]: Use when configuring `Memory` - LLM, embedder, vector store, graph store. - [Open Source Node.js Quickstart](https://docs.mem0.ai/open-source/node-quickstart): Get started with Mem0 Open Source using Node.js
- [Open Source Python Quickstart](https://docs.mem0.ai/open-source/python-quickstart) [OSS]: Use for the first self-hosted Python integration.
- [Open Source Node.js Quickstart](https://docs.mem0.ai/open-source/node-quickstart) [OSS]: Use for the first self-hosted Node integration.
## Core Concepts ## Core Concepts
- [Memory Types](https://docs.mem0.ai/core-concepts/memory-types) [Both]: Use when explaining working, factual, episodic, and semantic memory distinctions. - [Memory Types](https://docs.mem0.ai/core-concepts/memory-types): Working memory (short-term session awareness), factual memory (structured knowledge), episodic memory (past conversations), and semantic memory (general knowledge)
- [Memory Operations - Add](https://docs.mem0.ai/core-concepts/memory-operations/add) [Both]: Use when explaining how `add()` extracts facts, resolves conflicts, and writes to both stores. - [Memory Operations - Add](https://docs.mem0.ai/core-concepts/memory-operations/add): How Mem0 processes conversations through information extraction, conflict resolution, and dual storage
- [Memory Operations - Search](https://docs.mem0.ai/core-concepts/memory-operations/search) [Both]: Use when explaining how queries are processed and ranked. - [Memory Operations - Search](https://docs.mem0.ai/core-concepts/memory-operations/search): Retrieval of relevant memories using semantic search with query processing and result ranking
- [Memory Operations - Update](https://docs.mem0.ai/core-concepts/memory-operations/update) [Both]: Use when memories need to be edited in place or reconciled against new info. - [Memory Operations - Update](https://docs.mem0.ai/core-concepts/memory-operations/update): Modifying existing memories when new information conflicts or supplements stored data
- [Memory Operations - Delete](https://docs.mem0.ai/core-concepts/memory-operations/delete) [Both]: Use when outdated memories must be removed. - [Memory Operations - Delete](https://docs.mem0.ai/core-concepts/memory-operations/delete): Removing outdated or irrelevant memories to maintain memory quality
- [Memory Evaluation](https://docs.mem0.ai/core-concepts/memory-evaluation) [Both]: Use when benchmarking memory quality or comparing against baselines.
## Platform ## Platform Features
### Features - Essential - [Platform Features Overview](https://docs.mem0.ai/platform/features/platform-overview): High-level overview of all Mem0 Platform capabilities
- [Platform Features Overview](https://docs.mem0.ai/platform/features/platform-overview) [Platform]: Use when surveying what managed offers beyond CRUD. - [Advanced Memory Operations](https://docs.mem0.ai/platform/advanced-memory-operations): Sophisticated memory management techniques for complex applications
- [V2 Memory Filters](https://docs.mem0.ai/platform/features/v2-memory-filters) [Platform]: Use when compound filters (AND/OR on metadata, entity, time) are needed at search.
- [Entity-Scoped Memory](https://docs.mem0.ai/platform/features/entity-scoped-memory) [Platform]: Use when partitioning memories by user, agent, app, or run.
- [Async Client](https://docs.mem0.ai/platform/features/async-client) [Platform]: Use when the app issues many concurrent Mem0 calls and needs non-blocking I/O.
- [Multimodal Support](https://docs.mem0.ai/platform/features/multimodal-support) [Platform]: Use when storing images or PDFs as memory input.
- [Custom Categories](https://docs.mem0.ai/platform/features/custom-categories) [Platform]: Use when the default categories do not match the domain.
### Features - Advanced Retrieval ### Essential Features
- [Advanced Retrieval](https://docs.mem0.ai/platform/features/advanced-retrieval) [Platform]: Use when the user needs keyword search, reranking, or hybrid retrieval. - [V2 Memory Filters](https://docs.mem0.ai/platform/features/v2-memory-filters): Advanced filtering and querying capabilities for memories
- [Criteria-Based Retrieval](https://docs.mem0.ai/platform/features/criteria-retrieval) [Platform]: Use when targeting memories by custom criteria, not just semantic similarity. - [Entity-Scoped Memory](https://docs.mem0.ai/platform/features/entity-scoped-memory): Organize memories by user, agent, app, and session identifiers
- [Contextual Add](https://docs.mem0.ai/platform/features/contextual-add) [Platform]: Use when `add()` should consider the surrounding conversation, not just the latest turn. - [Async Client](https://docs.mem0.ai/platform/features/async-client): Non-blocking operations for high-concurrency applications
- [Custom Instructions](https://docs.mem0.ai/platform/features/custom-instructions) [Platform]: Use when tailoring what Mem0 extracts and stores on Platform. - [Async Mode Default Changes](https://docs.mem0.ai/platform/features/async-mode-default-change): Understanding new async behavior defaults
- [Advanced Memory Operations](https://docs.mem0.ai/platform/advanced-memory-operations) [Platform]: Use when basic CRUD is not enough - batch ops, complex filters, workflows. - [Multimodal Support](https://docs.mem0.ai/platform/features/multimodal-support): Integration of images and documents (JPG, PNG, MDX, TXT, PDF) via URLs or Base64
- [Custom Categories](https://docs.mem0.ai/platform/features/custom-categories): Define domain-specific categories to improve memory organization
### Features - Data Management ### Advanced Features
- [Direct Import](https://docs.mem0.ai/platform/features/direct-import) [Platform]: Use when seeding a Mem0 project from existing data. - [Graph Threshold](https://docs.mem0.ai/platform/features/graph-threshold): Configure graph relationship sensitivity and strength
- [Memory Export](https://docs.mem0.ai/platform/features/memory-export) [Platform]: Use when exporting memories via a Pydantic schema. - [Advanced Retrieval](https://docs.mem0.ai/platform/features/advanced-retrieval): Enhanced search with keyword search, reranking, and filtering capabilities
- [Timestamp Support](https://docs.mem0.ai/platform/features/timestamp) [Platform]: Use when temporal queries or time-based filtering matter. - [Criteria-Based Retrieval](https://docs.mem0.ai/platform/features/criteria-retrieval): Targeted memory retrieval using custom criteria
- [Contextual Add](https://docs.mem0.ai/platform/features/contextual-add): Add memories with enhanced context awareness
- [Custom Instructions](https://docs.mem0.ai/platform/features/custom-instructions): Customize how Mem0 processes and stores information
### Features - Integration & Ops ### Data Management
- [Webhooks](https://docs.mem0.ai/platform/features/webhooks) [Platform]: Use when another system needs to react to memory changes in real time. - [Direct Import](https://docs.mem0.ai/platform/features/direct-import): Bulk import existing data into Mem0 memory
- [Feedback Mechanism](https://docs.mem0.ai/platform/features/feedback-mechanism) [Platform]: Use when capturing user feedback to improve memory quality. - [Memory Export](https://docs.mem0.ai/platform/features/memory-export): Export memories in structured formats using customizable Pydantic schemas
- [Group Chat Support](https://docs.mem0.ai/platform/features/group-chat) [Platform]: Use when the conversation has multiple participants. - [Timestamp Support](https://docs.mem0.ai/platform/features/timestamp): Temporal memory management with time-based queries
- [MCP Integration](https://docs.mem0.ai/platform/features/mcp-integration) [Platform]: Use when wiring Mem0 into Claude/Cursor/other MCP clients. - [Expiration Dates](https://docs.mem0.ai/platform/features/expiration-date): Automatic memory cleanup with configurable expiration
### Integration Features
- [Webhooks](https://docs.mem0.ai/platform/features/webhooks): Real-time notifications for memory events
- [Feedback Mechanism](https://docs.mem0.ai/platform/features/feedback-mechanism): Improve memory quality through user feedback
- [Group Chat Support](https://docs.mem0.ai/platform/features/group-chat): Multi-conversation memory management
- [MCP Integration](https://docs.mem0.ai/platform/features/mcp-integration): Model Context Protocol integration for AI coding tools
### Support & Migration ### Support & Migration
- [FAQs](https://docs.mem0.ai/platform/faqs) [Platform]: Use when answering common Platform questions. - [FAQs](https://docs.mem0.ai/platform/faqs): Frequently asked questions about Mem0 Platform
- [Contribute to Platform](https://docs.mem0.ai/platform/contribute) [Platform]: Use when a user wants to contribute to Platform docs or code. - [Contribute Guide](https://docs.mem0.ai/platform/contribute): Contributing to Mem0 Platform development
- [OSS to Platform Migration](https://docs.mem0.ai/migration/oss-to-platform) [Both]: Use when moving from self-hosted to managed. - [OSS to Platform Migration](https://docs.mem0.ai/migration/oss-to-platform): Guide for migrating from open-source to managed platform
- [OSS v2 to v3 Migration](https://docs.mem0.ai/migration/oss-v2-to-v3) [OSS]: Use when upgrading a self-hosted deployment across major versions. - [V0 to V1 Migration](https://docs.mem0.ai/migration/v0-to-v1): Upgrading from Mem0 v0 to v1
- [Platform v2 to v3 Migration](https://docs.mem0.ai/migration/platform-v2-to-v3) [Platform]: Use when upgrading a Platform integration across major versions. - [Breaking Changes](https://docs.mem0.ai/migration/breaking-changes): List of breaking changes across versions
- [API Changes](https://docs.mem0.ai/migration/api-changes) [Both]: Use when the upgrade involves API surface changes. - [API Changes](https://docs.mem0.ai/migration/api-changes): Detailed API changes and migration paths
- [Changelog](https://docs.mem0.ai/changelog/highlights) [Both]: Use when the user asks what shipped recently.
## Open Source ## Open Source
- [Open Source Features Overview](https://docs.mem0.ai/open-source/features/overview) [OSS]: Use when surveying OSS-only capabilities. ### Getting Started
- [Metadata Filtering](https://docs.mem0.ai/open-source/features/metadata-filtering) [OSS]: Use when filtering by custom metadata fields in self-hosted. - [Python Quickstart](https://docs.mem0.ai/open-source/python-quickstart): Installation, configuration, and usage examples for Python SDK
- [Reranker Search](https://docs.mem0.ai/open-source/features/reranker-search) [OSS]: Use when improving OSS search quality with a reranker. - [Node.js Quickstart](https://docs.mem0.ai/open-source/node-quickstart): Installation, configuration, and usage examples for Node.js SDK
- [Reranking](https://docs.mem0.ai/open-source/features/reranking) [OSS]: Use when configuring reranking end-to-end in OSS. - [Configuration Guide](https://docs.mem0.ai/open-source/configuration): Complete configuration options for self-hosted deployment
- [Async Memory](https://docs.mem0.ai/open-source/features/async-memory) [OSS]: Use when the self-hosted app needs `AsyncMemory`.
- [OSS Multimodal Support (features)](https://docs.mem0.ai/open-source/features/multimodal-support) [OSS]: Use when handling images and PDFs self-hosted (feature guide). ### Open Source Features
- [OSS Multimodal Support](https://docs.mem0.ai/open-source/multimodal-support) [OSS]: Use when handling images and PDFs self-hosted (concept overview). - [Features Overview](https://docs.mem0.ai/open-source/features/overview): Overview of all open-source features
- [Custom Instructions (OSS)](https://docs.mem0.ai/open-source/features/custom-instructions) [OSS]: Use when tailoring extraction prompts in OSS. - [Metadata Filtering](https://docs.mem0.ai/open-source/features/metadata-filtering): Advanced filtering using custom metadata fields
- [REST API Server](https://docs.mem0.ai/open-source/features/rest-api) [OSS]: Use when exposing a self-hosted Mem0 as a FastAPI service. - [Reranker Search](https://docs.mem0.ai/open-source/features/reranker-search): Enhanced search results with reranking models
- [OpenAI Compatibility](https://docs.mem0.ai/open-source/features/openai_compatibility) [OSS]: Use when hitting an OpenAI-compatible endpoint with self-hosted. - [Async Memory](https://docs.mem0.ai/open-source/features/async-memory): Asynchronous memory operations for better performance
- [Multimodal Support](https://docs.mem0.ai/open-source/features/multimodal-support): Handle text, images, and documents in self-hosted setup
- [Custom Instructions](https://docs.mem0.ai/open-source/features/custom-instructions): Tailor information extraction for specific use cases
- [Custom Memory Update Prompt](https://docs.mem0.ai/open-source/features/custom-update-memory-prompt): Customize how memories are updated and merged
- [REST API Server](https://docs.mem0.ai/open-source/features/rest-api): FastAPI-based server with core operations and OpenAPI documentation
- [OpenAI Compatibility](https://docs.mem0.ai/open-source/features/openai_compatibility): Seamless integration with OpenAI-compatible APIs
## Components
### LLMs
- [LLM Overview](https://docs.mem0.ai/components/llms/overview): Comprehensive guide to Large Language Model integration and configuration options
- [LLM Configuration](https://docs.mem0.ai/components/llms/config): Configuration reference for LLM providers
- [OpenAI](https://docs.mem0.ai/components/llms/models/openai): Integration with OpenAI models including GPT-4
- [Anthropic](https://docs.mem0.ai/components/llms/models/anthropic): Claude model integration with advanced reasoning capabilities
- [Azure OpenAI](https://docs.mem0.ai/components/llms/models/azure_openai): Microsoft Azure hosted OpenAI models for enterprise environments
- [Ollama](https://docs.mem0.ai/components/llms/models/ollama): Local model deployment for privacy-focused applications
- [Together](https://docs.mem0.ai/components/llms/models/together): Open-source model inference platform
- [Groq](https://docs.mem0.ai/components/llms/models/groq): High-performance LPU optimized models for fast inference
- [LiteLLM](https://docs.mem0.ai/components/llms/models/litellm): Unified LLM interface and proxy
- [Mistral AI](https://docs.mem0.ai/components/llms/models/mistral_AI): Mistral model integration
- [Google AI](https://docs.mem0.ai/components/llms/models/google_AI): Gemini model integration for multimodal applications
- [AWS Bedrock](https://docs.mem0.ai/components/llms/models/aws_bedrock): Enterprise-grade AWS managed model integration
- [DeepSeek](https://docs.mem0.ai/components/llms/models/deepseek): Advanced reasoning models
- [MiniMax](https://docs.mem0.ai/components/llms/models/minimax): MiniMax model integration
- [xAI](https://docs.mem0.ai/components/llms/models/xAI): xAI Grok models integration
- [Sarvam](https://docs.mem0.ai/components/llms/models/sarvam): Indian language models
- [LM Studio](https://docs.mem0.ai/components/llms/models/lmstudio): Local model management and deployment
- [LangChain LLM](https://docs.mem0.ai/components/llms/models/langchain): LangChain LLM integration
- [vLLM](https://docs.mem0.ai/components/llms/models/vllm): High-performance inference framework
### Vector Databases
- [Vector Database Overview](https://docs.mem0.ai/components/vectordbs/overview): Guide to supported vector databases for semantic memory storage
- [Vector Database Configuration](https://docs.mem0.ai/components/vectordbs/config): Configuration reference for vector database providers
- [Qdrant](https://docs.mem0.ai/components/vectordbs/dbs/qdrant): High-performance vector similarity search engine
- [Chroma](https://docs.mem0.ai/components/vectordbs/dbs/chroma): AI-native open-source vector database optimized for speed
- [PGVector](https://docs.mem0.ai/components/vectordbs/dbs/pgvector): PostgreSQL extension for vector similarity search
- [Milvus](https://docs.mem0.ai/components/vectordbs/dbs/milvus): Open-source vector database for AI applications at scale
- [Pinecone](https://docs.mem0.ai/components/vectordbs/dbs/pinecone): Managed vector database with serverless and pod deployment options
- [MongoDB](https://docs.mem0.ai/components/vectordbs/dbs/mongodb): Document database with vector search capabilities
- [Azure AI Search](https://docs.mem0.ai/components/vectordbs/dbs/azure): Microsoft's enterprise search service
- [Azure MySQL](https://docs.mem0.ai/components/vectordbs/dbs/azure_mysql): Azure Database for MySQL with vector search
- [Redis](https://docs.mem0.ai/components/vectordbs/dbs/redis): Real-time vector storage and search with Redis Stack
- [Valkey](https://docs.mem0.ai/components/vectordbs/dbs/valkey): Open-source Redis alternative with vector search
- [Elasticsearch](https://docs.mem0.ai/components/vectordbs/dbs/elasticsearch): Distributed search and analytics engine
- [OpenSearch](https://docs.mem0.ai/components/vectordbs/dbs/opensearch): Open-source search and analytics platform
- [Supabase](https://docs.mem0.ai/components/vectordbs/dbs/supabase): Open-source Firebase alternative with vector support
- [Upstash Vector](https://docs.mem0.ai/components/vectordbs/dbs/upstash-vector): Serverless vector database
- [Vectorize](https://docs.mem0.ai/components/vectordbs/dbs/vectorize): Vectorize vector database integration
- [Vertex AI Vector Search](https://docs.mem0.ai/components/vectordbs/dbs/vertex_ai): Google Cloud's vector search service
- [Weaviate](https://docs.mem0.ai/components/vectordbs/dbs/weaviate): Open-source vector search engine with built-in ML capabilities
- [FAISS](https://docs.mem0.ai/components/vectordbs/dbs/faiss): Facebook AI Similarity Search library
- [LangChain Vector Store](https://docs.mem0.ai/components/vectordbs/dbs/langchain): LangChain vector store integration
- [Baidu](https://docs.mem0.ai/components/vectordbs/dbs/baidu): Baidu vector database integration
- [Cassandra](https://docs.mem0.ai/components/vectordbs/dbs/cassandra): Apache Cassandra with vector search capabilities
- [S3 Vectors](https://docs.mem0.ai/components/vectordbs/dbs/s3_vectors): Amazon S3 Vectors integration
- [Databricks](https://docs.mem0.ai/components/vectordbs/dbs/databricks): Delta Lake integration for vector search
- [Neptune Analytics](https://docs.mem0.ai/components/vectordbs/dbs/neptune_analytics): AWS Neptune Analytics for graph and vector search
- [Turbopuffer](https://docs.mem0.ai/components/vectordbs/dbs/turbopuffer): High-performance serverless vector database
### Embedding Models
- [Embeddings Overview](https://docs.mem0.ai/components/embedders/overview): Embedding model configuration for semantic understanding
- [Embeddings Configuration](https://docs.mem0.ai/components/embedders/config): Configuration reference for embedding providers
- [OpenAI Embeddings](https://docs.mem0.ai/components/embedders/models/openai): High-quality text embeddings with customizable dimensions
- [Azure OpenAI Embeddings](https://docs.mem0.ai/components/embedders/models/azure_openai): Enterprise Azure-hosted embedding models
- [Ollama Embeddings](https://docs.mem0.ai/components/embedders/models/ollama): Local embedding models for privacy-focused applications
- [Hugging Face Embeddings](https://docs.mem0.ai/components/embedders/models/huggingface): Open-source embedding models for local deployment
- [Vertex AI Embeddings](https://docs.mem0.ai/components/embedders/models/vertexai): Google Cloud's enterprise embedding models
- [Google AI Embeddings](https://docs.mem0.ai/components/embedders/models/google_AI): Gemini embedding models
- [LM Studio Embeddings](https://docs.mem0.ai/components/embedders/models/lmstudio): Local model embeddings
- [Together Embeddings](https://docs.mem0.ai/components/embedders/models/together): Open-source model embeddings
- [LangChain Embeddings](https://docs.mem0.ai/components/embedders/models/langchain): LangChain embedder integration
- [AWS Bedrock Embeddings](https://docs.mem0.ai/components/embedders/models/aws_bedrock): Amazon embedding models through Bedrock
### Rerankers
- [Reranker Overview](https://docs.mem0.ai/components/rerankers/overview): Guide to reranking models for improving search result quality
- [Reranker Configuration](https://docs.mem0.ai/components/rerankers/config): Configuration reference for reranker providers
- [Reranker Optimization](https://docs.mem0.ai/components/rerankers/optimization): Performance tuning and optimization strategies for rerankers
- [Custom Reranker Prompts](https://docs.mem0.ai/components/rerankers/custom-prompts): Customize reranker behavior with custom prompts
- [Cohere Reranker](https://docs.mem0.ai/components/rerankers/models/cohere): Cohere reranking model integration
- [Sentence Transformer Reranker](https://docs.mem0.ai/components/rerankers/models/sentence_transformer): Cross-encoder reranking with sentence transformers
- [Hugging Face Reranker](https://docs.mem0.ai/components/rerankers/models/huggingface): Hugging Face reranking models
- [LLM Reranker](https://docs.mem0.ai/components/rerankers/models/llm_reranker): Use LLMs as rerankers for flexible relevance scoring
- [Zero Entropy Reranker](https://docs.mem0.ai/components/rerankers/models/zero_entropy): Zero Entropy reranking model
## Integrations ## Integrations
- [Integrations Overview](https://docs.mem0.ai/integrations) [Both]: Use when surveying every available integration. - [Integrations Overview](https://docs.mem0.ai/integrations): Overview of all available Mem0 integrations
### Agent Frameworks ### Agent Frameworks
- [LangChain](https://docs.mem0.ai/integrations/langchain) [Both]: Use when the user is on LangChain. - [LangChain](https://docs.mem0.ai/integrations/langchain): Seamless integration with LangChain framework for enhanced agent capabilities
- [LangGraph](https://docs.mem0.ai/integrations/langgraph) [Both]: Use when building stateful multi-actor LangGraph apps. - [LangGraph](https://docs.mem0.ai/integrations/langgraph): Build stateful, multi-actor applications with persistent memory
- [LangChain Tools](https://docs.mem0.ai/integrations/langchain-tools) [Both]: Use when Mem0 should be exposed as a LangChain tool. - [LlamaIndex](https://docs.mem0.ai/integrations/llama-index): Enhanced RAG applications with intelligent memory layer
- [LlamaIndex](https://docs.mem0.ai/integrations/llama-index) [Both]: Use when layering memory on a LlamaIndex RAG app. - [CrewAI](https://docs.mem0.ai/integrations/crewai): Multi-agent systems with shared and individual memory capabilities
- [CrewAI](https://docs.mem0.ai/integrations/crewai) [Both]: Use when building CrewAI multi-agent systems. - [AutoGen](https://docs.mem0.ai/integrations/autogen): Microsoft's multi-agent conversation framework with memory
- [AutoGen](https://docs.mem0.ai/integrations/autogen) [Both]: Use when the user is on Microsoft AutoGen. - [Agno](https://docs.mem0.ai/integrations/agno): Agno framework integration with persistent memory
- [Agno](https://docs.mem0.ai/integrations/agno) [Both]: Use when the user is on Agno. - [Camel AI](https://docs.mem0.ai/integrations/camel-ai): Camel AI multi-agent framework with memory support
- [Camel AI](https://docs.mem0.ai/integrations/camel-ai) [Both]: Use when the user is on Camel AI. - [OpenClaw](https://docs.mem0.ai/integrations/openclaw): OpenClaw framework integration
- [ChatDev](https://docs.mem0.ai/integrations/chatdev) [Both]: Use when the user is on ChatDev. - [OpenAI Agents SDK](https://docs.mem0.ai/integrations/openai-agents-sdk): OpenAI's agent framework with Mem0 memory
- [Hermes](https://docs.mem0.ai/integrations/hermes) [Both]: Use when the user is on Hermes. - [Google AI ADK](https://docs.mem0.ai/integrations/google-ai-adk): Google AI Agent Development Kit with persistent memory
- [OpenAI Agents SDK](https://docs.mem0.ai/integrations/openai-agents-sdk) [Both]: Use when the user is on the OpenAI Agents SDK. - [Mastra](https://docs.mem0.ai/integrations/mastra): Mastra TypeScript agent framework integration
- [Google AI ADK](https://docs.mem0.ai/integrations/google-ai-adk) [Both]: Use when the user is on Google's Agent Development Kit. - [Vercel AI SDK](https://docs.mem0.ai/integrations/vercel-ai-sdk): Build AI-powered web applications with persistent memory
- [Mastra](https://docs.mem0.ai/integrations/mastra) [Both]: Use when the user is on Mastra (TypeScript).
- [OpenClaw](https://docs.mem0.ai/integrations/openclaw) [Both]: Use when wiring Mem0 into Claude Code or editors via OpenClaw.
- [Vercel AI SDK](https://docs.mem0.ai/integrations/vercel-ai-sdk) [Both]: Use when the user is on the Vercel AI SDK.
### AI Coding Tools
- [Claude Code](https://docs.mem0.ai/integrations/claude-code) [Both]: Use when wiring memory into Claude Code.
- [Cursor](https://docs.mem0.ai/integrations/cursor) [Both]: Use when wiring memory into Cursor.
- [Codex](https://docs.mem0.ai/integrations/codex) [Both]: Use when wiring memory into Codex / other editor assistants.
### Voice & Real-time ### Voice & Real-time
- [LiveKit](https://docs.mem0.ai/integrations/livekit) [Both]: Use when building real-time voice/video with memory. - [LiveKit](https://docs.mem0.ai/integrations/livekit): Real-time voice and video AI with persistent memory
- [Pipecat](https://docs.mem0.ai/integrations/pipecat) [Both]: Use when the voice pipeline is Pipecat. - [Pipecat](https://docs.mem0.ai/integrations/pipecat): Voice AI pipeline framework with memory capabilities
- [ElevenLabs](https://docs.mem0.ai/integrations/elevenlabs) [Both]: Use when voice synthesis uses ElevenLabs. - [ElevenLabs](https://docs.mem0.ai/integrations/elevenlabs): Voice synthesis integration with conversational memory
### Cloud & Infrastructure ### Cloud & Infrastructure
- [AWS Bedrock](https://docs.mem0.ai/integrations/aws-bedrock) [Both]: Use when the user is on AWS Bedrock managed AI services. - [AWS Bedrock](https://docs.mem0.ai/integrations/aws-bedrock): Enterprise AWS integration for managed AI services
### Developer Tools ### Developer Tools
- [Dify](https://docs.mem0.ai/integrations/dify) [Both]: Use when the user is on Dify LLMOps. - [Dify](https://docs.mem0.ai/integrations/dify): LLMOps platform integration for production AI applications
- [Flowise](https://docs.mem0.ai/integrations/flowise) [Both]: Use when the user is on Flowise no-code. - [Flowise](https://docs.mem0.ai/integrations/flowise): No-code LLM workflow builder with memory capabilities
- [AgentOps](https://docs.mem0.ai/integrations/agentops) [Both]: Use when tracking agent observability with memory metadata. - [LangChain Tools](https://docs.mem0.ai/integrations/langchain-tools): Use Mem0 as a LangChain tool for agents
- [Keywords AI](https://docs.mem0.ai/integrations/keywords) [Both]: Use when monitoring with Keywords AI. - [AgentOps](https://docs.mem0.ai/integrations/agentops): Agent observability and monitoring with memory tracking
- [Raycast](https://docs.mem0.ai/integrations/raycast) [Both]: Use when the user wants quick memory access via Raycast. - [Keywords AI](https://docs.mem0.ai/integrations/keywords): Keywords AI integration for LLM monitoring
- [Raycast](https://docs.mem0.ai/integrations/raycast): Raycast extension for quick memory access
## Cookbooks ## Cookbooks and Examples
- [Cookbooks Overview](https://docs.mem0.ai/cookbooks/overview) [Both]: Use when surveying all reference examples. - [Cookbooks Overview](https://docs.mem0.ai/cookbooks/overview): Complete guide to Mem0 examples and implementation patterns
### Essentials ### Essential Guides
- [Building an AI Companion](https://docs.mem0.ai/cookbooks/essentials/building-ai-companion) [Both]: Use when starting a companion app from scratch. - [Building AI Companion](https://docs.mem0.ai/cookbooks/essentials/building-ai-companion): Core patterns for building AI agents with memory
- [Partition Memories by Entity](https://docs.mem0.ai/cookbooks/essentials/entity-partitioning-playbook) [Both]: Use when isolating multi-tenant memories. - [Partition Memories by Entity](https://docs.mem0.ai/cookbooks/essentials/entity-partitioning-playbook): Keep multi-tenant assistants isolated by tagging user, agent, app, and session identifiers
- [Controlling Memory Ingestion](https://docs.mem0.ai/cookbooks/essentials/controlling-memory-ingestion) [Both]: Use when deciding what to store and what to skip. - [Controlling Memory Ingestion](https://docs.mem0.ai/cookbooks/essentials/controlling-memory-ingestion): Fine-tune what gets stored in memory and when
- [Tagging and Organizing Memories](https://docs.mem0.ai/cookbooks/essentials/tagging-and-organizing-memories) [Both]: Use when memory taxonomy matters. - [Tagging and Organizing Memories](https://docs.mem0.ai/cookbooks/essentials/tagging-and-organizing-memories): Advanced memory organization and categorization
- [Exporting Memories](https://docs.mem0.ai/cookbooks/essentials/exporting-memories) [Both]: Use when backing up or migrating memory data. - [Exporting Memories](https://docs.mem0.ai/cookbooks/essentials/exporting-memories): Backup and transfer memory data between systems
### AI Companions ### AI Companion Examples
- [Quickstart Demo](https://docs.mem0.ai/cookbooks/companions/quickstart-demo) [Both]: Use when showing the smallest end-to-end companion. - [Quickstart Demo](https://docs.mem0.ai/cookbooks/companions/quickstart-demo): Quick demo of building an AI companion with memory
- [Node.js Companion](https://docs.mem0.ai/cookbooks/companions/nodejs-companion) [Both]: Use when the companion is in JavaScript/TypeScript. - [Node.js Companion](https://docs.mem0.ai/cookbooks/companions/nodejs-companion): JavaScript-based AI companion applications
- [AI Tutor](https://docs.mem0.ai/cookbooks/companions/ai-tutor) [Both]: Use when the agent adapts to a learner over time. - [AI Tutor](https://docs.mem0.ai/cookbooks/companions/ai-tutor): Educational AI that adapts to learning progress
- [Travel Assistant](https://docs.mem0.ai/cookbooks/companions/travel-assistant) [Both]: Use when the agent learns travel preferences. - [Travel Assistant](https://docs.mem0.ai/cookbooks/companions/travel-assistant): Travel planning agent that learns preferences
- [YouTube Research Assistant](https://docs.mem0.ai/cookbooks/companions/youtube-research) [Both]: Use when building an agent that ingests video content over sessions. - [YouTube Research Assistant](https://docs.mem0.ai/cookbooks/companions/youtube-research): AI that researches and learns from video content
- [Voice Companion (OpenAI)](https://docs.mem0.ai/cookbooks/companions/voice-companion-openai) [Both]: Use when the companion is voice-first with OpenAI Realtime. - [Voice Companion](https://docs.mem0.ai/cookbooks/companions/voice-companion-openai): Voice-enabled AI with conversational memory
- [Local Companion (Ollama)](https://docs.mem0.ai/cookbooks/companions/local-companion-ollama) [OSS]: Use when the companion must run entirely on local models. - [Local Companion](https://docs.mem0.ai/cookbooks/companions/local-companion-ollama): Privacy-focused companion using local models
### Operations & Automation ### Operations & Automation
- [Support Inbox](https://docs.mem0.ai/cookbooks/operations/support-inbox) [Both]: Use when a support agent needs conversation history across tickets. - [Support Inbox](https://docs.mem0.ai/cookbooks/operations/support-inbox): Customer service agents with conversation history
- [Email Automation](https://docs.mem0.ai/cookbooks/operations/email-automation) [Both]: Use when processing email with contextual memory. - [Email Automation](https://docs.mem0.ai/cookbooks/operations/email-automation): Smart email processing with contextual memory
- [Content Writing](https://docs.mem0.ai/cookbooks/operations/content-writing) [Both]: Use when an AI writer must maintain brand voice across sessions. - [Content Writing](https://docs.mem0.ai/cookbooks/operations/content-writing): AI writers that maintain brand voice and style
- [Deep Research](https://docs.mem0.ai/cookbooks/operations/deep-research) [Both]: Use when research agents build on previous findings. - [Deep Research](https://docs.mem0.ai/cookbooks/operations/deep-research): Research assistants that build on previous findings
- [Team Task Agent](https://docs.mem0.ai/cookbooks/operations/team-task-agent) [Both]: Use when collaborative agents share project memory. - [Team Task Agent](https://docs.mem0.ai/cookbooks/operations/team-task-agent): Collaborative AI agents with shared project memory
### Integration Examples ### Integration Examples
- [Agents SDK Tool](https://docs.mem0.ai/cookbooks/integrations/agents-sdk-tool) [Platform]: Use when exposing Mem0 as a tool in OpenAI Agents SDK. - [Agents SDK Tool](https://docs.mem0.ai/cookbooks/integrations/agents-sdk-tool): Using Mem0 as a tool with OpenAI Agents SDK
- [OpenAI Tool Calls](https://docs.mem0.ai/cookbooks/integrations/openai-tool-calls) [Platform]: Use when hooking Mem0 into OpenAI function calling. - [OpenAI Tool Calls](https://docs.mem0.ai/cookbooks/integrations/openai-tool-calls): Mem0 integrated with OpenAI function calling
- [Mastra Agent](https://docs.mem0.ai/cookbooks/integrations/mastra-agent) [Both]: Use when the agent is built in Mastra. - [Mastra Agent](https://docs.mem0.ai/cookbooks/integrations/mastra-agent): Mastra framework integration with memory
- [Healthcare Google ADK](https://docs.mem0.ai/cookbooks/integrations/healthcare-google-adk) [Both]: Use when the domain is medical and the framework is Google ADK. - [Healthcare Google ADK](https://docs.mem0.ai/cookbooks/integrations/healthcare-google-adk): Medical AI applications with memory
- [AWS Bedrock](https://docs.mem0.ai/cookbooks/integrations/aws-bedrock) [Both]: Use when deploying with AWS managed model services. - [AWS Bedrock](https://docs.mem0.ai/cookbooks/integrations/aws-bedrock): Enterprise memory with AWS managed services
- [Tavily Search](https://docs.mem0.ai/cookbooks/integrations/tavily-search) [Both]: Use when the agent layers web search on memory. - [Neptune Analytics](https://docs.mem0.ai/cookbooks/integrations/neptune-analytics): Graph and vector search with AWS Neptune
- [Tavily Search](https://docs.mem0.ai/cookbooks/integrations/tavily-search): Web search with persistent memory of results
### Framework Examples ### Framework Examples
- [LlamaIndex React](https://docs.mem0.ai/cookbooks/frameworks/llamaindex-react) [Both]: Use when building a React UI with LlamaIndex and memory. - [LlamaIndex React](https://docs.mem0.ai/cookbooks/frameworks/llamaindex-react): React applications with LlamaIndex and memory
- [LlamaIndex Multiagent](https://docs.mem0.ai/cookbooks/frameworks/llamaindex-multiagent) [Both]: Use when running LlamaIndex multi-agent systems with shared memory. - [LlamaIndex Multiagent](https://docs.mem0.ai/cookbooks/frameworks/llamaindex-multiagent): Multi-agent systems with shared memory
- [Multimodal Retrieval](https://docs.mem0.ai/cookbooks/frameworks/multimodal-retrieval) [Both]: Use when memory must handle text, images, and docs together. - [Multimodal Retrieval](https://docs.mem0.ai/cookbooks/frameworks/multimodal-retrieval): Memory systems handling text, images, and documents
- [Eliza OS Character](https://docs.mem0.ai/cookbooks/frameworks/eliza-os-character) [Both]: Use when building a character-based agent with persistent personality. - [Eliza OS Character](https://docs.mem0.ai/cookbooks/frameworks/eliza-os-character): Character-based AI with persistent personality
- [Gemini with Mem0 MCP](https://docs.mem0.ai/cookbooks/frameworks/gemini-3-with-mem0-mcp) [Platform]: Use when Gemini connects to Mem0 over MCP. - [Gemini with Mem0 MCP](https://docs.mem0.ai/cookbooks/frameworks/gemini-3-with-mem0-mcp): Google Gemini integration using MCP server
## API Reference ## API Reference
All API Reference docs describe Mem0 Platform REST endpoints (requires API key). - [API Reference Overview](https://docs.mem0.ai/api-reference): REST API overview with authentication and quick start guide
- [Organizations & Projects](https://docs.mem0.ai/api-reference/organizations-projects): Managing organizations and projects for multi-tenant setups
- [API Reference Overview](https://docs.mem0.ai/api-reference) [Platform]: Use when explaining authentication and the general request/response shape. ### Core Memory APIs
- [Organizations & Projects](https://docs.mem0.ai/api-reference/organizations-projects) [Platform]: Use when the user needs multi-tenant isolation. - [Add Memories](https://docs.mem0.ai/api-reference/memory/add-memories): REST API for storing new memories with detailed request/response formats
- [Get All Memories](https://docs.mem0.ai/api-reference/memory/get-memories): Retrieve all memories with pagination and filtering options
- [Search Memories](https://docs.mem0.ai/api-reference/memory/search-memories): Advanced search API with filtering and ranking capabilities
- [Update Memory](https://docs.mem0.ai/api-reference/memory/update-memory): Modify existing memories with conflict resolution
- [Delete Memory](https://docs.mem0.ai/api-reference/memory/delete-memory): Remove a specific memory by ID
### Core Memory ### Additional Memory APIs
- [Add Memories](https://docs.mem0.ai/api-reference/memory/add-memories) [Platform]: Use when writing one or more memories. - [Create Memory Export](https://docs.mem0.ai/api-reference/memory/create-memory-export): Export memories in bulk
- [Get All Memories](https://docs.mem0.ai/api-reference/memory/get-memories) [Platform]: Use when paginating memories for a user/agent. - [Feedback](https://docs.mem0.ai/api-reference/memory/feedback): Submit feedback on memory quality
- [Get Memory](https://docs.mem0.ai/api-reference/memory/get-memory) [Platform]: Use when fetching one memory by ID. - [Get Memory](https://docs.mem0.ai/api-reference/memory/get-memory): Retrieve a single memory by ID
- [Search Memories](https://docs.mem0.ai/api-reference/memory/search-memories) [Platform]: Use when running a semantic query with filters. - [Memory History](https://docs.mem0.ai/api-reference/memory/history-memory): View the history of changes to a memory
- [Update Memory](https://docs.mem0.ai/api-reference/memory/update-memory) [Platform]: Use when editing a memory in place. - [Get Memory Export](https://docs.mem0.ai/api-reference/memory/get-memory-export): Retrieve a previously created memory export
- [Delete Memory](https://docs.mem0.ai/api-reference/memory/delete-memory) [Platform]: Use when removing one memory. - [Batch Update](https://docs.mem0.ai/api-reference/memory/batch-update): Update multiple memories in a single request
- [Delete All Memories](https://docs.mem0.ai/api-reference/memory/delete-memories) [Platform]: Use when purging memories matching a scope. - [Batch Delete](https://docs.mem0.ai/api-reference/memory/batch-delete): Delete multiple memories in a single request
- [Batch Update](https://docs.mem0.ai/api-reference/memory/batch-update) [Platform]: Use when updating many memories in one call. - [Delete All Memories](https://docs.mem0.ai/api-reference/memory/delete-memories): Remove all memories matching criteria
- [Batch Delete](https://docs.mem0.ai/api-reference/memory/batch-delete) [Platform]: Use when deleting many memories in one call.
- [Memory History](https://docs.mem0.ai/api-reference/memory/history-memory) [Platform]: Use when the user needs the change log for a memory.
- [Feedback](https://docs.mem0.ai/api-reference/memory/feedback) [Platform]: Use when capturing user signals on memory quality.
- [Create Memory Export](https://docs.mem0.ai/api-reference/memory/create-memory-export) [Platform]: Use when kicking off an async export job.
- [Get Memory Export](https://docs.mem0.ai/api-reference/memory/get-memory-export) [Platform]: Use when fetching the result of an export job.
### Events ### Events APIs
- [Get Events](https://docs.mem0.ai/api-reference/events/get-events) [Platform]: Use when listing async memory operation events. - [Get Events](https://docs.mem0.ai/api-reference/events/get-events): List asynchronous memory operation events
- [Get Event](https://docs.mem0.ai/api-reference/events/get-event) [Platform]: Use when fetching one event by ID. - [Get Event](https://docs.mem0.ai/api-reference/events/get-event): Retrieve details of a specific event
### Entities ### Entities APIs
- [Get Users](https://docs.mem0.ai/api-reference/entities/get-users) [Platform]: Use when listing users, agents, or apps known to a project. - [Get Users](https://docs.mem0.ai/api-reference/entities/get-users): List all entities (users, agents, apps)
- [Delete User](https://docs.mem0.ai/api-reference/entities/delete-user) [Platform]: Use when removing an entity and all its memories. - [Delete User](https://docs.mem0.ai/api-reference/entities/delete-user): Remove an entity and all associated memories
### Organizations ### Organizations APIs
- [Create Organization](https://docs.mem0.ai/api-reference/organization/create-org) [Platform]: Use when setting up a new org. - [Create Organization](https://docs.mem0.ai/api-reference/organization/create-org): Create a new organization
- [Get Organizations](https://docs.mem0.ai/api-reference/organization/get-orgs) [Platform]: Use when listing orgs. - [Get Organizations](https://docs.mem0.ai/api-reference/organization/get-orgs): List all organizations
- [Get Organization](https://docs.mem0.ai/api-reference/organization/get-org) [Platform]: Use when fetching one org. - [Get Organization](https://docs.mem0.ai/api-reference/organization/get-org): Retrieve organization details
- [Get Organization Members](https://docs.mem0.ai/api-reference/organization/get-org-members) [Platform]: Use when listing org members. - [Get Organization Members](https://docs.mem0.ai/api-reference/organization/get-org-members): List organization members
- [Add Organization Member](https://docs.mem0.ai/api-reference/organization/add-org-member) [Platform]: Use when inviting a member to an org. - [Add Organization Member](https://docs.mem0.ai/api-reference/organization/add-org-member): Add a member to an organization
- [Delete Organization](https://docs.mem0.ai/api-reference/organization/delete-org) [Platform]: Use when removing an org. - [Delete Organization](https://docs.mem0.ai/api-reference/organization/delete-org): Remove an organization
### Projects ### Project APIs
- [Create Project](https://docs.mem0.ai/api-reference/project/create-project) [Platform]: Use when creating a project inside an org. - [Create Project](https://docs.mem0.ai/api-reference/project/create-project): Create a new project within an organization
- [Get Projects](https://docs.mem0.ai/api-reference/project/get-projects) [Platform]: Use when listing projects. - [Get Projects](https://docs.mem0.ai/api-reference/project/get-projects): List all projects
- [Get Project](https://docs.mem0.ai/api-reference/project/get-project) [Platform]: Use when fetching one project. - [Get Project](https://docs.mem0.ai/api-reference/project/get-project): Retrieve project details
- [Get Project Members](https://docs.mem0.ai/api-reference/project/get-project-members) [Platform]: Use when listing project members. - [Get Project Members](https://docs.mem0.ai/api-reference/project/get-project-members): List project members
- [Add Project Member](https://docs.mem0.ai/api-reference/project/add-project-member) [Platform]: Use when inviting a member to a project. - [Add Project Member](https://docs.mem0.ai/api-reference/project/add-project-member): Add a member to a project
- [Delete Project](https://docs.mem0.ai/api-reference/project/delete-project) [Platform]: Use when removing a project. - [Delete Project](https://docs.mem0.ai/api-reference/project/delete-project): Remove a project
### Webhooks ### Webhook APIs
- [Create Webhook](https://docs.mem0.ai/api-reference/webhook/create-webhook) [Platform]: Use when registering a webhook endpoint. - [Create Webhook](https://docs.mem0.ai/api-reference/webhook/create-webhook): Register a new webhook endpoint
- [Get Webhook](https://docs.mem0.ai/api-reference/webhook/get-webhook) [Platform]: Use when fetching webhook config. - [Get Webhook](https://docs.mem0.ai/api-reference/webhook/get-webhook): Retrieve webhook configuration
- [Update Webhook](https://docs.mem0.ai/api-reference/webhook/update-webhook) [Platform]: Use when modifying webhook settings. - [Update Webhook](https://docs.mem0.ai/api-reference/webhook/update-webhook): Modify webhook settings
- [Delete Webhook](https://docs.mem0.ai/api-reference/webhook/delete-webhook) [Platform]: Use when removing a webhook. - [Delete Webhook](https://docs.mem0.ai/api-reference/webhook/delete-webhook): Remove a webhook
## Skills & Plugins
Mem0 ships first-class integrations for AI coding editors and MCP-aware tools. When the user is in Claude Code, Cursor, Codex, or any MCP client, load this section first.
### Claude Code Skills (in-repo, not on docs.mem0.ai)
Source: https://github.com/mem0ai/mem0/tree/main/skills
- **skills/mem0** - Default Mem0 skill. Trigger on mentions of `MemoryClient`, "memory layer", personalization, or adding long-term memory to chatbots/agents. Covers Python SDK, TS SDK, and every framework integration.
- **skills/mem0-cli** - Trigger on CLI / terminal / shell usage of Mem0.
- **skills/mem0-vercel-ai-sdk** - Trigger when the stack includes `@mem0/vercel-ai-provider` or `createMem0`.
Each subdirectory is a Claude Code Skill (`SKILL.md` + supporting assets). Load only the one that matches the user's stack.
### Editor Plugin (shared glue)
Source: https://github.com/mem0ai/mem0/tree/main/mem0-plugin
The `mem0-plugin/` directory provides MCP server connection, lifecycle hooks, and skill bundling for Claude Code, Cursor, and Codex. It exposes 9 MCP tools: `add_memory`, `search_memories`, `get_memories`, `get_memory`, `update_memory`, `delete_memory`, `delete_all_memories`, `delete_entities`, `list_entities`.
Editor-specific setup docs (already listed above under `## Integrations > AI Coding Tools`):
- `integrations/claude-code` [Both]
- `integrations/cursor` [Both]
- `integrations/codex` [Both]
- `integrations/openclaw` [Both]
### MCP Endpoints
- Hosted MCP server: `https://mcp.mem0.ai` - requires Platform API key. See `platform/mem0-mcp`.
- Self-hosted MCP server: ships with `openmemory/api/` (FastAPI) - runs against your own Qdrant + LLM stack.
## Community & Support ## Community & Support
- [Contributing - Development](https://docs.mem0.ai/contributing/development) [Both]: Use when the user wants to contribute code. - [Contributing - Development](https://docs.mem0.ai/contributing/development): Guidelines for contributing to Mem0's open-source development
- [Contributing - Documentation](https://docs.mem0.ai/contributing/documentation) [Both]: Use when the user wants to contribute docs. - [Contributing - Documentation](https://docs.mem0.ai/contributing/documentation): Guidelines for contributing to Mem0's documentation
- [Changelog](https://docs.mem0.ai/changelog): Detailed product updates and version history
## Optional
Everything below is OSS-only provider configuration. Skip this entire section when the user is on Mem0 Platform (providers are managed server-side). When the user is self-hosting, load only the subsection that matches the provider they are configuring.
### LLM Providers [OSS]
- [LLM Overview](https://docs.mem0.ai/components/llms/overview) [OSS]: Use when the user is choosing an LLM for memory extraction.
- [LLM Configuration](https://docs.mem0.ai/components/llms/config) [OSS]: Use for the `llm` config schema.
- [OpenAI](https://docs.mem0.ai/components/llms/models/openai) [OSS]: Use when the extraction LLM is OpenAI.
- [Anthropic](https://docs.mem0.ai/components/llms/models/anthropic) [OSS]: Use when the extraction LLM is Claude.
- [Azure OpenAI](https://docs.mem0.ai/components/llms/models/azure_openai) [OSS]: Use when the user is on Azure-hosted OpenAI.
- [AWS Bedrock](https://docs.mem0.ai/components/llms/models/aws_bedrock) [OSS]: Use when the LLM runs through Bedrock.
- [Google AI](https://docs.mem0.ai/components/llms/models/google_AI) [OSS]: Use when the LLM is Gemini.
- [Groq](https://docs.mem0.ai/components/llms/models/groq) [OSS]: Use when the user wants Groq's low-latency inference.
- [DeepSeek](https://docs.mem0.ai/components/llms/models/deepseek) [OSS]: Use when the LLM is DeepSeek.
- [Mistral AI](https://docs.mem0.ai/components/llms/models/mistral_AI) [OSS]: Use when the LLM is Mistral.
- [MiniMax](https://docs.mem0.ai/components/llms/models/minimax) [OSS]: Use when the LLM is MiniMax.
- [xAI](https://docs.mem0.ai/components/llms/models/xAI) [OSS]: Use when the LLM is xAI Grok.
- [Sarvam](https://docs.mem0.ai/components/llms/models/sarvam) [OSS]: Use for Indian-language Sarvam models.
- [Together](https://docs.mem0.ai/components/llms/models/together) [OSS]: Use when the LLM runs on Together.
- [Ollama](https://docs.mem0.ai/components/llms/models/ollama) [OSS]: Use when the LLM is a local Ollama model.
- [LM Studio](https://docs.mem0.ai/components/llms/models/lmstudio) [OSS]: Use when the LLM is served from LM Studio.
- [LiteLLM](https://docs.mem0.ai/components/llms/models/litellm) [OSS]: Use when multiplexing many providers behind LiteLLM.
- [vLLM](https://docs.mem0.ai/components/llms/models/vllm) [OSS]: Use when self-hosting inference with vLLM.
- [LangChain LLM](https://docs.mem0.ai/components/llms/models/langchain) [OSS]: Use when the LLM is wrapped behind a LangChain adapter.
### Embedding Providers [OSS]
- [Embeddings Overview](https://docs.mem0.ai/components/embedders/overview) [OSS]: Use when choosing an embedding model.
- [Embeddings Configuration](https://docs.mem0.ai/components/embedders/config) [OSS]: Use for the `embedder` config schema.
- [OpenAI Embeddings](https://docs.mem0.ai/components/embedders/models/openai) [OSS]: Use when embeddings come from OpenAI.
- [Azure OpenAI Embeddings](https://docs.mem0.ai/components/embedders/models/azure_openai) [OSS]: Use for Azure-hosted OpenAI embeddings.
- [AWS Bedrock Embeddings](https://docs.mem0.ai/components/embedders/models/aws_bedrock) [OSS]: Use for Bedrock-hosted embeddings.
- [Google AI Embeddings](https://docs.mem0.ai/components/embedders/models/google_AI) [OSS]: Use for Gemini embeddings.
- [Vertex AI Embeddings](https://docs.mem0.ai/components/embedders/models/vertexai) [OSS]: Use for Google Cloud Vertex AI embeddings.
- [Hugging Face Embeddings](https://docs.mem0.ai/components/embedders/models/huggingface) [OSS]: Use for open-source HF embedding models.
- [Ollama Embeddings](https://docs.mem0.ai/components/embedders/models/ollama) [OSS]: Use when embeddings run through local Ollama.
- [LM Studio Embeddings](https://docs.mem0.ai/components/embedders/models/lmstudio) [OSS]: Use when embeddings run through LM Studio.
- [Together Embeddings](https://docs.mem0.ai/components/embedders/models/together) [OSS]: Use when embeddings run on Together.
- [LangChain Embeddings](https://docs.mem0.ai/components/embedders/models/langchain) [OSS]: Use when embeddings are wrapped behind a LangChain adapter.
### Vector Databases [OSS]
- [Vector Database Overview](https://docs.mem0.ai/components/vectordbs/overview) [OSS]: Use when choosing a vector store.
- [Vector Database Configuration](https://docs.mem0.ai/components/vectordbs/config) [OSS]: Use for the `vector_store` config schema.
- [Qdrant](https://docs.mem0.ai/components/vectordbs/dbs/qdrant) [OSS]: Use as the default self-hosted vector store (best-tested).
- [Chroma](https://docs.mem0.ai/components/vectordbs/dbs/chroma) [OSS]: Use when the user wants a lightweight embedded store.
- [PGVector](https://docs.mem0.ai/components/vectordbs/dbs/pgvector) [OSS]: Use when Postgres is already in the stack.
- [Milvus](https://docs.mem0.ai/components/vectordbs/dbs/milvus) [OSS]: Use for large-scale Milvus deployments.
- [Pinecone](https://docs.mem0.ai/components/vectordbs/dbs/pinecone) [OSS]: Use when the user is on Pinecone managed.
- [MongoDB](https://docs.mem0.ai/components/vectordbs/dbs/mongodb) [OSS]: Use when Mongo Atlas Vector Search is the backing store.
- [Azure AI Search](https://docs.mem0.ai/components/vectordbs/dbs/azure) [OSS]: Use when the user is on Azure AI Search.
- [Azure MySQL](https://docs.mem0.ai/components/vectordbs/dbs/azure_mysql) [OSS]: Use when vector search runs on Azure Database for MySQL.
- [Redis](https://docs.mem0.ai/components/vectordbs/dbs/redis) [OSS]: Use when Redis Stack is the backing store.
- [Valkey](https://docs.mem0.ai/components/vectordbs/dbs/valkey) [OSS]: Use when the user is on Valkey (Redis fork).
- [Elasticsearch](https://docs.mem0.ai/components/vectordbs/dbs/elasticsearch) [OSS]: Use when Elasticsearch is the backing store.
- [OpenSearch](https://docs.mem0.ai/components/vectordbs/dbs/opensearch) [OSS]: Use when OpenSearch is the backing store.
- [Supabase](https://docs.mem0.ai/components/vectordbs/dbs/supabase) [OSS]: Use when Supabase with pgvector is the backing store.
- [Upstash Vector](https://docs.mem0.ai/components/vectordbs/dbs/upstash-vector) [OSS]: Use for serverless Upstash Vector.
- [Vectorize](https://docs.mem0.ai/components/vectordbs/dbs/vectorize) [OSS]: Use when the store is Cloudflare Vectorize.
- [Vertex AI Vector Search](https://docs.mem0.ai/components/vectordbs/dbs/vertex_ai) [OSS]: Use when the store is Google Cloud Vertex Vector Search.
- [Weaviate](https://docs.mem0.ai/components/vectordbs/dbs/weaviate) [OSS]: Use when Weaviate is the backing store.
- [FAISS](https://docs.mem0.ai/components/vectordbs/dbs/faiss) [OSS]: Use for local FAISS-based similarity search.
- [LangChain Vector Store](https://docs.mem0.ai/components/vectordbs/dbs/langchain) [OSS]: Use when the vector store is wrapped behind LangChain.
- [Baidu](https://docs.mem0.ai/components/vectordbs/dbs/baidu) [OSS]: Use when the user is on Baidu Cloud vector service.
- [Cassandra](https://docs.mem0.ai/components/vectordbs/dbs/cassandra) [OSS]: Use when Cassandra is the backing store.
- [S3 Vectors](https://docs.mem0.ai/components/vectordbs/dbs/s3_vectors) [OSS]: Use for AWS S3 Vectors.
- [Databricks](https://docs.mem0.ai/components/vectordbs/dbs/databricks) [OSS]: Use when the user is on Databricks with Delta Lake.
- [Neptune Analytics](https://docs.mem0.ai/components/vectordbs/dbs/neptune_analytics) [OSS]: Use when the user is on AWS Neptune Analytics (graph + vector).
- [Turbopuffer](https://docs.mem0.ai/components/vectordbs/dbs/turbopuffer) [OSS]: Use when the user is on Turbopuffer serverless.
### Rerankers [OSS]
- [Reranker Overview](https://docs.mem0.ai/components/rerankers/overview) [OSS]: Use when the user wants to improve OSS search result quality.
- [Reranker Configuration](https://docs.mem0.ai/components/rerankers/config) [OSS]: Use for the `reranker` config schema.
- [Reranker Optimization](https://docs.mem0.ai/components/rerankers/optimization) [OSS]: Use when tuning reranker performance.
- [Custom Reranker Prompts](https://docs.mem0.ai/components/rerankers/custom-prompts) [OSS]: Use when rewriting reranker prompts.
- [Cohere Reranker](https://docs.mem0.ai/components/rerankers/models/cohere) [OSS]: Use for Cohere Rerank.
- [Sentence Transformer Reranker](https://docs.mem0.ai/components/rerankers/models/sentence_transformer) [OSS]: Use for local cross-encoder rerankers.
- [Hugging Face Reranker](https://docs.mem0.ai/components/rerankers/models/huggingface) [OSS]: Use for HF-hosted reranker models.
- [LLM Reranker (prompt)](https://docs.mem0.ai/components/rerankers/models/llm) [OSS]: Use when the reranker is a prompted LLM (config guide).
- [LLM Reranker](https://docs.mem0.ai/components/rerankers/models/llm_reranker) [OSS]: Use when the reranker is a prompted LLM (implementation reference).
- [Zero Entropy Reranker](https://docs.mem0.ai/components/rerankers/models/zero_entropy) [OSS]: Use for the Zero Entropy reranker.
+4
View File
@@ -8,6 +8,10 @@ icon: "house"
Mem0 Open Source delivers the same adaptive memory engine as the platform, but packaged for teams that need to run everything on their own infrastructure. You own the stack, the data, and the customizations. Mem0 Open Source delivers the same adaptive memory engine as the platform, but packaged for teams that need to run everything on their own infrastructure. You own the stack, the data, and the customizations.
<Tip>
Mem0 v1.0.0 brought rerankers, async-by-default clients, and Azure OpenAI support. See the <Link href="/changelog">release notes</Link> for the full rundown before upgrading.
</Tip>
## What Mem0 OSS provides ## What Mem0 OSS provides
- **Full control**: Tune every component, from LLMs to vector stores, inside your environment. - **Full control**: Tune every component, from LLMs to vector stores, inside your environment.
+2
View File
@@ -3,6 +3,8 @@ title: Group Chat
description: 'Enable multi-participant conversations with automatic memory attribution to individual speakers' description: 'Enable multi-participant conversations with automatic memory attribution to individual speakers'
--- ---
<Snippet file="paper-release.mdx" />
## Overview ## Overview
The Group Chat feature enables Mem0 to process conversations involving multiple participants and automatically attribute memories to individual speakers. This allows for precise tracking of each participant's preferences, characteristics, and contributions in collaborative discussions, team meetings, or multi-agent conversations. The Group Chat feature enables Mem0 to process conversations involving multiple participants and automatically attribute memories to individual speakers. This allows for precise tracking of each participant's preferences, characteristics, and contributions in collaborative discussions, team meetings, or multi-agent conversations.
@@ -15,6 +15,10 @@ When working with large-scale memory stores, you need precise control over which
* **Time-based queries**: Retrieve memories within specific date ranges * **Time-based queries**: Retrieve memories within specific date ranges
* **Performance optimization**: Reduce query complexity by pre-filtering * **Performance optimization**: Reduce query complexity by pre-filtering
<Callout type="info" icon="info-circle" color="#7A5DFF">
Filters were introduced in v1.0.0 to provide precise control over memory retrieval.
</Callout>
## Filter structure ## Filter structure
Filters use a nested JSON structure with logical operators at the root: Filters use a nested JSON structure with logical operators at the root:
+4
View File
@@ -8,6 +8,10 @@ icon: "cloud"
Mem0 is the memory engine that keeps conversations contextual so users never repeat themselves and your agents respond with continuity. Mem0 Platform delivers that experience as a fully managed service—scaling, securing, and enriching memories without any infrastructure work on your side. Mem0 is the memory engine that keeps conversations contextual so users never repeat themselves and your agents respond with continuity. Mem0 Platform delivers that experience as a fully managed service—scaling, securing, and enriching memories without any infrastructure work on your side.
<Tip>
Mem0 v1.0.0 shipped rerankers, async-by-default behavior, and Azure OpenAI support. Catch the full list of changes in the <Link href="/changelog">release notes</Link>.
</Tip>
## Why it matters ## Why it matters
- **Personalized replies**: Memories persist across users and agents, cutting prompt bloat and repeat questions. - **Personalized replies**: Memories persist across users and agents, cutting prompt bloat and repeat questions.
+1 -1
View File
@@ -18,7 +18,7 @@ module.exports = {
moduleNameMapper: { moduleNameMapper: {
"^@/(.*)$": "<rootDir>/src/$1", "^@/(.*)$": "<rootDir>/src/$1",
}, },
setupFiles: ["dotenv/config", "<rootDir>/jest.setup.ts"], setupFiles: ["dotenv/config"],
testPathIgnorePatterns: ["/node_modules/", "/dist/"], testPathIgnorePatterns: ["/node_modules/", "/dist/"],
moduleFileExtensions: ["ts", "tsx", "js", "jsx", "json", "node"], moduleFileExtensions: ["ts", "tsx", "js", "jsx", "json", "node"],
globals: { globals: {
-3
View File
@@ -1,3 +0,0 @@
import pkg from "./package.json";
(globalThis as any).__MEM0_SDK_VERSION__ = pkg.version;
+1 -1
View File
@@ -1,6 +1,6 @@
{ {
"name": "mem0ai", "name": "mem0ai",
"version": "3.0.1", "version": "3.0.0",
"description": "The Memory Layer For Your AI Apps", "description": "The Memory Layer For Your AI Apps",
"main": "./dist/index.js", "main": "./dist/index.js",
"module": "./dist/index.mjs", "module": "./dist/index.mjs",
+1 -1
View File
@@ -1,7 +1,7 @@
// @ts-nocheck // @ts-nocheck
import type { TelemetryClient, TelemetryOptions } from "./telemetry.types"; import type { TelemetryClient, TelemetryOptions } from "./telemetry.types";
let version = __MEM0_SDK_VERSION__; let version = "2.1.36";
// Safely check for process.env in different environments // Safely check for process.env in different environments
let MEM0_TELEMETRY = true; let MEM0_TELEMETRY = true;
-1
View File
@@ -1 +0,0 @@
declare const __MEM0_SDK_VERSION__: string;
+1 -1
View File
@@ -4,7 +4,7 @@ import type {
TelemetryEventData, TelemetryEventData,
} from "./telemetry.types"; } from "./telemetry.types";
let version = __MEM0_SDK_VERSION__; let version = "2.1.34";
// Safely check for process.env in different environments // Safely check for process.env in different environments
let MEM0_TELEMETRY = true; let MEM0_TELEMETRY = true;
-7
View File
@@ -1,5 +1,4 @@
import { defineConfig } from "tsup"; import { defineConfig } from "tsup";
import pkg from "./package.json";
const external = [ const external = [
"openai", "openai",
@@ -24,10 +23,6 @@ const external = [
"natural", "natural",
]; ];
const define = {
__MEM0_SDK_VERSION__: JSON.stringify(pkg.version),
};
export default defineConfig([ export default defineConfig([
{ {
entry: ["src/client/index.ts"], entry: ["src/client/index.ts"],
@@ -35,7 +30,6 @@ export default defineConfig([
dts: true, dts: true,
sourcemap: true, sourcemap: true,
external, external,
define,
}, },
{ {
entry: ["src/oss/src/index.ts"], entry: ["src/oss/src/index.ts"],
@@ -44,6 +38,5 @@ export default defineConfig([
dts: true, dts: true,
sourcemap: true, sourcemap: true,
external, external,
define,
}, },
]); ]);
+1 -4
View File
@@ -13,10 +13,7 @@ class FastEmbedEmbedding(EmbeddingBase):
super().__init__(config) super().__init__(config)
self.config.model = self.config.model or "thenlper/gte-large" self.config.model = self.config.model or "thenlper/gte-large"
self.dense_model = TextEmbedding(model_name=self.config.model) self.dense_model = TextEmbedding(model_name = self.config.model)
if not self.config.embedding_dims:
self.config.embedding_dims = self.dense_model.embedding_size
def embed(self, text, memory_action: Optional[Literal["add", "search", "update"]] = None): def embed(self, text, memory_action: Optional[Literal["add", "search", "update"]] = None):
""" """
-147
View File
@@ -1,147 +0,0 @@
#!/usr/bin/env python3
"""Check docs/llms.txt coverage against docs/**/*.mdx.
Two-way diff:
- pages present in docs/ but not linked in docs/llms.txt -> "missing"
- URLs linked in docs/llms.txt that point to no page -> "stale"
Modes:
default read-only; exits 1 if any drift is found.
--write appends placeholder entries for missing pages under a
"## Unclassified - needs triage" H2 at the end of
docs/llms.txt. Stale URLs are reported but never removed
automatically (human decides whether a page was renamed
or genuinely deleted). Exits 1 if anything was written,
0 if the file was already in sync.
Exit codes:
0 in sync, or --write mode completed (workflow continues to open a PR)
1 read-only drift detected
The script has no third-party dependencies; stdlib only.
"""
from __future__ import annotations
import argparse
import pathlib
import re
import sys
REPO_ROOT = pathlib.Path(__file__).resolve().parents[1]
DOCS_DIR = REPO_ROOT / "docs"
LLMS_TXT = DOCS_DIR / "llms.txt"
IGNORE_FILE = REPO_ROOT / "scripts" / "llms-txt-ignore.txt"
BASE_URL = "https://docs.mem0.ai/"
TRIAGE_HEADER = "## Unclassified - needs triage"
URL_RE = re.compile(r"\(https://docs\.mem0\.ai/([^)\s#]*)")
def load_ignore_prefixes() -> list[str]:
if not IGNORE_FILE.exists():
return []
prefixes: list[str] = []
for raw in IGNORE_FILE.read_text().splitlines():
line = raw.strip()
if line and not line.startswith("#"):
prefixes.append(line)
return prefixes
def canonical_repo_pages(ignore_prefixes: list[str]) -> tuple[set[str], set[str]]:
all_pages: set[str] = set()
included_pages: set[str] = set()
for path in DOCS_DIR.rglob("*.mdx"):
rel = path.relative_to(DOCS_DIR).with_suffix("").as_posix()
all_pages.add(rel)
if not any(rel.startswith(p) for p in ignore_prefixes):
included_pages.add(rel)
return all_pages, included_pages
def indexed_urls(text: str) -> set[str]:
urls: set[str] = set()
for match in URL_RE.finditer(text):
path = match.group(1).rstrip("/")
if path:
urls.add(path)
return urls
def format_placeholder(page: str) -> str:
title = page.rsplit("/", 1)[-1].replace("-", " ").replace("_", " ").title()
return (
f"- [{title}]({BASE_URL}{page}) [TODO: Platform|OSS|Both]: "
"TODO - rewrite as 'Use when ...' and move into the correct section."
)
def append_triage_block(text: str, missing_pages: list[str]) -> str:
entries = "\n".join(format_placeholder(p) for p in missing_pages)
if TRIAGE_HEADER in text:
return text.rstrip() + "\n" + entries + "\n"
preamble = (
"> New docs pages were detected by CI. For each entry below: replace "
"the scope tag with `[Platform]`, `[OSS]`, or `[Both]`; rewrite the "
"description as `Use when ...`; move it into the correct section; "
"then delete this H2 once empty.\n"
)
return text.rstrip() + "\n\n" + TRIAGE_HEADER + "\n\n" + preamble + "\n" + entries + "\n"
def main() -> int:
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument(
"--write",
action="store_true",
help="scaffold placeholder entries in docs/llms.txt for missing pages",
)
args = parser.parse_args()
if not LLMS_TXT.exists():
print(f"ERROR: {LLMS_TXT} not found.", file=sys.stderr)
return 1
ignore_prefixes = load_ignore_prefixes()
all_pages, included_pages = canonical_repo_pages(ignore_prefixes)
text = LLMS_TXT.read_text()
linked = indexed_urls(text)
missing = sorted(included_pages - linked)
stale = sorted(linked - all_pages)
if missing:
print(f"Pages missing from docs/llms.txt ({len(missing)}):")
for p in missing:
print(f" + {p}")
if stale:
print(f"\nURLs in docs/llms.txt with no matching .mdx page ({len(stale)}):")
for p in stale:
print(f" - {p}")
print(
"\n(Stale URLs are never auto-removed: check whether the page was "
"renamed, and update the link by hand.)"
)
if not missing and not stale:
print("docs/llms.txt is in sync with docs/**/*.mdx.")
return 0
if args.write:
if missing:
new_text = append_triage_block(text, missing)
LLMS_TXT.write_text(new_text)
print(
f"\nAppended {len(missing)} placeholder entries under "
f"'{TRIAGE_HEADER}' in docs/llms.txt."
)
else:
print("\nNo additions to scaffold; stale URLs surfaced above require manual cleanup.")
return 0
return 1
if __name__ == "__main__":
sys.exit(main())
-11
View File
@@ -1,11 +0,0 @@
# Page path prefixes (relative to docs/, without .mdx) that intentionally
# stay out of docs/llms.txt. One prefix per line. Lines starting with '#'
# are comments.
#
# Why each prefix is here:
# _snippets/ — reusable MDX fragments, not standalone pages
# templates/ — authoring templates for new docs, not user-facing
# changelog/ — versioned release notes; one rollup link lives in the index
_snippets/
templates/
changelog/
+2 -1
View File
@@ -12,7 +12,7 @@ description: >
license: Apache-2.0 license: Apache-2.0
metadata: metadata:
author: mem0ai author: mem0ai
version: "1.1.0" version: "1.0.0"
category: ai-memory category: ai-memory
tags: "cli, terminal, memory, ai, command-line" tags: "cli, terminal, memory, ai, command-line"
compatibility: Node.js 18+ (npm install -g @mem0/cli) or Python 3.10+ (pip install mem0-cli), MEM0_API_KEY env var compatibility: Node.js 18+ (npm install -g @mem0/cli) or Python 3.10+ (pip install mem0-cli), MEM0_API_KEY env var
@@ -134,6 +134,7 @@ Choose whichever runtime you already have installed. The behavior is the same.
- **`--all` vs `--entity` delete modes:** `mem0 delete --all -u alice` deletes all memories for user alice. `mem0 delete --entity -u alice` deletes the entity itself AND all its memories (cascade). These are mutually exclusive modes. - **`--all` vs `--entity` delete modes:** `mem0 delete --all -u alice` deletes all memories for user alice. `mem0 delete --entity -u alice` deletes the entity itself AND all its memories (cascade). These are mutually exclusive modes.
- **Entity ID resolution:** If you pass any explicit scope flag (e.g. `--user-id`), the CLI uses ONLY the explicit IDs and ignores config defaults. If no scope flags are given, all configured defaults apply. - **Entity ID resolution:** If you pass any explicit scope flag (e.g. `--user-id`), the CLI uses ONLY the explicit IDs and ignores config defaults. If no scope flags are given, all configured defaults apply.
- **Stdin detection:** When no text argument is provided and input is piped (not a TTY), the CLI reads from stdin. Works with `add`, `search`, and `update`. - **Stdin detection:** When no text argument is provided and input is piped (not a TTY), the CLI reads from stdin. Works with `add`, `search`, and `update`.
- **Graph tri-state:** `--no-graph` takes precedence over `--graph`, which takes precedence over the config default (`defaults.enable_graph`).
## References ## References
@@ -77,8 +77,12 @@ Add a memory from text, messages, file, or stdin.
| `--messages <json>` | string | - | Conversation messages as JSON array (e.g. `'[{"role":"user","content":"..."}]'`). | | `--messages <json>` | string | - | Conversation messages as JSON array (e.g. `'[{"role":"user","content":"..."}]'`). |
| `-f, --file <path>` | path | - | Read messages from a JSON file. | | `-f, --file <path>` | path | - | Read messages from a JSON file. |
| `-m, --metadata <json>` | string | - | Custom metadata as JSON object (e.g. `'{"source":"cli"}'`). | | `-m, --metadata <json>` | string | - | Custom metadata as JSON object (e.g. `'{"source":"cli"}'`). |
| `--immutable` | boolean | false | Prevent future updates to this memory. |
| `--no-infer` | boolean | false | Skip inference; store the text verbatim. | | `--no-infer` | boolean | false | Skip inference; store the text verbatim. |
| `--expires <date>` | string | - | Expiration date in `YYYY-MM-DD` format. |
| `--categories <cats>` | string | - | Categories as JSON array or comma-separated string. | | `--categories <cats>` | string | - | Categories as JSON array or comma-separated string. |
| `--graph` | boolean | false | Enable graph memory extraction for this call. |
| `--no-graph` | boolean | false | Disable graph memory extraction for this call. |
| `-o, --output <fmt>` | string | `text` | Output format: `text`, `json`, `quiet`. | | `-o, --output <fmt>` | string | `text` | Output format: `text`, `json`, `quiet`. |
**Input priority:** `--file` > `--messages` > text argument > stdin (if piped and no text). **Input priority:** `--file` > `--messages` > text argument > stdin (if piped and no text).
@@ -130,10 +134,13 @@ Search memories by semantic query.
| `--app-id <id>` | string | - | Filter by app. | | `--app-id <id>` | string | - | Filter by app. |
| `--run-id <id>` | string | - | Filter by run. | | `--run-id <id>` | string | - | Filter by run. |
| `-k, --top-k, --limit <n>` | integer | 10 | Maximum number of results to return. | | `-k, --top-k, --limit <n>` | integer | 10 | Maximum number of results to return. |
| `--threshold <score>` | float | 0.1 | Minimum similarity score (0.0 to 1.0). | | `--threshold <score>` | float | 0.3 | Minimum similarity score (0.0 to 1.0). |
| `--rerank` | boolean | false | Enable reranking for improved relevance (Platform only). | | `--rerank` | boolean | false | Enable reranking for improved relevance (Platform only). |
| `--keyword` | boolean | false | Use keyword search instead of semantic. |
| `--filter <json>` | string | - | Advanced filter expression as JSON (AND/OR operators). | | `--filter <json>` | string | - | Advanced filter expression as JSON (AND/OR operators). |
| `--fields <list>` | string | - | Comma-separated list of fields to return. | | `--fields <list>` | string | - | Comma-separated list of fields to return. |
| `--graph` | boolean | false | Enable graph in search. |
| `--no-graph` | boolean | false | Disable graph in search. |
| `-o, --output <fmt>` | string | `text` | Output format: `text`, `json`, `table`. | | `-o, --output <fmt>` | string | `text` | Output format: `text`, `json`, `table`. |
**Examples:** **Examples:**
@@ -193,6 +200,8 @@ List memories with optional filters and pagination.
| `--category <name>` | string | - | Filter by category. | | `--category <name>` | string | - | Filter by category. |
| `--after <date>` | string | - | Created after (YYYY-MM-DD). | | `--after <date>` | string | - | Created after (YYYY-MM-DD). |
| `--before <date>` | string | - | Created before (YYYY-MM-DD). | | `--before <date>` | string | - | Created before (YYYY-MM-DD). |
| `--graph` | boolean | false | Enable graph in listing. |
| `--no-graph` | boolean | false | Disable graph in listing. |
| `-o, --output <fmt>` | string | `table` | Output format: `text`, `json`, `table`. | | `-o, --output <fmt>` | string | `table` | Output format: `text`, `json`, `table`. |
**Examples:** **Examples:**
@@ -364,7 +373,7 @@ Get a single configuration value.
|------|------|----------|-------------| |------|------|----------|-------------|
| `key` | string | Yes | Dotted config key (e.g. `platform.api_key`, `defaults.user_id`). | | `key` | string | Yes | Dotted config key (e.g. `platform.api_key`, `defaults.user_id`). |
**Valid keys:** `platform.api_key`, `platform.base_url`, `defaults.user_id`, `defaults.agent_id`, `defaults.app_id`, `defaults.run_id`. **Valid keys:** `platform.api_key`, `platform.base_url`, `defaults.user_id`, `defaults.agent_id`, `defaults.app_id`, `defaults.run_id`, `defaults.enable_graph`.
API key values are always redacted in output. API key values are always redacted in output.
@@ -395,6 +404,7 @@ Set a configuration value.
```bash ```bash
mem0 config set defaults.user_id alice mem0 config set defaults.user_id alice
mem0 config set platform.base_url https://api.mem0.ai mem0 config set platform.base_url https://api.mem0.ai
mem0 config set defaults.enable_graph true
``` ```
--- ---
@@ -628,6 +638,20 @@ This applies to commands with `resolveIds: true`: `add`, `search`, `list`, `dele
--- ---
## Graph Tri-State
The `enable_graph` parameter follows a three-level precedence:
```
--no-graph (explicit disable) > --graph (explicit enable) > config default
```
If `--no-graph` is passed, graph is disabled regardless of other settings. If `--graph` is passed (without `--no-graph`), graph is enabled. If neither is passed, the config value `defaults.enable_graph` is used.
This applies to commands with `resolveGraph: true`: `add`, `search`, `list`.
---
## Filter Building ## Filter Building
For `search` and `list`, entity IDs and additional filters are composed into the API filter structure: For `search` and `list`, entity IDs and additional filters are composed into the API filter structure:
+23 -3
View File
@@ -24,7 +24,8 @@ The restricted permissions ensure API keys are not world-readable.
"user_id": "", "user_id": "",
"agent_id": "", "agent_id": "",
"app_id": "", "app_id": "",
"run_id": "" "run_id": "",
"enable_graph": false
}, },
"platform": { "platform": {
"api_key": "", "api_key": "",
@@ -42,6 +43,7 @@ The restricted permissions ensure API keys are not world-readable.
| `defaults.agent_id` | string | `""` | Default agent ID for scoping commands. | | `defaults.agent_id` | string | `""` | Default agent ID for scoping commands. |
| `defaults.app_id` | string | `""` | Default app ID for scoping commands. | | `defaults.app_id` | string | `""` | Default app ID for scoping commands. |
| `defaults.run_id` | string | `""` | Default run ID for scoping commands. | | `defaults.run_id` | string | `""` | Default run ID for scoping commands. |
| `defaults.enable_graph` | boolean | `false` | Default graph memory extraction toggle. |
| `platform.api_key` | string | `""` | API key for the Mem0 Platform. | | `platform.api_key` | string | `""` | API key for the Mem0 Platform. |
| `platform.base_url` | string | `"https://api.mem0.ai"` | Base URL for API requests. | | `platform.base_url` | string | `"https://api.mem0.ai"` | Base URL for API requests. |
@@ -125,6 +127,7 @@ Reads a single configuration value. The key uses dotted notation.
```bash ```bash
mem0 config get platform.api_key # prints: m0-x...xxxx (redacted) mem0 config get platform.api_key # prints: m0-x...xxxx (redacted)
mem0 config get defaults.user_id # prints: alice mem0 config get defaults.user_id # prints: alice
mem0 config get defaults.enable_graph # prints: false
``` ```
**Valid keys:** **Valid keys:**
@@ -134,6 +137,7 @@ mem0 config get defaults.user_id # prints: alice
- `defaults.agent_id` - `defaults.agent_id`
- `defaults.app_id` - `defaults.app_id`
- `defaults.run_id` - `defaults.run_id`
- `defaults.enable_graph`
Unknown keys print an error message. Unknown keys print an error message.
@@ -144,6 +148,7 @@ Sets a configuration value and saves the config file.
```bash ```bash
mem0 config set defaults.user_id alice mem0 config set defaults.user_id alice
mem0 config set platform.base_url https://api.mem0.ai mem0 config set platform.base_url https://api.mem0.ai
mem0 config set defaults.enable_graph true
``` ```
**Type coercion:** **Type coercion:**
@@ -173,6 +178,20 @@ Environment variables override config file values but are overridden by CLI flag
| `MEM0_AGENT_ID` | `defaults.agent_id` | string | `""` | | `MEM0_AGENT_ID` | `defaults.agent_id` | string | `""` |
| `MEM0_APP_ID` | `defaults.app_id` | string | `""` | | `MEM0_APP_ID` | `defaults.app_id` | string | `""` |
| `MEM0_RUN_ID` | `defaults.run_id` | string | `""` | | `MEM0_RUN_ID` | `defaults.run_id` | string | `""` |
| `MEM0_ENABLE_GRAPH` | `defaults.enable_graph` | boolean | `false` |
### Boolean Parsing for `MEM0_ENABLE_GRAPH`
Accepted truthy values (case-insensitive): `"true"`, `"1"`, `"yes"`. Everything else is treated as `false`.
```bash
export MEM0_ENABLE_GRAPH=true # enabled
export MEM0_ENABLE_GRAPH=1 # enabled
export MEM0_ENABLE_GRAPH=yes # enabled
export MEM0_ENABLE_GRAPH=false # disabled
export MEM0_ENABLE_GRAPH=0 # disabled
export MEM0_ENABLE_GRAPH="" # disabled
```
--- ---
@@ -181,8 +200,8 @@ Environment variables override config file values but are overridden by CLI flag
Configuration values are resolved in this order (highest priority first): Configuration values are resolved in this order (highest priority first):
``` ```
1. CLI flags --api-key, --user-id, --base-url, etc. 1. CLI flags --api-key, --user-id, --base-url, --graph, --no-graph, etc.
2. Environment vars MEM0_API_KEY, MEM0_USER_ID, etc. 2. Environment vars MEM0_API_KEY, MEM0_USER_ID, MEM0_ENABLE_GRAPH, etc.
3. Config file ~/.mem0/config.json 3. Config file ~/.mem0/config.json
4. Defaults Hardcoded defaults (empty strings, false, https://api.mem0.ai) 4. Defaults Hardcoded defaults (empty strings, false, https://api.mem0.ai)
``` ```
@@ -222,3 +241,4 @@ The `config get` and `config set` commands use dotted key paths. Here is the ful
| `defaults.agent_id` | defaults | agent_id | | `defaults.agent_id` | defaults | agent_id |
| `defaults.app_id` | defaults | app_id | | `defaults.app_id` | defaults | app_id |
| `defaults.run_id` | defaults | run_id | | `defaults.run_id` | defaults | run_id |
| `defaults.enable_graph` | defaults | enable_graph |
+11 -10
View File
@@ -12,7 +12,7 @@ description: >
license: Apache-2.0 license: Apache-2.0
metadata: metadata:
author: mem0ai author: mem0ai
version: "1.1.0" version: "1.0.0"
category: ai-memory category: ai-memory
tags: "vercel, ai-sdk, memory, nextjs, typescript, provider" tags: "vercel, ai-sdk, memory, nextjs, typescript, provider"
compatibility: Node.js 18+, npm install @mem0/vercel-ai-provider, Vercel AI SDK v5 (ai package), MEM0_API_KEY + LLM provider API key compatibility: Node.js 18+, npm install @mem0/vercel-ai-provider, Vercel AI SDK v5 (ai package), MEM0_API_KEY + LLM provider API key
@@ -47,16 +47,16 @@ import { createMem0 } from "@mem0/vercel-ai-provider";
const mem0 = createMem0(); const mem0 = createMem0();
const { text } = await generateText({ const { text } = await generateText({
model: mem0("gpt-5-mini", { user_id: "alice" }), model: mem0("gpt-4-turbo", { user_id: "alice" }),
prompt: "Recommend a restaurant", prompt: "Recommend a restaurant",
}); });
``` ```
What happens under the hood: What happens under the hood:
1. The prompt is sent to Mem0 search (`POST /v3/memories/search/`) to retrieve relevant memories 1. The prompt is sent to Mem0 search (`POST /v2/memories/search/`) to retrieve relevant memories
2. Retrieved memories are injected as a system message at the start of the prompt 2. Retrieved memories are injected as a system message at the start of the prompt
3. The underlying LLM (e.g., OpenAI gpt-5-mini) generates a response using the enriched prompt 3. The underlying LLM (e.g., OpenAI gpt-4-turbo) generates a response using the enriched prompt
4. The conversation is stored back to Mem0 (`POST /v3/memories/add/`) as a fire-and-forget async call (no await) 4. The conversation is stored back to Mem0 (`POST /v1/memories/`) as a fire-and-forget async call (no await)
## Pattern 2: Standalone Utilities ## Pattern 2: Standalone Utilities
@@ -77,7 +77,7 @@ const memories = await retrieveMemories(prompt, {
// Generate using any provider with injected memories // Generate using any provider with injected memories
const { text } = await generateText({ const { text } = await generateText({
model: openai("gpt-5-mini"), model: openai("gpt-4-turbo"),
prompt, prompt,
system: memories, system: memories,
}); });
@@ -102,7 +102,7 @@ import { createMem0 } from "@mem0/vercel-ai-provider";
const mem0 = createMem0(); const mem0 = createMem0();
const result = streamText({ const result = streamText({
model: mem0("gpt-5-mini", { user_id: "alice" }), model: mem0("gpt-4-turbo", { user_id: "alice" }),
prompt: "What should I cook for dinner?", prompt: "What should I cook for dinner?",
}); });
@@ -128,7 +128,7 @@ Select a provider when creating the Mem0 instance:
```typescript ```typescript
const mem0 = createMem0({ provider: "anthropic" }); const mem0 = createMem0({ provider: "anthropic" });
const { text } = await generateText({ const { text } = await generateText({
model: mem0("gpt-5-mini", { user_id: "alice" }), model: mem0("claude-sonnet-4-20250514", { user_id: "alice" }),
prompt: "Hello!", prompt: "Hello!",
}); });
``` ```
@@ -139,7 +139,7 @@ const { text } = await generateText({
``` ```
User prompt User prompt
--> searchInternalMemories (POST /v3/memories/search/) --> searchInternalMemories (POST /v2/memories/search/)
--> memories injected as system message at start of prompt --> memories injected as system message at start of prompt
--> underlying LLM generates response (doGenerate or doStream) --> underlying LLM generates response (doGenerate or doStream)
--> processMemories fires addMemories as fire-and-forget (no await) --> processMemories fires addMemories as fire-and-forget (no await)
@@ -161,7 +161,7 @@ User controls each step:
| Function | Returns | Use when | | Function | Returns | Use when |
|----------|---------|----------| |----------|---------|----------|
| `retrieveMemories` | Formatted system prompt **string** | Injecting directly into `system` parameter | | `retrieveMemories` | Formatted system prompt **string** | Injecting directly into `system` parameter |
| `getMemories` | Raw memory **array** | Processing memories programmatically | | `getMemories` | Raw memory **array** (or full response if `enable_graph`) | Processing memories programmatically |
| `searchMemories` | Full search **response** (results + relations) | Need relations, scores, metadata | | `searchMemories` | Full search **response** (results + relations) | Need relations, scores, metadata |
| `addMemories` | API response | Storing new messages to Mem0 | | `addMemories` | API response | Storing new messages to Mem0 |
@@ -171,6 +171,7 @@ All four accept `LanguageModelV2Prompt | string` as the first argument and optio
- **Always provide `user_id`** (or `agent_id`/`app_id`/`run_id`) for consistent memory retrieval. Without an entity identifier, memories cannot be scoped. - **Always provide `user_id`** (or `agent_id`/`app_id`/`run_id`) for consistent memory retrieval. Without an entity identifier, memories cannot be scoped.
- **Standalone utilities require explicit API key**: pass `mem0ApiKey` in the config object, or set the `MEM0_API_KEY` environment variable. - **Standalone utilities require explicit API key**: pass `mem0ApiKey` in the config object, or set the `MEM0_API_KEY` environment variable.
- **Graph memories**: set `enable_graph: true` in the config to retrieve graph relations alongside text memories. When enabled, `getMemories` returns the full response (with `results` and `relations`), not just the array.
- **This uses Vercel AI SDK v5** (LanguageModelV2 / ProviderV2 interfaces). It is not compatible with AI SDK v3 or v4. - **This uses Vercel AI SDK v5** (LanguageModelV2 / ProviderV2 interfaces). It is not compatible with AI SDK v3 or v4.
- **`processMemories` fires `addMemories` as fire-and-forget** (`.then()` without `await`). Memory storage happens asynchronously and does not block the LLM response. - **`processMemories` fires `addMemories` as fire-and-forget** (`.then()` without `await`). Memory storage happens asynchronously and does not block the LLM response.
- **The `"gemini"` alias** exists in the provider switch but is NOT in the `supportedProviders` list. Use `"google"` instead. - **The `"gemini"` alias** exists in the provider switch but is NOT in the `supportedProviders` list. Use `"google"` instead.
@@ -79,7 +79,8 @@ async function retrieveMemories(
1. Flattens the prompt to a plain string (extracts text from `LanguageModelV2Prompt` parts) 1. Flattens the prompt to a plain string (extracts text from `LanguageModelV2Prompt` parts)
2. Calls `searchInternalMemories` (`POST /v2/memories/search/`) 2. Calls `searchInternalMemories` (`POST /v2/memories/search/`)
3. Formats each memory as `"Memory: {memory.memory}\n\n"` 3. Formats each memory as `"Memory: {memory.memory}\n\n"`
4. Wraps everything in a system prompt preamble 4. If `enable_graph: true`, also appends graph relations as `"Relation: {source} -> {relationship} -> {target}\n\n"`
5. Wraps everything in a system prompt preamble
**Returns:** A **string** containing the formatted system prompt with embedded memories. Returns `""` (empty string) if no memories found. **Returns:** A **string** containing the formatted system prompt with embedded memories. Returns `""` (empty string) if no memories found.
@@ -90,13 +91,17 @@ System Message: These are the memories I have stored. Give more weightage to the
Memory: User loves Italian food Memory: User loves Italian food
Memory: User is vegetarian Memory: User is vegetarian
HERE ARE THE GRAPHS RELATIONS FOR THE PREFERENCES OF THE USER:
Relation: Alice -> likes -> Italian cuisine
``` ```
--- ---
## `getMemories(prompt, config?)` ## `getMemories(prompt, config?)`
Retrieves memories and returns the **raw memory array**. Retrieves memories and returns the **raw memory array** (or full response if graph is enabled).
```typescript ```typescript
import { getMemories } from "@mem0/vercel-ai-provider"; import { getMemories } from "@mem0/vercel-ai-provider";
@@ -106,6 +111,14 @@ const memories = await getMemories("What are my preferences?", {
mem0ApiKey: "m0-xxx", mem0ApiKey: "m0-xxx",
}); });
// Returns: [{ memory: "User loves Italian food", id: "...", ... }, ...] // Returns: [{ memory: "User loves Italian food", id: "...", ... }, ...]
// With graph enabled:
const graphMemories = await getMemories("What are my preferences?", {
user_id: "alice",
mem0ApiKey: "m0-xxx",
enable_graph: true,
});
// Returns: { results: [...], relations: [...] }
``` ```
**Signature:** **Signature:**
@@ -127,9 +140,10 @@ async function getMemories(
**Behavior:** **Behavior:**
1. Flattens the prompt to a plain string 1. Flattens the prompt to a plain string
2. Calls `searchInternalMemories` (`POST /v2/memories/search/`) 2. Calls `searchInternalMemories` (`POST /v2/memories/search/`)
3. Returns `memories.results` (the array of memory objects) 3. If `enable_graph` is **not** set: returns `memories.results` (the array of memory objects)
4. If `enable_graph` is set: returns the full response object (with both `results` and `relations`)
**Returns:** Memory object array. **Returns:** Memory object array, or full response object when graph is enabled.
--- ---
@@ -170,7 +184,7 @@ async function searchMemories(
**Returns:** The complete API response object. On error, returns `[]`. **Returns:** The complete API response object. On error, returns `[]`.
**Note:** Unlike `getMemories`, this always returns the full response. **Note:** Unlike `getMemories`, this always returns the full response regardless of `enable_graph` setting.
--- ---
@@ -179,8 +193,8 @@ async function searchMemories(
| Function | Returns | Use when | | Function | Returns | Use when |
|----------|---------|----------| |----------|---------|----------|
| `retrieveMemories` | Formatted system prompt **string** | Injecting directly into a `system` parameter for `generateText`/`streamText` | | `retrieveMemories` | Formatted system prompt **string** | Injecting directly into a `system` parameter for `generateText`/`streamText` |
| `getMemories` | Memory **array** | Processing memories programmatically (filtering, transforming, counting) | | `getMemories` | Memory **array** (or full response if `enable_graph`) | Processing memories programmatically (filtering, transforming, counting) |
| `searchMemories` | Full API **response** (results + relations) | Need relations, similarity scores, or complete metadata | | `searchMemories` | Full API **response** (results + relations) | Need relations, similarity scores, or complete metadata regardless of graph setting |
| `addMemories` | API response | Storing new conversation messages as memories | | `addMemories` | API response | Storing new conversation messages as memories |
## Internal: `searchInternalMemories(query, config?, top_k?)` ## Internal: `searchInternalMemories(query, config?, top_k?)`
@@ -196,13 +210,15 @@ async function searchInternalMemories(
``` ```
**Behavior:** **Behavior:**
1. Builds a `filters` object from entity identifiers (`user_id`, `app_id`, `agent_id`, `run_id`) 1. Builds an `OR` filter from entity identifiers (`user_id`, `app_id`, `agent_id`, `run_id`)
2. Resolves entity identifiers 2. Resolves org/project identifiers (`org_id` takes precedence over `org_name`)
3. Loads the API key from `config.mem0ApiKey` or `MEM0_API_KEY` env var 3. Loads the API key from `config.mem0ApiKey` or `MEM0_API_KEY` env var
4. Calls `POST {host}/v2/memories/search/` with: 4. Calls `POST {host}/v2/memories/search/` with:
- `query`: the search string - `query`: the search string
- `filters`: the filter object with entity identifiers - `filters`: the OR filter object
- `top_k`: from config or default 5 - `top_k`: from config or default 5
- `version`: `"v2"`
- `output_format`: `"v1.1"`
- All other config fields spread into the request body - All other config fields spread into the request body
**Default host:** `https://api.mem0.ai` **Default host:** `https://api.mem0.ai`
@@ -248,6 +264,10 @@ All fields are optional. Used across all utility functions.
| `app_id` | `string` | -- | Scope memories to an application | | `app_id` | `string` | -- | Scope memories to an application |
| `agent_id` | `string` | -- | Scope memories to an agent | | `agent_id` | `string` | -- | Scope memories to an agent |
| `run_id` | `string` | -- | Scope memories to a session/run | | `run_id` | `string` | -- | Scope memories to a session/run |
| `org_name` | `string` | -- | Organization name (fallback if `org_id` not set) |
| `project_name` | `string` | -- | Project name (fallback if `org_id` not set) |
| `org_id` | `string` | -- | Organization ID (takes precedence) |
| `project_id` | `string` | -- | Project ID |
| `metadata` | `Record<string, any>` | -- | Custom metadata | | `metadata` | `Record<string, any>` | -- | Custom metadata |
| `filters` | `Record<string, any>` | -- | Custom search filters | | `filters` | `Record<string, any>` | -- | Custom search filters |
| `infer` | `boolean` | -- | Enable inference | | `infer` | `boolean` | -- | Enable inference |
@@ -257,4 +277,8 @@ All fields are optional. Used across all utility functions.
| `top_k` | `number` | `5` | Number of memories to retrieve | | `top_k` | `number` | `5` | Number of memories to retrieve |
| `threshold` | `number` | -- | Minimum similarity score | | `threshold` | `number` | -- | Minimum similarity score |
| `rerank` | `boolean` | -- | Enable re-ranking | | `rerank` | `boolean` | -- | Enable re-ranking |
| `enable_graph` | `boolean` | -- | Enable graph memory (relations) |
| `host` | `string` | `https://api.mem0.ai` | Custom API host | | `host` | `string` | `https://api.mem0.ai` | Custom API host |
| `output_format` | `string` | -- | Output format version |
| `filter_memories` | `boolean` | -- | Enable memory filtering |
| `async_mode` | `boolean` | -- | Enable async processing |
@@ -9,8 +9,8 @@ Factory function that creates a `Mem0Provider` instance. This is the primary ent
```typescript ```typescript
import { createMem0 } from "@mem0/vercel-ai-provider"; import { createMem0 } from "@mem0/vercel-ai-provider";
const mem0 = createMem0(); // defaults: provider "openai" const mem0 = createMem0(); // defaults: provider "openai"
const mem0 = createMem0({ provider: "anthropic" }); // use Anthropic as LLM backend const mem0 = createMem0({ provider: "anthropic" }); // use Anthropic as LLM backend
``` ```
**Signature:** **Signature:**
@@ -39,7 +39,7 @@ interface Mem0Provider extends ProviderV2 {
} }
``` ```
- **Direct call** (`mem0("gpt-5-mini", {...})`): creates a generic language model (neither chat nor completion mode forced). - **Direct call** (`mem0("gpt-4-turbo", {...})`): creates a generic language model (neither chat nor completion mode forced).
- **`chat()`**: creates a model with `modelType: "chat"` (note: in the current source, the chat constructor sets `modelType: "completion"` -- this appears to be a bug; functionally equivalent to `completion()` at present). - **`chat()`**: creates a model with `modelType: "chat"` (note: in the current source, the chat constructor sets `modelType: "completion"` -- this appears to be a bug; functionally equivalent to `completion()` at present).
- **`completion()`**: creates a model with `modelType: "completion"`. - **`completion()`**: creates a model with `modelType: "completion"`.
- **`languageModel()`**: alias for the generic model (same as direct call). - **`languageModel()`**: alias for the generic model (same as direct call).
@@ -73,7 +73,7 @@ interface Mem0ProviderSettings {
| `provider` | Which LLM backend to use | `"openai"`, `"anthropic"`, `"google"`, `"groq"`, `"cohere"` | | `provider` | Which LLM backend to use | `"openai"`, `"anthropic"`, `"google"`, `"groq"`, `"cohere"` |
| `mem0ApiKey` | Mem0 Platform API key | `"m0-xxx"` | | `mem0ApiKey` | Mem0 Platform API key | `"m0-xxx"` |
| `apiKey` | LLM provider API key | `"sk-xxx"` (OpenAI), `"sk-ant-xxx"` (Anthropic) | | `apiKey` | LLM provider API key | `"sk-xxx"` (OpenAI), `"sk-ant-xxx"` (Anthropic) |
| `mem0Config` | Default Mem0 settings for all calls | `{ user_id: "alice" }` | | `mem0Config` | Default Mem0 settings for all calls | `{ user_id: "alice", enable_graph: true }` |
| `config` | Provider-specific SDK settings | `{ organization: "org-xxx" }` for OpenAI | | `config` | Provider-specific SDK settings | `{ organization: "org-xxx" }` for OpenAI |
| `baseURL` | Override LLM provider base URL | `"https://my-proxy.example.com"` | | `baseURL` | Override LLM provider base URL | `"https://my-proxy.example.com"` |
@@ -85,7 +85,7 @@ A pre-configured instance using default settings (OpenAI provider, no API keys s
import { mem0 } from "@mem0/vercel-ai-provider"; import { mem0 } from "@mem0/vercel-ai-provider";
const { text } = await generateText({ const { text } = await generateText({
model: mem0("gpt-5-mini", { user_id: "alice" }), model: mem0("gpt-4-turbo", { user_id: "alice" }),
prompt: "Hello", prompt: "Hello",
}); });
``` ```
@@ -102,6 +102,10 @@ interface Mem0ConfigSettings {
app_id?: string; // Scope memories to an application app_id?: string; // Scope memories to an application
agent_id?: string; // Scope memories to an agent agent_id?: string; // Scope memories to an agent
run_id?: string; // Scope memories to a specific run/session run_id?: string; // Scope memories to a specific run/session
org_name?: string; // Organization name (used if org_id not set)
project_name?: string; // Project name (used if org_id not set)
org_id?: string; // Organization ID (takes precedence over org_name)
project_id?: string; // Project ID (takes precedence over project_name)
metadata?: Record<string, any>; // Custom metadata attached to memories metadata?: Record<string, any>; // Custom metadata attached to memories
filters?: Record<string, any>; // Custom filters for memory search filters?: Record<string, any>; // Custom filters for memory search
infer?: boolean; // Enable inference during memory operations infer?: boolean; // Enable inference during memory operations
@@ -109,9 +113,13 @@ interface Mem0ConfigSettings {
page_size?: number; // Pagination: results per page page_size?: number; // Pagination: results per page
mem0ApiKey?: string; // Mem0 API key (overrides provider-level key) mem0ApiKey?: string; // Mem0 API key (overrides provider-level key)
top_k?: number; // Number of memories to retrieve (default: 5) top_k?: number; // Number of memories to retrieve (default: 5)
threshold?: number; // Minimum similarity score for retrieval (default: 0.1) threshold?: number; // Minimum similarity score for retrieval
rerank?: boolean; // Enable re-ranking of search results (default: false) rerank?: boolean; // Enable re-ranking of search results
enable_graph?: boolean; // Enable graph memory (returns relations)
host?: string; // Custom Mem0 API host (default: "https://api.mem0.ai") host?: string; // Custom Mem0 API host (default: "https://api.mem0.ai")
output_format?: string; // Output format version
filter_memories?: boolean; // Enable memory filtering
async_mode?: boolean; // Enable async processing of memory operations
} }
``` ```
@@ -130,9 +138,9 @@ This means a `Mem0ChatConfig` has all fields from both `Mem0ConfigSettings` and
Alias for `Mem0ConfigSettings`. Passed as the second argument when creating a model: Alias for `Mem0ConfigSettings`. Passed as the second argument when creating a model:
```typescript ```typescript
mem0("gpt-5-mini", { user_id: "alice" }) mem0("gpt-4-turbo", { user_id: "alice", enable_graph: true })
// ^^^^^^^^^^^^^^^^^^ // ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
// This object is Mem0ChatSettings // This object is Mem0ChatSettings
``` ```
## `LLMProviderSettings` Type ## `LLMProviderSettings` Type
@@ -180,8 +188,8 @@ An alternative exported class that creates models directly without the callable-
import { Mem0 } from "@mem0/vercel-ai-provider"; import { Mem0 } from "@mem0/vercel-ai-provider";
const mem0 = new Mem0({ provider: "openai" }); const mem0 = new Mem0({ provider: "openai" });
const chatModel = mem0.chat("gpt-5-mini", { user_id: "alice" }); const chatModel = mem0.chat("gpt-4-turbo", { user_id: "alice" });
const completionModel = mem0.completion("gpt-5-mini"); const completionModel = mem0.completion("gpt-3.5-turbo-instruct");
``` ```
The facade defaults its base URL to `"http://127.0.0.1:11434/api"` (Ollama-style) rather than `"http://api.openai.com"`. It always uses `"openai"` as the provider for created models. The facade defaults its base URL to `"http://127.0.0.1:11434/api"` (Ollama-style) rather than `"http://api.openai.com"`. It always uses `"openai"` as the provider for created models.
@@ -202,7 +210,7 @@ class Mem0GenericLanguageModel implements LanguageModelV2 {
readonly supportedUrls: Record<string, RegExp[]> = { '*': [/.*/] }; readonly supportedUrls: Record<string, RegExp[]> = { '*': [/.*/] };
provider: string; // e.g., "openai" provider: string; // e.g., "openai"
modelId: string; // e.g., "gpt-5-mini" modelId: string; // e.g., "gpt-4-turbo"
settings: Mem0ChatSettings; settings: Mem0ChatSettings;
config: Mem0ChatConfig; config: Mem0ChatConfig;
@@ -222,12 +230,10 @@ Both `doGenerate` and `doStream` follow the same internal flow:
4. Delegate to the underlying model's `doGenerate` or `doStream` 4. Delegate to the underlying model's `doGenerate` or `doStream`
5. Return the result 5. Return the result
**Note:** Entity identifier fields use snake_case (`user_id`, `app_id`, `agent_id`, `run_id`) to match the Mem0 API.
## Type: `Mem0ChatModelId` ## Type: `Mem0ChatModelId`
```typescript ```typescript
type Mem0ChatModelId = string & NonNullable<unknown>; type Mem0ChatModelId = string & NonNullable<unknown>;
``` ```
Any non-null string. The model ID is passed through to the underlying provider (e.g., `"gpt-5-mini"`, `"gemini-pro"`). Any non-null string. The model ID is passed through to the underlying provider (e.g., `"gpt-4-turbo"`, `"claude-sonnet-4-20250514"`, `"gemini-pro"`).
@@ -13,7 +13,7 @@ import { createMem0 } from "@mem0/vercel-ai-provider";
const mem0 = createMem0(); const mem0 = createMem0();
const { text } = await generateText({ const { text } = await generateText({
model: mem0("gpt-5-mini", { user_id: "alice" }), model: mem0("gpt-4-turbo", { user_id: "alice" }),
prompt: "Recommend a restaurant based on my preferences", prompt: "Recommend a restaurant based on my preferences",
}); });
@@ -33,7 +33,7 @@ import { createMem0 } from "@mem0/vercel-ai-provider";
const mem0 = createMem0(); const mem0 = createMem0();
const result = streamText({ const result = streamText({
model: mem0("gpt-5-mini", { user_id: "alice" }), model: mem0("gpt-4-turbo", { user_id: "alice" }),
prompt: "What should I cook for dinner tonight?", prompt: "What should I cook for dinner tonight?",
}); });
@@ -53,17 +53,17 @@ import { openai } from "@ai-sdk/openai";
import { generateText } from "ai"; import { generateText } from "ai";
import { retrieveMemories, addMemories } from "@mem0/vercel-ai-provider"; import { retrieveMemories, addMemories } from "@mem0/vercel-ai-provider";
const user_id = "alice"; const userId = "alice";
const prompt = "Suggest a weekend trip"; const prompt = "Suggest a weekend trip";
// Step 1: Retrieve memories as a formatted system prompt // Step 1: Retrieve memories as a formatted system prompt
const memories = await retrieveMemories(prompt, { const memories = await retrieveMemories(prompt, {
user_id: user_id, user_id: userId,
}); });
// Step 2: Generate with the memories injected as system context // Step 2: Generate with the memories injected as system context
const { text } = await generateText({ const { text } = await generateText({
model: openai("gpt-5-mini"), model: openai("gpt-4-turbo"),
prompt, prompt,
system: memories, system: memories,
}); });
@@ -76,7 +76,7 @@ await addMemories(
{ role: "user", content: [{ type: "text", text: prompt }] }, { role: "user", content: [{ type: "text", text: prompt }] },
{ role: "assistant", content: [{ type: "text", text }] }, { role: "assistant", content: [{ type: "text", text }] },
], ],
{ user_id: user_id } { user_id: userId }
); );
``` ```
@@ -121,7 +121,7 @@ import { z } from "zod";
const mem0 = createMem0(); const mem0 = createMem0();
const { object } = await generateObject({ const { object } = await generateObject({
model: mem0("gpt-5-mini", { user_id: "alice" }), model: mem0("gpt-4-turbo", { user_id: "alice" }),
prompt: "Suggest a meal plan for today", prompt: "Suggest a meal plan for today",
schema: z.object({ schema: z.object({
breakfast: z.string(), breakfast: z.string(),
@@ -138,7 +138,53 @@ console.log(object);
The `defaultObjectGenerationMode` is `"json"`, so structured output works out of the box. The `defaultObjectGenerationMode` is `"json"`, so structured output works out of the box.
## 6. Multi-Provider Setup ## 6. Graph Memory Enabled
Retrieve both text memories and entity relationship graphs.
```typescript
import { generateText } from "ai";
import { createMem0 } from "@mem0/vercel-ai-provider";
const mem0 = createMem0();
const { text } = await generateText({
model: mem0("gpt-4-turbo", {
user_id: "alice",
enable_graph: true,
}),
prompt: "What connections do you know about between my friends?",
});
console.log(text);
```
With `enable_graph: true`, the system prompt includes both:
- **Text memories**: `"Memory: Alice is friends with Bob"`
- **Graph relations**: `"Relation: Alice -> friends_with -> Bob"`
### Using graph with standalone utilities
```typescript
import { getMemories, searchMemories } from "@mem0/vercel-ai-provider";
// getMemories with graph returns the full response
const graphResult = await getMemories("my social connections", {
user_id: "alice",
enable_graph: true,
});
console.log(graphResult.results); // memory objects
console.log(graphResult.relations); // graph relations
// searchMemories always returns the full response
const fullResponse = await searchMemories("my social connections", {
user_id: "alice",
});
console.log(fullResponse.results);
console.log(fullResponse.relations);
```
## 7. Multi-Provider Setup
Configure different LLM providers with the wrapped model. Configure different LLM providers with the wrapped model.
@@ -148,7 +194,7 @@ Configure different LLM providers with the wrapped model.
import { createMem0 } from "@mem0/vercel-ai-provider"; import { createMem0 } from "@mem0/vercel-ai-provider";
const mem0 = createMem0(); // defaults to "openai" const mem0 = createMem0(); // defaults to "openai"
const model = mem0("gpt-5-mini", { user_id: "alice" }); const model = mem0("gpt-4-turbo", { user_id: "alice" });
``` ```
### Anthropic ### Anthropic
@@ -189,7 +235,7 @@ const mem0 = createMem0({
}); });
``` ```
## 7. Next.js API Route Integration ## 8. Next.js API Route Integration
A POST handler that uses the wrapped model in a Next.js App Router API route. A POST handler that uses the wrapped model in a Next.js App Router API route.
@@ -201,12 +247,12 @@ import { createMem0 } from "@mem0/vercel-ai-provider";
const mem0 = createMem0(); const mem0 = createMem0();
export async function POST(req: Request) { export async function POST(req: Request) {
const { messages, user_id } = await req.json(); const { messages, userId } = await req.json();
const lastMessage = messages[messages.length - 1]; const lastMessage = messages[messages.length - 1];
const result = streamText({ const result = streamText({
model: mem0("gpt-5-mini", { user_id }), model: mem0("gpt-4-turbo", { user_id: userId }),
prompt: lastMessage.content, prompt: lastMessage.content,
}); });
@@ -223,17 +269,17 @@ import { streamText } from "ai";
import { retrieveMemories, addMemories } from "@mem0/vercel-ai-provider"; import { retrieveMemories, addMemories } from "@mem0/vercel-ai-provider";
export async function POST(req: Request) { export async function POST(req: Request) {
const { messages, user_id } = await req.json(); const { messages, userId } = await req.json();
const lastMessage = messages[messages.length - 1]; const lastMessage = messages[messages.length - 1];
// Retrieve relevant memories // Retrieve relevant memories
const memories = await retrieveMemories(lastMessage.content, { const memories = await retrieveMemories(lastMessage.content, {
user_id, user_id: userId,
}); });
// Stream the response // Stream the response
const result = streamText({ const result = streamText({
model: openai("gpt-5-mini"), model: openai("gpt-4-turbo"),
prompt: lastMessage.content, prompt: lastMessage.content,
system: memories, system: memories,
}); });
@@ -245,7 +291,7 @@ export async function POST(req: Request) {
{ role: "user", content: [{ type: "text", text: lastMessage.content }] }, { role: "user", content: [{ type: "text", text: lastMessage.content }] },
{ role: "assistant", content: [{ type: "text", text }] }, { role: "assistant", content: [{ type: "text", text }] },
], ],
{ user_id } { user_id: userId }
); );
}); });
@@ -253,7 +299,7 @@ export async function POST(req: Request) {
} }
``` ```
## 8. How Memory Processing Works Internally ## 9. How Memory Processing Works Internally
### Wrapped model flow (doGenerate / doStream) ### Wrapped model flow (doGenerate / doStream)
@@ -262,10 +308,10 @@ export async function POST(req: Request) {
2. processMemories(messagesPrompts, mem0Config): 2. processMemories(messagesPrompts, mem0Config):
a. addMemories(messagesPrompts, mem0Config) a. addMemories(messagesPrompts, mem0Config)
--> fire-and-forget: .then().catch(), NO await --> fire-and-forget: .then().catch(), NO await
--> POST /v3/memories/add/ with converted messages --> POST /v1/memories/ with converted messages
b. await getMemories(messagesPrompts, mem0Config) b. await getMemories(messagesPrompts, mem0Config)
--> POST /v3/memories/search/ with flattened prompt --> POST /v2/memories/search/ with flattened prompt
--> returns memory array --> returns memory array (or {results, relations} if enable_graph)
c. Format memories into system message string c. Format memories into system message string
d. Prepend system message to messagesPrompts array d. Prepend system message to messagesPrompts array
e. Return { memories, messagesPrompts } e. Return { memories, messagesPrompts }
@@ -291,7 +337,7 @@ The memories are injected as a system message at position 0 of the prompt array:
} }
``` ```
## 9. Custom Configuration ## 10. Custom Configuration
### Custom Mem0 API host ### Custom Mem0 API host
@@ -312,15 +358,32 @@ const memories = await retrieveMemories(prompt, {
}); });
``` ```
### Organization and project scoping
```typescript
const mem0 = createMem0();
const { text } = await generateText({
model: mem0("gpt-4-turbo", {
user_id: "alice",
org_id: "org-123",
project_id: "proj-456",
}),
prompt: "Hello",
});
```
Note: `org_id` takes precedence over `org_name`. If `org_id` is set, `org_name` and `project_name` are not sent in the request.
### Memory filtering and ranking ### Memory filtering and ranking
```typescript ```typescript
const mem0 = createMem0(); const mem0 = createMem0();
const model = mem0("gpt-5-mini", { const model = mem0("gpt-4-turbo", {
user_id: "alice", user_id: "alice",
top_k: 10, // retrieve up to 10 memories (default: 5) top_k: 10, // retrieve up to 10 memories (default: 5)
threshold: 0.8, // only memories with score >= 0.8 threshold: 0.8, // only memories with score >= 0.8
rerank: true, // enable re-ranking of results rerank: true, // enable re-ranking of results
filter_memories: true,
}); });
``` ```
@@ -346,13 +409,14 @@ Set defaults at the provider level that apply to every model created:
const mem0 = createMem0({ const mem0 = createMem0({
mem0Config: { mem0Config: {
user_id: "alice", user_id: "alice",
enable_graph: true,
top_k: 10, top_k: 10,
}, },
}); });
// These calls inherit user_id and top_k from mem0Config // These calls inherit user_id, enable_graph, and top_k from mem0Config
const { text } = await generateText({ const { text } = await generateText({
model: mem0("gpt-5-mini"), model: mem0("gpt-4-turbo"),
prompt: "Hello", prompt: "Hello",
}); });
``` ```
@@ -361,7 +425,7 @@ Per-call settings (passed as the second argument to `mem0()`) are merged on top
```typescript ```typescript
// Override user_id for this specific call // Override user_id for this specific call
const model = mem0("gpt-5-mini", { user_id: "bob" }); const model = mem0("gpt-4-turbo", { user_id: "bob" });
``` ```
The merge order is: `config.mem0Config` (provider defaults) < `settings` (per-call overrides). The merge order is: `config.mem0Config` (provider defaults) < `settings` (per-call overrides).
+8 -17
View File
@@ -15,10 +15,10 @@ description: >
license: Apache-2.0 license: Apache-2.0
metadata: metadata:
author: mem0ai author: mem0ai
version: "3.0.0" version: "2.0.0"
category: ai-memory category: ai-memory
tags: "memory, personalization, ai, python, typescript, vector-search" tags: "memory, personalization, ai, python, typescript, vector-search"
compatibility: Requires Python 3.10+ or Node.js 18+, pip install mem0ai or npm install mem0ai, MEM0_API_KEY env var (Platform), and internet access to api.mem0.ai. SDK v3 with v2 compatibility mode available. compatibility: Requires Python 3.10+ or Node.js 18+, pip install mem0ai or npm install mem0ai, MEM0_API_KEY env var (Platform), and internet access to api.mem0.ai
--- ---
# Mem0 Platform Integration # Mem0 Platform Integration
@@ -77,14 +77,14 @@ client.add(messages, user_id="alice")
### Search memories ### Search memories
```python ```python
results = client.search("dietary preferences", filters={"user_id": "alice"}) results = client.search("dietary preferences", user_id="alice")
for mem in results.get("results", []): for mem in results.get("results", []):
print(mem["memory"]) print(mem["memory"])
``` ```
### Get all memories ### Get all memories
```python ```python
all_memories = client.get_all(filters={"user_id": "alice"}) all_memories = client.get_all(user_id="alice")
``` ```
### Update a memory ### Update a memory
@@ -109,12 +109,12 @@ openai = OpenAI()
def chat(user_input: str, user_id: str) -> str: def chat(user_input: str, user_id: str) -> str:
# 1. Retrieve relevant memories # 1. Retrieve relevant memories
memories = mem0.search(user_input, filters={"user_id": user_id}) memories = mem0.search(user_input, user_id=user_id)
context = "\n".join([m["memory"] for m in memories.get("results", [])]) context = "\n".join([m["memory"] for m in memories.get("results", [])])
# 2. Generate response with memory context # 2. Generate response with memory context
response = openai.chat.completions.create( response = openai.chat.completions.create(
model="gpt-5-mini", model="gpt-4.1-nano-2025-04-14",
messages=[ messages=[
{"role": "system", "content": f"User context:\n{context}"}, {"role": "system", "content": f"User context:\n{context}"},
{"role": "user", "content": user_input}, {"role": "user", "content": user_input},
@@ -132,20 +132,11 @@ def chat(user_input: str, user_id: str) -> str:
## Common edge cases ## Common edge cases
- **Search returns empty:** Memories process asynchronously. Wait 2-3s after `add()` before searching. Also verify `user_id` matches exactly (case-sensitive) and use `filters={"user_id": "..."}` syntax. - **Search returns empty:** Memories process asynchronously. Wait 2-3s after `add()` before searching. Also verify `user_id` matches exactly (case-sensitive).
- **AND filter with user_id + agent_id returns empty:** Entities are stored separately. Use `OR` instead, or query separately. - **AND filter with user_id + agent_id returns empty:** Entities are stored separately. Use `OR` instead, or query separately.
- **Duplicate memories:** Don't mix `infer=True` (default) and `infer=False` for the same data. Stick to one mode. - **Duplicate memories:** Don't mix `infer=True` (default) and `infer=False` for the same data. Stick to one mode.
- **Wrong import:** Always use `from mem0 import MemoryClient` (or `AsyncMemoryClient` for async). Do not use `from mem0 import Memory`. - **Wrong import:** Always use `from mem0 import MemoryClient` (or `AsyncMemoryClient` for async). Do not use `from mem0 import Memory`.
- **v3 defaults:** `top_k=20`, `threshold=0.1`, `rerank=False`. Adjust as needed for your use case. - **Immutable memories:** Cannot be updated or deleted once created. Use `client.history(memory_id)` to track changes over time.
## v2 Compatibility
If you're using SDK v2.x, note these differences:
- **Entity IDs:** Pass `user_id` as top-level kwarg to `search()` instead of inside `filters`
- **Defaults:** `top_k=100`, no threshold, `rerank=True`
- **Graph memory:** Available via `enable_graph=True`
See the [migration guide](https://docs.mem0.ai/migration/oss-v2-to-v3) for details.
## Live documentation search ## Live documentation search
+14 -18
View File
@@ -46,16 +46,18 @@ Both read from `MEM0_API_KEY` env var if no key provided.
```python ```python
# Python: kwargs # Python: kwargs
client.add(messages, user_id="alice", metadata={"source": "chat"}) client.add(messages, user_id="alice", metadata={"source": "chat"})
client.search("query", filters={"user_id": "alice"}, top_k=5, rerank=True) client.search("query", user_id="alice", top_k=5, rerank=True)
``` ```
```typescript ```typescript
// TypeScript: options object with camelCase for top-level params, snake_case for filter keys // TypeScript: options object
await client.add(messages, { userId: 'alice', metadata: { source: 'chat' } }); await client.add(messages, { user_id: 'alice', metadata: { source: 'chat' } });
await client.search('query', { filters: { user_id: 'alice' }, topK: 5, rerank: true }); await client.search('query', { user_id: 'alice', top_k: 5, rerank: true });
``` ```
**v3:** Python uses `snake_case` everywhere. TypeScript uses `camelCase` for top-level params (`userId`, `topK`) but `snake_case` for filter keys (`user_id`, `agent_id`). **Important:** Both use `snake_case` for API parameter names (`user_id`, `agent_id`, `top_k`, etc.). Only method names differ.
Exception: OSS TypeScript uses `camelCase` for config params (`userId`, `agentId`, `runId`).
## Architectural Differences ## Architectural Differences
@@ -95,8 +97,10 @@ These methods exist in Python but not TypeScript:
| Python config key | TypeScript config key | | Python config key | TypeScript config key |
|-------------------|----------------------| |-------------------|----------------------|
| `vector_store` | `vectorStore` | | `vector_store` | `vectorStore` |
| `graph_store` | `graphStore` |
| `history_db_path` | `historyDbPath` | | `history_db_path` | `historyDbPath` |
| `custom_instructions` | `customInstructions` | | `custom_instructions` | `customInstructions` |
| `enable_graph` | `enableGraph` |
## OSS Scope Parameter Naming ## OSS Scope Parameter Naming
@@ -106,24 +110,16 @@ These methods exist in Python but not TypeScript:
| `agent_id="bot"` | `agentId: 'bot'` | | `agent_id="bot"` | `agentId: 'bot'` |
| `run_id="session"` | `runId: 'session'` | | `run_id="session"` | `runId: 'session'` |
## Entity ID Passing (v3)
| Method | Python | TypeScript |
|--------|--------|------------|
| add() | Top-level: `user_id="alice"` | Top-level: `{ userId: 'alice' }` |
| search() | In filters: `filters={"user_id": "alice"}` | In filters: `{ filters: { user_id: 'alice' } }` |
| get_all() | In filters: `filters={"user_id": "alice"}` | In filters: `{ filters: { user_id: 'alice' } }` |
## Common Gotcha ## Common Gotcha
When searching/filtering, both Python and TypeScript use `snake_case` for filter keys. TypeScript only uses `camelCase` for top-level method parameters: When searching/filtering, **both SDKs use `snake_case`** for filter keys:
```python ```python
# Python - snake_case in filters # Python
results = client.search("query", filters={"user_id": "alice"}) filters = {"AND": [{"user_id": "alice"}, {"categories": {"contains": "health"}}]}
``` ```
```typescript ```typescript
// TypeScript - snake_case in filters, camelCase for top-level params // TypeScript -- same snake_case in filter objects!
const results = await client.search('query', { filters: { user_id: 'alice' }, topK: 20 }); const filters = { AND: [{ user_id: 'alice' }, { categories: { contains: 'health' } }] };
``` ```
+69 -75
View File
@@ -41,18 +41,23 @@ const messages = [
{ role: 'user', content: "I'm a vegetarian and allergic to nuts." }, { role: 'user', content: "I'm a vegetarian and allergic to nuts." },
{ role: 'assistant', content: "Got it! I'll remember that." }, { role: 'assistant', content: "Got it! I'll remember that." },
]; ];
await client.add(messages, { userId: 'alice' }); await client.add(messages, { user_id: 'alice' });
``` ```
| Parameter | Type | Description | | Parameter | Type | Description |
|-----------|------|-------------| |-----------|------|-------------|
| `messages` | `Message[]` | Array of `{role, content}` objects | | `messages` | `Message[]` | Array of `{role, content}` objects |
| `options.userId` | string | User identifier | | `options.user_id` | string | User identifier |
| `options.agentId` | string | Agent identifier | | `options.agent_id` | string | Agent identifier |
| `options.appId` | string | Application identifier | | `options.app_id` | string | Application identifier |
| `options.runId` | string | Session identifier | | `options.run_id` | string | Session identifier |
| `options.metadata` | object | Custom key-value pairs | | `options.metadata` | object | Custom key-value pairs |
| `options.enable_graph` | boolean | Activate knowledge graph |
| `options.infer` | boolean | If false, store raw text (default: true) | | `options.infer` | boolean | If false, store raw text (default: true) |
| `options.immutable` | boolean | Prevent future modification |
| `options.expiration_date` | string | Auto-expiry (`YYYY-MM-DD`) |
| `options.includes` | string | Preference filter for inclusion |
| `options.excludes` | string | Preference filter for exclusion |
**Returns:** `Promise<any>` -- list of events **Returns:** `Promise<any>` -- list of events
@@ -61,7 +66,7 @@ await client.add(messages, { userId: 'alice' });
Search memories by semantic similarity. Search memories by semantic similarity.
```typescript ```typescript
const results = await client.search('dietary preferences', { filters: { user_id: 'alice' }, topK: 20 }); const results = await client.search('dietary preferences', { user_id: 'alice' });
for (const mem of results.results) { for (const mem of results.results) {
console.log(mem.memory, mem.score); console.log(mem.memory, mem.score);
} }
@@ -70,12 +75,17 @@ for (const mem of results.results) {
| Parameter | Type | Description | | Parameter | Type | Description |
|-----------|------|-------------| |-----------|------|-------------|
| `query` | string | Natural language search query | | `query` | string | Natural language search query |
| `options.filters` | object | Filter object with entity IDs (`user_id`, `agent_id`, etc.) and/or `AND`/`OR`/`NOT` conditions | | `options.user_id` | string | Filter by user |
| `options.topK` | number | Number of results (default: 20) | | `options.agent_id` | string | Filter by agent |
| `options.rerank` | boolean | Enable semantic reranking (default: false) | | `options.filters` | object | V2 filter object (`AND`/`OR`/`NOT`) |
| `options.threshold` | number | Minimum similarity (default: 0.1) | | `options.top_k` | number | Number of results (default: 10) |
| `options.rerank` | boolean | Enable semantic reranking |
| `options.threshold` | number | Minimum similarity (default: 0.3) |
| `options.keyword_search` | boolean | Enable keyword search |
| `options.enable_graph` | boolean | Include graph relations |
| `options.filter_memories` | boolean | Precision filtering |
**Returns:** `Promise<SearchResult>` -- `{results: [{id, memory, score, ...}]}` **Returns:** `Promise<SearchResult>` -- `{results: [{id, memory, score, ...}], relations: [...]}`
#### get(memoryId) #### get(memoryId)
@@ -88,7 +98,7 @@ const memory = await client.get('ea925981-...');
Retrieve all memories. Requires at least one entity identifier in filters. Retrieve all memories. Requires at least one entity identifier in filters.
```typescript ```typescript
const memories = await client.getAll({ filters: { user_id: 'alice' } }); const memories = await client.getAll({ user_id: 'alice' });
// With filters // With filters
const filtered = await client.getAll({ const filtered = await client.getAll({
filters: { AND: [{ user_id: 'alice' }, { categories: { contains: 'health' } }] }, filters: { AND: [{ user_id: 'alice' }, { categories: { contains: 'health' } }] },
@@ -97,9 +107,11 @@ const filtered = await client.getAll({
| Parameter | Type | Description | | Parameter | Type | Description |
|-----------|------|-------------| |-----------|------|-------------|
| `options.filters` | object | Filter object with entity IDs (`user_id`, `agent_id`, etc.) and/or `AND`/`OR`/`NOT` conditions | | `options.user_id` | string | Filter by user |
| `options.filters` | object | V2 filter object |
| `options.page` | number | Page number | | `options.page` | number | Page number |
| `options.pageSize` | number | Results per page | | `options.page_size` | number | Results per page |
| `options.enable_graph` | boolean | Include graph relations |
#### update(memoryId, data) #### update(memoryId, data)
@@ -124,14 +136,14 @@ await client.delete('ea925981-...');
#### deleteAll(options?) #### deleteAll(options?)
```typescript ```typescript
await client.deleteAll({ userId: 'alice' }); await client.deleteAll({ user_id: 'alice' });
``` ```
#### history(memoryId) #### history(memoryId)
```typescript ```typescript
const history = await client.history('ea925981-...'); const history = await client.history('ea925981-...');
// Returns: [{previousValue, newValue, action, timestamps}] // Returns: [{previous_value, new_value, action, timestamps}]
``` ```
--- ---
@@ -167,8 +179,8 @@ const users = await client.users();
#### deleteUser(data) / deleteUsers(data) #### deleteUser(data) / deleteUsers(data)
```typescript ```typescript
await client.deleteUser({ userId: 'alice' }); // Single entity await client.deleteUser({ user_id: 'alice' }); // Single entity
await client.deleteUsers({ agentId: 'bot-1' }); // Flexible await client.deleteUsers({ agent_id: 'bot-1' }); // Flexible
``` ```
--- ---
@@ -177,12 +189,13 @@ await client.deleteUsers({ agentId: 'bot-1' }); // Flexible
```typescript ```typescript
// Get project config // Get project config
const config = await client.getProject({ fields: ['customCategories'] }); const config = await client.getProject({ fields: ['custom_categories'] });
// Update project settings // Update project settings
await client.updateProject({ await client.updateProject({
customInstructions: 'Extract dietary preferences and health info', custom_instructions: 'Extract dietary preferences and health info',
customCategories: [{ health: 'Medical and dietary info' }], custom_categories: [{ health: 'Medical and dietary info' }],
enable_graph: true,
}); });
``` ```
@@ -192,25 +205,25 @@ await client.updateProject({
```typescript ```typescript
// List // List
const webhooks = await client.getWebhooks({ projectId: 'proj_123' }); const webhooks = await client.getWebhooks({ project_id: 'proj_123' });
// Create // Create
const webhook = await client.createWebhook({ const webhook = await client.createWebhook({
url: 'https://your-app.com/webhook', url: 'https://your-app.com/webhook',
name: 'Memory Logger', name: 'Memory Logger',
projectId: 'proj_123', project_id: 'proj_123',
eventTypes: ['memory_add', 'memory_update'], event_types: ['memory_add', 'memory_update'],
}); });
// Update // Update
await client.updateWebhook({ await client.updateWebhook({
webhookId: 'wh_123', webhook_id: 'wh_123',
name: 'Updated Logger', name: 'Updated Logger',
url: 'https://new-url.com', url: 'https://new-url.com',
}); });
// Delete // Delete
await client.deleteWebhook({ webhookId: 'wh_123' }); await client.deleteWebhook({ webhook_id: 'wh_123' });
``` ```
--- ---
@@ -219,9 +232,9 @@ await client.deleteWebhook({ webhookId: 'wh_123' });
```typescript ```typescript
await client.feedback({ await client.feedback({
memoryId: 'mem-123', memory_id: 'mem-123',
feedback: 'POSITIVE', feedback: 'POSITIVE',
feedbackReason: 'Accurately captured preference', feedback_reason: 'Accurately captured preference',
}); });
``` ```
@@ -235,7 +248,7 @@ const exportReq = await client.createMemoryExport({
filters: { user_id: 'alice' }, filters: { user_id: 'alice' },
}); });
const result = await client.getMemoryExport({ memoryExportId: exportReq.id }); const result = await client.getMemoryExport({ memory_export_id: exportReq.id });
``` ```
--- ---
@@ -246,12 +259,14 @@ Key interfaces from `mem0.types.ts`:
```typescript ```typescript
interface Message { role: string; content: string; } interface Message { role: string; content: string; }
interface Memory { id: string; memory: string; userId: string; categories: string[]; score?: number; /* ... */ } interface Memory { id: string; memory: string; user_id: string; categories: string[]; score?: number; /* ... */ }
interface MemoryOptions { userId?: string; agentId?: string; appId?: string; runId?: string; metadata?: object; /* ... */ } interface MemoryOptions { user_id?: string; agent_id?: string; app_id?: string; run_id?: string; metadata?: object; /* ... */ }
interface SearchOptions { filters?: object; topK?: number; rerank?: boolean; threshold?: number; /* ... */ } interface SearchOptions { user_id?: string; filters?: object; top_k?: number; rerank?: boolean; threshold?: number; /* ... */ }
interface MemoryHistory { id: string; memoryId: string; previousValue: string; newValue: string; action: string; /* ... */ } interface MemoryHistory { id: string; memory_id: string; previous_value: string; new_value: string; action: string; /* ... */ }
interface FeedbackPayload { memoryId: string; feedback: string; feedbackReason?: string; } interface FeedbackPayload { memory_id: string; feedback: string; feedback_reason?: string; }
interface WebhookCreatePayload { url: string; name: string; projectId: string; eventTypes: string[]; } interface WebhookCreatePayload { url: string; name: string; project_id: string; event_types: string[]; }
enum OutputFormat { v1_0 = 'v1.0', v1_1 = 'v1.1' }
enum API_VERSION { v1 = 'v1', v2 = 'v2' }
``` ```
--- ---
@@ -281,7 +296,7 @@ const config = {
llm: { llm: {
provider: 'openai', // openai, groq, anthropic, google, ollama, lmstudio, mistral, azure provider: 'openai', // openai, groq, anthropic, google, ollama, lmstudio, mistral, azure
config: { config: {
model: 'gpt-5-mini', model: 'gpt-4o-mini',
apiKey: 'sk-xxx', apiKey: 'sk-xxx',
}, },
}, },
@@ -300,8 +315,17 @@ const config = {
port: 6333, port: 6333,
}, },
}, },
graphStore: { // Optional
provider: 'neo4j',
config: {
url: 'neo4j://localhost:7687',
username: 'neo4j',
password: 'password',
},
},
historyDbPath: 'history.db', historyDbPath: 'history.db',
customInstructions: '...', customPrompt: '...',
enableGraph: false,
disableHistory: false, disableHistory: false,
}; };
@@ -339,14 +363,17 @@ await m.add([
#### search(query, config) #### search(query, config)
```typescript ```typescript
const results = await m.search('dietary preferences', { filters: { user_id: 'alice' }, topK: 5 }); const results = await m.search('dietary preferences', { userId: 'alice', limit: 5 });
``` ```
| Parameter | Type | Description | | Parameter | Type | Description |
|-----------|------|-------------| |-----------|------|-------------|
| `query` | string | Search query | | `query` | string | Search query |
| `config.filters` | object | Filter object with entity IDs (`user_id`, `agent_id`, `run_id`, etc.) | | `config.userId` | string | Filter by user |
| `config.topK` | number | Max results (default: 20) | | `config.agentId` | string | Filter by agent |
| `config.runId` | string | Filter by run |
| `config.limit` | number | Max results (default: 100) |
| `config.filters` | object | Advanced filters |
#### get(memoryId) / getAll(config) / update(memoryId, data) / delete(memoryId) / deleteAll(config) / history(memoryId) #### get(memoryId) / getAll(config) / update(memoryId, data) / delete(memoryId) / deleteAll(config) / history(memoryId)
@@ -374,45 +401,12 @@ await m.reset();
| **Auth** | API key required (`MEM0_API_KEY`) | No API key -- config-based | | **Auth** | API key required (`MEM0_API_KEY`) | No API key -- config-based |
| **Execution** | API calls to `api.mem0.ai` | Local execution | | **Execution** | API calls to `api.mem0.ai` | Local execution |
| **Infrastructure** | Fully managed | Self-managed vector DB, embedder, LLM | | **Infrastructure** | Fully managed | Self-managed vector DB, embedder, LLM |
| **Param style** | Top-level: `camelCase` (`userId`, `topK`), filter keys: `snake_case` (`user_id`) | Top-level: `camelCase` (`userId`, `topK`), filter keys: `snake_case` (`user_id`) | | **Param style** | `snake_case` in options (`user_id`) | `camelCase` in config (`userId`) |
| **Batch ops** | `batchUpdate`, `batchDelete` | Not available | | **Batch ops** | `batchUpdate`, `batchDelete` | Not available |
| **Webhooks** | Full CRUD | Not available | | **Webhooks** | Full CRUD | Not available |
| **Export** | `createMemoryExport` | Not available | | **Export** | `createMemoryExport` | Not available |
| **Feedback** | `feedback()` | Not available | | **Feedback** | `feedback()` | Not available |
| **Project mgmt** | `getProject`, `updateProject` | Not available | | **Project mgmt** | `getProject`, `updateProject` | Not available |
| **User listing** | `users()`, `deleteUser()` | Not available | | **User listing** | `users()`, `deleteUser()` | Not available |
| **Graph store** | Platform-managed | Self-managed (Neo4j) |
| **History** | Platform-managed | SQLite (configurable) | | **History** | Platform-managed | SQLite (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:**
```typescript
// 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:**
| Param | v2 | v3 |
|-------|----|----|
| `topK` | 100 | 20 |
| `threshold` | none | 0.1 |
| `rerank` | true | false |
**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](https://docs.mem0.ai/migration/oss-v2-to-v3) for details.
+47 -53
View File
@@ -36,7 +36,7 @@ client = AsyncMemoryClient(api_key="m0-xxx")
# Or use as context manager # Or use as context manager
async with AsyncMemoryClient(api_key="m0-xxx") as client: async with AsyncMemoryClient(api_key="m0-xxx") as client:
results = await client.search("query", filters={"user_id": "alice"}) results = await client.search("query", user_id="alice")
``` ```
Same methods as `MemoryClient`, all `async`/`await`. Supports async context manager. Same methods as `MemoryClient`, all `async`/`await`. Supports async context manager.
@@ -65,19 +65,25 @@ client.add(messages, user_id="alice")
| `app_id` | str | None | Application identifier | | `app_id` | str | None | Application identifier |
| `run_id` | str | None | Session/run identifier | | `run_id` | str | None | Session/run identifier |
| `metadata` | dict | None | Custom key-value pairs | | `metadata` | dict | None | Custom key-value pairs |
| `enable_graph` | bool | None | Activate knowledge graph extraction |
| `infer` | bool | True | If False, store raw text without LLM inference | | `infer` | bool | True | If False, store raw text without LLM inference |
| `immutable` | bool | None | If True, prevents future modification |
| `expiration_date` | str | None | Auto-expiry date (`YYYY-MM-DD`) |
| `includes` | str | None | Preference filter for inclusion |
| `excludes` | str | None | Preference filter for exclusion |
| `async_mode` | bool | True | If False, wait for processing to complete |
| `custom_categories` | list | None | Override project categories | | `custom_categories` | list | None | Override project categories |
| `custom_instructions` | str | None | Override extraction instructions | | `custom_instructions` | str | None | Override extraction instructions |
| `timestamp` | int \| float \| str | None | Custom timestamp (Unix epoch or ISO 8601) | | `timestamp` | int \| float \| str | None | Custom timestamp (Unix epoch or ISO 8601) |
**Returns:** `dict` -- list of events: `[{"id": "...", "event": "ADD", "data": {"memory": "..."}}]` **Returns:** `dict` -- list of events: `[{"id": "...", "event": "ADD|UPDATE|DELETE", "data": {"memory": "..."}}]`
#### search(query, **kwargs) #### search(query, **kwargs)
Search memories by semantic similarity. Search memories by semantic similarity.
```python ```python
results = client.search("dietary preferences", filters={"user_id": "alice"}) results = client.search("dietary preferences", user_id="alice")
for mem in results.get("results", []): for mem in results.get("results", []):
print(mem["memory"], mem["score"]) print(mem["memory"], mem["score"])
``` ```
@@ -85,14 +91,20 @@ for mem in results.get("results", []):
| Parameter | Type | Default | Description | | Parameter | Type | Default | Description |
|-----------|------|---------|-------------| |-----------|------|---------|-------------|
| `query` | str | required | Natural language search query | | `query` | str | required | Natural language search query |
| `filters` | dict | None | Filter object with entity IDs and/or `AND`/`OR`/`NOT` conditions (e.g., `{"user_id": "alice"}`) | | `user_id` | str | None | Filter by user |
| `agent_id` | str | None | Filter by agent |
| `app_id` | str | None | Filter by app |
| `top_k` | int | 10 | Number of results | | `top_k` | int | 10 | Number of results |
| `rerank` | bool | False | Enable deep semantic reranking (+150-200ms) | | `filters` | dict | None | V2 filter object (`AND`/`OR`/`NOT`) |
| `threshold` | float | 0.1 | Minimum similarity score | | `rerank` | bool | None | Enable deep semantic reranking (+150-200ms) |
| `threshold` | float | 0.3 | Minimum similarity score |
| `keyword_search` | bool | None | Enable keyword-based search (+10ms) |
| `enable_graph` | bool | None | Include graph relations in results |
| `filter_memories` | bool | None | Precision filtering, removes low-relevance (+200-300ms) |
| `fields` | list | None | Specific fields to return | | `fields` | list | None | Specific fields to return |
| `categories` | list | None | Filter by category | | `categories` | list | None | Filter by category |
**Returns:** `dict` -- `{"results": [{id, memory, user_id, categories, score, created_at, ...}]}` **Returns:** `dict` -- `{"results": [{id, memory, user_id, categories, score, created_at, ...}], "relations": [...]}`
#### get(memory_id) #### get(memory_id)
@@ -109,23 +121,27 @@ memory = client.get(memory_id="ea925981-...")
Retrieve all memories with optional filtering. Requires at least one entity identifier. Retrieve all memories with optional filtering. Requires at least one entity identifier.
```python ```python
memories = client.get_all(filters={"user_id": "alice"}) memories = client.get_all(user_id="alice")
# With compound filters # With filters
memories = client.get_all(filters={"AND": [{"user_id": "alice"}, {"categories": {"contains": "health"}}]}) memories = client.get_all(filters={"AND": [{"user_id": "alice"}, {"categories": {"contains": "health"}}]})
``` ```
| Parameter | Type | Default | Description | | Parameter | Type | Default | Description |
|-----------|------|---------|-------------| |-----------|------|---------|-------------|
| `filters` | dict | None | Filter object with entity IDs and/or `AND`/`OR`/`NOT` conditions | | `user_id` | str | None | Filter by user |
| `agent_id` | str | None | Filter by agent |
| `app_id` | str | None | Filter by app |
| `top_k` | int | None | Limit results | | `top_k` | int | None | Limit results |
| `page` | int | None | Page number | | `page` | int | None | Page number |
| `page_size` | int | None | Results per page | | `page_size` | int | None | Results per page |
| `filters` | dict | None | V2 filter object |
| `enable_graph` | bool | None | Include graph relations |
**Returns:** `dict` -- `{"results": [...]}` **Returns:** `dict` -- `{"results": [...]}`
#### update(memory_id, text=None, metadata=None, timestamp=None) #### update(memory_id, text=None, metadata=None, timestamp=None)
Update a memory's content, metadata, or timestamp. At least one parameter required. Update a memory's content, metadata, or timestamp. At least one parameter required. Cannot update immutable memories.
```python ```python
client.update("ea925981-...", text="Updated: vegan since 2024") client.update("ea925981-...", text="Updated: vegan since 2024")
@@ -304,10 +320,11 @@ config = client.project.get(fields=["custom_categories", "custom_instructions"])
client.project.update( client.project.update(
custom_instructions="Extract dietary preferences and health info", custom_instructions="Extract dietary preferences and health info",
custom_categories=[{"health": "Medical and dietary info"}], custom_categories=[{"health": "Medical and dietary info"}],
enable_graph=True,
multilingual=True, multilingual=True,
) )
# Create/delete project # Create/delete project (requires org_id)
client.project.create(name="My Project", description="...") client.project.create(name="My Project", description="...")
client.project.delete() client.project.delete()
@@ -345,7 +362,7 @@ config = {
"llm": { "llm": {
"provider": "openai", # openai, groq, azure, ollama, lmstudio, google, anthropic, mistral "provider": "openai", # openai, groq, azure, ollama, lmstudio, google, anthropic, mistral
"config": { "config": {
"model": "gpt-5-mini", "model": "gpt-4o-mini",
"api_key": "sk-xxx", "api_key": "sk-xxx",
} }
}, },
@@ -364,8 +381,18 @@ config = {
"port": 6333, "port": 6333,
} }
}, },
"graph_store": { # Optional
"provider": "neo4j",
"config": {
"url": "neo4j://localhost:7687",
"username": "neo4j",
"password": "password",
}
},
"history_db_path": "history.db", # SQLite path for change history "history_db_path": "history.db", # SQLite path for change history
"custom_instructions": "...", # Custom LLM prompt for extraction "custom_instructions": "...", # Custom LLM prompt for extraction
"custom_update_memory_prompt": "...", # Custom LLM prompt for updates
"enable_graph": False, # Enable graph memory
} }
m = Memory.from_config(config) m = Memory.from_config(config)
@@ -376,7 +403,7 @@ m = Memory.from_config(config)
```python ```python
with Memory(config) as m: with Memory(config) as m:
m.add("I prefer dark mode", user_id="alice") m.add("I prefer dark mode", user_id="alice")
results = m.search("preferences", filters={"user_id": "alice"}) results = m.search("preferences", user_id="alice")
# SQLite connections released automatically # SQLite connections released automatically
``` ```
@@ -398,14 +425,12 @@ At least one of `user_id`, `agent_id`, `run_id` required.
**Returns:** `{"results": [...], "relations": [...]}` **Returns:** `{"results": [...], "relations": [...]}`
#### search(query, *, filters=None, top_k=20, threshold=0.1, rerank=False) #### search(query, *, user_id, agent_id, run_id, limit=100, filters=None, threshold=None, rerank=True)
```python ```python
results = m.search("dietary preferences", filters={"user_id": "alice"}, top_k=5) results = m.search("dietary preferences", user_id="alice", limit=5)
``` ```
Entity IDs (`user_id`, `agent_id`, `run_id`) must be passed inside the `filters` dict.
Supports filter operators: `eq`, `ne`, `in`, `nin`, `gt`, `gte`, `lt`, `lte`, `contains`, `not_contains`. Supports filter operators: `eq`, `ne`, `in`, `nin`, `gt`, `gte`, `lt`, `lte`, `contains`, `not_contains`.
#### get(memory_id) / get_all(**kwargs) / update(memory_id, data, metadata=None) / delete(memory_id) / delete_all(**kwargs) / history(memory_id) #### get(memory_id) / get_all(**kwargs) / update(memory_id, data, metadata=None) / delete(memory_id) / delete_all(**kwargs) / history(memory_id)
@@ -431,7 +456,7 @@ from mem0 import AsyncMemory
m = AsyncMemory(config) m = AsyncMemory(config)
await m.add("text", user_id="alice") await m.add("text", user_id="alice")
results = await m.search("query", filters={"user_id": "alice"}) results = await m.search("query", user_id="alice")
``` ```
--- ---
@@ -444,44 +469,13 @@ results = await m.search("query", filters={"user_id": "alice"})
| **Auth** | API key required (`MEM0_API_KEY`) | No API key -- config-based | | **Auth** | API key required (`MEM0_API_KEY`) | No API key -- config-based |
| **Execution** | API calls to `api.mem0.ai` | Local execution | | **Execution** | API calls to `api.mem0.ai` | Local execution |
| **Infrastructure** | Fully managed | Self-managed vector DB, embedder, LLM | | **Infrastructure** | Fully managed | Self-managed vector DB, embedder, LLM |
| **Entity filtering** | `filters={"user_id": "..."}` | `filters={"user_id": "..."}` |
| **Batch ops** | `batch_update`, `batch_delete` | Not available | | **Batch ops** | `batch_update`, `batch_delete` | Not available |
| **Webhooks** | Full CRUD | Not available | | **Webhooks** | Full CRUD | Not available |
| **Export** | `create_memory_export`, `get_memory_export` | Not available | | **Export** | `create_memory_export`, `get_memory_export` | Not available |
| **Feedback** | `feedback()` | Not available | | **Feedback** | `feedback()` | Not available |
| **Project mgmt** | `client.project.*` | Not available | | **Project mgmt** | `client.project.*` | Not available |
| **User listing** | `users()`, `delete_users()` | Not available | | **User listing** | `users()`, `delete_users()` | Not available |
| **Custom prompts** | Via project settings | Direct config (`custom_instructions`) | | **Custom prompts** | Via project settings | Direct config |
| **Graph store** | Platform-managed | Self-managed (Neo4j) |
| **History** | Platform-managed | SQLite (configurable) | | **History** | Platform-managed | SQLite (configurable) |
| **Async** | `AsyncMemoryClient` | `AsyncMemory` | | **Async** | `AsyncMemoryClient` | `AsyncMemory` |
---
## v2 Compatibility
If you're using SDK v2.x or the v2 API:
**API Changes:**
- **Entity IDs in search/get_all:** Pass `user_id`, `agent_id` as top-level kwargs instead of inside `filters`
```python
# v2
results = client.search("query", user_id="alice")
# v3
results = client.search("query", filters={"user_id": "alice"})
```
- **add() returns:** v2 returns ADD, UPDATE, DELETE events; v3 returns ADD only
**Default Changes:**
| Param | v2 | v3 |
|-------|----|----|
| `top_k` | 100 | 20 |
| `threshold` | None | 0.1 |
| `rerank` | True | False |
**Removed Parameters:**
- Constructor: `org_id`, `project_id`
- add(): `async_mode`, `output_format`, `enable_graph`, `immutable`, `expiration_date`, `filter_memories`, `batch_size`, `force_add_only`, `includes`, `excludes`, `keyword_search`
- search()/get_all(): `enable_graph`
- Config: `enable_graph`, `graph_store`, `custom_fact_extraction_prompt` (renamed to `custom_instructions`)
See the [v2 to v3 migration guide](https://docs.mem0.ai/migration/oss-v2-to-v3) for full details.
+19 -29
View File
@@ -8,15 +8,13 @@ All endpoints require: `Authorization: Token <MEM0_API_KEY>`
| Operation | Method | URL | | Operation | Method | URL |
|-----------|--------|-----| |-----------|--------|-----|
| Add Memories | `POST` | `/v3/memories/add/` | | Add Memories | `POST` | `/v1/memories/` |
| Search Memories | `POST` | `/v3/memories/search/` | | Search Memories | `POST` | `/v2/memories/search/` |
| Get All Memories | `POST` | `/v3/memories/` | | Get All Memories | `POST` | `/v2/memories/` |
| Get Single Memory | `GET` | `/v1/memories/{memory_id}/` | | Get Single Memory | `GET` | `/v1/memories/{memory_id}/` |
| Update Memory | `PUT` | `/v1/memories/{memory_id}/` | | Update Memory | `PUT` | `/v1/memories/{memory_id}/` |
| Delete Memory | `DELETE` | `/v1/memories/{memory_id}/` | | Delete Memory | `DELETE` | `/v1/memories/{memory_id}/` |
Note: v1/v2 endpoints still work (backward compatible).
## Memory Object Structure ## Memory Object Structure
| Field | Type | Description | | Field | Type | Description |
@@ -29,6 +27,8 @@ Note: v1/v2 endpoints still work (backward compatible).
| `run_id` | string (nullable) | Run/session identifier | | `run_id` | string (nullable) | Run/session identifier |
| `metadata` | object | Custom key-value pairs | | `metadata` | object | Custom key-value pairs |
| `categories` | array of strings | Auto-assigned category tags | | `categories` | array of strings | Auto-assigned category tags |
| `immutable` | boolean | If true, prevents modification |
| `expiration_date` | datetime (nullable) | Auto-expiry date |
| `hash` | string | Content hash | | `hash` | string | Content hash |
| `created_at` | datetime | Creation timestamp | | `created_at` | datetime | Creation timestamp |
| `updated_at` | datetime | Last modification timestamp | | `updated_at` | datetime | Last modification timestamp |
@@ -50,9 +50,10 @@ Memories can be scoped to different levels:
## Processing Model ## Processing Model
- Memories are processed **asynchronously** (v3 default) - Memories are processed **asynchronously by default** (`async_mode=true`)
- Add responses return queued `ADD` events only (v3 is ADD-only, no UPDATE/DELETE) - Add responses return queued events (`ADD`, `UPDATE`, `DELETE`) for tracking
- Poll status via `GET /v1/event/{event_id}/` - Set `async_mode=false` for synchronous processing when needed
- Graph metadata is processed asynchronously -- use `get_all()` for complete graph data
## Filter System ## Filter System
@@ -105,17 +106,19 @@ Root must be `AND`, `OR`, or `NOT`. Simple shorthand `{"user_id": "alice"}` also
## Response Formats ## Response Formats
### Add Response (v3) ### Add Response
```json ```json
{ [
"message": "Memory processing has been queued for background execution", {
"status": "PENDING", "id": "mem_01JF8ZS4Y0R0SPM13R5R6H32CJ",
"event_id": "evt-uuid" "event": "ADD",
} "data": { "memory": "The user moved to Austin in 2025." }
}
]
``` ```
v3 is ADD-only. No UPDATE or DELETE events. Event types: `ADD`, `UPDATE`, `DELETE`. A single add can trigger multiple events.
### Search Response ### Search Response
@@ -134,17 +137,4 @@ v3 is ADD-only. No UPDATE or DELETE events.
} }
``` ```
In v3, `score` is a combined multi-signal relevance score. With `enable_graph=true`, includes additional `relations` array with entity relationships.
### Get All Response (v3)
```json
{
"count": 123,
"next": "https://api.mem0.ai/v3/memories/?page=2&page_size=50",
"previous": null,
"results": [...]
}
```
v3 returns paginated envelope. Use `page` and `page_size` query params.
+97 -41
View File
@@ -25,9 +25,9 @@ User Input → Retrieve relevant memories → Enrich LLM prompt → Generate res
Mem0 handles the complexity of extraction, deduplication, conflict resolution, and semantic retrieval so your application only needs to call `search()` and `add()`. Mem0 handles the complexity of extraction, deduplication, conflict resolution, and semantic retrieval so your application only needs to call `search()` and `add()`.
**Storage architecture:** **Dual storage architecture:**
- **Vector store**: Embeddings for semantic similarity search - **Vector store**: Embeddings for semantic similarity search
- **Entity store**: Automatic entity linking for relationship-aware retrieval - **Graph store** (optional): Entity nodes and relationship edges for structured knowledge
--- ---
@@ -40,32 +40,41 @@ Messages In
│ │
▼ ▼
┌─────────────────────┐ ┌─────────────────────┐
│ 1. EXTRACTION │ Single LLM call extracts all distinct new facts │ 1. EXTRACTION │ LLM analyzes messages, extracts key facts
│ (infer=True) │ If infer=False, stores raw text as-is │ (infer=True) │ If infer=False, stores raw text as-is
└─────────┬───────────┘ └─────────┬───────────┘
│ │
▼ ▼
┌─────────────────────┐ ┌─────────────────────┐
│ 2. DEDUPLICATION │ Hash-based dedup (MD5 prevents exact duplicates) │ 2. CONFLICT │ Checks existing memories for duplicates
│ │ No UPDATE/DELETE - v3 is ADD-only │ RESOLUTION │ Latest truth wins (newer overrides older)
│ │ Only runs when infer=True
└─────────┬───────────┘ └─────────┬───────────┘
│ │
▼ ▼
┌─────────────────────┐ ┌─────────────────────┐
│ 3. STORAGE │ Batch embed → vector store │ 3. STORAGE │ Generates embeddings → vector store
│ │ Entity extraction → entity store │ │ Optional: entity extraction → graph store
│ │ Indexes metadata, categories, timestamps
└─────────┬───────────┘ └─────────┬───────────┘
│ │
▼ ▼
Memory Object Memory Object
(id, memory, categories, structured_attributes)
``` ```
### Processing (v3) ### Processing modes
v3 processes memories asynchronously by default: **Async (default, `async_mode=True`):**
- API returns immediately: `{"status": "PENDING", "event_id": "evt-..."}` - API returns immediately: `{"status": "PENDING", "event_id": "..."}`
- Poll status via `GET /v1/event/{event_id}/` - Processing happens in background
- Use webhooks for completion notifications - Use webhooks for completion notifications
- Best for: high-throughput, non-blocking workflows
**Sync (`async_mode=False`):**
- API waits for full processing
- Returns complete memory object with `id`, `event`, `memory`
- Best for: real-time access immediately after add
### Extraction modes ### Extraction modes
@@ -84,7 +93,7 @@ v3 processes memories asynchronously by default:
--- ---
## Retrieval Pipeline (v3) ## Retrieval Pipeline
### What happens when you call `client.search()` ### What happens when you call `client.search()`
@@ -93,37 +102,45 @@ Query In
│ │
▼ ▼
┌─────────────────────┐ ┌─────────────────────┐
│ 1. PREPROCESSING │ Lemmatize keywords, extract entities │ 1. QUERY EMBEDDING │ Convert query to vector representation
└─────────┬───────────┘ └─────────┬───────────┘
│ │
▼ ▼
┌─────────────────────┐ ┌─────────────────────┐
│ 2. PARALLEL SCORING │ Semantic search (vector similarity) │ 2. VECTOR SEARCH │ Cosine similarity across stored embeddings
│ │ BM25 keyword search (term matching) │ │ Scoped by filters (user_id, agent_id, etc.)
│ │ Entity matching (entity graph boost)
└─────────┬───────────┘ └─────────┬───────────┘
│ │
▼ ▼ (optional enhancements)
┌─────────────────────┐ ┌─────────────────────┐
│ 3. SCORE FUSION │ Combine signals into single score │ 3a. KEYWORD SEARCH │ Expands results with specific terms (+10ms)
│ │ Optional: rerank=True for deep reordering │ 3b. RERANKING │ Deep semantic reordering (+150-200ms)
│ 3c. FILTER MEMORIES │ Precision filtering, removes low-relevance (+200-300ms)
└─────────┬───────────┘
│
▼ (if enable_graph=True)
┌─────────────────────┐
│ 4. GRAPH LOOKUP │ Finds entity relationships
│ │ Appends relations WITHOUT reranking vector results
└─────────┬───────────┘ └─────────┬───────────┘
│ │
▼ ▼
Results (combined score per memory) Results + Relations
``` ```
### v3 Search Defaults ### Retrieval enhancement combinations
| Parameter | Default | Notes | | Configuration | Latency | Best for |
|-----------|---------|-------| |--------------|---------|----------|
| `top_k` | 20 | Was 100 in v2 | | Base search only | ~100ms | Simple lookups |
| `threshold` | 0.1 | Was None in v2 | | `keyword_search=True` | ~110ms | Entity-heavy queries, broad coverage |
| `rerank` | False | Was True in v2 | | `rerank=True` | ~250-300ms | User-facing results, top-N precision |
| `keyword_search=True` + `rerank=True` | ~310ms | Balanced (recommended for most apps) |
| `rerank=True` + `filter_memories=True` | ~400-500ms | Safety-critical, production systems |
### Implicit null scoping ### Implicit null scoping
When you search with `filters={"user_id": "alice"}` only, Mem0 returns memories where `agent_id`, `app_id`, and `run_id` are all null. This prevents cross-scope leakage by default. When you search with `user_id="alice"` only, Mem0 returns memories where `agent_id`, `app_id`, and `run_id` are all null. This prevents cross-scope leakage by default.
To include memories with non-null fields, use explicit filters: To include memories with non-null fields, use explicit filters:
```python ```python
@@ -133,23 +150,53 @@ filters={"OR": [{"user_id": "alice"}]}
--- ---
## Memory Lifecycle (v3) ## Memory Lifecycle
v3 uses ADD-only extraction. Memories accumulate over time rather than being consolidated. ```
CREATE ──→ ACTIVE ──→ UPDATE ──→ ACTIVE
│ │ │
│ ▼ ▼
│ EXPIRED EXPIRED
│ (still stored, (still stored,
│ not retrieved) not retrieved)
│ │ │
▼ ▼ ▼
DELETE DELETE DELETE
(permanent)
```
### Creation ### Creation
- `client.add(messages, user_id="...")` - Triggered by `client.add(messages, user_id="...")`
- Single-pass extraction → deduplication → storage - Messages processed through extraction → conflict resolution → storage
- Returns `{"event_id": "...", "status": "PENDING"}` - Gets unique UUID, `created_at` timestamp
- Optional: custom `timestamp`, `expiration_date`, `metadata`, `immutable`
### Updates ### Updates
- `client.update(memory_id, text="...")` replaces text - `client.update(memory_id, text="...")` replaces text and reindexes
- Batch: `client.batch_update([...])` - `client.batch_update([...])` for up to 1000 memories at once
- Immutable memories (`immutable=True`) cannot be updated — must delete and re-add
### Deduplication
- Automatic during `add()` with `infer=True`
- Conflict resolution merges duplicate facts
- Latest truth wins when contradictions detected
- Prevents memory bloat from repeated information
### Expiration
- Optional `expiration_date` parameter (ISO 8601 or `YYYY-MM-DD`)
- After expiration: memory NOT returned in searches but remains in storage
- Useful for time-sensitive info (events, temporary preferences, session state)
### Deletion ### Deletion
- Single: `client.delete(memory_id)` - Single: `client.delete(memory_id)` — permanent, no recovery
- Batch: `client.batch_delete([...])` - Batch: `client.batch_delete([memory_ids])` — up to 1000
- Bulk: `client.delete_all(filters={"user_id": "alice"})` - Bulk: `client.delete_all(user_id="alice")` — all memories for entity
- `delete_all()` without filters raises error to prevent accidental data loss
### History tracking
- `client.history(memory_id)` returns version timeline
- Shows all changes: `{previous_value, new_value, action, timestamps}`
- Useful for audit trails and debugging
--- ---
@@ -167,6 +214,8 @@ v3 uses ADD-only extraction. Memories accumulate over time rather than being con
"categories": ["health", "preferences"], "categories": ["health", "preferences"],
"created_at": "2025-03-12T12:34:56Z", "created_at": "2025-03-12T12:34:56Z",
"updated_at": "2025-03-12T12:34:56Z", "updated_at": "2025-03-12T12:34:56Z",
"expiration_date": null,
"immutable": false,
"structured_attributes": { "structured_attributes": {
"day": 12, "month": 3, "year": 2025, "day": 12, "month": 3, "year": 2025,
"hour": 12, "minute": 34, "hour": 12, "minute": 34,
@@ -190,6 +239,8 @@ v3 uses ADD-only extraction. Memories accumulate over time rather than being con
| `categories` | array | Auto-assigned or custom category tags | | `categories` | array | Auto-assigned or custom category tags |
| `created_at` | datetime | Creation timestamp | | `created_at` | datetime | Creation timestamp |
| `updated_at` | datetime | Last modification timestamp | | `updated_at` | datetime | Last modification timestamp |
| `expiration_date` | datetime | Auto-expiry date (stops retrieval, data persists) |
| `immutable` | boolean | If true, prevents modification |
| `structured_attributes` | object | Temporal breakdown for time-based queries | | `structured_attributes` | object | Temporal breakdown for time-based queries |
| `score` | float | Semantic similarity (search results only, 0-1) | | `score` | float | Semantic similarity (search results only, 0-1) |
@@ -271,7 +322,7 @@ Mem0 supports three layers of memory, from shortest to longest lived:
```python ```python
def chat(user_input: str, user_id: str, session_id: str) -> str: def chat(user_input: str, user_id: str, session_id: str) -> str:
# 1. Retrieve user memories (long-term preferences) # 1. Retrieve user memories (long-term preferences)
user_mems = mem0.search(user_input, filters={"user_id": user_id}) user_mems = mem0.search(user_input, user_id=user_id)
# 2. Retrieve session memories (current task context) # 2. Retrieve session memories (current task context)
session_mems = mem0.search(user_input, filters={ session_mems = mem0.search(user_input, filters={
@@ -299,13 +350,18 @@ def chat(user_input: str, user_id: str, session_id: str) -> str:
| Operation | Typical Latency | | Operation | Typical Latency |
|-----------|----------------| |-----------|----------------|
| Hybrid search (v3 default) | ~100-150ms | | Base vector search | ~100ms |
| + keyword_search | +10ms |
| + reranking | +150-200ms | | + reranking | +150-200ms |
| Add (async) | < 50ms response | | + filter_memories | +200-300ms |
| Add (async, default) | < 50ms response, background processing |
| Add (sync) | 500ms-2s depending on extraction complexity |
| Graph operations | Slight overhead for large stores |
### Processing ### Processing
- **Async (default):** Returns immediately, processes in background - **Async mode (default):** Returns immediately, processes in background
- **Sync mode:** Waits for full extraction + storage pipeline
- **Batch operations:** Up to 1000 memories per batch_update/batch_delete - **Batch operations:** Up to 1000 memories per batch_update/batch_delete
- **Webhooks:** Real-time notifications when async processing completes - **Webhooks:** Real-time notifications when async processing completes
+92 -26
View File
@@ -5,7 +5,7 @@ Additional platform capabilities beyond core CRUD operations.
## Table of Contents ## Table of Contents
- [Advanced Retrieval](#advanced-retrieval) - [Advanced Retrieval](#advanced-retrieval)
- [Entity Linking](#entity-linking) - [Graph Memory](#graph-memory)
- [Custom Categories](#custom-categories) - [Custom Categories](#custom-categories)
- [Custom Instructions](#custom-instructions) - [Custom Instructions](#custom-instructions)
- [Criteria Retrieval](#criteria-retrieval) - [Criteria Retrieval](#criteria-retrieval)
@@ -18,58 +18,124 @@ Additional platform capabilities beyond core CRUD operations.
## Advanced Retrieval ## Advanced Retrieval
### Hybrid Search (v3 Default) Three enhancement options for tuning search precision, recall, and latency.
v3 uses multi-signal hybrid search combining: ### Keyword Search (`keyword_search=True`)
- **Semantic search** (vector similarity)
- **BM25 keyword search** (normalized term matching)
- **Entity matching** (entity graph boost)
This is automatic — no configuration needed. Expands results to include memories with specific terms, names, and technical keywords.
- Latency: +10ms
- Recall: Significantly increased
- Best for: entity-heavy queries, comprehensive coverage
### Reranking (`rerank=True`) ### Reranking (`rerank=True`)
Deep semantic reordering of results — most relevant first. Deep semantic reordering of results — most relevant first.
- Latency: +150-200ms - Latency: +150-200ms
- Default: `False` (was `True` in v2) - Accuracy: Significantly improved
- Best for: user-facing results, top-N precision - Best for: user-facing results, top-N precision
### Filter Memories (`filter_memories=True`)
Precision filtering — removes low-relevance results entirely.
- Latency: +200-300ms
- Precision: Maximized
- Best for: safety-critical applications, production systems
### Recommended Combinations
**Python:** **Python:**
```python ```python
results = client.search(query, filters={"user_id": "user123"}, rerank=True) # Fast & broad
results = client.search(query, keyword_search=True, user_id="user123")
# Balanced (recommended for most apps)
results = client.search(query, keyword_search=True, rerank=True, user_id="user123")
# High precision (critical apps)
results = client.search(query, rerank=True, filter_memories=True, user_id="user123")
``` ```
**TypeScript:** **TypeScript:**
```typescript ```typescript
const results = await client.search(query, { const results = await client.search(query, {
filters: { user_id: 'user123' }, user_id: 'user123',
keyword_search: true,
rerank: true, rerank: true,
}); });
``` ```
--- ---
## Entity Linking ## Graph Memory
v3 replaces graph memory with built-in entity linking. Entities (proper nouns, quoted text, compound noun phrases) are automatically extracted and linked across memories. Entity-level knowledge graph that creates relationships between memories.
### How It Works ### How It Works
1. **Extraction**: During `add()`, entities are automatically extracted from memory text 1. **Extraction**: LLM analyzes conversation and identifies entities and relationships
2. **Storage**: Entities are stored in a parallel collection (`{collection}_entities`) 2. **Storage**: Embeddings go to vector store; entity nodes and edges go to graph store
3. **Retrieval**: During `search()`, query entities are matched and used to boost relevant memories 3. **Retrieval**: Vector search returns semantic matches; graph relations are appended to results
Entity linking is automatic — no configuration required. The boost is folded into the combined `score` on each result. Graph relations **augment** vector results without reordering them. Vector similarity always determines hit sequence.
### v2 Migration Note ### Enabling Graph Memory
If you were using `enable_graph=True` in v2: **Per request:**
- Remove `enable_graph` from all API calls ```python
- Remove `graph_store` from OSS configuration client.add(messages, user_id="alice", enable_graph=True)
- Entity relationships are now consumed through retrieval ranking, not exposed as a separate `relations` array client.search("query", user_id="alice", enable_graph=True)
client.get_all(filters={"AND": [{"user_id": "alice"}]}, enable_graph=True)
```
See the [v2 to v3 migration guide](https://docs.mem0.ai/migration/oss-v2-to-v3) for details. **Project-level (default for all operations):**
```python
client.project.update(enable_graph=True)
```
```javascript
await client.updateProject({ enable_graph: true });
```
### Relation Structure
Each relation in the response contains:
| Field | Type | Description |
|-------|------|-------------|
| `source` | string | Source entity name |
| `source_type` | string | Source entity type (e.g., "Person") |
| `relationship` | string | Relationship label (e.g., "lives_in") |
| `target` | string | Target entity name |
| `target_type` | string | Target entity type (e.g., "City") |
| `score` | number | Confidence score |
**Example:**
```json
{
"relations": [
{
"source": "Joseph",
"source_type": "Person",
"relationship": "lives_in",
"target": "Seattle",
"target_type": "City",
"score": 0.92
}
]
}
```
### Technical Notes
- Graph Memory adds processing time; see docs for current plan availability
- Works optimally with rich conversation histories containing entity relationships
- Best suited for long-running assistants tracking evolving information
- Graph writes and reads toggle independently per request
- Multi-agent context supported via `user_id`, `agent_id`, `run_id` scoping
- Add operations are asynchronous; graph metadata may not be immediately available
--- ---
@@ -94,7 +160,7 @@ client.project.update(custom_categories=new_categories)
``` ```
```javascript ```javascript
await client.updateProject({ customCategories: newCategories }); await client.updateProject({ custom_categories: new_categories });
``` ```
**Retrieve active categories:** **Retrieve active categories:**
@@ -119,7 +185,7 @@ client.project.update(custom_instructions="Your guidelines here...")
``` ```
```javascript ```javascript
await client.updateProject({ customInstructions: "Your guidelines here..." }); await client.updateProject({ custom_instructions: "Your guidelines here..." });
``` ```
### Template Structure ### Template Structure
@@ -163,7 +229,7 @@ client.project.update(retrieval_criteria=retrieval_criteria)
```typescript ```typescript
await client.updateProject({ await client.updateProject({
retrievalCriteria: [ retrieval_criteria: [
{ name: 'joy', description: 'Positive emotions', weight: 3 }, { name: 'joy', description: 'Positive emotions', weight: 3 },
{ name: 'urgency', description: 'Time-sensitive items', weight: 4 }, { name: 'urgency', description: 'Time-sensitive items', weight: 4 },
], ],
@@ -215,7 +281,7 @@ for item in feedback_data:
```typescript ```typescript
await client.feedback('mem-123', { await client.feedback('mem-123', {
feedback: 'POSITIVE', feedback: 'POSITIVE',
feedbackReason: 'Accurately captured dietary preference', feedback_reason: 'Accurately captured dietary preference',
}); });
``` ```
@@ -27,7 +27,7 @@ from langchain_core.messages import SystemMessage, HumanMessage
from langchain_core.prompts import ChatPromptTemplate, MessagesPlaceholder from langchain_core.prompts import ChatPromptTemplate, MessagesPlaceholder
from mem0 import MemoryClient from mem0 import MemoryClient
llm = ChatOpenAI(model="gpt-5-mini") llm = ChatOpenAI(model="gpt-4.1-nano-2025-04-14")
mem0 = MemoryClient() mem0 = MemoryClient()
prompt = ChatPromptTemplate.from_messages([ prompt = ChatPromptTemplate.from_messages([
@@ -128,7 +128,7 @@ import { createMem0 } from "@mem0/vercel-ai-provider";
const mem0 = createMem0(); const mem0 = createMem0();
const { text } = await generateText({ const { text } = await generateText({
model: mem0("gpt-5-mini", { user_id: "borat" }), model: mem0("gpt-4-turbo", { user_id: "borat" }),
prompt: "Suggest me a good car to buy!", prompt: "Suggest me a good car to buy!",
}); });
``` ```
@@ -167,7 +167,7 @@ agent = Agent(
Use search_memory to recall past conversations. Use search_memory to recall past conversations.
Use save_memory to store important information.""", Use save_memory to store important information.""",
tools=[search_memory, save_memory], tools=[search_memory, save_memory],
model="gpt-5-mini" model="gpt-4.1-nano-2025-04-14"
) )
result = Runner.run_sync(agent, "I love Italian food and I'm planning a trip to Rome next month") result = Runner.run_sync(agent, "I love Italian food and I'm planning a trip to Rome next month")
@@ -183,21 +183,21 @@ travel_agent = Agent(
name="Travel Planner", name="Travel Planner",
instructions="You are a travel planning specialist. Use search_memory and save_memory tools.", instructions="You are a travel planning specialist. Use search_memory and save_memory tools.",
tools=[search_memory, save_memory], tools=[search_memory, save_memory],
model="gpt-5-mini" model="gpt-4.1-nano-2025-04-14"
) )
health_agent = Agent( health_agent = Agent(
name="Health Advisor", name="Health Advisor",
instructions="You are a health and wellness advisor. Use search_memory and save_memory tools.", instructions="You are a health and wellness advisor. Use search_memory and save_memory tools.",
tools=[search_memory, save_memory], tools=[search_memory, save_memory],
model="gpt-5-mini" model="gpt-4.1-nano-2025-04-14"
) )
triage_agent = Agent( triage_agent = Agent(
name="Personal Assistant", name="Personal Assistant",
instructions="""Route travel questions to Travel Planner, health questions to Health Advisor.""", instructions="""Route travel questions to Travel Planner, health questions to Health Advisor.""",
handoffs=[travel_agent, health_agent], handoffs=[travel_agent, health_agent],
model="gpt-5-mini" model="gpt-4.1-nano-2025-04-14"
) )
result = Runner.run_sync(triage_agent, "Plan a healthy meal for my Italy trip") result = Runner.run_sync(triage_agent, "Plan a healthy meal for my Italy trip")
@@ -254,7 +254,7 @@ from langchain_openai import ChatOpenAI
from mem0 import MemoryClient from mem0 import MemoryClient
from langchain_core.messages import SystemMessage, HumanMessage, AIMessage from langchain_core.messages import SystemMessage, HumanMessage, AIMessage
llm = ChatOpenAI(model="gpt-5-mini") llm = ChatOpenAI(model="gpt-4")
mem0 = MemoryClient() mem0 = MemoryClient()
class State(TypedDict): class State(TypedDict):
@@ -319,7 +319,7 @@ memory = Mem0Memory.from_client(
from llama_index.core.agent import FunctionCallingAgent from llama_index.core.agent import FunctionCallingAgent
from llama_index.llms.openai import OpenAI from llama_index.llms.openai import OpenAI
llm = OpenAI(model="gpt-5-mini") llm = OpenAI(model="gpt-4")
agent = FunctionCallingAgent.from_tools( agent = FunctionCallingAgent.from_tools(
tools=[], tools=[],
llm=llm, llm=llm,
@@ -352,7 +352,7 @@ USER_ID = "alice"
agent = ConversableAgent( agent = ConversableAgent(
"chatbot", "chatbot",
llm_config={"config_list": [{"model": "gpt-5-mini", "api_key": os.environ["OPENAI_API_KEY"]}]}, llm_config={"config_list": [{"model": "gpt-4", "api_key": os.environ["OPENAI_API_KEY"]}]},
code_execution_config=False, code_execution_config=False,
human_input_mode="NEVER", human_input_mode="NEVER",
) )
+2 -2
View File
@@ -59,11 +59,11 @@ const messages = [
{"role": "user", "content": "I'm a vegetarian and allergic to nuts."}, {"role": "user", "content": "I'm a vegetarian and allergic to nuts."},
{"role": "assistant", "content": "Got it! I'll remember your dietary preferences."} {"role": "assistant", "content": "Got it! I'll remember your dietary preferences."}
]; ];
await client.add(messages, { userId: "user123" }); await client.add(messages, { user_id: "user123" });
// Search memories // Search memories
const results = await client.search("What are my dietary restrictions?", { const results = await client.search("What are my dietary restrictions?", {
filters: { user_id: "user123" } user_id: "user123"
}); });
console.log(results); console.log(results);
``` ```
+53 -96
View File
@@ -40,12 +40,16 @@ client.add(messages, user_id="alice")
# With metadata # With metadata
client.add(messages, user_id="alice", metadata={"source": "onboarding"}) client.add(messages, user_id="alice", metadata={"source": "onboarding"})
# With graph memory
client.add(messages, user_id="alice", enable_graph=True)
``` ```
**TypeScript:** **TypeScript:**
```typescript ```typescript
await client.add(messages, { userId: "alice" }); await client.add(messages, { user_id: "alice" });
await client.add(messages, { userId: "alice", metadata: { source: "onboarding" } }); await client.add(messages, { user_id: "alice", metadata: { source: "onboarding" } });
await client.add(messages, { user_id: "alice", enable_graph: true });
``` ```
### Parameters ### Parameters
@@ -57,14 +61,32 @@ await client.add(messages, { userId: "alice", metadata: { source: "onboarding" }
| `agent_id` | string | Agent identifier | | `agent_id` | string | Agent identifier |
| `run_id` | string | Session identifier | | `run_id` | string | Session identifier |
| `metadata` | object | Custom key-value pairs | | `metadata` | object | Custom key-value pairs |
| `enable_graph` | boolean | Activate knowledge graph |
| `infer` | boolean | If `false`, store raw text without inference (default: `true`) | | `infer` | boolean | If `false`, store raw text without inference (default: `true`) |
| `immutable` | boolean | Prevents modification after creation |
| `expiration_date` | string | Auto-expiry date (`YYYY-MM-DD`) |
| `includes` | string | Preference filters for inclusion |
| `excludes` | string | Preference filters for exclusion |
| `async_mode` | boolean | Async processing (default: `true`). Set `false` to wait |
### Advanced Add Options ### Advanced Add Options
```python ```python
# Immutable -- cannot be modified or overwritten
client.add(messages, user_id="alice", immutable=True)
# Expiring memory
client.add(messages, user_id="alice", expiration_date="2025-12-31")
# Selective extraction
client.add(messages, user_id="alice", includes="dietary preferences", excludes="payment info")
# Agent + session scoping # Agent + session scoping
client.add(messages, user_id="alice", agent_id="nutrition-agent", run_id="session-456") client.add(messages, user_id="alice", agent_id="nutrition-agent", run_id="session-456")
# Synchronous processing (wait for completion)
client.add(messages, user_id="alice", async_mode=False)
# Raw text -- skip LLM inference # Raw text -- skip LLM inference
client.add( client.add(
[{"role": "user", "content": "User prefers dark mode."}], [{"role": "user", "content": "User prefers dark mode."}],
@@ -79,7 +101,7 @@ client.add(
**Python:** **Python:**
```python ```python
results = client.search("dietary preferences?", filters={"user_id": "alice"}) results = client.search("dietary preferences?", user_id="alice")
# With filters and reranking # With filters and reranking
results = client.search( results = client.search(
@@ -89,14 +111,20 @@ results = client.search(
rerank=True, rerank=True,
threshold=0.5 threshold=0.5
) )
# With graph relations
results = client.search("colleagues", user_id="alice", enable_graph=True)
# Keyword search
results = client.search("vegetarian", user_id="alice", keyword_search=True)
``` ```
**TypeScript:** **TypeScript:**
```typescript ```typescript
const results = await client.search("dietary preferences", { filters: { user_id: "alice" } }); const results = await client.search("dietary preferences", { user_id: "alice" });
const results = await client.search("work experience", { const results = await client.search("work experience", {
filters: { AND: [{ user_id: "alice" }, { categories: { contains: "professional_details" } }] }, filters: { AND: [{ user_id: "alice" }, { categories: { contains: "professional_details" } }] },
topK: 5, top_k: 5,
rerank: true, rerank: true,
}); });
``` ```
@@ -106,17 +134,19 @@ const results = await client.search("work experience", {
| Name | Type | Description | | Name | Type | Description |
|------|------|-------------| |------|------|-------------|
| `query` | string | Natural language search query | | `query` | string | Natural language search query |
| `filters` | object | Filter object (AND/OR operators). Use `{"user_id": "..."}` to filter by user | | `user_id` | string | Filter by user |
| `top_k` | number | Number of results (default: 10 for Platform) | | `filters` | object | V2 filter object (AND/OR operators) |
| `rerank` | boolean | Enable reranking for better relevance (default: `false`) | | `top_k` | number | Number of results (default: 10) |
| `threshold` | number | Minimum similarity score (default: 0.1) | | `rerank` | boolean | Enable reranking for better relevance |
| `threshold` | number | Minimum similarity score (default: 0.3) |
| `keyword_search` | boolean | Use keyword-based search |
| `enable_graph` | boolean | Include graph relations |
### Common Filter Patterns ### Common Filter Patterns
**Python:**
```python ```python
# Single user filter # Single user (shorthand)
filters={"user_id": "alice"} client.search("query", user_id="alice")
# OR across agents # OR across agents
filters={"OR": [{"user_id": "alice"}, {"agent_id": {"in": ["travel-agent", "sports-agent"]}}]} filters={"OR": [{"user_id": "alice"}, {"agent_id": {"in": ["travel-agent", "sports-agent"]}}]}
@@ -149,21 +179,6 @@ filters={"AND": [
]} ]}
``` ```
**TypeScript:**
```typescript
// Single user filter
filters: { user_id: "alice" }
// OR across agents
filters: { OR: [{ user_id: "alice" }, { agent_id: { in: ["travel-agent", "sports-agent"] } }] }
// Category filtering (partial match)
filters: { AND: [{ user_id: "alice" }, { categories: { contains: "finance" } }] }
// Category filtering (exact match)
filters: { AND: [{ user_id: "alice" }, { categories: { in: ["personal_information"] } }] }
```
--- ---
## get() / getAll() -- Retrieve Memories ## get() / getAll() -- Retrieve Memories
@@ -174,7 +189,7 @@ filters: { AND: [{ user_id: "alice" }, { categories: { in: ["personal_informatio
memory = client.get(memory_id="ea925981-...") memory = client.get(memory_id="ea925981-...")
# All memories for a user # All memories for a user
memories = client.get_all(filters={"user_id": "alice"}) memories = client.get_all(filters={"AND": [{"user_id": "alice"}]})
# With date range # With date range
memories = client.get_all( memories = client.get_all(
@@ -183,12 +198,15 @@ memories = client.get_all(
{"created_at": {"gte": "2024-07-01", "lte": "2024-07-31"}} {"created_at": {"gte": "2024-07-01", "lte": "2024-07-31"}}
]} ]}
) )
# With graph data
memories = client.get_all(filters={"AND": [{"user_id": "alice"}]}, enable_graph=True)
``` ```
**TypeScript:** **TypeScript:**
```typescript ```typescript
const memory = await client.get("ea925981-..."); const memory = await client.get("ea925981-...");
const memories = await client.getAll({ filters: { user_id: "alice" } }); const memories = await client.getAll({ filters: { AND: [{ user_id: "alice" }] } });
``` ```
**Note:** `get_all` requires at least one of `user_id`, `agent_id`, `app_id`, or `run_id` in filters. **Note:** `get_all` requires at least one of `user_id`, `agent_id`, `app_id`, or `run_id` in filters.
@@ -208,6 +226,8 @@ client.update(memory_id="ea925981-...", text="Updated", metadata={"verified": Tr
await client.update("ea925981-...", { text: "Updated: vegan since 2024" }); await client.update("ea925981-...", { text: "Updated: vegan since 2024" });
``` ```
Cannot update immutable memories.
--- ---
## delete() / deleteAll() -- Remove Memories ## delete() / deleteAll() -- Remove Memories
@@ -221,7 +241,7 @@ client.delete_all(user_id="alice") # Irreversible bulk delete
**TypeScript:** **TypeScript:**
```typescript ```typescript
await client.delete("ea925981-..."); await client.delete("ea925981-...");
await client.deleteAll({ userId: "alice" }); await client.deleteAll({ user_id: "alice" });
``` ```
--- ---
@@ -281,73 +301,10 @@ data = client.get_memory_export(memory_export_id=export["id"])
2. **SQL operators rejected** -- use `gte`, `lt`, etc. Not `>=`, `<`. 2. **SQL operators rejected** -- use `gte`, `lt`, etc. Not `>=`, `<`.
3. **Metadata filtering is limited** -- only top-level keys with `eq`, `contains`, `ne`. 3. **Metadata filtering is limited** -- only top-level keys with `eq`, `contains`, `ne`.
4. **Wildcard `*` excludes null** -- only matches non-null values. 4. **Wildcard `*` excludes null** -- only matches non-null values.
5. **Default threshold is 0.1** -- increase for stricter matching. 5. **Default threshold is 0.3** -- increase for stricter matching.
6. **Async processing** -- memories process asynchronously. Wait 2-3s after `add()` before searching. 6. **Async processing** -- memories process asynchronously. Wait 2-3s after `add()` before searching.
7. **Immutable memories** -- cannot be updated or deleted once created.
## Naming Conventions ## Naming Conventions
Python uses `snake_case` everywhere (`user_id`, `memory_id`, `get_all`). TypeScript uses `camelCase` for methods (`getAll`, `deleteAll`, `batchUpdate`) and top-level parameters (`userId`, `topK`, `pageSize`), but filter keys use `snake_case` (`user_id`, `agent_id`). Python uses `snake_case` (`user_id`, `memory_id`, `get_all`). TypeScript uses `camelCase` for methods (`getAll`, `deleteAll`, `batchUpdate`) but `snake_case` for API parameters (`user_id`, `agent_id`).
---
## v2 to v3 Migration
### Breaking Changes in v3
**1. Entity IDs in search() and getAll()**
v3 requires entity IDs (`user_id`, `agent_id`, `run_id`) inside `filters` instead of as top-level parameters:
```python
# v2 (deprecated)
client.search("query", user_id="alice")
client.get_all(user_id="alice")
# v3
client.search("query", filters={"user_id": "alice"})
client.get_all(filters={"user_id": "alice"})
```
```typescript
// v2 (deprecated)
await client.search("query", { user_id: "alice" });
await client.getAll({ user_id: "alice" });
// v3
await client.search("query", { filters: { user_id: "alice" } });
await client.getAll({ filters: { user_id: "alice" } });
```
**2. TypeScript Parameter Naming**
v3 TypeScript uses camelCase for all parameters:
| v2 | v3 |
|----|-----|
| `user_id` | `userId` |
| `agent_id` | `agentId` |
| `run_id` | `runId` |
| `top_k` | `topK` |
| `page_size` | `pageSize` |
**3. Default Values Changed**
| Parameter | v2 Default | v3 Default |
|-----------|------------|------------|
| `threshold` | 0.3 | 0.1 |
| `rerank` | (not specified) | `false` |
**4. Removed Parameters**
The following parameters are no longer supported:
| Parameter | Status |
|-----------|--------|
| `enable_graph` | Removed from add/search/getAll |
| `keyword_search` | Removed from search |
| `filter_memories` | Removed |
| `immutable` | Removed from add |
| `expiration_date` | Removed from add |
| `includes` | Removed from add |
| `excludes` | Removed from add |
| `async_mode` | Removed from add |
+24 -24
View File
@@ -39,7 +39,7 @@ Use these known facts about the user to personalize your response:
{context if context else 'No prior context yet.'}""" {context if context else 'No prior context yet.'}"""
response = openai_client.chat.completions.create( response = openai_client.chat.completions.create(
model="gpt-5-mini", model="gpt-4.1-nano-2025-04-14",
messages=[ messages=[
{"role": "system", "content": system_prompt}, {"role": "system", "content": system_prompt},
{"role": "user", "content": user_input}, {"role": "user", "content": user_input},
@@ -72,14 +72,14 @@ const openai = new OpenAI();
async function chat(userInput: string, userId: string): Promise<string> { async function chat(userInput: string, userId: string): Promise<string> {
// 1. Retrieve relevant memories // 1. Retrieve relevant memories
const memories = await mem0.search(userInput, { filters: { user_id: userId } }); const memories = await mem0.search(userInput, { user_id: userId });
const context = memories.results const context = memories.results
?.map((m: any) => `- ${m.memory}`) ?.map((m: any) => `- ${m.memory}`)
.join('\n') || 'No prior context yet.'; .join('\n') || 'No prior context yet.';
// 2. Generate response with memory context // 2. Generate response with memory context
const response = await openai.chat.completions.create({ const response = await openai.chat.completions.create({
model: 'gpt-5-mini', model: 'gpt-4.1-nano-2025-04-14',
messages: [ messages: [
{ role: 'system', content: `You are Ray, a personal fitness coach.\nUser context:\n${context}` }, { role: 'system', content: `You are Ray, a personal fitness coach.\nUser context:\n${context}` },
{ role: 'user', content: userInput }, { role: 'user', content: userInput },
@@ -90,7 +90,7 @@ async function chat(userInput: string, userId: string): Promise<string> {
// 3. Store interaction // 3. Store interaction
await mem0.add( await mem0.add(
[{ role: 'user', content: userInput }, { role: 'assistant', content: reply }], [{ role: 'user', content: userInput }, { role: 'assistant', content: reply }],
{ userId: userId } { user_id: userId }
); );
return reply; return reply;
} }
@@ -182,7 +182,7 @@ await client.updateProject({
async function logInteraction(userId: string, message: string, priority = 'normal') { async function logInteraction(userId: string, message: string, priority = 'normal') {
await client.add( await client.add(
[{ role: 'user', content: message }], [{ role: 'user', content: message }],
{ userId: userId, metadata: { priority, source: 'support_chat' } } { user_id: userId, metadata: { priority, source: 'support_chat' } }
); );
} }
@@ -230,7 +230,7 @@ def consult(user_id: str, question: str) -> str:
context = "\n".join([f"- {m['memory']}" for m in memories.get("results", [])]) context = "\n".join([f"- {m['memory']}" for m in memories.get("results", [])])
response = openai_client.chat.completions.create( response = openai_client.chat.completions.create(
model="gpt-5-mini", model="gpt-4.1-nano-2025-04-14",
messages=[ messages=[
{"role": "system", "content": f"You are a health coach. Patient context:\n{context}"}, {"role": "system", "content": f"You are a health coach. Patient context:\n{context}"},
{"role": "user", "content": question}, {"role": "user", "content": question},
@@ -264,20 +264,20 @@ const openai = new OpenAI();
async function savePatientInfo(userId: string, info: string) { async function savePatientInfo(userId: string, info: string) {
await mem0.add( await mem0.add(
[{ role: 'user', content: info }], [{ role: 'user', content: info }],
{ userId: userId, runId: 'healthcare_session', metadata: { type: 'patient_information' } } { user_id: userId, run_id: 'healthcare_session', metadata: { type: 'patient_information' } }
); );
} }
async function consult(userId: string, question: string): Promise<string> { async function consult(userId: string, question: string): Promise<string> {
const memories = await mem0.search(question, { const memories = await mem0.search(question, {
filters: { user_id: userId }, user_id: userId,
topK: 5, top_k: 5,
threshold: 0.7, threshold: 0.7,
}); });
const context = memories.results?.map((m: any) => `- ${m.memory}`).join('\n') || ''; const context = memories.results?.map((m: any) => `- ${m.memory}`).join('\n') || '';
const response = await openai.chat.completions.create({ const response = await openai.chat.completions.create({
model: 'gpt-5-mini', model: 'gpt-4.1-nano-2025-04-14',
messages: [ messages: [
{ role: 'system', content: `You are a health coach. Patient context:\n${context}` }, { role: 'system', content: `You are a health coach. Patient context:\n${context}` },
{ role: 'user', content: question }, { role: 'user', content: question },
@@ -287,7 +287,7 @@ async function consult(userId: string, question: string): Promise<string> {
await mem0.add( await mem0.add(
[{ role: 'user', content: question }, { role: 'assistant', content: reply }], [{ role: 'user', content: question }, { role: 'assistant', content: reply }],
{ userId: userId, runId: 'healthcare_session' } { user_id: userId, run_id: 'healthcare_session' }
); );
return reply; return reply;
} }
@@ -333,7 +333,7 @@ def draft_content(user_id: str, topic: str) -> str:
style_context = "\n".join([f"- {m['memory']}" for m in prefs.get("results", [])]) style_context = "\n".join([f"- {m['memory']}" for m in prefs.get("results", [])])
response = openai_client.chat.completions.create( response = openai_client.chat.completions.create(
model="gpt-5-mini", model="gpt-4.1-nano-2025-04-14",
messages=[ messages=[
{"role": "system", "content": f"Write content matching these style preferences:\n{style_context}"}, {"role": "system", "content": f"Write content matching these style preferences:\n{style_context}"},
{"role": "user", "content": f"Write a blog post about: {topic}"}, {"role": "user", "content": f"Write a blog post about: {topic}"},
@@ -359,7 +359,7 @@ const openai = new OpenAI();
async function storePreferences(userId: string, preferences: string) { async function storePreferences(userId: string, preferences: string) {
await mem0.add( await mem0.add(
[{ role: 'user', content: preferences }], [{ role: 'user', content: preferences }],
{ userId: userId, runId: 'editing_session', metadata: { type: 'preferences' } } { user_id: userId, run_id: 'editing_session', metadata: { type: 'preferences' } }
); );
} }
@@ -370,7 +370,7 @@ async function draftContent(userId: string, topic: string): Promise<string> {
const styleContext = prefs.results?.map((m: any) => `- ${m.memory}`).join('\n') || ''; const styleContext = prefs.results?.map((m: any) => `- ${m.memory}`).join('\n') || '';
const response = await openai.chat.completions.create({ const response = await openai.chat.completions.create({
model: 'gpt-5-mini', model: 'gpt-4.1-nano-2025-04-14',
messages: [ messages: [
{ role: 'system', content: `Write content matching these preferences:\n${styleContext}` }, { role: 'system', content: `Write content matching these preferences:\n${styleContext}` },
{ role: 'user', content: `Write a blog post about: ${topic}` }, { role: 'user', content: `Write a blog post about: ${topic}` },
@@ -465,10 +465,10 @@ async function storeScopedMemory(
userId: string, agentId: string, runId: string, appId: string userId: string, agentId: string, runId: string, appId: string
) { ) {
await client.add(messages, { await client.add(messages, {
userId: userId, user_id: userId,
agentId: agentId, agent_id: agentId,
runId: runId, run_id: runId,
appId: appId, app_id: appId,
}); });
} }
@@ -520,7 +520,7 @@ def personalized_search(user_id: str, query: str, search_results: list) -> str:
user_context = "\n".join([f"- {m['memory']}" for m in memories.get("results", [])]) user_context = "\n".join([f"- {m['memory']}" for m in memories.get("results", [])])
response = openai_client.chat.completions.create( response = openai_client.chat.completions.create(
model="gpt-5-mini", model="gpt-4.1-nano-2025-04-14",
messages=[ messages=[
{"role": "system", "content": f"Personalize search results using user context:\n{user_context}"}, {"role": "system", "content": f"Personalize search results using user context:\n{user_context}"},
{"role": "user", "content": f"Query: {query}\n\nSearch results:\n{search_results}"}, {"role": "user", "content": f"Query: {query}\n\nSearch results:\n{search_results}"},
@@ -551,11 +551,11 @@ const mem0 = new MemoryClient({ apiKey: process.env.MEM0_API_KEY! });
const openai = new OpenAI(); const openai = new OpenAI();
async function personalizedSearch(userId: string, query: string, searchResults: string[]): Promise<string> { async function personalizedSearch(userId: string, query: string, searchResults: string[]): Promise<string> {
const memories = await mem0.search(query, { filters: { user_id: userId }, topK: 5 }); const memories = await mem0.search(query, { user_id: userId, top_k: 5 });
const context = memories.results?.map((m: any) => `- ${m.memory}`).join('\n') || ''; const context = memories.results?.map((m: any) => `- ${m.memory}`).join('\n') || '';
const response = await openai.chat.completions.create({ const response = await openai.chat.completions.create({
model: 'gpt-5-mini', model: 'gpt-4.1-nano-2025-04-14',
messages: [ messages: [
{ role: 'system', content: `Personalize results using user context:\n${context}` }, { role: 'system', content: `Personalize results using user context:\n${context}` },
{ role: 'user', content: `Query: ${query}\nResults: ${searchResults.join(', ')}` }, { role: 'user', content: `Query: ${query}\nResults: ${searchResults.join(', ')}` },
@@ -563,7 +563,7 @@ async function personalizedSearch(userId: string, query: string, searchResults:
}); });
const reply = response.choices[0].message.content!; const reply = response.choices[0].message.content!;
await mem0.add([{ role: 'user', content: query }], { userId: userId }); await mem0.add([{ role: 'user', content: query }], { user_id: userId });
return reply; return reply;
} }
``` ```
@@ -631,14 +631,14 @@ const client = new MemoryClient({ apiKey: process.env.MEM0_API_KEY! });
async function storeEmail(userId: string, sender: string, subject: string, body: string, date: string) { async function storeEmail(userId: string, sender: string, subject: string, body: string, date: string) {
await client.add( await client.add(
[{ role: 'user', content: `Email from ${sender}: ${subject}\n\n${body}` }], [{ role: 'user', content: `Email from ${sender}: ${subject}\n\n${body}` }],
{ userId: userId, metadata: { email_type: 'incoming', sender, subject, date } } { user_id: userId, metadata: { email_type: 'incoming', sender, subject, date } }
); );
} }
async function searchEmails(userId: string, query: string) { async function searchEmails(userId: string, query: string) {
return client.search(query, { return client.search(query, {
filters: { AND: [{ user_id: userId }, { categories: { contains: 'email' } }] }, filters: { AND: [{ user_id: userId }, { categories: { contains: 'email' } }] },
topK: 10, top_k: 10,
}); });
} }
``` ```