fix(docs): update the cookbooks and remove and update teh depcreataed param (#4814)

Co-authored-by: Claude Opus 4.5 <noreply@anthropic.com>
This commit is contained in:
Kartik
2026-04-16 17:39:55 +05:30
committed by GitHub
parent fb224083e4
commit 0b14f75c05
12 changed files with 48 additions and 370 deletions
+2 -2
View File
@@ -56,7 +56,7 @@ class Mem0Teachability(AgentCapability):
def process_last_received_message(self, text: Union[Dict, str]):
expanded_text = text
if self.memory.get_all(agent_id=self.agent_id):
if self.memory.get_all(filters={"agent_id": self.agent_id}):
expanded_text = self._consider_memo_retrieval(text)
self._consider_memo_storage(text)
return expanded_text
@@ -139,7 +139,7 @@ class Mem0Teachability(AgentCapability):
return comment + self._concatenate_memo_texts(memo_list)
def _retrieve_relevant_memos(self, input_text: str) -> list:
search_results = self.memory.search(input_text, agent_id=self.agent_id, limit=self.max_num_retrievals)
search_results = self.memory.search(input_text, filters={"agent_id": self.agent_id}, top_k=self.max_num_retrievals)
memo_list = [result["memory"] for result in search_results if result["score"] <= self.recall_threshold]
if self.verbosity >= 1 and not memo_list:
@@ -158,7 +158,7 @@ class PersonalTravelAssistant:
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)
memories = self.memory.search(query, filters={"user_id": user_id})
return [m['memory'] for m in memories.get('results', [])]
# Usage example
@@ -354,10 +354,10 @@ Exclude:
```
</Tab>
<Tab title="Open Source">
Tell Mem0 what matters by including `custom_fact_extraction_prompt` in the config dict:
Tell Mem0 what matters by including `custom_instructions` in the config dict:
```python
MEMORY_CONFIG["custom_fact_extraction_prompt"] = """
MEMORY_CONFIG["custom_instructions"] = """
Extract from running coach conversations:
- Training goals and race targets
- Physical constraints or injuries
@@ -375,7 +375,7 @@ Return JSON with key "facts" as a list of strings (use [] if nothing to store).
memory = Memory.from_config(MEMORY_CONFIG)
```
<Note>`custom_fact_extraction_prompt` is a top-level key in the config dictionary passed to `Memory.from_config()`. Make sure it's set before creating the Memory instance — not after.</Note>
<Note>`custom_instructions` is a top-level key in the config dictionary passed to `Memory.from_config()`. Make sure it's set before creating the Memory instance — not after.</Note>
</Tab>
</Tabs>
@@ -520,7 +520,7 @@ memory.add(
# "hey" → don't store
# "cool thanks" → don't store
# Or rely on custom_fact_extraction_prompt to filter automatically
# Or rely on custom_instructions to filter automatically
```
</Tab>
</Tabs>
@@ -545,11 +545,11 @@ 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
metadata={"memory_bucket": "constraints", "expires_on": expiration}
)
```
In 14 days, this memory disappears automatically. Ray stops asking about the ankle.
Store `expires_on` in metadata and periodically clean up expired memories. Ray stops asking about the ankle once it's removed.
</Tab>
<Tab title="Open Source">
```python
@@ -627,7 +627,7 @@ MEMORY_CONFIG = {
"ollama_base_url": "http://localhost:11434",
},
},
"custom_fact_extraction_prompt": """
"custom_instructions": """
Extract: goals, constraints, preferences, progress
Exclude: greetings, filler, casual chat
Return JSON with key "facts" as a list of strings.
@@ -684,8 +684,7 @@ 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
metadata={"memory_bucket": "constraints", "expires_on": expiration}
)
```
</Tab>
@@ -112,19 +112,17 @@ 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
user_id="company_kb"
)
client.add(
"David reports to Rachel, who manages the design team",
user_id="company_kb",
enable_graph=True
user_id="company_kb"
)
```
When you set `enable_graph=True`, Mem0 extracts entities and relationships:
When graph memory is enabled, Mem0 extracts entities and relationships:
- `emma --[works_with]--> david`
- `david --[reports_to]--> rachel`
@@ -135,8 +133,7 @@ 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
filters={"user_id": "company_kb"}
)
print(results['results'][0]['memory'])
@@ -209,30 +206,27 @@ For our company knowledge base, we'll use both:
## Putting It Together
Let's build a small company knowledge base with both approaches:
Let's build a small company knowledge base:
```python
# Facts about individuals - vector store is fine
# Facts about individuals
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
# Relationships
client.add(
"Emma and David work together on the mobile app",
user_id="company_kb",
enable_graph=True
user_id="company_kb"
)
client.add(
"David reports to Rachel",
user_id="company_kb",
enable_graph=True
user_id="company_kb"
)
client.add(
"Rachel runs weekly team syncs every Tuesday",
user_id="company_kb",
enable_graph=True
user_id="company_kb"
)
```
@@ -257,8 +251,7 @@ Emma specializes in React and TypeScript
# 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
filters={"user_id": "company_kb"}
)
print(results['results'][0]['memory'])
@@ -281,23 +274,22 @@ Enable graph memory when your queries need multi-hop traversal: org charts (who
## 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.
Graph memory adds processing time and cost. Mem0 makes extra LLM calls to extract entities and relationships from each memory.
<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.
**Cost consideration:** Graph memory extraction adds ~2-3 extra LLM calls per `add()` operation to identify entities and relationships. Use it when your use case benefits from relationship traversal—organizational structures, team hierarchies, and long-term connections.
</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
# Long-term organizational structure - benefits from graph
client.add(
"Emma mentors two junior engineers on the frontend team",
user_id="company_kb",
enable_graph=True
user_id="company_kb"
)
# Temporary notes - skip graph, not worth the cost
# Temporary notes stored with a run_id for session isolation
client.add(
"Emma is out sick today",
user_id="company_kb",
@@ -308,38 +300,13 @@ client.add(
---
## 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
- **Cost optimization** - Use graph for long-term organizational structure, vector for temporary notes and simple facts
This pattern scales from 10-person startups to enterprise org charts with thousands of employees.
@@ -514,8 +514,8 @@ These controls prevent retrieval failures and ensure your AI assistant works wit
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 title="Build a Mem0 Companion" icon="users" href="/cookbooks/essentials/building-ai-companion">
Learn core memory patterns including temporary vs permanent data handling.
</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.
@@ -280,8 +280,8 @@ This covers data portability, GDPR compliance, system migrations, and manual rev
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 title="Build a Mem0 Companion" icon="users" href="/cookbooks/essentials/building-ai-companion">
Learn core memory patterns including temporary vs permanent data handling.
</Card>
<Card title="Control Memory Ingestion" icon="filter" href="/cookbooks/essentials/controlling-memory-ingestion">
Ensure only verified insights make it into your export pipeline.
@@ -1,277 +0,0 @@
---
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>
@@ -77,7 +77,7 @@ def retrieve_patient_info(query: str) -> dict:
results = mem0_client.search(
query,
user_id=USER_ID,
limit=5,
top_k=5,
threshold=0.7 # Higher threshold for more relevant results
)
@@ -28,13 +28,10 @@ Get your Mem0 API key from the <a href="https://app.mem0.ai/dashboard/api-keys"
### Configuration
```javascript
const mem0Config = {
apiKey: process.env.MEM0_API_KEY,
user_id: "sample-user",
};
const USER_ID = "sample-user";
const openAIClient = new OpenAI();
const mem0Client = new MemoryClient(mem0Config);
const mem0Client = new MemoryClient({ apiKey: process.env.MEM0_API_KEY });
```
## Adding Memories
@@ -43,14 +40,14 @@ Store user preferences, past interactions, or any relevant information:
<CodeGroup>
```javascript JavaScript
async function addUserPreferences() {
const mem0Client = new MemoryClient(mem0Config);
const mem0Client = new MemoryClient({ apiKey: process.env.MEM0_API_KEY });
const userPreferences = "I Love BMW, Audi and Porsche. I Hate Mercedes. I love Red cars and Maroon cars. I have a budget of 120K to 150K USD. I like Audi the most.";
await mem0Client.add([{
role: "user",
content: userPreferences,
}], mem0Config);
}], { userId: "sample-user" });
}
await addUserPreferences();
@@ -91,7 +88,7 @@ await addUserPreferences();
Search for relevant memories based on the current user input:
```javascript
const relevantMemories = await mem0Client.search(userInput, mem0Config);
const relevantMemories = await mem0Client.search(userInput, { userId: USER_ID });
```
## Structured Responses with Zod
@@ -152,10 +149,7 @@ import dotenv from 'dotenv';
dotenv.config();
const mem0Config = {
apiKey: process.env.MEM0_API_KEY,
user_id: "sample-user",
};
const USER_ID = "sample-user";
async function run() {
// Responses without memories
@@ -185,7 +179,7 @@ const Cars = z.object({
async function main(memory = false) {
const openAIClient = new OpenAI();
const mem0Client = new MemoryClient(mem0Config);
const mem0Client = new MemoryClient({ apiKey: process.env.MEM0_API_KEY });
const input = "Suggest me some cars that I can buy today.";
@@ -195,12 +189,12 @@ async function main(memory = false) {
await mem0Client.add([{
role: "user",
content: input,
}], mem0Config);
}], { userId: USER_ID });
// Search for relevant memories
let relevantMemories = []
if (memory) {
relevantMemories = await mem0Client.search(input, mem0Config);
relevantMemories = await mem0Client.search(input, { userId: USER_ID });
}
const response = await openAIClient.responses.create({
@@ -213,14 +207,14 @@ async function main(memory = false) {
}
async function addSampleMemories() {
const mem0Client = new MemoryClient(mem0Config);
const mem0Client = new MemoryClient({ apiKey: process.env.MEM0_API_KEY });
const myInterests = "I Love BMW, Audi and Porsche. I Hate Mercedes. I love Red cars and Maroon cars. I have a budget of 120K to 150K USD. I like Audi the most.";
await mem0Client.add([{
role: "user",
content: myInterests,
}], mem0Config);
}], { userId: USER_ID });
}
const getMemoryString = (memories) => {
-7
View File
@@ -37,13 +37,6 @@ Here are some examples of how Mem0 can be integrated into various applications:
>
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
+4 -1
View File
@@ -328,7 +328,6 @@
"cookbooks/essentials/building-ai-companion",
"cookbooks/essentials/entity-partitioning-playbook",
"cookbooks/essentials/controlling-memory-ingestion",
"cookbooks/essentials/memory-expiration-short-and-long-term",
"cookbooks/essentials/tagging-and-organizing-memories",
"cookbooks/essentials/exporting-memories",
"cookbooks/essentials/choosing-memory-architecture-vector-vs-graph"
@@ -627,6 +626,10 @@
"source": "/platform/features/expiration-date",
"destination": "/"
},
{
"source": "/cookbooks/essentials/memory-expiration-short-and-long-term",
"destination": "/cookbooks/essentials/building-ai-companion"
},
{
"source": "/platform/features/async-mode-default-change",
"destination": "/"
-1
View File
@@ -208,7 +208,6 @@ Key differentiators:
- [Building AI Companion](https://docs.mem0.ai/cookbooks/essentials/building-ai-companion): Core patterns for building AI agents with memory
- [Partition Memories by Entity](https://docs.mem0.ai/cookbooks/essentials/entity-partitioning-playbook): Keep multi-tenant assistants isolated by tagging user, agent, app, and session identifiers
- [Controlling Memory Ingestion](https://docs.mem0.ai/cookbooks/essentials/controlling-memory-ingestion): Fine-tune what gets stored in memory and when
- [Memory Expiration](https://docs.mem0.ai/cookbooks/essentials/memory-expiration-short-and-long-term): Implement short-term and long-term memory strategies
- [Tagging and Organizing Memories](https://docs.mem0.ai/cookbooks/essentials/tagging-and-organizing-memories): Advanced memory organization and categorization
- [Exporting Memories](https://docs.mem0.ai/cookbooks/essentials/exporting-memories): Backup and transfer memory data between systems
- [Choosing Memory Architecture](https://docs.mem0.ai/cookbooks/essentials/choosing-memory-architecture-vector-vs-graph): Vector vs Graph memory architectures comparison