Compare commits

...

76 Commits

Author SHA1 Message Date
Saket Aryan 34c797d285 fix: disable ph telemetry still calls posthog (#4203) 2026-03-04 03:55:34 +05:30
Saket Aryan a0d8a02b94 chore(ts-sdk): bump axios to 1.13.6 (#4177) 2026-03-02 13:24:35 +05:30
Saket Aryan 93c720301e docs: update delete_all to reflect filter validation breaking change (#4103) 2026-02-25 21:10:35 +05:30
mgoulart db15d5c629 fix(oss): validate LLM fact output via FactRetrievalSchema before embedding (#4083) 2026-02-22 19:57:48 -08:00
mem0-bot[bot] aa4a944b51 fix: Bug: Openclaw Extension OSS Mode lacks threshold restrictions (#4106) (#4115) 2026-02-22 18:44:11 -08:00
Prathamesh ab5e930cf7 Update OpenClaw integration architecture diagram (#4079) 2026-02-19 16:42:43 -08:00
Deshraj Yadav 0e76de7bd5 Add source openclaw (#4082) 2026-02-19 16:35:41 -08:00
Mragank Shekhar 5a93643f12 docs: add memory_categorize webhook event type (#4077) 2026-02-19 15:09:11 +05:30
Mragank Shekhar a140829395 chore: update user facing timestamp for a memory (#4066) 2026-02-18 03:27:46 +05:30
Zlo7 a6810819ca OpenClaw plugin: fix auto-recall injection and auto-capture message drop (#4065) 2026-02-17 13:26:45 -08:00
Saket Aryan a02205e519 chore: remove legacy v0.x docs and version dropdown (#4060) 2026-02-16 13:25:05 -08:00
Saket Aryan 69a832dc58 chore: add update project options (#3947) 2026-02-03 10:55:43 +05:30
Deshraj Yadav 70baa46cb1 fix: add OpenClaw to docs navigation (#3965) 2026-02-02 10:17:19 -08:00
Deshraj Yadav 3d3e875d21 Feature: Add OpenClaw plugin and documentation (#3964) 2026-02-02 10:04:08 -08:00
Saket Aryan dba7f0458a (version-bump): update the project version to v1.0.2 (#3902) 2026-01-13 13:01:38 +05:30
Saket Aryan 27e5db5831 (fix): mongodb distribution name, azure ai search, and workflow trigger (#3900) 2026-01-13 12:52:49 +05:30
Saket Aryan 2c90eedfff chore: do a disk cleanup in gh actions to fix memo build (#3899) 2026-01-13 11:42:54 +05:30
Noah Stapp a1db0f6362 Add DriverInfo metadata to MongoDB vector store (#3648) 2026-01-12 21:07:42 -08:00
Saket Aryan 90a7b1afa0 feat(ts-sdk): add support for keyword arguments in add and search methods (#3895) 2026-01-10 21:19:55 +05:30
Saket Aryan 69a552d8a8 fix(docs): Improve light mode support for introduction page and organize thumbnails (#3880) 2026-01-03 21:21:24 +05:30
Saket Aryan 417ebffadd (ts-sdk-update): Update for TypeScript SDK v2.2. (#3865) 2025-12-29 15:01:18 +05:30
Saket Aryan 1dc07d3550 (docs): update to use the v2 URL Patterns in delete user route (#3864) 2025-12-29 14:51:42 +05:30
Saket Aryan 65e22e34d9 chore: remove unnecessary dependencies from Vercel AI SDK to reduce package size (#3856) 2025-12-26 22:24:40 +05:30
Parth Sharma e08f44c5f2 [docs] link to fix api key redirect (#3843) 2025-12-18 00:20:29 +05:30
Parth Sharma 16d989bbcd [docs] Series of docs for mem0-mcp (#3831) 2025-12-15 22:03:23 +05:30
Swarnaprakash Udayakumar 0f8654bd40 Add Strands agent (with AWS ElastiCache and Neptune) example mention in Joint blog post by Mem0 and AWS (#3824) 2025-12-13 14:00:29 +05:30
Parth Sharma 654089fcfc [docs] Filters fix in docs (#3815) 2025-12-11 18:38:08 +05:30
Parth Sharma 222c6ceea1 (docs-fix): fix broken redirect in python and node quickstart (#3826) 2025-12-11 15:50:20 +05:30
Parth Sharma 84bd6e3b97 fix(docs): Correct API authentication header from Bearer to Token (#3820) 2025-12-11 00:32:59 +05:30
Parth Sharma 5676bebd5f docs: migration guide v1 (#3822) 2025-12-10 23:45:19 +05:30
Parth Sharma f14132db44 [docs] Gemini-3 demo with mem0-mcp (#3810) 2025-12-09 23:43:49 +05:30
Parth Sharma 903c3635cc [docs] Add memory and v2 docs fixup (#3792) 2025-11-27 23:41:51 +05:30
Parth Sharma cc2894aaec [docs] Docs redirect to platform (#3769) 2025-11-22 10:17:58 +05:30
Deshraj Yadav 97cbff77ef Add events API docs and spec updates (#3752) 2025-11-14 20:53:31 -08:00
Parth Sharma e29220efda [docs] new redirect for entity doc (#3750) 2025-11-14 08:51:25 -08:00
Prateek Chhikara 3b84a234e1 Updates to python sdk (#3749) 2025-11-13 14:22:39 -08:00
Parth Sharma 2bca30ebe6 [docs] Minor Docs fixes ( enhancements , restructure ) (#3748) 2025-11-13 11:58:36 -08:00
Parth Sharma 3297ec1a46 [doc] Partition Memories by Entity , features doc and cookbook (#3735) 2025-11-13 10:26:41 -08:00
Parth Sharma 61e2a40d55 [docs] python quickstart fix (#3742) 2025-11-13 10:18:55 -08:00
Parth Sharma 9f921e27cb [docs] add callouts and comparision to clear the problem of when to use Infer=True/False (#3738) 2025-11-10 14:23:49 -08:00
Parth Sharma 568e97d013 [docs] graph memory docs fix (#3728) 2025-11-07 09:41:35 -08:00
Parth Sharma ac5660e26d [docs] LLM.txt + Context menu to make our Docs LLM friendly (#3726) 2025-11-07 09:38:12 -08:00
Parth Sharma 76abd5117d [docs] API References and search Doc fix (#3712) 2025-11-04 13:53:37 -08:00
Prateek Chhikara 978babd3db Docs Update (#3706) 2025-11-03 11:03:33 -08:00
Parth Sharma 2b0a457198 [docs] Custom categories Documentation fix (#3702) 2025-11-03 10:11:04 -08:00
Parth Sharma 6a7277070f [docs] Add Redirects to the new docs to fix broken links (#3701) 2025-11-01 06:19:47 -07:00
Parth Sharma 4c53930e47 [docs] complete redirects (#3700) 2025-10-31 20:26:30 -07:00
Parth Sharma 84687fc3d2 [fix] list' object has no attribute 'id' - Id fault with chroma pinecone and other providers (#3693) 2025-10-31 16:46:10 +05:30
Parth Sharma 3ca939e210 [docs] redirect with fixed ci fails - langchain (#3699) 2025-10-31 16:45:15 +05:30
Parth Sharma 5f5e64b44b [docs] tab icon cleanup (#3679) 2025-10-28 09:42:19 +01:00
Parth Sharma 5cb6b31690 [docs] Cookbook name cleanup (#3678) 2025-10-28 09:20:23 +01:00
Parth Sharma ee8955d08b [docs] OSS Features , Overview , Brushup (#3676) 2025-10-27 12:31:40 -07:00
Parth Sharma 80c9139c5b [docs] zoom effect fix (#3670) 2025-10-27 08:56:32 +05:30
Parth Sharma 7be32641c7 [docs] Essential cookbook added and overall revamp to the structure of cookbooks (#3668) 2025-10-27 00:19:29 +05:30
Parth Sharma 2c18355dd2 [docs] platform core concept revamp and overview update (#3664) 2025-10-26 15:15:13 +05:30
Parth Sharma 61faf71064 [docs] Template moulding in docs/platform and index improvement (#3663) 2025-10-25 14:05:18 -07:00
Parth Sharma ac9598a67f [docs] Added Templates and Contribution Guidelines (#3662) 2025-10-25 12:58:40 -07:00
Parth Sharma f98a17c716 [docs] Welcome page thumbnail and reranker fix (#3660) 2025-10-25 12:20:52 -07:00
Vedant Thakkar 639d26e1ac feat(api): add vector store configuration endpoints (#3583) 2025-10-23 18:36:25 +05:30
Parth Sharma f7d7c53001 Added improved docs index and overview pages and quickstart (#3603) 2025-10-22 10:30:45 -07:00
Frederik Berg ec1a60bf8d Add delete_memories MCP tool for targeted deletion (#3616) 2025-10-22 10:08:28 -07:00
Frederik Berg 77c71a134a Fix REST API infer parameter ignored (#3607) 2025-10-22 10:08:15 -07:00
Frederik Berg 2692e49d50 Fix: Add missing filter methods to AsyncMemory (#3624)
Co-authored-by: Claude <noreply@anthropic.com>
2025-10-22 16:08:04 +05:30
Ronak Bhalgami eb2f8a3738 fix: Prevent Mock object issues in graph memory tests (#3627)
Co-authored-by: parshvadaftari <daftariparshva@gmail.com>
2025-10-22 03:53:12 +05:30
Prateek Chhikara 4a30745592 Add redirect to new apis doc page (#3639) 2025-10-21 13:55:14 -07:00
Rahul Sharma 3b1a4c2e68 Fix condition check for memories_result type in AsyncMemory class (#3621) 2025-10-22 01:55:28 +05:30
Mrinank Bhowmick 5227b0a062 Fix embedder config schema to support embeddingDims and url parameters (#3633) 2025-10-21 09:30:44 -07:00
Prateek Chhikara 8031f0bf8f Changes to docs (#3637) 2025-10-20 16:13:34 -07:00
Prateek Chhikara dd3e5363dd Update docs (#3636) 2025-10-20 16:12:11 -07:00
Frederik Berg d5a130b785 Fix memory deletion not removing from vector store (#3610) 2025-10-18 14:17:03 -07:00
Frederik Berg 8ede1df10a Fix list_memories endpoint Pydantic validation error (#3608) 2025-10-18 14:16:49 -07:00
Parshva Daftari 8ba18bf8bc [fix] docs for search memories (#3622) 2025-10-18 13:27:15 -07:00
Ronak Bhalgami de224dd26d feat: Add configurable embedding similarity threshold for graph store node matching (#3593) 2025-10-18 13:03:30 -07:00
Faizan Habib 9ef644b95e Add Apache Cassandra vector store support (#3578) 2025-10-17 23:48:49 +05:30
Aashis kumar 7afbaae7a3 Fix condition check for memories_result type in Memory class (#3596) 2025-10-17 02:17:18 +05:30
Tarun Jain 1090784302 [feat add]FastEmbed embedding for local embeddings (#3552) 2025-10-16 22:52:22 +05:30
331 changed files with 18964 additions and 23700 deletions
+11
View File
@@ -7,6 +7,8 @@ on:
- 'mem0/**'
- 'tests/**'
- 'embedchain/**'
- '.github/workflows/**'
- 'pyproject.toml'
pull_request:
paths:
- 'mem0/**'
@@ -28,6 +30,8 @@ jobs:
mem0:
- 'mem0/**'
- 'tests/**'
- '.github/workflows/**'
- 'pyproject.toml'
embedchain:
- 'embedchain/**'
@@ -44,6 +48,13 @@ jobs:
uses: actions/setup-python@v4
with:
python-version: ${{ matrix.python-version }}
- name: Clean up disk space
run: |
df -h
sudo rm -rf /usr/share/dotnet /usr/local/lib/android /opt/ghc /opt/hostedtoolcache/CodeQL
sudo docker image prune --all --force
sudo docker builder prune -a
df -h
- name: Install Hatch
run: pip install hatch
- name: Load cached venv
+66 -172
View File
@@ -1,44 +1,83 @@
---
title: Overview
icon: "info"
title: "Overview"
icon: "terminal"
iconType: "solid"
description: "REST APIs for memory management, search, and entity operations"
---
Mem0 provides a powerful set of APIs that allow you to integrate advanced memory management capabilities into your applications. Our APIs are designed to be intuitive, efficient, and scalable, enabling you to create, retrieve, update, and delete memories across various entities such as users, agents, apps, and runs.
## Mem0 REST API
Mem0 provides a comprehensive REST API for integrating advanced memory capabilities into your applications. Create, search, update, and manage memories across users, agents, and custom entities with simple HTTP requests.
<Info>
**Quick start:** Get your API key from the [Mem0 Dashboard](https://app.mem0.ai/dashboard/api-keys) and make your first memory operation in minutes.
</Info>
---
## Quick Start Guide
Get started with Mem0 API in three simple steps:
1. **[Add Memories](/api-reference/memory/add-memories)** - Store information and context from user conversations
2. **[Search Memories](/api-reference/memory/v2-search-memories)** - Retrieve relevant memories based on queries
2. **[Search Memories](/api-reference/memory/v2-search-memories)** - Retrieve relevant memories using semantic search
3. **[Get Memories](/api-reference/memory/v2-get-memories)** - Fetch all memories for a specific entity
### Common Operations
---
## Core Operations
<CardGroup cols={2}>
<Card title="Add Memories" icon="plus" href="/api-reference/memory/add-memories">
Store new memories from conversations and interactions
</Card>
<Card title="Search Memories" icon="magnifying-glass" href="/api-reference/memory/v2-search-memories">
Find relevant memories using semantic search
Find relevant memories using semantic search with filters
</Card>
<Card title="Update Memory" icon="pen" href="/api-reference/memory/update-memory">
Modify existing memory content
Modify existing memory content and metadata
</Card>
<Card title="Delete Memory" icon="trash" href="/api-reference/memory/delete-memory">
Remove specific memories or batch delete
Remove specific memories or batch delete operations
</Card>
</CardGroup>
## API Structure
---
Our API is organized into several main categories:
## API Categories
1. **[Memory APIs](#memory-apis)**: Core operations for managing individual memories and collections
2. **[Entities APIs](#entities-apis)**: Manage different entity types (users, agents, etc.) and their associated memories
3. **[Organizations APIs](#organizations-apis)**: Manage organizations and their members (optional)
4. **[Project APIs](#project-apis)**: Manage projects within organizations (optional)
Explore the full API organized by functionality:
<CardGroup cols={2}>
<Card title="Memory APIs" icon="microchip" href="/api-reference/memory/add-memories">
Core and advanced operations: CRUD, search, batch updates, history, and exports
</Card>
<Card title="Events APIs" icon="clock" href="/api-reference/events/get-events">
Track and monitor the status of asynchronous memory operations
</Card>
<Card title="Entities APIs" icon="users" href="/api-reference/entities/get-users">
Manage users, agents, and their associated memory data
</Card>
<Card title="Organizations & Projects" icon="building" href="/api-reference/organizations-projects">
Multi-tenant support, access control, and team collaboration
</Card>
<Card title="Webhooks" icon="webhook" href="/api-reference/webhook/create-webhook">
Real-time notifications for memory events and updates
</Card>
</CardGroup>
<Note>
**Building multi-tenant apps?** Learn about [Organizations & Projects](/api-reference/organizations-projects) for team isolation and access control.
</Note>
---
## Authentication
@@ -50,165 +89,20 @@ Authorization: Token <your-api-key>
Get your API key from the [Mem0 Dashboard](https://app.mem0.ai/dashboard/api-keys).
## Organizations and projects (optional)
<Warning>
**Keep your API key secure.** Never expose it in client-side code or public repositories. Use environment variables and server-side requests only.
</Warning>
Organizations and projects provide the following capabilities:
---
- **Multi-org/project Support**: Specify organization and project when initializing the Mem0 client to attribute API usage appropriately.
- **Member Management**: Control access to data through organization and project membership.
- **Access Control**: Only members can access memories and data within their organization/project scope.
- **Team Isolation**: Maintain data separation between different teams and projects for secure collaboration.
## Next Steps
Example with the mem0 Python package:
<CardGroup cols={2}>
<Card title="Add Your First Memory" icon="rocket" href="/api-reference/memory/add-memories">
Start storing memories via the REST API
</Card>
<Tabs>
<Tab title="Python">
```python
from mem0 import MemoryClient
client = MemoryClient(org_id='YOUR_ORG_ID', project_id='YOUR_PROJECT_ID')
```
</Tab>
<Tab title="Node.js">
```javascript
import { MemoryClient } from "mem0ai";
const client = new MemoryClient({organizationId: "YOUR_ORG_ID", projectId: "YOUR_PROJECT_ID"});
```
</Tab>
</Tabs>
### Project Management Methods
The Mem0 client provides comprehensive project management capabilities through the `client.project` interface:
#### Get Project Details
Retrieve information about the current project:
```python
# Get all project details
project_info = client.project.get()
# Get specific fields only
project_info = client.project.get(fields=["name", "description", "custom_categories"])
```
#### Create a New Project
Create a new project within your organization:
```python
# Create a project with name and description
new_project = client.project.create(
name="My New Project",
description="A project for managing customer support memories"
)
```
#### Update Project Settings
Modify project configuration including custom instructions, categories, and graph settings:
```python
# Update project with custom categories
client.project.update(
custom_categories=[
{"customer_preferences": "Customer likes, dislikes, and preferences"},
{"support_history": "Previous support interactions and resolutions"}
]
)
# Update project with custom instructions
client.project.update(
custom_instructions="..."
)
# Enable graph memory for the project
client.project.update(enable_graph=True)
# Update multiple settings at once
client.project.update(
custom_instructions="...",
custom_categories=[
{"personal_info": "User personal information and preferences"},
{"work_context": "Professional context and work-related information"}
],
enable_graph=True
)
```
#### Delete Project
<Note>
This action will remove all memories, messages, and other related data in the project. This operation is irreversible.
</Note>
Remove a project and all its associated data:
```python
# Delete the current project (irreversible)
result = client.project.delete()
```
#### Member Management
Manage project members and their access levels:
```python
# Get all project members
members = client.project.get_members()
# Add a new member as a reader
client.project.add_member(
email="colleague@company.com",
role="READER" # or "OWNER"
)
# Update a member's role
client.project.update_member(
email="colleague@company.com",
role="OWNER"
)
# Remove a member from the project
client.project.remove_member(email="colleague@company.com")
```
#### Member Roles
- **READER**: Can view and search memories, but cannot modify project settings or manage members.
- **OWNER**: Full access including project modification, member management, and all reader permissions.
#### Async Support
All project methods are also available in async mode:
```python
from mem0 import AsyncMemoryClient
async def manage_project():
client = AsyncMemoryClient(org_id='YOUR_ORG_ID', project_id='YOUR_PROJECT_ID')
# All methods support async/await
project_info = await client.project.get()
await client.project.update(enable_graph=True)
members = await client.project.get_members()
# To call the async function properly
import asyncio
asyncio.run(manage_project())
```
## Getting Started
To begin using the Mem0 API, you'll need to:
1. Sign up for a [Mem0 account](https://app.mem0.ai) and obtain your API key.
2. Familiarize yourself with the API endpoints and their functionalities.
3. Make your first API call to add or retrieve a memory.
Explore the detailed documentation for each API endpoint to learn more about request/response formats, parameters, and example usage.
<Card title="Search with Filters" icon="filter" href="/api-reference/memory/v2-search-memories">
Learn advanced search and filtering techniques
</Card>
</CardGroup>
+1 -1
View File
@@ -1,4 +1,4 @@
---
title: 'Delete User'
openapi: delete /v1/entities/{entity_type}/{entity_id}/
openapi: delete /v2/entities/{entity_type}/{entity_id}/
---
+6
View File
@@ -0,0 +1,6 @@
---
title: 'Get Event'
openapi: get /v1/event/{event_id}/
---
Retrieve details about a specific event by passing its `event_id`. This endpoint is particularly helpful for tracking the status, payload, and completion details of asynchronous memory operations.
+13
View File
@@ -0,0 +1,13 @@
---
title: 'Get Events'
openapi: get /v1/events/
---
List recent events for your organization and project.
## Use Cases
- **Dashboards**: Summarize adds/searches over time by paging through events.
- **Alerting**: Poll for `FAILED` events and trigger follow-up workflows.
- **Audit**: Store the returned payload/metadata for compliance logs.
+90 -5
View File
@@ -3,10 +3,95 @@ title: 'Add Memories'
openapi: post /v1/memories/
---
## Graph Memory
Add new facts, messages, or metadata to a user’s memory store. The Add Memories endpoint accepts either raw text or conversational turns and commits them asynchronously so the memory is ready for later search, retrieval, and graph queries.
To enable graph-based memory relationships, pass the `enable_graph=True` parameter. This creates relationships between entities in your memories for more contextual retrieval.
## Endpoint
<Note>
Learn more in the [Graph Memory documentation](/platform/features/graph-memory).
</Note>
- **Method**: `POST`
- **URL**: `/v1/memories/`
- **Content-Type**: `application/json`
Memories are processed asynchronously by default. The response contains queued events you can track while the platform finalizes enrichment.
## Required headers
| Header | Required | Description |
| --- | --- | --- |
| `Authorization: Token <MEM0_API_KEY>` | Yes | API key scoped to your workspace. |
| `Accept: application/json` | Yes | Ensures a JSON response. |
## Request body
Provide at least one message or direct memory string. Most callers supply `messages` so Mem0 can infer structured memories as part of ingestion.
<CodeGroup>
```json Basic request
{
"user_id": "alice",
"messages": [
{ "role": "user", "content": "I moved to Austin last month." }
],
"metadata": {
"source": "onboarding_form"
}
}
```
</CodeGroup>
### Common fields
| Field | Type | Required | Description |
| --- | --- | --- | --- |
| `user_id` | string | No* | Associates the memory with a user. Provide when you want the memory scoped to a specific identity. |
| `messages` | array | No* | Conversation turns for Mem0 to infer memories from. Each object should include `role` and `content`. |
| `metadata` | object | Optional | Custom key/value metadata (e.g., `{"topic": "preferences"}`). |
| `infer` | boolean (default `true`) | Optional | Set to `false` to skip inference and store the provided text as-is. |
| `async_mode` | boolean (default `true`) | Optional | Controls asynchronous processing. Most clients leave this enabled. |
| `output_format` | string (default `v1.1`) | Optional | Response format. `v1.1` wraps results in a `results` array. |
> \* Provide at least one `messages` entry to describe what you are storing. For scoped memories, include `user_id`. You can also attach `agent_id`, `app_id`, `run_id`, `project_id`, or `org_id` to refine ownership.
## Response
Successful requests return an array of events queued for processing. Each event includes the generated memory text and an identifier you can persist for auditing.
<CodeGroup>
```json 200 response
[
{
"id": "mem_01JF8ZS4Y0R0SPM13R5R6H32CJ",
"event": "ADD",
"data": {
"memory": "The user moved to Austin in 2025."
}
}
]
```
```json 400 response
{
"error": "400 Bad Request",
"details": {
"message": "Invalid input data. Please refer to the memory creation documentation at https://docs.mem0.ai/platform/quickstart#4-1-create-memories for correct formatting and required fields."
}
}
```
</CodeGroup>
## Graph relationships
Add Memories can enrich the knowledge graph on write. Set `enable_graph: true` to create entity nodes and relationships for the stored memory. Use this when you want downstream `get_all` or search calls to traverse connected entities.
<CodeGroup>
```json Graph-aware request
{
"user_id": "alice",
"messages": [
{ "role": "user", "content": "I met with Dr. Lee at General Hospital." }
],
"enable_graph": true
}
```
</CodeGroup>
The response follows the same format, and related entities become available in [Graph Memory](/platform/features/graph-memory) queries.
+61 -33
View File
@@ -1,9 +1,10 @@
---
title: 'Get Memories (v2)'
title: "Get Memories"
openapi: post /v2/memories/
---
The v2 get memories API is powerful and flexible, allowing for more precise memory listing without the need for a search query. It supports complex logical operations (AND, OR, NOT) and comparison operators for advanced filtering capabilities. The comparison operators include:
- `in`: Matches any of the values specified
- `gte`: Greater than or equal to
- `lte`: Less than or equal to
@@ -15,7 +16,7 @@ The v2 get memories API is powerful and flexible, allowing for more precise memo
<CodeGroup>
```python Code
memories = m.get_all(
memories = client.get_all(
filters={
"AND": [
{
@@ -29,43 +30,70 @@ memories = m.get_all(
)
```
```json Output
[
```python Output
{
"id":"f38b689d-6b24-45b7-bced-17fbb4d8bac7",
"memory":"Name: Alex. Vegetarian. Allergic to nuts.",
"user_id":"alex",
"hash":"62bc074f56d1f909f1b4c2b639f56f6a",
"metadata":null,
"created_at":"2024-07-25T23:57:00.108347-07:00",
"updated_at":"2024-07-25T23:57:00.108367-07:00"
"results": [
{
"id": "f4cbdb08-7062-4f3e-8eb2-9f5c80dfe64c",
"memory": "Alex is planning a trip to San Francisco from July 1st to July 10th",
"created_at": "2024-07-01T12:00:00Z",
"updated_at": "2024-07-01T12:00:00Z"
},
{
"id": "a2b8c3d4-5e6f-7g8h-9i0j-1k2l3m4n5o6p",
"memory": "Alex prefers vegetarian restaurants",
"created_at": "2024-07-05T15:30:00Z",
"updated_at": "2024-07-05T15:30:00Z"
}
],
"total": 2
}
]
```
</CodeGroup>
<CodeGroup>
```python Wildcard Example
# Using wildcard to get all memories for a specific user across all run_ids
memories = m.get_all(
filters={
"AND": [
{
"user_id": "alex"
},
{
"run_id": "*"
}
]
}
)
```
</CodeGroup>
## Graph Memory
To retrieve memories with graph-based relationships, pass the `enable_graph=True` parameter. This includes relationship data in the response for more contextual results.
To retrieve graph memory relationships between entities, pass `output_format="v1.1"` in your request. This will return memories with entity and relationship information from the knowledge graph.
<Note>
Learn more in the [Graph Memory documentation](/platform/features/graph-memory).
</Note>
<CodeGroup>
```python Code
memories = client.get_all(
filters={
"user_id": "alex"
},
output_format="v1.1"
)
```
```python Output
{
"results": [
{
"id": "f4cbdb08-7062-4f3e-8eb2-9f5c80dfe64c",
"memory": "Alex is planning a trip to San Francisco",
"entities": [
{
"id": "entity-1",
"name": "Alex",
"type": "person"
},
{
"id": "entity-2",
"name": "San Francisco",
"type": "location"
}
],
"relations": [
{
"source": "entity-1",
"target": "entity-2",
"relationship": "traveling_to"
}
]
}
]
}
```
</CodeGroup>
@@ -14,8 +14,8 @@ The v2 search API is powerful and flexible, allowing for more precise memory ret
- `*`: Wildcard character that matches everything
<CodeGroup>
```python Code
related_memories = m.search(
```python Platform API Example
related_memories = client.search(
query="What are Alice's hobbies?",
filters={
"OR": [
@@ -53,7 +53,7 @@ related_memories = m.search(
<CodeGroup>
```python Wildcard Example
# Using wildcard to match all run_ids for a specific user
all_memories = m.search(
all_memories = client.search(
query="What are Alice's hobbies?",
filters={
"AND": [
@@ -72,7 +72,7 @@ all_memories = m.search(
<CodeGroup>
```python Categories Filter Examples
# Example 1: Using 'contains' for partial matching
finance_memories = m.search(
finance_memories = client.search(
query="What are my financial goals?",
filters={
"AND": [
@@ -87,7 +87,7 @@ finance_memories = m.search(
)
# Example 2: Using 'in' for exact matching
personal_memories = m.search(
personal_memories = client.search(
query="What personal information do you have?",
filters={
"AND": [
@@ -0,0 +1,197 @@
---
title: Organizations & Projects
icon: "building"
description: "Manage multi-tenant applications with organization and project APIs"
---
## Overview
Organizations and projects provide multi-tenant support, access control, and team collaboration capabilities for Mem0 Platform. Use these APIs to build applications that support multiple teams, customers, or isolated environments.
<Info>
Organizations and projects are **optional** features. You can use Mem0 without them for single-user or simple multi-user applications.
</Info>
## Key Capabilities
- **Multi-org/project Support**: Specify organization and project when initializing the Mem0 client to attribute API usage appropriately
- **Member Management**: Control access to data through organization and project membership
- **Access Control**: Only members can access memories and data within their organization/project scope
- **Team Isolation**: Maintain data separation between different teams and projects for secure collaboration
---
## Using Organizations & Projects
### Initialize with Org/Project Context
Example with the mem0 Python package:
<Tabs>
<Tab title="Python">
```python
from mem0 import MemoryClient
client = MemoryClient(org_id='YOUR_ORG_ID', project_id='YOUR_PROJECT_ID')
```
</Tab>
<Tab title="Node.js">
```javascript
import { MemoryClient } from "mem0ai";
const client = new MemoryClient({
organizationId: "YOUR_ORG_ID",
projectId: "YOUR_PROJECT_ID"
});
```
</Tab>
</Tabs>
---
## Project Management
The Mem0 client provides comprehensive project management through the `client.project` interface:
### Get Project Details
Retrieve information about the current project:
```python
# Get all project details
project_info = client.project.get()
# Get specific fields only
project_info = client.project.get(fields=["name", "description", "custom_categories"])
```
### Create a New Project
Create a new project within your organization:
```python
# Create a project with name and description
new_project = client.project.create(
name="My New Project",
description="A project for managing customer support memories"
)
```
### Update Project Settings
Modify project configuration including custom instructions, categories, and graph settings:
```python
# Update project with custom categories
client.project.update(
custom_categories=[
{"customer_preferences": "Customer likes, dislikes, and preferences"},
{"support_history": "Previous support interactions and resolutions"}
]
)
# Update project with custom instructions
client.project.update(
custom_instructions="..."
)
# Enable graph memory for the project
client.project.update(enable_graph=True)
# Update multiple settings at once
client.project.update(
custom_instructions="...",
custom_categories=[
{"personal_info": "User personal information and preferences"},
{"work_context": "Professional context and work-related information"}
],
enable_graph=True
)
```
### Delete Project
<Warning>
This action will remove all memories, messages, and other related data in the project. **This operation is irreversible.**
</Warning>
Remove a project and all its associated data:
```python
# Delete the current project (irreversible)
result = client.project.delete()
```
---
## Member Management
Manage project members and their access levels:
```python
# Get all project members
members = client.project.get_members()
# Add a new member as a reader
client.project.add_member(
email="colleague@company.com",
role="READER" # or "OWNER"
)
# Update a member's role
client.project.update_member(
email="colleague@company.com",
role="OWNER"
)
# Remove a member from the project
client.project.remove_member(email="colleague@company.com")
```
### Member Roles
| Role | Permissions |
|------|-------------|
| **READER** | Can view and search memories, but cannot modify project settings or manage members |
| **OWNER** | Full access including project modification, member management, and all reader permissions |
---
## Async Support
All project methods are available in async mode:
```python
from mem0 import AsyncMemoryClient
async def manage_project():
client = AsyncMemoryClient(org_id='YOUR_ORG_ID', project_id='YOUR_PROJECT_ID')
# All methods support async/await
project_info = await client.project.get()
await client.project.update(enable_graph=True)
members = await client.project.get_members()
# To call the async function properly
import asyncio
asyncio.run(manage_project())
```
---
## API Reference
For complete API specifications and additional endpoints, see:
<CardGroup cols={2}>
<Card title="Organizations APIs" icon="building" href="/api-reference/organization/create-org">
Create, get, and manage organizations
</Card>
<Card title="Project APIs" icon="folder" href="/api-reference/project/create-project">
Full project CRUD and member management endpoints
</Card>
</CardGroup>
+125
View File
@@ -7,6 +7,88 @@ mode: "wide"
<Tabs>
<Tab title="Python">
<Update label="2026-03-03" description="v1.0.5">
- **Telemetry Fix**
- Fixed an issue where the PostHog client was initialized even after telemetry was disabled. Although events were not captured, the client was unnecessarily initialized.
</Update>
<Update label="2026-02-17" description="v1.0.4">
**New Features & Updates:**
- **Memory Update:**
- Added `timestamp` parameter to `update()` — accepts Unix epoch (int/float) or ISO 8601 string
</Update>
<Update label="2026-01-29" description="v1.0.3">
**New Features & Updates:**
- **Project Settings:**
- Added inclusion prompt, exclusion prompt, memory depth, and usecase setting
</Update>
<Update label="2026-01-13" description="v1.0.2">
**New Features & Updates:**
- **Vector Stores:**
- Added DriverInfo metadata to MongoDB vector store
</Update>
<Update label="2025-11-14" description="v1.0.1">
**New Features & Updates:**
- **Vector Stores:**
- Added Apache Cassandra vector store support
- **Embeddings:**
- Added FastEmbed embedding support for local embeddings
- **Graph Store:**
- Added configurable embedding similarity threshold for graph store node matching
**Bug Fixes:**
- **Core:**
- Fixed condition check for memories_result type in Memory class
- Fixed list_memories endpoint Pydantic validation error
- Fixed memory deletion not removing from vector store
</Update>
<Update label="2025-10-16" description="v1.0.0">
**New Features & Updates:**
- **Vector Stores:**
- Added Azure MySQL support
- Added Azure AI Search Vector Store support
- **LLMs:**
- Added Tool Call support for LangchainLLM
- Enabled custom model and parameters for Hugging Face with huggingface_base_url
- Updated default LLM configuration
- **Rerankers:**
- Added reranker support: Cohere, ZeroEntropy, Hugging Face, Sentence Transformers, and LLMs
- **Core:**
- Added metadata filtering for OSS
- Added Assistant memory retrieval
- Enabled async mode as default
**Improvements:**
- **Prompts:**
- Improved prompt for better memory retrieval
- **Dependencies:**
- Updated dependency compatibility with OpenAI 2.x
- **Validation:**
- Validated embedding_dims for Kuzu integration
**Bug Fixes:**
- **Vector Stores:**
- Fixed Databricks Vector Store integration
- Fixed Milvus DB bug and added test coverage
- Fixed Weaviate search method
- **LLMs:**
- Fixed bug with thinking LLM in vLLM
</Update>
<Update label="2025-09-25" description="v0.1.118">
**New Features & Updates:**
@@ -647,6 +729,44 @@ mode: "wide"
<Tab title="TypeScript">
<Update label="2026-02-17" description="v2.2.3">
**New Features & Updates:**
- **Memory Update:**
- Added `timestamp` parameter to `update()` — accepts Unix epoch or ISO 8601 string
</Update>
<Update label="2026-01-29" description="v2.2.2">
**New Features & Updates:**
- **Project Settings:**
- Added inclusion prompt, exclusion prompt, memory depth, and usecase setting
</Update>
<Update label="2025-12-30" description="v2.2.1">
**Improvements:**
- **Client:** Added support for keyword arguments in `add` and `search` methods, allowing additional properties beyond defined options for experimental features
</Update>
<Update label="2025-12-29" description="v2.2.0">
**New Features:**
- **Vector Stores:** Added Azure AI Search vector store support
**Improvements:**
- **Config:** Fixed embedder config schema to support `embeddingDims` and `url` parameters
- **Graph Memory:** Replaced hardcoded LLM provider with provider from configuration
**Bug Fixes:**
- **Embedders:** Fixed hardcoded `embeddingDims` values in embedders (OpenAI, Ollama, Google, Azure)
- **Build:** Fixed TypeScript build errors
</Update>
<Update label="2025-09-04" description="v2.1.38">
**New Features:**
- **Client:** Added `metadata` param to `update` method.
@@ -1123,6 +1243,11 @@ mode: "wide"
<Tab title="Vercel AI SDK">
<Update label="2025-12-26" description="v2.0.5">
**Bug Fix:**
- **Vercel AI SDK:** Removed unnecessary dependencies to make the package lighter.
</Update>
<Update label="2025-09-25" description="v2.0.4">
**Bug Fix:**
- **Vercel AI SDK:** Fixed version parameter in the AI SDK to use V2 for addition.
-2
View File
@@ -1,7 +1,5 @@
---
title: Configurations
icon: "gear"
iconType: "solid"
---
-2
View File
@@ -1,7 +1,5 @@
---
title: Overview
icon: "info"
iconType: "solid"
---
Mem0 offers support for various embedding models, allowing users to choose the one that best suits their needs.
-2
View File
@@ -1,7 +1,5 @@
---
title: Configurations
icon: "gear"
iconType: "solid"
---
## How to define configurations?
-2
View File
@@ -1,7 +1,5 @@
---
title: Overview
icon: "info"
iconType: "solid"
---
Mem0 includes built-in support for various popular large language models. Memory can utilize the LLM provided by the user, ensuring efficient use for specific needs.
+42 -44
View File
@@ -1,73 +1,71 @@
---
title: Config
description: 'Configuration options for rerankers in Mem0'
icon: "gear"
iconType: "solid"
description: "Configuration options for rerankers in Mem0"
---
## Common Configuration Parameters
All rerankers share these common configuration parameters:
| Parameter | Description | Type | Default |
|-----------|-------------|------|---------|
| `provider` | Reranker provider name | `str` | Required |
| `top_k` | Maximum number of results to return after reranking | `int` | `None` |
| `api_key` | API key for the reranker service | `str` | `None` |
| Parameter | Description | Type | Default |
| ---------- | --------------------------------------------------- | ----- | -------- |
| `provider` | Reranker provider name | `str` | Required |
| `top_k` | Maximum number of results to return after reranking | `int` | `None` |
| `api_key` | API key for the reranker service | `str` | `None` |
## Provider-Specific Configuration
### Zero Entropy
| Parameter | Description | Type | Default |
|-----------|-------------|------|---------|
| `model` | Model to use: `zerank-1` or `zerank-1-small` | `str` | `"zerank-1"` |
| `api_key` | Zero Entropy API key | `str` | `None` |
| Parameter | Description | Type | Default |
| --------- | -------------------------------------------- | ----- | ------------ |
| `model` | Model to use: `zerank-1` or `zerank-1-small` | `str` | `"zerank-1"` |
| `api_key` | Zero Entropy API key | `str` | `None` |
### Cohere
| Parameter | Description | Type | Default |
|-----------|-------------|------|---------|
| `model` | Cohere rerank model | `str` | `"rerank-english-v3.0"` |
| `api_key` | Cohere API key | `str` | `None` |
| `return_documents` | Whether to return document texts in response | `bool` | `False` |
| `max_chunks_per_doc` | Maximum chunks per document | `int` | `None` |
| Parameter | Description | Type | Default |
| -------------------- | -------------------------------------------- | ------ | ----------------------- |
| `model` | Cohere rerank model | `str` | `"rerank-english-v3.0"` |
| `api_key` | Cohere API key | `str` | `None` |
| `return_documents` | Whether to return document texts in response | `bool` | `False` |
| `max_chunks_per_doc` | Maximum chunks per document | `int` | `None` |
### Sentence Transformer
| Parameter | Description | Type | Default |
|-----------|-------------|------|---------|
| `model` | HuggingFace cross-encoder model name | `str` | `"cross-encoder/ms-marco-MiniLM-L-6-v2"` |
| `device` | Device to run model on (`cpu`, `cuda`, etc.) | `str` | `None` |
| `batch_size` | Batch size for processing | `int` | `32` |
| `show_progress_bar` | Show progress during processing | `bool` | `False` |
| Parameter | Description | Type | Default |
| ------------------- | -------------------------------------------- | ------ | ---------------------------------------- |
| `model` | HuggingFace cross-encoder model name | `str` | `"cross-encoder/ms-marco-MiniLM-L-6-v2"` |
| `device` | Device to run model on (`cpu`, `cuda`, etc.) | `str` | `None` |
| `batch_size` | Batch size for processing | `int` | `32` |
| `show_progress_bar` | Show progress during processing | `bool` | `False` |
### Hugging Face
| Parameter | Description | Type | Default |
|-----------|-------------|------|---------|
| `model` | HuggingFace reranker model name | `str` | `"BAAI/bge-reranker-large"` |
| `api_key` | HuggingFace API token | `str` | `None` |
| `device` | Device to run model on (`cpu`, `cuda`, etc.) | `str` | `None` |
| Parameter | Description | Type | Default |
| --------- | -------------------------------------------- | ----- | --------------------------- |
| `model` | HuggingFace reranker model name | `str` | `"BAAI/bge-reranker-large"` |
| `api_key` | HuggingFace API token | `str` | `None` |
| `device` | Device to run model on (`cpu`, `cuda`, etc.) | `str` | `None` |
### LLM-based
| Parameter | Description | Type | Default |
|-----------|-------------|------|---------|
| `model` | LLM model to use for scoring | `str` | `"gpt-4o-mini"` |
| `provider` | LLM provider (`openai`, `anthropic`, etc.) | `str` | `"openai"` |
| `api_key` | API key for LLM provider | `str` | `None` |
| `temperature` | Temperature for LLM generation | `float` | `0.0` |
| `max_tokens` | Maximum tokens for LLM response | `int` | `100` |
| `scoring_prompt` | Custom prompt template for scoring | `str` | Default scoring prompt |
| Parameter | Description | Type | Default |
| ---------------- | ------------------------------------------ | ------- | ---------------------- |
| `model` | LLM model to use for scoring | `str` | `"gpt-4o-mini"` |
| `provider` | LLM provider (`openai`, `anthropic`, etc.) | `str` | `"openai"` |
| `api_key` | API key for LLM provider | `str` | `None` |
| `temperature` | Temperature for LLM generation | `float` | `0.0` |
| `max_tokens` | Maximum tokens for LLM response | `int` | `100` |
| `scoring_prompt` | Custom prompt template for scoring | `str` | Default scoring prompt |
### LLM Reranker
| Parameter | Description | Type | Default |
|-----------|-------------|------|---------|
| `llm.provider` | LLM provider for reranking | `str` | Required |
| `llm.config` | LLM configuration object | `dict` | Required |
| `top_n` | Number of results to return | `int` | `None` |
| Parameter | Description | Type | Default |
| -------------- | --------------------------- | ------ | -------- |
| `llm.provider` | LLM provider for reranking | `str` | Required |
| `llm.config` | LLM configuration object | `dict` | Required |
| `top_n` | Number of results to return | `int` | `None` |
## Environment Variables
@@ -93,10 +91,10 @@ config = {
"llm": {
"provider": "openai",
"config": {
"model": "gpt-4o-mini"
"model": "gpt-4.1-nano-2025-04-14"
}
},
"rerank": {
"reranker": {
"provider": "zero_entropy",
"config": {
"model": "zerank-1",
+12 -9
View File
@@ -1,7 +1,5 @@
---
title: Custom Prompts
icon: "pencil"
iconType: "solid"
---
When using LLM rerankers, you can customize the prompts used for ranking to better suit your specific use case and domain.
@@ -54,7 +52,7 @@ config = {
"llm": {
"provider": "openai",
"config": {
"model": "gpt-4",
"model": "gpt-4.1-nano-2025-04-14",
"api_key": "your-openai-key"
}
},
@@ -71,16 +69,17 @@ memory = Memory.from_config(config)
Your custom prompt can use the following variables:
| Variable | Description |
|----------|-------------|
| `{query}` | The search query |
| `{memories}` | The list of memory entries to rank |
| `{user_id}` | The user ID (if available) |
| Variable | Description |
| ---------------- | ------------------------------------- |
| `{query}` | The search query |
| `{memories}` | The list of memory entries to rank |
| `{user_id}` | The user ID (if available) |
| `{user_context}` | Additional user context (if provided) |
## Domain-Specific Examples
### Customer Support
```python
customer_support_prompt = """
You are ranking customer support conversation memories.
@@ -100,6 +99,7 @@ Rank each memory 1-10 based on support relevance.
```
### Educational Content
```python
educational_prompt = """
Rank these learning memories for a student query.
@@ -119,6 +119,7 @@ Score each memory for educational value (1-10).
```
### Personal Assistant
```python
personal_assistant_prompt = """
Rank personal memories for relevance to the user's query.
@@ -140,6 +141,7 @@ Provide relevance scores (1-10) with brief explanations.
## Advanced Prompt Techniques
### Multi-Criteria Ranking
```python
multi_criteria_prompt = """
Evaluate memories using multiple criteria:
@@ -165,6 +167,7 @@ Format: JSON with detailed scoring
```
### Contextual Ranking
```python
contextual_prompt = """
Consider the following context when ranking memories:
@@ -214,4 +217,4 @@ for i, prompt in enumerate(prompts):
- **Too Long**: Keep prompts under token limits for your chosen LLM
- **Too Vague**: Be specific about ranking criteria
- **Inconsistent Format**: Ensure JSON output format is clearly specified
- **Missing Context**: Include relevant variables for your use case
- **Missing Context**: Include relevant variables for your use case
+10 -12
View File
@@ -1,8 +1,6 @@
---
title: Cohere
description: 'Reranking with Cohere'
icon: "building"
iconType: "solid"
description: "Reranking with Cohere"
---
Cohere provides enterprise-grade reranking models with excellent multilingual support and production-ready performance.
@@ -37,7 +35,7 @@ config = {
"llm": {
"provider": "openai",
"config": {
"model": "gpt-4o-mini"
"model": "gpt-4.1-nano-2025-04-14"
}
},
"reranker": {
@@ -124,13 +122,13 @@ config = {
## Configuration Parameters
| Parameter | Description | Type | Default |
|-----------|-------------|------|---------|
| `model` | Cohere rerank model to use | `str` | `"rerank-english-v3.0"` |
| `api_key` | Cohere API key | `str` | `None` |
| `top_k` | Maximum documents to return | `int` | `None` |
| `return_documents` | Whether to return document texts | `bool` | `False` |
| `max_chunks_per_doc` | Maximum chunks per document | `int` | `None` |
| Parameter | Description | Type | Default |
| -------------------- | -------------------------------- | ------ | ----------------------- |
| `model` | Cohere rerank model to use | `str` | `"rerank-english-v3.0"` |
| `api_key` | Cohere API key | `str` | `None` |
| `top_k` | Maximum documents to return | `int` | `None` |
| `return_documents` | Whether to return document texts | `bool` | `False` |
| `max_chunks_per_doc` | Maximum chunks per document | `int` | `None` |
## Features
@@ -144,4 +142,4 @@ config = {
1. **Model Selection**: Use `rerank-english-v3.0` for English, `rerank-multilingual-v3.0` for other languages
2. **Batch Processing**: Process multiple queries efficiently
3. **Error Handling**: Implement retry logic for production systems
4. **Monitoring**: Track reranking performance and costs
4. **Monitoring**: Track reranking performance and costs
@@ -1,8 +1,6 @@
---
title: Hugging Face Reranker
description: 'Access thousands of reranking models from Hugging Face Hub'
icon: "face-smile"
iconType: "solid"
---
## Overview
+11 -9
View File
@@ -1,10 +1,12 @@
---
title: LLM as Reranker
description: 'Flexible reranking using LLMs'
icon: "robot"
iconType: "solid"
---
<Warning>
**This page has been superseded.** Please see [LLM Reranker](/components/rerankers/models/llm_reranker) for the complete and up-to-date documentation on using LLMs for reranking.
</Warning>
LLM-based reranker provides maximum flexibility by using any Large Language Model to score document relevance. This approach allows for custom prompts and domain-specific scoring logic.
## Supported LLM Providers
@@ -37,7 +39,7 @@ config = {
"model": "gpt-4o-mini"
}
},
"rerank": {
"reranker": {
"provider": "llm",
"config": {
"model": "gpt-4o-mini",
@@ -71,7 +73,7 @@ Score from 0.0 to 1.0 where:
Provide only a single numerical score between 0.0 and 1.0."""
config["rerank"]["config"]["scoring_prompt"] = custom_prompt
config["reranker"]["config"]["scoring_prompt"] = custom_prompt
```
## Usage Example
@@ -87,7 +89,7 @@ os.environ["OPENAI_API_KEY"] = "your-api-key"
config = {
"vector_store": {"provider": "chroma"},
"llm": {"provider": "openai", "config": {"model": "gpt-4o-mini"}},
"rerank": {
"reranker": {
"provider": "llm",
"config": {
"model": "gpt-4o-mini",
@@ -147,7 +149,7 @@ Consider:
Score from 0.0 to 1.0. Provide only the numerical score."""
config = {
"rerank": {
"reranker": {
"provider": "llm",
"config": {
"model": "gpt-4o-mini",
@@ -166,7 +168,7 @@ Use different LLM providers for reranking:
```python Python
# Using Anthropic Claude
anthropic_config = {
"rerank": {
"reranker": {
"provider": "llm",
"config": {
"model": "claude-3-haiku-20240307",
@@ -178,8 +180,8 @@ anthropic_config = {
# Using local Ollama model
ollama_config = {
"rerank": {
"provider": "llm",
"reranker": {
"provider": "llm",
"config": {
"model": "llama2:7b",
"provider": "ollama",
@@ -1,8 +1,6 @@
---
title: LLM Reranker
description: 'Use any language model as a reranker with custom prompts'
icon: "robot"
iconType: "solid"
---
## Overview
@@ -1,8 +1,6 @@
---
title: Sentence Transformer
description: 'Local reranking with HuggingFace cross-encoder models'
icon: "server"
iconType: "solid"
---
Sentence Transformer reranker provides local reranking using HuggingFace cross-encoder models, perfect for privacy-focused deployments where you want to keep data on-premises.
@@ -1,8 +1,6 @@
---
title: Zero Entropy
description: 'Neural reranking with Zero Entropy'
icon: "sparkles"
iconType: "solid"
---
[Zero Entropy](https://www.zeroentropy.dev) provides neural reranking models that significantly improve search relevance with fast performance.
@@ -1,7 +1,5 @@
---
title: Performance Optimization
icon: "bolt"
iconType: "solid"
---
Optimizing reranker performance is crucial for maintaining fast search response times while improving result quality. This guide covers best practices for different reranker types.
+68 -60
View File
@@ -1,70 +1,78 @@
---
title: Overview
icon: "arrow-up-arrow-down"
iconType: "solid"
description: 'Pick the right reranker path to boost Mem0 search relevance.'
---
Mem0 includes built-in support for various reranking providers to improve the relevance of memory search results. Rerankers post-process initial vector search results by re-scoring and re-ordering them using more sophisticated relevance models.
Mem0 rerankers rescore vector search hits so your agents surface the most relevant memories. Use this hub to decide when reranking helps, configure a provider, and fine-tune performance.
## Usage
<Info>
Reranking trades extra latency for better precision. Start once you have baseline search working and measure before/after relevance.
</Info>
To use a reranker:
1. **Configure**: Add a `rerank` configuration section in your memory config
2. **Search**: Reranking is automatically enabled for all searches (default: `rerank=True`)
If no reranker is configured, search results will rely on vector similarity scoring alone.
For comprehensive configuration parameters for each reranker, please refer to [Config](./config).
### Controlling Reranking Per Search
Once configured, reranking is enabled by default. You can control it per-search:
```python
# Reranking enabled (default)
results = memory.search("query", user_id="user1")
# Explicitly enable reranking
results = memory.search("query", user_id="user1", rerank=True)
# Disable reranking for this specific search
results = memory.search("query", user_id="user1", rerank=False)
```
## How Reranking Works
1. **Initial Search**: Vector similarity search retrieves candidate memories
2. **Reranking** (if enabled): Selected reranker re-scores candidates using advanced models
3. **Final Results**: Re-ordered results with both vector and rerank scores
<Note>
Reranking operates as a post-processing step and can significantly improve search relevance at the cost of additional latency and API calls.
</Note>
## Supported Rerankers
See the list of supported rerankers below.
<CardGroup cols={2}>
<Card title="Zero Entropy" href="/components/rerankers/models/zero_entropy" />
<Card title="Cohere" href="/components/rerankers/models/cohere" />
<Card title="Sentence Transformer" href="/components/rerankers/models/sentence_transformer" />
<Card title="Hugging Face" href="/components/rerankers/models/huggingface" />
<Card title="LLM-based" href="/components/rerankers/models/llm" />
<Card title="LLM Reranker" href="/components/rerankers/models/llm_reranker" />
<CardGroup cols={3}>
<Card
title="Understand Reranking"
description="See how reranker-enhanced search changes your retrieval flow."
icon="search"
href="/open-source/features/reranker-search"
/>
<Card
title="Configure Providers"
description="Add reranker blocks to your memory configuration."
icon="settings"
href="/components/rerankers/config"
/>
<Card
title="Optimize Performance"
description="Balance relevance, latency, and cost with tuning tactics."
icon="speedometer"
href="/components/rerankers/optimization"
/>
<Card
title="Custom Prompts"
description="Shape LLM-based reranking with tailored instructions."
icon="code"
href="/components/rerankers/custom-prompts"
/>
<Card
title="Zero Entropy Guide"
description="Adopt the managed neural reranker for production workloads."
icon="sparkles"
href="/components/rerankers/models/zero_entropy"
/>
<Card
title="Sentence Transformers"
description="Keep reranking on-device with cross-encoder models."
icon="cpu"
href="/components/rerankers/models/sentence_transformer"
/>
</CardGroup>
## When to Use Reranking
## Picking the Right Reranker
- **Improved Relevance**: When vector search alone doesn't provide sufficiently relevant results
- **Domain-Specific Queries**: For specialized terminology or context that benefits from advanced models
- **Quality vs Speed Trade-off**: When you can accept higher latency for better search quality
- **Production Systems**: Where search quality directly impacts user experience
- **API-first** when you need top quality and can absorb request costs (Cohere, Zero Entropy).
- **Self-hosted** for privacy-sensitive deployments that must stay on your hardware (Sentence Transformer, Hugging Face).
- **LLM-driven** when you need bespoke scoring logic or complex prompts.
- **Hybrid** by enabling reranking only on premium journeys to control spend.
Choose the reranker that best fits your use case:
- **Zero Entropy**: Best balance of speed and quality for general use
- **Cohere**: Enterprise-grade with excellent multilingual support
- **Sentence Transformer**: Local deployment for privacy-sensitive applications
- **Hugging Face**: Wide variety of pre-trained models for specialized use cases
- **LLM-based**: Maximum customization with custom prompts and logic
## Implementation Checklist
1. Confirm baseline search KPIs so you can measure uplift.
2. Select a provider and add the `reranker` block to your config.
3. Test latency impact with production-like query batches.
4. Decide whether to enable reranking globally or per-search via the `rerank` flag.
<CardGroup cols={2}>
<Card
title="Set Up Reranking"
description="Walk through the configuration fields and defaults."
icon="settings"
href="/components/rerankers/config"
/>
<Card
title="Example: Reranker Search"
description="Follow the feature guide to see reranking in action."
icon="rocket"
href="/open-source/features/reranker-search"
/>
</CardGroup>
-2
View File
@@ -1,7 +1,5 @@
---
title: Configurations
icon: "gear"
iconType: "solid"
---
## How to define configurations?
+181
View File
@@ -0,0 +1,181 @@
---
title: Apache Cassandra
---
[Apache Cassandra](https://cassandra.apache.org/) is a highly scalable, distributed NoSQL database designed for handling large amounts of data across many commodity servers with no single point of failure. It supports vector storage for semantic search capabilities in AI applications and can scale to massive datasets with linear performance improvements.
### Usage
```python
import os
from mem0 import Memory
os.environ["OPENAI_API_KEY"] = "sk-xx"
config = {
"vector_store": {
"provider": "cassandra",
"config": {
"contact_points": ["127.0.0.1"],
"port": 9042,
"username": "cassandra",
"password": "cassandra",
"keyspace": "mem0",
"collection_name": "memories",
}
}
}
m = Memory.from_config(config)
messages = [
{"role": "user", "content": "I'm planning to watch a movie tonight. Any recommendations?"},
{"role": "assistant", "content": "How about thriller movies? They can be quite engaging."},
{"role": "user", "content": "I'm not a big fan of thriller movies but I love sci-fi movies."},
{"role": "assistant", "content": "Got it! I'll avoid thriller recommendations and suggest sci-fi movies in the future."}
]
m.add(messages, user_id="alice", metadata={"category": "movies"})
```
#### Using DataStax Astra DB
For managed Cassandra with DataStax Astra DB:
```python
config = {
"vector_store": {
"provider": "cassandra",
"config": {
"contact_points": ["dummy"], # Not used with secure connect bundle
"username": "token",
"password": "AstraCS:...", # Your Astra DB application token
"keyspace": "mem0",
"collection_name": "memories",
"secure_connect_bundle": "/path/to/secure-connect-bundle.zip"
}
}
}
```
<Note>
When using DataStax Astra DB, provide the secure connect bundle path. The contact_points parameter is ignored when a secure connect bundle is provided.
</Note>
### Config
Here are the parameters available for configuring Apache Cassandra:
| Parameter | Description | Default Value |
| --- | --- | --- |
| `contact_points` | List of contact point IP addresses | Required |
| `port` | Cassandra port | `9042` |
| `username` | Database username | `None` |
| `password` | Database password | `None` |
| `keyspace` | Keyspace name | `"mem0"` |
| `collection_name` | Table name for storing vectors | `"memories"` |
| `embedding_model_dims` | Dimensions of embedding vectors | `1536` |
| `secure_connect_bundle` | Path to Astra DB secure connect bundle | `None` |
| `protocol_version` | CQL protocol version | `4` |
| `load_balancing_policy` | Custom load balancing policy | `None` |
### Setup
#### Option 1: Local Cassandra Setup using Docker:
```bash
# Pull and run Cassandra container
docker run --name mem0-cassandra \
-p 9042:9042 \
-e CASSANDRA_CLUSTER_NAME="Mem0Cluster" \
-d cassandra:latest
# Wait for Cassandra to start (may take 1-2 minutes)
docker exec -it mem0-cassandra cqlsh
# Create keyspace
CREATE KEYSPACE IF NOT EXISTS mem0
WITH replication = {'class': 'SimpleStrategy', 'replication_factor': 1};
```
#### Option 2: DataStax Astra DB (Managed Cloud):
1. Sign up at [DataStax Astra](https://astra.datastax.com/)
2. Create a new database
3. Download the secure connect bundle
4. Generate an application token
<Tip>
For production deployments, use DataStax Astra DB for fully managed Cassandra with automatic scaling, backups, and security.
</Tip>
#### Option 3: Install Cassandra Locally:
**Ubuntu/Debian:**
```bash
# Add Apache Cassandra repository
echo "deb https://downloads.apache.org/cassandra/debian 40x main" | sudo tee -a /etc/apt/sources.list.d/cassandra.sources.list
curl https://downloads.apache.org/cassandra/KEYS | sudo apt-key add -
# Install Cassandra
sudo apt-get update
sudo apt-get install cassandra
# Start Cassandra
sudo systemctl start cassandra
# Verify installation
nodetool status
```
**macOS:**
```bash
# Using Homebrew
brew install cassandra
# Start Cassandra
brew services start cassandra
# Connect to CQL shell
cqlsh
```
### Python Client Installation
Install the required Python package:
```bash
pip install cassandra-driver
```
### Performance Considerations
- **Replication Factor**: For production, use replication factor of at least 3
- **Consistency Level**: Balance between consistency and performance (QUORUM recommended)
- **Partitioning**: Cassandra automatically distributes data across nodes
- **Scaling**: Add nodes to linearly increase capacity and performance
### Advanced Configuration
```python
from cassandra.policies import DCAwareRoundRobinPolicy
config = {
"vector_store": {
"provider": "cassandra",
"config": {
"contact_points": ["node1.example.com", "node2.example.com", "node3.example.com"],
"port": 9042,
"username": "mem0_user",
"password": "secure_password",
"keyspace": "mem0_prod",
"collection_name": "memories",
"protocol_version": 4,
"load_balancing_policy": DCAwareRoundRobinPolicy(local_dc='DC1')
}
}
}
```
<Warning>
For production use, configure appropriate replication strategies and consistency levels based on your availability and consistency requirements.
</Warning>
-3
View File
@@ -1,7 +1,5 @@
---
title: Overview
icon: "info"
iconType: "solid"
---
Mem0 includes built-in support for various popular databases. Memory can utilize the database provided by the user, ensuring efficient use for specific needs.
@@ -51,4 +49,3 @@ If you are using a customized model with different dimensions other than 1536 (f
`ValueError: shapes (0,1536) and (768,) not aligned: 1536 (dim 1) != 768 (dim 0)`
You can add `"embedding_model_dims": 768,` to the config of the vector_store to resolve this issue.
@@ -1,7 +1,9 @@
---
title: Personalized AI Tutor
description: "Keep student progress and preferences persistent across tutoring sessions."
---
You can create a personalized AI Tutor using Mem0. This guide will walk you through the necessary steps and provide the complete code to get you started.
## Overview
@@ -110,3 +112,14 @@ for m in memories['results']:
## Conclusion
As the conversation progresses, Mem0's memory automatically updates based on the interactions, providing a continuously improving personalized learning experience. This setup ensures that the AI Tutor can offer contextually relevant and accurate responses, enhancing the overall educational process.
---
<CardGroup cols={2}>
<Card title="Build a Mem0 Companion" icon="users" href="/cookbooks/essentials/building-ai-companion">
Learn the foundations of memory-powered companions with production-ready patterns.
</Card>
<Card title="Travel Assistant with Mem0" icon="plane" href="/cookbooks/companions/travel-assistant">
Build a travel companion that remembers preferences and past conversations.
</Card>
</CardGroup>
@@ -1,8 +1,8 @@
---
title: Mem0 with Ollama
title: Self-Hosted AI Companion
description: "Run Mem0 end-to-end on your machine using Ollama-powered LLMs and embedders."
---
## Running Mem0 Locally with Ollama
Mem0 can be utilized entirely locally by leveraging Ollama for both the embedding model and the language model (LLM). This guide will walk you through the necessary steps and provide the complete code to get you started.
@@ -69,4 +69,15 @@ memories = m.get_all(user_id="john")
## Conclusion
This local setup of Mem0 using Ollama provides a fully self-contained solution for memory management and AI interactions. It allows for greater control over your data and models while still leveraging the powerful capabilities of Mem0.
This local setup of Mem0 using Ollama provides a fully self-contained solution for memory management and AI interactions. It allows for greater control over your data and models while still leveraging the powerful capabilities of Mem0.
---
<CardGroup cols={2}>
<Card title="Configure Open Source" icon="gear" href="/open-source/configuration">
Explore advanced configuration options for vector stores, LLMs, and embedders.
</Card>
<Card title="Build a Mem0 Companion" icon="users" href="/cookbooks/essentials/building-ai-companion">
Learn core companion patterns that work with any LLM provider.
</Card>
</CardGroup>
@@ -1,7 +1,9 @@
---
title: AI Companion in Node.js
title: Build a Node.js Companion
description: "Build a JavaScript fitness coach that remembers user goals run after run."
---
You can create a personalized AI Companion using Mem0. This guide will walk you through the necessary steps and provide the complete code to get you started.
## Overview
@@ -124,3 +126,14 @@ export OPENAI_API_KEY=your_api_key
This implementation demonstrates how to create an AI Companion that maintains context across conversations using Mem0's memory capabilities. The system automatically stores and retrieves relevant information, creating a more personalized and context-aware interaction experience.
As users interact with the system, Mem0's memory system continuously learns and adapts, making future responses more relevant and personalized. This setup is ideal for creating long-term learning AI assistants that can maintain context and provide increasingly personalized responses over time.
---
<CardGroup cols={2}>
<Card title="Partition Memories by Entity" icon="layers" href="/cookbooks/essentials/entity-partitioning-playbook">
Separate user, agent, and session context to keep your companion consistent.
</Card>
<Card title="Quickstart Demo with Mem0" icon="rocket" href="/cookbooks/companions/quickstart-demo">
Run the full showcase app to see memory-powered companions in action.
</Card>
</CardGroup>
@@ -1,7 +1,9 @@
---
title: Mem0 Demo
title: Interactive Memory Demo
description: "Spin up the showcase companion app to see Mem0 memories in action."
---
You can create a personalized AI Companion using Mem0. This guide will walk you through the necessary steps and provide the complete setup instructions to get you started.
<video
@@ -66,3 +68,13 @@ You can find the complete source code for this demo on GitHub:
This setup demonstrates how to build an AI Companion that maintains memory across interactions using Mem0. The system continuously adapts to user interactions, making future responses more relevant and personalized. Experiment with the application and enhance it further to suit your use case!
---
<CardGroup cols={2}>
<Card title="Build a Mem0 Companion" icon="users" href="/cookbooks/essentials/building-ai-companion">
Deep dive into production patterns for fitness coaches, tutors, and assistants.
</Card>
<Card title="Node.js Companion with Mem0" icon="code" href="/cookbooks/companions/nodejs-companion">
Implement a command-line companion using the Node.js SDK.
</Card>
</CardGroup>
@@ -1,5 +1,6 @@
---
title: Personal AI Travel Assistant
title: Smart Travel Assistant
description: "Plan itineraries that remember traveler preferences across trips."
---
@@ -199,4 +200,15 @@ if __name__ == "__main__":
## Conclusion
This Personalized AI Travel Assistant leverages Mem0's memory capabilities to provide context-aware responses. As you interact with it, the assistant learns and improves, offering increasingly personalized travel advice and information.
This Personalized AI Travel Assistant leverages Mem0's memory capabilities to provide context-aware responses. As you interact with it, the assistant learns and improves, offering increasingly personalized travel advice and information.
---
<CardGroup cols={2}>
<Card title="Tag and Organize Memories" icon="tag" href="/cookbooks/essentials/tagging-and-organizing-memories">
Use categories to organize travel preferences, destinations, and user context.
</Card>
<Card title="AI Tutor with Mem0" icon="graduation-cap" href="/cookbooks/companions/ai-tutor">
Build an educational companion that remembers learning progress and preferences.
</Card>
</CardGroup>
@@ -1,9 +1,8 @@
---
title: 'Mem0 with OpenAI Agents SDK for Voice'
description: 'Integrate memory capabilities into your voice agents using Mem0 and OpenAI Agents SDK'
title: Voice-First AI Companion
description: "Pair the OpenAI Agents SDK with Mem0 to build a voice assistant that remembers."
---
## Building Voice Agents with Memory using Mem0 and OpenAI Agents SDK
This guide demonstrates how to combine OpenAI's Agents SDK for voice applications with Mem0's memory capabilities to create a voice assistant that remembers user preferences and past interactions.
@@ -533,6 +532,17 @@ async def save_memories(
"""Store a user memory in memory."""
# This will be visible in your console
logger.debug(f"Saving memory: {memory} for user {USER_ID}")
# Rest of your function...
```
```
---
<CardGroup cols={2}>
<Card title="Multimodal Support" icon="image" href="/platform/features/multimodal-support">
Learn how to add vision and audio memory alongside voice interactions.
</Card>
<Card title="Build a Mem0 Companion" icon="users" href="/cookbooks/essentials/building-ai-companion">
Master the core patterns for building memory-powered companions.
</Card>
</CardGroup>
@@ -1,7 +1,9 @@
---
title: YouTube Assistant Extension
title: Research Assistant for YouTube
description: "Layer personalized context over any video using the Mem0 YouTube assistant."
---
Enhance your YouTube experience with Mem0's YouTube Assistant, a Chrome extension that brings AI-powered chat directly to your YouTube videos. Get instant, personalized answers about video content while leveraging your own knowledge and memories, all without leaving the page.
## Features
@@ -53,3 +55,14 @@ This extension is not available on the Chrome Web Store yet. You can install it
## Privacy and Data Security
Your API keys are stored locally in your browser. Your messages are sent to the Mem0 API for extracting and retrieving memories. Mem0 is committed to ensuring your data's privacy and security.
---
<CardGroup cols={2}>
<Card title="Tag and Organize Memories" icon="tag" href="/cookbooks/essentials/tagging-and-organizing-memories">
Categorize video insights to build a searchable research knowledge base.
</Card>
<Card title="Deep Research with Mem0" icon="magnifying-glass" href="/cookbooks/operations/deep-research">
Combine memory with search tools to conduct comprehensive research projects.
</Card>
</CardGroup>
@@ -0,0 +1,530 @@
---
title: Build a Companion with Mem0
description: "Spin up a fitness coach that remembers goals, adapts tone, and keeps sessions personal."
---
Essentially, creating a companion out of LLMs is as simple as a loop. But these loops work great for one type of character without personalization and fall short as soon as you restart the chat.
Problem: LLMs are stateless. GPT doesn't remember conversations. You could stuff everything inside the context window, but that becomes slow, expensive, and breaks at scale.
The solution: Mem0. It extracts and stores what matters from conversations, then retrieves it when needed. Your companion remembers user preferences, past events, and history.
In this cookbook we'll build a **fitness companion** that:
- Remembers user goals across sessions
- Recalls past workouts and progress
- Adapts its personality based on user preferences
- Handles both short-term context (today's chat) and long-term memory (months of history)
By the end, you'll have a working fitness companion and know how to handle common production challenges.
---
## The Basic Loop with Memory
Max wants to train for a marathon. He starts chatting with Ray, an AI running coach.
```python
from openai import OpenAI
from mem0 import MemoryClient
openai_client = OpenAI(api_key="your-openai-key")
mem0_client = MemoryClient(api_key="your-mem0-key")
def chat(user_input, user_id):
# Retrieve relevant memories
memories = mem0_client.search(user_input, user_id=user_id, limit=5)
context = "\\n".join(m["memory"] for m in memories["results"])
# Call LLM with memory context
response = openai_client.chat.completions.create(
model="gpt-4o-mini",
messages=[
{"role": "system", "content": f"You're Ray, a running coach. Memories:\\n{context}"},
{"role": "user", "content": user_input}
]
).choices[0].message.content
# Store the exchange
mem0_client.add([
{"role": "user", "content": user_input},
{"role": "assistant", "content": response}
], user_id=user_id)
return response
```
**Session 1:**
```python
chat("I want to run a marathon in under 4 hours", user_id="max")
# Output: "That's a solid goal. What's your current weekly mileage?"
# Stored in Mem0: "Max wants to run sub-4 marathon"
```
**Session 2 (next day, app restarted):**
```python
chat("What should I focus on today?", user_id="max")
# Output: "Based on your sub-4 marathon goal, let's work on building your aerobic base..."
```
<Info>
Ray remembers Max's goal across sessions. The app restarted, but the memory persisted. This is the core pattern: retrieve memories, pass them as context, store new exchanges.
</Info>
Ray remembers. Restart the app, and the goal persists. From here on, we'll focus on just the Mem0 API calls.
---
## Organizing Memory by Type
### Separating Temporary from Permanent
Max mentions his knee hurts. That's different from his marathon goal - one is temporary, the other is long-term.
**Categories vs Metadata:**
- **Categories**: AI-assigned by Mem0 based on content (you can't force them)
- **Metadata**: Manually set by you for forced tagging
Define custom categories at the project level. Mem0 will automatically tag memories with relevant categories based on content:
```python
mem0_client.project.update(custom_categories=[
{"goals": "Race targets and training objectives"},
{"constraints": "Injuries, limitations, recovery needs"},
{"preferences": "Training style, surfaces, schedules"}
])
```
<Note>
**Categories vs Metadata:** Categories are AI-assigned by Mem0 based on content semantics. You define the palette, Mem0 picks which ones apply. If you need guaranteed tagging, use `metadata` instead.
</Note>
Now when you add memories, Mem0 automatically assigns the appropriate categories:
```python
# Add goal - Mem0 automatically tags it as "goals"
mem0_client.add(
[{"role": "user", "content": "Sub-4 marathon is my A-race"}],
user_id="max"
)
# Add constraint - Mem0 automatically tags it as "constraints"
mem0_client.add(
[{"role": "user", "content": "My right knee flares up on downhills"}],
user_id="max"
)
```
Mem0 reads the content and intelligently picks which categories apply. You define the palette, it handles the tagging.
**Important:** You cannot force specific categories. Mem0's platform decides which categories are relevant based on content. If you need to force-tag something, use `metadata` instead:
```python
# Force tag using metadata (not categories)
mem0_client.add(
[{"role": "user", "content": "Some workout note"}],
user_id="max",
metadata={"workout_type": "speed", "forced_tag": "custom_label"}
)
```
### Filtering by Category
Retrieve just constraints for workout planning:
```python
constraints = mem0_client.search(
query="injury concerns",
filters={
"AND": [
{"user_id": "max"},
{"categories": {"in": ["constraints"]}}
]
},
threshold=0.0 # optional: widen recall for short phrases
)
print([m["memory"] for m in constraints["results"]])
# Output: ["Max's right knee flares up on downhills"]
```
Ray can plan workouts that avoid aggravating Max's knee, without pulling in race goals or other unrelated memories.
---
## Filtering What Gets Stored
### The Problem
Run the basic loop for a week and check what's stored:
```python
memories = mem0_client.get_all(filters={"AND": [{"user_id": "max"}]})
print([m["memory"] for m in memories["results"]])
# Output: ["Max wants to run marathon under 4 hours", "hey", "lol ok", "cool thanks", "gtg bye"]
```
<Warning>
Without filters, Mem0 stores everything—greetings, filler, and casual chat. This pollutes retrieval: instead of pulling "marathon goal," you get "lol ok." Set custom instructions to keep memory clean.
</Warning>
Noise. Greetings and filler clutter the memory.
### Custom Instructions
Tell Mem0 what matters:
```python
mem0_client.project.update(custom_instructions="""
Extract from running coach conversations:
- Training goals and race targets
- Physical constraints or injuries
- Training preferences (time of day, surfaces, weather)
- Progress milestones
Exclude:
- Greetings and filler
- Casual chatter
- Hypotheticals unless planning related
""")
```
Now chat again:
```python
chat("hey how's it going", user_id="max")
chat("I prefer trail running over roads", user_id="max")
memories = mem0_client.get_all(filters={"AND": [{"user_id": "max"}]})
print([m["memory"] for m in memories["results"]])
# Output: ["Max wants to run marathon under 4 hours", "Max prefers trail running over roads"]
```
<Info>
**Expected output:** Only 2 memories stored—the marathon goal and trail preference. The greeting "hey how's it going" was filtered out automatically. Custom instructions are working.
</Info>
Only meaningful facts. Filler gets dropped automatically.
---
---
## Agent Memory for Personality
### Why Agents Need Memory Too
Max prefers direct feedback, not motivational fluff. Ray needs to remember how to communicate - that's agent memory, separate from user memory.
Store agent personality:
```python
mem0_client.add(
[{"role": "system", "content": "Max wants direct, data-driven feedback. Skip motivational language."}],
agent_id="ray_coach"
)
```
Retrieve agent style alongside user memories:
```python
# Get coach personality
agent_memories = mem0_client.search("coaching style", agent_id="ray_coach")
# Output: ["Max wants direct, data-driven feedback. Skip motivational language."]
# Store conversations with agent_id
mem0_client.add([
{"role": "user", "content": "How'd my run look today?"},
{"role": "assistant", "content": "Pace was 8:15/mile. Heart rate 152, zone 2."}
], user_id="max", agent_id="ray_coach")
```
<Info>
**Expected behavior:** Ray's responses are now data-driven and direct. The agent memory stored the coaching style preference, so future responses adapt automatically without Max having to repeat his preference.
</Info>
No "Great job!" or "Keep it up!" - just data. Ray adapts to Max's preference.
---
## Managing Short-Term Context
### When to Store in Mem0
Don't send every single message to Mem0. Keep recent context in memory, let Mem0 handle the important long-term facts.
```python
# Store only meaningful exchanges in Mem0
mem0_client.add([
{"role": "user", "content": "I want to run a marathon"},
{"role": "assistant", "content": "Let's build a training plan"}
], user_id="max")
# Skip storing filler
# "hey" → don't store
# "cool thanks" → don't store
# Or rely on custom_instructions to filter automatically
```
Last 10 messages in your app's buffer. Important facts in Mem0. Faster, cheaper, still works.
---
## Time-Bound Memories
### Auto-Expiring Facts
Max tweaks his ankle. It'll heal in two weeks - the memory should expire too.
```python
from datetime import datetime, timedelta
expiration = (datetime.now() + timedelta(days=14)).strftime("%Y-%m-%d")
mem0_client.add(
[{"role": "user", "content": "Rolled my left ankle, needs rest"}],
user_id="max",
expiration_date=expiration
)
```
In 14 days, this memory disappears automatically. Ray stops asking about the ankle.
---
## Putting It All Together
Here's the Mem0 setup combining everything:
```python
from mem0 import MemoryClient
from datetime import datetime, timedelta
mem0_client = MemoryClient(api_key="your-mem0-key")
# Configure memory filtering and categories
mem0_client.project.update(
custom_instructions="""
Extract: goals, constraints, preferences, progress
Exclude: greetings, filler, casual chat
""",
custom_categories=[
{"name": "goals", "description": "Training targets"},
{"name": "constraints", "description": "Injuries and limitations"},
{"name": "preferences", "description": "Training style"}
]
)
```
**Week 1 - Store goals and preferences:**
```python
mem0_client.add([
{"role": "user", "content": "I want to run a sub-4 marathon"},
{"role": "assistant", "content": "Got it. Let's build a training plan."}
], user_id="max", agent_id="ray", categories=["goals"])
mem0_client.add([
{"role": "user", "content": "I prefer trail running over roads"}
], user_id="max", categories=["preferences"])
```
**Week 3 - Temporary injury with expiration:**
```python
expiration = (datetime.now() + timedelta(days=14)).strftime("%Y-%m-%d")
mem0_client.add(
[{"role": "user", "content": "Rolled ankle, need light workouts"}],
user_id="max",
categories=["constraints"],
expiration_date=expiration
)
```
**Retrieve for context:**
```python
memories = mem0_client.search("training plan", user_id="max", limit=5)
# Gets: marathon goal, trail preference, ankle injury (if still valid)
```
Ray remembers goals, preferences, and personality. Handles temporary injuries. Works across sessions.
---
## Common Production Patterns
### Episodic Stories with run_id
Training for Boston is different from training for New York. Separate the memory threads:
```python
mem0_client.add(messages, user_id="max", run_id="boston-2025")
mem0_client.add(messages, user_id="max", run_id="nyc-2025")
# Retrieve only Boston memories
boston_memories = mem0_client.search(
"training plan",
user_id="max",
run_id="boston-2025"
)
```
Each race gets its own episodic boundary. No cross-contamination.
### Importing Historical Data
Max has 6 months of training logs to backfill:
```python
old_logs = [
[{"role": "user", "content": "Completed 20-mile long run"}],
[{"role": "user", "content": "Hit 8:00 pace on tempo run"}],
]
for log in old_logs:
mem0_client.add(log, user_id="max")
```
### Handling Contradictions
Max changes his goal from sub-4 to sub-3:45:
```python
# Find the old memory
memories = mem0_client.get_all(filters={"AND": [{"user_id": "max"}]})
goal_memory = [m for m in memories["results"] if "sub-4" in m["memory"]][0]
# Update it
mem0_client.update(goal_memory["id"], "Max wants to run sub-3:45 marathon")
```
Update instead of creating duplicates.
### Multiple Agents
Max works with Ray for running and Jordan for strength training:
```python
chat("easy run today", user_id="max", agent_id="ray")
chat("leg day workout", user_id="max", agent_id="jordan")
```
Each coach maintains separate personality memory while sharing user context.
### Filtering by Date
Prioritize recent training over old data:
```python
recent = mem0_client.search(
"training progress",
user_id="max",
filters={"created_at": {"gte": "2025-10-01"}}
)
```
### Metadata Tagging
Tag workouts by type:
```python
mem0_client.add(
[{"role": "user", "content": "10x400m intervals"}],
user_id="max",
metadata={"workout_type": "speed", "intensity": "high"}
)
# Later, find all speed workouts
speed_sessions = mem0_client.search(
"speed work",
user_id="max",
filters={"metadata": {"workout_type": "speed"}}
)
```
### Pruning Old Memories
Delete irrelevant memories:
```python
mem0_client.delete(memory_id="mem_xyz")
# Or clear an entire run_id
mem0_client.delete_all(user_id="max", run_id="old-training-cycle")
```
---
## What You Built
A companion that:
- **Persists across sessions** - Mem0 storage
- **Filters noise** - custom instructions
- **Organizes by type** - categories
- **Adapts personality** - **`agent_id`**
- **Stays fast** - short-term buffer
- **Handles temporal facts** - expiration
- **Scales to production** - batching, metadata, pruning
This pattern works for any companion: fitness coaches, tutors, roleplay characters, therapy bots, creative writing partners.
---
<Tip>
Start with 2-3 categories max (e.g., goals, constraints, preferences). More categories dilute tagging accuracy. You can always add more later after seeing what Mem0 extracts.
</Tip>
---
## Production Checklist
Before launching:
- Set custom instructions for your domain
- Define 2-3 categories (goals, constraints, preferences)
- Add expiration strategy for time-bound facts
- Implement error handling for API calls
- Monitor memory quality in Mem0 dashboard
- Clear test data from production project
---
<CardGroup cols={2}>
<Card title="Partition Memories by Entity" icon="layers" href="/cookbooks/essentials/entity-partitioning-playbook">
Keep companions from leaking context by combining user, agent, and session scopes.
</Card>
<Card title="Tag Support Memories" icon="tag" href="/cookbooks/essentials/tagging-and-organizing-memories">
Organize customer context to keep assistants responsive at scale.
</Card>
</CardGroup>
@@ -0,0 +1,361 @@
---
title: Choose Vector vs Graph Memory
description: "Blend vector search with graph relationships to answer multi-hop questions."
---
Most AI agents use vector stores for RAG operations - they work great for semantic search and retrieving relevant context. But there's a gap when queries require understanding connections between entities.
Mem0 brings graph memory into the picture to fill this gap. In this cookbook, we'll create a company knowledge base with Mem0, using both vector and graph stores. You'll learn when each one helps along the way.
---
## Vector and Graph Stores
When you add a memory to Mem0, it goes into a **vector store** by default. Vector stores are excellent at semantic search - finding memories that match the meaning of your query.
**Graph stores** work differently. They extract **entities** (people, projects, teams) and **relationships between them** (works_with, reports_to, member_of). This lets you answer questions that need connecting information across multiple memories.
We will go through examples in this cookbook while building a company's knowledge base along the way.
---
## Starting Simple
Since we're building a company knowledge base, let's add some employee information:
```python
from mem0 import MemoryClient
client = MemoryClient(api_key="your-api-key")
# Add employee info
client.add("Emma is a software engineer in Seattle", user_id="company_kb")
client.add("David is a product manager in Austin", user_id="company_kb")
```
Now let's search for Emma's role:
```python
results = client.search("What does Emma do?", filters={"user_id": "company_kb"})
print(results['results'][0]['memory'])
```
**Output:**
```
Emma is a software engineer in Seattle
```
<Info>
**Expected output:** Vector search returned Emma's role instantly. When queries ask for facts directly stored in one memory, vector semantic search is perfect—fast and accurate.
</Info>
This works perfectly. Vector search found the memory that semantically matches "What does Emma do?" and returned Emma's role.
---
## Adding Team Structure
Let's add some information about how the team works together:
```python
client.add("Emma works with David on the mobile app redesign", user_id="company_kb")
client.add("David reports to Rachel, who manages the design team", user_id="company_kb")
```
Now we have two pieces of information stored:
1. Emma works with David
2. David reports to Rachel
Let's try asking something that needs both pieces:
```python
results = client.search(
"Who is Emma's teammate's manager?",
filters={"user_id": "company_kb"}
)
for r in results['results']:
print(r['memory'])
```
**Output:**
```
Emma works with David on the mobile app redesign
David reports to Rachel, who manages the design team
```
Vector search returned both memories, but it didn't connect them. You'd need to manually figure out:
- Emma's teammate is David (from memory 1)
- David's manager is Rachel (from memory 2)
- So the answer is Rachel
<Warning>
Vector search can't traverse relationships. It returns relevant memories, but you must connect the dots manually. For "Who is Emma's teammate's manager?", vector search gives you the pieces—not the answer. This breaks down as queries get more complex (3+ hops).
</Warning>
---
## Enter Graph Memory
Let's add the same information with graph memory enabled:
```python
client.add(
"Emma works with David on the mobile app redesign",
user_id="company_kb",
enable_graph=True
)
client.add(
"David reports to Rachel, who manages the design team",
user_id="company_kb",
enable_graph=True
)
```
When you set `enable_graph=True`, Mem0 extracts entities and relationships:
- `emma --[works_with]--> david`
- `david --[reports_to]--> rachel`
- `rachel --[manages]--> design_team`
Now the same query works differently:
```python
results = client.search(
"Who is Emma's teammate's manager?",
filters={"user_id": "company_kb"},
enable_graph=True
)
print(results['results'][0]['memory'])
print("\\nRelationships found:")
for rel in results.get('relations', []):
print(f" {rel['source']}, {rel['target']} ({rel['relationship']})")
```
**Output:**
```
David reports to Rachel, who manages the design team
Relationships found:
emma, david (works_with)
david, rachel (reports_to)
```
<Info>
**Expected behavior:** Graph memory returns the direct answer—"David reports to Rachel"—plus the relationship chain that got there. No manual connecting needed. The graph traversed: Emma → works_with → David → reports_to → Rachel.
</Info>
Graph memory traversed the relationships automatically: Emma works with David, David reports to Rachel, so Rachel is the answer.
---
## How It Connects
Here's what the graph looks like behind the scenes:
```mermaid
graph LR
Emma[Emma] -->|works_with| David[David]
David -->|reports_to| Rachel[Rachel]
Rachel -->|manages| DesignTeam[Design Team]
David -->|works_on| MobileApp[Mobile App]
Emma -->|works_on| MobileApp
```
Graph memory lets you discover relations and memories which are tricky to do with direct vector stores.
Vector search would need the exact words in your query to match. Graph memory follows the connections.
---
## When to Use Each
Use **vector store** (default) when:
- Searching documents by semantic similarity
- Looking up facts that don't need relationships
- Building FAQs or knowledge bases where each item stands alone
Use **graph memory** when:
- Tracking organizational hierarchies (who reports to whom)
- Understanding project teams (who collaborates with whom)
- Building CRMs (which contacts connect to which companies)
- Product recommendations (what items are bought together)
For our company knowledge base, we'll use both:
- Vector for individual facts: "Emma specializes in React"
- Graph for relationships: "Emma works with David"
---
## Putting It Together
Let's build a small company knowledge base with both approaches:
```python
# Facts about individuals - vector store is fine
client.add("Emma specializes in React and TypeScript", user_id="company_kb")
client.add("David has 5 years of product management experience", user_id="company_kb")
# Relationships - use graph memory
client.add(
"Emma and David work together on the mobile app",
user_id="company_kb",
enable_graph=True
)
client.add(
"David reports to Rachel",
user_id="company_kb",
enable_graph=True
)
client.add(
"Rachel runs weekly team syncs every Tuesday",
user_id="company_kb",
enable_graph=True
)
```
Now we can ask different types of questions:
```python
# Direct fact - vector search
results = client.search("What are Emma's skills?", filters={"user_id": "company_kb"})
print(results['results'][0]['memory'])
```
**Output:**
```
Emma specializes in React and TypeScript
```
```python
# Multi-hop relationship - graph search
results = client.search(
"What meetings does Emma's project manager's boss run?",
filters={"user_id": "company_kb"},
enable_graph=True
)
print(results['results'][0]['memory'])
```
**Output:**
```
Rachel runs weekly team syncs every Tuesday
```
Graph memory connected: Emma works with David, David reports to Rachel, Rachel runs team syncs.
<Tip>
Enable graph memory when your queries need multi-hop traversal: org charts (who reports to whom), project teams (who collaborates), CRMs (which contacts connect to companies). For single-fact lookups, stick with vector search—it's faster and cheaper.
</Tip>
---
## The Tradeoff
Graph memory adds processing time and cost. When you call `client.add()` with `enable_graph=True`, Mem0 makes extra LLM calls to extract entities and relationships.
<Note>
**Cost consideration:** Graph memory extraction adds ~2-3 extra LLM calls per `add()` operation to identify entities and relationships. Use it selectively—enable graph for organizational structure and long-term relationships, skip it for temporary notes and simple facts.
</Note>
Use graph memory when the relationship traversal adds real value. For most use cases, vector search is sufficient and faster.
```python
# Long-term organizational structure - worth using graph
client.add(
"Emma mentors two junior engineers on the frontend team",
user_id="company_kb",
enable_graph=True
)
# Temporary notes - skip graph, not worth the cost
client.add(
"Emma is out sick today",
user_id="company_kb",
run_id="daily_notes"
)
```
---
## Enabling Graph Memory
You can enable graph memory in two ways:
**Per-call** (recommended to start):
```python
client.add("Emma works with David", user_id="company_kb", enable_graph=True)
client.search("team structure", filters={"user_id": "company_kb"}, enable_graph=True)
```
**Project-wide** (if most of your data has relationships):
```python
client.project.update(enable_graph=True)
# Now every add uses graph automatically
client.add("Emma mentors Jordan", user_id="company_kb")
```
---
## What You Built
A hybrid company knowledge base that combines both architectures:
- **Vector search** - Fast semantic lookups for individual facts (Emma's skills, David's experience)
- **Graph memory** - Multi-hop relationship traversal (Emma's teammate's manager, project hierarchies)
- **Selective enablement** - Graph only for long-term organizational structure, vector for everything else
- **Cost optimization** - Skip graph extraction for temporary notes and simple facts
This pattern scales from 10-person startups to enterprise org charts with thousands of employees.
---
## Summary
Vector stores handle most memory operations efficiently—semantic search works great for finding relevant information. Add graph memory when your queries need to understand how entities connect across multiple hops.
The key is knowing which tool fits your query pattern: direct questions work with vectors, multi-hop relationship queries need graphs.
<CardGroup cols={2}>
<Card title="Partition Memories by Entity" icon="layers" href="/cookbooks/essentials/entity-partitioning-playbook">
Scope memories across users, agents, apps, and sessions to balance personalization and reuse.
</Card>
<Card title="Export Everything Safely" icon="download" href="/cookbooks/essentials/exporting-memories">
Learn how to migrate or audit stored memories with structured exports.
</Card>
</CardGroup>
@@ -0,0 +1,523 @@
---
title: Control Memory Ingestion
description: "Filter speculation, enforce formats, and gate low-confidence data before it persists."
---
AI assistants plugged with memory systems face a problem - they often store everything. Not every conversation needs to be remembered, and not every detail should go to the memory store. Without proper controls, memory systems accumulate unreliable data.
Mem0 lets you control your memory ingestion pipeline. In this cookbook, we'll demonstrate these controls using a medical assistant example - showing how to filter unwanted data, enforce data formats, and implement confidence-based storage.
---
## Overview
Without controls, everything gets stored - speculation, low-confidence data, and information that shouldn't persist. This uncontrolled ingestion leads to cluttered memory and retrieval failures.
Mem0 provides **three tools to control** what gets stored:
1. **Custom instructions** define what to remember and what to ignore.
2. **Confidence thresholds** ensure only verified facts persist.
3. **Memory updates** let you change information without creating duplicates.
In this tutorial, we will:
- Filter speculative statements with custom instructions
- Configure confidence thresholds for fact verification
- Update stored information without duplication
- Build a complete ingestion pipeline
---
## Setup
```python
from mem0 import MemoryClient
client = MemoryClient(api_key="your-api-key")
```
<Note>
Replace `your-api-key` with your actual Mem0 API key from the [dashboard](https://app.mem0.ai). Without proper API authentication, memory operations will fail.
</Note>
---
## The Problem
Uncontrolled ingestion stores everything, including speculation:
```python
# Patient mentions speculation
messages = [{"role": "user", "content": "I think I might be allergic to penicillin"}]
client.add(messages, user_id="patient_123")
# Check what got stored
results = client.search("patient allergies", filters={"user_id": "patient_123"})
print(results['results'][0]['memory'])
```
**Output:**
```
Patient is allergic to penicillin
```
<Warning>
Without custom instructions, AI assistants treat speculation as confirmed facts. "I think I might be allergic" becomes "Patient is allergic"—a dangerous transformation in sensitive domains like healthcare, legal, or financial services.
</Warning>
The speculation became a confirmed fact. Let's add controls.
---
## Custom Instructions
Custom instructions tell Mem0 what to store and what to ignore.
```python
instructions = """
Only store CONFIRMED medical facts.
Store:
- Confirmed diagnoses from doctors
- Known allergies with documented reactions
- Current medications being taken
Ignore:
- Speculation (words like "might", "maybe", "I think")
- Unverified symptoms
- Casual mentions without confirmation
"""
client.project.update(custom_instructions=instructions)
# Same speculative statement
messages = [{"role": "user", "content": "I think I might be allergic to penicillin"}]
client.add(messages, user_id="patient_123")
# Check what got stored
results = client.get_all(filters={"user_id": "patient_123"})
print(f"Memories stored: {len(results['results'])}")
```
**Output:**
```
Memories stored: 0
```
<Info>
**Expected output:** Zero memories stored. The speculative statement "I think I might be allergic" was filtered out before reaching storage. Custom instructions are actively blocking unreliable data.
</Info>
The speculation was filtered out.
---
## Designing Custom Instructions
When designing instructions, consider the trade-off between precision and recall:
**Too restrictive:** You'll miss important information (false negatives)
```python
# Too strict - filters out useful context
"""
Only store information if explicitly stated by a doctor with full name,
date, time, and medical license number.
"""
```
**Too permissive:** You'll store unreliable data (false positives)
```python
# Too loose - stores speculation as fact
"""
Store any health-related information mentioned.
"""
```
**Balanced approach:**
```python
# Clear categories with examples
"""
Store CONFIRMED facts:
- Diagnoses: "Dr. Smith diagnosed hypertension on March 15th"
- Allergies: "Patient had hives reaction to penicillin"
- Medications: "Taking Lisinopril 10mg daily"
Ignore SPECULATION:
- "I think I might have..."
- "Maybe it's..."
- "Could be related to..."
"""
```
<Tip>
Start with strict instructions (only store confirmed facts), then relax them based on your use case. It's easier to allow more data than to clean up polluted memory. Test with sample conversations before deploying to production.
</Tip>
Start with clear categories and iterate based on retrieval quality.
---
## Confidence Thresholds
Mem0 assigns confidence scores to extracted memories. Use these to filter low-quality data.
### Setting Thresholds
Setting the right confidence threshold depends on your application:
- **High-stakes domains** (medical, legal): Require 0.8+ confidence
- **General assistants**: 0.6+ confidence is often sufficient
- **Exploratory systems**: Lower thresholds (0.4+) capture more data
Test your pipeline with multiple input examples and threshold combinations to find what works for your use case.
```python
# Configure stricter instructions
client.project.update(
custom_instructions="""
Only extract memories with HIGH confidence.
Require specific details (dates, dosages, doctor names) for medical facts.
Skip vague or uncertain statements.
"""
)
# Test with uncertain statement
messages = [{"role": "user", "content": "The doctor mentioned something about my blood pressure"}]
result1 = client.add(messages, user_id="patient_123")
# Test with confirmed fact
messages = [{"role": "user", "content": "Dr. Smith diagnosed me with hypertension on March 15th"}]
result2 = client.add(messages, user_id="patient_123")
print("Vague statement stored:", len(result1['results']) > 0)
print("Confirmed fact stored:", len(result2['results']) > 0)
```
**Output:**
```
Vague statement stored: False
Confirmed fact stored: True
```
<Info icon="check">
**Expected behavior:** Low-confidence extractions are now filtered out automatically. Only verified facts with specific details (names, dates, dosages) persist in memory. The confidence threshold is working.
</Info>
The vague statement was filtered for low confidence. The confirmed fact with specific details was stored.
---
## Filtering Sensitive Information
Custom instructions can prevent storing personal identifiers:
```python
client.project.update(
custom_instructions="""
Medical memory rules:
STORE:
- Confirmed diagnoses
- Verified allergies
- Current medications
NEVER STORE:
- Social Security Numbers
- Insurance policy numbers
- Credit card information
- Full addresses
- Phone numbers
Replace identifiers with generic references if mentioned.
"""
)
# Test with PII
messages = [
{"role": "user", "content": "My SSN is 123-45-6789 and I'm allergic to penicillin"}
]
client.add(messages, user_id="patient_123")
# Check what was stored
results = client.get_all(filters={"user_id": "patient_123"})
for result in results['results']:
print(result['memory'])
```
**Output:**
```
Patient is allergic to penicillin
```
The SSN was filtered out, but the allergy was stored.
---
## Updating Memories
When information changes, update existing memories instead of creating duplicates.
```python
# Initial allergy stored
result = client.add(
[{"role": "user", "content": "Patient confirmed allergy to penicillin with documented hives reaction"}],
user_id="patient_123"
)
memory_id = result['results'][0]['id']
print(f"Stored memory: {memory_id}")
# Later, patient gets retested - allergy was false positive
client.update(
memory_id=memory_id,
text="Patient tested negative for penicillin allergy on April 2nd, 2025. Previous allergy was false positive.",
metadata={"verified": True, "updated_date": "2025-04-02"}
)
# Retrieve the updated memory
updated = client.get(memory_id)
print(f"\\nUpdated memory: {updated['memory']}")
print(f"Metadata: {updated['metadata']}")
```
**Output:**
```
Stored memory: mem_abc123
Updated memory: Patient tested negative for penicillin allergy on April 2nd, 2025. Previous allergy was false positive.
Metadata: {'verified': True, 'updated_date': '2025-04-02'}
```
### Benefits of Updating
**Preserves history:**
- `created_at` shows when the memory was first stored
- `updated_at` shows when it was modified
- Audit trail for compliance
**Avoids conflicts:**
- No duplicate or contradicting memories
- Single source of truth for each fact
<Warning>
That “no duplicates” promise comes from the inference pipeline. Keep `infer=True` when you rely on automatic updates. Raw imports (`infer=False`) skip conflict checks, so mixing the two modes for the same fact will create duplicates.
</Warning>
**Maintains relationships:**
- If using graph memory, connections to other entities persist
### Pick the right inference mode
| Mode | What it does | Best for | Watch out for |
| --- | --- | --- | --- |
| `infer=True` *(default)* | Runs the LLM pipeline so Mem0 extracts structured facts and resolves conflicts automatically. | Daily conversations, preference tracking, anything you want deduped. | Slightly slower because inference runs on every write. |
| `infer=False` | Stores your payload exactly as-is—no inference, no dedupe. | Bulk imports, compliance snapshots, curated facts you already trust. | Later `infer=True` calls for the same fact will create duplicates you must clean manually. |
<Tip>
Stay consistent per data source. If you need both behaviors, keep them in separate scopes (e.g., different `app_id` or `run_id`) so you always know which memories are inferred vs direct imports.
</Tip>
---
## Update vs Delete
When should you update vs delete?
### Update when:
- Information changes but remains relevant
- You need audit history
- The memory has relationships to other data
```python
# Medication dosage changed
client.update(
memory_id=med_id,
text="Taking Lisinopril 20mg daily (increased from 10mg on March 1st)"
)
```
### Delete when:
- Information was completely wrong
- Memory is no longer relevant
- Duplicate entry
```python
# Duplicate entry
client.delete(memory_id)
```
---
## Putting It Together
Here's a complete ingestion pipeline with all controls:
```python
from mem0 import MemoryClient
import os
# Initialize client
client = MemoryClient(api_key=os.getenv("MEM0_API_KEY"))
# Configure custom instructions
client.project.update(
custom_instructions="""
Medical memory assistant rules:
STORE:
- Confirmed diagnoses (with doctor name and date)
- Verified allergies (with reaction details)
- Current medications (with dosage)
IGNORE:
- Speculation (might, maybe, possibly)
- Unverified symptoms
- Personal identifiers (SSN, insurance numbers)
CONFIDENCE:
Require high confidence. Reject vague or uncertain statements.
Require specific details: names, dates, dosages.
"""
)
# Helper function for safe ingestion
def add_medical_memory(content, user_id, metadata=None):
"""Add memory with automatic filtering."""
result = client.add(
[{"role": "user", "content": content}],
user_id=user_id,
metadata=metadata or {}
)
if result['results']:
print(f"✓ Stored: {result['results'][0]['memory']}")
else:
print(f"✗ Filtered: {content}")
return result
# Test cases
print("Testing ingestion pipeline:\\n")
test_cases = [
"I think I might be allergic to penicillin",
"Dr. Johnson confirmed penicillin allergy on Jan 15th with hives reaction",
"Patient SSN is 123-45-6789",
"Currently taking Lisinopril 10mg daily for hypertension",
"Feeling tired lately",
"Dr. Martinez diagnosed Type 2 diabetes on February 3rd, 2025"
]
for content in test_cases:
add_medical_memory(content, user_id="patient_123")
print()
```
**Output:**
```
Testing ingestion pipeline:
✗ Filtered: I think I might be allergic to penicillin
✓ Stored: Patient has confirmed penicillin allergy diagnosed by Dr. Johnson on January 15th with hives reaction
✗ Filtered: Patient SSN is 123-45-6789
✓ Stored: Patient is currently taking Lisinopril 10mg daily for hypertension
✗ Filtered: Feeling tired lately
✓ Stored: Patient diagnosed with Type 2 diabetes by Dr. Martinez on February 3rd, 2025
```
---
## Per-Call Instructions
You can override project-level instructions for specific conversations:
First define custom instructions
```python
custom_instructions="""Emergency intake mode:Store ALL symptoms and observations immediately.
Flag for later review and verification."""
```
```python
# Emergency intake - store everything temporarily
emergency_messages = [
{"role": "user", "content": "Patient arrived with chest pain and shortness of breath"}
]
client.add(
emergency_messages,
user_id="patient_456",
custom_instructions=custom_instructions,
metadata={"type": "emergency", "review_required": True}
)
```
This is useful for:
- Different conversation types (emergency vs routine)
- Channel-specific rules (phone vs in-person)
- Temporary data collection that needs review
---
## What You Built
You now have a medical assistant with production-grade memory controls:
- **Custom instructions** - Filter speculation and enforce confirmed facts only
- **Confidence thresholds** - Gate extractions below 0.7 confidence score
- **Memory updates** - Modify stored information without creating duplicates
- **Per-call instructions** - Apply temporary rules for specific conversations
- **PII filtering** - Block sensitive data (SSNs, insurance numbers) automatically
These controls prevent retrieval failures and ensure your AI assistant works with reliable, verified information.
---
## Summary
Start with conservative filters (only store confirmed facts) and iterate based on your application's needs. Combine custom instructions with confidence thresholds for the most reliable memory ingestion pipeline.
<CardGroup cols={2}>
<Card title="Expire Short-Term Data" icon="timer" href="/cookbooks/essentials/memory-expiration-short-and-long-term">
Automatically clean up session context before it clutters retrieval.
</Card>
<Card title="Choose Your Memory Architecture" icon="sitemap" href="/cookbooks/essentials/choosing-memory-architecture-vector-vs-graph">
Learn when to layer graph memory alongside vectors for multi-hop queries.
</Card>
</CardGroup>
@@ -0,0 +1,336 @@
---
title: Partition Memories by Entity
description: Keep memories separate by tagging each write and query with user, agent, app, and session identifiers.
---
Nora runs a travel service. When she stored all memories in one bucket, a recruiter's nut allergy accidentally appeared in a traveler's dinner reservation. Let's fix this by properly separating memories for different users, agents, and applications.
<Info icon="clock">
**Time to complete:** ~15 minutes · **Languages:** Python
</Info>
## Setup
```python
from mem0 import MemoryClient
client = MemoryClient(api_key="m0-...")
```
Grab an API key from the <Link href="https://app.mem0.ai/">Mem0 dashboard</Link> to get started.
## Store and Retrieve Scoped Memories
Let's start by storing Cam's travel preferences and retrieving them:
```python
cam_messages = [
{"role": "user", "content": "I'm Cam. Keep in mind I avoid shellfish and prefer boutique hotels."},
{"role": "assistant", "content": "Noted! I'll use those preferences in future itineraries."}
]
result = client.add(
cam_messages,
user_id="traveler_cam",
agent_id="travel_planner",
run_id="tokyo-2025-weekend",
app_id="concierge_app"
)
```
The memory is now stored. Let's retrieve those memories with the same identifiers:
```python
user_scope = {
"AND": [
{"user_id": "traveler_cam"},
{"app_id": "concierge_app"},
{"run_id": "tokyo-2025-weekend"}
]
}
user_memories = client.search("Any dietary restrictions?", filters=user_scope)
print(user_memories)
agent_scope = {
"AND": [
{"agent_id": "travel_planner"},
{"app_id": "concierge_app"}
]
}
agent_memories = client.search("Any dietary restrictions?", filters=agent_scope)
print(agent_memories)
```
**Output:**
```
# User scope returns user's memory
{'results': [{'memory': 'avoids shellfish and prefers boutique hotels', ...}]}
# Agent scope returns agent's own memory
{'results': [{'memory': 'Cam prefers boutique hotels and avoids shellfish', ...}]}
```
<Tip icon="compass">
Memories can be written with several identifiers, but each search resolves one entity boundary at a time. Run separate queries for user and agent scopes—just like above—rather than combining both in a single filter.
</Tip>
## When Memories Leak
When Nora adds a chef agent, Cam's travel preferences leak into food recommendations:
```python
chef_filters = {"AND": [{"user_id": "traveler_cam"}]}
collision = client.search("What should I cook?", filters=chef_filters)
print(collision)
```
**Output:**
```
['avoids shellfish and prefers boutique hotels', 'prefers Kyoto kaiseki dining experiences']
```
The travel preferences appear because we only filtered by `user_id`. The chef agent shouldn't see hotel preferences.
## Fix the Leak with Proper Filters
First, let's add a memory specifically for the chef agent:
```python
chef_memory = [
{"role": "user", "content": "I'd like to try some authentic Kyoto cuisine."},
{"role": "assistant", "content": "I'll remember that you prefer Kyoto kaiseki dining experiences."}
]
client.add(
chef_memory,
user_id="traveler_cam",
agent_id="chef_recommender",
run_id="menu-planning-2025-04",
app_id="concierge_app"
)
```
Now search within the chef's scope:
```python
safe_filters = {
"AND": [
{"agent_id": "chef_recommender"},
{"app_id": "concierge_app"},
{"run_id": "menu-planning-2025-04"}
]
}
chef_memories = client.search("Any food alerts?", filters=safe_filters)
print(chef_memories)
```
**Output:**
```
{'results': [{'memory': 'prefers Kyoto kaiseki dining experiences', ...}]}
```
Now the chef agent only sees its own food preferences. The hotel preferences stay with the travel agent.
## Separate Apps with app_id
Nora white-labels her travel service for a sports brand. Use `app_id` to keep enterprise data separate:
```python
enterprise_filters = {
"AND": [
{"app_id": "sports_brand_portal"}
],
"OR": [
{"user_id": "*"},
{"agent_id": "*"}
]
}
page = client.get_all(filters=enterprise_filters, page=1, page_size=10)
print([row["user_id"] for row in page["results"]])
```
**Output:**
```
['athlete_jane', 'coach_mike', 'team_admin']
```
<Info>
Wildcards (`"*"` ) only match non-null values. Make sure you write memories with explicit `app_id` values.
</Info>
<Tip icon="sparkles">
Need a deeper tour of AND vs OR, nested filters, or wildcard tricks? Check the <Link href="/platform/features/v2-memory-filters">Memory Filters v2 guide</Link> for full examples you can copy into this flow.
</Tip>
When the sports brand offboards, delete all their data:
```python
client.delete_all(app_id="sports_brand_portal")
```
**Output:**
```
{'message': 'Memories deleted successfully!'}
```
## Production Patterns
```python
# Nightly audits - check all data for an app
def audit_app(app_id: str):
filters = {
"AND": [{"app_id": app_id}],
"OR": [{"user_id": "*"}, {"agent_id": "*"}]
}
return client.get_all(filters=filters, page=1, page_size=50)
# Session cleanup - delete temporary conversations
def close_ticket(ticket_id: str, user_id: str):
client.delete_all(user_id=user_id, run_id=ticket_id)
# Compliance exports - get all data for one tenant
export = client.get_memory_export(filters={"AND": [{"app_id": "sports_brand_portal"}]})
```
## Complete Example
Putting it all together - here's how to properly scope memories:
```python
# Store memories with all identifiers
client.add(
[{"role": "user", "content": "I need a hotel near the conference center."}],
user_id="exec_123",
agent_id="booking_assistant",
app_id="enterprise_portal",
run_id="trip-2025-03"
)
# Retrieve with the same scope
filters = {
"AND": [
{"user_id": "exec_123"},
{"app_id": "enterprise_portal"},
{"run_id": "trip-2025-03"}
]
}
# Alternative: Use wildcards if you're not sure about some fields
# filters = {
# "AND": [
# {"user_id": "exec_123"},
# {"agent_id": "*"}, # Match any agent
# {"app_id": "enterprise_portal"},
# {"run_id": "*"} # Match any run
# ]
# }
results = client.search("Hotels near conference", filters=filters)
# Debug: Print the filter you're using
print(f"Searching with filters: {filters}")
# If no results, try a broader search to see what's stored
if not results["results"]:
print("No results found! Trying broader search...")
broader = client.get_all(filters={"user_id": "exec_123"})
print(broader)
print(results["results"][0]["memory"])
```
**Output:**
```
I need a hotel near the conference center.
```
## When to Use Each Identifier
| Identifier | When to Use | Example Values |
|------------|-------------|----------------|
| `user_id` | Individual preferences that persist across all interactions | `cam_traveler`, `sarah_exec`, `team_alpha` |
| `agent_id` | Different AI roles need separate context | `travel_agent`, `concierge`, `customer_support` |
| `app_id` | White-label deployments or separate products | `travel_app_ios`, `enterprise_portal`, `partner_integration` |
| `run_id` | Temporary sessions that should be isolated | `support_ticket_9234`, `chat_session_456`, `booking_flow_789` |
## Troubleshooting Common Issues
### My search returns empty results!
**Problem**: Using `AND` with exact matches but some fields might be `null`.
**Solution**:
```python
# If this returns nothing:
filters = {"AND": [{"user_id": "u1"}, {"agent_id": "a1"}]}
# Try using wildcards:
filters = {"AND": [{"user_id": "u1"}, {"agent_id": "*"}]}
# Or don't include fields you don't need:
filters = {"AND": [{"user_id": "u1"}]}
```
### OR gives results but AND doesn't
This confirms you have a **field mismatch**. The memory exists but some identifier values don't match exactly.
**Always check what's actually stored:**
```python
# Get all memories for the user to see the actual field values
all_mems = client.get_all(filters={"user_id": "your_user_id"})
print(json.dumps(all_mems, indent=2))
```
## Best Practices
1. **Use consistent identifier formats**
```python
# Good: consistent patterns
user_id = "cam_traveler"
agent_id = "travel_agent_v1"
app_id = "nora_concierge_app"
run_id = "tokyo_trip_2025_03"
# Avoid: mixed patterns
# user_id = "123", agent_id = "agent2", app_id = "app"
```
2. **Print filters when debugging**
```python
filters = {"AND": [{"user_id": "cam", "agent_id": "chef"}]}
print(f"Searching with filters: {filters}") # Helps catch typos
```
3. **Clean up temporary sessions**
```python
# After a support ticket closes
client.delete_all(user_id="customer_123", run_id="ticket_456")
```
## Summary
You learned how to:
- Store memories with proper entity scoping using `user_id`, `agent_id`, `app_id`, and `run_id`
- Prevent memory leaks between different agents and applications
- Clean up data for specific tenants or sessions
- Use wildcards to query across scoped memories
## Next Steps
<CardGroup cols={2}>
<Card
title="Deep Dive: Memory Filters v2"
description="Layer entity filters with JSON logic to answer complex queries."
icon="sliders"
href="/platform/features/v2-memory-filters"
/>
<Card
title="Control Memory Ingestion"
description="Pair scoped storage with rules that block low-quality facts."
icon="shield-check"
href="/cookbooks/essentials/controlling-memory-ingestion"
/>
</CardGroup>
@@ -0,0 +1,289 @@
---
title: Export Stored Memories
description: "Retrieve, review, and migrate user memories with structured exports."
---
Mem0 is a dynamic memory store that gives you full control over your data. Along with storing memories, it gives you the ability to retrieve, export, and migrate your data whenever you need.
This cookbook shows you how to retrieve and export your data for inspection, migration, or compliance.
---
## Setup
```python
from mem0 import MemoryClient
client = MemoryClient(api_key="your-api-key")
```
<Note>
Your API key needs export permissions to download memory data. Check your project settings on the [dashboard](https://app.mem0.ai) if export operations fail with authentication errors.
</Note>
Let's add some sample memories to work with:
```python
# Dev's work history
client.add(
"Dev works at TechCorp as a senior engineer",
user_id="dev",
metadata={"type": "professional"}
)
# Arjun's preferences
client.add(
"Arjun prefers morning meetings and async communication",
user_id="arjun",
metadata={"type": "preference"}
)
# Carl's project notes
client.add(
"Carl is leading the API redesign project, targeting Q2 launch",
user_id="carl",
metadata={"type": "project"}
)
```
---
## Getting All Memories
Use `get_all()` with filters to retrieve everything for a specific user:
```python
dev_memories = client.get_all(
filters={"user_id": "dev"},
page_size=50
)
print(f"Total memories: {dev_memories['count']}")
print(f"First memory: {dev_memories['results'][0]['memory']}")
```
**Output:**
```
Total memories: 1
First memory: Dev works at TechCorp as a senior engineer
```
<Info>
**Expected output:** `get_all()` retrieved Dev's complete memory record. This method returns everything matching your filters—no semantic search, no ranking, just raw retrieval. Perfect for exports and audits.
</Info>
You can filter by metadata to get specific types:
```python
carl_projects = client.get_all(
filters={
"AND": [
{"user_id": "carl"},
{"metadata": {"type": "project"}}
]
}
)
for memory in carl_projects['results']:
print(memory['memory'])
```
**Output:**
```
Carl is leading the API redesign project, targeting Q2 launch
```
---
## Searching Memories
When you need semantic search instead of retrieving everything, use `search()`:
```python
results = client.search(
query="What does Dev do for work?",
filters={"user_id": "dev"},
top_k=5
)
for result in results['results']:
print(f"{result['memory']} (score: {result['score']:.2f})")
```
**Output:**
```
Dev works at TechCorp as a senior engineer (score: 0.89)
```
Search works across all memory fields and ranks by relevance. Use it when you have a specific question, use `get_all()` when you need everything.
---
## Exporting to Structured Format
For migrations or compliance, you can export memories into a structured schema using Pydantic-style JSON schemas.
### Step 1: Define the schema
```python
professional_profile_schema = {
"properties": {
"full_name": {
"type": "string",
"description": "The person's full name"
},
"current_role": {
"type": "string",
"description": "Current job title or role"
},
"company": {
"type": "string",
"description": "Current employer"
}
},
"title": "ProfessionalProfile",
"type": "object"
}
```
### Step 2: Create export job
```python
export_job = client.create_memory_export(
schema=professional_profile_schema,
filters={"user_id": "dev"}
)
print(f"Export ID: {export_job['id']}")
print(f"Status: {export_job['status']}")
```
**Output:**
```
Export ID: exp_abc123
Status: processing
```
<Info>
**Export initiated:** Status is "processing". Large exports may take a few seconds. Poll with `get_memory_export()` until status changes to "completed" before downloading data.
</Info>
### Step 3: Download the export
```python
# Get by ID
export_data = client.get_memory_export(
memory_export_id=export_job['id']
)
print(export_data['data'])
```
**Output:**
```json
{
"full_name": "Dev",
"current_role": "senior engineer",
"company": "TechCorp"
}
```
You can also retrieve exports by filters:
```python
# Get latest export matching filters
export_by_filters = client.get_memory_export(
filters={"user_id": "dev"}
)
print(export_by_filters['data'])
```
---
## Adding Export Instructions
Guide how Mem0 resolves conflicts or formats the export:
```python
export_with_instructions = client.create_memory_export(
schema=professional_profile_schema,
filters={"user_id": "arjun"},
export_instructions="""
1. Use the most recent information if there are conflicts
2. Only include confirmed facts, not speculation
3. Return null for missing fields rather than guessing
"""
)
```
<Tip>
Always check export status before downloading. Call `get_memory_export()` in a loop with a short delay until `status == "completed"`. Attempting to download while still processing returns incomplete data.
</Tip>
---
## Platform Export
You can also export memories directly from the Mem0 platform UI:
1. Navigate to **Memory Exports** in your project dashboard
2. Click **Create Export**
3. Select your filters and schema
4. Download the completed export as JSON
This is useful for one-off exports or manual data reviews.
<Warning>
Exported data expires after 7 days. Download and store exports locally if you need long-term archives. After expiration, you'll need to recreate the export job.
</Warning>
---
## What You Built
A complete memory export system with multiple retrieval methods:
- **Bulk retrieval (get_all)** - Fetch all memories matching filters for comprehensive audits
- **Semantic search** - Query-based lookups with relevance scoring
- **Structured exports** - Pydantic-schema exports for migrations and compliance
- **Export instructions** - Guide conflict resolution and data formatting
- **Platform UI exports** - One-off manual downloads via dashboard
This covers data portability, GDPR compliance, system migrations, and manual reviews.
---
## Summary
Use **`get_all()`** for bulk retrieval, **`search()`** for specific questions, and **`create_memory_export()`** for structured data exports with custom schemas. Remember exports expire after 7 days—download them locally for long-term archives.
<CardGroup cols={2}>
<Card title="Expire Short-Term Data" icon="timer" href="/cookbooks/essentials/memory-expiration-short-and-long-term">
Keep exports lean by clearing session context before you archive it.
</Card>
<Card title="Control Memory Ingestion" icon="filter" href="/cookbooks/essentials/controlling-memory-ingestion">
Ensure only verified insights make it into your export pipeline.
</Card>
</CardGroup>
@@ -0,0 +1,277 @@
---
title: Set Memory Expiration
description: "Define short-term versus long-term retention so the store stays fresh."
---
While building memory systems, we realized their size grows fast. Session notes, temporary context, chat history - everything starts accumulating and bogging down the system. This pollutes search results and increase storage costs. Not every memory needs to persist forever.
In this cookbook, we'll go through how to use short-term vs long-term memories and see where it's best to use them.
---
## Overview
By default, Mem0 memories persist forever. This works for user preferences and core facts, but temporary data should expire automatically.
In this tutorial, we will:
- Understand default (permanent) memory behavior
- Add expiration dates for temporary memories
- Decide what should be temporary vs permanent
---
## Setup
```python
from mem0 import MemoryClient
from datetime import datetime, timedelta
client = MemoryClient(api_key="your-api-key")
```
<Note>
Import `datetime` and `timedelta` to calculate expiration dates. Without these imports, you'll need to manually format ISO timestamps—error-prone and harder to read.
</Note>
---
## Default Behavior: Everything Persists
By default, all memories persist forever:
```python
# Store user preference
client.add("User prefers dark mode", user_id="sarah")
# Store session context
client.add("Currently browsing electronics category", user_id="sarah")
# 6 months later - both still exist
results = client.get_all(filters={"user_id": "sarah"})
print(f"Total memories: {len(results['results'])}")
```
**Output:**
```
Total memories: 2
```
Both the preference and session context persist. The preference is useful, but the 6-month-old session context is not.
---
## The Problem: Memory Bloat
Without expiration, memories accumulate forever. Session notes from weeks ago mix with current preferences. Storage grows, search results get polluted with irrelevant old context, and retrieval quality degrades.
<Warning>
Memory bloat degrades search quality. When "User prefers dark mode" competes with "Currently browsing electronics" from 6 months ago, semantic search returns stale session data instead of actual preferences. Old memories pollute retrieval.
</Warning>
---
## Short-Term Memories: Adding Expiration
Set `expiration_date` to make memories temporary:
```python
from datetime import datetime, timedelta
# Session context - expires in 7 days
expires_at = (datetime.now() + timedelta(days=7)).isoformat()
client.add(
"Currently browsing electronics category",
user_id="sarah",
expiration_date=expires_at
)
# User preference - no expiration, persists forever
client.add(
"User prefers dark mode",
user_id="sarah"
)
```
<Info icon="check">
**Expected behavior:** After 7 days, the session context automatically disappears—no cron jobs, no manual cleanup. The preference persists forever. Mem0 handles expiration transparently.
</Info>
Memories with `expiration_date` are automatically removed after expiring. No cleanup job needed - Mem0 handles it.
<Tip>
Start conservative with short expiration windows (7 days), then extend them based on usage patterns. It's easier to increase retention than to clean up over-retained stale data. Monitor search quality to find the right balance.
</Tip>
---
## When to Use Each
### Permanent Memories (no expiration_date):
**Use for:**
- User preferences and settings
- Account information
- Important facts and milestones
- Historical data that matters long-term
```python
client.add("User prefers email notifications", user_id="sarah")
client.add("User's birthday is March 15th", user_id="sarah")
client.add("User completed onboarding on Jan 5th", user_id="sarah")
```
### Temporary Memories (with expiration_date):
**Use for:**
- Session context (current page, browsing history)
- Temporary reminders
- Recent chat history
- Cached data
```python
expires_7d = (datetime.now() + timedelta(days=7)).isoformat()
client.add(
"Currently viewing product ABC123",
user_id="sarah",
expiration_date=expires_7d
)
client.add(
"Asked about return policy",
user_id="sarah",
expiration_date=expires_7d
)
```
---
## Setting Different Expiration Periods
Different data needs different lifetimes:
```python
# Session context - 7 days
expires_7d = (datetime.now() + timedelta(days=7)).isoformat()
client.add("Browsing electronics", user_id="sarah", expiration_date=expires_7d)
# Recent chat - 30 days
expires_30d = (datetime.now() + timedelta(days=30)).isoformat()
client.add("User asked about warranty", user_id="sarah", expiration_date=expires_30d)
# Important preference - no expiration
client.add("User prefers dark mode", user_id="sarah")
```
---
## Using Metadata to Track Memory Types
Tag memories to make filtering easier:
```python
expires_7d = (datetime.now() + timedelta(days=7)).isoformat()
# Tag session context
client.add(
"Browsing electronics",
user_id="sarah",
expiration_date=expires_7d,
metadata={"type": "session"}
)
# Tag preference
client.add(
"User prefers dark mode",
user_id="sarah",
metadata={"type": "preference"}
)
# Query only preferences
preferences = client.get_all(
filters={
"AND": [
{"user_id": "sarah"},
{"metadata": {"type": "preference"}}
]
}
)
```
---
## Checking Expiration Status
See which memories will expire and when:
```python
results = client.get_all(filters={"user_id": "sarah"})
for memory in results['results']:
exp_date = memory.get('expiration_date')
if exp_date:
print(f"Temporary: {memory['memory']}")
print(f" Expires: {exp_date}\\n")
else:
print(f"Permanent: {memory['memory']}\\n")
```
**Output:**
```
Temporary: Browsing electronics
Expires: 2025-11-01T10:30:00Z
Temporary: Viewed MacBook Pro and Dell XPS
Expires: 2025-11-01T10:30:00Z
Permanent: User prefers dark mode
Permanent: User prefers email notifications
```
---
## What You Built
A self-cleaning memory system with automatic retention policies:
- **Automatic expiration** - Memories self-destruct after defined periods, no cron jobs needed
- **Tiered retention** - 7-day session context, 30-day chat history, permanent preferences
- **Metadata tagging** - Classify memories by type (session, preference, chat) for filtered retrieval
- **Expiration tracking** - Check which memories will expire and when using `get_all()`
This pattern keeps storage costs low and search quality high as your memory store scales.
---
## Summary
Memory expiration keeps storage clean and search results relevant. Use **`expiration_date`** for temporary data (session context, recent chats), skip it for permanent facts (preferences, account info). Mem0 handles cleanup automatically—no background jobs required.
Start by identifying what's temporary versus permanent, then set conservative expiration windows and adjust based on retrieval quality.
<CardGroup cols={2}>
<Card title="Control Memory Ingestion" icon="filter" href="/cookbooks/essentials/controlling-memory-ingestion">
Pair expirations with ingestion rules so only trusted context persists.
</Card>
<Card title="Export Memories Safely" icon="download" href="/cookbooks/essentials/exporting-memories">
Build compliant archives once your retention windows are dialed in.
</Card>
</CardGroup>
@@ -0,0 +1,251 @@
---
title: Tag and Organize Memories
description: "Let Mem0 auto-categorize support data so teams retrieve the right facts fast."
---
When you have large volumes of memory data, sorting it during post-processing becomes difficult. What if your memory store understood the importance of creating tags and buckets without a lot of effort?
Mem0 handles this for you by providing the flexibility to organize memories with custom categories. This cookbook shows you how to tag and organize memories for a customer support platform.
---
## Setup
```python
from mem0 import MemoryClient
client = MemoryClient(api_key="your-api-key")
```
<Note>
Define custom categories at the **project level** with `client.project.update()` before adding memories. Categories apply to all future memories—Mem0 auto-assigns them based on content semantics.
</Note>
---
## The Problem
Without categories, all memories sit in one undifferentiated bucket. Support agents waste time searching through everything to find billing issues, account details, or past tickets.
Let's see what happens without organization:
```python
# Joseph (support agent) stores various customer interactions
client.add(
"Maria called about her account password reset",
user_id="maria",
)
client.add(
"Maria was charged twice for last month's subscription",
user_id="maria",
)
client.add(
"Maria wants to upgrade to the premium plan",
user_id="maria",
)
# Now try to find just billing issues
all_memories = client.get_all(filters={"user_id": "maria"})
print(f"Total memories: {len(all_memories['results'])}")
for memory in all_memories['results']:
print(f"- {memory['memory']}")
```
**Output:**
```
Total memories: 3
- Maria called about her account password reset
- Maria was charged twice for last month's subscription
- Maria wants to upgrade to the premium plan
```
<Warning>
Without categories, agents waste time reading through everything. For a customer with 100 memories, finding one billing issue means scanning all 100. Categories let you filter to exactly what you need—billing issues only, no password resets or feedback mixed in.
</Warning>
Everything is mixed together. Support agents have to read through all memories to find what they need.
---
## Custom Categories
Define categories that match how your support team thinks about customer issues:
```python
custom_categories = [
{"support_tickets": "Customer issues and resolutions"},
{"account_info": "Account details and preferences"},
{"billing": "Payment history and billing questions"},
{"product_feedback": "Feature requests and feedback"},
]
client.project.update(custom_categories=custom_categories)
```
<Tip>
Start with 3-5 clear categories that match how your team thinks. Too many categories dilute auto-tagging accuracy. Add more later if needed—it's easier to expand than to fix over-complicated classification.
</Tip>
These categories are now available project-wide. Every memory can be tagged with one or more categories.
---
## Tagging Memories
Once categories are defined at the project level, Mem0 automatically assigns them based on content:
```python
# Billing issue - automatically tagged as "billing"
client.add(
"Maria was charged twice for last month's subscription",
user_id="maria",
metadata={"priority": "high", "source": "phone_call"}
)
# Account update - automatically tagged as "account_info"
client.add(
"Maria changed her email to maria.new@example.com",
user_id="maria",
metadata={"source": "web_portal"}
)
# Product feedback - automatically tagged as "product_feedback"
client.add(
"Maria requested a dark mode feature for the dashboard",
user_id="maria",
metadata={"source": "chat"}
)
```
Mem0 reads the content and intelligently assigns the appropriate categories. You don't manually tag - the platform does it for you based on the category definitions.
---
## Retrieving by Category
Filter memories by category to find exactly what you need:
```python
# Joseph needs to pull all billing issues for audit
billing_issues = client.get_all(
filters={
"AND": [
{"user_id": "maria"},
{"categories": {"in": ["billing"]}}
]
}
)
print("Billing issues:")
for memory in billing_issues['results']:
print(f"- {memory['memory']}")
```
**Output:**
```
Billing issues:
- Maria was charged twice for last month's subscription
```
<Info icon="check">
**Expected output:** Only the billing issue returned—no password reset, no upgrade request. Category filtering worked. Joseph can audit billing without reading through unrelated support tickets.
</Info>
Only billing-related memories are returned. No need to filter through account updates or feedback.
You can also retrieve multiple categories:
```python
# Get both account info and billing
account_and_billing = client.get_all(
filters={
"AND": [
{"user_id": "maria"},
{"categories": {"in": ["account_info", "billing"]}}
]
}
)
for memory in account_and_billing['results']:
print(f"[{memory['categories'][0]}] {memory['memory']}")
```
**Output:**
```
[account_info] Maria changed her email to maria.new@example.com
[billing] Maria was charged twice for last month's subscription
```
---
## Updating Categories
Categories are automatically assigned based on content. To trigger re-categorization, update the memory content:
```python
# Find memories that need re-categorization
needs_update = client.get_all(
filters={
"AND": [
{"user_id": "maria"},
{"categories": {"in": ["misc"]}}
]
}
)
# Update memory content to trigger re-categorization
for memory in needs_update['results']:
client.update(
memory_id=memory['id'],
data=memory['memory'] # Re-process with current category definitions
)
```
When you update a memory, Mem0 re-analyzes it against your current category definitions. This is useful when you introduce new categories or refine category descriptions.
---
## What You Built
A customer support platform with intelligent memory organization:
- **Project-wide categories** - Support tickets, billing, account info, and product feedback auto-classified
- **Automatic tagging** - Mem0 assigns categories based on content semantics, no manual tagging
- **Filtered retrieval** - Pull only billing issues or only account updates using `categories: {in: [...]}`
- **Re-categorization** - Update memory content to trigger re-analysis against new category definitions
- **Multi-category support** - Memories can belong to multiple categories when appropriate
This pattern scales from 10 customers to 10,000 without degrading retrieval speed.
---
## Summary
Categories make retrieval faster and compliance easier. Define 3-5 clear categories with `client.project.update()`, let Mem0 auto-assign them based on content, then filter with `categories: {in: [...]}` to pull exactly what you need.
Instead of searching through everything, agents jump directly to the information type they need—billing issues, account details, or support tickets.
<CardGroup cols={2}>
<Card title="Control Memory Ingestion" icon="filter" href="/cookbooks/essentials/controlling-memory-ingestion">
Keep categories meaningful by filtering noise before it lands in storage.
</Card>
<Card title="Export Tagged Memories" icon="download" href="/cookbooks/essentials/exporting-memories">
Use categories to drive audits, migrations, and compliance reports.
</Card>
</CardGroup>
@@ -1,4 +1,8 @@
# Mem0 Chrome Extension
---
title: Browser Extension Memory
description: "Add Mem0's universal memory layer to Chrome chat surfaces."
---
Enhance your AI interactions with Mem0, a Chrome extension that introduces a universal memory layer across platforms like ChatGPT, Claude, and Perplexity. Mem0 ensures seamless context sharing, making your AI experiences more personalized and efficient.
@@ -53,3 +57,14 @@ You can install the Mem0 Chrome Extension using one of the following methods:
## Privacy and Data Security
Your messages are sent to the Mem0 API for extracting and retrieving memories. Mem0 is committed to ensuring your data's privacy and security.
---
<CardGroup cols={2}>
<Card title="Build a Mem0 Companion" icon="users" href="/cookbooks/essentials/building-ai-companion">
Learn the foundations of memory-powered assistants that work across platforms.
</Card>
<Card title="Multimodal Support" icon="image" href="/platform/features/multimodal-support">
Extend your browser interactions with vision and audio memory.
</Card>
</CardGroup>
@@ -1,7 +1,9 @@
---
title: Eliza OS Character
title: Persistent Eliza Characters
description: "Bring persistent personality to Eliza OS agents using Mem0."
---
You can create a personalized Eliza OS Character using Mem0. This guide will walk you through the necessary steps and provide the complete code to get you started.
## Overview
@@ -70,3 +72,14 @@ pnpm start
You have now created a personalized Eliza OS Character using Mem0. You can now start interacting with the character by running the project and talking to the character.
This is a simple example of how to use Mem0 to create a personalized AI agent. You can use this as a starting point to create your own AI agent.
---
<CardGroup cols={2}>
<Card title="Partition Memories by Entity" icon="layers" href="/cookbooks/essentials/entity-partitioning-playbook">
Keep character personas isolated by tagging user, agent, and session identifiers.
</Card>
<Card title="AI Tutor with Mem0" icon="graduation-cap" href="/cookbooks/companions/ai-tutor">
Build another type of personalized companion with memory capabilities.
</Card>
</CardGroup>
@@ -0,0 +1,246 @@
---
title: "Gemini 3 with Mem0 MCP"
description: "Create snappy, smart, memory-aware agents by pairing Gemini 3 with Mem0 MCP server."
---
Gemini 3, when paired with mem0-mcp-server, works in synergy to create snappy, smart, memory-aware agents.
<Callout type="info" icon="sparkles" color="#8B5CF6">
This is the primary example of MCP integration - the same patterns work with Claude Desktop, Cursor, or any MCP-compatible client.
</Callout>
## MCP Server Tools
The Mem0 MCP server provides these tools to Gemini:
| Tool | Description |
| --------------------- | ---------------------------------------- |
| `add_memory` | Store new information in memory |
| `search_memories` | Find relevant memories |
| `get_memories` | Retrieve specific memories by ID |
| `get_memory` | Retrieve one memory by its `memory_id` |
| `update_memory` | Modify existing memory content |
| `delete_memory` | Remove specific memories |
| `delete_all_memories` | Clear all memories for a user |
| `delete_entities` | Delete all memories related to an entity |
| `list_entities` | Enumerate users/agents/apps/runs stored |
## Setup
### Install dependencies
```bash
pip install pydantic-ai nest-asyncio python-dotenv uv google-genai
```
### Environment Setup
Create a file named `.env`:
```bash
MEM0_API_KEY=m0-xxxxxxxxxxxxxxxxx
GEMINI_API_KEY=your-gemini-api-key-here
MEM0_DEFAULT_USER_ID=demo-user
```
<Note>
Ensure you have your Mem0 API key from the [Mem0 Dashboard](https://app.mem0.ai) and your Gemini API key from the [Google AI Studio](https://ai.studio/app/api-keys).
</Note>
## Gemini Memory Agent
This example shows how to create a memory-augmented agent using Gemini 3 through an agent loop.
<Info icon="document">
Save this as <strong>gemini_agent.py</strong>:
</Info>
```python
import asyncio
import os
from dotenv import load_dotenv
from pydantic_ai import Agent
from pydantic_ai.mcp import MCPServerStdio
# Load environment variables
load_dotenv()
class MemoryAgent:
def __init__(self, model="gemini-3-pro-preview"):
self.agent = None
self.server = None
self.model = model
self._setup()
def _setup(self):
"""Initialize the agent with MCP tools"""
# Create MCP server directly
self.server = MCPServerStdio(
command="uvx",
args=["mem0-mcp-server"],
env=os.environ
)
# Create agent with Gemini and memory tools
self.agent = Agent(
f"google-gla:{self.model}",
toolsets=[self.server],
system_prompt=(
"You are an assistant with memory capabilities. "
"Automatically remember important details about users, "
"preferences, and facts. Search memories before answering "
"questions about past information."
),
)
print(f"Agent initialized with {self.model}")
async def chat(self, message):
"""Send message and get response"""
async with self.server:
result = await self.agent.run(message)
return result.output
async def interactive_chat(self):
"""Run interactive chat session"""
print("\nMemory Agent Ready! (Type 'quit' to exit)")
while True:
try:
user_input = input("\nYou: ").strip()
if user_input.lower() in ["quit", "exit"]:
print("Goodbye!")
break
if not user_input:
continue
response = await self.chat(user_input)
print(f"\nAgent: {response}")
except KeyboardInterrupt:
print("\nGoodbye!")
break
except Exception as e:
print(f"\nError: {e}")
async def main():
"""Main entry point"""
agent = MemoryAgent()
await agent.interactive_chat()
if __name__ == "__main__":
asyncio.run(main())
```
## Running the Agent
To run the interactive agent:
```bash
python gemini_agent.py
```
## Example Interactions
### Multi-Tool Capabilities
*Shows Gemini generating synthetic data while simultaneously storing and searching in one request*
**Prompt:**
```
I need player statistics for a basketball team dashboard demo. Generate 5 synthetic player profiles with different positions, ages, and performance metrics, then store all of them. Also check if we have any existing player data in memory.
```
**Response:**
```
I've created and stored 5 synthetic player profiles for your basketball team dashboard demo:
- Marcus Chen (32, Point Guard) - 12.5 PPG, 8.2 APG, 45% FG, 3 seasons with team
- Jamal Williams (28, Center) - 18.7 PPG, 10.5 RPG, 2.3 BPG, rookie season
- Carlos Rodriguez (35, Small Forward) - 15.3 PPG, 6.8 RPG, 38% 3PT, team captain
- Tito Kawaguchi (24, Shooting Guard) - 22.1 PPG, 4.1 APG, 42% 3PT, 6th man of the year candidate
- Viktor Petrov (30, Power Forward) - 14.8 PPG, 9.2 RPG, 52% FG, defensive specialist
I searched for existing player data in your memory but found none. All synthetic player profiles have been stored with appropriate basketball statistics for demo purposes.
```
### Smart Query Generation
*Demonstrates how Gemini transforms vague human input into optimal search queries*
**Prompt:**
```
Anything about my health I should know about?
```
**Response:**
```
Based on your memory history, I searched for health-related information using these queries: "medical", "allergies", "dietary restrictions", "exercise", "wellness", "doctor visits", "health conditions".
**Health Information Found:**
- Allergies: Shellfish allergy
- Dietary preferences: Weekday vegetarian, flexible weekends, dislikes kiwi
- Exercise routine: 5km runs on weekday mornings
- Diet: Oat milk cappuccino with one sugar (monitoring sugar intake recommended)
I don't see any medical conditions or recent doctor visits in your stored information.
```
### Memory Attribution
*Shows how Gemini distinguishes between stored memories and general knowledge*
**Prompt:**
```
What's my coffee order again?
```
**Response:**
```
Based on your stored memories, your coffee order is an oat milk cappuccino with one sugar.
This information was retrieved from your memory history where you previously mentioned this preference. I don't have any information about whether you've changed this preference recently.
```
## Why Use Gemini with Mem0 MCP?
### How Mem0 Enhances Your Application
- **Smart Memory Management** - Organizes memories into searchable information *without setting up vector databases*
- **Fast Retrieval** - Instant lookups with *sub-millisecond ping*, handles large datasets
- **Graph Capabilities** - Builds knowledge *automatically* as you push information
- **Simple Integration** - Uses Mem0 API in the backend, works with *any MCP client* with just a few lines of code
### Gemini 3 + Mem0 Benefits
- **Native function calling**: Built-in support for Mem0's memory tools
- **Large context window**: Supports up to 1M tokens for extensive memory context
- **Parallel execution**: Can call multiple memory tools simultaneously
- **Cost-effective**: Competitive pricing for memory-intensive applications
## What You Built
- **Memory-augmented AI agent** - Gemini with persistent memory across sessions
- **Automatic context management** - Agent automatically stores and retrieves relevant information
- **Multi-tool parallel execution** - Simultaneous memory operations for efficiency
- **Natural memory interface** - Users interact normally while agent manages memory behind the scenes
## Conclusion
You've successfully built a Gemini 3 agent with persistent memory using Mem0's MCP server. The agent can now remember user preferences, maintain context across sessions, and provide more personalized interactions.
## Next Steps
<CardGroup cols={2}>
<Card
title="MCP Integration Feature"
description="Learn about MCP configuration options and deployment methods"
icon="plug"
href="/platform/features/mcp-integration"
/>
<Card
title="MCP Quickstart"
description="Get started with MCP for any AI client in minutes"
icon="rocket"
href="/platform/mem0-mcp"
/>
</CardGroup>
@@ -1,7 +1,9 @@
---
title: LlamaIndex Multi-Agent Learning System
title: Multi-Agent Collaboration
description: "Share a persistent memory layer across collaborating LlamaIndex agents."
---
<Snippet file="blank-notif.mdx" />
Build an intelligent multi-agent learning system that uses Mem0 to maintain persistent memory across multiple specialized agents. This example demonstrates how to create a tutoring system where different agents collaborate while sharing a unified memory layer.
@@ -357,4 +359,13 @@ Based on our previous session, I remember we covered Vision Language Models and
- [LlamaIndex Agent Workflows](https://docs.llamaindex.ai/en/stable/use_cases/agents/)
- [Mem0 Platform](https://app.mem0.ai/)
<Snippet file="get-help.mdx" />
---
<CardGroup cols={2}>
<Card title="LlamaIndex ReAct with Mem0" icon="brain" href="/cookbooks/frameworks/llamaindex-react">
Start with single-agent patterns before scaling to multi-agent systems.
</Card>
<Card title="Partition Memories by Entity" icon="layers" href="/cookbooks/essentials/entity-partitioning-playbook">
Learn how to scope memories across multiple agents, users, and sessions.
</Card>
</CardGroup>
@@ -1,7 +1,9 @@
---
title: LlamaIndex ReAct Agent
title: ReAct Agents with Memory
description: "Teach a ReAct agent to store and recall context via Mem0."
---
Create a ReAct Agent with LlamaIndex which uses Mem0 as the memory store.
## Overview
@@ -184,3 +186,14 @@ I've ordered a pizza for you, and the bill has been sent to your email. Enjoy yo
```
<Note>The agent is able to remember the past preferences the user shared and use them to perform actions.</Note>
---
<CardGroup cols={2}>
<Card title="LlamaIndex Multiagent with Mem0" icon="users" href="/cookbooks/frameworks/llamaindex-multiagent">
Scale to multi-agent workflows with shared memory coordination.
</Card>
<Card title="Build a Mem0 Companion" icon="users" href="/cookbooks/essentials/building-ai-companion">
Master the core patterns for memory-powered agents across frameworks.
</Card>
</CardGroup>
@@ -1,7 +1,9 @@
---
title: Multimodal Demo with Mem0
title: Visual Memory Retrieval
description: "Store and recall visual context alongside text conversations."
---
Enhance your AI interactions with Mem0's multimodal capabilities. Mem0 now supports image understanding, allowing for richer context and more natural interactions across supported AI platforms.
> Experience the power of multimodal AI! Test out Mem0's image understanding capabilities at [multimodal-demo.mem0.ai](https://multimodal-demo.mem0.ai)
@@ -29,3 +31,13 @@ Enhance your AI interactions with Mem0's multimodal capabilities. Mem0 now suppo
Visit [multimodal-demo.mem0.ai](https://multimodal-demo.mem0.ai) to experience Mem0's multimodal capabilities firsthand. Upload images and see how Mem0 understands and remembers visual context across your conversations.
---
<CardGroup cols={2}>
<Card title="Multimodal Support" icon="image" href="/platform/features/multimodal-support">
Learn how to store and retrieve vision and audio memories in your apps.
</Card>
<Card title="Voice Companion with OpenAI" icon="microphone" href="/cookbooks/companions/voice-companion-openai">
Build voice-first companions that remember conversations.
</Card>
</CardGroup>
@@ -1,5 +1,6 @@
---
title: Mem0 as an Agentic Tool
title: Memory-Powered Agent SDK
description: "Expose Mem0 memories as callable tools inside OpenAI agent workflows."
---
@@ -125,7 +126,7 @@ async def get_all_memory(
) -> str:
"""Retrieve all memories from Mem0"""
user_id = context.context.user_id or "default_user"
memories = await client.get_all(user_id=user_id)
memories = await client.get_all(filters={"AND": [{"user_id": user_id}]})
results = '\n'.join([result["memory"] for result in memories["results"]])
return str(results)
```
@@ -224,3 +225,14 @@ context = Mem0Context(user_id="user123")
- [Mem0 Documentation](https://docs.mem0.ai)
- [Mem0 Dashboard](https://app.mem0.ai/dashboard)
- [API Reference](https://docs.mem0.ai/api-reference)
---
<CardGroup cols={2}>
<Card title="OpenAI Tool Calls with Mem0" icon="wrench" href="/cookbooks/integrations/openai-tool-calls">
Extend OpenAI assistants with tool-based memory operations.
</Card>
<Card title="Build a Mem0 Companion" icon="users" href="/cookbooks/essentials/building-ai-companion">
Learn the core patterns for memory-powered agents with any SDK.
</Card>
</CardGroup>
@@ -1,7 +1,9 @@
---
title: "AWS Bedrock Example"
title: Bedrock with Persistent Memory
description: "Pair Mem0 with AWS Bedrock, OpenSearch, and Neptune for a managed stack."
---
This example demonstrates how to configure and use the `mem0ai` SDK with **AWS Bedrock**, **OpenSearch Service (AOSS)**, and **AWS Neptune Analytics** for persistent memory capabilities in Python.
## Installation
@@ -36,7 +38,7 @@ This sets up Mem0 with:
- [AWS Bedrock for LLM](https://docs.mem0.ai/components/llms/models/aws_bedrock)
- [AWS Bedrock for embeddings](https://docs.mem0.ai/components/embedders/models/aws_bedrock#aws-bedrock)
- [OpenSearch as the vector store](https://docs.mem0.ai/components/vectordbs/dbs/opensearch)
- [Neptune Analytics as your graph store](https://docs.mem0.ai/open-source/graph_memory/overview#initialize-neptune-analytics)
- [Graph Memory guide](https://docs.mem0.ai/open-source/features/graph-memory)
```python
import boto3
@@ -128,3 +130,14 @@ memory = m.get(memory_id)
## Conclusion
With Mem0 and AWS services like Bedrock, OpenSearch, and Neptune Analytics, you can build intelligent AI companions that remember, adapt, and personalize their responses over time. This makes them ideal for long-term assistants, tutors, or support bots with persistent memory and natural conversation abilities.
---
<CardGroup cols={2}>
<Card title="Neptune Analytics with Mem0" icon="database" href="/cookbooks/integrations/neptune-analytics">
Explore graph-based memory storage with AWS Neptune Analytics.
</Card>
<Card title="Graph Memory Features" icon="sitemap" href="/platform/features/graph-memory">
Learn how to leverage knowledge graphs for entity relationships.
</Card>
</CardGroup>
@@ -1,11 +1,9 @@
---
title: 'Healthcare Assistant with Mem0 and Google ADK'
description: 'Build a personalized healthcare agent that remembers patient information across conversations using Mem0 and Google ADK'
title: Healthcare Coach with ADK
description: "Guide patients with an assistant that remembers history across ADK sessions."
---
## Healthcare Assistant with Memory
This example demonstrates how to build a healthcare assistant that remembers patient information across conversations using Google ADK and Mem0.
## Overview
@@ -290,3 +288,14 @@ The `threshold` parameter in the search function ensures that only highly releva
This example demonstrates how to build a healthcare assistant with persistent memory using Google ADK and Mem0. The integration allows for a more personalized patient experience by maintaining context across conversation turns, which is particularly valuable in healthcare scenarios where continuity of information is crucial.
By storing and retrieving patient information intelligently, the assistant provides more relevant responses without requiring the patient to repeat their medical history, symptoms, or preferences.
---
<CardGroup cols={2}>
<Card title="Tag and Organize Memories" icon="tag" href="/cookbooks/essentials/tagging-and-organizing-memories">
Categorize patient data by symptoms, history, and visit context.
</Card>
<Card title="Support Inbox with Mem0" icon="headset" href="/cookbooks/operations/support-inbox">
Apply similar memory patterns to customer support workflows.
</Card>
</CardGroup>
@@ -1,7 +1,9 @@
---
title: Mem0 with Mastra
title: Persistent Mastra Agents
description: "Extend Mastra agents with persistent memories powered by Mem0."
---
In this example you'll learn how to use Mem0 to add long-term memory capabilities to [Mastra's agent](https://mastra.ai/) via tool-use. This memory integration can work alongside Mastra's [agent memory features](https://mastra.ai/docs/agents/01-agent-memory).
You can find the complete example code in the [Mastra repository](https://github.com/mastra-ai/mastra/tree/main/examples/memory-with-mem0).
@@ -122,4 +124,15 @@ export const mastra = new Mastra({
In the example above:
- We import the `@mastra/mem0` integration
- We define two tools that use the Mem0 API client to create new memories and recall previously saved memories
- The tool accepts `question` as an input and returns the memory as a string
- The tool accepts `question` as an input and returns the memory as a string
---
<CardGroup cols={2}>
<Card title="Partition Memories by Entity" icon="layers" href="/cookbooks/essentials/entity-partitioning-playbook">
Separate user, agent, and app memories to keep multi-agent flows clean.
</Card>
<Card title="Agents SDK Tool with Mem0" icon="robot" href="/cookbooks/integrations/agents-sdk-tool">
Explore tool-calling patterns with the OpenAI Agents SDK.
</Card>
</CardGroup>
@@ -1,7 +1,9 @@
---
title: "AWS Neptune Analytics"
title: Graph Memory on Neptune
description: "Combine Mem0 graph memory with AWS Neptune Analytics and Bedrock."
---
This example demonstrates how to configure and use the `mem0ai` SDK with **AWS Bedrock** and **AWS Neptune Analytics** for persistent memory capabilities in Python.
## Installation
@@ -36,7 +38,7 @@ This sets up Mem0 with:
- [AWS Bedrock for LLM](https://docs.mem0.ai/components/llms/models/aws_bedrock)
- [AWS Bedrock for embeddings](https://docs.mem0.ai/components/embedders/models/aws_bedrock#aws-bedrock)
- [Neptune Analytics as the vector store](https://docs.mem0.ai/components/vectordbs/dbs/neptune_analytics)
- [Neptune Analytics as the graph store](https://docs.mem0.ai/open-source/graph_memory/overview#initialize-neptune-analytics).
- [Graph Memory guide](https://docs.mem0.ai/open-source/features/graph-memory).
```python
import boto3
@@ -118,3 +120,14 @@ memory = m.get(memory_id)
## Conclusion
With Mem0 and AWS services like Bedrock and Neptune Analytics, you can build intelligent AI companions that remember, adapt, and personalize their responses over time. This makes them ideal for long-term assistants, tutors, or support bots with persistent memory and natural conversation abilities.
---
<CardGroup cols={2}>
<Card title="AWS Bedrock with Mem0" icon="aws" href="/cookbooks/integrations/aws-bedrock">
Combine Neptune Analytics with AWS Bedrock for complete AWS stack.
</Card>
<Card title="Graph Memory Architecture" icon="sitemap" href="/cookbooks/essentials/choosing-memory-architecture-vector-vs-graph">
Understand when to use graph vs vector memory for your use case.
</Card>
</CardGroup>
@@ -1,7 +1,9 @@
---
title: OpenAI Inbuilt Tools
title: Memory as OpenAI Tool
description: "Wire Mem0 memories into OpenAI's inbuilt function-calling flow."
---
Integrate Mem0’s memory capabilities with OpenAI’s Inbuilt Tools to create AI agents with persistent memory.
## Getting Started
@@ -309,4 +311,15 @@ run().catch(console.error);
- [Mem0 Documentation](https://docs.mem0.ai)
- [Mem0 Dashboard](https://app.mem0.ai/dashboard)
- [API Reference](https://docs.mem0.ai/api-reference)
- [OpenAI Documentation](https://platform.openai.com/docs)
- [OpenAI Documentation](https://platform.openai.com/docs)
---
<CardGroup cols={2}>
<Card title="Agents SDK Tool with Mem0" icon="robot" href="/cookbooks/integrations/agents-sdk-tool">
Extend the OpenAI Agents SDK with Mem0 integration capabilities.
</Card>
<Card title="Control Memory Ingestion" icon="filter" href="/cookbooks/essentials/controlling-memory-ingestion">
Fine-tune what memories get stored during tool calls.
</Card>
</CardGroup>
@@ -1,7 +1,9 @@
---
title: 'Personalized Search with Tavily'
title: Search with Personal Context
description: "Blend Tavily's realtime results with personal context stored in Mem0."
---
<Snippet file="security-compliance.mdx" />
Imagine asking a search assistant for "coffee shops nearby" and instead of generic results, it shows remote-work-friendly cafes with great WiFi in your city because it remembers you mentioned working remotely before. Or when you search for "lunchbox ideas for kids" it knows you have a 7-year-old daughter and recommends peanut-free options that align with her allergy.
@@ -190,4 +192,15 @@ With Mem0 and Tavily, you can build a search assistant that doesn't just fetch r
Whether for shopping, travel, or daily life, this approach turns a generic search into a truly personalized experience.
Full Code: [Personalized Search GitHub](https://github.com/mem0ai/mem0/blob/main/examples/misc/personalized_search.py)
Full Code: [Personalized Search GitHub](https://github.com/mem0ai/mem0/blob/main/examples/misc/personalized_search.py)
---
<CardGroup cols={2}>
<Card title="Deep Research with Mem0" icon="magnifying-glass" href="/cookbooks/operations/deep-research">
Build comprehensive research agents that remember findings across sessions.
</Card>
<Card title="Tag and Organize Memories" icon="tag" href="/cookbooks/essentials/tagging-and-organizing-memories">
Categorize search results and user preferences for better personalization.
</Card>
</CardGroup>
@@ -1,7 +1,9 @@
---
title: Memory-Guided Content Writing
title: Content Creation Workflow
description: "Store voice guidelines once and apply them across every draft."
---
This guide demonstrates how to leverage **Mem0** to streamline content writing by applying your unique writing style and preferences using persistent memory.
## Why Use Mem0?
@@ -207,8 +209,13 @@ We believe this strategy will effectively increase our market share. To achieve
Mem0 enables a seamless, intelligent content-writing workflow, perfect for content creators, marketers, and technical writers looking to scale their personal tone and structure across work.
## Help & Resources
---
- [Mem0 Platform](https://app.mem0.ai/)
<Snippet file="get-help.mdx" />
<CardGroup cols={2}>
<Card title="Control Memory Ingestion" icon="filter" href="/cookbooks/essentials/controlling-memory-ingestion">
Filter and curate content examples to maintain consistent writing style.
</Card>
<Card title="Email Automation with Mem0" icon="envelope" href="/cookbooks/operations/email-automation">
Automate email drafting with memory-powered context and tone matching.
</Card>
</CardGroup>
@@ -1,7 +1,9 @@
---
title: Personalized Deep Research
title: Multi-Session Research Agent
description: "Run multi-session investigations that remember past findings and preferences."
---
Deep Research is an intelligent agent that synthesizes large amounts of online data and completes complex research tasks, customized to your unique preferences and insights. Built on Mem0's technology, it enhances AI-driven online exploration with personalized memories.
You can check out the GitHub repository here: [Personalized Deep Research](https://github.com/mem0ai/personalized-deep-research/tree/mem0)
@@ -64,3 +66,14 @@ Watch Deep Research in action:
> To try it yourself, clone the repository and follow the instructions in the README to run it locally or deploy it.
- [Personalized Deep Research GitHub](https://github.com/mem0ai/personalized-deep-research/tree/mem0)
---
<CardGroup cols={2}>
<Card title="Search Memory Operations" icon="magnifying-glass" href="/core-concepts/memory-operations/search">
Master semantic search to retrieve research findings across sessions.
</Card>
<Card title="YouTube Research with Mem0" icon="video" href="/cookbooks/companions/youtube-research">
Build a video research assistant that remembers insights from content.
</Card>
</CardGroup>
@@ -1,7 +1,9 @@
---
title: Email Processing with Mem0
title: Automated Email Intelligence
description: "Capture, categorize, and recall inbox threads using persistent memories."
---
This guide demonstrates how to build an intelligent email processing system using Mem0's memory capabilities. You'll learn how to store, categorize, retrieve, and analyze emails to create a smart email management solution.
## Overview
@@ -194,3 +196,13 @@ print(f"Found {len(meeting_emails['results'])} relevant emails")
By combining Mem0's memory capabilities with email processing, you can create intelligent email management systems that help users organize, prioritize, and act on their inbox effectively. The advanced capabilities like automatic categorization, action item extraction, and priority management can significantly reduce the time spent on email management, allowing users to focus on more important tasks.
---
<CardGroup cols={2}>
<Card title="Tag and Organize Memories" icon="tag" href="/cookbooks/essentials/tagging-and-organizing-memories">
Categorize email threads by sender, topic, and priority for faster retrieval.
</Card>
<Card title="Support Inbox with Mem0" icon="headset" href="/cookbooks/operations/support-inbox">
Build customer support agents that remember context across tickets.
</Card>
</CardGroup>
@@ -1,5 +1,6 @@
---
title: Customer Support AI Agent
title: Memory-Powered Support Agent
description: "Build a support assistant that keeps past tickets and resolutions at its fingertips."
---
@@ -108,4 +109,15 @@ for m in memories['results']:
### Conclusion
As the conversation progresses, Mem0's memory automatically updates based on the interactions, providing a continuously improving personalized support experience.
As the conversation progresses, Mem0's memory automatically updates based on the interactions, providing a continuously improving personalized support experience.
---
<CardGroup cols={2}>
<Card title="Build a Mem0 Companion" icon="users" href="/cookbooks/essentials/building-ai-companion">
Master the foundational patterns for building memory-powered assistants.
</Card>
<Card title="Email Automation with Mem0" icon="envelope" href="/cookbooks/operations/email-automation">
Extend support capabilities with intelligent email processing and routing.
</Card>
</CardGroup>
@@ -1,7 +1,9 @@
---
title: Multi-User Collaboration with Mem0
title: Collaborative Task Assistant
description: "Coordinate multi-user projects with shared memories and roles."
---
## Overview
Build a multi-user collaborative chat or task management system with Mem0. Each message is attributed to its author, and all messages are stored in a shared project space. Mem0 makes it easy to track contributions, sort and group messages, and collaborate in real time.
@@ -121,3 +123,14 @@ agent.print_grouped_by_actor()
## Conclusion
Mem0 enables fast, transparent collaboration for teams and agents, with full attribution, flexible memory search, and easy message organization.
---
<CardGroup cols={2}>
<Card title="Partition Memories by Entity" icon="layers" href="/cookbooks/essentials/entity-partitioning-playbook">
Learn how to scope memories across users, agents, and runs for team workflows.
</Card>
<Card title="Support Inbox with Mem0" icon="headset" href="/cookbooks/operations/support-inbox">
Apply collaborative memory patterns to customer support scenarios.
</Card>
</CardGroup>
+228
View File
@@ -0,0 +1,228 @@
---
title: Overview
description: How to use mem0 in your existing applications?
---
With Mem0, you can create stateful LLM-based applications such as chatbots, virtual assistants, or AI agents. Mem0 enhances your applications by providing a memory layer that makes responses:
- More personalized
- More reliable
- Cost-effective by reducing the number of LLM interactions
- More engaging
- Enables long-term memory
Here are some examples of how Mem0 can be integrated into various applications:
## Essentials
<CardGroup cols={2}>
<Card
title="Build a Companion with Mem0"
icon="users"
href="/cookbooks/essentials/building-ai-companion"
>
Learn core memory lifecycle patterns.
</Card>
<Card
title="Partition Memories by Entity"
icon="server"
href="/cookbooks/essentials/entity-partitioning-playbook"
>
Balance personalization with consistent behavior across users, agents, and apps.
</Card>
<Card
title="Control Memory Ingestion"
icon="filter"
href="/cookbooks/essentials/controlling-memory-ingestion"
>
Filter speculation and low-confidence data.
</Card>
<Card
title="Set Memory Expiration"
icon="timer"
href="/cookbooks/essentials/memory-expiration-short-and-long-term"
>
Short-term vs long-term retention strategies.
</Card>
</CardGroup>
## Companion Playbooks
<CardGroup cols={2}>
<Card title="Interactive Memory Demo" icon="rocket" href="/cookbooks/companions/quickstart-demo">
See Mem0 memories in action.
</Card>
<Card
title="Research Assistant for YouTube"
icon="video"
href="/cookbooks/companions/youtube-research"
>
Personalized context for video browsing.
</Card>
<Card
title="Voice-First AI Companion"
icon="microphone"
href="/cookbooks/companions/voice-companion-openai"
>
Voice-first experiences with Agents SDK.
</Card>
<Card title="Personalized AI Tutor" icon="graduation-cap" href="/cookbooks/companions/ai-tutor">
Student progress persistent across sessions.
</Card>
<Card title="Smart Travel Assistant" icon="plane" href="/cookbooks/companions/travel-assistant">
Itineraries that remember traveler preferences.
</Card>
<Card title="Build a Node.js Companion" icon="js" href="/cookbooks/companions/nodejs-companion">
JavaScript fitness coach remembering goals.
</Card>
<Card
title="Self-Hosted AI Companion"
icon="server"
href="/cookbooks/companions/local-companion-ollama"
>
Run Mem0 end-to-end with Ollama.
</Card>
</CardGroup>
## Ops & Automations
<CardGroup cols={2}>
<Card
title="Automated Email Intelligence"
icon="envelope"
href="/cookbooks/operations/email-automation"
>
Capture and recall inbox threads.
</Card>
<Card
title="Content Creation Workflow"
icon="pencil"
href="/cookbooks/operations/content-writing"
>
Store tone and style guidelines.
</Card>
<Card
title="Multi-Session Research Agent"
icon="magnifying-glass"
href="/cookbooks/operations/deep-research"
>
Multi-session investigations without repeating.
</Card>
<Card
title="Memory-Powered Support Agent"
icon="headset"
href="/cookbooks/operations/support-inbox"
>
Past tickets at support fingertips.
</Card>
<Card
title="Collaborative Task Assistant"
icon="users"
href="/cookbooks/operations/team-task-agent"
>
Coordinate multi-user projects with roles.
</Card>
</CardGroup>
## Integrations & Platforms
<CardGroup cols={2}>
<Card
title="Memory-Powered Agent SDK"
icon="robot"
href="/cookbooks/integrations/agents-sdk-tool"
>
Callable tools inside agent workflows.
</Card>
<Card
title="Memory as OpenAI Tool"
icon="wrench"
href="/cookbooks/integrations/openai-tool-calls"
>
Memories in function-calling flows.
</Card>
<Card title="Persistent Mastra Agents" icon="code" href="/cookbooks/integrations/mastra-agent">
Persistent memory for Mastra agents.
</Card>
<Card
title="Healthcare Coach with ADK"
icon="heart-pulse"
href="/cookbooks/integrations/healthcare-google-adk"
>
Patient history across ADK sessions.
</Card>
<Card
title="Search with Personal Context"
icon="search"
href="/cookbooks/integrations/tavily-search"
>
Realtime search with personal context.
</Card>
<Card
title="Bedrock with Persistent Memory"
icon="aws"
href="/cookbooks/integrations/aws-bedrock"
>
Mem0 with AWS Bedrock and Neptune.
</Card>
<Card
title="Graph Memory on Neptune"
icon="network-wired"
href="/cookbooks/integrations/neptune-analytics"
>
Graph memory with Neptune Analytics.
</Card>
</CardGroup>
## Frameworks & Multimodal
<CardGroup cols={2}>
<Card title="ReAct Agents with Memory" icon="brain" href="/cookbooks/frameworks/llamaindex-react">
ReAct agents with memory storage.
</Card>
<Card
title="Multi-Agent Collaboration"
icon="users"
href="/cookbooks/frameworks/llamaindex-multiagent"
>
Shared memory across collaborating agents.
</Card>
<Card
title="Visual Memory Retrieval"
icon="image"
href="/cookbooks/frameworks/multimodal-retrieval"
>
Visual context alongside text conversations.
</Card>
<Card
title="Persistent Eliza Characters"
icon="robot"
href="/cookbooks/frameworks/eliza-os-character"
>
Persistent personality for Eliza agents.
</Card>
<Card title="Browser Extension Memory" icon="globe" href="/cookbooks/frameworks/chrome-extension">
Universal memory layer for Chrome.
</Card>
</CardGroup>
---
## Contribute a Cookbook
Have a unique Mem0 use case or integration? We'd love to feature your cookbook!
All cookbooks follow a standardized template to ensure consistency and quality. Check out our template to see the structure and best practices.
<CardGroup cols={2}>
<Card title="Cookbook Template" icon="book-open" href="/templates/cookbook_template">
Follow this structure for narrative, end-to-end Mem0 workflows.
</Card>
<Card
title="Contribution Guide"
icon="github"
href="https://github.com/mem0ai/mem0/blob/main/CONTRIBUTING.md"
>
Learn how to submit your cookbook to the Mem0 repository.
</Card>
</CardGroup>
+84 -32
View File
@@ -5,43 +5,56 @@ icon: "plus"
iconType: "solid"
---
# How Mem0 Adds Memory
## Overview
Adding memory is how Mem0 captures useful details from a conversation so your agents can reuse them later. Think of it as saving the important sentences from a chat transcript into a structured notebook your agent can search.
The `add` operation stores memory into Mem0. Whether you're working with a chatbot, a voice assistant, or a multi-agent system, this is the entry point to create long-term memory.
<Info>
**Why it matters**
- Preserves user preferences, goals, and feedback across sessions.
- Powers personalization and decision-making in downstream conversations.
- Keeps context consistent between managed Platform and OSS deployments.
</Info>
Memories typically come from a **user-assistant interaction** and Mem0 handles the extraction, transformation, and storage for you.
## Key terms
Mem0 offers two implementation flows:
- **Messages** – The ordered list of user/assistant turns you send to `add`.
- **Infer** – Controls whether Mem0 extracts structured memories (`infer=True`, default) or stores raw messages.
- **Metadata** – Optional filters (e.g., `{"category": "movie_recommendations"}`) that improve retrieval later.
- **User / Session identifiers** – `user_id`, `session_id`, or `run_id` that scope the memory for future searches.
- **Mem0 Platform** (Managed, scalable, with dashboard + API)
- **Mem0 Open Source** (Lightweight, fully local, flexible SDKs)
## How does it work?
Each supports the same core memory operations, but with slightly different setup.
Mem0 offers two flows:
- **Mem0 Platform** – Fully managed API with dashboard, scaling, and graph features.
- **Mem0 Open Source** – Local SDK that you run in your own environment.
## Architecture
Both flows take the same payload and pass it through the same pipeline.
<Frame caption="Architecture diagram illustrating the process of adding memories.">
<img src="../../images/add_architecture.png" />
</Frame>
When you call `add`, Mem0 performs the following steps under the hood:
<Steps>
<Step title="Information extraction">
Mem0 sends the messages through an LLM that pulls out key facts, decisions, or preferences to remember.
</Step>
<Step title="Conflict resolution">
Existing memories are checked for duplicates or contradictions so the latest truth wins.
</Step>
<Step title="Storage">
The resulting memories land in managed vector storage (and optional graph storage) so future searches return them quickly.
</Step>
</Steps>
1. **Information Extraction**
The input messages are passed through an LLM that extracts key facts, decisions, preferences, or events worth remembering.
<Warning>
Duplicate protection only runs during that conflict-resolution step when you let Mem0 infer memories (`infer=True`, the default). If you switch to `infer=False`, Mem0 stores your payload exactly as provided, so duplicates will land. Mixing both modes for the same fact will save it twice.
</Warning>
2. **Conflict Resolution**
Mem0 compares the new memory against existing ones to detect duplication or contradiction and handles updates accordingly.
You trigger this pipeline with a single `add` call—no manual orchestration needed.
3. **Memory Storage**
The result is stored in a vector database (for semantic search) and optionally in a graph structure (for relationship mapping).
You don't need to handle any of this manually - Mem0 takes care of it with a single API call or SDK method.
---
## Example: Mem0 Platform
## Add with Mem0 Platform
<CodeGroup>
```python Python
@@ -57,7 +70,6 @@ messages = [
client.add(
messages=messages,
user_id="alice",
)
```
@@ -71,17 +83,18 @@ const messages = [
{ role: "assistant", content: "Great! I’ll remember that for future suggestions." }
];
await client.add({
messages,
await client.add(messages, {
user_id: "alice",
version: "v2"
version: "v2",
});
```
</CodeGroup>
---
<Info icon="check">
Expect a `memory_id` (or list of IDs) in the response. Check the Mem0 dashboard to confirm the new entry under the correct user.
</Info>
## Example: Mem0 Open Source
## Add with Mem0 Open Source
<CodeGroup>
```python Python
@@ -125,7 +138,13 @@ const result = memory.add(messages, {
```
</CodeGroup>
---
<Tip>
Use `infer=False` only when you need to store raw transcripts. Most workflows benefit from Mem0 extracting structured memories automatically.
</Tip>
<Warning>
If you do choose `infer=False`, keep it consistent. Raw inserts skip conflict resolution, so a later `infer=True` call with the same content will create a second memory instead of updating the first.
</Warning>
## When Should You Add Memory?
@@ -137,6 +156,10 @@ Add memory whenever your agent learns something useful:
- A new entity is introduced
- A user gives feedback or clarification
<Callout type="tip" icon="plug">
**MCP Alternative**: With <Link href="/platform/mem0-mcp">Mem0 MCP</Link>, AI agents can add memories automatically based on context.
</Callout>
Storing this context allows the agent to reason better in future interactions.
@@ -145,9 +168,38 @@ Storing this context allows the agent to reason better in future interactions.
For full list of supported fields, required formats, and advanced options, see the
[Add Memory API Reference](/api-reference/memory/add-memories).
---
## Managed vs OSS differences
## Need help?
If you have any questions, please feel free to reach out to us using one of the following methods:
| Capability | Mem0 Platform | Mem0 OSS |
| --- | --- | --- |
| Conflict resolution | Automatic with dashboard visibility | SDK handles merges locally; you control storage |
| Graph writes | Toggle per request (`enable_graph=True`) | Requires configuring a graph provider |
| Rate limits | Managed quotas per workspace | Limited by your hardware and provider APIs |
| Dashboard visibility | Yes — inspect memories visually | Inspect via CLI, logs, or custom UI |
<Snippet file="get-help.mdx"/>
## Put it into practice
- Review the <Link href="/platform/advanced-memory-operations">Advanced Memory Operations</Link> guide to layer metadata, rerankers, and graph toggles.
- Explore the <Link href="/api-reference/memory/add-memories">Add Memories API reference</Link> for every request/response field.
## See it live
- <Link href="/cookbooks/operations/support-inbox">Support Inbox with Mem0</Link> shows add + search powering a support flow.
- <Link href="/cookbooks/companions/ai-tutor">AI Tutor with Mem0</Link> uses add to personalize lesson plans.
{/* DEBUG: verify CTA targets */}
<CardGroup cols={2}>
<Card
title="Explore Search Concepts"
description="See how stored memories feed retrieval in the Search guide."
icon="search"
href="/core-concepts/memory-operations/search"
/>
<Card
title="Build a Support Agent"
description="Follow the cookbook to apply add/search/update in production."
icon="rocket"
href="/cookbooks/operations/support-inbox"
/>
</CardGroup>
+136 -35
View File
@@ -5,27 +5,39 @@ icon: "trash"
iconType: "solid"
---
## Overview
# Remove Memories Safely
Memories can become outdated, irrelevant, or need to be removed for privacy or compliance reasons. Mem0 offers flexible ways to delete memory:
Deleting memories is how you honor compliance requests, undo bad data, or clean up expired sessions. Mem0 lets you delete a specific memory, a list of IDs, or everything that matches a filter.
1. **Delete a Single Memory**: Using a specific memory ID
2. **Batch Delete**: Delete multiple known memory IDs (up to 1000)
3. **Filtered Delete**: Delete memories matching a filter (e.g., `user_id`, `metadata`, `run_id`)
<Info>
**Why it matters**
- Satisfies user erasure (GDPR/CCPA) without touching the rest of your data.
- Keeps knowledge bases accurate by removing stale or incorrect facts.
- Works for both the managed Platform API and the OSS SDK.
</Info>
This page walks through code examples for each method.
## Key terms
- **memory_id** – Unique ID returned by `add`/`search` identifying the record to delete.
- **batch_delete** – API call that removes up to 1000 memories in one request.
- **delete_all** – Filter-based deletion by user, agent, run, or metadata.
- **immutable** – Flagged memories that cannot be updated; delete + re-add instead.
## Use Cases
## How the delete flow works
- Forget a user’s past preferences by request
- Remove outdated or incorrect memory entries
- Clean up memory after session expiration
- Comply with data deletion requests (e.g., GDPR)
<Steps>
<Step title="Choose the scope">
Decide whether you’re removing a single memory, a list, or everything that matches a filter.
</Step>
<Step title="Submit the delete call">
Call `delete`, `batch_delete`, or `delete_all` with the required IDs or filters.
</Step>
<Step title="Verify">
Confirm the response message, then re-run `search` or check the dashboard/logs to ensure the memory is gone.
</Step>
</Steps>
---
## 1. Delete a Single Memory by ID
## Delete a single memory (Platform)
<CodeGroup>
```python Python
@@ -48,9 +60,11 @@ client.delete("your_memory_id")
```
</CodeGroup>
---
<Info icon="check">
You’ll receive a confirmation payload. The dashboard reflects the removal within seconds.
</Info>
## 2. Batch Delete Multiple Memories
## Batch delete multiple memories (Platform)
<CodeGroup>
```python Python
@@ -83,9 +97,7 @@ client.batchDelete(deleteMemories)
```
</CodeGroup>
---
## 3. Delete Memories by Filter (e.g., user_id)
## Delete memories by filter (Platform)
<CodeGroup>
```python Python
@@ -95,6 +107,12 @@ client = MemoryClient(api_key="your-api-key")
# Delete all memories for a specific user
client.delete_all(user_id="alice")
# Delete all memories for a specific agent
client.delete_all(agent_id="support-bot")
# Delete all memories for a specific run
client.delete_all(run_id="session-xyz")
```
```javascript JavaScript
@@ -114,27 +132,110 @@ You can also filter by other parameters such as:
- `run_id`
- `metadata` (as JSON string)
---
<Warning>
**Breaking change:** `delete_all` previously wiped all project memories when called with no filters. It now **raises an error** if no filters are provided. Use `"*"` wildcards for intentional bulk deletion (see below).
</Warning>
## Key Differences
### Wildcard deletes
| Method | Use When | IDs Needed | Filters |
|----------------------|-------------------------------------------|------------|----------|
| `delete(memory_id)` | You know exactly which memory to remove | ✔ | ✘ |
| `batch_delete([...])`| You have a known list of memory IDs | ✔ | ✘ |
| `delete_all(...)` | You want to delete by user/agent/run/etc | ✘ | ✔ |
Setting a filter to `"*"` deletes **all memories** for that entity type across the entire project. This is an intentionally explicit opt-in to bulk deletion.
<CodeGroup>
```python Python
from mem0 import MemoryClient
### More Details
client = MemoryClient(api_key="your-api-key")
For request/response schema and additional filtering options, see:
- [Delete Memory API Reference](/api-reference/memory/delete-memory)
- [Batch Delete API Reference](/api-reference/memory/batch-delete)
- [Delete Memories by Filter Reference](/api-reference/memory/delete-memories)
# Delete all memories across every user in the project
client.delete_all(user_id="*")
You’ve now seen how to add, search, update, and delete memories in Mem0.
# Delete all memories across every agent in the project
client.delete_all(agent_id="*")
## Need help?
If you have any questions, please feel free to reach out to us using one of the following methods:
# Full project wipe — all four filters must be explicitly set to "*"
client.delete_all(user_id="*", agent_id="*", app_id="*", run_id="*")
```
<Snippet file="get-help.mdx"/>
```javascript JavaScript
import MemoryClient from 'mem0ai';
const client = new MemoryClient({ apiKey: "your-api-key" });
// Delete all memories across every user in the project
client.deleteAll({ user_id: "*" })
.then(result => console.log(result))
.catch(error => console.error(error));
// Full project wipe — all four filters must be explicitly set to "*"
client.deleteAll({ user_id: "*", agent_id: "*", app_id: "*", run_id: "*" })
.then(result => console.log(result))
.catch(error => console.error(error));
```
</CodeGroup>
<Warning>
A full project wipe requires **all four** filters set to `"*"`. Setting only some to `"*"` deletes memories only for those entity types, not the entire project.
</Warning>
## Delete with Mem0 OSS
<CodeGroup>
```python Python
from mem0 import Memory
memory = Memory()
memory.delete(memory_id="mem_123")
memory.delete_all(user_id="alice")
```
</CodeGroup>
<Note>
The OSS JavaScript SDK does not yet expose deletion helpers—use the REST API or Python SDK when self-hosting.
</Note>
## Use cases recap
- Forget a user’s preferences at their request.
- Remove outdated or incorrect facts before they spread.
- Clean up memories after session expiration or retention deadlines.
- Comply with privacy legislation (GDPR, CCPA) and internal policies.
<Callout type="tip" icon="plug">
**MCP Alternative**: With <Link href="/platform/mem0-mcp">Mem0 MCP</Link>, AI agents can delete their own memories when data becomes irrelevant or at user request.
</Callout>
## Method comparison
| Method | Use when | IDs required | Filters |
| --- | --- | --- | --- |
| `delete(memory_id)` | You know the exact record | ✔️ | ✖️ |
| `batch_delete([...])` | You have a list of IDs to purge | ✔️ | ✖️ |
| `delete_all(...)` | You need to forget a user/agent/run | ✖️ | ✔️ |
## 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>.
- Pair deletes with <Link href="/platform/features/expiration-date">Expiration Policies</Link> to automate retention.
## See it live
- <Link href="/cookbooks/operations/support-inbox">Support Inbox with Mem0</Link> demonstrates compliance-driven deletes.
- <Link href="/platform/features/direct-import">Data Management tooling</Link> shows how deletes fit into broader lifecycle flows.
{/* DEBUG: verify CTA targets */}
<CardGroup cols={2}>
<Card
title="Review Add Concepts"
description="Ensure the memories you keep are structured from the start."
icon="circle-check"
href="/core-concepts/memory-operations/add"
/>
<Card
title="Enable Expiration Policies"
description="Automate retention with the platform’s expiration feature."
icon="clock"
href="/platform/features/expiration-date"
/>
</CardGroup>
+111 -34
View File
@@ -5,20 +5,23 @@ icon: "magnifying-glass"
iconType: "solid"
---
## Overview
# How Mem0 Searches Memory
The `search` operation allows you to retrieve relevant memories based on a natural language query and optional filters like user ID, agent ID, categories, and more. This is the foundation of giving your agents memory-aware behavior.
Mem0's search operation lets agents ask natural-language questions and get back the memories that matter most. Like a smart librarian, it finds exactly what you need from everything you've stored.
Mem0 supports:
- Semantic similarity search
- Metadata filtering (with advanced logic)
- Reranking and thresholds
- Cross-agent, multi-session context resolution
<Info>
**Why it matters**
- Retrieves the right facts without rebuilding prompts from scratch.
- Supports both managed Platform and OSS so you can test locally and deploy at scale.
- Keeps results relevant with filters, rerankers, and thresholds.
</Info>
This applies to both:
- **Mem0 Platform** (hosted API with full-scale features)
- **Mem0 Open Source** (local-first with LLM inference and local vector DB)
## Key terms
- **Query** – Natural-language question or statement you pass to `search`.
- **Filters** – JSON logic (AND/OR, comparison operators) that narrows results by user, categories, dates, etc.
- **top_k / threshold** – Controls how many memories return and the minimum similarity score.
- **Rerank** – Optional second pass that boosts precision when a reranker is configured.
## Architecture
@@ -26,23 +29,58 @@ This applies to both:
<img src="../../images/search_architecture.png" />
</Frame>
When you call `search`, Mem0 performs the following steps:
<Steps>
<Step title="Query processing">
Mem0 cleans and enriches your natural-language query so the downstream embedding search is accurate.
</Step>
<Step title="Vector search">
Embeddings locate the closest memories using cosine similarity across your scoped dataset.
</Step>
<Step title="Filtering & reranking">
Logical filters narrow candidates; rerankers or thresholds fine-tune ordering.
</Step>
<Step title="Results delivery">
Formatted memories (with metadata and timestamps) return to your agent or calling service.
</Step>
</Steps>
1. **Query Processing**
An LLM refines and optimizes your natural language query.
This pipeline runs the same way for the hosted Platform API and the OSS SDK.
2. **Vector Search**
Semantic embeddings are used to find the most relevant memories using cosine similarity.
## How does it work?
3. **Filtering & Ranking**
Logical and comparison-based filters are applied. Memories are scored, filtered, and optionally reranked.
Search converts your natural language question into a vector embedding, then finds memories with similar embeddings in your database. The results are ranked by similarity score and can be further refined with filters or reranking.
4. **Results Delivery**
Relevant memories are returned with associated metadata and timestamps.
```python
# Minimal example that shows the concept in action
# Platform API
client.search("What are Alice's hobbies?", filters={"user_id": "alice"})
---
# OSS
m.search("What are Alice's hobbies?", user_id="alice")
```
## Example: Mem0 Platform
<Tip>
Always provide at least a `user_id` filter to scope searches to the right user's memories. This prevents cross-contamination between users.
</Tip>
## When should you use it?
- **Context retrieval** - When your agent needs past context to generate better responses
- **Personalization** - To recall user preferences, history, or past interactions
- **Fact checking** - To verify information against stored memories before responding
- **Decision support** - When agents need relevant background information to make decisions
## Platform vs OSS usage
| Capability | Mem0 Platform | Mem0 OSS |
| --- | --- | --- |
| **user_id usage** | In `filters={"user_id": "alice"}` for search/get_all | As parameter `user_id="alice"` for all operations |
| **Filter syntax** | Logical operators (`AND`, `OR`, comparisons) with field-level access | Basic field filters, extend via Python hooks |
| **Reranking** | Toggle `rerank=True` with managed reranker catalog | Requires configuring local or third-party rerankers |
| **Thresholds** | Request-level configuration (`threshold`, `top_k`) | Controlled via SDK parameters |
| **Response metadata** | Includes confidence scores, timestamps, dashboard visibility | Determined by your storage backend |
## Search with Mem0 Platform
<CodeGroup>
```python Python
@@ -79,9 +117,7 @@ const results = await client.search(query, {
```
</CodeGroup>
---
## Example: Mem0 Open Source
## Search with Mem0 Open Source
<CodeGroup>
```python Python
@@ -116,13 +152,29 @@ const memories = memory.search("food preferences", {
```
</CodeGroup>
---
<Info icon="check">
Expect an array of memory documents. Platform responses include vectors, metadata, and timestamps; OSS returns your stored schema.
</Info>
## Using Filters
## Filter patterns
Filters help narrow down search results. Common use cases:
**Filter by Session Context:**
*Platform API:*
```python
# Get memories from a specific agent session
client.search("query", filters={
"AND": [
{"user_id": "alice"},
{"agent_id": "chatbot"},
{"run_id": "session-123"}
]
})
```
*OSS:*
```python
# Get memories from a specific agent session
m.search("query", user_id="alice", agent_id="chatbot", run_id="session-123")
@@ -150,24 +202,49 @@ client.search("preferences", filters={
})
```
---
## Tips for Better Search
## Tips for better search
- **Use natural language**: Mem0 understands intent, so describe what you're looking for naturally
- **Scope with session IDs**: Always provide at least `user_id` to scope search to relevant memories
- **Scope with user ID**: Always provide `user_id` to scope search to relevant memories
- **Platform API**: Use `filters={"user_id": "alice"}`
- **OSS**: Use `user_id="alice"` as parameter
- **Combine filters**: Use AND/OR logic to create precise queries (Platform)
- **Consider wildcard filters**: Use wildcard filters (e.g., `run_id: "*"`) for broader matches
- **Tune parameters**: Adjust `top_k` for result count, `threshold` for relevance cutoff
- **Enable reranking**: Use `rerank=True` (default) when you have a reranker configured
<Callout type="tip" icon="plug">
**MCP Alternative**: With <Link href="/platform/mem0-mcp">Mem0 MCP</Link>, AI agents can search their own memories proactively when needed.
</Callout>
### More Details
For the full list of filter logic, comparison operators, and optional search parameters, see the
[Search Memory API Reference](/api-reference/memory/v2-search-memories).
[Search Memory API Reference](/api-reference/memory/search-memories).
## Need help?
If you have any questions, please feel free to reach out to us using one of the following methods:
## Put it into practice
<Snippet file="get-help.mdx"/>
- Revisit the <Link href="/core-concepts/memory-operations/add">Add Memory</Link> guide to ensure you capture the context you expect to retrieve.
- Configure rerankers and filters in <Link href="/platform/features/advanced-retrieval">Advanced Retrieval</Link> for higher precision.
## See it live
- <Link href="/cookbooks/operations/support-inbox">Support Inbox with Mem0</Link> demonstrates scoped search with rerankers.
- <Link href="/cookbooks/integrations/tavily-search">Tavily Search with Mem0</Link> shows hybrid search in action.
{/* DEBUG: verify CTA targets */}
<CardGroup cols={2}>
<Card
title="Search Memory API"
description="Complete API reference with all filter operators and parameters."
icon="book"
href="/api-reference/memory/search-memories"
/>
<Card
title="Support Inbox Cookbook"
description="Build a complete support system with scoped search and reranking."
icon="rocket"
href="/cookbooks/operations/support-inbox"
/>
</CardGroup>
+98 -35
View File
@@ -1,33 +1,45 @@
---
title: Update Memory
description: Modify an existing memory by updating its content or metadata.
icon: "pencil"
icon: "pen-to-square"
iconType: "solid"
---
## Overview
# Keep Memories Accurate with Update
User preferences, interests, and behaviors often evolve over time. The `update` operation lets you revise a stored memory, whether it's updating facts, rephrasing a message, or enriching metadata.
Mem0’s update operation lets you fix or enrich an existing memory without deleting it. When a user changes their preference or clarifies a fact, use update to keep the knowledge base fresh.
Mem0 supports both:
- **Single Memory Update** for one specific memory using its ID
- **Batch Update** for updating many memories at once (up to 1000)
<Info>
**Why it matters**
- Corrects outdated or incorrect memories immediately.
- Adds new metadata so filters and rerankers stay sharp.
- Works for both one-off edits and large batches (up to 1000 memories).
</Info>
This guide includes usage for both single update and batch update of memories through **Mem0 Platform**.
## Key terms
- **memory_id** – Unique identifier returned by `add` or `search` results.
- **text** / **data** – New content that replaces the stored memory value.
- **metadata** – Optional key-value pairs you update alongside the text.
- **timestamp** – Unix epoch (int/float) or ISO 8601 string to override the memory's timestamp.
- **batch_update** – Platform API that edits multiple memories in a single request.
- **immutable** – Flagged memories that must be deleted and re-added instead of updated.
## Use Cases
## How the update flow works
- Refine a vague or incorrect memory after a correction
- Add or edit memory with new metadata (e.g., categories, tags)
- Evolve factual knowledge as the user's profile changes
- Handle profile evolution: "I love spicy food" → later says "Actually, I can't handle spicy food"
<Steps>
<Step title="Locate the memory">
Use `search` or dashboard inspection to capture the `memory_id` you want to change.
</Step>
<Step title="Submit the update">
Call `update` (or `batch_update`) with new text and optional metadata. Mem0 overwrites the stored value and adjusts indexes.
</Step>
<Step title="Verify">
Check the response or re-run `search` to ensure the revised memory appears with the new content.
</Step>
</Steps>
Updating memory ensures your agents remain accurate, adaptive, and personalized.
---
## Update Memory
## Single memory update (Platform)
<CodeGroup>
```python Python
@@ -39,7 +51,8 @@ memory_id = "your_memory_id"
client.update(
memory_id=memory_id,
text="Updated memory content about the user",
metadata={"category": "profile-update"}
metadata={"category": "profile-update"},
timestamp="2025-01-15T12:00:00Z"
)
```
@@ -49,18 +62,19 @@ import MemoryClient from 'mem0ai';
const client = new MemoryClient({ apiKey: "your-api-key" });
const memory_id = "your_memory_id";
client.update(memory_id, {
await client.update(memory_id, {
text: "Updated memory content about the user",
metadata: { category: "profile-update" }
})
.then(result => console.log(result))
.catch(error => console.error(error));
metadata: { category: "profile-update" },
timestamp: "2025-01-15T12:00:00Z"
});
```
</CodeGroup>
---
<Info icon="check">
Expect a confirmation message and the updated memory to appear in the dashboard almost instantly.
</Info>
## Batch Update
## Batch update (Platform)
Update up to 1000 memories in one call.
@@ -95,21 +109,70 @@ client.batchUpdate(updateMemories)
```
</CodeGroup>
---
## Update with Mem0 OSS
<CodeGroup>
```python Python
from mem0 import Memory
memory = Memory()
memory.update(
memory_id="mem_123",
data="Alex now prefers decaf coffee",
)
```
```
```
</CodeGroup>
<Note>
OSS JavaScript SDK does not expose `update` yet—use the REST API or Python SDK when self-hosting.
</Note>
## Tips
- You can update both `text` and `metadata` in the same call
- Use `batchUpdate` when you're applying similar corrections at scale
- If memory is marked `immutable`, it must first be deleted and re-added
- Combine this with feedback mechanisms (e.g., user thumbs-up/down) to self-improve memory
- Update both `text` **and** `metadata` together to keep filters accurate.
- Batch updates are ideal after large imports or when syncing CRM corrections.
- Immutable memories must be deleted and re-added instead of updated.
- Pair updates with feedback signals (thumbs up/down) to self-heal memories automatically.
<Callout type="tip" icon="plug">
**MCP Alternative**: With <Link href="/platform/mem0-mcp">Mem0 MCP</Link>, AI agents can update their own memories when users correct information.
</Callout>
### More Details
## Managed vs OSS differences
Refer to the full [Update Memory API Reference](/api-reference/memory/update-memory) and [Batch Update Reference](/api-reference/memory/batch-update) for schema and advanced fields.
| Capability | Mem0 Platform | Mem0 OSS |
| --- | --- | --- |
| Update call | `client.update(memory_id, {...})` | `memory.update(memory_id, data=...)` |
| Batch updates | `client.batch_update` (up to 1000 memories) | Script your own loop or bulk job |
| Dashboard visibility | Inspect updates in the UI | Inspect via logs or custom tooling |
| Immutable handling | Returns descriptive error | Raises exception—delete and re-add |
## Need help?
If you have any questions, please feel free to reach out to us using one of the following methods:
## Put it into practice
<Snippet file="get-help.mdx"/>
- Review the <Link href="/api-reference/memory/update-memory">Update Memory API reference</Link> for request/response details.
- Combine updates with <Link href="/platform/features/feedback-mechanism">Feedback Mechanism</Link> to automate corrections.
## See it live
- <Link href="/cookbooks/operations/support-inbox">Support Inbox with Mem0</Link> uses updates to refine customer profiles.
- <Link href="/cookbooks/companions/ai-tutor">AI Tutor with Mem0</Link> demonstrates user preference corrections mid-course.
{/* DEBUG: verify CTA targets */}
<CardGroup cols={2}>
<Card
title="Learn Delete Concepts"
description="Understand when to remove memories instead of editing them."
icon="trash"
href="/core-concepts/memory-operations/delete"
/>
<Card
title="Automate Corrections"
description="See how feedback loops trigger updates in production."
icon="rocket"
href="/platform/features/feedback-mechanism"
/>
</CardGroup>
+109 -30
View File
@@ -1,50 +1,129 @@
---
title: Memory Types
description: Understanding different types of memory in AI Applications
icon: "memory"
description: "See how Mem0 layers conversation, session, and user memories to keep agents contextual."
icon: "tag"
iconType: "solid"
---
To build useful AI applications, we need to understand how different memory systems work together. This guide explores the fundamental types of memory in AI systems and shows how Mem0 implements these concepts.
# How Mem0 Organizes Memory
## Why Memory Matters
Mem0 separates memory into layers so agents remember the right detail at the right time. Think of it like a notebook: a sticky note for the current task, a daily journal for the session, and an archive for everything a user has shared.
AI systems need memory for three key purposes:
1. Maintaining context during conversations
2. Learning from past interactions
3. Building personalized experiences over time
<Info>
**Why it matters**
- Keeps conversations coherent without repeating instructions.
- Lets agents personalize responses based on long-term preferences.
- Avoids over-fetching data by scoping memory to the correct layer.
</Info>
Without proper memory systems, AI applications would treat each interaction as completely new, losing valuable context and personalization opportunities.
## Key terms
## Short-Term Memory
- **Conversation memory** – In-flight messages inside a single turn (what was just said).
- **Session memory** – Short-lived facts that apply for the current task or channel.
- **User memory** – Long-lived knowledge tied to a person, account, or workspace.
- **Organizational memory** – Shared context available to multiple agents or teams.
The most basic form of memory in AI systems holds immediate context - like a person remembering what was just said in a conversation. This includes:
```mermaid
graph LR
A[Conversation turn] --> B[Session memory]
B --> C[User memory]
C --> D[Org memory]
C --> E[Mem0 retrieval layer]
```
- **Conversation History**: Recent messages and their order
- **Working Memory**: Temporary variables and state
- **Attention Context**: Current focus of the conversation
## Short-term vs long-term memory
## Long-Term Memory
Short-term memory keeps the current conversation coherent. It includes:
More sophisticated AI applications implement long-term memory to retain information across conversations. This includes:
- **Conversation history** – recent turns in order so the agent remembers what was just said.
- **Working memory** – temporary state such as tool outputs or intermediate calculations.
- **Attention context** – the immediate focus of the assistant, similar to what a person holds in mind mid-sentence.
- **Factual Memory**: Stored knowledge about users, preferences, and domain-specific information
- **Episodic Memory**: Past interactions and experiences
- **Semantic Memory**: Understanding of concepts and their relationships
Long-term memory preserves knowledge across sessions. It captures:
## Memory Characteristics
- **Factual memory** – user preferences, account details, and domain facts.
- **Episodic memory** – summaries of past interactions or completed tasks.
- **Semantic memory** – relationships between concepts so agents can reason about them later.
Each memory type has distinct characteristics:
Mem0 maps these classic categories onto its layered storage so you can decide what should fade quickly versus what should last for months.
| Type | Persistence | Access Speed | Use Case |
|------|-------------|--------------|-----------|
| Short-Term | Temporary | Instant | Active conversations |
| Long-Term | Persistent | Fast | User preferences and history |
## How does it work?
## How Mem0 Implements Long-Term Memory
Mem0 stores each layer separately and merges them when you query:
Mem0's long-term memory system builds on these foundations by:
1. **Capture** – Messages enter the conversation layer while the turn is active.
2. **Promote** – Relevant details persist to session or user memory based on your `user_id`, `session_id`, and metadata.
3. **Retrieve** – The search pipeline pulls from all layers, ranking user memories first, then session notes, then raw history.
1. Using vector embeddings to store and retrieve semantic information
2. Maintaining user-specific context across sessions
3. Implementing efficient retrieval mechanisms for relevant past interactions
```python
import os
from mem0 import Memory
memory = Memory(api_key=os.environ["MEM0_API_KEY"])
# Sticky note: conversation memory
memory.add(
["I'm Alex and I prefer boutique hotels."],
user_id="alex",
session_id="trip-planning-2025",
)
# Later in the session, pull long-term + session context
results = memory.search(
"Any hotel preferences?",
user_id="alex",
session_id="trip-planning-2025",
)
```
<Tip>
Use `session_id` when you want short-term context to expire automatically; rely on `user_id` for lasting personalization.
</Tip>
## When should you use each layer?
- **Conversation memory** – Tool calls or chain-of-thought that only matter within the current turn.
- **Session memory** – Multi-step tasks (onboarding flows, debugging sessions) that should reset once complete.
- **User memory** – Personal preferences, account state, or compliance details that must persist across interactions.
- **Organizational memory** – Shared FAQs, product catalogs, or policies that every agent should recall.
## How it compares
| Layer | Lifetime | Short or long term | Best for | Trade-offs |
| --- | --- | --- | --- | --- |
| Conversation | Single response | Short-term | Tool execution detail | Lost after the turn finishes |
| Session | Minutes to hours | Short-term | Multi-step flows | Clear it manually when done |
| User | Weeks to forever | Long-term | Personalization | Requires consent/governance |
| Org | Configured globally | Long-term | Shared knowledge | Needs owner to keep current |
<Warning>
Avoid storing secrets or unredacted PII in user or org memories—Mem0 is retrievable by design. Encrypt or hash sensitive values first.
</Warning>
## Put it into practice
- Use the <Link href="/core-concepts/memory-operations/add">Add Memory</Link> guide to persist user preferences.
- Follow <Link href="/platform/advanced-memory-operations">Advanced Memory Operations</Link> to tune metadata and graph writes.
## See it live
- <Link href="/cookbooks/companions/ai-tutor">AI Tutor with Mem0</Link> shows session vs user memories in action.
- <Link href="/cookbooks/operations/support-inbox">Support Inbox with Mem0</Link> demonstrates shared org memory.
{/* DEBUG: verify CTA targets */}
<CardGroup cols={2}>
<Card
title="Explore Memory Operations"
description="Dive into the add/search/update/delete concepts next."
icon="circle-check"
href="/core-concepts/memory-operations/add"
/>
<Card
title="See a Cookbook"
description="Apply layered memories inside a customer support agent."
icon="rocket"
href="/cookbooks/operations/support-inbox"
/>
</CardGroup>
+860 -655
View File
File diff suppressed because it is too large Load Diff
-116
View File
@@ -1,116 +0,0 @@
---
title: Overview
description: How to use mem0 in your existing applications?
---
With Mem0, you can create stateful LLM-based applications such as chatbots, virtual assistants, or AI agents. Mem0 enhances your applications by providing a memory layer that makes responses:
- More personalized
- More reliable
- Cost-effective by reducing the number of LLM interactions
- More engaging
- Enables long-term memory
Here are some examples of how Mem0 can be integrated into various applications:
## Examples
Explore how **Mem0** can power real-world applications and bring personalized, intelligent experiences to life:
<CardGroup cols={2}>
<Card title="Mem0 Demo" icon="rocket" href="/examples/mem0-demo">
Get started with **Mem0** with this simple demo showcasing basic memory operations.
</Card>
<Card title="AI Companion in Node.js" icon="node" href="/examples/ai_companion_js">
Build a personalized AI Companion in **Node.js** that remembers conversations and adapts over time.
</Card>
<Card title="Mem0 with Ollama" icon="server" href="/examples/mem0-with-ollama">
Run **Mem0 locally** with **Ollama** to create private, stateful AI experiences without cloud APIs.
</Card>
<Card title="Personal AI Tutor" icon="graduation-cap" href="/examples/personal-ai-tutor">
Create an **AI Tutor** that adapts to student progress, learning style, and history.
</Card>
<Card title="Customer Support Agent" icon="headset" href="/examples/customer-support-agent">
Build a **Customer Support AI** that recalls user preferences and past chats.
</Card>
<Card title="Personal Travel Assistant" icon="plane" href="/examples/personal-travel-assistant">
Develop a **Personal Travel Assistant** that remembers your preferences and past trips.
</Card>
<Card title="Chrome Extension" icon="puzzle-piece" href="/examples/chrome-extension">
Add **long-term memory** to ChatGPT, Claude, or Perplexity via the **Mem0 Chrome Extension**.
</Card>
<Card title="YouTube Assistant" icon="video" href="/examples/youtube-assistant">
Integrate **Mem0** into **YouTube's** native UI with personalized responses.
</Card>
<Card title="Memory-Guided Content Writing" icon="pen" href="/examples/memory-guided-content-writing">
Create a **Writing Assistant** that understands and adapts to your unique style.
</Card>
<Card title="Multimodal AI Demo" icon="image" href="/examples/multimodal-demo">
Supercharge AI with **Mem0's multimodal memory** — blend text, images, and more.
</Card>
<Card title="Email Processing" icon="envelope" href="/examples/email_processing">
Use Mem0's memory capabilities to process emails with persistent memory.
</Card>
<Card title="Personalized Research Agent" icon="magnifying-glass" href="/examples/personalized-deep-research">
Build a **Deep Research AI** that remembers your research goals.
</Card>
<Card title="Multi-User Collaboration" icon="users" href="/examples/collaborative-task-agent">
Build collaborative agents with shared memory across multiple users.
</Card>
<Card title="LlamaIndex ReAct Agent" icon="book-open" href="/examples/llama-index-mem0">
Combine **LlamaIndex** and Mem0 to create a **ReAct Agent** with persistent memory.
</Card>
<Card title="LlamaIndex Multi-Agent System" icon="book-open" href="/examples/llamaindex-multiagent-learning-system">
Multi-agent learning system powered by memory.
</Card>
<Card title="Personalized Search with Tavily" icon="search" href="/examples/personalized-search-tavily-mem0">
Build a personalized search experience using Mem0 and Tavily.
</Card>
<Card title="Mem0 as an Agentic Tool" icon="robot" href="/examples/mem0-agentic-tool">
Integrate Mem0's memory capabilities with OpenAI's Agents SDK.
</Card>
<Card title="OpenAI Inbuilt Tools" icon="wrench" href="/examples/openai-inbuilt-tools">
Use Mem0 with OpenAI's Inbuilt Tools to create AI agents with persistent memory.
</Card>
<Card title="OpenAI Voice Demo" icon="microphone" href="/examples/mem0-openai-voice-demo">
Voice-enabled AI agents with persistent memory using OpenAI.
</Card>
<Card title="Healthcare Assistant with Google ADK" icon="heart-pulse" href="/examples/mem0-google-adk-healthcare-assistant">
Build a personalized healthcare assistant with persistent memory using Google ADK.
</Card>
<Card title="Mem0 with Mastra" icon="wand-magic-sparkles" href="/examples/mem0-mastra">
Integrate Mem0 with Mastra for powerful agentic workflows.
</Card>
<Card title="Eliza OS Character" icon="comment" href="/examples/eliza_os">
Build conversational AI characters with persistent memory using Eliza OS.
</Card>
<Card title="AWS Bedrock Example" icon="aws" href="/examples/aws_example">
Use Mem0 with **AWS Bedrock**, **OpenSearch**, and **Neptune Analytics**.
</Card>
<Card title="AWS Neptune Analytics" icon="aws" href="/examples/aws_neptune_analytics_hybrid_store">
Hybrid memory store with **AWS Neptune Analytics** and Bedrock.
</Card>
</CardGroup>
@@ -1,120 +0,0 @@
---
title: "AWS Neptune Analytics"
---
This example demonstrates how to configure and use the `mem0ai` SDK with **AWS Bedrock** and **AWS Neptune Analytics** for persistent memory capabilities in Python.
## Installation
Install the required dependencies to include the Amazon data stack, including **boto3** and **langchain-aws**:
```bash
pip install "mem0ai[graph,extras]"
```
## Environment Setup
Set your AWS environment variables:
```python
import os
# Set these in your environment or notebook
os.environ['AWS_REGION'] = 'us-west-2'
os.environ['AWS_ACCESS_KEY_ID'] = 'AK00000000000000000'
os.environ['AWS_SECRET_ACCESS_KEY'] = 'AS00000000000000000'
# Confirm they are set
print(os.environ['AWS_REGION'])
print(os.environ['AWS_ACCESS_KEY_ID'])
print(os.environ['AWS_SECRET_ACCESS_KEY'])
```
## Configuration and Usage
This sets up Mem0 with:
- [AWS Bedrock for LLM](https://docs.mem0.ai/components/llms/models/aws_bedrock)
- [AWS Bedrock for embeddings](https://docs.mem0.ai/components/embedders/models/aws_bedrock#aws-bedrock)
- [Neptune Analytics as the vector store](https://docs.mem0.ai/components/vectordbs/dbs/neptune_analytics)
- [Neptune Analytics as the graph store](https://docs.mem0.ai/open-source/graph_memory/overview#initialize-neptune-analytics).
```python
import boto3
from mem0.memory.main import Memory
region = 'us-west-2'
neptune_analytics_endpoint = 'neptune-graph://my-graph-identifier'
config = {
"embedder": {
"provider": "aws_bedrock",
"config": {
"model": "amazon.titan-embed-text-v2:0"
}
},
"llm": {
"provider": "aws_bedrock",
"config": {
"model": "us.anthropic.claude-3-7-sonnet-20250219-v1:0",
"temperature": 0.1,
"max_tokens": 2000
}
},
"vector_store": {
"provider": "neptune",
"config": {
"collection_name": "mem0",
"endpoint": neptune_analytics_endpoint,
},
},
"graph_store": {
"provider": "neptune",
"config": {
"endpoint": neptune_analytics_endpoint,
},
},
}
# Initialize the memory system
m = Memory.from_config(config)
```
## Usage
Reference [Notebook example](https://github.com/mem0ai/mem0/blob/main/examples/graph-db-demo/neptune-example.ipynb)
#### Add a memory:
```python
messages = [
{"role": "user", "content": "I'm planning to watch a movie tonight. Any recommendations?"},
{"role": "assistant", "content": "How about a thriller movies? They can be quite engaging."},
{"role": "user", "content": "I'm not a big fan of thriller movies but I love sci-fi movies."},
{"role": "assistant", "content": "Got it! I'll avoid thriller recommendations and suggest sci-fi movies in the future."}
]
# Store inferred memories (default behavior)
result = m.add(messages, user_id="alice", metadata={"category": "movie_recommendations"})
```
#### Search a memory:
```python
relevant_memories = m.search(query, user_id="alice")
```
#### Get all memories:
```python
all_memories = m.get_all(user_id="alice")
```
#### Get a specific memory:
```python
memory = m.get(memory_id)
```
---
## Conclusion
With Mem0 and AWS services like Bedrock and Neptune Analytics, you can build intelligent AI companions that remember, adapt, and personalize their responses over time. This makes them ideal for long-term assistants, tutors, or support bots with persistent memory and natural conversation abilities.
-111
View File
@@ -1,111 +0,0 @@
---
title: Customer Support AI Agent
---
You can create a personalized Customer Support AI Agent using Mem0. This guide will walk you through the necessary steps and provide the complete code to get you started.
## Overview
The Customer Support AI Agent leverages Mem0 to retain information across interactions, enabling a personalized and efficient support experience.
## Setup
Install the necessary packages using pip:
```bash
pip install openai mem0ai
```
## Full Code Example
Below is the simplified code to create and interact with a Customer Support AI Agent using Mem0:
```python
import os
from openai import OpenAI
from mem0 import Memory
# Set the OpenAI API key
os.environ['OPENAI_API_KEY'] = 'sk-xxx'
class CustomerSupportAIAgent:
def __init__(self):
"""
Initialize the CustomerSupportAIAgent with memory configuration and OpenAI client.
"""
config = {
"vector_store": {
"provider": "qdrant",
"config": {
"host": "localhost",
"port": 6333,
}
},
}
self.memory = Memory.from_config(config)
self.client = OpenAI()
self.app_id = "customer-support"
def handle_query(self, query, user_id=None):
"""
Handle a customer query and store the relevant information in memory.
:param query: The customer query to handle.
:param user_id: Optional user ID to associate with the memory.
"""
# Start a streaming chat completion request to the AI
stream = self.client.chat.completions.create(
model="gpt-4",
stream=True,
messages=[
{"role": "system", "content": "You are a customer support AI agent."},
{"role": "user", "content": query}
]
)
# Store the query in memory
self.memory.add(query, user_id=user_id, metadata={"app_id": self.app_id})
# Print the response from the AI in real-time
for chunk in stream:
if chunk.choices[0].delta.content is not None:
print(chunk.choices[0].delta.content, end="")
def get_memories(self, user_id=None):
"""
Retrieve all memories associated with the given customer ID.
:param user_id: Optional user ID to filter memories.
:return: List of memories.
"""
return self.memory.get_all(user_id=user_id)
# Instantiate the CustomerSupportAIAgent
support_agent = CustomerSupportAIAgent()
# Define a customer ID
customer_id = "jane_doe"
# Handle a customer query
support_agent.handle_query("I need help with my recent order. It hasn't arrived yet.", user_id=customer_id)
```
### Fetching Memories
You can fetch all the memories at any point in time using the following code:
```python
memories = support_agent.get_memories(user_id=customer_id)
for m in memories['results']:
print(m['memory'])
```
### Key Points
- **Initialization**: The CustomerSupportAIAgent class is initialized with the necessary memory configuration and OpenAI client setup.
- **Handling Queries**: The handle_query method sends a query to the AI and stores the relevant information in memory.
- **Retrieving Memories**: The get_memories method fetches all stored memories associated with a customer.
### Conclusion
As the conversation progresses, Mem0's memory automatically updates based on the interactions, providing a continuously improving personalized support experience.
-202
View File
@@ -1,202 +0,0 @@
---
title: Personal AI Travel Assistant
---
Create a personalized AI Travel Assistant using Mem0. This guide provides step-by-step instructions and the complete code to get you started.
## Overview
The Personalized AI Travel Assistant uses Mem0 to store and retrieve information across interactions, enabling a tailored travel planning experience. It integrates with OpenAI's GPT-4 model to provide detailed and context-aware responses to user queries.
## Setup
Install the required dependencies using pip:
```bash
pip install openai mem0ai
```
## Full Code Example
Here's the complete code to create and interact with a Personalized AI Travel Assistant using Mem0:
<CodeGroup>
```python After v1.1
import os
from openai import OpenAI
from mem0 import Memory
# Set the OpenAI API key
os.environ['OPENAI_API_KEY'] = "sk-xxx"
config = {
"llm": {
"provider": "openai",
"config": {
"model": "gpt-4.1-nano-2025-04-14",
"temperature": 0.1,
"max_tokens": 2000,
}
},
"embedder": {
"provider": "openai",
"config": {
"model": "text-embedding-3-large"
}
},
"vector_store": {
"provider": "qdrant",
"config": {
"collection_name": "test",
"embedding_model_dims": 3072,
}
},
"version": "v1.1",
}
class PersonalTravelAssistant:
def __init__(self):
self.client = OpenAI()
self.memory = Memory.from_config(config)
self.messages = [{"role": "system", "content": "You are a personal AI Assistant."}]
def ask_question(self, question, user_id):
# Fetch previous related memories
previous_memories = self.search_memories(question, user_id=user_id)
# Build the prompt
system_message = "You are a personal AI Assistant."
if previous_memories:
prompt = f"{system_message}\n\nUser input: {question}\nPrevious memories: {', '.join(previous_memories)}"
else:
prompt = f"{system_message}\n\nUser input: {question}"
# Generate response using Responses API
response = self.client.responses.create(
model="gpt-4.1-nano-2025-04-14",
input=prompt
)
# Extract answer from the response
answer = response.output[0].content[0].text
# Store the question in memory
self.memory.add(question, user_id=user_id)
return answer
def get_memories(self, user_id):
memories = self.memory.get_all(user_id=user_id)
return [m['memory'] for m in memories['results']]
def search_memories(self, query, user_id):
memories = self.memory.search(query, user_id=user_id)
return [m['memory'] for m in memories['results']]
# Usage example
user_id = "traveler_123"
ai_assistant = PersonalTravelAssistant()
def main():
while True:
question = input("Question: ")
if question.lower() in ['q', 'exit']:
print("Exiting...")
break
answer = ai_assistant.ask_question(question, user_id=user_id)
print(f"Answer: {answer}")
memories = ai_assistant.get_memories(user_id=user_id)
print("Memories:")
for memory in memories:
print(f"- {memory}")
print("-----")
if __name__ == "__main__":
main()
```
```python Before v1.1
import os
from openai import OpenAI
from mem0 import Memory
# Set the OpenAI API key
os.environ['OPENAI_API_KEY'] = 'sk-xxx'
class PersonalTravelAssistant:
def __init__(self):
self.client = OpenAI()
self.memory = Memory()
self.messages = [{"role": "system", "content": "You are a personal AI Assistant."}]
def ask_question(self, question, user_id):
# Fetch previous related memories
previous_memories = self.search_memories(question, user_id=user_id)
prompt = question
if previous_memories:
prompt = f"User input: {question}\n Previous memories: {previous_memories}"
self.messages.append({"role": "user", "content": prompt})
# Generate response using gpt-4.1-nano
response = self.client.chat.completions.create(
model="gpt-4.1-nano-2025-04-14"2025-04-14",
messages=self.messages
)
answer = response.choices[0].message.content
self.messages.append({"role": "assistant", "content": answer})
# Store the question in memory
self.memory.add(question, user_id=user_id)
return answer
def get_memories(self, user_id):
memories = self.memory.get_all(user_id=user_id)
return [m['memory'] for m in memories.get('results', [])]
def search_memories(self, query, user_id):
memories = self.memory.search(query, user_id=user_id)
return [m['memory'] for m in memories.get('results', [])]
# Usage example
user_id = "traveler_123"
ai_assistant = PersonalTravelAssistant()
def main():
while True:
question = input("Question: ")
if question.lower() in ['q', 'exit']:
print("Exiting...")
break
answer = ai_assistant.ask_question(question, user_id=user_id)
print(f"Answer: {answer}")
memories = ai_assistant.get_memories(user_id=user_id)
print("Memories:")
for memory in memories:
print(f"- {memory}")
print("-----")
if __name__ == "__main__":
main()
```
</CodeGroup>
## Key Components
- **Initialization**: The `PersonalTravelAssistant` class is initialized with the OpenAI client and Mem0 memory setup.
- **Asking Questions**: The `ask_question` method sends a question to the AI, incorporates previous memories, and stores new information.
- **Memory Management**: The `get_memories` and search_memories methods handle retrieval and searching of stored memories.
## Usage
1. Set your OpenAI API key in the environment variable.
2. Instantiate the `PersonalTravelAssistant`.
3. Use the `main()` function to interact with the assistant in a loop.
## Conclusion
This Personalized AI Travel Assistant leverages Mem0's memory capabilities to provide context-aware responses. As you interact with it, the assistant learns and improves, offering increasingly personalized travel advice and information.
Binary file not shown.

After

Width:  |  Height:  |  Size: 59 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 91 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 44 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 31 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 92 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 118 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 48 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 75 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 52 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 31 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 66 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 75 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 178 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 426 KiB

+10
View File
@@ -11,6 +11,10 @@ Mem0 seamlessly integrates with popular AI frameworks and tools to enhance your
- Framework-agnostic memory layer
- Simple integration with existing AI tools and frameworks
<Callout type="tip" icon="puzzle-piece">
**Universal Integration**: Use <Link href="/platform/mem0-mcp">Mem0 MCP</Link> for a standardized protocol that works with ANY AI client.
</Callout>
Here are the available integrations for Mem0:
## Integrations
@@ -33,6 +37,12 @@ Here are the available integrations for Mem0:
>
Monitor and analyze Mem0 operations with comprehensive AI agent analytics and LLM observability.
</Card>
<Card
title="Camel AI"
href="/integrations/camel-ai"
>
Use Mem0Storage to persist Camel multi-agent conversations and share cloud memory across agents.
</Card>
<Card
title="LangChain"
icon={
+8 -6
View File
@@ -163,10 +163,12 @@ Organize your monitoring with structured sessions:
4. **Tagging**: Use tags to organize different types of memory operations
5. **Environment Separation**: Use different projects or tags for dev/staging/prod
## Help
<CardGroup cols={2}>
<Card title="CrewAI Integration" icon="users" href="/integrations/crewai">
Monitor multi-agent CrewAI systems
</Card>
<Card title="LangChain Integration" icon="link" href="/integrations/langchain">
Track LangChain agent performance
</Card>
</CardGroup>
- [AgentOps Documentation](https://docs.agentops.ai/)
- [AgentOps Dashboard](https://app.agentops.ai/)
- [Mem0 Platform](https://app.mem0.ai/)
<Snippet file="get-help.mdx" />
+8 -5
View File
@@ -195,9 +195,12 @@ Customize the integration to your needs:
- **Memory Search**: Configure search relevance and result count
- **Memory Formatting**: Support for various OpenAI message formats
## Help
<CardGroup cols={2}>
<Card title="OpenAI Agents SDK" icon="cube" href="/integrations/openai-agents-sdk">
Build agents with OpenAI SDK and Mem0
</Card>
<Card title="Mastra Integration" icon="star" href="/integrations/mastra">
Create intelligent agents with Mastra framework
</Card>
</CardGroup>
- [Agno Documentation](https://docs.agno.com/introduction)
- [Mem0 Platform](https://app.mem0.ai/)
<Snippet file="get-help.mdx" />
+8 -2
View File
@@ -130,6 +130,12 @@ By integrating AutoGen with Mem0, you've created a conversational AI system with
This integration enables the creation of more intelligent and personalized AI agents for various applications, such as customer support, virtual assistants, and interactive chatbots.
## Help
<CardGroup cols={2}>
<Card title="CrewAI Integration" icon="users" href="/integrations/crewai">
Build multi-agent systems with CrewAI and Mem0
</Card>
<Card title="LangGraph Integration" icon="diagram-project" href="/integrations/langgraph">
Create stateful workflows with LangGraph
</Card>
</CardGroup>
<Snippet file="get-help.mdx" />
+8 -7
View File
@@ -120,11 +120,12 @@ all_memories = m.get_all(user_id="alice")
4. **User-specific Memory Spaces**: Memories are isolated per user ID
5. **Persistent Memory Context**: Maintain and recall history across sessions
## Help
- [AWS Bedrock Documentation](https://docs.aws.amazon.com/bedrock/)
- [Amazon OpenSearch Service Docs](https://docs.aws.amazon.com/opensearch-service/)
- [Mem0 Platform](https://app.mem0.ai)
<Snippet file="get-help.mdx" />
<CardGroup cols={2}>
<Card title="AWS Bedrock Cookbook" icon="aws" href="/cookbooks/integrations/aws-bedrock">
Complete guide to using Bedrock with Mem0
</Card>
<Card title="Neptune Analytics Cookbook" icon="database" href="/cookbooks/integrations/neptune-analytics">
Build graph memory with AWS Neptune
</Card>
</CardGroup>
+144
View File
@@ -0,0 +1,144 @@
---
title: Camel AI
description: "Plug Mem0 cloud memory into Camel's agents with the built‑in Mem0Storage."
partnerBadge: "Camel AI"
---
# Camel AI integration
Connect Camel's agent framework to Mem0 so every agent can persist and recall conversation context across sessions with minimal setup.
<Info>
**Prerequisites**
- Mem0: `MEM0_API_KEY` (or self-hosted endpoint), `pip install mem0ai`
- Camel AI: `pip install camel-ai` (requires Python 3.9+)
- Optional: OpenAI API key if you run LLM-backed agents
</Info>
<Note>Camel provides a Python SDK today. A TypeScript path is not available yet.</Note>
## Configure credentials
<Tabs>
<Tab title="Mem0">
<Steps>
<Step title="Export your API key">
```bash
export MEM0_API_KEY="sk-..."
```
</Step>
<Step title="(Self-host) Point to your Mem0 API">
```bash
export MEM0_BASE_URL="https://your-mem0-domain"
```
</Step>
</Steps>
</Tab>
<Tab title="Camel">
<Steps>
<Step title="Install Camel with Mem0 dependency">
```bash
pip install "camel-ai>=0.2.0" mem0ai
```
</Step>
<Step title="(Optional) Add your model credentials">
```bash
export OPENAI_API_KEY="sk-openai..."
```
</Step>
</Steps>
</Tab>
</Tabs>
<Tip>
Mem0Storage reads `MEM0_API_KEY` automatically. Pass `api_key` explicitly only when you need to override the environment.
</Tip>
## Wire Mem0 into a Camel agent
<Steps>
<Step title="Create a Mem0-backed memory store">
```python
import os
from camel.storages import Mem0Storage
mem0_store = Mem0Storage(
api_key=os.environ.get("MEM0_API_KEY"),
agent_id="travel_agent",
user_id="alice",
metadata={"source": "camel-demo"},
)
```
</Step>
<Step title="Attach it to Camel memory">
```python
from camel.memories import ChatHistoryMemory, ScoreBasedContextCreator
from camel.utils import OpenAITokenCounter
from camel.types import ModelType
memory = ChatHistoryMemory(
context_creator=ScoreBasedContextCreator(
token_counter=OpenAITokenCounter(ModelType.GPT_4O_MINI),
token_limit=1024,
),
storage=mem0_store,
agent_id="travel_agent",
)
```
</Step>
<Step title="Let your agent read and write Mem0">
```python
from camel.agents import ChatAgent
from camel.messages import BaseMessage
agent = ChatAgent(
system_message=BaseMessage.make_assistant_message(
role_name="Agent",
content="You are a helpful travel assistant. Reuse stored memories."
)
)
agent.memory = memory
response = agent.step(
BaseMessage.make_user_message(
role_name="User",
content="I prefer boutique hotels in Paris."
)
)
print(response.msgs[0].content)
```
</Step>
</Steps>
<Info icon="check">
Run `python camel_mem0_demo.py` (or the snippet above in a REPL). You should see the agent respond and the memory persisted to Mem0. Re-running with a new prompt should include the stored preference.
</Info>
## Verify the integration
- Mem0 dashboard shows new memories under `agent_id=travel_agent` and `user_id=alice`.
- `mem0_store.load()` returns the records you just wrote.
- Camel agent replies reference prior user preferences on subsequent runs.
## Troubleshooting
- **Missing MEM0_API_KEY** — set `export MEM0_API_KEY="sk-..."` or pass `api_key` into `Mem0Storage`.
- **No memories returned** — ensure `agent_id`/`user_id` in your query match what you used when writing.
- **Network errors to Mem0** — if self-hosting, set `MEM0_BASE_URL` to your deployment URL.
<CardGroup cols={2}>
<Card
title="Memory types in Mem0"
description="Choose between chat history and semantic search for your Camel agents."
icon="sparkles"
href="/core-concepts/memory-types"
/>
<Card
title="Try LangChain next"
description="Wire the same Mem0 project into LangChain workflows."
icon="rocket"
href="/integrations/langchain"
/>
</CardGroup>
+8 -5
View File
@@ -160,9 +160,12 @@ if __name__ == "__main__":
By combining CrewAI with Mem0, you can create sophisticated AI systems that maintain context and provide personalized experiences while leveraging the power of autonomous agents.
## Help
<CardGroup cols={2}>
<Card title="AutoGen Integration" icon="users" href="/integrations/autogen">
Build multi-agent systems with AutoGen and Mem0
</Card>
<Card title="LangGraph Integration" icon="diagram-project" href="/integrations/langgraph">
Create stateful agent workflows with memory
</Card>
</CardGroup>
- [CrewAI Documentation](https://docs.crewai.com/)
- [Mem0 Platform](https://app.mem0.ai/)
<Snippet file="get-help.mdx" />
+8 -1
View File
@@ -31,4 +31,11 @@ Mem0 brings a robust memory layer to Dify AI, empowering your AI agents with per
Enhance your Dify-powered AI with Mem0 and transform your conversational experiences. Start integrating intelligent memory management today and give your agents the context they need to excel!
[Explore Mem0 on Dify Marketplace](https://marketplace.dify.ai/plugins/yevanchen/mem0)
<CardGroup cols={2}>
<Card title="Flowise Integration" icon="share-nodes" href="/integrations/flowise">
Build visual AI workflows with Flowise
</Card>
<Card title="LangChain Integration" icon="link" href="/integrations/langchain">
Create LangChain-powered applications
</Card>
</CardGroup>
+8 -5
View File
@@ -436,9 +436,12 @@ By integrating ElevenLabs Conversational AI with Mem0, you can create voice agen
- Reduced need for users to repeat information
- Long-term relationship building between users and AI agents
## Help
<CardGroup cols={2}>
<Card title="LiveKit Integration" icon="video" href="/integrations/livekit">
Build real-time voice and video agents
</Card>
<Card title="Pipecat Integration" icon="waveform" href="/integrations/pipecat">
Create voice-first AI applications
</Card>
</CardGroup>
- [ElevenLabs Conversational AI Documentation](https://elevenlabs.io/docs/api-reference/conversational-ai)
- [Mem0 Platform](https://app.mem0.ai/)
<Snippet file="get-help.mdx" />
+8 -7
View File
@@ -115,11 +115,12 @@ Additional settings available in [Mem0 Project Settings](https://app.mem0.ai/das
2. **Memory Organization**: Utilize projects and organizations for better memory management
3. **Regular Maintenance**: Monitor and clean up unused memories periodically
## Help
<CardGroup cols={2}>
<Card title="LangChain Integration" icon="link" href="/integrations/langchain">
Build LangChain-powered flows with memory
</Card>
<Card title="Dify Integration" icon="blocks" href="/integrations/dify">
Create AI workflows with Dify platform
</Card>
</CardGroup>
- [Flowise Documentation](https://flowiseai.com/docs)
- [Flowise GitHub Repository](https://github.com/FlowiseAI/Flowise)
- [Flowise Website](https://flowiseai.com/)
- [Mem0 Platform](https://app.mem0.ai/)
<Snippet file="get-help.mdx" />
+8 -5
View File
@@ -285,9 +285,12 @@ os.environ["GOOGLE_CLOUD_PROJECT"] = "your-project-id"
os.environ["GOOGLE_CLOUD_LOCATION"] = "us-central1"
```
## Help
<CardGroup cols={2}>
<Card title="Healthcare Agent Cookbook" icon="heart-pulse" href="/cookbooks/integrations/healthcare-google-adk">
Build HIPAA-compliant healthcare agents with Google ADK
</Card>
<Card title="OpenAI Agents SDK" icon="cube" href="/integrations/openai-agents-sdk">
Compare with OpenAI's agent framework
</Card>
</CardGroup>
- [Google ADK Documentation](https://google.github.io/adk-docs/)
- [Mem0 Platform](https://app.mem0.ai/)
<Snippet file="get-help.mdx" />
+8 -5
View File
@@ -131,9 +131,12 @@ For detailed information on this integration, refer to the official [Keywords AI
Integrating Mem0 with Keywords AI provides a powerful combination for building AI applications with persistent memory and comprehensive observability. This integration enables more personalized user experiences while providing insights into your application's memory usage.
## Help
<CardGroup cols={2}>
<Card title="OpenAI Agents SDK" icon="cube" href="/integrations/openai-agents-sdk">
Build monitored agents with OpenAI SDK
</Card>
<Card title="AgentOps Integration" icon="chart-line" href="/integrations/agentops">
Monitor agent performance with AgentOps
</Card>
</CardGroup>
- [Keywords AI Documentation](https://docs.keywordsai.co)
- [Mem0 Platform](https://app.mem0.ai/)
<Snippet file="get-help.mdx" />
+8 -2
View File
@@ -320,6 +320,12 @@ All tools are implemented as Langchain `StructuredTool` instances, making them c
Each tool provides structured input validation through Pydantic models and returns consistent responses that can be processed by your agent.
## Help
<CardGroup cols={2}>
<Card title="LangChain Integration" icon="link" href="/integrations/langchain">
Build conversational agents with LangChain and Mem0
</Card>
<Card title="LangGraph Integration" icon="diagram-project" href="/integrations/langgraph">
Create stateful workflows with LangGraph
</Card>
</CardGroup>
<Snippet file="get-help.mdx" />
+8 -5
View File
@@ -161,10 +161,13 @@ if __name__ == "__main__":
By integrating LangChain with Mem0, you can build a personalized Travel Agent AI that can maintain context across interactions and provide tailored travel recommendations and assistance.
## Help
<CardGroup cols={2}>
<Card title="LangGraph Integration" icon="diagram-project" href="/integrations/langgraph">
Build stateful agents with LangGraph and Mem0
</Card>
<Card title="LangChain Tools" icon="wrench" href="/integrations/langchain-tools">
Use Mem0 as LangChain tools for agent workflows
</Card>
</CardGroup>
- [LangChain Documentation](https://python.langchain.com/)
- [Mem0 Platform](https://app.mem0.ai/)
<Snippet file="get-help.mdx" />
+8 -5
View File
@@ -163,9 +163,12 @@ if __name__ == "__main__":
By integrating LangGraph with Mem0, you can build a personalized Customer Support AI Agent that can maintain context across interactions and provide personalized assistance.
## Help
<CardGroup cols={2}>
<Card title="LangChain Integration" icon="link" href="/integrations/langchain">
Build conversational agents with LangChain and Mem0
</Card>
<Card title="CrewAI Integration" icon="users" href="/integrations/crewai">
Create multi-agent systems with CrewAI
</Card>
</CardGroup>
- [LangGraph Documentation](https://python.langchain.com/docs/langgraph)
- [Mem0 Platform](https://app.mem0.ai/)
<Snippet file="get-help.mdx" />
+8 -6
View File
@@ -228,10 +228,12 @@ logger = logging.getLogger("memory_voice_agent")
- Check the logs for any issues with API keys, connectivity, or memory operations.
- Ensure your `.env` file is correctly configured and loaded.
<CardGroup cols={2}>
<Card title="ElevenLabs Integration" icon="volume" href="/integrations/elevenlabs">
Build conversational voice agents with ElevenLabs
</Card>
<Card title="Pipecat Integration" icon="waveform" href="/integrations/pipecat">
Create real-time voice applications with Pipecat
</Card>
</CardGroup>
## Help
- [LiveKit Documentation](https://docs.livekit.io/)
- [Mem0 Platform](https://app.mem0.ai/)
<Snippet file="get-help.mdx" />

Some files were not shown because too many files have changed in this diff Show More