Update Docs (#3315)

This commit is contained in:
Deshraj Yadav
2025-08-13 21:37:15 -07:00
committed by GitHub
parent 5e895c240a
commit 192db1844c
127 changed files with 2882 additions and 3317 deletions
+190 -141
View File
@@ -1,207 +1,256 @@
---
title: Contextual Add (ADD v2)
title: Contextual Memory Creation
icon: "square-plus"
iconType: "solid"
description: "Add messages with automatic context management - no manual history tracking required"
---
<Snippet file="blank-notif.mdx" />
## What is Contextual Memory Creation?
Mem0 now supports an contextual add version (v2). To use it, set `version="v2"` during the add call. The default version is v1, which is deprecated now. We recommend migrating to `v2` for new applications.
## Key Differences Between v1 and v2
### Version 1 (Legacy)
In v1 (default), users needed to pass either the entire conversation history or past k messages with each new message to generate properly contextualized memories. This approach required:
- Manually tracking and sending previous messages using a sliding window approach
- Increased payload sizes as conversations grew longer, requiring careful window size management
Contextual memory creation automatically manages message history for you, so you can focus on building great AI experiences instead of tracking interactions manually. Simply send new messages, and Mem0 handles the context automatically.
<CodeGroup>
```python Python
# Just send new messages - Mem0 handles the context
messages = [
{"role": "user", "content": "I love Italian food, especially pasta"},
{"role": "assistant", "content": "Great! I'll remember your preference for Italian cuisine."}
]
client.add(messages, user_id="user123", version="v2")
```
```javascript JavaScript
// Just send new messages - Mem0 handles the context
const messages = [
{"role": "user", "content": "I love Italian food, especially pasta"},
{"role": "assistant", "content": "Great! I'll remember your preference for Italian cuisine."}
];
await client.add(messages, { user_id: "user123", version: "v2" });
```
</CodeGroup>
## Why Use Contextual Memory Creation?
- **Simple**: Send only new messages, no manual history tracking
- **Efficient**: Smaller payloads and faster processing
- **Automatic**: Context management handled by Mem0
- **Reliable**: No risk of missing interaction history
- **Scalable**: Works seamlessly as your application grows
## How It Works
### Basic Usage
<CodeGroup>
```python Python
# First interaction
messages1 = [
{"role": "user", "content": "Hi, I'm Alex and I live in San Francisco."},
{"role": "assistant", "content": "Hello Alex! Nice to meet you. San Francisco is a beautiful city."}
{"role": "user", "content": "Hi, I'm Sarah from New York"},
{"role": "assistant", "content": "Hello Sarah! Nice to meet you."}
]
client.add(messages1, user_id="alex")
client.add(messages1, user_id="sarah", version="v2")
# Second interaction - must include previous messages for context
# Later interaction - just send new messages
messages2 = [
{"role": "user", "content": "Hi, I'm Alex and I live in San Francisco."},
{"role": "assistant", "content": "Hello Alex! Nice to meet you. San Francisco is a beautiful city."},
{"role": "user", "content": "I like to eat sushi, and yesterday I went to Sunnyvale to eat sushi with my friends."},
{"role": "assistant", "content": "Sushi is really a tasty choice. What did you do this weekend?"}
{"role": "user", "content": "I'm planning a trip to Italy next month"},
{"role": "assistant", "content": "How exciting! Italy is beautiful this time of year."}
]
client.add(messages2, user_id="alex")
client.add(messages2, user_id="sarah", version="v2")
# Mem0 automatically knows Sarah is from New York and can use this context
```
```javascript JavaScript
// First interaction
const messages1 = [
{"role": "user", "content": "Hi, I'm Alex and I live in San Francisco."},
{"role": "assistant", "content": "Hello Alex! Nice to meet you. San Francisco is a beautiful city."}
{"role": "user", "content": "Hi, I'm Sarah from New York"},
{"role": "assistant", "content": "Hello Sarah! Nice to meet you."}
];
client.add(messages1, { user_id: "alex" })
.then(response => console.log(response))
.catch(error => console.error(error));
await client.add(messages1, { user_id: "sarah", version: "v2" });
// Second interaction - must include previous messages for context
// Later interaction - just send new messages
const messages2 = [
{"role": "user", "content": "Hi, I'm Alex and I live in San Francisco."},
{"role": "assistant", "content": "Hello Alex! Nice to meet you. San Francisco is a beautiful city."},
{"role": "user", "content": "I like to eat sushi, and yesterday I went to Sunnyvale to eat sushi with my friends."},
{"role": "assistant", "content": "Sushi is really a tasty choice. What did you do this weekend?"}
{"role": "user", "content": "I'm planning a trip to Italy next month"},
{"role": "assistant", "content": "How exciting! Italy is beautiful this time of year."}
];
client.add(messages2, { user_id: "alex" })
.then(response => console.log(response))
.catch(error => console.error(error));
await client.add(messages2, { user_id: "sarah", version: "v2" });
// Mem0 automatically knows Sarah is from New York and can use this context
```
</CodeGroup>
### Version 2 (Recommended)
In v2, Mem0 automatically manages conversation context. Users only need to send new messages, and the system will:
## Organization Strategies
- Automatically retrieve relevant conversation history
- Generate properly contextualized memories
- Reduce payload sizes and simplify integration
Choose the right approach based on your application's needs:
### User-Level Memories (`user_id` only)
Best for: Personal preferences, profile information, long-term user data
<CodeGroup>
```python Python
# First interaction
# Persistent user memories across all interactions
messages = [
{"role": "user", "content": "I'm allergic to nuts and dairy"},
{"role": "assistant", "content": "I've noted your allergies for future reference."}
]
client.add(messages, user_id="user123", version="v2")
# This allergy info will be available in ALL future interactions
```
```javascript JavaScript
// Persistent user memories across all interactions
const messages = [
{"role": "user", "content": "I'm allergic to nuts and dairy"},
{"role": "assistant", "content": "I've noted your allergies for future reference."}
];
await client.add(messages, { user_id: "user123", version: "v2" });
// This allergy info will be available in ALL future interactions
```
</CodeGroup>
### Session-Specific Memories (`user_id` + `run_id`)
Best for: Task-specific context, separate interaction threads, project-based sessions
<CodeGroup>
```python Python
# Trip planning session
messages1 = [
{"role": "user", "content": "Hi, I'm Alex and I live in San Francisco."},
{"role": "assistant", "content": "Hello Alex! Nice to meet you. San Francisco is a beautiful city."}
{"role": "user", "content": "I want to plan a 5-day trip to Tokyo"},
{"role": "assistant", "content": "Perfect! Let's plan your Tokyo adventure."}
]
client.add(messages1, user_id="alex", version="v2")
client.add(messages1, user_id="user123", run_id="tokyo-trip-2024", version="v2")
# Second interaction - only need to send new messages
# Later in the same trip planning session
messages2 = [
{"role": "user", "content": "I like to eat sushi, and yesterday I went to Sunnyvale to eat sushi with my friends."},
{"role": "assistant", "content": "Sushi is really a tasty choice. What did you do this weekend?"}
{"role": "user", "content": "I prefer staying near Shibuya"},
{"role": "assistant", "content": "Great choice! Shibuya is very convenient."}
]
client.add(messages2, user_id="alex", version="v2")
client.add(messages2, user_id="user123", run_id="tokyo-trip-2024", version="v2")
# Different session for work project (separate context)
work_messages = [
{"role": "user", "content": "Let's discuss the Q4 marketing strategy"},
{"role": "assistant", "content": "Sure! What are your main goals for Q4?"}
]
client.add(work_messages, user_id="user123", run_id="q4-marketing", version="v2")
```
```javascript JavaScript
// First interaction
// Trip planning session
const messages1 = [
{"role": "user", "content": "Hi, I'm Alex and I live in San Francisco."},
{"role": "assistant", "content": "Hello Alex! Nice to meet you. San Francisco is a beautiful city."}
{"role": "user", "content": "I want to plan a 5-day trip to Tokyo"},
{"role": "assistant", "content": "Perfect! Let's plan your Tokyo adventure."}
];
client.add(messages1, { user_id: "alex", version: "v2" })
.then(response => console.log(response))
.catch(error => console.error(error));
await client.add(messages1, { user_id: "user123", run_id: "tokyo-trip-2024", version: "v2" });
// Second interaction - only need to send new messages
// Later in the same trip planning session
const messages2 = [
{"role": "user", "content": "I like to eat sushi, and yesterday I went to Sunnyvale to eat sushi with my friends."},
{"role": "assistant", "content": "Sushi is really a tasty choice. What did you do this weekend?"}
{"role": "user", "content": "I prefer staying near Shibuya"},
{"role": "assistant", "content": "Great choice! Shibuya is very convenient."}
];
client.add(messages2, { user_id: "alex", version: "v2" })
.then(response => console.log(response))
.catch(error => console.error(error));
```
await client.add(messages2, { user_id: "user123", run_id: "tokyo-trip-2024", version: "v2" });
// Different session for work project (separate context)
const workMessages = [
{"role": "user", "content": "Let's discuss the Q4 marketing strategy"},
{"role": "assistant", "content": "Sure! What are your main goals for Q4?"}
];
await client.add(workMessages, { user_id: "user123", run_id: "q4-marketing", version: "v2" });
```
</CodeGroup>
## Benefits of Using v2
1. **Simplified Integration**: No need to track and manage conversation history
2. **Reduced Payload Size**: Only send new messages, not the entire conversation
3. **Improved Memory Quality**: Automatic context retrieval ensures better memory generation
## Understanding ID Parameters in v2
When using contextual add v2, you have different options for how to organize and retrieve memories:
### Using Only `user_id`
When you provide only a `user_id`:
- Memories are associated with this user's long-term memory store
- The system will automatically retrieve relevant context from all of the user's previous conversations
- These memories persist indefinitely across all of the user's sessions
- Ideal for maintaining persistent user information (preferences, personal details, etc.)
<CodeGroup>
## Real-World Use Cases
<Tabs>
<Tab title="Customer Support">
```python Python
# Adding to long-term user memory
# Support ticket context - keeps interaction focused
messages = [
{"role": "user", "content": "I'm allergic to peanuts and shellfish."},
{"role": "assistant", "content": "I've noted your allergies to peanuts and shellfish."}
{"role": "user", "content": "My subscription isn't working"},
{"role": "assistant", "content": "I can help with that. What specific issue are you experiencing?"},
{"role": "user", "content": "I can't access premium features even though I paid"}
]
client.add(messages, user_id="alex", version="v2")
# Each support ticket gets its own run_id
client.add(messages,
user_id="customer123",
run_id="ticket-2024-001",
version="v2"
)
```
```javascript JavaScript
// Adding to long-term user memory
const messages = [
{"role": "user", "content": "I'm allergic to peanuts and shellfish."},
{"role": "assistant", "content": "I've noted your allergies to peanuts and shellfish."}
];
client.add(messages, { user_id: "alex", version: "v2" })
.then(response => console.log(response))
.catch(error => console.error(error));
```
</CodeGroup>
### Using `user_id` with `run_id`
When you provide both `user_id` and `run_id`:
- Memories are associated with a specific conversation session or interaction
- The system will retrieve context primarily from this specific session
- These memories are still tied to the user but are organized by the specific session
- Ideal for maintaining context within a specific conversation flow or task
- Helps prevent context from different conversations from interfering with each other
<CodeGroup>
</Tab>
<Tab title="Personal AI Assistant">
```python Python
# Adding to a specific conversation session
messages = [
{"role": "user", "content": "For this trip to Paris, I want to focus on art museums."},
{"role": "assistant", "content": "Great! I'll help you plan your Paris trip with a focus on art museums."}
# Personal preferences (persistent across all interactions)
preference_messages = [
{"role": "user", "content": "I prefer morning workouts and vegetarian meals"},
{"role": "assistant", "content": "Got it! I'll keep your fitness and dietary preferences in mind."}
]
client.add(messages, user_id="alex", run_id="paris-trip-2024", version="v2")
# Later in the same conversation session
messages2 = [
{"role": "user", "content": "I'd like to visit the Louvre on Monday."},
{"role": "assistant", "content": "The Louvre is a great choice for Monday. Would you like information about opening hours?"}
client.add(preference_messages, user_id="user456", version="v2")
# Daily planning session (session-specific)
planning_messages = [
{"role": "user", "content": "Help me plan tomorrow's schedule"},
{"role": "assistant", "content": "Of course! I'll consider your morning workout preference."}
]
client.add(messages2, user_id="alex", run_id="paris-trip-2024", version="v2")
client.add(planning_messages,
user_id="user456",
run_id="daily-plan-2024-01-15",
version="v2"
)
```
</Tab>
<Tab title="Educational Platform">
```python Python
# Student profile (persistent)
profile_messages = [
{"role": "user", "content": "I'm studying computer science and struggle with math"},
{"role": "assistant", "content": "I'll tailor explanations to help with math concepts."}
]
```javascript JavaScript
// Adding to a specific conversation session
const messages = [
{"role": "user", "content": "For this trip to Paris, I want to focus on art museums."},
{"role": "assistant", "content": "Great! I'll help you plan your Paris trip with a focus on art museums."}
];
client.add(messages, { user_id: "alex", run_id: "paris-trip-2024", version: "v2" })
.then(response => console.log(response))
.catch(error => console.error(error));
client.add(profile_messages, user_id="student789", version="v2")
// Later in the same conversation session
const messages2 = [
{"role": "user", "content": "I'd like to visit the Louvre on Monday."},
{"role": "assistant", "content": "The Louvre is a great choice for Monday. Would you like information about opening hours?"}
];
client.add(messages2, { user_id: "alex", run_id: "paris-trip-2024", version: "v2" })
.then(response => console.log(response))
.catch(error => console.error(error));
# Specific lesson session
lesson_messages = [
{"role": "user", "content": "Can you explain algorithms?"},
{"role": "assistant", "content": "Sure! I'll explain algorithms with math-friendly examples."}
]
client.add(lesson_messages,
user_id="student789",
run_id="algorithms-lesson-1",
version="v2"
)
```
</Tab>
</Tabs>
</CodeGroup>
## Best Practices
Using `run_id` helps you organize memories into logical sessions or tasks, making it easier to maintain context for specific interactions while still associating everything with the user's overall profile.
### ✅ Do
- **Organize by context scope**: Use `user_id` only for persistent data, add `run_id` for session-specific context
- **Keep messages focused** on the current interaction
- **Test with real interaction flows** to ensure context works as expected
### ❌ Don't
- Send duplicate messages or interaction history
- Forget to include `version="v2"` parameter
- Mix contextual and non-contextual approaches in the same application
## Troubleshooting
| Issue | Solution |
|-------|----------|
| **Context not working** | Ensure you're using `version="v2"` and consistent `user_id` |
| **Wrong context retrieved** | Check if you need separate `run_id` values for different interaction topics |
| **Missing interaction history** | Verify all messages in the interaction thread use the same `user_id` and `run_id` |
| **Too much irrelevant context** | Use more specific `run_id` values to separate different interaction types |
If you have any questions, please feel free to reach out to us using one of the following methods:
<Snippet file="get-help.mdx" />