Update Docs (#3315)
This commit is contained in:
File diff suppressed because it is too large
Load Diff
@@ -2,174 +2,282 @@
|
||||
title: Advanced Retrieval
|
||||
icon: "magnifying-glass"
|
||||
iconType: "solid"
|
||||
description: "Advanced memory search with keyword expansion, intelligent reranking, and precision filtering"
|
||||
---
|
||||
|
||||
<Snippet file="blank-notif.mdx" />
|
||||
## What is Advanced Retrieval?
|
||||
|
||||
Mem0’s **Advanced Retrieval** provides additional control over how memories are selected and ranked during search. While the default search uses embedding-based semantic similarity, Advanced Retrieval introduces specialized options to improve recall, ranking accuracy, or filtering based on specific use case.
|
||||
Advanced Retrieval gives you precise control over how memories are found and ranked. While basic search uses semantic similarity, these advanced options help you find exactly what you need, when you need it.
|
||||
|
||||
You can enable any of the following modes independently or together:
|
||||
<CodeGroup>
|
||||
|
||||
- Keyword Search
|
||||
- Reranking
|
||||
- Filtering
|
||||
## Search Enhancement Options
|
||||
|
||||
Each enhancement can be toggled independently via the `search()` API call. These flags are off by default. These are useful when building agents that require fine-grained retrieval control
|
||||
### Keyword Search
|
||||
**Expands results** to include memories with specific terms, names, and technical keywords.
|
||||
|
||||
## Keyword Search
|
||||
|
||||
Keyword search expands the result set by including memories that contain lexically similar terms and important keywords from the query, even if they're not semantically similar.
|
||||
|
||||
### When to use
|
||||
- You are searching for specific entities, names, or technical terms
|
||||
- When you need comprehensive coverage of a topic
|
||||
- You want broader recall at the cost of slight noise
|
||||
|
||||
|
||||
### API Usage
|
||||
```python
|
||||
<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 are my food preferences?",
|
||||
query="What foods should I avoid?",
|
||||
keyword_search=True,
|
||||
user_id="alex"
|
||||
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>
|
||||
|
||||
### Example
|
||||
### Reranking
|
||||
**Reorders results** using deep semantic understanding to put the most relevant memories first.
|
||||
|
||||
**Without keyword_search:**
|
||||
- "Vegetarian. Allergic to nuts."
|
||||
- "Prefers spicy food and enjoys Thai cuisine"
|
||||
|
||||
**With keyword_search=True:**
|
||||
- "Vegetarian. Allergic to nuts."
|
||||
- "Prefers spicy food and enjoys Thai cuisine"
|
||||
- "Mentioned disliking seafood during restaurant discussion"
|
||||
|
||||
### Trade-offs
|
||||
- Increases recall
|
||||
- May slightly reduce precision
|
||||
- Adds ~10ms latency
|
||||
|
||||
|
||||
|
||||
## Reranking
|
||||
|
||||
Reranking reorders the retrieved results using a deep semantic relevance model that improves the position of the most relevant matches.
|
||||
|
||||
### When to use
|
||||
- You rely on top-1 or top-N precision
|
||||
- When result order is critical for your application
|
||||
- You want consistent result quality across sessions
|
||||
|
||||
### API Usage
|
||||
```python
|
||||
<Tabs>
|
||||
<Tab title="When to Use">
|
||||
- Need the most relevant result at the top
|
||||
- Result order is critical for your application
|
||||
- Want consistent quality across different queries
|
||||
- Building user-facing features where accuracy matters
|
||||
</Tab>
|
||||
<Tab title="How it Works">
|
||||
```python Python
|
||||
# Get the most relevant travel plans first
|
||||
results = client.search(
|
||||
query="What are my travel plans?",
|
||||
query="What are my upcoming travel plans?",
|
||||
rerank=True,
|
||||
user_id="alex"
|
||||
user_id="user123"
|
||||
)
|
||||
|
||||
# Before reranking: After reranking:
|
||||
# 1. "Went to Paris" → 1. "Tokyo trip next month"
|
||||
# 2. "Tokyo trip next" → 2. "Need to book hotel in Tokyo"
|
||||
# 3. "Need hotel" → 3. "Went to Paris last year"
|
||||
```
|
||||
</Tab>
|
||||
<Tab title="Performance">
|
||||
- **Latency**: 150-200ms additional
|
||||
- **Accuracy**: Significantly improved
|
||||
- **Ordering**: Much more relevant
|
||||
- **Best for**: Top-N precision, user-facing results
|
||||
</Tab>
|
||||
</Tabs>
|
||||
|
||||
### Example
|
||||
### Memory Filtering
|
||||
**Filters results** to keep only the most precisely relevant memories.
|
||||
|
||||
**Without rerank:**
|
||||
1. "Traveled to France last year"
|
||||
2. "Planning a trip to Japan next month"
|
||||
3. "Interested in visiting Tokyo restaurants"
|
||||
|
||||
**With rerank=True:**
|
||||
1. "Planning a trip to Japan next month"
|
||||
2. "Interested in visiting Tokyo restaurants"
|
||||
3. "Traveled to France last year"
|
||||
|
||||
### Trade-offs
|
||||
- Significantly improves result ordering accuracy
|
||||
- Ensures most relevant memories appear first
|
||||
- Adds ~150–200ms latency
|
||||
- Higher computational cost
|
||||
|
||||
|
||||
|
||||
## Filtering
|
||||
|
||||
Filtering allows you to narrow down search results by applying specific criteria from the set of retrieved memories.
|
||||
|
||||
### When to use
|
||||
- You require highly specific results
|
||||
- You are working with huge amount of data where noise is problematic
|
||||
- You require quality over quantity results
|
||||
|
||||
### API Usage
|
||||
```python
|
||||
<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="alex"
|
||||
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>
|
||||
|
||||
### Example
|
||||
## Real-World Use Cases
|
||||
|
||||
**Without filtering:**
|
||||
- "Vegetarian. Allergic to nuts."
|
||||
- "I enjoy cooking Italian food on weekends"
|
||||
- "Mentioned disliking seafood during restaurant discussion"
|
||||
- "Prefers to eat dinner at 7pm"
|
||||
|
||||
**With filter_memories=True:**
|
||||
- "Vegetarian. Allergic to nuts."
|
||||
- "Mentioned disliking seafood during restaurant discussion"
|
||||
|
||||
### Trade-offs
|
||||
- Maximizes precision (highly relevant results only)
|
||||
- May reduce recall (filters out some relevant memories)
|
||||
- Adds ~200-300ms latency
|
||||
- Best for focused, specific queries
|
||||
|
||||
|
||||
|
||||
## Combining Modes
|
||||
|
||||
You can combine all three retrieval modes as needed:
|
||||
|
||||
```python
|
||||
<Tabs>
|
||||
<Tab title="Personal AI Assistant">
|
||||
```python Python
|
||||
# Smart home assistant finding device preferences
|
||||
results = client.search(
|
||||
query="What are my travel plans?",
|
||||
keyword_search=True,
|
||||
rerank=True,
|
||||
filter_memories=True,
|
||||
user_id="alex"
|
||||
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"
|
||||
)
|
||||
|
||||
# Finds: "Keep bedroom at 68°F", "Too cold last night at 65°F", etc.
|
||||
```
|
||||
</Tab>
|
||||
<Tab title="Customer Support">
|
||||
```python Python
|
||||
# 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"
|
||||
)
|
||||
|
||||
# Returns only relevant billing problems, not general questions
|
||||
```
|
||||
</Tab>
|
||||
<Tab title="Healthcare AI">
|
||||
```python Python
|
||||
# Critical medical information needs perfect accuracy
|
||||
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
|
||||
```
|
||||
</Tab>
|
||||
<Tab title="Learning Platform">
|
||||
```python Python
|
||||
# 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"
|
||||
)
|
||||
|
||||
# Gets comprehensive view of Python learning journey
|
||||
```
|
||||
</Tab>
|
||||
</Tabs>
|
||||
|
||||
## Choosing the Right Combination
|
||||
|
||||
### Recommended Configurations
|
||||
|
||||
<CodeGroup>
|
||||
```python Python
|
||||
# Fast and broad - 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
|
||||
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
|
||||
def precise_search(query, user_id):
|
||||
return client.search(
|
||||
query=query,
|
||||
rerank=True,
|
||||
filter_memories=True,
|
||||
user_id=user_id
|
||||
)
|
||||
```
|
||||
|
||||
This configuration broadens the candidate pool with keywords, improves ordering via rerank, and finally cuts noise with filtering.
|
||||
<Note> Combining all modes may add up to ~450ms latency per query. </Note>
|
||||
```javascript JavaScript
|
||||
// Fast and broad - good for exploration
|
||||
function quickSearch(query, userId) {
|
||||
return client.search(query, {
|
||||
user_id: userId,
|
||||
keyword_search: true
|
||||
});
|
||||
}
|
||||
|
||||
// Balanced - 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
|
||||
function preciseSearch(query, userId) {
|
||||
return client.search(query, {
|
||||
user_id: userId,
|
||||
rerank: true,
|
||||
filter_memories: true
|
||||
});
|
||||
}
|
||||
```
|
||||
</CodeGroup>
|
||||
|
||||
## Performance Benchmarks
|
||||
## Best Practices
|
||||
|
||||
| **Mode** | **Approximate Latency** |
|
||||
|------------------|-------------------------|
|
||||
| `keyword_search` | <10ms |
|
||||
| `rerank` | 150–200ms |
|
||||
| `filter_memories`| 200–300ms |
|
||||
### ✅ Do
|
||||
- **Start simple** with just one enhancement and measure impact
|
||||
- **Use keyword search** for entity-heavy queries (names, places, technical terms)
|
||||
- **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
|
||||
|
||||
### ❌ Don't
|
||||
- Enable all options by default without measuring necessity
|
||||
- Use filtering for broad exploratory queries
|
||||
- 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
|
||||
|
||||
## Best Practices & Limitations
|
||||
### Latency Expectations
|
||||
|
||||
- Use `keyword_search` for broader recall when query context is limited
|
||||
- Use `rerank` to prioritize the top-most relevant result
|
||||
- Use `filter_memories` in production-facing or safety-critical agents
|
||||
- Combine filtering and reranking for maximum accuracy
|
||||
- Filters may eliminate all results—always handle the empty set gracefully
|
||||
- Filtering uses LLM evaluation and may be rate-limited depending on your plan
|
||||
```python Python
|
||||
# Performance monitoring example
|
||||
import time
|
||||
|
||||
<Note> You can enable or disable these search modes by passing the respective parameters to the `search` method. There is no required sequence for these modes, and any combination can be used based on your needs. </Note>
|
||||
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
|
||||
```
|
||||
|
||||
### 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
|
||||
4. **Monitor and alert** on search latency patterns
|
||||
|
||||
---
|
||||
If you have any questions, please feel free to reach out to us using one of the following methods:
|
||||
|
||||
**Ready to enhance your search?** Start with keyword search for broader coverage, add reranking for better ordering, and use filtering when precision is critical.
|
||||
|
||||
<Snippet file="get-help.mdx" />
|
||||
|
||||
@@ -5,7 +5,6 @@ icon: "bolt"
|
||||
iconType: "solid"
|
||||
---
|
||||
|
||||
<Snippet file="blank-notif.mdx" />
|
||||
The `AsyncMemoryClient` is an asynchronous client for interacting with the Mem0 API. It provides similar functionality to the synchronous `MemoryClient` but allows for non-blocking operations, which can be beneficial in applications that require high concurrency.
|
||||
|
||||
## Initialization
|
||||
|
||||
@@ -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" />
|
||||
@@ -4,9 +4,6 @@ icon: "magnifying-glass-plus"
|
||||
iconType: "solid"
|
||||
---
|
||||
|
||||
<Snippet file="blank-notif.mdx" />
|
||||
|
||||
|
||||
Mem0’s **Criteria Retrieval** feature allows you to retrieve memories based on your defined criteria. It goes beyond generic semantic relevance and rank memories based on what matters to your application - emotional tone, intent, behavioral signals, or other custom traits.
|
||||
|
||||
Instead of just searching for "how similar a memory is to this query?", you can define what *relevance* really means for your project. For example:
|
||||
|
||||
@@ -5,8 +5,6 @@ icon: "tags"
|
||||
iconType: "solid"
|
||||
---
|
||||
|
||||
<Snippet file="blank-notif.mdx" />
|
||||
|
||||
## How to set custom categories?
|
||||
|
||||
You can now create custom categories tailored to your specific needs, instead of using the default categories such as travel, sports, music, and more (see [default categories](#default-categories) below). **When custom categories are provided, they will override the default categories.**
|
||||
|
||||
@@ -1,78 +1,338 @@
|
||||
---
|
||||
title: Custom Instructions
|
||||
description: 'Enhance your product experience by adding custom instructions tailored to your needs'
|
||||
description: 'Control how Mem0 extracts and stores memories using natural language guidelines'
|
||||
icon: "pencil"
|
||||
iconType: "solid"
|
||||
---
|
||||
|
||||
<Snippet file="blank-notif.mdx" />
|
||||
## What are Custom Instructions?
|
||||
|
||||
## Introduction to Custom Instructions
|
||||
|
||||
Custom instructions allow you to define specific guidelines for your project. This feature helps ensure consistency and provides clear direction for handling project-specific requirements.
|
||||
|
||||
Custom instructions are particularly useful when you want to:
|
||||
- Define how information should be extracted from conversations
|
||||
- Specify what types of data should be captured or ignored
|
||||
- Set rules for categorizing and organizing memories
|
||||
- Maintain consistent handling of project-specific requirements
|
||||
|
||||
When custom instructions are set at the project level, they will be applied to all new memories added within that project. This ensures that your data is processed according to your defined guidelines across your entire project.
|
||||
|
||||
## Setting Custom Instructions
|
||||
|
||||
You can set custom instructions for your project using the following method:
|
||||
Custom instructions are natural language guidelines that tell Mem0 exactly what information to extract and remember from conversations. Think of them as smart filters that ensure your AI application captures only the most relevant data for your specific use case.
|
||||
|
||||
<CodeGroup>
|
||||
```python Code
|
||||
# Update custom instructions
|
||||
prompt ="""
|
||||
Your Task: Extract ONLY health-related information from conversations, focusing on the following areas:
|
||||
```python Python
|
||||
# Simple example: Health app focusing on wellness
|
||||
prompt = """
|
||||
Extract only health and wellness information:
|
||||
- Symptoms, medications, and treatments
|
||||
- Exercise routines and dietary habits
|
||||
- Doctor appointments and health goals
|
||||
|
||||
1. Medical Conditions, Symptoms, and Diagnoses:
|
||||
- Illnesses, disorders, or symptoms (e.g., fever, diabetes).
|
||||
- Confirmed or suspected diagnoses.
|
||||
|
||||
2. Medications, Treatments, and Procedures:
|
||||
- Prescription or OTC medications (names, dosages).
|
||||
- Treatments, therapies, or medical procedures.
|
||||
|
||||
3. Diet, Exercise, and Sleep:
|
||||
- Dietary habits, fitness routines, and sleep patterns.
|
||||
|
||||
4. Doctor Visits and Appointments:
|
||||
- Past, upcoming, or regular medical visits.
|
||||
|
||||
5. Health Metrics:
|
||||
- Data like weight, BP, cholesterol, or sugar levels.
|
||||
|
||||
Guidelines:
|
||||
- Focus solely on health-related content.
|
||||
- Maintain clarity and context accuracy while recording.
|
||||
Exclude: Personal identifiers, financial data
|
||||
"""
|
||||
response = client.project.update(custom_instructions=prompt)
|
||||
print(response)
|
||||
|
||||
client.project.update(custom_instructions=prompt)
|
||||
```
|
||||
|
||||
```json Output
|
||||
{
|
||||
"message": "Updated custom instructions"
|
||||
}
|
||||
```javascript JavaScript
|
||||
// Simple example: Health app focusing on wellness
|
||||
const prompt = `
|
||||
Extract only health and wellness information:
|
||||
- Symptoms, medications, and treatments
|
||||
- Exercise routines and dietary habits
|
||||
- Doctor appointments and health goals
|
||||
|
||||
Exclude: Personal identifiers, financial data
|
||||
`;
|
||||
|
||||
await client.project.update({ custom_instructions: prompt });
|
||||
```
|
||||
</CodeGroup>
|
||||
|
||||
You can also retrieve the current custom instructions:
|
||||
## Why Use Custom Instructions?
|
||||
|
||||
- **Focus on What Matters**: Only capture information relevant to your application
|
||||
- **Maintain Privacy**: Explicitly exclude sensitive data like passwords or personal identifiers
|
||||
- **Ensure Consistency**: All memories follow the same extraction rules across your project
|
||||
- **Improve Quality**: Filter out noise and irrelevant conversations
|
||||
|
||||
## How to Set Custom Instructions
|
||||
|
||||
### Basic Setup
|
||||
|
||||
<CodeGroup>
|
||||
```python Code
|
||||
# Retrieve current custom instructions
|
||||
```python Python
|
||||
# Set instructions for your project
|
||||
client.project.update(custom_instructions="Your guidelines here...")
|
||||
|
||||
# Retrieve current instructions
|
||||
response = client.project.get(fields=["custom_instructions"])
|
||||
print(response)
|
||||
print(response["custom_instructions"])
|
||||
```
|
||||
|
||||
```json Output
|
||||
{
|
||||
"custom_instructions": "Your Task: Extract ONLY health-related information from conversations, focusing on the following areas:\n1. Medical Conditions, Symptoms, and Diagnoses - illnesses, disorders, or symptoms (e.g., fever, diabetes), confirmed or suspected diagnoses.\n2. Medications, Treatments, and Procedures - prescription or OTC medications (names, dosages), treatments, therapies, or medical procedures.\n3. Diet, Exercise, and Sleep - dietary habits, fitness routines, and sleep patterns.\n4. Doctor Visits and Appointments - past, upcoming, or regular medical visits.\n5. Health Metrics - data like weight, BP, cholesterol, or sugar levels.\n\nGuidelines: Focus solely on health-related content. Maintain clarity and context accuracy while recording."
|
||||
}
|
||||
```javascript JavaScript
|
||||
// Set instructions for your project
|
||||
await client.project.update({ custom_instructions: "Your guidelines here..." });
|
||||
|
||||
// Retrieve current instructions
|
||||
const response = await client.project.get({ fields: ["custom_instructions"] });
|
||||
console.log(response.custom_instructions);
|
||||
```
|
||||
</CodeGroup>
|
||||
</CodeGroup>
|
||||
|
||||
### Best Practice Template
|
||||
|
||||
Structure your instructions using this proven template:
|
||||
|
||||
```
|
||||
Your Task: [Brief description of what to extract]
|
||||
|
||||
Information to Extract:
|
||||
1. [Category 1]:
|
||||
- [Specific details]
|
||||
- [What to look for]
|
||||
|
||||
2. [Category 2]:
|
||||
- [Specific details]
|
||||
- [What to look for]
|
||||
|
||||
Guidelines:
|
||||
- [Processing rules]
|
||||
- [Quality requirements]
|
||||
|
||||
Exclude:
|
||||
- [Sensitive data to avoid]
|
||||
- [Irrelevant information]
|
||||
```
|
||||
|
||||
## Real-World Examples
|
||||
|
||||
<Tabs>
|
||||
<Tab title="E-commerce Customer Support">
|
||||
<CodeGroup>
|
||||
```python Python
|
||||
instructions = """
|
||||
Extract customer service information for better support:
|
||||
|
||||
1. Product Issues:
|
||||
- Product names, SKUs, defects
|
||||
- Return/exchange requests
|
||||
- Quality complaints
|
||||
|
||||
2. Customer Preferences:
|
||||
- Preferred brands, sizes, colors
|
||||
- Shopping frequency and habits
|
||||
- Price sensitivity
|
||||
|
||||
3. Service Experience:
|
||||
- Satisfaction with support
|
||||
- Resolution time expectations
|
||||
- Communication preferences
|
||||
|
||||
Exclude: Payment card numbers, passwords, personal identifiers.
|
||||
"""
|
||||
|
||||
client.project.update(custom_instructions=instructions)
|
||||
```
|
||||
|
||||
```javascript JavaScript
|
||||
const instructions = `
|
||||
Extract customer service information for better support:
|
||||
|
||||
1. Product Issues:
|
||||
- Product names, SKUs, defects
|
||||
- Return/exchange requests
|
||||
- Quality complaints
|
||||
|
||||
2. Customer Preferences:
|
||||
- Preferred brands, sizes, colors
|
||||
- Shopping frequency and habits
|
||||
- Price sensitivity
|
||||
|
||||
3. Service Experience:
|
||||
- Satisfaction with support
|
||||
- Resolution time expectations
|
||||
- Communication preferences
|
||||
|
||||
Exclude: Payment card numbers, passwords, personal identifiers.
|
||||
`;
|
||||
|
||||
await client.project.update({ custom_instructions: instructions });
|
||||
```
|
||||
</CodeGroup>
|
||||
</Tab>
|
||||
<Tab title="Personalized Learning Platform">
|
||||
<CodeGroup>
|
||||
```python Python
|
||||
education_prompt = """
|
||||
Extract learning-related information for personalized education:
|
||||
|
||||
1. Learning Progress:
|
||||
- Course completions and current modules
|
||||
- Skills acquired and improvement areas
|
||||
- Learning goals and objectives
|
||||
|
||||
2. Student Preferences:
|
||||
- Learning styles (visual, audio, hands-on)
|
||||
- Time availability and scheduling
|
||||
- Subject interests and career goals
|
||||
|
||||
3. Performance Data:
|
||||
- Assignment feedback and patterns
|
||||
- Areas of struggle or strength
|
||||
- Study habits and engagement
|
||||
|
||||
Exclude: Specific grades, personal identifiers, financial information.
|
||||
"""
|
||||
|
||||
client.project.update(custom_instructions=education_prompt)
|
||||
```
|
||||
|
||||
```javascript JavaScript
|
||||
const educationPrompt = `
|
||||
Extract learning-related information for personalized education:
|
||||
|
||||
1. Learning Progress:
|
||||
- Course completions and current modules
|
||||
- Skills acquired and improvement areas
|
||||
- Learning goals and objectives
|
||||
|
||||
2. Student Preferences:
|
||||
- Learning styles (visual, audio, hands-on)
|
||||
- Time availability and scheduling
|
||||
- Subject interests and career goals
|
||||
|
||||
3. Performance Data:
|
||||
- Assignment feedback and patterns
|
||||
- Areas of struggle or strength
|
||||
- Study habits and engagement
|
||||
|
||||
Exclude: Specific grades, personal identifiers, financial information.
|
||||
`;
|
||||
|
||||
await client.project.update({ custom_instructions: educationPrompt });
|
||||
```
|
||||
</CodeGroup>
|
||||
</Tab>
|
||||
<Tab title="AI Financial Advisor">
|
||||
<CodeGroup>
|
||||
```python Python
|
||||
finance_prompt = """
|
||||
Extract financial planning information for advisory services:
|
||||
|
||||
1. Financial Goals:
|
||||
- Retirement and investment objectives
|
||||
- Risk tolerance and preferences
|
||||
- Short-term and long-term goals
|
||||
|
||||
2. Life Events:
|
||||
- Career and income changes
|
||||
- Family changes (marriage, children)
|
||||
- Major planned purchases
|
||||
|
||||
3. Investment Interests:
|
||||
- Asset allocation preferences
|
||||
- ESG or ethical investment interests
|
||||
- Previous investment experience
|
||||
|
||||
Exclude: Account numbers, SSNs, passwords, specific financial amounts.
|
||||
"""
|
||||
|
||||
client.project.update(custom_instructions=finance_prompt)
|
||||
```
|
||||
|
||||
```javascript JavaScript
|
||||
const financePrompt = `
|
||||
Extract financial planning information for advisory services:
|
||||
|
||||
1. Financial Goals:
|
||||
- Retirement and investment objectives
|
||||
- Risk tolerance and preferences
|
||||
- Short-term and long-term goals
|
||||
|
||||
2. Life Events:
|
||||
- Career and income changes
|
||||
- Family changes (marriage, children)
|
||||
- Major planned purchases
|
||||
|
||||
3. Investment Interests:
|
||||
- Asset allocation preferences
|
||||
- ESG or ethical investment interests
|
||||
- Previous investment experience
|
||||
|
||||
Exclude: Account numbers, SSNs, passwords, specific financial amounts.
|
||||
`;
|
||||
|
||||
await client.project.update({ custom_instructions: financePrompt });
|
||||
```
|
||||
</CodeGroup>
|
||||
</Tab>
|
||||
</Tabs>
|
||||
|
||||
## Advanced Techniques
|
||||
|
||||
### Conditional Processing
|
||||
|
||||
Handle different conversation types with conditional logic:
|
||||
|
||||
<CodeGroup>
|
||||
```python Python
|
||||
advanced_prompt = """
|
||||
Extract information based on conversation context:
|
||||
|
||||
IF customer support conversation:
|
||||
- Issue type, severity, resolution status
|
||||
- Customer satisfaction indicators
|
||||
|
||||
IF sales conversation:
|
||||
- Product interests, budget range
|
||||
- Decision timeline and influencers
|
||||
|
||||
IF onboarding conversation:
|
||||
- User experience level
|
||||
- Feature interests and priorities
|
||||
|
||||
Always exclude personal identifiers and maintain professional context.
|
||||
"""
|
||||
|
||||
client.project.update(custom_instructions=advanced_prompt)
|
||||
```
|
||||
</CodeGroup>
|
||||
|
||||
### Testing Your Instructions
|
||||
|
||||
Always test your custom instructions with real messages examples:
|
||||
|
||||
<CodeGroup>
|
||||
```python Python
|
||||
# Test with sample messages
|
||||
messages = [
|
||||
{"role": "user", "content": "I'm having billing issues with my subscription"},
|
||||
{"role": "assistant", "content": "I can help with that. What's the specific problem?"},
|
||||
{"role": "user", "content": "I'm being charged twice each month"}
|
||||
]
|
||||
|
||||
# Add the messages and check extracted memories
|
||||
result = client.add(messages, user_id="test_user")
|
||||
memories = client.get_all(user_id="test_user")
|
||||
|
||||
# Review if the right information was extracted
|
||||
for memory in memories:
|
||||
print(f"Extracted: {memory['memory']}")
|
||||
```
|
||||
</CodeGroup>
|
||||
|
||||
## Best Practices
|
||||
|
||||
### ✅ Do
|
||||
- **Be specific** about what information to extract
|
||||
- **Use clear categories** to organize your instructions
|
||||
- **Test with real conversations** before deploying
|
||||
- **Explicitly state exclusions** for privacy and compliance
|
||||
- **Start simple** and iterate based on results
|
||||
|
||||
### ❌ Don't
|
||||
- Make instructions too long or complex
|
||||
- Create conflicting rules within your guidelines
|
||||
- Be overly restrictive (balance specificity with flexibility)
|
||||
- Forget to exclude sensitive information
|
||||
- Skip testing with diverse conversation examples
|
||||
|
||||
## Common Issues and Solutions
|
||||
|
||||
| Issue | Solution |
|
||||
|-------|----------|
|
||||
| **Instructions too long** | Break into focused categories, keep concise |
|
||||
| **Missing important data** | Add specific examples of what to capture |
|
||||
| **Capturing irrelevant info** | Strengthen exclusion rules and be more specific |
|
||||
| **Inconsistent results** | Clarify guidelines and test with more examples |
|
||||
|
||||
@@ -5,8 +5,6 @@ icon: "arrow-right"
|
||||
iconType: "solid"
|
||||
---
|
||||
|
||||
<Snippet file="blank-notif.mdx" />
|
||||
|
||||
## How to use Direct Import?
|
||||
The Direct Import feature allows users to skip the memory deduction phase and directly input pre-defined memories into the system for storage and retrieval.
|
||||
To enable this feature, you need to set the `infer` parameter to `False` in the `add` method.
|
||||
|
||||
@@ -5,8 +5,6 @@ icon: "clock"
|
||||
iconType: "solid"
|
||||
---
|
||||
|
||||
<Snippet file="blank-notif.mdx" />
|
||||
|
||||
## Benefits of Memory Expiration
|
||||
|
||||
Setting expiration dates for memories offers several advantages:
|
||||
|
||||
@@ -4,8 +4,6 @@ icon: "thumbs-up"
|
||||
iconType: "solid"
|
||||
---
|
||||
|
||||
<Snippet file="blank-notif.mdx" />
|
||||
|
||||
Mem0's **Feedback Mechanism** allows you to provide feedback on the memories generated by your application. This feedback is used to improve the accuracy of the memories and the search results.
|
||||
|
||||
## How it works
|
||||
@@ -50,15 +48,154 @@ The `feedback` parameter can be one of the following values:
|
||||
|
||||
## Parameters
|
||||
|
||||
The `feedback` method takes the following parameters:
|
||||
The `feedback` method accepts these parameters:
|
||||
|
||||
- `memory_id`: The ID of the memory to give feedback on.
|
||||
- `feedback`: The feedback to give on the memory. (Optional)
|
||||
- `feedback_reason`: The reason for the feedback. (Optional)
|
||||
|
||||
The `feedback_reason` parameter is optional and can be used to provide a reason for the feedback.
|
||||
| Parameter | Type | Required | Description |
|
||||
|-----------|------|----------|-------------|
|
||||
| `memory_id` | string | Yes | The ID of the memory to give feedback on |
|
||||
| `feedback` | string | No | Type of feedback: `POSITIVE`, `NEGATIVE`, or `VERY_NEGATIVE` |
|
||||
| `feedback_reason` | string | No | Optional explanation for the feedback |
|
||||
|
||||
<Note>
|
||||
You can pass `None` or `null` to the `feedback` and `feedback_reason` parameters to remove the feedback for a memory.
|
||||
Pass `None` or `null` to the `feedback` and `feedback_reason` parameters to remove existing feedback for a memory.
|
||||
</Note>
|
||||
|
||||
## Bulk Feedback Operations
|
||||
|
||||
For applications with high volumes of feedback, you can provide feedback on multiple memories at once:
|
||||
|
||||
<CodeGroup>
|
||||
|
||||
```python Python
|
||||
from mem0 import MemoryClient
|
||||
|
||||
client = MemoryClient(api_key="your_api_key")
|
||||
|
||||
# Bulk feedback example
|
||||
feedback_data = [
|
||||
{
|
||||
"memory_id": "memory-1",
|
||||
"feedback": "POSITIVE",
|
||||
"feedback_reason": "Accurately captured the user's preference"
|
||||
},
|
||||
{
|
||||
"memory_id": "memory-2",
|
||||
"feedback": "NEGATIVE",
|
||||
"feedback_reason": "Contains outdated information"
|
||||
}
|
||||
]
|
||||
|
||||
for item in feedback_data:
|
||||
client.feedback(**item)
|
||||
```
|
||||
|
||||
```javascript JavaScript
|
||||
import MemoryClient from 'mem0ai';
|
||||
|
||||
const client = new MemoryClient({ apiKey: 'your-api-key'});
|
||||
|
||||
// Bulk feedback example
|
||||
const feedbackData = [
|
||||
{
|
||||
memory_id: "memory-1",
|
||||
feedback: "POSITIVE",
|
||||
feedback_reason: "Accurately captured the user's preference"
|
||||
},
|
||||
{
|
||||
memory_id: "memory-2",
|
||||
feedback: "NEGATIVE",
|
||||
feedback_reason: "Contains outdated information"
|
||||
}
|
||||
];
|
||||
|
||||
for (const item of feedbackData) {
|
||||
await client.feedback(item);
|
||||
}
|
||||
```
|
||||
|
||||
</CodeGroup>
|
||||
|
||||
## Best Practices
|
||||
|
||||
### When to Provide Feedback
|
||||
- **Immediately after memory retrieval** when you can assess relevance
|
||||
- **During user interactions** when users explicitly indicate satisfaction/dissatisfaction
|
||||
- **Through automated evaluation** using your application's success metrics
|
||||
|
||||
### Effective Feedback Reasons
|
||||
Provide specific, actionable feedback reasons:
|
||||
|
||||
✅ **Good examples:**
|
||||
- "Contains outdated contact information"
|
||||
- "Accurately captured the user's dietary restrictions"
|
||||
- "Irrelevant to the current conversation context"
|
||||
|
||||
❌ **Avoid vague reasons:**
|
||||
- "Bad memory"
|
||||
- "Wrong"
|
||||
- "Not good"
|
||||
|
||||
### Feedback Strategy
|
||||
1. **Be consistent** - Apply the same criteria across similar memories
|
||||
2. **Be specific** - Detailed reasons help improve the system faster
|
||||
3. **Monitor patterns** - Regular feedback analysis helps identify improvement areas
|
||||
|
||||
## Error Handling
|
||||
|
||||
Handle potential errors when submitting feedback:
|
||||
|
||||
<CodeGroup>
|
||||
|
||||
```python Python
|
||||
from mem0 import MemoryClient
|
||||
from mem0.exceptions import MemoryNotFoundError, APIError
|
||||
|
||||
client = MemoryClient(api_key="your_api_key")
|
||||
|
||||
try:
|
||||
client.feedback(
|
||||
memory_id="memory-123",
|
||||
feedback="POSITIVE",
|
||||
feedback_reason="Helpful context for user query"
|
||||
)
|
||||
print("Feedback submitted successfully")
|
||||
except MemoryNotFoundError:
|
||||
print("Memory not found")
|
||||
except APIError as e:
|
||||
print(f"API error: {e}")
|
||||
except Exception as e:
|
||||
print(f"Unexpected error: {e}")
|
||||
```
|
||||
|
||||
```javascript JavaScript
|
||||
import MemoryClient from 'mem0ai';
|
||||
|
||||
const client = new MemoryClient({ apiKey: 'your-api-key'});
|
||||
|
||||
try {
|
||||
await client.feedback({
|
||||
memory_id: "memory-123",
|
||||
feedback: "POSITIVE",
|
||||
feedback_reason: "Helpful context for user query"
|
||||
});
|
||||
console.log("Feedback submitted successfully");
|
||||
} catch (error) {
|
||||
if (error.status === 404) {
|
||||
console.log("Memory not found");
|
||||
} else {
|
||||
console.log(`Error: ${error.message}`);
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
</CodeGroup>
|
||||
|
||||
## Feedback Analytics
|
||||
|
||||
Track the impact of your feedback by monitoring memory performance over time. Consider implementing:
|
||||
|
||||
- **Feedback completion rates** - What percentage of memories receive feedback
|
||||
- **Feedback distribution** - Balance of positive vs. negative feedback
|
||||
- **Memory quality trends** - How accuracy improves with feedback volume
|
||||
- **User satisfaction metrics** - Correlation between feedback and user experience
|
||||
|
||||
|
||||
@@ -5,8 +5,6 @@ iconType: "solid"
|
||||
description: "Enable graph-based memory retrieval for more contextually relevant results"
|
||||
---
|
||||
|
||||
<Snippet file="blank-notif.mdx" />
|
||||
|
||||
## Overview
|
||||
|
||||
Graph Memory enhances memory pipeline by creating relationships between entities in your data. It builds a network of interconnected information for more contextually relevant search results.
|
||||
|
||||
@@ -5,8 +5,6 @@ icon: "file-export"
|
||||
iconType: "solid"
|
||||
---
|
||||
|
||||
<Snippet file="blank-notif.mdx" />
|
||||
|
||||
## Overview
|
||||
|
||||
The Memory Export feature allows you to create structured exports of memories using customizable Pydantic schemas. This process enables you to transform your stored memories into specific data formats that match your needs. You can apply various filters to narrow down which memories to export and define exactly how the data should be structured.
|
||||
|
||||
@@ -5,8 +5,6 @@ icon: "image"
|
||||
iconType: "solid"
|
||||
---
|
||||
|
||||
<Snippet file="blank-notif.mdx" />
|
||||
|
||||
Mem0 extends its capabilities beyond text by supporting multimodal data, including images and documents. With this feature, users can seamlessly integrate visual and document content into their interactions—allowing Mem0 to extract relevant information from various media types and enrich the memory system.
|
||||
|
||||
## How It Works
|
||||
|
||||
@@ -4,8 +4,6 @@ icon: "info"
|
||||
iconType: "solid"
|
||||
---
|
||||
|
||||
<Snippet file="blank-notif.mdx" />
|
||||
|
||||
Learn about the key features and capabilities that make Mem0 a powerful platform for memory management and retrieval.
|
||||
|
||||
## Core Features
|
||||
|
||||
@@ -5,8 +5,6 @@ icon: "filter"
|
||||
iconType: "solid"
|
||||
---
|
||||
|
||||
<Snippet file="blank-notif.mdx" />
|
||||
|
||||
## Benefits of Memory Customization
|
||||
|
||||
Memory customization offers several key benefits:
|
||||
|
||||
@@ -5,8 +5,6 @@ icon: "clock"
|
||||
iconType: "solid"
|
||||
---
|
||||
|
||||
<Snippet file="blank-notif.mdx" />
|
||||
|
||||
## Overview
|
||||
|
||||
The Memory Timestamps feature allows you to specify when a memory was created, regardless of when it's actually added to the system. This powerful capability enables you to:
|
||||
|
||||
@@ -5,8 +5,6 @@ icon: "webhook"
|
||||
iconType: "solid"
|
||||
---
|
||||
|
||||
<Snippet file="blank-notif.mdx" />
|
||||
|
||||
## Overview
|
||||
|
||||
Webhooks enable real-time notifications for memory events in your Mem0 project. Webhooks are configured at the project level, meaning each webhook is tied to a specific project and receives events solely from that project. You can configure webhooks to send HTTP POST requests to your specified URLs whenever memories are created, updated, or deleted.
|
||||
|
||||
@@ -5,8 +5,6 @@ icon: "eye"
|
||||
iconType: "solid"
|
||||
---
|
||||
|
||||
<Snippet file="async-memory-add.mdx" />
|
||||
|
||||
## Welcome to Mem0 Platform
|
||||
|
||||
The Mem0 Platform is a managed service and the easiest way to add our powerful memory layer to your applications.
|
||||
|
||||
+94
-2051
File diff suppressed because it is too large
Load Diff
Reference in New Issue
Block a user