fix(sdk): removing deprecating param from our sdk and docs changes with it (#4740)

This commit is contained in:
Kartik
2026-04-12 00:34:58 +05:30
committed by GitHub
parent 3882af7450
commit e44b46ef2e
138 changed files with 1186 additions and 2840 deletions
+1 -2
View File
@@ -47,8 +47,7 @@ Provide at least one message or direct memory string. Most callers supply `messa
| `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. |
| `enable_graph` | boolean (default `false`) | Optional | Set to `true` to create entity nodes and relationships for knowledge graph. |
> \* 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.
+1 -2
View File
@@ -62,8 +62,7 @@ To retrieve graph memory relationships between entities, pass `output_format="v1
memories = client.get_all(
filters={
"user_id": "alex"
},
output_format="v1.1"
}
)
```
@@ -32,7 +32,7 @@ Example with the mem0 Python package:
```python
from mem0 import MemoryClient
client = MemoryClient(org_id='YOUR_ORG_ID', project_id='YOUR_PROJECT_ID')
client = MemoryClient(api_key="your-api-key")
```
</Tab>
@@ -41,10 +41,7 @@ client = MemoryClient(org_id='YOUR_ORG_ID', project_id='YOUR_PROJECT_ID')
```javascript
import { MemoryClient } from "mem0ai";
const client = new MemoryClient({
organizationId: "YOUR_ORG_ID",
projectId: "YOUR_PROJECT_ID"
});
const client = new MemoryClient({ apiKey: "your-api-key" });
```
</Tab>
@@ -172,7 +169,7 @@ All project methods are available in async mode:
from mem0 import AsyncMemoryClient
async def manage_project():
client = AsyncMemoryClient(org_id='YOUR_ORG_ID', project_id='YOUR_PROJECT_ID')
client = AsyncMemoryClient(api_key="your-api-key")
# All methods support async/await
project_info = await client.project.get()
+1 -1
View File
@@ -15,7 +15,7 @@ Mem0 supports LangChain as a provider for vector store integration. LangChain pr
```python Python
import os
from mem0 import Memory
from langchain_community.vectorstores import Chroma
from langchain_chroma import Chroma
from langchain_openai import OpenAIEmbeddings
# Initialize a LangChain vector store
@@ -129,13 +129,13 @@ async def search_memories(
user_id=USER_ID,
limit=5,
threshold=0.7, # Higher threshold for more relevant results
)
# Format and return the results
if not results.get('results', []):
return "I don't have any relevant memories about this topic."
memories = [f"• {result['memory']}" for result in results.get('results', [])]
return "Here's what I remember that might be relevant:\n" + "\n".join(memories)
```
@@ -345,13 +345,13 @@ async def search_memories(
user_id=USER_ID,
limit=5,
threshold=0.7, # Higher threshold for more relevant results
)
# Format and return the results
if not results.get('results', []):
return "I don't have any relevant memories about this topic."
memories = [f"• {result['memory']}" for result in results.get('results', [])]
return "Here's what I remember that might be relevant:\n" + "\n".join(memories)
@@ -85,7 +85,6 @@ const messages = [
await client.add(messages, {
user_id: "alice",
version: "v2",
});
```
</CodeGroup>
+37 -16
View File
@@ -70,7 +70,6 @@
"platform/features/v2-memory-filters",
"platform/features/entity-scoped-memory",
"platform/features/async-client",
"platform/features/async-mode-default-change",
"platform/features/multimodal-support",
"platform/features/custom-categories"
]
@@ -94,8 +93,7 @@
"pages": [
"platform/features/direct-import",
"platform/features/memory-export",
"platform/features/timestamp",
"platform/features/expiration-date"
"platform/features/timestamp"
]
},
{
@@ -122,8 +120,6 @@
"icon": "arrow-right",
"pages": [
"migration/oss-to-platform",
"migration/v0-to-v1",
"migration/breaking-changes",
"migration/api-changes"
]
},
@@ -133,16 +129,6 @@
"pages": [
"platform/contribute"
]
},
{
"group": "Release Notes",
"icon": "rocket",
"pages": [
"changelog/highlights",
"changelog/sdk",
"changelog/platform",
"changelog/openclaw"
]
}
]
},
@@ -182,7 +168,7 @@
"open-source/features/reranker-search",
"open-source/features/async-memory",
"open-source/features/multimodal-support",
"open-source/features/custom-fact-extraction-prompt",
"open-source/features/custom-instructions",
"open-source/features/custom-update-memory-prompt",
"open-source/features/rest-api",
"open-source/features/openai_compatibility"
@@ -562,6 +548,21 @@
]
}
]
},
{
"tab": "Release Notes",
"groups": [
{
"group": "Release Notes",
"icon": "rocket",
"pages": [
"changelog/highlights",
"changelog/sdk",
"changelog/platform",
"changelog/openclaw"
]
}
]
}
]
}
@@ -612,6 +613,26 @@
]
},
"redirects": [
{
"source": "/migration/breaking-changes",
"destination": "/"
},
{
"source": "/migration/v0-to-v1",
"destination": "/"
},
{
"source": "/platform/features/expiration-date",
"destination": "/"
},
{
"source": "/platform/features/async-mode-default-change",
"destination": "/"
},
{
"source": "/open-source/features/custom-fact-extraction-prompt",
"destination": "/open-source/features/custom-instructions"
},
{
"source": "/changelog",
"destination": "/changelog/highlights"
+1 -1
View File
@@ -268,7 +268,7 @@ memories = mem0.search(
{"categories": {"contains": "travel"}}
]
},
limit=5
top_k=5
)
# Configure agent with custom model settings
+1 -2
View File
@@ -16,7 +16,7 @@ Combining Mem0 with Keywords AI allows you to:
4. Optimize token usage and reduce costs
<Note>
You can get your Mem0 API key, user_id, and org_id from the <a href="https://app.mem0.ai/" rel="nofollow">Mem0 dashboard</a>. These are required for proper integration.
You can get your Mem0 API key from the <a href="https://app.mem0.ai/" rel="nofollow">Mem0 dashboard</a>.
</Note>
## Setup and Configuration
@@ -107,7 +107,6 @@ response = client.chat.completions.create(
extra_body={
"mem0_params": {
"user_id": "test_user",
"org_id": "org_1",
"api_key": os.environ.get("MEM0_API_KEY"),
"add_memories": {
"messages": messages,
+1 -4
View File
@@ -29,10 +29,7 @@ import os
os.environ["MEM0_API_KEY"] = "your-api-key"
client = MemoryClient(
org_id=your_org_id,
project_id=your_project_id
)
client = MemoryClient()
```
## Available Tools
+2 -2
View File
@@ -45,7 +45,7 @@ mem0 = MemoryClient()
@function_tool
def search_memory(query: str, user_id: str) -> str:
"""Search through past conversations and memories"""
memories = mem0.search(query, user_id=user_id, limit=3)
memories = mem0.search(query, user_id=user_id, top_k=3)
if memories and memories.get('results'):
return "\n".join([f"- {mem['memory']}" for mem in memories['results']])
return "No relevant memories found."
@@ -215,7 +215,7 @@ Customize memory behavior:
memories = mem0.search(
query="travel preferences",
user_id="alex",
limit=5 # Number of memories to retrieve
top_k=5 # Number of memories to retrieve
)
# Add metadata to memories
+1 -1
View File
@@ -155,7 +155,7 @@ openclaw mem0 stats
| Key | Type | Default | Description |
|-----|------|---------|-------------|
| `customPrompt` | `string` | *(built-in)* | Extraction prompt for memory processing |
| `customInstructions` | `string` | *(built-in)* | Extraction prompt for memory processing |
| `oss.embedder.provider` | `string` | `"openai"` | Embedding provider (`"openai"`, `"ollama"`, etc.) |
| `oss.embedder.config` | `object` | — | Provider config: `apiKey`, `model`, `baseURL` |
| `oss.vectorStore.provider` | `string` | `"memory"` | Vector store (`"memory"`, `"qdrant"`, `"chroma"`, etc.) |
+1 -1
View File
@@ -52,7 +52,7 @@ npm install @mem0/vercel-ai-provider
> **Note**: The `openai` provider is set as default. Consider using `MEM0_API_KEY` and `OPENAI_API_KEY` as environment variables for security.
> **Note**: The `mem0Config` is optional. It is used to set the global config for the Mem0 Client (eg. `user_id`, `agent_id`, `app_id`, `run_id`, `org_id`, `project_id` etc).
> **Note**: The `mem0Config` is optional. It is used to set the global config for the Mem0 Client (eg. `user_id`, `agent_id`, `app_id`, `run_id` etc).
3. Add Memories to Enhance Context:
+1 -1
View File
@@ -86,7 +86,7 @@ Key differentiators:
- [Reranker Search](https://docs.mem0.ai/open-source/features/reranker-search): Enhanced search results with reranking models
- [Async Memory](https://docs.mem0.ai/open-source/features/async-memory): Asynchronous memory operations for better performance
- [Multimodal Support](https://docs.mem0.ai/open-source/features/multimodal-support): Handle text, images, and documents in self-hosted setup
- [Custom Fact Extraction](https://docs.mem0.ai/open-source/features/custom-fact-extraction-prompt): Tailor information extraction for specific use cases
- [Custom Instructions](https://docs.mem0.ai/open-source/features/custom-instructions): Tailor information extraction for specific use cases
- [Custom Memory Update Prompt](https://docs.mem0.ai/open-source/features/custom-update-memory-prompt): Customize how memories are updated and merged
- [REST API Server](https://docs.mem0.ai/open-source/features/rest-api): FastAPI-based server with core operations and OpenAPI documentation
- [OpenAI Compatibility](https://docs.mem0.ai/open-source/features/openai_compatibility): Seamless integration with OpenAI-compatible APIs
+2 -2
View File
@@ -319,7 +319,7 @@ config = {
"graph_store": {...},
"version": "v1.0", # ❌ v1.0 no longer supported
"history_db_path": "...",
"custom_fact_extraction_prompt": "..."
"custom_instructions": "..."
}
```
@@ -336,7 +336,7 @@ config = {
},
"version": "v1.1", # ✅ v1.1+ only
"history_db_path": "...",
"custom_fact_extraction_prompt": "...",
"custom_instructions": "...",
"custom_update_memory_prompt": "..." # ✅ NEW: Custom update prompt
}
```
-383
View File
@@ -1,383 +0,0 @@
---
title: Breaking Changes in v1.0.0
description: 'Complete list of breaking changes when upgrading from v0.x to v1.0.0 '
icon: "triangle-exclamation"
iconType: "solid"
---
<Warning>
**Important:** This page lists all breaking changes. Please review carefully before upgrading.
</Warning>
## API Version Changes
### Removed v1.0 API Support
**Breaking Change:** The v1.0 API format is completely removed and no longer supported.
#### Before (v0.x)
```python
# This was supported in v0.x
config = {
"version": "v1.0" # ❌ No longer supported
}
result = m.add(
"memory content",
user_id="alice"
)
```
#### After (v1.0.0 )
```python
# v1.1 is the minimum supported version
config = {
"version": "v1.1" # ✅ Required minimum
}
result = m.add(
"memory content",
user_id="alice"
)
```
**Error Message:**
```
ValueError: The v1.0 API format is no longer supported in mem0ai 1.0.0+.
Please use v1.1 format which returns a dict with 'results' key.
```
## Parameter Removals
### 1. version Parameter in Method Calls
**Breaking Change:** Version parameter removed from method calls.
#### Before (v0.x)
```python
result = m.add("content", user_id="alice", version="v1.0")
```
#### After (v1.0.0 )
```python
result = m.add("content", user_id="alice")
```
### 2. async_mode Parameter (Platform Client)
**Change:** For `MemoryClient` (Platform API), `async_mode` now defaults to `True` but can still be configured.
#### Before (v0.x)
```python
from mem0 import MemoryClient
client = MemoryClient(api_key="your-key")
result = client.add("content", user_id="alice", async_mode=True)
result = client.add("content", user_id="alice", async_mode=False)
```
#### After (v1.0.0 )
```python
from mem0 import MemoryClient
client = MemoryClient(api_key="your-key")
# async_mode now defaults to True, but you can still override it
result = client.add("content", user_id="alice") # Uses async_mode=True by default
# You can still explicitly set it to False if needed
result = client.add("content", user_id="alice", async_mode=False)
```
## Response Format Changes
### Standardized Response Structure
**Breaking Change:** All responses now return a standardized dictionary format.
#### Before (v0.x)
```python
# Could return different formats based on version configuration
result = m.add("content", user_id="alice")
# With v1.0: Returns [{"id": "...", "memory": "...", "event": "ADD"}]
# With v1.1: Returns {"results": [{"id": "...", "memory": "...", "event": "ADD"}]}
```
#### After (v1.0.0 )
```python
# Always returns standardized format
result = m.add("content", user_id="alice")
# Always returns: {"results": [{"id": "...", "memory": "...", "event": "ADD"}]}
# Access results consistently
for memory in result["results"]:
print(memory["memory"])
```
## Configuration Changes
### Version Configuration
**Breaking Change:** Default API version changed.
#### Before (v0.x)
```python
# v1.0 was supported
config = {
"version": "v1.0" # ❌ No longer supported
}
```
#### After (v1.0.0 )
```python
# v1.1 is minimum, v1.1 is default
config = {
"version": "v1.1" # ✅ Minimum supported
}
# Or omit for default
config = {
# version defaults to v1.1
}
```
### Memory Configuration
**Breaking Change:** Some configuration options have changed defaults.
#### Before (v0.x)
```python
from mem0 import Memory
# Default configuration in v0.x
m = Memory() # Used default settings suitable for v0.x
```
#### After (v1.0.0 )
```python
from mem0 import Memory
# Default configuration optimized for v1.0.0
m = Memory() # Uses v1.1+ optimized defaults
# Explicit configuration recommended
config = {
"version": "v1.1",
"vector_store": {
"provider": "qdrant",
"config": {
"host": "localhost",
"port": 6333
}
}
}
m = Memory.from_config(config)
```
## Method Signature Changes
### Search Method
**Enhanced but backward compatible:**
#### Before (v0.x)
```python
results = m.search(
"query",
user_id="alice",
filters={"key": "value"} # Simple key-value only
)
```
#### After (v1.0.0 )
```python
# Basic usage remains the same
results = m.search("query", user_id="alice")
# Enhanced filtering available (optional)
results = m.search(
"query",
user_id="alice",
filters={
"AND": [
{"key": "value"},
{"score": {"gte": 0.8}}
]
},
rerank=True # New parameter
)
```
## Error Handling Changes
### New Error Types
**Breaking Change:** More specific error types and messages.
#### Before (v0.x)
```python
try:
result = m.add("content", user_id="alice", version="v1.0")
except Exception as e:
print(f"Generic error: {e}")
```
#### After (v1.0.0 )
```python
try:
result = m.add("content", user_id="alice")
except ValueError as e:
if "v1.0 API format is no longer supported" in str(e):
# Handle version error specifically
print("Please upgrade your code to use v1.1+ format")
else:
print(f"Value error: {e}")
except Exception as e:
print(f"Unexpected error: {e}")
```
### Validation Changes
**Breaking Change:** Stricter parameter validation.
#### Before (v0.x)
```python
# Some invalid parameters might have been ignored
result = m.add(
"content",
user_id="alice",
invalid_param="ignored" # Might have been silently ignored
)
```
#### After (v1.0.0 )
```python
# Strict validation - unknown parameters cause errors
try:
result = m.add(
"content",
user_id="alice",
invalid_param="value" # ❌ Will raise TypeError
)
except TypeError as e:
print(f"Invalid parameter: {e}")
```
## Import Changes
### No Breaking Changes in Imports
**Good News:** Import statements remain the same.
```python
# These imports work in both v0.x and v1.0.0
from mem0 import Memory, AsyncMemory
from mem0 import MemoryConfig
```
## Dependency Changes
### Minimum Python Version
**Potential Breaking Change:** Check Python version requirements.
#### Before (v0.x)
- Python 3.8+ supported
#### After (v1.0.0 )
- Python 3.9+ required (check current requirements)
### Package Dependencies
**Breaking Change:** Some dependencies updated with potential breaking changes.
```bash
# Check for conflicts after upgrade
pip install --upgrade mem0ai
pip check # Verify no dependency conflicts
```
## Data Migration
### Database Schema
**Good News:** No database schema changes required.
- Existing memories remain compatible
- No data migration required
- Vector store data unchanged
### Memory Format
**Good News:** Memory storage format unchanged.
- Existing memories work with v1.0.0
- Search continues to work with old memories
- No re-indexing required
## Testing Changes
### Test Updates Required
**Breaking Change:** Update tests for new response format.
#### Before (v0.x)
```python
def test_add_memory():
result = m.add("content", user_id="alice")
assert isinstance(result, list) # ❌ No longer true
assert len(result) > 0
```
#### After (v1.0.0 )
```python
def test_add_memory():
result = m.add("content", user_id="alice")
assert isinstance(result, dict) # ✅ Always dict
assert "results" in result # ✅ Always has results key
assert len(result["results"]) > 0
```
## Rollback Considerations
### Safe Rollback Process
If you need to rollback:
```bash
# 1. Rollback package
pip install mem0ai==0.1.20 # Last stable v0.x
# 2. Revert code changes
git checkout previous_commit
# 3. Test functionality
python test_mem0_functionality.py
```
### Data Safety
- **Safe:** Memories stored in v0.x format work with v1.0.0
- **Safe:** Rollback doesn't lose data
- **Safe:** Vector store data remains intact
## Next Steps
1. **Review all breaking changes** in your codebase
2. **Update method calls** to remove deprecated parameters
3. **Update response handling** to use standardized format
4. **Test thoroughly** with your existing data
5. **Update error handling** for new error types
<CardGroup cols={2}>
<Card title="Migration Guide" icon="arrow-right" href="/migration/v0-to-v1">
Step-by-step migration instructions
</Card>
<Card title="API Changes" icon="code" href="/migration/api-changes">
Complete API reference changes
</Card>
</CardGroup>
<Warning>
**Need Help?** If you encounter issues during migration, check our [GitHub Discussions](https://github.com/mem0ai/mem0/discussions) or community support channels.
</Warning>
+10 -6
View File
@@ -81,6 +81,10 @@ client = MemoryClient(api_key="m0-...")
**Critical Change**: Platform uses v2 endpoints that require filtering parameters to be nested inside a `filters` dictionary.
</Warning>
<Note>
The `limit` parameter has been removed in favor of `top_k` across all SDKs. Update any code using `limit=` to use `top_k=` instead.
</Note>
| Method | Open Source | Platform |
| ------ | ----------- | -------- |
| `search()` | `m.search(query, user_id="alex")` | `client.search(query, filters={"user_id": "alex"})` |
@@ -121,18 +125,18 @@ Note: `add()` and `delete()` methods remain unchanged. The `update()` method is
<CodeGroup>
```python Open Source (Old)
# Get all memories for a user
memories = m.get_all(user_id="alex", limit=10)
memories = m.get_all(user_id="alex", top_k=10)
# Get memories with pagination
memories = m.get_all(user_id="alex", limit=5, offset=10)
memories = m.get_all(user_id="alex", top_k=5, offset=10)
```
```python Platform (New)
# Get all memories for a user
memories = client.get_all(filters={"user_id": "alex"}, limit=10)
memories = client.get_all(filters={"user_id": "alex"}, top_k=10)
# Get memories with pagination
memories = client.get_all(filters={"user_id": "alex"}, limit=5, offset=10)
memories = client.get_all(filters={"user_id": "alex"}, top_k=5, offset=10)
```
</CodeGroup>
</Accordion>
@@ -283,7 +287,7 @@ The Platform introduces powerful capabilities not available in OSS:
"user preferences",
filters={"user_id": "alex"},
rerank=True, # Platform exclusive
limit=5
top_k=5
)
# Search with keyword expansion
@@ -335,7 +339,7 @@ The Platform introduces powerful capabilities not available in OSS:
{"timestamp": {"gte": "2024-01-01"}}
]
},
limit=100
top_k=100
)
# Monitor usage patterns
-481
View File
@@ -1,481 +0,0 @@
---
title: Migrating from v0.x to v1.0.0
description: 'Complete guide to upgrade your Mem0 implementation to version 1.0.0 '
icon: "arrow-right"
iconType: "solid"
---
<Warning>
**Breaking Changes Ahead!** Mem0 1.0.0 introduces several breaking changes. Please read this guide carefully before upgrading.
</Warning>
## Overview
Mem0 1.0.0 is a major release that modernizes the API, improves performance, and adds powerful new features. This guide will help you migrate your existing v0.x implementation to the new version.
## Key Changes Summary
| Feature | v0.x | v1.0.0 | Migration Required |
|---------|------|-------------|-------------------|
| API Version | v1.0 supported | v1.0 **removed**, v1.1+ only | ✅ Yes |
| Async Mode (Platform Client) | Optional/manual | Defaults to `True`, configurable | ⚠️ Partial |
| Metadata Filtering | Basic | Enhanced with operators | ⚠️ Optional |
| Reranking | Not available | Full support | ⚠️ Optional |
## Step-by-Step Migration
### 1. Update Installation
```bash
# Update to the latest version
pip install --upgrade mem0ai
```
### 2. Remove Deprecated Parameters
#### Before (v0.x)
```python
from mem0 import Memory
# These parameters are no longer supported
m = Memory()
result = m.add(
"I love pizza",
user_id="alice",
version="v1.0" # ❌ REMOVED
)
```
#### After (v1.0.0 )
```python
from mem0 import Memory
# Clean, simplified API
m = Memory()
result = m.add(
"I love pizza",
user_id="alice"
# version parameter removed
)
```
### 3. Update Configuration
#### Before (v0.x)
```python
config = {
"vector_store": {
"provider": "qdrant",
"config": {
"host": "localhost",
"port": 6333
}
},
"version": "v1.0" # ❌ No longer supported
}
m = Memory.from_config(config)
```
#### After (v1.0.0 )
```python
config = {
"vector_store": {
"provider": "qdrant",
"config": {
"host": "localhost",
"port": 6333
}
},
"version": "v1.1" # ✅ v1.1 is the minimum supported version
}
m = Memory.from_config(config)
```
### 4. Handle Response Format Changes
#### Before (v0.x)
```python
# Response could be a list or dict depending on version
result = m.add("I love coffee", user_id="alice")
if isinstance(result, list):
# Handle list format
for item in result:
print(item["memory"])
else:
# Handle dict format
print(result["results"])
```
#### After (v1.0.0 )
```python
# Response is always a standardized dict with "results" key
result = m.add("I love coffee", user_id="alice")
# Always access via "results" key
for item in result["results"]:
print(item["memory"])
```
### 5. Update Search Operations
#### Before (v0.x)
```python
# Basic search
results = m.search("What do I like?", user_id="alice")
# With filters
results = m.search(
"What do I like?",
user_id="alice",
filters={"category": "food"}
)
```
#### After (v1.0.0 )
```python
# Same basic search API
results = m.search("What do I like?", user_id="alice")
# Enhanced filtering with operators (optional upgrade)
results = m.search(
"What do I like?",
user_id="alice",
filters={
"AND": [
{"category": "food"},
{"rating": {"gte": 8}}
]
}
)
# New: Reranking support (optional)
results = m.search(
"What do I like?",
user_id="alice",
rerank=True # Requires reranker configuration
)
```
### 6. Platform Client async_mode Default Changed
**Change:** For `MemoryClient`, the `async_mode` parameter now defaults to `True` for better performance.
#### Before (v0.x)
```python
from mem0 import MemoryClient
client = MemoryClient(api_key="your-key")
# Had to explicitly set async_mode
result = client.add("I enjoy hiking", user_id="alice", async_mode=True)
```
#### After (v1.0.0 )
```python
from mem0 import MemoryClient
client = MemoryClient(api_key="your-key")
# async_mode now defaults to True (best performance)
result = client.add("I enjoy hiking", user_id="alice")
# You can still override if needed for synchronous processing
result = client.add("I enjoy hiking", user_id="alice", async_mode=False)
```
## Configuration Migration
### Basic Configuration
#### Before (v0.x)
```python
config = {
"vector_store": {
"provider": "qdrant",
"config": {
"host": "localhost",
"port": 6333
}
},
"llm": {
"provider": "openai",
"config": {
"model": "gpt-3.5-turbo",
"api_key": "your-key"
}
},
"version": "v1.0"
}
```
#### After (v1.0.0 )
```python
config = {
"vector_store": {
"provider": "qdrant",
"config": {
"host": "localhost",
"port": 6333
}
},
"llm": {
"provider": "openai",
"config": {
"model": "gpt-3.5-turbo",
"api_key": "your-key"
}
},
"version": "v1.1", # Minimum supported version
# New optional features
"reranker": {
"provider": "cohere",
"config": {
"model": "rerank-english-v3.0",
"api_key": "your-cohere-key"
}
}
}
```
### Enhanced Features (Optional)
```python
# Take advantage of new features
config = {
"vector_store": {
"provider": "qdrant",
"config": {
"host": "localhost",
"port": 6333
}
},
"llm": {
"provider": "openai",
"config": {
"model": "gpt-4",
"api_key": "your-key"
}
},
"embedder": {
"provider": "openai",
"config": {
"model": "text-embedding-3-small",
"api_key": "your-key"
}
},
"reranker": {
"provider": "sentence_transformer",
"config": {
"model": "cross-encoder/ms-marco-MiniLM-L-6-v2"
}
},
"version": "v1.1"
}
```
## Error Handling Migration
### Before (v0.x)
```python
try:
result = m.add("memory", user_id="alice", version="v1.0")
except Exception as e:
print(f"Error: {e}")
```
### After (v1.0.0 )
```python
try:
result = m.add("memory", user_id="alice")
except ValueError as e:
if "v1.0 API format is no longer supported" in str(e):
print("Please upgrade your code to use v1.1+ format")
else:
print(f"Error: {e}")
except Exception as e:
print(f"Unexpected error: {e}")
```
## Testing Your Migration
### 1. Basic Functionality Test
```python
def test_basic_functionality():
m = Memory()
# Test add
result = m.add("I love testing", user_id="test_user")
assert "results" in result
assert len(result["results"]) > 0
# Test search
search_results = m.search("testing", user_id="test_user")
assert "results" in search_results
# Test get_all
all_memories = m.get_all(user_id="test_user")
assert "results" in all_memories
print("✅ Basic functionality test passed")
test_basic_functionality()
```
### 2. Enhanced Features Test
```python
def test_enhanced_features():
config = {
"reranker": {
"provider": "sentence_transformer",
"config": {
"model": "cross-encoder/ms-marco-MiniLM-L-6-v2"
}
}
}
m = Memory.from_config(config)
# Test reranking
m.add("I love advanced features", user_id="test_user")
results = m.search("features", user_id="test_user", rerank=True)
assert "results" in results
# Test enhanced filtering
results = m.search(
"features",
user_id="test_user",
filters={"user_id": {"eq": "test_user"}}
)
assert "results" in results
print("✅ Enhanced features test passed")
test_enhanced_features()
```
## Common Migration Issues
### Issue 1: Version Error
**Error:**
```
ValueError: The v1.0 API format is no longer supported in mem0ai 1.0.0+
```
**Solution:**
```python
# Remove version parameters or set to v1.1+
config = {
# ... other config
"version": "v1.1" # or remove entirely for default
}
```
### Issue 2: Response Format Error
**Error:**
```
KeyError: 'results'
```
**Solution:**
```python
# Always access response via "results" key
result = m.add("memory", user_id="alice")
memories = result["results"] # Not result directly
```
### Issue 3: Parameter Error
**Error:**
```
TypeError: add() got an unexpected keyword argument 'output_format'
```
**Solution:**
```python
# Remove deprecated parameters
result = m.add(
"memory",
user_id="alice"
# Remove: version
)
```
## Rollback Plan
If you encounter issues during migration:
### 1. Immediate Rollback
```bash
# Downgrade to last v0.x version
pip install mem0ai==0.1.20 # Replace with your last working version
```
### 2. Gradual Migration
```python
# Test both versions side by side
import mem0_v0 # Your old version
import mem0 # New version
def compare_results(query, user_id):
old_results = mem0_v0.search(query, user_id=user_id)
new_results = mem0.search(query, user_id=user_id)
print("Old format:", old_results)
print("New format:", new_results["results"])
```
## Performance Improvements
### Before (v0.x)
```python
# Sequential operations
result1 = m.add("memory 1", user_id="alice")
result2 = m.add("memory 2", user_id="alice")
result3 = m.search("query", user_id="alice")
```
### After (v1.0.0 )
```python
# Better async performance
async def batch_operations():
async_memory = AsyncMemory()
# Concurrent operations
results = await asyncio.gather(
async_memory.add("memory 1", user_id="alice"),
async_memory.add("memory 2", user_id="alice"),
async_memory.search("query", user_id="alice")
)
return results
```
## Next Steps
1. **Complete the migration** using this guide
2. **Test thoroughly** with your existing data
3. **Explore new features** like enhanced filtering and reranking
4. **Update your documentation** to reflect the new API
5. **Monitor performance** and optimize as needed
<CardGroup cols={2}>
<Card title="Breaking Changes" icon="triangle-exclamation" href="/migration/breaking-changes">
Detailed list of all breaking changes
</Card>
<Card title="API Changes" icon="code" href="/migration/api-changes">
Complete API reference changes
</Card>
</CardGroup>
<Info>
Need help with migration? Check our [GitHub Discussions](https://github.com/mem0ai/mem0/discussions) or reach out to our community for support.
</Info>
+2 -2
View File
@@ -240,7 +240,7 @@ async_openai_client = AsyncOpenAI()
async_memory = AsyncMemory()
async def chat_with_memories(message: str, user_id: str = "default_user") -> str:
search_result = await async_memory.search(query=message, user_id=user_id, limit=3)
search_result = await async_memory.search(query=message, user_id=user_id, top_k=3)
relevant_memories = search_result["results"]
memories_str = "\n".join(f"- {entry['memory']}" for entry in relevant_memories)
@@ -326,7 +326,7 @@ async def add_memory(messages: list, user_id: str):
@app.get("/memories/search")
async def search_memories(query: str, user_id: str, limit: int = 10):
try:
result = await memory.search(query=query, user_id=user_id, limit=limit)
result = await memory.search(query=query, user_id=user_id, top_k=limit)
return {"status": "success", "data": result}
except Exception as exc:
raise HTTPException(status_code=500, detail=str(exc))
@@ -1,13 +1,13 @@
---
title: Custom Fact Extraction Prompt
title: Custom Instructions
description: Tailor fact extraction so Mem0 stores only the details you care about.
icon: "wand-magic-sparkles"
---
Custom fact extraction prompts let you decide exactly which facts Mem0 records from a conversation. Define a focused prompt, give a few examples, and Mem0 will add only the memories that match your use case.
Custom instructions let you decide exactly which facts Mem0 records from a conversation. Define a focused prompt, give a few examples, and Mem0 will add only the memories that match your use case.
<Info>
**You’ll use this when…**
**You'll use this when...**
- A project needs domain-specific facts (order numbers, customer info) without storing casual chatter.
- You already have a clear schema for memories and want the LLM to follow it.
- You must prevent irrelevant details from entering long-term storage.
@@ -17,6 +17,10 @@ Custom fact extraction prompts let you decide exactly which facts Mem0 records f
Prompts that are too broad cause unrelated facts to slip through. Keep instructions tight and test them with real transcripts.
</Warning>
<Note>
The `custom_fact_extraction_prompt` parameter has been renamed to `custom_instructions`. If you are upgrading from an older version, update your configuration accordingly.
</Note>
---
## Feature anatomy
@@ -24,13 +28,13 @@ Custom fact extraction prompts let you decide exactly which facts Mem0 records f
- **Prompt instructions:** Describe which entities or phrases to keep. Specific guidance keeps the extractor focused.
- **Few-shot examples:** Show positive and negative cases so the model copies the right format.
- **Structured output:** Responses return JSON with a `facts` array that Mem0 converts into individual memories.
- **LLM configuration:** `custom_fact_extraction_prompt` (Python) or `customPrompt` (TypeScript) lives alongside your model settings.
- **LLM configuration:** `custom_instructions` (Python) or `customInstructions` (TypeScript) lives alongside your model settings.
<AccordionGroup>
<Accordion title="Prompt blueprint">
1. State the allowed fact types.
2. Include short examples that mirror production messages.
3. Show both empty (`[]`) and populated outputs.
1. State the allowed fact types.
2. Include short examples that mirror production messages.
3. Show both empty (`[]`) and populated outputs.
4. Remind the model to return JSON with a `facts` key only.
</Accordion>
</AccordionGroup>
@@ -43,8 +47,8 @@ Custom fact extraction prompts let you decide exactly which facts Mem0 records f
<CodeGroup>
```python Python
custom_fact_extraction_prompt = """
Please only extract entities containing customer support information, order details, and user information.
custom_instructions = """
Please only extract entities containing customer support information, order details, and user information.
Here are some few shot examples:
Input: Hi.
@@ -67,8 +71,8 @@ Return the facts and customer information in a json format as shown above.
```
```ts TypeScript
const customPrompt = `
Please only extract entities containing customer support information, order details, and user information.
const customInstructions = `
Please only extract entities containing customer support information, order details, and user information.
Here are some few shot examples:
Input: Hi.
@@ -110,7 +114,7 @@ config = {
"max_tokens": 2000,
}
},
"custom_fact_extraction_prompt": custom_fact_extraction_prompt,
"custom_instructions": custom_instructions,
"version": "v1.1"
}
@@ -131,7 +135,7 @@ const config = {
maxTokens: 1500,
},
},
customPrompt: customPrompt,
customInstructions: customInstructions,
};
const memory = new Memory(config);
@@ -263,7 +263,7 @@ Please note to return the IDs in the output from the input IDs only and do not g
- Log each decision so product teams can review why a change happened.
<Note>
The prompt works alongside `custom_fact_extraction_prompt`—fact extraction identifies candidate facts, and the update prompt decides how to merge them into long-term storage.
The prompt works alongside `custom_instructions`—fact extraction identifies candidate facts, and the update prompt decides how to merge them into long-term storage.
</Note>
---
@@ -288,7 +288,7 @@ Please note to return the IDs in the output from the input IDs only and do not g
## Compare prompts
| Feature | `custom_update_memory_prompt` | `custom_fact_extraction_prompt` |
| Feature | `custom_update_memory_prompt` | `custom_instructions` |
| --- | --- | --- |
| Primary job | Decide memory actions (ADD/UPDATE/DELETE/NONE) | Pull facts from user and assistant messages |
| Inputs | Retrieved facts + existing memory entries | Raw conversation turns |
@@ -297,7 +297,7 @@ Please note to return the IDs in the output from the input IDs only and do not g
---
<CardGroup cols={2}>
<Card title="Design Fact Extraction" icon="sparkles" href="/open-source/features/custom-fact-extraction-prompt">
<Card title="Design Fact Extraction" icon="sparkles" href="/open-source/features/custom-instructions">
Coordinate both prompts so fact extraction feeds clean inputs into the update flow.
</Card>
<Card title="Build Email Automations" icon="inbox" href="/cookbooks/operations/email-automation">
+4 -4
View File
@@ -94,7 +94,7 @@ memory.add(conversation, user_id="demo-user")
results = memory.search(
"Who did Alice meet at GraphConf?",
user_id="demo-user",
limit=3,
top_k=3,
rerank=True,
)
@@ -146,7 +146,7 @@ await memory.add(conversation, { userId: "demo-user" });
const results = await memory.search(
"Who did Alice meet at GraphConf?",
{ userId: "demo-user", limit: 3, rerank: true }
{ userId: "demo-user", topK: 3, rerank: true }
);
results.results.forEach((hit) => {
@@ -204,7 +204,7 @@ const config = {
username: process.env.NEO4J_USERNAME!,
password: process.env.NEO4J_PASSWORD!,
},
customPrompt: "Please only capture people, organisations, and project links.",
customInstructions: "Please only capture people, organisations, and project links.",
}
};
@@ -265,7 +265,7 @@ Monitor graph growth, especially on free tiers, by periodically cleaning dormant
## Decision Points
- Select the graph store that fits your deployment (managed Aura vs. self-hosted Neo4j vs. AWS Neptune vs. local Kuzu vs. Apache AGE on PostgreSQL).
- Decide when to enable graph writes per request; routine conversations may stay vector-only to save latency.
- Decide whether to include a graph store in your config; routine conversations may stay vector-only to save latency.
- Set a policy for pruning stale relationships so your graph stays fast and affordable.
## Provider setup
@@ -131,7 +131,7 @@ print(response.choices[0].message.content)
| `run_id` | `str` | Optional session/run identifier for short-lived flows. |
| `metadata` | `dict` | Store extra fields alongside each memory entry. |
| `filters` | `dict` | Restrict retrieval to specific memories while responding. |
| `limit` | `int` | Cap how many memories Mem0 pulls into the context (default 10). |
| `top_k` | `int` | Cap how many memories Mem0 pulls into the context (default 10). |
Other request fields mirror OpenAI’s chat completion API.
+1 -1
View File
@@ -30,7 +30,7 @@ Mem0 Open Source ships with capabilities that adapt memory behavior for producti
<Card title="Multimodal Support" icon="image" href="/open-source/features/multimodal-support">
Process images, audio, and video memories.
</Card>
<Card title="Custom Fact Extraction" icon="wand-magic-sparkles" href="/open-source/features/custom-fact-extraction-prompt">
<Card title="Custom Instructions" icon="wand-magic-sparkles" href="/open-source/features/custom-instructions">
Tailor how facts are extracted from text.
</Card>
</CardGroup>
@@ -321,7 +321,7 @@ results = m.search(
]
},
rerank=True,
limit=20
top_k=20
)
```
@@ -366,7 +366,7 @@ results = m.search(
user_id="reader123",
filters={"content_type": "book_recommendation"},
rerank=True,
limit=10
top_k=10
)
for result in results["results"]:
+2 -2
View File
@@ -230,7 +230,7 @@ Mem0 offers granular configuration across vector stores, LLMs, embedders, and hi
| --- | --- | --- |
| `historyDbPath` | Path to history database | `"{mem0_dir}/history.db"` |
| `version` | API version | `"v1.0"` |
| `customPrompt` | Custom processing prompt | `undefined` |
| `customInstructions` | Custom processing prompt | `undefined` |
</Accordion>
<Accordion title="History store">
| Parameter | Description | Default |
@@ -273,7 +273,7 @@ const config = {
}
},
disableHistory: false,
customPrompt: "I'm a virtual assistant. I'm here to help you with your queries."
customInstructions: "I'm a virtual assistant. I'm here to help you with your queries."
};
```
</Accordion>
+26 -26
View File
@@ -183,7 +183,7 @@
"x-code-samples": [
{
"lang": "Python",
"source": "# To use the Python SDK, install the package:\n# pip install mem0ai\n\nfrom mem0 import MemoryClient\nclient = MemoryClient(api_key=\"your_api_key\", org_id=\"your_org_id\", project_id=\"your_project_id\")\nusers = client.users()\nprint(users)"
"source": "# To use the Python SDK, install the package:\n# pip install mem0ai\n\nfrom mem0 import MemoryClient\nclient = MemoryClient(api_key=\"your_api_key\")\nusers = client.users()\nprint(users)"
},
{
"lang": "JavaScript",
@@ -717,7 +717,7 @@
"x-code-samples": [
{
"lang": "Python",
"source": "# To use the Python SDK, install the package:\n# pip install mem0ai\n\nfrom mem0 import MemoryClient\n\nclient = MemoryClient(api_key=\"your_api_key\", org_id=\"your_org_id\", project_id=\"your_project_id\")\n\njson_schema = {pydantic_json_schema}\nfilters = {\n \"AND\": [\n {\"user_id\": \"alex\"}\n ]\n}\n\nresponse = client.create_memory_export(\n schema=json_schema,\n filters=filters\n)\nprint(response)"
"source": "# To use the Python SDK, install the package:\n# pip install mem0ai\n\nfrom mem0 import MemoryClient\n\nclient = MemoryClient(api_key=\"your_api_key\")\n\njson_schema = {pydantic_json_schema}\nfilters = {\n \"AND\": [\n {\"user_id\": \"alex\"}\n ]\n}\n\nresponse = client.create_memory_export(\n schema=json_schema,\n filters=filters\n)\nprint(response)"
},
{
"lang": "JavaScript",
@@ -845,7 +845,7 @@
"x-code-samples": [
{
"lang": "Python",
"source": "# To use the Python SDK, install the package:\n# pip install mem0ai\n\nfrom mem0 import MemoryClient\n\nclient = MemoryClient(api_key=\"your_api_key\", org_id=\"your_org_id\", project_id=\"project_id\")\n\nmemory_export_id = \"<memory_export_id>\"\n\nresponse = client.get_memory_export(memory_export_id=memory_export_id)\nprint(response)"
"source": "# To use the Python SDK, install the package:\n# pip install mem0ai\n\nfrom mem0 import MemoryClient\n\nclient = MemoryClient(api_key=\"your_api_key\")\n\nmemory_export_id = \"<memory_export_id>\"\n\nresponse = client.get_memory_export(memory_export_id=memory_export_id)\nprint(response)"
},
{
"lang": "JavaScript",
@@ -1096,7 +1096,7 @@
"x-code-samples": [
{
"lang": "Python",
"source": "# To use the Python SDK, install the package:\n# pip install mem0ai\n\nfrom mem0 import MemoryClient\nclient = MemoryClient(api_key=\"your_api_key\", org_id=\"your_org_id\", project_id=\"your_project_id\")\n\n# Retrieve memories for a specific user\nuser_memories = client.get_all(user_id=\"<user_id>\")\n\nprint(user_memories)"
"source": "# To use the Python SDK, install the package:\n# pip install mem0ai\n\nfrom mem0 import MemoryClient\nclient = MemoryClient(api_key=\"your_api_key\")\n\n# Retrieve memories for a specific user\nuser_memories = client.get_all(user_id=\"<user_id>\")\n\nprint(user_memories)"
},
{
"lang": "JavaScript",
@@ -1203,11 +1203,11 @@
"x-code-samples": [
{
"lang": "Python",
"source": "# To use the Python SDK, install the package:\n# pip install mem0ai\n\nfrom mem0 import MemoryClient\n\nclient = MemoryClient(api_key=\"your_api_key\", org_id=\"your_org_id\", project_id=\"your_project_id\")\n\nmessages = [\n {\"role\": \"user\", \"content\": \"<user-message>\"},\n {\"role\": \"assistant\", \"content\": \"<assistant-response>\"}\n]\n\nclient.add(messages, user_id=\"<user-id>\", version=\"v2\")"
"source": "# To use the Python SDK, install the package:\n# pip install mem0ai\n\nfrom mem0 import MemoryClient\n\nclient = MemoryClient(api_key=\"your_api_key\")\n\nmessages = [\n {\"role\": \"user\", \"content\": \"<user-message>\"},\n {\"role\": \"assistant\", \"content\": \"<assistant-response>\"}\n]\n\nclient.add(messages, user_id=\"<user-id>\")"
},
{
"lang": "JavaScript",
"source": "// To use the JavaScript SDK, install the package:\n// npm i mem0ai\n\nimport MemoryClient from 'mem0ai';\nconst client = new MemoryClient({ apiKey: \"your-api-key\" });\n\nconst messages = [\n { role: \"user\", content: \"Hi, I'm Alex. I'm a vegetarian and I'm allergic to nuts.\" },\n { role: \"assistant\", content: \"Hello Alex! I've noted that you're a vegetarian and have a nut allergy. I'll keep this in mind for any food-related recommendations or discussions.\" }\n];\n\nclient.add(messages, { user_id: \"<user_id>\", version: \"v2\" })\n .then(result => console.log(result))\n .catch(error => console.error(error));"
"source": "// To use the JavaScript SDK, install the package:\n// npm i mem0ai\n\nimport MemoryClient from 'mem0ai';\nconst client = new MemoryClient({ apiKey: \"your-api-key\" });\n\nconst messages = [\n { role: \"user\", content: \"Hi, I'm Alex. I'm a vegetarian and I'm allergic to nuts.\" },\n { role: \"assistant\", content: \"Hello Alex! I've noted that you're a vegetarian and have a nut allergy. I'll keep this in mind for any food-related recommendations or discussions.\" }\n];\n\nclient.add(messages, { user_id: \"<user_id>\" })\n .then(result => console.log(result))\n .catch(error => console.error(error));"
},
{
"lang": "cURL",
@@ -1232,7 +1232,7 @@
"tags": [
"memories"
],
"description": "Delete memories by filter. At least one filter is required — previously omitting all filters silently deleted everything; now it returns a validation error.",
"description": "Delete memories by filter. At least one filter is required \u2014 previously omitting all filters silently deleted everything; now it returns a validation error.",
"operationId": "memories_delete",
"parameters": [
{
@@ -1315,15 +1315,15 @@
"x-code-samples": [
{
"lang": "Python",
"source": "# To use the Python SDK, install the package:\n# pip install mem0ai\n\nfrom mem0 import MemoryClient\nclient = MemoryClient(api_key=\"your_api_key\", org_id=\"your_org_id\", project_id=\"your_project_id\")\n\n# Delete all memories for a specific user\nclient.delete_all(user_id=\"<user_id>\")\n\n# Delete all memories for every user in the project (wildcard)\nclient.delete_all(user_id=\"*\")\n\n# Full project wipe — all four filters must be explicitly set to \"*\"\nclient.delete_all(user_id=\"*\", agent_id=\"*\", app_id=\"*\", run_id=\"*\")\n\n# NOTE: Calling delete_all() with no filters raises a validation error.\n# At least one filter is required to prevent accidental data loss."
"source": "# To use the Python SDK, install the package:\n# pip install mem0ai\n\nfrom mem0 import MemoryClient\nclient = MemoryClient(api_key=\"your_api_key\")\n\n# Delete all memories for a specific user\nclient.delete_all(user_id=\"<user_id>\")\n\n# Delete all memories for every user in the project (wildcard)\nclient.delete_all(user_id=\"*\")\n\n# Full project wipe \u2014 all four filters must be explicitly set to \"*\"\nclient.delete_all(user_id=\"*\", agent_id=\"*\", app_id=\"*\", run_id=\"*\")\n\n# NOTE: Calling delete_all() with no filters raises a validation error.\n# At least one filter is required to prevent accidental data loss."
},
{
"lang": "JavaScript",
"source": "// To use the JavaScript SDK, install the package:\n// npm i mem0ai\n\nimport MemoryClient from 'mem0ai';\nconst client = new MemoryClient({ apiKey: \"your-api-key\" });\n\n// Delete all memories for a specific user\nclient.deleteAll({ user_id: \"<user_id>\" })\n .then(result => console.log(result))\n .catch(error => console.error(error));\n\n// Delete all memories for every user in the project (wildcard)\nclient.deleteAll({ user_id: \"*\" })\n .then(result => console.log(result))\n .catch(error => console.error(error));\n\n// Full project wipe — all four filters must be explicitly set to \"*\"\nclient.deleteAll({ user_id: \"*\", agent_id: \"*\", app_id: \"*\", run_id: \"*\" })\n .then(result => console.log(result))\n .catch(error => console.error(error));"
"source": "// To use the JavaScript SDK, install the package:\n// npm i mem0ai\n\nimport MemoryClient from 'mem0ai';\nconst client = new MemoryClient({ apiKey: \"your-api-key\" });\n\n// Delete all memories for a specific user\nclient.deleteAll({ user_id: \"<user_id>\" })\n .then(result => console.log(result))\n .catch(error => console.error(error));\n\n// Delete all memories for every user in the project (wildcard)\nclient.deleteAll({ user_id: \"*\" })\n .then(result => console.log(result))\n .catch(error => console.error(error));\n\n// Full project wipe \u2014 all four filters must be explicitly set to \"*\"\nclient.deleteAll({ user_id: \"*\", agent_id: \"*\", app_id: \"*\", run_id: \"*\" })\n .then(result => console.log(result))\n .catch(error => console.error(error));"
},
{
"lang": "cURL",
"source": "# Delete memories for a specific user\ncurl --request DELETE \\\n --url 'https://api.mem0.ai/v1/memories/?user_id=<user_id>' \\\n --header 'Authorization: Token <api-key>'\n\n# Delete memories for all users (wildcard)\ncurl --request DELETE \\\n --url 'https://api.mem0.ai/v1/memories/?user_id=*' \\\n --header 'Authorization: Token <api-key>'\n\n# Full project wipe — all four filters must be set to *\ncurl --request DELETE \\\n --url 'https://api.mem0.ai/v1/memories/?user_id=*&agent_id=*&app_id=*&run_id=*' \\\n --header 'Authorization: Token <api-key>'"
"source": "# Delete memories for a specific user\ncurl --request DELETE \\\n --url 'https://api.mem0.ai/v1/memories/?user_id=<user_id>' \\\n --header 'Authorization: Token <api-key>'\n\n# Delete memories for all users (wildcard)\ncurl --request DELETE \\\n --url 'https://api.mem0.ai/v1/memories/?user_id=*' \\\n --header 'Authorization: Token <api-key>'\n\n# Full project wipe \u2014 all four filters must be set to *\ncurl --request DELETE \\\n --url 'https://api.mem0.ai/v1/memories/?user_id=*&agent_id=*&app_id=*&run_id=*' \\\n --header 'Authorization: Token <api-key>'"
},
{
"lang": "Go",
@@ -1441,11 +1441,11 @@
"x-code-samples": [
{
"lang": "Python",
"source": "# To use the Python SDK, install the package:\n# pip install mem0ai\n\nfrom mem0 import MemoryClient\nclient = MemoryClient(api_key=\"your_api_key\", org_id=\"your_org_id\", project_id=\"your_project_id\")\n\n# Retrieve memories with filters\nmemories = client.get_all(\n filters={\n \"AND\": [\n {\n \"user_id\": \"alex\"\n },\n {\n \"created_at\": {\n \"gte\": \"2024-07-01\",\n \"lte\": \"2024-07-31\"\n }\n }\n ]\n },\n version=\"v2\"\n)\n\nprint(memories)"
"source": "# To use the Python SDK, install the package:\n# pip install mem0ai\n\nfrom mem0 import MemoryClient\nclient = MemoryClient(api_key=\"your_api_key\")\n\n# Retrieve memories with filters\nmemories = client.get_all(\n filters={\n \"AND\": [\n {\n \"user_id\": \"alex\"\n },\n {\n \"created_at\": {\n \"gte\": \"2024-07-01\",\n \"lte\": \"2024-07-31\"\n }\n }\n ]\n }\n)\n\nprint(memories)"
},
{
"lang": "JavaScript",
"source": "// To use the JavaScript SDK, install the package:\n// npm i mem0ai\n\nimport MemoryClient from 'mem0ai';\nconst client = new MemoryClient({ apiKey: \"your-api-key\" });\n\nconst filters = {\n AND: [\n { user_id: 'alex' },\n { created_at: { gte: '2024-07-01', lte: '2024-07-31' } }\n ]\n};\n\nclient.getAll({ filters, api_version: 'v2' })\n .then(result => console.log(result))\n .catch(error => console.error(error));"
"source": "// To use the JavaScript SDK, install the package:\n// npm i mem0ai\n\nimport MemoryClient from 'mem0ai';\nconst client = new MemoryClient({ apiKey: \"your-api-key\" });\n\nconst filters = {\n AND: [\n { user_id: 'alex' },\n { created_at: { gte: '2024-07-01', lte: '2024-07-31' } }\n ]\n};\n\nclient.getAll({ filters })\n .then(result => console.log(result))\n .catch(error => console.error(error));"
},
{
"lang": "cURL",
@@ -1589,11 +1589,11 @@
"x-code-samples": [
{
"lang": "Python",
"source": "# To use the Python SDK, install the package:\n# pip install mem0ai\n\nfrom mem0 import MemoryClient\nclient = MemoryClient(api_key=\"your_api_key\", org_id=\"your_org_id\", project_id=\"your_project_id\")\n\nquery = \"Your search query here\"\n\nresults = client.search(query, user_id=\"<user_id>\", output_format=\"v1.1\")\nprint(results)"
"source": "# To use the Python SDK, install the package:\n# pip install mem0ai\n\nfrom mem0 import MemoryClient\nclient = MemoryClient(api_key=\"your_api_key\")\n\nquery = \"Your search query here\"\n\nresults = client.search(query, user_id=\"<user_id>\")\nprint(results)"
},
{
"lang": "JavaScript",
"source": "// To use the JavaScript SDK, install the package:\n// npm i mem0ai\n\nimport MemoryClient from 'mem0ai';\nconst client = new MemoryClient({ apiKey: \"your-api-key\" });\n\nconst query = \"Your search query here\";\n\nclient.search(query, { user_id: \"<user_id>\", output_format: \"v1.1\" })\n .then(result => console.log(result))\n .catch(error => console.error(error));"
"source": "// To use the JavaScript SDK, install the package:\n// npm i mem0ai\n\nimport MemoryClient from 'mem0ai';\nconst client = new MemoryClient({ apiKey: \"your-api-key\" });\n\nconst query = \"Your search query here\";\n\nclient.search(query, { user_id: \"<user_id>\" })\n .then(result => console.log(result))\n .catch(error => console.error(error));"
},
{
"lang": "cURL",
@@ -1708,11 +1708,11 @@
"x-code-samples": [
{
"lang": "Python",
"source": "# To use the Python SDK, install the package:\n# pip install mem0ai\n\nfrom mem0 import MemoryClient\nclient = MemoryClient(api_key=\"your_api_key\", org_id=\"your_org_id\", project_id=\"your_project_id\")\n\nquery = \"What do you know about me?\"\nfilters = {\n \"OR\":[\n {\n \"user_id\":\"alex\"\n },\n {\n \"agent_id\":{\n \"in\":[\n \"travel-assistant\",\n \"customer-support\"\n ]\n }\n }\n ]\n}\nclient.search(query, version=\"v2\", filters=filters)"
"source": "# To use the Python SDK, install the package:\n# pip install mem0ai\n\nfrom mem0 import MemoryClient\nclient = MemoryClient(api_key=\"your_api_key\")\n\nquery = \"What do you know about me?\"\nfilters = {\n \"OR\":[\n {\n \"user_id\":\"alex\"\n },\n {\n \"agent_id\":{\n \"in\":[\n \"travel-assistant\",\n \"customer-support\"\n ]\n }\n }\n ]\n}\nclient.search(query, filters=filters)"
},
{
"lang": "JavaScript",
"source": "// To use the JavaScript SDK, install the package:\n// npm i mem0ai\n\nimport MemoryClient from 'mem0ai';\nconst client = new MemoryClient({ apiKey: \"your-api-key\" });\n\nconst query = \"What do you know about me?\";\nconst filters = {\n OR: [\n { user_id: \"alex\" },\n { agent_id: { in: [\"travel-assistant\", \"customer-support\"] } }\n ]\n};\n\nclient.search(query, { api_version: \"v2\", filters })\n .then(result => console.log(result))\n .catch(error => console.error(error));"
"source": "// To use the JavaScript SDK, install the package:\n// npm i mem0ai\n\nimport MemoryClient from 'mem0ai';\nconst client = new MemoryClient({ apiKey: \"your-api-key\" });\n\nconst query = \"What do you know about me?\";\nconst filters = {\n OR: [\n { user_id: \"alex\" },\n { agent_id: { in: [\"travel-assistant\", \"customer-support\"] } }\n ]\n};\n\nclient.search(query, { filters })\n .then(result => console.log(result))\n .catch(error => console.error(error));"
},
{
"lang": "cURL",
@@ -1864,7 +1864,7 @@
"x-code-samples": [
{
"lang": "Python",
"source": "# To use the Python SDK, install the package:\n# pip install mem0ai\n\nfrom mem0 import MemoryClient\nclient = MemoryClient(api_key=\"your_api_key\", org_id=\"your_org_id\", project_id=\"your_project_id\")\n\nmemory = client.get(memory_id=\"<memory_id>\")"
"source": "# To use the Python SDK, install the package:\n# pip install mem0ai\n\nfrom mem0 import MemoryClient\nclient = MemoryClient(api_key=\"your_api_key\")\n\nmemory = client.get(memory_id=\"<memory_id>\")"
},
{
"lang": "JavaScript",
@@ -1989,7 +1989,7 @@
"x-code-samples": [
{
"lang": "Python",
"source": "# To use the Python SDK, install the package:\n# pip install mem0ai\n\nfrom mem0 import MemoryClient\nclient = MemoryClient(api_key=\"your_api_key\", org_id=\"your_org_id\", project_id=\"your_project_id\")\n\n# Update a memory\nmemory_id = \"<memory_id>\"\nclient.update(\n memory_id=memory_id,\n text=\"Your updated memory message here\",\n metadata={\"category\": \"example\"}\n)"
"source": "# To use the Python SDK, install the package:\n# pip install mem0ai\n\nfrom mem0 import MemoryClient\nclient = MemoryClient(api_key=\"your_api_key\")\n\n# Update a memory\nmemory_id = \"<memory_id>\"\nclient.update(\n memory_id=memory_id,\n text=\"Your updated memory message here\",\n metadata={\"category\": \"example\"}\n)"
},
{
"lang": "JavaScript",
@@ -2053,7 +2053,7 @@
"x-code-samples": [
{
"lang": "Python",
"source": "# To use the Python SDK, install the package:\n# pip install mem0ai\n\nfrom mem0 import MemoryClient\nclient = MemoryClient(api_key=\"your_api_key\", org_id=\"your_org_id\", project_id=\"your_project_id\")\n\nmemory_id = \"<memory_id>\"\nclient.delete(memory_id=memory_id)"
"source": "# To use the Python SDK, install the package:\n# pip install mem0ai\n\nfrom mem0 import MemoryClient\nclient = MemoryClient(api_key=\"your_api_key\")\n\nmemory_id = \"<memory_id>\"\nclient.delete(memory_id=memory_id)"
},
{
"lang": "JavaScript",
@@ -2199,7 +2199,7 @@
"x-code-samples": [
{
"lang": "Python",
"source": "# To use the Python SDK, install the package:\n# pip install mem0ai\n\nfrom mem0 import MemoryClient\nclient = MemoryClient(api_key=\"your_api_key\", org_id=\"your_org_id\", project_id=\"your_project_id\")\n\n# Add some message to create history\nmessages = [{\"role\": \"user\", \"content\": \"<user-message>\"}]\nclient.add(messages, user_id=\"<user-id>\")\n\n# Add second message to update history\nmessages.append({\"role\": \"user\", \"content\": \"<user-message>\"})\nclient.add(messages, user_id=\"<user-id>\")\n\n# Get history of how memory changed over time\nmemory_id = \"<memory-id-here>\"\nhistory = client.history(memory_id)"
"source": "# To use the Python SDK, install the package:\n# pip install mem0ai\n\nfrom mem0 import MemoryClient\nclient = MemoryClient(api_key=\"your_api_key\")\n\n# Add some message to create history\nmessages = [{\"role\": \"user\", \"content\": \"<user-message>\"}]\nclient.add(messages, user_id=\"<user-id>\")\n\n# Add second message to update history\nmessages.append({\"role\": \"user\", \"content\": \"<user-message>\"})\nclient.add(messages, user_id=\"<user-id>\")\n\n# Get history of how memory changed over time\nmemory_id = \"<memory-id-here>\"\nhistory = client.history(memory_id)"
},
{
"lang": "JavaScript",
@@ -3608,7 +3608,7 @@
"x-code-samples": [
{
"lang": "Python",
"source": "# To use the Python SDK, install the package:\n# pip install mem0ai\n\nfrom mem0 import MemoryClient\n\nclient = MemoryClient(api_key=\"your_api_key\", org_id=\"your_org_id\", project_id=\"your_project_id\")\n\nresponse = client.get_project()\nprint(response)"
"source": "# To use the Python SDK, install the package:\n# pip install mem0ai\n\nfrom mem0 import MemoryClient\n\nclient = MemoryClient(api_key=\"your_api_key\")\n\nresponse = client.get_project()\nprint(response)"
},
{
"lang": "JavaScript",
@@ -4411,7 +4411,7 @@
"x-code-samples": [
{
"lang": "Python",
"source": "# To use the Python SDK, install the package:\n# pip install mem0ai\n\nfrom mem0 import MemoryClient\nclient = MemoryClient(api_key=\"your_api_key\", org_id=\"your_org_id\", project_id=\"your_project_id\")\n\nupdate_memories = [\n {\n \"memory_id\": \"285ed74b-6e05-4043-b16b-3abd5b533496\",\n \"text\": \"Watches football\"\n },\n {\n \"memory_id\": \"2c9bd859-d1b7-4d33-a6b8-94e0147c4f07\",\n \"text\": \"Likes to travel\"\n }\n]\n\nresponse = client.batch_update(update_memories)\nprint(response)"
"source": "# To use the Python SDK, install the package:\n# pip install mem0ai\n\nfrom mem0 import MemoryClient\nclient = MemoryClient(api_key=\"your_api_key\")\n\nupdate_memories = [\n {\n \"memory_id\": \"285ed74b-6e05-4043-b16b-3abd5b533496\",\n \"text\": \"Watches football\"\n },\n {\n \"memory_id\": \"2c9bd859-d1b7-4d33-a6b8-94e0147c4f07\",\n \"text\": \"Likes to travel\"\n }\n]\n\nresponse = client.batch_update(update_memories)\nprint(response)"
},
{
"lang": "JavaScript",
@@ -4490,7 +4490,7 @@
"x-code-samples": [
{
"lang": "Python",
"source": "# To use the Python SDK, install the package:\n# pip install mem0ai\n\nfrom mem0 import MemoryClient\nclient = MemoryClient(api_key=\"your_api_key\", org_id=\"your_org_id\", project_id=\"your_project_id\")\n\ndelete_memories = [\n {\"memory_id\": \"285ed74b-6e05-4043-b16b-3abd5b533496\"},\n {\"memory_id\": \"2c9bd859-d1b7-4d33-a6b8-94e0147c4f07\"}\n]\n\nresponse = client.batch_delete(delete_memories)\nprint(response)"
"source": "# To use the Python SDK, install the package:\n# pip install mem0ai\n\nfrom mem0 import MemoryClient\nclient = MemoryClient(api_key=\"your_api_key\")\n\ndelete_memories = [\n {\"memory_id\": \"285ed74b-6e05-4043-b16b-3abd5b533496\"},\n {\"memory_id\": \"2c9bd859-d1b7-4d33-a6b8-94e0147c4f07\"}\n]\n\nresponse = client.batch_delete(delete_memories)\nprint(response)"
},
{
"lang": "JavaScript",
@@ -4758,7 +4758,7 @@
"x-code-samples": [
{
"lang": "Python",
"source": "# To use the Python SDK, install the package:\n# pip install mem0ai\n\nfrom mem0 import MemoryClient\nclient = MemoryClient(api_key=\"your_api_key\", org_id=\"your_org_id\", project_id=\"your_project_id\")\n\n# Create a webhook\nwebhook = client.create_webhook(\n url=\"https://your-webhook-url.com\",\n name=\"My Webhook\",\n project_id=\"your_project_id\",\n event_types=[\"memory:add\", \"memory:categorize\"]\n)\nprint(webhook)"
"source": "# To use the Python SDK, install the package:\n# pip install mem0ai\n\nfrom mem0 import MemoryClient\nclient = MemoryClient(api_key=\"your_api_key\")\n\n# Create a webhook\nwebhook = client.create_webhook(\n url=\"https://your-webhook-url.com\",\n name=\"My Webhook\",\n project_id=\"your_project_id\",\n event_types=[\"memory:add\", \"memory:categorize\"]\n)\nprint(webhook)"
},
{
"lang": "JavaScript",
@@ -4998,7 +4998,7 @@
"x-code-samples": [
{
"lang": "Python",
"source": "# To use the Python SDK, install the package:\n# pip install mem0ai\n\nfrom mem0 import MemoryClient\nclient = MemoryClient(api_key=\"your_api_key\", org_id=\"your_org_id\", project_id=\"your_project_id\")\n\n# Delete a webhook\nresponse = client.delete_webhook(webhook_id=\"your_webhook_id\")\nprint(response)"
"source": "# To use the Python SDK, install the package:\n# pip install mem0ai\n\nfrom mem0 import MemoryClient\nclient = MemoryClient(api_key=\"your_api_key\")\n\n# Delete a webhook\nresponse = client.delete_webhook(webhook_id=\"your_webhook_id\")\nprint(response)"
},
{
"lang": "JavaScript",
@@ -5742,4 +5742,4 @@
}
},
"x-original-swagger-version": "2.0"
}
}
+16 -102
View File
@@ -1,6 +1,6 @@
---
title: Advanced Retrieval
description: "Advanced memory search with keyword expansion, intelligent reranking, and precision filtering"
description: "Advanced memory search with intelligent reranking for precise results"
---
## What is Advanced Retrieval?
@@ -9,40 +9,6 @@ Advanced Retrieval gives you precise control over how memories are found and ran
## Search Enhancement Options
### Keyword Search
Expands results to include memories with specific terms, names, and technical keywords.
<Tabs>
<Tab title="When to Use">
- Searching for specific entities, names, or technical terms
- Need comprehensive coverage of a topic
- Want broader recall even if some results are less relevant
- Working with domain-specific terminology
</Tab>
<Tab title="How it Works">
```python Python
# Find memories containing specific food-related terms
results = client.search(
query="What foods should I avoid?",
keyword_search=True,
user_id="user123"
)
# Results might include:
# ✓ "Allergic to peanuts and shellfish"
# ✓ "Lactose intolerant - avoid dairy"
# ✓ "Mentioned avoiding gluten last week"
```
</Tab>
<Tab title="Performance">
- **Latency**: ~10ms additional
- **Recall**: Significantly increased
- **Precision**: Slightly decreased
- **Best for**: Entity search, comprehensive coverage
</Tab>
</Tabs>
### Reranking
Reorders results using deep semantic understanding to put the most relevant memories first.
@@ -77,41 +43,6 @@ results = client.search(
</Tab>
</Tabs>
### Memory Filtering
Filters results to keep only the most precisely relevant memories.
<Tabs>
<Tab title="When to Use">
- Need highly specific, focused results
- Working with large datasets where noise is problematic
- Quality over quantity is essential
- Building production or safety-critical applications
</Tab>
<Tab title="How it Works">
```python Python
# Get only the most relevant dietary restrictions
results = client.search(
query="What are my dietary restrictions?",
filter_memories=True,
user_id="user123"
)
# Before filtering: After filtering:
# • "Allergic to nuts" → • "Allergic to nuts"
# • "Likes Italian food" → • "Vegetarian diet"
# • "Vegetarian diet" →
# • "Eats dinner at 7pm" →
```
</Tab>
<Tab title="Performance">
- **Latency**: 200-300ms additional
- **Precision**: Maximized
- **Recall**: May be reduced
- **Best for**: Focused queries, production systems
</Tab>
</Tabs>
## Real-World Use Cases
<Tabs>
@@ -120,7 +51,6 @@ results = client.search(
# Smart home assistant finding device preferences
results = client.search(
query="How do I like my bedroom temperature?",
keyword_search=True, # Find specific temperature mentions
rerank=True, # Get most recent preferences first
user_id="user123"
)
@@ -133,8 +63,6 @@ results = client.search(
# Find specific product issues with high precision
results = client.search(
query="Problems with premium subscription billing",
keyword_search=True, # Find "premium", "billing", "subscription"
filter_memories=True, # Only billing-related issues
user_id="customer456"
)
@@ -147,11 +75,10 @@ results = client.search(
results = client.search(
query="Patient allergies and contraindications",
rerank=True, # Most important info first
filter_memories=True, # Only medical restrictions
user_id="patient789"
)
# Ensures critical allergy info appears first and filters out non-medical data
# Ensures critical allergy info appears first
```
</Tab>
<Tab title="Learning Platform">
@@ -159,7 +86,6 @@ results = client.search(
# Find learning progress for specific topics
results = client.search(
query="Python programming progress and difficulties",
keyword_search=True, # Find "Python", "programming", specific concepts
rerank=True, # Recent progress first
user_id="student123"
)
@@ -169,63 +95,57 @@ results = client.search(
</Tab>
</Tabs>
## Choosing the Right Combination
## Choosing the Right Configuration
### Recommended Configurations
<CodeGroup>
```python Python
# Fast and broad - good for exploration
# Basic search - good for exploration
def quick_search(query, user_id):
return client.search(
query=query,
keyword_search=True,
user_id=user_id
)
# Balanced - good for most applications
# Reranked search - good for most applications
def standard_search(query, user_id):
return client.search(
query=query,
keyword_search=True,
rerank=True,
user_id=user_id
)
# High precision - good for critical applications
# Reranked search - good for critical applications
def precise_search(query, user_id):
return client.search(
query=query,
rerank=True,
filter_memories=True,
user_id=user_id
)
```
```javascript JavaScript
// Fast and broad - good for exploration
// Basic search - good for exploration
function quickSearch(query, userId) {
return client.search(query, {
user_id: userId,
keyword_search: true
user_id: userId
});
}
// Balanced - good for most applications
// Reranked search - good for most applications
function standardSearch(query, userId) {
return client.search(query, {
user_id: userId,
keyword_search: true,
rerank: true
});
}
// High precision - good for critical applications
// Reranked search - good for critical applications
function preciseSearch(query, userId) {
return client.search(query, {
user_id: userId,
rerank: true,
filter_memories: true
rerank: true
});
}
```
@@ -235,19 +155,15 @@ function preciseSearch(query, userId) {
### Do
- Start simple with just one enhancement and measure impact
- Use keyword search for entity-heavy queries (names, places, technical terms)
- Start simple with basic search and measure impact before enabling reranking
- Use reranking when the top result quality matters most
- Use filtering for production systems where precision is critical
- Handle empty results gracefully when filtering is too aggressive
- Monitor latency and adjust based on your application's needs
- Handle empty results gracefully
### Don't
- Enable all options by default without measuring necessity
- Use filtering for broad exploratory queries
- Enable reranking by default without measuring necessity
- Ignore latency impact in real-time applications
- Forget to handle cases where filtering returns no results
- Use advanced retrieval for simple, fast lookup scenarios
## Performance Guidelines
@@ -261,20 +177,18 @@ import time
start_time = time.time()
results = client.search(
query="user preferences",
keyword_search=True, # +10ms
rerank=True, # +150ms
filter_memories=True, # +250ms
user_id="user123"
)
latency = time.time() - start_time
print(f"Search completed in {latency:.2f}s") # ~0.41s expected
print(f"Search completed in {latency:.2f}s")
```
### Optimization Tips
1. **Cache frequent queries** to avoid repeated advanced processing
2. **Use session-specific search** with `run_id` to reduce search space
3. **Implement fallback logic** when filtering returns empty results
3. **Implement fallback logic** when search returns empty results
4. **Monitor and alert** on search latency patterns
<Snippet file="get-help.mdx" />
@@ -1,197 +0,0 @@
---
title: Async Mode Default Change
description: "The async_mode parameter now defaults to true for all memory additions, changing from synchronous processing."
---
<Note type="warning">
**Important Change**
The `async_mode` parameter defaults to `true` for all memory additions, changing the default API behavior to asynchronous processing.
</Note>
## Overview
The Memory Addition API processes all memory additions asynchronously by default. This change improves performance and scalability by queuing memory operations in the background, allowing your application to continue without waiting for memory processing to complete.
## What's Changing
The parameter `async_mode` will default to `true` instead of `false`.
This means memory additions will be **processed asynchronously** by default - queued for background execution instead of waiting for processing to complete.
## Behavior Comparison
### Old Default Behavior (async_mode = false)
When `async_mode` was set to `false`, the API returned fully processed memory objects immediately:
```json
{
"results": [
{
"id": "de0ee948-af6a-436c-835c-efb6705207de",
"event": "ADD",
"memory": "User Order #1234 was for a 'Nova 2000'",
"structured_attributes": {
"day": 13,
"hour": 16,
"year": 2025,
"month": 10,
"minute": 59,
"quarter": 4,
"is_weekend": false,
"day_of_week": "monday",
"day_of_year": 286,
"week_of_year": 42
}
}
]
}
```
### New Default Behavior (async_mode = true)
With `async_mode` defaulting to `true`, memory processing is queued in the background and the API returns immediately:
```json
{
"results": [
{
"message": "Memory processing has been queued for background execution",
"status": "PENDING",
"event_id": "d7b5282a-0031-4cc2-98ba-5a02d8531e17"
}
]
}
```
## Migration Guide
### If You Need Synchronous Processing
If your integration relies on receiving the processed memory object immediately, you can explicitly set `async_mode` to `false` in your requests:
<CodeGroup>
```python Python
from mem0 import MemoryClient
client = MemoryClient(api_key="your-api-key")
# Explicitly set async_mode=False to preserve synchronous behavior
messages = [
{"role": "user", "content": "I ordered a Nova 2000"}
]
result = client.add(
messages,
user_id="user-123",
async_mode=False # This ensures synchronous processing
)
```
```javascript JavaScript
const { MemoryClient } = require('mem0ai');
const client = new MemoryClient({ apiKey: 'your-api-key' });
// Explicitly set async_mode: false to preserve synchronous behavior
const messages = [
{ role: "user", content: "I ordered a Nova 2000" }
];
const result = await client.add(messages, {
user_id: "user-123",
async_mode: false // This ensures synchronous processing
});
```
```bash cURL
curl -X POST https://api.mem0.ai/v1/memories/ \
-H "Authorization: Token your-api-key" \
-H "Content-Type: application/json" \
-d '{
"messages": [
{"role": "user", "content": "I ordered a Nova 2000"}
],
"user_id": "user-123",
"async_mode": false
}'
```
</CodeGroup>
### If You Want to Adopt Asynchronous Processing
If you want to benefit from the improved performance of asynchronous processing:
1. **Remove** any explicit `async_mode=False` parameters from your code
2. **Use webhooks** to receive notifications when memory processing completes
<Note>
Learn more about [Webhooks](/platform/features/webhooks) for real-time notifications about memory events.
</Note>
## Benefits of Asynchronous Processing
Switching to asynchronous processing provides several advantages:
- **Faster API Response Times**: Your application doesn't wait for memory processing
- **Better Scalability**: Handle more memory additions concurrently
- **Improved User Experience**: Reduced latency in your application
- **Resource Efficiency**: Background processing optimizes server resources
## Important Notes
- The default behavior is now `async_mode=true` for asynchronous processing
- Explicitly set `async_mode=false` if you need synchronous behavior
- Use webhooks to receive notifications when memories are processed
## Monitoring Memory Processing
When using asynchronous mode, use webhooks to receive notifications about memory events:
<Card title="Configure Webhooks" icon="webhook" href="/platform/features/webhooks">
Learn how to set up webhooks for memory processing events
</Card>
You can also retrieve all processed memories at any time:
<CodeGroup>
```python Python
# Retrieve all memories for a user
# Note: get_all now requires filters
memories = client.get_all(filters={"AND": [{"user_id": "user-123"}]})
```
```javascript JavaScript
// Retrieve all memories for a user
// Note: getAll now requires filters
const memories = await client.getAll({ filters: {"AND": [{"user_id": "user-123"}]} });
```
</CodeGroup>
## Need Help?
If you have questions about this change or need assistance updating your integration:
<Snippet file="get-help.mdx" />
## Related Documentation
<CardGroup cols={2}>
<Card title="Async Client" icon="bolt" href="/platform/features/async-client">
Learn about the asynchronous client for Mem0
</Card>
<Card title="Add Memories API" icon="plus" href="/api-reference/memory/add-memories">
View the complete API reference for adding memories
</Card>
<Card title="Webhooks" icon="webhook" href="/platform/features/webhooks">
Configure webhooks for memory processing events
</Card>
<Card title="Memory Operations" icon="gear" href="/core-concepts/memory-operations/add">
Understand memory addition operations
</Card>
</CardGroup>
@@ -38,11 +38,7 @@ Before defining any criteria, make sure to initialize the `MemoryClient` with yo
```python
from mem0 import MemoryClient
client = MemoryClient(
api_key="your_mem0_api_key",
org_id="your_organization_id",
project_id="your_project_id"
)
client = MemoryClient(api_key="your_mem0_api_key")
```
### Define Your Criteria
+2 -2
View File
@@ -98,7 +98,7 @@ messages = [
]
# Add memories with project-level custom categories
client.add(messages, user_id="alice", async_mode=False)
client.add(messages, user_id="alice")
```
</CodeGroup>
@@ -187,7 +187,7 @@ messages = [
]
# Add memories with default categories
client.add(messages, user_id='alice', async_mode=False)
client.add(messages, user_id='alice')
```
```python Memories with categories
-109
View File
@@ -1,109 +0,0 @@
---
title: Expiration Date
description: 'Set time-bound memories in Mem0 with automatic expiration dates to manage temporal information effectively.'
---
## Benefits of Memory Expiration
Setting expiration dates for memories offers several advantages:
- **Time-Sensitive Information Management**: Handle information that is only relevant for a specific time period.
- **Event-Based Memory**: Manage information related to upcoming events that becomes irrelevant after the event passes.
These benefits enable more sophisticated memory management for applications where temporal context matters.
## Setting Memory Expiration Date
You can set an expiration date for memories, after which they will no longer be retrieved in searches. This is useful for creating temporary memories or memories that are relevant only for a specific time period.
<CodeGroup>
```python Python
import datetime
from mem0 import MemoryClient
client = MemoryClient(api_key="your-api-key")
messages = [
{
"role": "user",
"content": "I'll be in San Francisco until the end of this month."
}
]
# Set an expiration date for this memory
client.add(messages=messages, user_id="alex", expiration_date=str(datetime.datetime.now().date() + datetime.timedelta(days=30)))
# You can also use an explicit date string
client.add(messages=messages, user_id="alex", expiration_date="2023-08-31")
```
```javascript JavaScript
import MemoryClient from 'mem0ai';
const client = new MemoryClient({ apiKey: 'your-api-key' });
const messages = [
{
"role": "user",
"content": "I'll be in San Francisco until the end of this month."
}
];
// Set an expiration date 30 days from now
const expirationDate = new Date();
expirationDate.setDate(expirationDate.getDate() + 30);
client.add(messages, {
user_id: "alex",
expiration_date: expirationDate.toISOString().split('T')[0]
})
.then(response => console.log(response))
.catch(error => console.error(error));
// You can also use an explicit date string
client.add(messages, {
user_id: "alex",
expiration_date: "2023-08-31"
})
.then(response => console.log(response))
.catch(error => console.error(error));
```
```bash cURL
curl -X POST "https://api.mem0.ai/v1/memories/" \
-H "Authorization: Token your-api-key" \
-H "Content-Type: application/json" \
-d '{
"messages": [
{
"role": "user",
"content": "I'll be in San Francisco until the end of this month."
}
],
"user_id": "alex",
"expiration_date": "2023-08-31"
}'
```
```json Output
{
"results": [
{
"id": "a1b2c3d4-e5f6-4g7h-8i9j-k0l1m2n3o4p5",
"data": {
"memory": "In San Francisco until the end of this month"
},
"event": "ADD"
}
]
}
```
</CodeGroup>
<Note>
Once a memory reaches its expiration date, it will not be included in search or get results, though the data remains stored in the system.
</Note>
If you have any questions, please feel free to reach out to us using one of the following methods:
<Snippet file="get-help.mdx" />
+4 -20
View File
@@ -30,11 +30,7 @@ When adding new memories, enable Graph Memory to automatically build relationshi
```python Python
from mem0 import MemoryClient
client = MemoryClient(
api_key="your-api-key",
org_id="your-org-id",
project_id="your-project-id"
)
client = MemoryClient(api_key="your-api-key")
messages = [
{"role": "user", "content": "My name is Joseph"},
@@ -53,11 +49,7 @@ client.add(
```javascript JavaScript
import { MemoryClient } from "mem0";
const client = new MemoryClient({
apiKey: "your-api-key",
org_id: "your-org-id",
project_id: "your-project-id"
});
const client = new MemoryClient({ apiKey: "your-api-key" });
const messages = [
{ role: "user", content: "My name is Joseph" },
@@ -284,11 +276,7 @@ Instead of passing `enable_graph=True` to every add call, you can enable it once
```python Python
from mem0 import MemoryClient
client = MemoryClient(
api_key="your-api-key",
org_id="your-org-id",
project_id="your-project-id"
)
client = MemoryClient(api_key="your-api-key")
# Enable graph memory for all operations in this project
client.project.update(enable_graph=True)
@@ -309,11 +297,7 @@ client.add(
```javascript JavaScript
import { MemoryClient } from "mem0";
const client = new MemoryClient({
apiKey: "your-api-key",
org_id: "your-org-id",
project_id: "your-project-id"
});
const client = new MemoryClient({ apiKey: "your-api-key" });
// Enable graph memory for all operations in this project
await client.project.update({ enable_graph: true });
+3 -4
View File
@@ -217,17 +217,16 @@ print(search_response)
## Async Mode Support
Group chat also supports async processing for improved performance:
Group chat supports async processing for improved performance. Memory additions are processed asynchronously by default.
<CodeGroup>
```python Python
# Group chat with async mode
# Group chat — async processing is the default
response = client.add(
messages,
run_id="groupchat_async",
infer=True,
async_mode=True
)
print(response)
```
@@ -268,7 +267,7 @@ Each message in a group chat must include:
4. **Memory Filtering**: Use filters to retrieve memories from specific participants or sessions when needed.
5. **Async Processing**: Use `async_mode=True` for large group conversations to improve performance.
5. **Async Processing**: Memory additions are processed asynchronously by default, which is ideal for large group conversations.
6. **Search Context**: Leverage the search functionality to find specific information within group chat contexts.