Merge branch 'main' into mem0-1.0.0

This commit is contained in:
parshvadaftari
2025-09-16 00:01:42 +05:30
60 changed files with 2346 additions and 248 deletions
@@ -70,3 +70,39 @@ The v2 search API is powerful and flexible, allowing for more precise memory ret
)
```
</CodeGroup>
<CodeGroup>
```python Categories Filter Examples
# Example 1: Using 'contains' for partial matching
finance_memories = m.search(
query="What are my financial goals?",
version="v2",
filters={
"AND": [
{ "user_id": "alice" },
{
"categories": {
"contains": "finance"
}
}
]
},
)
# Example 2: Using 'in' for exact matching
personal_memories = m.search(
query="What personal information do you have?",
version="v2",
filters={
"AND": [
{ "user_id": "alice" },
{
"categories": {
"in": ["personal_information"]
}
}
]
},
)
```
</CodeGroup>
+53
View File
@@ -7,6 +7,49 @@ mode: "wide"
<Tabs>
<Tab title="Python">
<Update label="2025-09-03" description="v0.1.117">
**New Features & Updates:**
- **OpenMemory:**
- Added memory export / import feature
- Added vector store integrations: Weaviate, FAISS, PGVector, Chroma, Redis, Elasticsearch, Milvus
- Added `export_openmemory.sh` migration script
- **Vector Stores:**
- Added Amazon S3 Vectors support
- Added Databricks Mosaic AI vector store support
- Added support for OpenAI Store
- **Graph Memory:** Added support for graph memory using Kuzu
- **Azure:** Added Azure Identity for Azure OpenAI and Azure AI Search authentication
- **Elasticsearch:** Added headers configuration support
**Improvements:**
- Added custom connection client to enable connecting to local containers for Weaviate
- Updated configuration AWS Bedrock
- Fixed dependency issues and tests; updated docstrings
- **Documentation:**
- Fixed Graph Docs page missing in sidebar
- Updated integration documentation
- Added version param in Search V2 API documentation
- Updated Databricks documentation and refactored docs
- Updated favicon logo
- Fixed typos and Typescript docs
**Bug Fixes:**
- Baidu: Added missing provider for Baidu vector DB
- MongoDB: Replaced `query_vector` args in search method
- Fixed new memory mistaken for current
- AsyncMemory._add_to_vector_store: handled edge case when no facts found
- Fixed missing commas in Kuzu graph INSERT queries
- Fixed inconsistent created and updated properties for Graph
- Fixed missing `app_id` on client for Neptune Analytics
- Correctly pick AWS region from environment variable
- Fixed Ollama model existence check
**Refactoring:**
- **PGVector:** Use internal connection pools and context managers
</Update>
<Update label="2025-08-14" description="v0.1.116">
**New Features & Updates:**
@@ -568,6 +611,11 @@ mode: "wide"
<Tab title="TypeScript">
<Update label="2025-09-04" description="v2.1.38">
**New Features:**
- **Client:** Added `metadata` param to `update` method.
</Update>
<Update label="2025-08-04" description="v2.1.37">
**New Features:**
- **OSS:** Added `RedisCloud` search module check
@@ -1039,6 +1087,11 @@ mode: "wide"
<Tab title="Vercel AI SDK">
<Update label="2025-09-03" description="v2.0.2">
**Bug Fix:**
- **Vercel AI SDK:** Fixed streaming response in the AI SDK.
</Update>
<Update label="2025-08-05" description="v2.0.1">
**New Features:**
- **Vercel AI SDK:** Added a new param `host` to the config.
+1 -1
View File
@@ -8,7 +8,7 @@ iconType: "solid"
The `config` is defined as an object with two main keys:
- `vector_store`: Specifies the vector database provider and its configuration
- `provider`: The name of the vector database (e.g., "chroma", "pgvector", "qdrant", "milvus", "upstash_vector", "azure_ai_search", "vertex_ai_vector_search")
- `provider`: The name of the vector database (e.g., "chroma", "pgvector", "qdrant", "milvus", "upstash_vector", "azure_ai_search", "vertex_ai_vector_search", "valkey")
- `config`: A nested dictionary containing provider-specific settings
+9 -2
View File
@@ -1,7 +1,9 @@
[Chroma](https://www.trychroma.com/) is an AI-native open-source vector database that simplifies building LLM apps by providing tools for storing, embedding, and searching embeddings with a focus on simplicity and speed.
[Chroma](https://www.trychroma.com/) is an AI-native open-source vector database that simplifies building LLM apps by providing tools for storing, embedding, and searching embeddings with a focus on simplicity and speed. It supports both local deployment and cloud hosting through ChromaDB Cloud.
### Usage
#### Local Installation
```python
import os
from mem0 import Memory
@@ -14,6 +16,9 @@ config = {
"config": {
"collection_name": "test",
"path": "db",
# Optional: ChromaDB Cloud configuration
# "api_key": "your-chroma-cloud-api-key",
# "tenant": "your-chroma-cloud-tenant-id",
}
}
}
@@ -38,4 +43,6 @@ Here are the parameters available for configuring Chroma:
| `client` | Custom client for Chroma | `None` |
| `path` | Path for the Chroma database | `db` |
| `host` | The host where the Chroma server is running | `None` |
| `port` | The port where the Chroma server is running | `None` |
| `port` | The port where the Chroma server is running | `None` |
| `api_key` | ChromaDB Cloud API key (for cloud usage) | `None` |
| `tenant` | ChromaDB Cloud tenant ID (for cloud usage) | `None` |
+49
View File
@@ -0,0 +1,49 @@
# Valkey Vector Store
[Valkey](https://valkey.io/) is an open source (BSD) high-performance key/value datastore that supports a variety of workloads and rich datastructures including vector search.
## Installation
```bash
pip install mem0ai[vector_stores]
```
## Usage
```python
config = {
"vector_store": {
"provider": "valkey",
"config": {
"collection_name": "test",
"valkey_url": "valkey://localhost:6379",
"embedding_model_dims": 1536,
"index_type": "flat"
}
}
}
m = Memory.from_config(config)
messages = [
{"role": "user", "content": "I'm planning to watch a movie tonight. Any recommendations?"},
{"role": "assistant", "content": "How about a thriller movies? They can be quite engaging."},
{"role": "user", "content": "I'm not a big fan of thriller movies but I love sci-fi movies."},
{"role": "assistant", "content": "Got it! I'll avoid thriller recommendations and suggest sci-fi movies in the future."}
]
m.add(messages, user_id="alice", metadata={"category": "movies"})
```
## Parameters
Let's see the available parameters for the `valkey` config:
| Parameter | Description | Default Value |
| --- | --- | --- |
| `collection_name` | The name of the collection to store the vectors | `mem0` |
| `valkey_url` | Connection URL for the Valkey server | `valkey://localhost:6379` |
| `embedding_model_dims` | Dimensions of the embedding model | `1536` |
| `index_type` | Vector index algorithm (`hnsw` or `flat`) | `hnsw` |
| `hnsw_m` | Number of bi-directional links for HNSW | `16` |
| `hnsw_ef_construction` | Size of dynamic candidate list for HNSW | `200` |
| `hnsw_ef_runtime` | Size of dynamic candidate list for search | `10` |
| `distance_metric` | Distance metric for vector similarity | `cosine` |
+2 -1
View File
@@ -11,7 +11,7 @@ Mem0 includes built-in support for various popular databases. Memory can utilize
See the list of supported vector databases below.
<Note>
The following vector databases are supported in the Python implementation. The TypeScript implementation currently only supports Qdrant, Redis,Vectorize and in-memory vector database.
The following vector databases are supported in the Python implementation. The TypeScript implementation currently only supports Qdrant, Redis, Valkey, Vectorize and in-memory vector database.
</Note>
<CardGroup cols={3}>
@@ -24,6 +24,7 @@ See the list of supported vector databases below.
<Card title="MongoDB" href="/components/vectordbs/dbs/mongodb"></Card>
<Card title="Azure" href="/components/vectordbs/dbs/azure"></Card>
<Card title="Redis" href="/components/vectordbs/dbs/redis"></Card>
<Card title="Valkey" href="/components/vectordbs/dbs/valkey"></Card>
<Card title="Elasticsearch" href="/components/vectordbs/dbs/elasticsearch"></Card>
<Card title="OpenSearch" href="/components/vectordbs/dbs/opensearch"></Card>
<Card title="Supabase" href="/components/vectordbs/dbs/supabase"></Card>
+5 -3
View File
@@ -1,8 +1,8 @@
{
"$schema": "https://mintlify.com/docs.json",
"theme": "maple",
"name": "Mem0",
"description": "Mem0 is a self-improving memory layer for LLM applications, enabling personalized AI experiences that save costs and delight users.",
"theme": "maple",
"colors": {
"primary": "#6c60f0",
"light": "#E6FFA2",
@@ -46,7 +46,7 @@
},
{
"group": "Platform",
"icon": "cogs",
"icon": "globe",
"pages": [
"platform/overview",
"platform/quickstart",
@@ -58,6 +58,7 @@
"platform/features/platform-overview",
"platform/features/contextual-add",
"platform/features/async-client",
"platform/features/graph-memory",
"platform/features/advanced-retrieval",
"platform/features/criteria-retrieval",
"platform/features/multimodal-support",
@@ -151,6 +152,7 @@
"components/vectordbs/dbs/mongodb",
"components/vectordbs/dbs/azure",
"components/vectordbs/dbs/redis",
"components/vectordbs/dbs/valkey",
"components/vectordbs/dbs/elasticsearch",
"components/vectordbs/dbs/opensearch",
"components/vectordbs/dbs/supabase",
@@ -380,7 +382,7 @@
"background": {
"color": {
"light": "#fff",
"dark": "#0f1117"
"dark": "#09090b"
}
},
"navbar": {
@@ -24,8 +24,7 @@ Before you begin, make sure you have:
Installed Google ADK and Mem0 SDK:
```bash
pip install google-adk
pip install mem0ai
pip install google-adk mem0ai python-dotenv
```
## Code Breakdown
@@ -35,21 +34,25 @@ Let's get started and understand the different components required in building a
```python
# Import dependencies
import os
import asyncio
from google.adk.agents import Agent
from google.adk.sessions import InMemorySessionService
from google.adk.runners import Runner
from google.adk.sessions import InMemorySessionService
from google.genai import types
from mem0 import MemoryClient
from dotenv import load_dotenv
# Set up API keys (replace with your actual keys)
os.environ["GOOGLE_API_KEY"] = "your-google-api-key"
os.environ["MEM0_API_KEY"] = "your-mem0-api-key"
load_dotenv()
# Set up environment variables
# os.environ["GOOGLE_API_KEY"] = "your-google-api-key"
# os.environ["MEM0_API_KEY"] = "your-mem0-api-key"
# Define a global user ID for simplicity
USER_ID = "Alex"
# Initialize Mem0 client
mem0_client = MemoryClient()
mem0 = MemoryClient()
```
## Define Memory Tools
+3 -1
View File
@@ -17,7 +17,7 @@ Before setting up Mem0 with AgentOps, ensure you have:
1. Installed the required packages:
```bash
pip install mem0ai agentops
pip install mem0ai agentops python-dotenv
```
2. Valid API keys:
@@ -37,7 +37,9 @@ import asyncio
import logging
from dotenv import load_dotenv
import agentops
import openai
load_dotenv()
#Set up environment variables for API keys
os.environ["AGENTOPS_API_KEY"] = os.getenv("AGENTOPS_API_KEY")
os.environ["OPENAI_API_KEY"] = os.getenv("OPENAI_API_KEY")
+9 -8
View File
@@ -18,7 +18,7 @@ Before setting up Mem0 with Agno, ensure you have:
1. Installed the required packages:
```bash
pip install agno mem0ai
pip install agno mem0ai python-dotenv
```
2. Valid API keys:
@@ -81,7 +81,7 @@ agent = Agent(
def chat_user(
user_input: Optional[str] = None,
user_id: str = "user_123",
user_id: str = "alex",
image_path: Optional[str] = None
) -> str:
"""
@@ -120,13 +120,13 @@ def chat_user(
})
# Store messages in memory
client.add(messages, user_id=user_id)
client.add(messages, user_id=user_id, output_format='v1.1')
print("✅ Image and text stored in memory.")
if user_input:
# Search for relevant memories
memories = client.search(user_input, user_id=user_id)
memory_context = "\n".join(f"- {m['memory']}" for m in memories.get('results', []))
memories = client.search(user_input, user_id=user_id, output_format='v1.1')
memory_context = "\n".join(f"- {m['memory']}" for m in memories['results'])
# Construct the prompt
prompt = f"""
@@ -150,7 +150,8 @@ User question:
response = agent.run(prompt)
# Store the interaction in memory
client.add(f"User: {user_input}\nAssistant: {response.content}", user_id=user_id)
interaction_message = [{"role": "user", "content": f"User: {user_input}\nAssistant: {response.content}"}]
client.add(interaction_message, user_id=user_id, output_format='v1.1')
return response.content
return "No user input or image provided."
@@ -159,9 +160,9 @@ User question:
# Example Usage
if __name__ == "__main__":
response = chat_user(
"This is the picture of what I brought with me in the trip to Bahamas",
"I like to travel and my favorite destination is London",
image_path="travel_items.jpeg",
user_id="user_123"
user_id="alex"
)
print(response)
```
+16 -9
View File
@@ -1,3 +1,7 @@
---
title: AutoGen
---
Build conversational AI agents with memory capabilities. This integration combines AutoGen for creating AI agents with Mem0 for memory management, enabling context-aware and personalized interactions.
## Overview
@@ -10,7 +14,7 @@ In this guide, we'll explore an example of creating a conversational AI system w
Install necessary libraries:
```bash
pip install pyautogen mem0ai openai
pip install autogen mem0ai openai python-dotenv
```
First, we'll import the necessary libraries and set up our configurations.
@@ -22,15 +26,18 @@ import os
from autogen import ConversableAgent
from mem0 import MemoryClient
from openai import OpenAI
from dotenv import load_dotenv
load_dotenv()
# Configuration
OPENAI_API_KEY = 'sk-xxx' # Replace with your actual OpenAI API key
MEM0_API_KEY = 'your-mem0-key' # Replace with your actual Mem0 API key from https://app.mem0.ai
USER_ID = "customer_service_bot"
# OPENAI_API_KEY = 'sk-xxx' # Replace with your actual OpenAI API key
# MEM0_API_KEY = 'your-mem0-key' # Replace with your actual Mem0 API key from https://app.mem0.ai
USER_ID = "alice"
# Set up OpenAI API key
os.environ['OPENAI_API_KEY'] = OPENAI_API_KEY
os.environ['MEM0_API_KEY'] = MEM0_API_KEY
OPENAI_API_KEY = os.environ.get('OPENAI_API_KEY')
# os.environ['MEM0_API_KEY'] = MEM0_API_KEY
# Initialize Mem0 and AutoGen agents
memory_client = MemoryClient()
@@ -55,7 +62,7 @@ conversation = [
{"role": "assistant", "content": "Thank you for the information. Let's troubleshoot this issue..."}
]
memory_client.add(messages=conversation, user_id=USER_ID)
memory_client.add(messages=conversation, user_id=USER_ID, output_format="v1.1")
print("Conversation added to memory.")
```
@@ -65,7 +72,7 @@ Create a function to get context-aware responses based on user's question and pr
```python
def get_context_aware_response(question):
relevant_memories = memory_client.search(question, user_id=USER_ID)
relevant_memories = memory_client.search(question, user_id=USER_ID, output_format='v1.1')
context = "\n".join([m["memory"] for m in relevant_memories.get('results', [])])
prompt = f"""Answer the user question considering the previous interactions:
@@ -97,7 +104,7 @@ manager = ConversableAgent(
)
def escalate_to_manager(question):
relevant_memories = memory_client.search(question, user_id=USER_ID)
relevant_memories = memory_client.search(question, user_id=USER_ID, output_format='v1.1')
context = "\n".join([m["memory"] for m in relevant_memories.get('results', [])])
prompt = f"""
+1 -1
View File
@@ -16,7 +16,7 @@ In this guide, we'll build a voice agent that:
Install necessary libraries:
```bash
pip install elevenlabs mem0 python-dotenv
pip install elevenlabs mem0ai python-dotenv
```
Configure your environment variables:
+16 -11
View File
@@ -17,7 +17,7 @@ Before setting up Mem0 with Google ADK, ensure you have:
1. Installed the required packages:
```bash
pip install google-adk mem0ai
pip install google-adk mem0ai python-dotenv
```
2. Valid API keys:
@@ -30,15 +30,19 @@ The following example demonstrates how to create a Google ADK agent with Mem0 me
```python
import os
import asyncio
from google.adk.agents import Agent
from google.adk.runners import Runner
from google.adk.sessions import InMemorySessionService
from google.genai import types
from mem0 import MemoryClient
from dotenv import load_dotenv
load_dotenv()
# Set up environment variables
os.environ["GOOGLE_API_KEY"] = "your-google-api-key"
os.environ["MEM0_API_KEY"] = "your-mem0-api-key"
# os.environ["GOOGLE_API_KEY"] = "your-google-api-key"
# os.environ["MEM0_API_KEY"] = "your-mem0-api-key"
# Initialize Mem0 client
mem0 = MemoryClient()
@@ -46,17 +50,18 @@ mem0 = MemoryClient()
# Define memory function tools
def search_memory(query: str, user_id: str) -> dict:
"""Search through past conversations and memories"""
memories = mem0.search(query, user_id=user_id)
memories = mem0.search(query, user_id=user_id, output_format='v1.1')
if memories.get('results', []):
memory_context = "\n".join([f"- {mem['memory']}" for mem in memories.get('results', [])])
memory_list = memories['results']
memory_context = "\n".join([f"- {mem['memory']}" for mem in memory_list])
return {"status": "success", "memories": memory_context}
return {"status": "no_memories", "message": "No relevant memories found"}
def save_memory(content: str, user_id: str) -> dict:
"""Save important information to memory"""
try:
mem0.add([{"role": "user", "content": content}], user_id=user_id)
return {"status": "success", "message": "Information saved to memory"}
result = mem0.add([{"role": "user", "content": content}], user_id=user_id, output_format='v1.1')
return {"status": "success", "message": "Information saved to memory", "result": result}
except Exception as e:
return {"status": "error", "message": f"Failed to save memory: {str(e)}"}
@@ -72,7 +77,7 @@ personal_assistant = Agent(
tools=[search_memory, save_memory]
)
def chat_with_agent(user_input: str, user_id: str) -> str:
async def chat_with_agent(user_input: str, user_id: str) -> str:
"""
Handle user input with automatic memory integration.
@@ -85,7 +90,7 @@ def chat_with_agent(user_input: str, user_id: str) -> str:
"""
# Set up session and runner
session_service = InMemorySessionService()
session = session_service.create_session(
session = await session_service.create_session(
app_name="memory_assistant",
user_id=user_id,
session_id=f"session_{user_id}"
@@ -107,10 +112,10 @@ def chat_with_agent(user_input: str, user_id: str) -> str:
# Example usage
if __name__ == "__main__":
response = chat_with_agent(
response = asyncio.run(chat_with_agent(
"I love Italian food and I'm planning a trip to Rome next month",
user_id="alice"
)
))
print(response)
```
+42 -28
View File
@@ -16,7 +16,7 @@ In this guide, we'll create a Travel Agent AI that:
Install necessary libraries:
```bash
pip install langchain langchain_openai mem0ai
pip install langchain langchain_openai mem0ai python-dotenv
```
Import required modules and set up configurations:
@@ -30,10 +30,13 @@ from langchain_openai import ChatOpenAI
from langchain_core.messages import SystemMessage, HumanMessage, AIMessage
from langchain_core.prompts import ChatPromptTemplate, MessagesPlaceholder
from mem0 import MemoryClient
from dotenv import load_dotenv
load_dotenv()
# Configuration
os.environ["OPENAI_API_KEY"] = "your-openai-api-key"
os.environ["MEM0_API_KEY"] = "your-mem0-api-key"
# os.environ["OPENAI_API_KEY"] = "your-openai-api-key"
# os.environ["MEM0_API_KEY"] = "your-mem0-api-key"
# Initialize LangChain and Mem0
llm = ChatOpenAI(model="gpt-4o-mini")
@@ -61,19 +64,26 @@ Create functions to handle context retrieval, response generation, and addition
```python
def retrieve_context(query: str, user_id: str) -> List[Dict]:
"""Retrieve relevant context from Mem0"""
memories = mem0.search(query, user_id=user_id)
serialized_memories = ' '.join([mem["memory"] for mem in memories.get('results', [])])
context = [
{
"role": "system",
"content": f"Relevant information: {serialized_memories}"
},
{
"role": "user",
"content": query
}
]
return context
try:
memories = mem0.search(query, user_id=user_id, output_format='v1.1')
memory_list = memories['results']
serialized_memories = ' '.join([mem["memory"] for mem in memory_list])
context = [
{
"role": "system",
"content": f"Relevant information: {serialized_memories}"
},
{
"role": "user",
"content": query
}
]
return context
except Exception as e:
print(f"Error retrieving memories: {e}")
# Return empty context if there's an error
return [{"role": "user", "content": query}]
def generate_response(input: str, context: List[Dict]) -> str:
"""Generate a response using the language model"""
@@ -86,17 +96,21 @@ def generate_response(input: str, context: List[Dict]) -> str:
def save_interaction(user_id: str, user_input: str, assistant_response: str):
"""Save the interaction to Mem0"""
interaction = [
{
"role": "user",
"content": user_input
},
{
"role": "assistant",
"content": assistant_response
}
]
mem0.add(interaction, user_id=user_id)
try:
interaction = [
{
"role": "user",
"content": user_input
},
{
"role": "assistant",
"content": assistant_response
}
]
result = mem0.add(interaction, user_id=user_id, output_format='v1.1')
print(f"Memory saved successfully: {len(result.get('results', []))} memories added")
except Exception as e:
print(f"Error saving interaction: {e}")
```
## Create Chat Turn Function
@@ -124,7 +138,7 @@ Set up the main program loop for user interaction:
```python
if __name__ == "__main__":
print("Welcome to your personal Travel Agent Planner! How can I assist you with your travel plans today?")
user_id = "john"
user_id = "alice"
while True:
user_input = input("You: ")
+45 -17
View File
@@ -16,7 +16,7 @@ In this guide, we'll create a Customer Support AI Agent that:
Install necessary libraries:
```bash
pip install langgraph langchain-openai mem0ai
pip install langgraph langchain-openai mem0ai python-dotenv
```
@@ -31,14 +31,17 @@ from langgraph.graph.message import add_messages
from langchain_openai import ChatOpenAI
from mem0 import MemoryClient
from langchain_core.messages import SystemMessage, HumanMessage, AIMessage
from dotenv import load_dotenv
load_dotenv()
# Configuration
OPENAI_API_KEY = 'sk-xxx' # Replace with your actual OpenAI API key
MEM0_API_KEY = 'your-mem0-key' # Replace with your actual Mem0 API key
# OPENAI_API_KEY = 'sk-xxx' # Replace with your actual OpenAI API key
# MEM0_API_KEY = 'your-mem0-key' # Replace with your actual Mem0 API key
# Initialize LangChain and Mem0
llm = ChatOpenAI(model="gpt-4", api_key=OPENAI_API_KEY)
mem0 = MemoryClient(api_key=MEM0_API_KEY)
llm = ChatOpenAI(model="gpt-4")
mem0 = MemoryClient()
```
## Define State and Graph
@@ -62,22 +65,47 @@ def chatbot(state: State):
messages = state["messages"]
user_id = state["mem0_user_id"]
# Retrieve relevant memories
memories = mem0.search(messages[-1].content, user_id=user_id)
try:
# Retrieve relevant memories
memories = mem0.search(messages[-1].content, user_id=user_id, output_format='v1.1')
# Handle dict response format
memory_list = memories['results']
context = "Relevant information from previous conversations:\n"
for memory in memories.get('results', []):
context += f"- {memory['memory']}\n"
context = "Relevant information from previous conversations:\n"
for memory in memory_list:
context += f"- {memory['memory']}\n"
system_message = SystemMessage(content=f"""You are a helpful customer support assistant. Use the provided context to personalize your responses and remember user preferences and past interactions.
system_message = SystemMessage(content=f"""You are a helpful customer support assistant. Use the provided context to personalize your responses and remember user preferences and past interactions.
{context}""")
full_messages = [system_message] + messages
response = llm.invoke(full_messages)
full_messages = [system_message] + messages
response = llm.invoke(full_messages)
# Store the interaction in Mem0
mem0.add(f"User: {messages[-1].content}\nAssistant: {response.content}", user_id=user_id)
return {"messages": [response]}
# Store the interaction in Mem0
try:
interaction = [
{
"role": "user",
"content": messages[-1].content
},
{
"role": "assistant",
"content": response.content
}
]
result = mem0.add(interaction, user_id=user_id, output_format='v1.1')
print(f"Memory saved: {len(result.get('results', []))} memories added")
except Exception as e:
print(f"Error saving memory: {e}")
return {"messages": [response]}
except Exception as e:
print(f"Error in chatbot: {e}")
# Fallback response without memory context
response = llm.invoke(messages)
return {"messages": [response]}
```
## Set Up Graph Structure
@@ -115,7 +143,7 @@ Set up the main program loop for user interaction:
```python
if __name__ == "__main__":
print("Welcome to Customer Support! How can I assist you today?")
mem0_user_id = "customer_123" # You can generate or retrieve this based on your user management system
mem0_user_id = "alice" # You can generate or retrieve this based on your user management system
while True:
user_input = input("You: ")
if user_input.lower() in ['quit', 'exit', 'bye']:
+20 -12
View File
@@ -13,7 +13,7 @@ LlamaIndex supports Mem0 as a [memory store](https://llamahub.ai/l/memory/llama-
To install the required package, run:
```bash
pip install llama-index-core llama-index-memory-mem0
pip install llama-index-core llama-index-memory-mem0 python-dotenv
```
### Setup with Mem0 Platform
@@ -25,18 +25,23 @@ Set your Mem0 Platform API key as an environment variable. You can replace `<you
</Note>
```python
os.environ["MEM0_API_KEY"] = "<your-mem0-api-key>"
from dotenv import load_dotenv
import os
load_dotenv()
# os.environ["MEM0_API_KEY"] = "<your-mem0-api-key>"
```
Import the necessary modules and create a Mem0Memory instance:
```python
from llama_index.memory.mem0 import Mem0Memory
context = {"user_id": "user_1"}
context = {"user_id": "alice"}
memory_from_client = Mem0Memory.from_client(
context=context,
api_key="<your-mem0-api-key>",
search_msg_limit=4, # optional, default is 5
output_format='v1.1', # Remove deprecation warnings
)
```
@@ -44,8 +49,8 @@ Context is used to identify the user, agent or the conversation in the Mem0. It
```python
context = {
"user_id": "user_1",
"agent_id": "agent_1",
"user_id": "alice",
"agent_id": "llama_agent_1",
"run_id": "run_1",
}
```
@@ -98,17 +103,20 @@ memory_from_config = Mem0Memory.from_config(
context=context,
config=config,
search_msg_limit=4, # optional, default is 5
output_format='v1.1', # Remove deprecation warnings
)
```
Initialize the LLM
```python
import os
from llama_index.llms.openai import OpenAI
from dotenv import load_dotenv
os.environ["OPENAI_API_KEY"] = "<your-openai-api-key>"
llm = OpenAI(model="gpt-4o")
load_dotenv()
# os.environ["OPENAI_API_KEY"] = "<your-openai-api-key>"
llm = OpenAI(model="gpt-4o-mini")
```
### SimpleChatEngine
@@ -122,7 +130,7 @@ agent = SimpleChatEngine.from_defaults(
)
# Start the chat
response = agent.chat("Hi, My name is Mayank")
response = agent.chat("Hi, My name is Alice")
print(response)
```
Now we will learn how to use Mem0 with FunctionCalling and ReAct agents.
@@ -165,7 +173,7 @@ agent = FunctionCallingAgent.from_tools(
)
# Start the chat
response = agent.chat("Hi, My name is Mayank")
response = agent.chat("Hi, My name is Alice")
print(response)
```
@@ -182,7 +190,7 @@ agent = ReActAgent.from_tools(
)
# Start the chat
response = agent.chat("Hi, My name is Mayank")
response = agent.chat("Hi, My name is Alice")
print(response)
```
+1 -1
View File
@@ -92,7 +92,7 @@ async def websocket_endpoint(websocket: WebSocket):
await websocket.accept()
# Basic setup with minimal configuration
user_id = "user123"
user_id = "alice"
# WebSocket transport
transport = FastAPIWebsocketTransport(
Binary file not shown.

Before

Width:  |  Height:  |  Size: 66 KiB

After

Width:  |  Height:  |  Size: 75 KiB

+22 -6
View File
@@ -1076,9 +1076,14 @@
"run_id": {"type": "string"},
"created_at": {"type": "string", "format": "date-time"},
"updated_at": {"type": "string", "format": "date-time"},
"categories": {"type": "array", "items": {"type": "string"}},
"categories": {"type": "object", "properties": {
"in": {"type": "array", "items": {"type": "string"}}
}},
"metadata": {"type": "object"},
"keywords": {"type": "string"}
"keywords": {"type": "object", "properties": {
"contains": {"type": "string"},
"icontains": {"type": "string"}
}}
},
"additionalProperties": {
"type": "object",
@@ -1094,7 +1099,7 @@
}
}
},
"description": "Filters to apply to the memories. Available fields are: user_id, agent_id, app_id, run_id, created_at, updated_at, categories, keywords. Supports logical operators (AND, OR) and comparison operators (in, gte, lte, gt, lt, ne, contains, icontains)",
"description": "Filters to apply to the memories. Available fields are: user_id, agent_id, app_id, run_id, created_at, updated_at, categories, keywords. Supports logical operators (AND, OR) and comparison operators (in, gte, lte, gt, lt, ne, contains, icontains). For categories field, use 'contains' for partial matching (e.g., {\"categories\": {\"contains\": \"finance\"}}) or 'in' for exact matching (e.g., {\"categories\": {\"in\": [\"personal_information\"]}}).",
"style": "deepObject",
"explode": true
},
@@ -5074,10 +5079,16 @@
"type": "string",
"description": "The query to search for in the memory."
},
"version": {
"title": "Version",
"type": "string",
"default": "v2",
"description": "The version of the memory to use. This should always be v2."
},
"filters": {
"title": "Filters",
"type": "object",
"description": "A dictionary of filters to apply to the search. Available fields are: user_id, agent_id, app_id, run_id, created_at, updated_at, categories, keywords. Supports logical operators (AND, OR) and comparison operators (in, gte, lte, gt, lt, ne, contains, icontains).",
"description": "A dictionary of filters to apply to the search. Available fields are: user_id, agent_id, app_id, run_id, created_at, updated_at, categories, keywords. Supports logical operators (AND, OR) and comparison operators (in, gte, lte, gt, lt, ne, contains, icontains). For categories field, use 'contains' for partial matching (e.g., {\"categories\": {\"contains\": \"finance\"}}) or 'in' for exact matching (e.g., {\"categories\": {\"in\": [\"personal_information\"]}}).",
"properties": {
"user_id": {"type": "string"},
"agent_id": {"type": "string"},
@@ -5085,8 +5096,13 @@
"run_id": {"type": "string"},
"created_at": {"type": "string", "format": "date-time"},
"updated_at": {"type": "string", "format": "date-time"},
"text": {"type": "string"},
"categories": {"type": "array", "items": {"type": "string"}},
"keywords": {"type": "object", "properties": {
"contains": {"type": "string"},
"icontains": {"type": "string"}
}},
"categories": {"type": "object", "properties": {
"in": {"type": "array", "items": {"type": "string"}}
}},
"metadata": {"type": "object"}
},
"additionalProperties": {
+75 -19
View File
@@ -285,6 +285,10 @@ curl -X POST "https://api.mem0.ai/v1/memories/" \
Our advanced search allows you to set custom search filters. You can filter by user_id, agent_id, app_id, run_id, created_at, updated_at, categories, and text. The filters support logical operators (AND, OR) and comparison operators (in, gte, lte, gt, lt, ne, contains, icontains, `*`). The wildcard character (`*`) matches everything for a specific field.
For the **categories** field specifically:
- Use `contains` for partial matching (e.g., `{"categories": {"contains": "finance"}}`)
- Use `in` for exact matching (e.g., `{"categories": {"in": ["personal_information"]}}`).
Here you need to define `version` as `v2` in the search method.
#### Example 1: Search using user_id and agent_id filters
@@ -407,58 +411,106 @@ curl -X POST "https://api.mem0.ai/v1/memories/search/?version=v2" \
```
</CodeGroup>
#### Example 3: Search using metadata and categories
#### Example 3: Search using categories filters
<CodeGroup>
```python Python
query = "What do you know about me?"
# Example 3a: Using 'contains' for partial matching
query = "What are my financial goals?"
filters = {
"AND": [
{"metadata": {"food": "vegan"}},
{ "user_id": "alice" },
{
"categories":{
"contains": "food_preferences"
}
}
"categories": {
"contains": "finance"
}
}
]
}
client.search(query, version="v2", filters=filters)
# Example 3b: Using 'in' for exact matching
query = "What personal information do you have?"
filters = {
"AND": [
{ "user_id": "alice" },
{
"categories": {
"in": ["personal_information"]
}
}
]
}
client.search(query, version="v2", filters=filters)
```
```javascript JavaScript
const query = "What do you know about me?";
const filters = {
// Example 3a: Using 'contains' for partial matching
const query1 = "What are my financial goals?";
const filters1 = {
"AND": [
{"metadata": {"food": "vegan"}},
{ "user_id": "alice" },
{
"categories": {
"contains": "food_preferences"
"contains": "finance"
}
}
]
};
client.search(query, { version: "v2", filters })
client.search(query1, { version: "v2", filters: filters1 })
.then(results => console.log(results))
.catch(error => console.error(error));
// Example 3b: Using 'in' for exact matching
const query2 = "What personal information do you have?";
const filters2 = {
"AND": [
{ "user_id": "alice" },
{
"categories": {
"in": ["personal_information"]
}
}
]
};
client.search(query2, { version: "v2", filters: filters2 })
.then(results => console.log(results))
.catch(error => console.error(error));
```
```bash cURL
# Example 3a: Using 'contains' for partial matching
curl -X POST "https://api.mem0.ai/v1/memories/search/?version=v2" \
-H "Authorization: Token your-api-key" \
-H "Content-Type: application/json" \
-d '{
"query": "What do you know about me?",
"query": "What are my financial goals?",
"filters": {
"AND": [
{
"metadata": {
"food": "vegan"
}
},
{ "user_id": "alice" },
{
"categories": {
"contains": "food_preferences"
"contains": "finance"
}
}
]
}
}'
# Example 3b: Using 'in' for exact matching
curl -X POST "https://api.mem0.ai/v1/memories/search/?version=v2" \
-H "Authorization: Token your-api-key" \
-H "Content-Type: application/json" \
-d '{
"query": "What personal information do you have?",
"filters": {
"AND": [
{ "user_id": "alice" },
{
"categories": {
"in": ["personal_information"]
}
}
]
@@ -693,6 +745,10 @@ curl -X GET "https://api.mem0.ai/v1/memories/?user_id=alex&keywords=to play&page
Our advanced retrieval allows you to set custom filters when fetching memories. You can filter by user_id, agent_id, app_id, run_id, created_at, updated_at, categories, and keywords. The filters support logical operators (AND, OR) and comparison operators (in, gte, lte, gt, lt, ne, contains, icontains, `*`). The wildcard character (`*`) matches everything for a specific field.
For the **categories** field specifically:
- Use `contains` for partial matching (e.g., `{"categories": {"contains": "finance"}}`)
- Use `in` for exact matching (e.g., `{"categories": {"in": ["personal_information"]}}`).
Here you need to define `version` as `v2` in the get_all method.
<CodeGroup>
@@ -9,8 +9,6 @@ description: "Advanced memory search with keyword expansion, intelligent reranki
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.
<CodeGroup>
## Search Enhancement Options
### Keyword Search
+1 -1
View File
@@ -36,7 +36,7 @@ Learn about the key features and capabilities that make Mem0 a powerful platform
<Card title="Memory Export" icon="file-export" href="memory-export">
Export memories in structured formats using customizable Pydantic schemas.
</Card>
<Card title="Graph Memory" icon="graph" href="graph-memory">
<Card title="Graph Memory" icon="circle-nodes" href="graph-memory">
Add memories in the form of nodes and edges in a graph database and search for related memories.
</Card>
</CardGroup>