chore: remove legacy v0.x docs and version dropdown (#4060)

This commit is contained in:
Saket Aryan
2026-02-17 02:55:05 +05:30
committed by GitHub
parent 69a832dc58
commit a02205e519
113 changed files with 1 additions and 14754 deletions
+1 -221
View File
@@ -15,11 +15,8 @@
"href": "https://app.mem0.ai/"
},
"navigation": {
"versions": [
"anchors": [
{
"version": "v1.0.1",
"anchors": [
{
"anchor": "Documentation",
"icon": "book-open",
"tabs": [
@@ -538,229 +535,12 @@
"pages": [
"changelog"
]
},
{
"group": "Legacy Docs",
"icon": "archive",
"pages": [
"v0x/introduction"
]
}
]
}
]
}
]
},
{
"version": "v0.x Legacy",
"anchors": [
{
"anchor": "Documentation",
"icon": "book-open",
"tabs": [
{
"tab": "Documentation",
"groups": [
{
"group": "Getting Started",
"icon": "rocket",
"pages": [
"v0x/introduction",
"v0x/quickstart",
"v0x/faqs"
]
},
{
"group": "Core Concepts",
"icon": "brain",
"pages": [
"v0x/core-concepts/memory-types",
{
"group": "Memory Operations",
"icon": "gear",
"pages": [
"v0x/core-concepts/memory-operations/add",
"v0x/core-concepts/memory-operations/search",
"v0x/core-concepts/memory-operations/update",
"v0x/core-concepts/memory-operations/delete"
]
}
]
},
{
"group": "Open Source",
"icon": "code-branch",
"pages": [
"v0x/open-source/overview",
"v0x/open-source/python-quickstart",
"v0x/open-source/node-quickstart",
{
"group": "LLMs",
"icon": "brain",
"pages": [
"v0x/components/llms/overview",
"v0x/components/llms/config",
{
"group": "Supported LLMs",
"icon": "list",
"pages": [
"v0x/components/llms/models/openai",
"v0x/components/llms/models/anthropic",
"v0x/components/llms/models/azure_openai",
"v0x/components/llms/models/ollama",
"v0x/components/llms/models/together",
"v0x/components/llms/models/groq",
"v0x/components/llms/models/litellm",
"v0x/components/llms/models/mistral_AI",
"v0x/components/llms/models/google_AI",
"v0x/components/llms/models/aws_bedrock",
"v0x/components/llms/models/deepseek",
"v0x/components/llms/models/xAI",
"v0x/components/llms/models/sarvam",
"v0x/components/llms/models/lmstudio",
"v0x/components/llms/models/langchain",
"v0x/components/llms/models/vllm"
]
}
]
},
{
"group": "Vector Databases",
"icon": "database",
"pages": [
"v0x/components/vectordbs/overview",
"v0x/components/vectordbs/config",
{
"group": "Supported Vector Databases",
"icon": "server",
"pages": [
"v0x/components/vectordbs/dbs/qdrant",
"v0x/components/vectordbs/dbs/chroma",
"v0x/components/vectordbs/dbs/pgvector",
"v0x/components/vectordbs/dbs/milvus",
"v0x/components/vectordbs/dbs/pinecone",
"v0x/components/vectordbs/dbs/mongodb",
"v0x/components/vectordbs/dbs/azure",
"v0x/components/vectordbs/dbs/azure_mysql",
"v0x/components/vectordbs/dbs/redis",
"v0x/components/vectordbs/dbs/valkey",
"v0x/components/vectordbs/dbs/elasticsearch",
"v0x/components/vectordbs/dbs/opensearch",
"v0x/components/vectordbs/dbs/supabase",
"v0x/components/vectordbs/dbs/upstash-vector",
"v0x/components/vectordbs/dbs/vectorize",
"v0x/components/vectordbs/dbs/vertex_ai",
"v0x/components/vectordbs/dbs/weaviate",
"v0x/components/vectordbs/dbs/faiss",
"v0x/components/vectordbs/dbs/langchain",
"v0x/components/vectordbs/dbs/baidu",
"v0x/components/vectordbs/dbs/s3_vectors",
"v0x/components/vectordbs/dbs/databricks",
"v0x/components/vectordbs/dbs/neptune_analytics"
]
}
]
},
{
"group": "Embedding Models",
"icon": "layer-group",
"pages": [
"v0x/components/embedders/overview",
"v0x/components/embedders/config",
{
"group": "Supported Embedding Models",
"icon": "list",
"pages": [
"v0x/components/embedders/models/openai",
"v0x/components/embedders/models/azure_openai",
"v0x/components/embedders/models/ollama",
"v0x/components/embedders/models/huggingface",
"v0x/components/embedders/models/vertexai",
"v0x/components/embedders/models/google_AI",
"v0x/components/embedders/models/lmstudio",
"v0x/components/embedders/models/together",
"v0x/components/embedders/models/langchain",
"v0x/components/embedders/models/aws_bedrock"
]
}
]
}
]
}
]
},
{
"tab": "Examples",
"groups": [
{
"group": "\ud83d\udca1 Examples",
"icon": "lightbulb",
"pages": [
"v0x/examples/mem0-demo",
"v0x/examples/ai_companion_js",
"v0x/examples/mem0-with-ollama",
"v0x/examples/personal-ai-tutor",
"v0x/examples/customer-support-agent",
"v0x/examples/personal-travel-assistant",
"v0x/examples/chrome-extension",
"v0x/examples/youtube-assistant",
"v0x/examples/memory-guided-content-writing",
"v0x/examples/multimodal-demo",
"v0x/examples/email_processing",
"v0x/examples/personalized-deep-research",
"v0x/examples/collaborative-task-agent",
"v0x/examples/llama-index-mem0",
"v0x/examples/llamaindex-multiagent-learning-system",
"v0x/examples/personalized-search-tavily-mem0",
"v0x/examples/mem0-agentic-tool",
"v0x/examples/openai-inbuilt-tools",
"v0x/examples/mem0-openai-voice-demo",
"v0x/examples/mem0-google-adk-healthcare-assistant",
"v0x/examples/mem0-mastra",
"v0x/examples/eliza_os",
"v0x/examples/aws_example",
"v0x/examples/aws_neptune_analytics_hybrid_store"
]
}
]
},
{
"tab": "Integrations",
"groups": [
{
"group": "Integrations",
"icon": "plug",
"pages": [
"v0x/integrations/langchain",
"v0x/integrations/langgraph",
"v0x/integrations/llama-index",
"v0x/integrations/agno",
"v0x/integrations/autogen",
"v0x/integrations/crewai",
"v0x/integrations/openai-agents-sdk",
"v0x/integrations/google-ai-adk",
"v0x/integrations/mastra",
"v0x/integrations/vercel-ai-sdk",
"v0x/integrations/livekit",
"v0x/integrations/pipecat",
"v0x/integrations/elevenlabs",
"v0x/integrations/aws-bedrock",
"v0x/integrations/flowise",
"v0x/integrations/langchain-tools",
"v0x/integrations/agentops",
"v0x/integrations/keywords",
"v0x/integrations/dify",
"v0x/integrations/raycast"
]
}
]
}
]
}
]
}
]
},
"background": {
"color": {
-101
View File
@@ -1,101 +0,0 @@
---
title: Configurations
icon: "gear"
iconType: "solid"
---
Config in mem0 is a dictionary that specifies the settings for your embedding models. It allows you to customize the behavior and connection details of your chosen embedder.
## How to define configurations?
The config is defined as an object (or dictionary) with two main keys:
- `embedder`: Specifies the embedder provider and its configuration
- `provider`: The name of the embedder (e.g., "openai", "ollama")
- `config`: A nested object or dictionary containing provider-specific settings
## How to use configurations?
Here's a general example of how to use the config with mem0:
<CodeGroup>
```python Python
import os
from mem0 import Memory
os.environ["OPENAI_API_KEY"] = "sk-xx"
config = {
"embedder": {
"provider": "your_chosen_provider",
"config": {
# Provider-specific settings go here
}
}
}
m = Memory.from_config(config)
m.add("Your text here", user_id="user", metadata={"category": "example"})
```
```typescript TypeScript
import { Memory } from 'mem0ai/oss';
const config = {
embedder: {
provider: 'openai',
config: {
apiKey: process.env.OPENAI_API_KEY || '',
model: 'text-embedding-3-small',
// Provider-specific settings go here
},
},
};
const memory = new Memory(config);
await memory.add("Your text here", { userId: "user", metadata: { category: "example" } });
```
</CodeGroup>
## Why is Config Needed?
Config is essential for:
1. Specifying which embedding model to use.
2. Providing necessary connection details (e.g., model, api_key, embedding_dims).
3. Ensuring proper initialization and connection to your chosen embedder.
## Master List of All Params in Config
Here's a comprehensive list of all parameters that can be used across different embedders:
<Tabs>
<Tab title="Python">
| Parameter | Description | Provider |
|-----------|-------------|----------|
| `model` | Embedding model to use | All |
| `api_key` | API key of the provider | All |
| `embedding_dims` | Dimensions of the embedding model | All |
| `http_client_proxies` | Allow proxy server settings | All |
| `ollama_base_url` | Base URL for the Ollama embedding model | Ollama |
| `model_kwargs` | Key-Value arguments for the Huggingface embedding model | Huggingface |
| `azure_kwargs` | Key-Value arguments for the AzureOpenAI embedding model | Azure OpenAI |
| `openai_base_url` | Base URL for OpenAI API | OpenAI |
| `vertex_credentials_json` | Path to the Google Cloud credentials JSON file for VertexAI | VertexAI |
| `memory_add_embedding_type` | The type of embedding to use for the add memory action | VertexAI |
| `memory_update_embedding_type` | The type of embedding to use for the update memory action | VertexAI |
| `memory_search_embedding_type` | The type of embedding to use for the search memory action | VertexAI |
| `lmstudio_base_url` | Base URL for LM Studio API | LM Studio |
</Tab>
<Tab title="TypeScript">
| Parameter | Description | Provider |
|-----------|-------------|----------|
| `model` | Embedding model to use | All |
| `apiKey` | API key of the provider | All |
| `embeddingDims` | Dimensions of the embedding model | All |
</Tab>
</Tabs>
## Supported Embedding Models
For detailed information on configuring specific embedders, please visit the [Embedding Models](./models) section. There you'll find information for each supported embedder with provider-specific usage examples and configuration details.
@@ -1,62 +0,0 @@
---
title: AWS Bedrock
---
To use AWS Bedrock embedding models, you need to have the appropriate AWS credentials and permissions. The embeddings implementation relies on the `boto3` library.
### Setup
- Ensure you have model access from the [AWS Bedrock Console](https://us-east-1.console.aws.amazon.com/bedrock/home?region=us-east-1#/modelaccess)
- Authenticate the boto3 client using a method described in the [AWS documentation](https://boto3.amazonaws.com/v1/documentation/api/latest/guide/credentials.html)
- Set up environment variables for authentication:
```bash
export AWS_REGION=us-east-1
export AWS_ACCESS_KEY_ID=your-access-key
export AWS_SECRET_ACCESS_KEY=your-secret-key
```
### Usage
<CodeGroup>
```python Python
import os
from mem0 import Memory
# For LLM if needed
os.environ["OPENAI_API_KEY"] = "your-openai-api-key"
# AWS credentials
os.environ["AWS_REGION"] = "us-west-2"
os.environ["AWS_ACCESS_KEY_ID"] = "your-access-key"
os.environ["AWS_SECRET_ACCESS_KEY"] = "your-secret-key"
config = {
"embedder": {
"provider": "aws_bedrock",
"config": {
"model": "amazon.titan-embed-text-v2:0"
}
}
}
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")
```
</CodeGroup>
### Config
Here are the parameters available for configuring AWS Bedrock embedder:
<Tabs>
<Tab title="Python">
| Parameter | Description | Default Value |
| --- | --- | --- |
| `model` | The name of the embedding model to use | `amazon.titan-embed-text-v1` |
</Tab>
</Tabs>
@@ -1,136 +0,0 @@
---
title: Azure OpenAI
---
To use Azure OpenAI embedding models, set the `EMBEDDING_AZURE_OPENAI_API_KEY`, `EMBEDDING_AZURE_DEPLOYMENT`, `EMBEDDING_AZURE_ENDPOINT` and `EMBEDDING_AZURE_API_VERSION` environment variables. You can obtain the Azure OpenAI API key from the Azure.
### Usage
<CodeGroup>
```python Python
import os
from mem0 import Memory
os.environ["EMBEDDING_AZURE_OPENAI_API_KEY"] = "your-api-key"
os.environ["EMBEDDING_AZURE_DEPLOYMENT"] = "your-deployment-name"
os.environ["EMBEDDING_AZURE_ENDPOINT"] = "your-api-base-url"
os.environ["EMBEDDING_AZURE_API_VERSION"] = "version-to-use"
os.environ["OPENAI_API_KEY"] = "your_api_key" # For LLM
config = {
"embedder": {
"provider": "azure_openai",
"config": {
"model": "text-embedding-3-large",
"azure_kwargs": {
"api_version": "",
"azure_deployment": "",
"azure_endpoint": "",
"api_key": "",
"default_headers": {
"CustomHeader": "your-custom-header",
}
}
}
}
}
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="john")
```
```typescript TypeScript
import { Memory } from 'mem0ai/oss';
const config = {
embedder: {
provider: "azure_openai",
config: {
model: "text-embedding-3-large",
modelProperties: {
endpoint: "your-api-base-url",
deployment: "your-deployment-name",
apiVersion: "version-to-use",
}
}
}
}
const memory = new Memory(config);
const 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."}
]
await memory.add(messages, { userId: "john" });
```
</CodeGroup>
As an alternative to using an API key, the Azure Identity credential chain can be used to authenticate with [Azure OpenAI role-based security](https://learn.microsoft.com/en-us/azure/ai-foundry/openai/how-to/role-based-access-control).
<Note> If an API key is provided, it will be used for authentication over an Azure Identity </Note>
Below is a sample configuration for using Mem0 with Azure OpenAI and Azure Identity:
```python
import os
from mem0 import Memory
# You can set the values directly in the config dictionary or use environment variables
os.environ["LLM_AZURE_DEPLOYMENT"] = "your-deployment-name"
os.environ["LLM_AZURE_ENDPOINT"] = "your-api-base-url"
os.environ["LLM_AZURE_API_VERSION"] = "version-to-use"
config = {
"llm": {
"provider": "azure_openai_structured",
"config": {
"model": "your-deployment-name",
"temperature": 0.1,
"max_tokens": 2000,
"azure_kwargs": {
"azure_deployment": "<your-deployment-name>",
"api_version": "<version-to-use>",
"azure_endpoint": "<your-api-base-url>",
"default_headers": {
"CustomHeader": "your-custom-header",
}
}
}
}
}
```
Refer to [Azure Identity troubleshooting tips](https://github.com/Azure/azure-sdk-for-python/blob/main/sdk/identity/azure-identity/TROUBLESHOOTING.md#troubleshoot-environmentcredential-authentication-issues) for setting up an Azure Identity credential.
### Config
Here are the parameters available for configuring Azure OpenAI embedder:
<Tabs>
<Tab title="Python">
| Parameter | Description | Default Value |
| --- | --- | --- |
| `model` | The name of the embedding model to use | `text-embedding-3-small` |
| `embedding_dims` | Dimensions of the embedding model | `1536` |
| `azure_kwargs` | The Azure OpenAI configs | `config_keys` |
</Tab>
<Tab title="TypeScript">
| Parameter | Description | Default Value |
| ----------------- | --------------------------------------------- | -------------------------- |
| `model` | The name of the embedding model to use | `text-embedding-3-small` |
| `embeddingDims` | Dimensions of the embedding model | `1536` |
| `apiKey` | Azure OpenAI API key | `None` |
| `modelProperties` | Object containing endpoint and other settings | `{ endpoint: "",...rest }`|
</Tab>
</Tabs>
@@ -1,80 +0,0 @@
---
title: Google AI
---
To use Google AI embedding models, set the `GOOGLE_API_KEY` environment variables. You can obtain the Gemini API key from [here](https://aistudio.google.com/app/apikey).
### Usage
<CodeGroup>
```python Python
import os
from mem0 import Memory
os.environ["GOOGLE_API_KEY"] = "key"
os.environ["OPENAI_API_KEY"] = "your_api_key" # For LLM
config = {
"embedder": {
"provider": "gemini",
"config": {
"model": "models/text-embedding-004",
}
}
}
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="john")
```
```typescript TypeScript
import { Memory } from 'mem0ai/oss';
const config = {
embedder: {
provider: "google",
config: {
apiKey: process.env["GOOGLE_API_KEY"],
model: "gemini-embedding-001",
embeddingDims: 1536,
},
},
};
const memory = new Memory(config);
const 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."}
]
await memory.add(messages, { userId: "john" });
```
</CodeGroup>
### Config
Here are the parameters available for configuring Gemini embedder:
<Tabs>
<Tab title="Python">
| Parameter | Description | Default Value |
| ---------------- | ------------------------------------ | ----------------------- |
| `model` | The name of the embedding model to use| `models/text-embedding-004` |
| `embedding_dims` | Dimensions of the embedding model | `1536` |
| `api_key` | The Google API key | `None` |
</Tab>
<Tab title="TypeScript">
| Parameter | Description | Default Value |
| ----------------- | --------------------------------------------- | -------------------------- |
| `model` | The name of the embedding model to use | `gemini-embedding-001` |
| `embeddingDims` | Dimensions of the embedding model | `1536` |
| `apiKey` | Google API key | `None` |
</Tab>
</Tabs>
@@ -1,75 +0,0 @@
---
title: Hugging Face
---
You can use embedding models from Huggingface to run Mem0 locally.
### Usage
```python
import os
from mem0 import Memory
os.environ["OPENAI_API_KEY"] = "your_api_key" # For LLM
config = {
"embedder": {
"provider": "huggingface",
"config": {
"model": "multi-qa-MiniLM-L6-cos-v1"
}
}
}
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="john")
```
### Using Text Embeddings Inference (TEI)
You can also use Hugging Face's Text Embeddings Inference service for faster and more efficient embeddings:
```python
import os
from mem0 import Memory
os.environ["OPENAI_API_KEY"] = "your_api_key" # For LLM
# Using HuggingFace Text Embeddings Inference API
config = {
"embedder": {
"provider": "huggingface",
"config": {
"huggingface_base_url": "http://localhost:3000/v1"
}
}
}
m = Memory.from_config(config)
m.add("This text will be embedded using the TEI service.", user_id="john")
```
To run the TEI service, you can use Docker:
```bash
docker run -d -p 3000:80 -v huggingfacetei:/data --platform linux/amd64 \
ghcr.io/huggingface/text-embeddings-inference:cpu-1.6 \
--model-id BAAI/bge-small-en-v1.5
```
### Config
Here are the parameters available for configuring Huggingface embedder:
| Parameter | Description | Default Value |
| --- | --- | --- |
| `model` | The name of the model to use | `multi-qa-MiniLM-L6-cos-v1` |
| `embedding_dims` | Dimensions of the embedding model | `selected_model_dimensions` |
| `model_kwargs` | Additional arguments for the model | `None` |
| `huggingface_base_url` | URL to connect to Text Embeddings Inference (TEI) API | `None` |
@@ -1,196 +0,0 @@
---
title: LangChain
---
Mem0 supports LangChain as a provider to access a wide range of embedding models. LangChain is a framework for developing applications powered by language models, making it easy to integrate various embedding providers through a consistent interface.
For a complete list of available embedding models supported by LangChain, refer to the [LangChain Text Embedding documentation](https://python.langchain.com/docs/integrations/text_embedding/).
## Usage
<CodeGroup>
```python Python
import os
from mem0 import Memory
from langchain_openai import OpenAIEmbeddings
# Set necessary environment variables for your chosen LangChain provider
os.environ["OPENAI_API_KEY"] = "your-api-key"
# Initialize a LangChain embeddings model directly
openai_embeddings = OpenAIEmbeddings(
model="text-embedding-3-small",
dimensions=1536
)
# Pass the initialized model to the config
config = {
"embedder": {
"provider": "langchain",
"config": {
"model": openai_embeddings
}
}
}
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"})
```
```typescript TypeScript
import { Memory } from 'mem0ai/oss';
import { OpenAIEmbeddings } from "@langchain/openai";
// Initialize a LangChain embeddings model directly
const openaiEmbeddings = new OpenAIEmbeddings({
modelName: "text-embedding-3-small",
dimensions: 1536,
apiKey: process.env.OPENAI_API_KEY,
});
const config = {
embedder: {
provider: 'langchain',
config: {
model: openaiEmbeddings,
},
},
};
const memory = new Memory(config);
const 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."}
]
await memory.add(messages, { userId: "alice", metadata: { category: "movies" } });
```
</CodeGroup>
## Supported LangChain Embedding Providers
LangChain supports a wide range of embedding providers, including:
- OpenAI (`OpenAIEmbeddings`)
- Cohere (`CohereEmbeddings`)
- Google (`VertexAIEmbeddings`)
- Hugging Face (`HuggingFaceEmbeddings`)
- Sentence Transformers (`HuggingFaceEmbeddings`)
- Azure OpenAI (`AzureOpenAIEmbeddings`)
- Ollama (`OllamaEmbeddings`)
- Together (`TogetherEmbeddings`)
- And many more
You can use any of these model instances directly in your configuration. For a complete and up-to-date list of available embedding providers, refer to the [LangChain Text Embedding documentation](https://python.langchain.com/docs/integrations/text_embedding/).
## Provider-Specific Configuration
When using LangChain as an embedder provider, you'll need to:
1. Set the appropriate environment variables for your chosen embedding provider
2. Import and initialize the specific model class you want to use
3. Pass the initialized model instance to the config
### Examples with Different Providers
<CodeGroup>
#### HuggingFace Embeddings
```python Python
from langchain_huggingface import HuggingFaceEmbeddings
# Initialize a HuggingFace embeddings model
hf_embeddings = HuggingFaceEmbeddings(
model_name="BAAI/bge-small-en-v1.5",
encode_kwargs={"normalize_embeddings": True}
)
config = {
"embedder": {
"provider": "langchain",
"config": {
"model": hf_embeddings
}
}
}
```
```typescript TypeScript
import { Memory } from 'mem0ai/oss';
import { HuggingFaceEmbeddings } from "@langchain/community/embeddings/hf";
// Initialize a HuggingFace embeddings model
const hfEmbeddings = new HuggingFaceEmbeddings({
modelName: "BAAI/bge-small-en-v1.5",
encode: {
normalize_embeddings: true,
},
});
const config = {
embedder: {
provider: 'langchain',
config: {
model: hfEmbeddings,
},
},
};
```
</CodeGroup>
<CodeGroup>
#### Ollama Embeddings
```python Python
from langchain_ollama import OllamaEmbeddings
# Initialize an Ollama embeddings model
ollama_embeddings = OllamaEmbeddings(
model="nomic-embed-text"
)
config = {
"embedder": {
"provider": "langchain",
"config": {
"model": ollama_embeddings
}
}
}
```
```typescript TypeScript
import { Memory } from 'mem0ai/oss';
import { OllamaEmbeddings } from "@langchain/community/embeddings/ollama";
// Initialize an Ollama embeddings model
const ollamaEmbeddings = new OllamaEmbeddings({
model: "nomic-embed-text",
baseUrl: "http://localhost:11434", // Ollama server URL
});
const config = {
embedder: {
provider: 'langchain',
config: {
model: ollamaEmbeddings,
},
},
};
```
</CodeGroup>
<Note>
Make sure to install the necessary LangChain packages and any provider-specific dependencies.
</Note>
## Config
All available parameters for the `langchain` embedder config are present in [Master List of All Params in Config](../config).
@@ -1,38 +0,0 @@
You can use embedding models from LM Studio to run Mem0 locally.
### Usage
```python
import os
from mem0 import Memory
os.environ["OPENAI_API_KEY"] = "your_api_key" # For LLM
config = {
"embedder": {
"provider": "lmstudio",
"config": {
"model": "nomic-embed-text-v1.5-GGUF/nomic-embed-text-v1.5.f16.gguf"
}
}
}
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="john")
```
### Config
Here are the parameters available for configuring Ollama embedder:
| Parameter | Description | Default Value |
| --- | --- | --- |
| `model` | The name of the OpenAI model to use | `nomic-embed-text-v1.5-GGUF/nomic-embed-text-v1.5.f16.gguf` |
| `embedding_dims` | Dimensions of the embedding model | `1536` |
| `lmstudio_base_url` | Base URL for LM Studio connection | `http://localhost:1234/v1` |
@@ -1,74 +0,0 @@
You can use embedding models from Ollama to run Mem0 locally.
### Usage
<CodeGroup>
```python Python
import os
from mem0 import Memory
os.environ["OPENAI_API_KEY"] = "your_api_key" # For LLM
config = {
"embedder": {
"provider": "ollama",
"config": {
"model": "mxbai-embed-large"
}
}
}
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="john")
```
```typescript TypeScript
import { Memory } from 'mem0ai/oss';
const config = {
embedder: {
provider: 'ollama',
config: {
model: 'nomic-embed-text:latest', // or any other Ollama embedding model
url: 'http://localhost:11434', // Ollama server URL
},
},
};
const memory = new Memory(config);
const 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."}
]
await memory.add(messages, { userId: "john" });
```
</CodeGroup>
### Config
Here are the parameters available for configuring Ollama embedder:
<Tabs>
<Tab title="Python">
| Parameter | Description | Default Value |
| --- | --- | --- |
| `model` | The name of the Ollama model to use | `nomic-embed-text` |
| `embedding_dims` | Dimensions of the embedding model | `512` |
| `ollama_base_url` | Base URL for ollama connection | `None` |
</Tab>
<Tab title="TypeScript">
| Parameter | Description | Default Value |
| --- | --- | --- |
| `model` | The name of the Ollama model to use | `nomic-embed-text:latest` |
| `url` | Base URL for Ollama server | `http://localhost:11434` |
| `embeddingDims` | Dimensions of the embedding model | 768 |
</Tab>
</Tabs>
@@ -1,72 +0,0 @@
---
title: OpenAI
---
To use OpenAI embedding models, set the `OPENAI_API_KEY` environment variable. You can obtain the OpenAI API key from the [OpenAI Platform](https://platform.openai.com/account/api-keys).
### Usage
<CodeGroup>
```python Python
import os
from mem0 import Memory
os.environ["OPENAI_API_KEY"] = "your_api_key"
config = {
"embedder": {
"provider": "openai",
"config": {
"model": "text-embedding-3-large"
}
}
}
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="john")
```
```typescript TypeScript
import { Memory } from 'mem0ai/oss';
const config = {
embedder: {
provider: 'openai',
config: {
apiKey: 'your-openai-api-key',
model: 'text-embedding-3-large',
},
},
};
const memory = new Memory(config);
await memory.add("I'm visiting Paris", { userId: "john" });
```
</CodeGroup>
### Config
Here are the parameters available for configuring OpenAI embedder:
<Tabs>
<Tab title="Python">
| Parameter | Description | Default Value |
| --- | --- | --- |
| `model` | The name of the embedding model to use | `text-embedding-3-small` |
| `embedding_dims` | Dimensions of the embedding model | `1536` |
| `api_key` | The OpenAI API key | `None` |
</Tab>
<Tab title="TypeScript">
| Parameter | Description | Default Value |
| --- | --- | --- |
| `model` | The name of the embedding model to use | `text-embedding-3-small` |
| `embeddingDims` | Dimensions of the embedding model | `1536` |
| `apiKey` | The OpenAI API key | `None` |
</Tab>
</Tabs>
@@ -1,45 +0,0 @@
---
title: Together
---
To use Together embedding models, set the `TOGETHER_API_KEY` environment variable. You can obtain the Together API key from the [Together Platform](https://api.together.xyz/settings/api-keys).
### Usage
<Note> The `embedding_model_dims` parameter for `vector_store` should be set to `768` for Together embedder. </Note>
```python
import os
from mem0 import Memory
os.environ["TOGETHER_API_KEY"] = "your_api_key"
os.environ["OPENAI_API_KEY"] = "your_api_key" # For LLM
config = {
"embedder": {
"provider": "together",
"config": {
"model": "togethercomputer/m2-bert-80M-8k-retrieval"
}
}
}
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="john")
```
### Config
Here are the parameters available for configuring Together embedder:
| Parameter | Description | Default Value |
| --- | --- | --- |
| `model` | The name of the embedding model to use | `togethercomputer/m2-bert-80M-8k-retrieval` |
| `embedding_dims` | Dimensions of the embedding model | `768` |
| `api_key` | The Together API key | `None` |
@@ -1,55 +0,0 @@
### Vertex AI
To use Google Cloud's Vertex AI for text embedding models, set the `GOOGLE_APPLICATION_CREDENTIALS` environment variable to point to the path of your service account's credentials JSON file. These credentials can be created in the [Google Cloud Console](https://console.cloud.google.com/).
### Usage
```python
import os
from mem0 import Memory
# Set the path to your Google Cloud credentials JSON file
os.environ["GOOGLE_APPLICATION_CREDENTIALS"] = "/path/to/your/credentials.json"
os.environ["OPENAI_API_KEY"] = "your_api_key" # For LLM
config = {
"embedder": {
"provider": "vertexai",
"config": {
"model": "text-embedding-004",
"memory_add_embedding_type": "RETRIEVAL_DOCUMENT",
"memory_update_embedding_type": "RETRIEVAL_DOCUMENT",
"memory_search_embedding_type": "RETRIEVAL_QUERY"
}
}
}
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="john")
```
The embedding types can be one of the following:
- SEMANTIC_SIMILARITY
- CLASSIFICATION
- CLUSTERING
- RETRIEVAL_DOCUMENT, RETRIEVAL_QUERY, QUESTION_ANSWERING, FACT_VERIFICATION
- CODE_RETRIEVAL_QUERY
Check out the [Vertex AI documentation](https://cloud.google.com/vertex-ai/generative-ai/docs/embeddings/task-types#supported_task_types) for more information.
### Config
Here are the parameters available for configuring the Vertex AI embedder:
| Parameter | Description | Default Value |
| ------------------------- | ------------------------------------------------ | -------------------- |
| `model` | The name of the Vertex AI embedding model to use | `text-embedding-004` |
| `vertex_credentials_json` | Path to the Google Cloud credentials JSON file | `None` |
| `embedding_dims` | Dimensions of the embedding model | `256` |
| `memory_add_embedding_type` | The type of embedding to use for the add memory action | `RETRIEVAL_DOCUMENT` |
| `memory_update_embedding_type` | The type of embedding to use for the update memory action | `RETRIEVAL_DOCUMENT` |
| `memory_search_embedding_type` | The type of embedding to use for the search memory action | `RETRIEVAL_QUERY` |
@@ -1,34 +0,0 @@
---
title: Overview
icon: "info"
iconType: "solid"
---
Mem0 offers support for various embedding models, allowing users to choose the one that best suits their needs.
## Supported Embedders
See the list of supported embedders below.
<Note>
The following embedders are supported in the Python implementation. The TypeScript implementation currently only supports OpenAI.
</Note>
<CardGroup cols={4}>
<Card title="OpenAI" href="/components/embedders/models/openai"></Card>
<Card title="Azure OpenAI" href="/components/embedders/models/azure_openai"></Card>
<Card title="Ollama" href="/components/embedders/models/ollama"></Card>
<Card title="Hugging Face" href="/components/embedders/models/huggingface"></Card>
<Card title="Google AI" href="/components/embedders/models/google_AI"></Card>
<Card title="Vertex AI" href="/components/embedders/models/vertexai"></Card>
<Card title="Together" href="/components/embedders/models/together"></Card>
<Card title="LM Studio" href="/components/embedders/models/lmstudio"></Card>
<Card title="Langchain" href="/components/embedders/models/langchain"></Card>
<Card title="AWS Bedrock" href="/components/embedders/models/aws_bedrock"></Card>
</CardGroup>
## Usage
To utilize a embedder, you must provide a configuration to customize its usage. If no configuration is supplied, a default configuration will be applied, and `OpenAI` will be used as the embedder.
For a comprehensive list of available parameters for embedder configuration, please refer to [Config](./config).
-137
View File
@@ -1,137 +0,0 @@
---
title: Configurations
icon: "gear"
iconType: "solid"
---
## How to define configurations?
<Tabs>
<Tab title="Python">
The `config` is defined as a Python dictionary with two main keys:
- `llm`: Specifies the llm provider and its configuration
- `provider`: The name of the llm (e.g., "openai", "groq")
- `config`: A nested dictionary containing provider-specific settings
</Tab>
<Tab title="TypeScript">
The `config` is defined as a TypeScript object with these keys:
- `llm`: Specifies the LLM provider and its configuration (required)
- `provider`: The name of the LLM (e.g., "openai", "groq")
- `config`: A nested object containing provider-specific settings
- `embedder`: Specifies the embedder provider and its configuration (optional)
- `vectorStore`: Specifies the vector store provider and its configuration (optional)
- `historyDbPath`: Path to the history database file (optional)
</Tab>
</Tabs>
### Config Values Precedence
Config values are applied in the following order of precedence (from highest to lowest):
1. Values explicitly set in the `config` object/dictionary
2. Environment variables (e.g., `OPENAI_API_KEY`, `OPENAI_BASE_URL`)
3. Default values defined in the LLM implementation
This means that values specified in the `config` will override corresponding environment variables, which in turn override default values.
## How to Use Config
Here's a general example of how to use the config with Mem0:
<CodeGroup>
```python Python
import os
from mem0 import Memory
os.environ["OPENAI_API_KEY"] = "sk-xx" # for embedder
config = {
"llm": {
"provider": "your_chosen_provider",
"config": {
# Provider-specific settings go here
}
}
}
m = Memory.from_config(config)
m.add("Your text here", user_id="user", metadata={"category": "example"})
```
```typescript TypeScript
import { Memory } from 'mem0ai/oss';
// Minimal configuration with just the LLM settings
const config = {
llm: {
provider: 'your_chosen_provider',
config: {
// Provider-specific settings go here
}
}
};
const memory = new Memory(config);
await memory.add("Your text here", { userId: "user123", metadata: { category: "example" } });
```
</CodeGroup>
## Why is Config Needed?
Config is essential for:
1. Specifying which LLM to use.
2. Providing necessary connection details (e.g., model, api_key, temperature).
3. Ensuring proper initialization and connection to your chosen LLM.
## Master List of All Params in Config
Here's a comprehensive list of all parameters that can be used across different LLMs:
<Tabs>
<Tab title="Python">
| Parameter | Description | Provider |
|----------------------|-----------------------------------------------|-------------------|
| `model` | Embedding model to use | All |
| `temperature` | Temperature of the model | All |
| `api_key` | API key to use | All |
| `max_tokens` | Tokens to generate | All |
| `top_p` | Probability threshold for nucleus sampling | All |
| `top_k` | Number of highest probability tokens to keep | All |
| `http_client_proxies`| Allow proxy server settings | AzureOpenAI |
| `models` | List of models | Openrouter |
| `route` | Routing strategy | Openrouter |
| `openrouter_base_url`| Base URL for Openrouter API | Openrouter |
| `site_url` | Site URL | Openrouter |
| `app_name` | Application name | Openrouter |
| `ollama_base_url` | Base URL for Ollama API | Ollama |
| `openai_base_url` | Base URL for OpenAI API | OpenAI |
| `azure_kwargs` | Azure LLM args for initialization | AzureOpenAI |
| `deepseek_base_url` | Base URL for DeepSeek API | DeepSeek |
| `xai_base_url` | Base URL for XAI API | XAI |
| `sarvam_base_url` | Base URL for Sarvam API | Sarvam |
| `reasoning_effort` | Reasoning level (low, medium, high) | Sarvam |
| `frequency_penalty` | Penalize frequent tokens (-2.0 to 2.0) | Sarvam |
| `presence_penalty` | Penalize existing tokens (-2.0 to 2.0) | Sarvam |
| `seed` | Seed for deterministic sampling | Sarvam |
| `stop` | Stop sequences (max 4) | Sarvam |
| `lmstudio_base_url` | Base URL for LM Studio API | LM Studio |
| `response_callback` | LLM response callback function | OpenAI |
</Tab>
<Tab title="TypeScript">
| Parameter | Description | Provider |
|----------------------|-----------------------------------------------|-------------------|
| `model` | Embedding model to use | All |
| `temperature` | Temperature of the model | All |
| `apiKey` | API key to use | All |
| `maxTokens` | Tokens to generate | All |
| `topP` | Probability threshold for nucleus sampling | All |
| `topK` | Number of highest probability tokens to keep | All |
| `openaiBaseUrl` | Base URL for OpenAI API | OpenAI |
</Tab>
</Tabs>
## Supported LLMs
For detailed information on configuring specific LLMs, please visit the [LLMs](./models) section. There you'll find information for each supported LLM with provider-specific usage examples and configuration details.
@@ -1,67 +0,0 @@
---
title: Anthropic
---
To use Anthropic's models, please set the `ANTHROPIC_API_KEY` which you find on their [Account Settings Page](https://console.anthropic.com/account/keys).
## Usage
<CodeGroup>
```python Python
import os
from mem0 import Memory
os.environ["OPENAI_API_KEY"] = "your-api-key" # used for embedding model
os.environ["ANTHROPIC_API_KEY"] = "your-api-key"
config = {
"llm": {
"provider": "anthropic",
"config": {
"model": "claude-sonnet-4-20250514",
"temperature": 0.1,
"max_tokens": 2000,
}
}
}
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"})
```
```typescript TypeScript
import { Memory } from 'mem0ai/oss';
const config = {
llm: {
provider: 'anthropic',
config: {
apiKey: process.env.ANTHROPIC_API_KEY || '',
model: 'claude-sonnet-4-20250514',
temperature: 0.1,
maxTokens: 2000,
},
},
};
const memory = new Memory(config);
const 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."}
]
await memory.add(messages, { userId: "alice", metadata: { category: "movies" } });
```
</CodeGroup>
## Config
All available parameters for the `anthropic` config are present in [Master List of All Params in Config](../config).
@@ -1,43 +0,0 @@
---
title: AWS Bedrock
---
### Setup
- Before using the AWS Bedrock LLM, make sure you have the appropriate model access from [Bedrock Console](https://us-east-1.console.aws.amazon.com/bedrock/home?region=us-east-1#/modelaccess).
- You will also need to authenticate the `boto3` client by using a method in the [AWS documentation](https://boto3.amazonaws.com/v1/documentation/api/latest/guide/credentials.html#configuring-credentials)
- You will have to export `AWS_REGION`, `AWS_ACCESS_KEY`, and `AWS_SECRET_ACCESS_KEY` to set environment variables.
### Usage
```python
import os
from mem0 import Memory
os.environ['AWS_REGION'] = 'us-west-2'
os.environ["AWS_ACCESS_KEY_ID"] = "xx"
os.environ["AWS_SECRET_ACCESS_KEY"] = "xx"
config = {
"llm": {
"provider": "aws_bedrock",
"config": {
"model": "anthropic.claude-3-5-haiku-20241022-v1:0",
"temperature": 0.2,
"max_tokens": 2000,
}
}
}
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"})
```
### Config
All available parameters for the `aws_bedrock` config are present in [Master List of All Params in Config](../config).
@@ -1,161 +0,0 @@
---
title: Azure OpenAI
---
<Note> Mem0 Now Supports Azure OpenAI Models in TypeScript SDK </Note>
To use Azure OpenAI models, you have to set the `LLM_AZURE_OPENAI_API_KEY`, `LLM_AZURE_ENDPOINT`, `LLM_AZURE_DEPLOYMENT` and `LLM_AZURE_API_VERSION` environment variables. You can obtain the Azure API key from the [Azure](https://azure.microsoft.com/).
Optionally, you can use Azure Identity to authenticate with Azure OpenAI, which allows you to use managed identities or service principals for production and Azure CLI login for development instead of an API key. If an Azure Identity is to be used, ***do not*** set the `LLM_AZURE_OPENAI_API_KEY` environment variable or the api_key in the config dictionary.
> **Note**: The following are currently unsupported with reasoning models `Parallel tool calling`,`temperature`, `top_p`, `presence_penalty`, `frequency_penalty`, `logprobs`, `top_logprobs`, `logit_bias`, `max_tokens`
## Usage
<CodeGroup>
```python Python
import os
from mem0 import Memory
os.environ["OPENAI_API_KEY"] = "your-api-key" # used for embedding model
os.environ["LLM_AZURE_OPENAI_API_KEY"] = "your-api-key"
os.environ["LLM_AZURE_DEPLOYMENT"] = "your-deployment-name"
os.environ["LLM_AZURE_ENDPOINT"] = "your-api-base-url"
os.environ["LLM_AZURE_API_VERSION"] = "version-to-use"
config = {
"llm": {
"provider": "azure_openai",
"config": {
"model": "your-deployment-name",
"temperature": 0.1,
"max_tokens": 2000,
"azure_kwargs": {
"azure_deployment": "",
"api_version": "",
"azure_endpoint": "",
"api_key": "",
"default_headers": {
"CustomHeader": "your-custom-header",
}
}
}
}
}
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"})
```
```typescript TypeScript
import { Memory } from 'mem0ai/oss';
const config = {
llm: {
provider: 'azure_openai',
config: {
apiKey: process.env.AZURE_OPENAI_API_KEY || '',
modelProperties: {
endpoint: 'https://your-api-base-url',
deployment: 'your-deployment-name',
modelName: 'your-model-name',
apiVersion: 'version-to-use',
// Any other parameters you want to pass to the Azure OpenAI API
},
},
},
};
const memory = new Memory(config);
const 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."}
]
await memory.add(messages, { userId: "alice", metadata: { category: "movies" } });
```
</CodeGroup>
We also support the new [OpenAI structured-outputs](https://platform.openai.com/docs/guides/structured-outputs/introduction) model. Typescript SDK does not support the `azure_openai_structured` model yet.
```python
import os
from mem0 import Memory
os.environ["LLM_AZURE_OPENAI_API_KEY"] = "your-api-key"
os.environ["LLM_AZURE_DEPLOYMENT"] = "your-deployment-name"
os.environ["LLM_AZURE_ENDPOINT"] = "your-api-base-url"
os.environ["LLM_AZURE_API_VERSION"] = "version-to-use"
config = {
"llm": {
"provider": "azure_openai_structured",
"config": {
"model": "your-deployment-name",
"temperature": 0.1,
"max_tokens": 2000,
"azure_kwargs": {
"azure_deployment": "",
"api_version": "",
"azure_endpoint": "",
"api_key": "",
"default_headers": {
"CustomHeader": "your-custom-header",
}
}
}
}
}
```
As an alternative to using an API key, the Azure Identity credential chain can be used to authenticate with [Azure OpenAI role-based security](https://learn.microsoft.com/en-us/azure/ai-foundry/openai/how-to/role-based-access-control).
<Note> If an API key is provided, it will be used for authentication over an Azure Identity </Note>
Below is a sample configuration for using Mem0 with Azure OpenAI and Azure Identity:
```python
import os
from mem0 import Memory
# You can set the values directly in the config dictionary or use environment variables
os.environ["LLM_AZURE_DEPLOYMENT"] = "your-deployment-name"
os.environ["LLM_AZURE_ENDPOINT"] = "your-api-base-url"
os.environ["LLM_AZURE_API_VERSION"] = "version-to-use"
config = {
"llm": {
"provider": "azure_openai_structured",
"config": {
"model": "your-deployment-name",
"temperature": 0.1,
"max_tokens": 2000,
"azure_kwargs": {
"azure_deployment": "<your-deployment-name>",
"api_version": "<version-to-use>",
"azure_endpoint": "<your-api-base-url>",
"default_headers": {
"CustomHeader": "your-custom-header",
}
}
}
}
}
```
Refer to [Azure Identity troubleshooting tips](https://github.com/Azure/azure-sdk-for-python/blob/main/sdk/identity/azure-identity/TROUBLESHOOTING.md#troubleshoot-environmentcredential-authentication-issues) for setting up an Azure Identity credential.
## Config
All available parameters for the `azure_openai` config are present in [Master List of All Params in Config](../config).
@@ -1,55 +0,0 @@
---
title: DeepSeek
---
To use DeepSeek LLM models, you have to set the `DEEPSEEK_API_KEY` environment variable. You can also optionally set `DEEPSEEK_API_BASE` if you need to use a different API endpoint (defaults to "https://api.deepseek.com").
## Usage
```python
import os
from mem0 import Memory
os.environ["DEEPSEEK_API_KEY"] = "your-api-key"
os.environ["OPENAI_API_KEY"] = "your-api-key" # for embedder model
config = {
"llm": {
"provider": "deepseek",
"config": {
"model": "deepseek-chat", # default model
"temperature": 0.2,
"max_tokens": 2000,
"top_p": 1.0
}
}
}
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"})
```
You can also configure the API base URL in the config:
```python
config = {
"llm": {
"provider": "deepseek",
"config": {
"model": "deepseek-chat",
"deepseek_base_url": "https://your-custom-endpoint.com",
"api_key": "your-api-key" # alternatively to using environment variable
}
}
}
```
## Config
All available parameters for the `deepseek` config are present in [Master List of All Params in Config](../config).
@@ -1,74 +0,0 @@
---
title: Google AI
---
To use the Gemini model, set the `GOOGLE_API_KEY` environment variable. You can obtain the Google/Gemini API key from [Google AI Studio](https://aistudio.google.com/app/apikey).
> **Note:** As of the latest release, Mem0 uses the new `google.genai` SDK instead of the deprecated `google.generativeai`. All message formatting and model interaction now use the updated `types` module from `google.genai`.
> **Note:** Some Gemini models are being deprecated and will retire soon. It is recommended to migrate to the latest stable models like `"gemini-2.0-flash-001"` or `"gemini-2.0-flash-lite-001"` to ensure ongoing support and improvements.
## Usage
<CodeGroup>
```python Python
import os
from mem0 import Memory
os.environ["OPENAI_API_KEY"] = "your-openai-api-key" # Used for embedding model
os.environ["GOOGLE_API_KEY"] = "your-gemini-api-key"
config = {
"llm": {
"provider": "gemini",
"config": {
"model": "gemini-2.0-flash-001",
"temperature": 0.2,
"max_tokens": 2000,
"top_p": 1.0
}
}
}
m = Memory.from_config(config)
messages = [
{"role": "user", "content": "I'm planning to watch a movie tonight. Any recommendations?"},
{"role": "assistant", "content": "How about thriller movies? They can be quite engaging."},
{"role": "user", "content": "I’m not a big fan of thrillers, but I love sci-fi movies."},
{"role": "assistant", "content": "Got it! I'll avoid thrillers and suggest sci-fi movies instead."}
]
m.add(messages, user_id="alice", metadata={"category": "movies"})
```
```typescript TypeScript
import { Memory } from "mem0ai/oss";
const config = {
llm: {
// You can also use "google" as provider ( for backward compatibility )
provider: "gemini",
config: {
model: "gemini-2.0-flash-001",
temperature: 0.1
}
}
}
const memory = new Memory(config);
const messages = [
{ role: "user", content: "I'm planning to watch a movie tonight. Any recommendations?" },
{ role: "assistant", content: "How about thriller movies? They can be quite engaging." },
{ role: "user", content: "I’m not a big fan of thrillers, but I love sci-fi movies." },
{ role: "assistant", content: "Got it! I'll avoid thrillers and suggest sci-fi movies instead." }
]
await memory.add(messages, { userId: "alice", metadata: { category: "movies" } });
```
</CodeGroup>
## Config
All available parameters for the `Gemini` config are present in [Master List of All Params in Config](../config).
-68
View File
@@ -1,68 +0,0 @@
---
title: Groq
---
[Groq](https://groq.com/) is the creator of the world's first Language Processing Unit (LPU), providing exceptional speed performance for AI workloads running on their LPU Inference Engine.
In order to use LLMs from Groq, go to their [platform](https://console.groq.com/keys) and get the API key. Set the API key as `GROQ_API_KEY` environment variable to use the model as given below in the example.
## Usage
<CodeGroup>
```python Python
import os
from mem0 import Memory
os.environ["OPENAI_API_KEY"] = "your-api-key" # used for embedding model
os.environ["GROQ_API_KEY"] = "your-api-key"
config = {
"llm": {
"provider": "groq",
"config": {
"model": "mixtral-8x7b-32768",
"temperature": 0.1,
"max_tokens": 2000,
}
}
}
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"})
```
```typescript TypeScript
import { Memory } from 'mem0ai/oss';
const config = {
llm: {
provider: 'groq',
config: {
apiKey: process.env.GROQ_API_KEY || '',
model: 'mixtral-8x7b-32768',
temperature: 0.1,
maxTokens: 1000,
},
},
};
const memory = new Memory(config);
const 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."}
]
await memory.add(messages, { userId: "alice", metadata: { category: "movies" } });
```
</CodeGroup>
## Config
All available parameters for the `groq` config are present in [Master List of All Params in Config](../config).
@@ -1,109 +0,0 @@
---
title: LangChain
---
Mem0 supports LangChain as a provider to access a wide range of LLM models. LangChain is a framework for developing applications powered by language models, making it easy to integrate various LLM providers through a consistent interface.
For a complete list of available chat models supported by LangChain, refer to the [LangChain Chat Models documentation](https://python.langchain.com/docs/integrations/chat).
## Usage
<CodeGroup>
```python Python
import os
from mem0 import Memory
from langchain_openai import ChatOpenAI
# Set necessary environment variables for your chosen LangChain provider
os.environ["OPENAI_API_KEY"] = "your-api-key"
# Initialize a LangChain model directly
openai_model = ChatOpenAI(
model="gpt-4.1-nano-2025-04-14",
temperature=0.2,
max_tokens=2000
)
# Pass the initialized model to the config
config = {
"llm": {
"provider": "langchain",
"config": {
"model": openai_model
}
}
}
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"})
```
```typescript TypeScript
import { Memory } from 'mem0ai/oss';
import { ChatOpenAI } from "@langchain/openai";
// Initialize a LangChain model directly
const openaiModel = new ChatOpenAI({
modelName: "gpt-4",
temperature: 0.2,
maxTokens: 2000,
apiKey: process.env.OPENAI_API_KEY,
});
const config = {
llm: {
provider: 'langchain',
config: {
model: openaiModel,
},
},
};
const memory = new Memory(config);
const 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."}
]
await memory.add(messages, { userId: "alice", metadata: { category: "movies" } });
```
</CodeGroup>
## Supported LangChain Providers
LangChain supports a wide range of LLM providers, including:
- OpenAI (`ChatOpenAI`)
- Anthropic (`ChatAnthropic`)
- Google (`ChatGoogleGenerativeAI`, `ChatGooglePalm`)
- Mistral (`ChatMistralAI`)
- Ollama (`ChatOllama`)
- Azure OpenAI (`AzureChatOpenAI`)
- HuggingFace (`HuggingFaceChatEndpoint`)
- And many more
You can use any of these model instances directly in your configuration. For a complete and up-to-date list of available providers, refer to the [LangChain Chat Models documentation](https://python.langchain.com/docs/integrations/chat).
## Provider-Specific Configuration
When using LangChain as a provider, you'll need to:
1. Set the appropriate environment variables for your chosen LLM provider
2. Import and initialize the specific model class you want to use
3. Pass the initialized model instance to the config
<Note>
Make sure to install the necessary LangChain packages and any provider-specific dependencies.
</Note>
## Config
All available parameters for the `langchain` config are present in [Master List of All Params in Config](../config).
@@ -1,34 +0,0 @@
[Litellm](https://litellm.vercel.app/docs/) is compatible with over 100 large language models (LLMs), all using a standardized input/output format. You can explore the [available models](https://litellm.vercel.app/docs/providers) to use with Litellm. Ensure you set the `API_KEY` for the model you choose to use.
## Usage
```python
import os
from mem0 import Memory
os.environ["OPENAI_API_KEY"] = "your-api-key"
config = {
"llm": {
"provider": "litellm",
"config": {
"model": "gpt-4.1-nano-2025-04-14",
"temperature": 0.2,
"max_tokens": 2000,
}
}
}
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"})
```
## Config
All available parameters for the `litellm` config are present in [Master List of All Params in Config](../config).
@@ -1,83 +0,0 @@
---
title: LM Studio
---
To use LM Studio with Mem0, you'll need to have LM Studio running locally with its server enabled. LM Studio provides a way to run local LLMs with an OpenAI-compatible API.
## Usage
<CodeGroup>
```python Python
import os
from mem0 import Memory
os.environ["OPENAI_API_KEY"] = "your-api-key" # used for embedding model
config = {
"llm": {
"provider": "lmstudio",
"config": {
"model": "lmstudio-community/Meta-Llama-3.1-70B-Instruct-GGUF/Meta-Llama-3.1-70B-Instruct-IQ2_M.gguf",
"temperature": 0.2,
"max_tokens": 2000,
"lmstudio_base_url": "http://localhost:1234/v1", # default LM Studio API URL
"lmstudio_response_format": {"type": "json_schema", "json_schema": {"type": "object", "schema": {}}},
}
}
}
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"})
```
</CodeGroup>
### Running Completely Locally
You can also use LM Studio for both LLM and embedding to run Mem0 entirely locally:
```python
from mem0 import Memory
# No external API keys needed!
config = {
"llm": {
"provider": "lmstudio"
},
"embedder": {
"provider": "lmstudio"
}
}
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="alice123", metadata={"category": "movies"})
```
<Note>
When using LM Studio for both LLM and embedding, make sure you have:
1. An LLM model loaded for generating responses
2. An embedding model loaded for vector embeddings
3. The server enabled with the correct endpoints accessible
</Note>
<Note>
To use LM Studio, you need to:
1. Download and install [LM Studio](https://lmstudio.ai/)
2. Start a local server from the "Server" tab
3. Set the appropriate `lmstudio_base_url` in your configuration (default is usually http://localhost:1234/v1)
</Note>
## Config
All available parameters for the `lmstudio` config are present in [Master List of All Params in Config](../config).
@@ -1,66 +0,0 @@
---
title: Mistral AI
---
To use mistral's models, please obtain the Mistral AI api key from their [console](https://console.mistral.ai/). Set the `MISTRAL_API_KEY` environment variable to use the model as given below in the example.
## Usage
<CodeGroup>
```python Python
import os
from mem0 import Memory
os.environ["OPENAI_API_KEY"] = "your-api-key" # used for embedding model
os.environ["MISTRAL_API_KEY"] = "your-api-key"
config = {
"llm": {
"provider": "litellm",
"config": {
"model": "open-mixtral-8x7b",
"temperature": 0.1,
"max_tokens": 2000,
}
}
}
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"})
```
```typescript TypeScript
import { Memory } from 'mem0ai/oss';
const config = {
llm: {
provider: 'mistral',
config: {
apiKey: process.env.MISTRAL_API_KEY || '',
model: 'mistral-tiny-latest', // Or 'mistral-small-latest', 'mistral-medium-latest', etc.
temperature: 0.1,
maxTokens: 2000,
},
},
};
const memory = new Memory(config);
const 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."}
]
await memory.add(messages, { userId: "alice", metadata: { category: "movies" } });
```
</CodeGroup>
## Config
All available parameters for the `litellm` config are present in [Master List of All Params in Config](../config).
@@ -1,60 +0,0 @@
You can use LLMs from Ollama to run Mem0 locally. These [models](https://ollama.com/search?c=tools) support tool support.
## Usage
<CodeGroup>
```python Python
import os
from mem0 import Memory
os.environ["OPENAI_API_KEY"] = "your-api-key" # for embedder
config = {
"llm": {
"provider": "ollama",
"config": {
"model": "mixtral:8x7b",
"temperature": 0.1,
"max_tokens": 2000,
}
}
}
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"})
```
```typescript TypeScript
import { Memory } from 'mem0ai/oss';
const config = {
llm: {
provider: 'ollama',
config: {
model: 'llama3.1:8b', // or any other Ollama model
url: 'http://localhost:11434', // Ollama server URL
temperature: 0.1,
},
},
};
const memory = new Memory(config);
const 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."}
]
await memory.add(messages, { userId: "alice", metadata: { category: "movies" } });
```
</CodeGroup>
## Config
All available parameters for the `ollama` config are present in [Master List of All Params in Config](../config).
@@ -1,99 +0,0 @@
---
title: OpenAI
---
To use OpenAI LLM models, you have to set the `OPENAI_API_KEY` environment variable. You can obtain the OpenAI API key from the [OpenAI Platform](https://platform.openai.com/account/api-keys).
> **Note**: The following are currently unsupported with reasoning models `Parallel tool calling`,`temperature`, `top_p`, `presence_penalty`, `frequency_penalty`, `logprobs`, `top_logprobs`, `logit_bias`, `max_tokens`
## Usage
<CodeGroup>
```python Python
import os
from mem0 import Memory
os.environ["OPENAI_API_KEY"] = "your-api-key"
config = {
"llm": {
"provider": "openai",
"config": {
"model": "gpt-4.1-nano-2025-04-14",
"temperature": 0.2,
"max_tokens": 2000,
}
}
}
# Use Openrouter by passing it's api key
# os.environ["OPENROUTER_API_KEY"] = "your-api-key"
# config = {
# "llm": {
# "provider": "openai",
# "config": {
# "model": "meta-llama/llama-3.1-70b-instruct",
# }
# }
# }
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"})
```
```typescript TypeScript
import { Memory } from 'mem0ai/oss';
const config = {
llm: {
provider: 'openai',
config: {
apiKey: process.env.OPENAI_API_KEY || '',
model: 'gpt-4-turbo-preview',
temperature: 0.2,
maxTokens: 1500,
},
},
};
const memory = new Memory(config);
const 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."}
]
await memory.add(messages, { userId: "alice", metadata: { category: "movies" } });
```
</CodeGroup>
We also support the new [OpenAI structured-outputs](https://platform.openai.com/docs/guides/structured-outputs/introduction) model.
```python
import os
from mem0 import Memory
os.environ["OPENAI_API_KEY"] = "your-api-key"
config = {
"llm": {
"provider": "openai_structured",
"config": {
"model": "gpt-4.1-nano-2025-04-14",
"temperature": 0.0,
}
}
}
m = Memory.from_config(config)
```
## Config
All available parameters for the `openai` config are present in [Master List of All Params in Config](../config).
@@ -1,73 +0,0 @@
---
title: Sarvam AI
---
**Sarvam AI** is an Indian AI company developing language models with a focus on Indian languages and cultural context. Their latest model **Sarvam-M** is designed to understand and generate content in multiple Indian languages while maintaining high performance in English.
To use Sarvam AI's models, please set the `SARVAM_API_KEY` which you can get from their [platform](https://dashboard.sarvam.ai/).
## Usage
```python
import os
from mem0 import Memory
os.environ["OPENAI_API_KEY"] = "your-api-key" # used for embedding model
os.environ["SARVAM_API_KEY"] = "your-api-key"
config = {
"llm": {
"provider": "sarvam",
"config": {
"model": "sarvam-m",
"temperature": 0.7,
}
}
}
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="alex")
```
## Advanced Usage with Sarvam-Specific Features
```python
import os
from mem0 import Memory
config = {
"llm": {
"provider": "sarvam",
"config": {
"model": {
"name": "sarvam-m",
"reasoning_effort": "high", # Enable advanced reasoning
"frequency_penalty": 0.1, # Reduce repetition
"seed": 42 # For deterministic outputs
},
"temperature": 0.3,
"max_tokens": 2000,
"api_key": "your-sarvam-api-key"
}
}
}
m = Memory.from_config(config)
# Example with Hindi conversation
messages = [
{"role": "user", "content": "मैं SBI में joint account खोलना चाहता हूँ।"},
{"role": "assistant", "content": "SBI में joint account खोलने के लिए आपको कुछ documents की जरूरत होगी। क्या आप जानना चाहते हैं कि कौन से documents चाहिए?"}
]
m.add(messages, user_id="rajesh", metadata={"language": "hindi", "topic": "banking"})
```
## Config
All available parameters for the `sarvam` config are present in [Master List of All Params in Config](../config).
@@ -1,35 +0,0 @@
To use TogetherAI LLM models, you have to set the `TOGETHER_API_KEY` environment variable. You can obtain the TogetherAI API key from their [Account settings page](https://api.together.xyz/settings/api-keys).
## Usage
```python
import os
from mem0 import Memory
os.environ["OPENAI_API_KEY"] = "your-api-key" # used for embedding model
os.environ["TOGETHER_API_KEY"] = "your-api-key"
config = {
"llm": {
"provider": "together",
"config": {
"model": "mistralai/Mixtral-8x7B-Instruct-v0.1",
"temperature": 0.2,
"max_tokens": 2000,
}
}
}
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"})
```
## Config
All available parameters for the `togetherai` config are present in [Master List of All Params in Config](../config).
-107
View File
@@ -1,107 +0,0 @@
---
title: vLLM
---
[vLLM](https://docs.vllm.ai/) is a high-performance inference engine for large language models that provides significant performance improvements for local inference. It's designed to maximize throughput and memory efficiency for serving LLMs.
## Prerequisites
1. **Install vLLM**:
```bash
pip install vllm
```
2. **Start vLLM server**:
```bash
# For testing with a small model
vllm serve microsoft/DialoGPT-medium --port 8000
# For production with a larger model (requires GPU)
vllm serve Qwen/Qwen2.5-32B-Instruct --port 8000
```
## Usage
```python
import os
from mem0 import Memory
os.environ["OPENAI_API_KEY"] = "your-api-key" # used for embedding model
config = {
"llm": {
"provider": "vllm",
"config": {
"model": "Qwen/Qwen2.5-32B-Instruct",
"vllm_base_url": "http://localhost:8000/v1",
"temperature": 0.1,
"max_tokens": 2000,
}
}
}
m = Memory.from_config(config)
messages = [
{"role": "user", "content": "I'm planning to watch a movie tonight. Any recommendations?"},
{"role": "assistant", "content": "How about thriller movies? They can be quite engaging."},
{"role": "user", "content": "I'm not a big fan of thrillers, but I love sci-fi movies."},
{"role": "assistant", "content": "Got it! I'll avoid thrillers and suggest sci-fi movies instead."}
]
m.add(messages, user_id="alice", metadata={"category": "movies"})
```
## Configuration Parameters
| Parameter | Description | Default | Environment Variable |
| --------------- | --------------------------------- | ----------------------------- | -------------------- |
| `model` | Model name running on vLLM server | `"Qwen/Qwen2.5-32B-Instruct"` | - |
| `vllm_base_url` | vLLM server URL | `"http://localhost:8000/v1"` | `VLLM_BASE_URL` |
| `api_key` | API key (dummy for local) | `"vllm-api-key"` | `VLLM_API_KEY` |
| `temperature` | Sampling temperature | `0.1` | - |
| `max_tokens` | Maximum tokens to generate | `2000` | - |
## Environment Variables
You can set these environment variables instead of specifying them in config:
```bash
export VLLM_BASE_URL="http://localhost:8000/v1"
export VLLM_API_KEY="your-vllm-api-key"
export OPENAI_API_KEY="your-openai-api-key" # for embeddings
```
## Benefits
- **High Performance**: 2-24x faster inference than standard implementations
- **Memory Efficient**: Optimized memory usage with PagedAttention
- **Local Deployment**: Keep your data private and reduce API costs
- **Easy Integration**: Drop-in replacement for other LLM providers
- **Flexible**: Works with any model supported by vLLM
## Troubleshooting
1. **Server not responding**: Make sure vLLM server is running
```bash
curl http://localhost:8000/health
```
2. **404 errors**: Ensure correct base URL format
```python
"vllm_base_url": "http://localhost:8000/v1" # Note the /v1
```
3. **Model not found**: Check model name matches server
4. **Out of memory**: Try smaller models or reduce `max_model_len`
```bash
vllm serve Qwen/Qwen2.5-32B-Instruct --max-model-len 4096
```
## Config
All available parameters for the `vllm` config are present in [Master List of All Params in Config](../config).
-41
View File
@@ -1,41 +0,0 @@
---
title: xAI
---
[xAI](https://x.ai/) is a new AI company founded by Elon Musk that develops large language models, including Grok. Grok is trained on real-time data from X (formerly Twitter) and aims to provide accurate, up-to-date responses with a touch of wit and humor.
In order to use LLMs from xAI, go to their [platform](https://console.x.ai) and get the API key. Set the API key as `XAI_API_KEY` environment variable to use the model as given below in the example.
## Usage
```python
import os
from mem0 import Memory
os.environ["OPENAI_API_KEY"] = "your-api-key" # used for embedding model
os.environ["XAI_API_KEY"] = "your-api-key"
config = {
"llm": {
"provider": "xai",
"config": {
"model": "grok-3-beta",
"temperature": 0.1,
"max_tokens": 2000,
}
}
}
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"})
```
## Config
All available parameters for the `xai` config are present in [Master List of All Params in Config](../config).
-63
View File
@@ -1,63 +0,0 @@
---
title: Overview
icon: "info"
iconType: "solid"
---
Mem0 includes built-in support for various popular large language models. Memory can utilize the LLM provided by the user, ensuring efficient use for specific needs.
## Usage
To use a llm, you must provide a configuration to customize its usage. If no configuration is supplied, a default configuration will be applied, and `OpenAI` will be used as the llm.
For a comprehensive list of available parameters for llm configuration, please refer to [Config](./config).
## Supported LLMs
See the list of supported LLMs below.
<Note>
All LLMs are supported in Python. The following LLMs are also supported in TypeScript: **OpenAI**, **Anthropic**, and **Groq**.
</Note>
<CardGroup cols={4}>
<Card title="OpenAI" href="/components/llms/models/openai" />
<Card title="Ollama" href="/components/llms/models/ollama" />
<Card title="Azure OpenAI" href="/components/llms/models/azure_openai" />
<Card title="Anthropic" href="/components/llms/models/anthropic" />
<Card title="Together" href="/components/llms/models/together" />
<Card title="Groq" href="/components/llms/models/groq" />
<Card title="Litellm" href="/components/llms/models/litellm" />
<Card title="Mistral AI" href="/components/llms/models/mistral_AI" />
<Card title="Google AI" href="/components/llms/models/google_AI" />
<Card title="AWS bedrock" href="/components/llms/models/aws_bedrock" />
<Card title="DeepSeek" href="/components/llms/models/deepseek" />
<Card title="xAI" href="/components/llms/models/xAI" />
<Card title="Sarvam AI" href="/components/llms/models/sarvam" />
<Card title="LM Studio" href="/components/llms/models/lmstudio" />
<Card title="Langchain" href="/components/llms/models/langchain" />
</CardGroup>
## Structured vs Unstructured Outputs
Mem0 supports two types of OpenAI LLM formats, each with its own strengths and use cases:
### Structured Outputs
Structured outputs are LLMs that align with OpenAI's structured outputs model:
- **Optimized for:** Returning structured responses (e.g., JSON objects)
- **Benefits:** Precise, easily parseable data
- **Ideal for:** Data extraction, form filling, API responses
- **Learn more:** [OpenAI Structured Outputs Guide](https://platform.openai.com/docs/guides/structured-outputs/introduction)
### Unstructured Outputs
Unstructured outputs correspond to OpenAI's standard, free-form text model:
- **Flexibility:** Returns open-ended, natural language responses
- **Customization:** Use the `response_format` parameter to guide output
- **Trade-off:** Less efficient than structured outputs for specific data needs
- **Best for:** Creative writing, explanations, general conversation
Choose the format that best suits your application's requirements for optimal performance and usability.
-128
View File
@@ -1,128 +0,0 @@
---
title: Configurations
icon: "gear"
iconType: "solid"
---
## How to define configurations?
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", "valkey")
- `config`: A nested dictionary containing provider-specific settings
## How to Use Config
Here's a general example of how to use the config with mem0:
<CodeGroup>
```python Python
import os
from mem0 import Memory
os.environ["OPENAI_API_KEY"] = "sk-xx"
config = {
"vector_store": {
"provider": "your_chosen_provider",
"config": {
# Provider-specific settings go here
}
}
}
m = Memory.from_config(config)
m.add("Your text here", user_id="user", metadata={"category": "example"})
```
```typescript TypeScript
// Example for in-memory vector database (Only supported in TypeScript)
import { Memory } from 'mem0ai/oss';
const configMemory = {
vector_store: {
provider: 'memory',
config: {
collectionName: 'memories',
dimension: 1536,
},
},
};
const memory = new Memory(configMemory);
await memory.add("Your text here", { userId: "user", metadata: { category: "example" } });
```
</CodeGroup>
<Note>
The in-memory vector database is only supported in the TypeScript implementation.
</Note>
## Why is Config Needed?
Config is essential for:
1. Specifying which vector database to use.
2. Providing necessary connection details (e.g., host, port, credentials).
3. Customizing database-specific settings (e.g., collection name, path).
4. Ensuring proper initialization and connection to your chosen vector store.
## Master List of All Params in Config
Here's a comprehensive list of all parameters that can be used across different vector databases:
<Tabs>
<Tab title="Python">
| Parameter | Description |
|-----------|-------------|
| `collection_name` | Name of the collection |
| `embedding_model_dims` | Dimensions of the embedding model |
| `client` | Custom client for the database |
| `path` | Path for the database |
| `host` | Host where the server is running |
| `port` | Port where the server is running |
| `user` | Username for database connection |
| `password` | Password for database connection |
| `dbname` | Name of the database |
| `url` | Full URL for the server |
| `api_key` | API key for the server |
| `on_disk` | Enable persistent storage |
| `endpoint_id` | Endpoint ID (vertex_ai_vector_search) |
| `index_id` | Index ID (vertex_ai_vector_search) |
| `deployment_index_id` | Deployment index ID (vertex_ai_vector_search) |
| `project_id` | Project ID (vertex_ai_vector_search) |
| `project_number` | Project number (vertex_ai_vector_search) |
| `vector_search_api_endpoint` | Vector search API endpoint (vertex_ai_vector_search) |
| `connection_string` | PostgreSQL connection string (for Supabase/PGVector) |
| `index_method` | Vector index method (for Supabase) |
| `index_measure` | Distance measure for similarity search (for Supabase) |
</Tab>
<Tab title="TypeScript">
| Parameter | Description |
|-----------|-------------|
| `collectionName` | Name of the collection |
| `embeddingModelDims` | Dimensions of the embedding model |
| `dimension` | Dimensions of the embedding model (for memory provider) |
| `host` | Host where the server is running |
| `port` | Port where the server is running |
| `url` | URL for the server |
| `apiKey` | API key for the server |
| `path` | Path for the database |
| `onDisk` | Enable persistent storage |
| `redisUrl` | URL for the Redis server |
| `username` | Username for database connection |
| `password` | Password for database connection |
</Tab>
</Tabs>
## Customizing Config
Each vector database has its own specific configuration requirements. To customize the config for your chosen vector store:
1. Identify the vector database you want to use from [supported vector databases](./dbs).
2. Refer to the `Config` section in the respective vector database's documentation.
3. Include only the relevant parameters for your chosen database in the `config` dictionary.
## Supported Vector Databases
For detailed information on configuring specific vector databases, please visit the [Supported Vector Databases](./dbs) section. There you'll find individual pages for each supported vector store with provider-specific usage examples and configuration details.
-179
View File
@@ -1,179 +0,0 @@
---
title: Azure AI Search
---
[Azure AI Search](https://learn.microsoft.com/azure/search/search-what-is-azure-search/) (formerly known as "Azure Cognitive Search") provides secure information retrieval at scale over user-owned content in traditional and generative AI search applications.
## Usage
```python
import os
from mem0 import Memory
os.environ["OPENAI_API_KEY"] = "sk-xx" # This key is used for embedding purpose
config = {
"vector_store": {
"provider": "azure_ai_search",
"config": {
"service_name": "<your-azure-ai-search-service-name>",
"api_key": "<your-api-key>",
"collection_name": "mem0",
"embedding_model_dims": 1536
}
}
}
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"})
```
## Using binary compression for large vector collections
```python
config = {
"vector_store": {
"provider": "azure_ai_search",
"config": {
"service_name": "<your-azure-ai-search-service-name>",
"api_key": "<your-api-key>",
"collection_name": "mem0",
"embedding_model_dims": 1536,
"compression_type": "binary",
"use_float16": True # Use half precision for storage efficiency
}
}
}
```
## Using hybrid search
```python
config = {
"vector_store": {
"provider": "azure_ai_search",
"config": {
"service_name": "<your-azure-ai-search-service-name>",
"api_key": "<your-api-key>",
"collection_name": "mem0",
"embedding_model_dims": 1536,
"hybrid_search": True,
"vector_filter_mode": "postFilter"
}
}
}
```
## Using Azure Identity for Authentication
As an alternative to using an API key, the Azure Identity credential chain can be used to authenticate with Azure OpenAI. The list below shows the order of precedence for credential application:
1. **Environment Credential:**
Azure client ID, secret, tenant ID, or certificate in environment variables for service principal authentication.
2. **Workload Identity Credential:**
Utilizes Azure Workload Identity (relevant for Kubernetes and Azure workloads).
3. **Managed Identity Credential:**
Authenticates as a Managed Identity (for apps/services hosted in Azure with Managed Identity enabled), this is the most secure production credential.
4. **Shared Token Cache Credential / Visual Studio Credential (Windows only):**
Uses cached credentials from Visual Studio sign-ins (and sometimes VS Code if SSO is enabled).
5. **Azure CLI Credential:**
Uses the currently logged-in user from the Azure CLI (`az login`), this is the most common development credential.
6. **Azure PowerShell Credential:**
Uses the identity from Azure PowerShell (`Connect-AzAccount`).
7. **Azure Developer CLI Credential:**
Uses the session from Azure Developer CLI (`azd auth login`).
<Note> If an API is provided, it will be used for authentication over an Azure Identity </Note>
To enable Role-Based Access Control (RBAC) for Azure AI Search, follow these steps:
1. In the Azure Portal, navigate to your **Azure AI Search** service.
2. In the left menu, select **Settings** > **Keys**.
3. Change the authentication setting to **Role-based access control**, or **Both** if you need API key compatibility. The default is “Key-based authentication”—you must switch it to use Azure roles.
4. **Go to Access Control (IAM):**
- In the Azure Portal, select your Search service.
- Click **Access Control (IAM)** on the left.
5. **Add a Role Assignment:**
- Click **Add** > **Add role assignment**.
6. **Choose Role:**
- Mem0 requires the **Search Index Data Contributor** and **Search Service Contributor** role.
7. **Choose Member**
- To assign to a User, Group, Service Principle or Managed Identity:
- For production it is recommended to use a service principal or managed identity.
- For a service principal: select **User, group, or service principal** and search for the service principal.
- For a managed identity: select **Managed identity** and choose the managed identity.
- For development, you can assign the role to a user account.
- For development: select ***User, group, or service principal** and pick a Azure Entra ID account (the same used with `az login`).
8. **Complete the Assignment:**
- Click **Review + Assign**.
If you are using Azure Identity, do not set the `api_key` in the configuration.
```python
config = {
"vector_store": {
"provider": "azure_ai_search",
"config": {
"service_name": "<your-azure-ai-search-service-name>",
"collection_name": "mem0",
"embedding_model_dims": 1536,
"compression_type": "binary",
"use_float16": True # Use half precision for storage efficiency
}
}
}
```
### Environment Variables to set to use Azure Identity Credential:
* For an Environment Credential, you will need to setup a Service Principal and set the following environment variables:
- `AZURE_TENANT_ID`: Your Azure Active Directory tenant ID.
- `AZURE_CLIENT_ID`: The client ID of your service principal or managed identity.
- `AZURE_CLIENT_SECRET`: The client secret of your service principal.
* For a User-Assigned Managed Identity, you will need to set the following environment variable:
- `AZURE_CLIENT_ID`: The client ID of the user-assigned managed identity.
* For a System-Assigned Managed Identity, no additional environment variables are needed.
### Developer logins to use for a Azure Identity Credential:
* For an Azure CLI Credential, you need to have the Azure CLI installed and logged in with `az login`.
* For an Azure PowerShell Credential, you need to have the Azure PowerShell module installed and logged in with `Connect-AzAccount`.
* For an Azure Developer CLI Credential, you need to have the Azure Developer CLI installed and logged in with `azd auth login`.
Troubleshooting tips for [Azure Identity](https://github.com/Azure/azure-sdk-for-python/blob/main/sdk/identity/azure-identity/TROUBLESHOOTING.md#troubleshoot-environmentcredential-authentication-issues).
## Configuration Parameters
| Parameter | Description | Default Value | Options |
| --- | --- | --- | --- |
| `service_name` | Azure AI Search service name | Required | - |
| `api_key` | API key of the Azure AI Search service | Optional | If not present, the [Azure Identity](#using-azure-identity-for-authentication) credential chain will be used |
| `collection_name` | The name of the collection/index to store vectors | `mem0` | Any valid index name |
| `embedding_model_dims` | Dimensions of the embedding model | `1536` | Any integer value |
| `compression_type` | Type of vector compression to use | `none` | `none`, `scalar`, `binary` |
| `use_float16` | Store vectors in half precision (Edm.Half) | `False` | `True`, `False` |
| `vector_filter_mode` | Vector filter mode to use | `preFilter` | `postFilter`, `preFilter` |
| `hybrid_search` | Use hybrid search | `False` | `True`, `False` |
## Notes on Configuration Options
- **compression_type**:
- `none`: No compression, uses full vector precision
- `scalar`: Scalar quantization with reasonable balance of speed and accuracy
- `binary`: Binary quantization for maximum compression with some accuracy trade-off
- **vector_filter_mode**:
- `preFilter`: Applies filters before vector search (faster)
- `postFilter`: Applies filters after vector search (may provide better relevance)
- **use_float16**: Using half precision (float16) reduces storage requirements but may slightly impact accuracy. Useful for very large vector collections.
- **Filterable Fields**: The implementation automatically extracts `user_id`, `run_id`, and `agent_id` fields from payloads for filtering.
@@ -1,128 +0,0 @@
---
title: Azure MySQL
---
[Azure Database for MySQL](https://azure.microsoft.com/products/mysql) is a fully managed relational database service that provides enterprise-grade reliability and security. It supports JSON-based vector storage for semantic search capabilities in AI applications.
### Usage
```python
import os
from mem0 import Memory
os.environ["OPENAI_API_KEY"] = "sk-xx"
config = {
"vector_store": {
"provider": "azure_mysql",
"config": {
"host": "your-server.mysql.database.azure.com",
"port": 3306,
"user": "your_username",
"password": "your_password",
"database": "mem0_db",
"collection_name": "memories",
}
}
}
m = Memory.from_config(config)
messages = [
{"role": "user", "content": "I'm planning to watch a movie tonight. Any recommendations?"},
{"role": "assistant", "content": "How about 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"})
```
#### Using Azure Managed Identity
For production deployments, use Azure Managed Identity instead of passwords:
```python
config = {
"vector_store": {
"provider": "azure_mysql",
"config": {
"host": "your-server.mysql.database.azure.com",
"user": "your_username",
"database": "mem0_db",
"collection_name": "memories",
"use_azure_credential": True, # Uses DefaultAzureCredential
"ssl_disabled": False
}
}
}
```
<Note>
When `use_azure_credential` is enabled, the password is obtained via Azure DefaultAzureCredential (supports Managed Identity, Azure CLI, etc.)
</Note>
### Config
Here are the parameters available for configuring Azure MySQL:
| Parameter | Description | Default Value |
| --- | --- | --- |
| `host` | MySQL server hostname | Required |
| `port` | MySQL server port | `3306` |
| `user` | Database user | Required |
| `password` | Database password (optional with Azure credential) | `None` |
| `database` | Database name | Required |
| `collection_name` | Table name for storing vectors | `"mem0"` |
| `embedding_model_dims` | Dimensions of embedding vectors | `1536` |
| `use_azure_credential` | Use Azure DefaultAzureCredential | `False` |
| `ssl_ca` | Path to SSL CA certificate | `None` |
| `ssl_disabled` | Disable SSL (not recommended) | `False` |
| `minconn` | Minimum connections in pool | `1` |
| `maxconn` | Maximum connections in pool | `5` |
### Setup
#### Create MySQL Flexible Server using Azure CLI:
```bash
# Create resource group
az group create --name mem0-rg --location eastus
# Create MySQL Flexible Server
az mysql flexible-server create \
--resource-group mem0-rg \
--name mem0-mysql-server \
--location eastus \
--admin-user myadmin \
--admin-password <YourPassword> \
--version 8.0.21
# Create database
az mysql flexible-server db create \
--resource-group mem0-rg \
--server-name mem0-mysql-server \
--database-name mem0_db
# Configure firewall
az mysql flexible-server firewall-rule create \
--resource-group mem0-rg \
--name mem0-mysql-server \
--rule-name AllowMyIP \
--start-ip-address <YourIP> \
--end-ip-address <YourIP>
```
#### Enable Azure AD Authentication:
1. In Azure Portal, navigate to your MySQL Flexible Server
2. Go to **Security** > **Authentication** and enable Azure AD
3. Add your application's managed identity as a MySQL user:
```sql
CREATE AADUSER 'your-app-identity' IDENTIFIED BY 'your-client-id';
GRANT ALL PRIVILEGES ON mem0_db.* TO 'your-app-identity'@'%';
FLUSH PRIVILEGES;
```
<Tip>
For production, use [Managed Identity](https://learn.microsoft.com/azure/active-directory/managed-identities-azure-resources/) to eliminate password management.
</Tip>
@@ -1,67 +0,0 @@
---
title: Baidu VectorDB (Mochow)
---
[Baidu VectorDB](https://cloud.baidu.com/doc/VDB/index.html) is an enterprise-level distributed vector database service developed by Baidu Intelligent Cloud. It is powered by Baidu's proprietary "Mochow" vector database kernel, providing high performance, availability, and security for vector search.
### Usage
```python
import os
from mem0 import Memory
config = {
"vector_store": {
"provider": "baidu",
"config": {
"endpoint": "http://your-mochow-endpoint:8287",
"account": "root",
"api_key": "your-api-key",
"database_name": "mem0",
"table_name": "mem0_table",
"embedding_model_dims": 1536,
"metric_type": "COSINE"
}
}
}
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 movie? 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"})
```
### Config
Here are the available parameters for the `mochow` config:
| Parameter | Description | Default Value |
| --- | --- | --- |
| `endpoint` | Endpoint URL for your Baidu VectorDB instance | Required |
| `account` | Baidu VectorDB account name | `root` |
| `api_key` | API key for accessing Baidu VectorDB | Required |
| `database_name` | Name of the database | `mem0` |
| `table_name` | Name of the table | `mem0_table` |
| `embedding_model_dims` | Dimensions of the embedding model | `1536` |
| `metric_type` | Distance metric for similarity search | `L2` |
### Distance Metrics
The following distance metrics are supported:
- `L2`: Euclidean distance (default)
- `IP`: Inner product
- `COSINE`: Cosine similarity
### Index Configuration
The vector index is automatically configured with the following HNSW parameters:
- `m`: 16 (number of connections per element)
- `efconstruction`: 200 (size of the dynamic candidate list)
- `auto_build`: true (automatically build index)
- `auto_build_index_policy`: Incremental build with 10000 rows increment
@@ -1,48 +0,0 @@
[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
os.environ["OPENAI_API_KEY"] = "sk-xx"
config = {
"vector_store": {
"provider": "chroma",
"config": {
"collection_name": "test",
"path": "db",
# Optional: ChromaDB Cloud configuration
# "api_key": "your-chroma-cloud-api-key",
# "tenant": "your-chroma-cloud-tenant-id",
}
}
}
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"})
```
### Config
Here are the parameters available for configuring Chroma:
| Parameter | Description | Default Value |
| --- | --- | --- |
| `collection_name` | The name of the collection | `mem0` |
| `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` |
| `api_key` | ChromaDB Cloud API key (for cloud usage) | `None` |
| `tenant` | ChromaDB Cloud tenant ID (for cloud usage) | `None` |
@@ -1,130 +0,0 @@
[Databricks Vector Search](https://docs.databricks.com/en/generative-ai/vector-search.html) is a serverless similarity search engine that allows you to store a vector representation of your data, including metadata, in a vector database. With Vector Search, you can create auto-updating vector search indexes from Delta tables managed by Unity Catalog and query them with a simple API to return the most similar vectors.
### Usage
```python
import os
from mem0 import Memory
config = {
"vector_store": {
"provider": "databricks",
"config": {
"workspace_url": "https://your-workspace.databricks.com",
"access_token": "your-access-token",
"endpoint_name": "your-vector-search-endpoint",
"index_name": "catalog.schema.index_name",
"source_table_name": "catalog.schema.source_table",
"embedding_dimension": 1536
}
}
}
m = Memory.from_config(config)
messages = [
{"role": "user", "content": "I'm planning to watch a movie tonight. Any recommendations?"},
{"role": "assistant", "content": "How about 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"})
```
### Config
Here are the parameters available for configuring Databricks Vector Search:
| Parameter | Description | Default Value |
| --- | --- | --- |
| `workspace_url` | The URL of your Databricks workspace | **Required** |
| `access_token` | Personal Access Token for authentication | `None` |
| `service_principal_client_id` | Service principal client ID (alternative to access_token) | `None` |
| `service_principal_client_secret` | Service principal client secret (required with client_id) | `None` |
| `endpoint_name` | Name of the Vector Search endpoint | **Required** |
| `index_name` | Name of the vector index (Unity Catalog format: catalog.schema.index) | **Required** |
| `source_table_name` | Name of the source Delta table (Unity Catalog format: catalog.schema.table) | **Required** |
| `embedding_dimension` | Dimension of self-managed embeddings | `1536` |
| `embedding_source_column` | Column name for text when using Databricks-computed embeddings | `None` |
| `embedding_model_endpoint_name` | Databricks serving endpoint for embeddings | `None` |
| `embedding_vector_column` | Column name for self-managed embedding vectors | `embedding` |
| `endpoint_type` | Type of endpoint (`STANDARD` or `STORAGE_OPTIMIZED`) | `STANDARD` |
| `sync_computed_embeddings` | Whether to sync computed embeddings automatically | `True` |
### Authentication
Databricks Vector Search supports two authentication methods:
#### Service Principal (Recommended for Production)
```python
config = {
"vector_store": {
"provider": "databricks",
"config": {
"workspace_url": "https://your-workspace.databricks.com",
"service_principal_client_id": "your-service-principal-id",
"service_principal_client_secret": "your-service-principal-secret",
"endpoint_name": "your-endpoint",
"index_name": "catalog.schema.index_name",
"source_table_name": "catalog.schema.source_table"
}
}
}
```
#### Personal Access Token (for Development)
```python
config = {
"vector_store": {
"provider": "databricks",
"config": {
"workspace_url": "https://your-workspace.databricks.com",
"access_token": "your-personal-access-token",
"endpoint_name": "your-endpoint",
"index_name": "catalog.schema.index_name",
"source_table_name": "catalog.schema.source_table"
}
}
}
```
### Embedding Options
#### Self-Managed Embeddings (Default)
Use your own embedding model and provide vectors directly:
```python
config = {
"vector_store": {
"provider": "databricks",
"config": {
# ... authentication config ...
"embedding_dimension": 768, # Match your embedding model
"embedding_vector_column": "embedding"
}
}
}
```
#### Databricks-Computed Embeddings
Let Databricks compute embeddings from text using a serving endpoint:
```python
config = {
"vector_store": {
"provider": "databricks",
"config": {
# ... authentication config ...
"embedding_source_column": "text",
"embedding_model_endpoint_name": "e5-small-v2"
}
}
}
```
### Important Notes
- **Delta Sync Index**: This implementation uses Delta Sync Index, which automatically syncs with your source Delta table. Direct vector insertion/deletion/update operations will log warnings as they're not supported with Delta Sync.
- **Unity Catalog**: Both the source table and index must be in Unity Catalog format (`catalog.schema.table_name`).
- **Endpoint Auto-Creation**: If the specified endpoint doesn't exist, it will be created automatically.
- **Index Auto-Creation**: If the specified index doesn't exist, it will be created automatically with the provided configuration.
- **Filter Support**: Supports filtering by metadata fields, with different syntax for STANDARD vs STORAGE_OPTIMIZED endpoints.
@@ -1,109 +0,0 @@
[Elasticsearch](https://www.elastic.co/) is a distributed, RESTful search and analytics engine that can efficiently store and search vector data using dense vectors and k-NN search.
### Installation
Elasticsearch support requires additional dependencies. Install them with:
```bash
pip install elasticsearch>=8.0.0
```
### Usage
```python
import os
from mem0 import Memory
os.environ["OPENAI_API_KEY"] = "sk-xx"
config = {
"vector_store": {
"provider": "elasticsearch",
"config": {
"collection_name": "mem0",
"host": "localhost",
"port": 9200,
"embedding_model_dims": 1536
}
}
}
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"})
```
### Config
Let's see the available parameters for the `elasticsearch` config:
| Parameter | Description | Default Value |
| ---------------------- | -------------------------------------------------- | ------------- |
| `collection_name` | The name of the index to store the vectors | `mem0` |
| `embedding_model_dims` | Dimensions of the embedding model | `1536` |
| `host` | The host where the Elasticsearch server is running | `localhost` |
| `port` | The port where the Elasticsearch server is running | `9200` |
| `cloud_id` | Cloud ID for Elastic Cloud deployment | `None` |
| `api_key` | API key for authentication | `None` |
| `user` | Username for basic authentication | `None` |
| `password` | Password for basic authentication | `None` |
| `verify_certs` | Whether to verify SSL certificates | `True` |
| `auto_create_index` | Whether to automatically create the index | `True` |
| `custom_search_query` | Function returning a custom search query | `None` |
| `headers` | Custom headers to include in requests | `None` |
### Features
- Efficient vector search using Elasticsearch's native k-NN search
- Support for both local and cloud deployments (Elastic Cloud)
- Multiple authentication methods (Basic Auth, API Key)
- Automatic index creation with optimized mappings for vector search
- Memory isolation through payload filtering
- Custom search query function to customize the search query
### Custom Search Query
The `custom_search_query` parameter allows you to customize the search query when `Memory.search` is called.
__Example__
```python
import os
from typing import List, Optional, Dict
from mem0 import Memory
def custom_search_query(query: List[float], limit: int, filters: Optional[Dict]) -> Dict:
return {
"knn": {
"field": "vector",
"query_vector": query,
"k": limit,
"num_candidates": limit * 2
}
}
os.environ["OPENAI_API_KEY"] = "sk-xx"
config = {
"vector_store": {
"provider": "elasticsearch",
"config": {
"collection_name": "mem0",
"host": "localhost",
"port": 9200,
"embedding_model_dims": 1536,
"custom_search_query": custom_search_query
}
}
}
```
It should be a function that takes the following parameters:
- `query`: a query vector used in `Memory.search`
- `limit`: a number of results used in `Memory.search`
- `filters`: a dictionary of key-value pairs used in `Memory.search`. You can add custom pairs for the custom search query.
The function should return a query body for the Elasticsearch search API.
@@ -1,72 +0,0 @@
[FAISS](https://github.com/facebookresearch/faiss) is a library for efficient similarity search and clustering of dense vectors. It is designed to work with large-scale datasets and provides a high-performance search engine for vector data. FAISS is optimized for memory usage and search speed, making it an excellent choice for production environments.
### Usage
```python
import os
from mem0 import Memory
os.environ["OPENAI_API_KEY"] = "sk-xx"
config = {
"vector_store": {
"provider": "faiss",
"config": {
"collection_name": "test",
"path": "/tmp/faiss_memories",
"distance_strategy": "euclidean"
}
}
}
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"})
```
### Installation
To use FAISS in your mem0 project, you need to install the appropriate FAISS package for your environment:
```bash
# For CPU version
pip install faiss-cpu
# For GPU version (requires CUDA)
pip install faiss-gpu
```
### Config
Here are the parameters available for configuring FAISS:
| Parameter | Description | Default Value |
| --- | --- | --- |
| `collection_name` | The name of the collection | `mem0` |
| `path` | Path to store FAISS index and metadata | `/tmp/faiss/<collection_name>` |
| `distance_strategy` | Distance metric strategy to use (options: 'euclidean', 'inner_product', 'cosine') | `euclidean` |
| `normalize_L2` | Whether to normalize L2 vectors (only applicable for euclidean distance) | `False` |
### Performance Considerations
FAISS offers several advantages for vector search:
1. **Efficiency**: FAISS is optimized for memory usage and speed, making it suitable for large-scale applications.
2. **Offline Support**: FAISS works entirely locally, with no need for external servers or API calls.
3. **Storage Options**: Vectors can be stored in-memory for maximum speed or persisted to disk.
4. **Multiple Index Types**: FAISS supports different index types optimized for various use cases (though mem0 currently uses the basic flat index).
### Distance Strategies
FAISS in mem0 supports three distance strategies:
- **euclidean**: L2 distance, suitable for most embedding models
- **inner_product**: Dot product similarity, useful for some specialized embeddings
- **cosine**: Cosine similarity, best for comparing semantic similarity regardless of vector magnitude
When using `cosine` or `inner_product` with normalized vectors, you may want to set `normalize_L2=True` for better results.
@@ -1,112 +0,0 @@
---
title: LangChain
---
Mem0 supports LangChain as a provider for vector store integration. LangChain provides a unified interface to various vector databases, making it easy to integrate different vector store providers through a consistent API.
<Note>
When using LangChain as your vector store provider, you must set the collection name to "mem0". This is a required configuration for proper integration with Mem0.
</Note>
## Usage
<CodeGroup>
```python Python
import os
from mem0 import Memory
from langchain_community.vectorstores import Chroma
from langchain_openai import OpenAIEmbeddings
# Initialize a LangChain vector store
embeddings = OpenAIEmbeddings()
vector_store = Chroma(
persist_directory="./chroma_db",
embedding_function=embeddings,
collection_name="mem0" # Required collection name
)
# Pass the initialized vector store to the config
config = {
"vector_store": {
"provider": "langchain",
"config": {
"client": vector_store
}
}
}
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"})
```
```typescript TypeScript
import { Memory } from "mem0ai";
import { OpenAIEmbeddings } from "@langchain/openai";
import { MemoryVectorStore as LangchainMemoryStore } from "langchain/vectorstores/memory";
const embeddings = new OpenAIEmbeddings();
const vectorStore = new LangchainVectorStore(embeddings);
const config = {
"vector_store": {
"provider": "langchain",
"config": { "client": vectorStore }
}
}
const memory = new Memory(config);
const 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." }
]
memory.add(messages, user_id="alice", metadata={"category": "movies"})
```
</CodeGroup>
## Supported LangChain Vector Stores
LangChain supports a wide range of vector store providers, including:
- Chroma
- FAISS
- Pinecone
- Weaviate
- Milvus
- Qdrant
- And many more
You can use any of these vector store instances directly in your configuration. For a complete and up-to-date list of available providers, refer to the [LangChain Vector Stores documentation](https://python.langchain.com/docs/integrations/vectorstores).
## Limitations
When using LangChain as a vector store provider, there are some limitations to be aware of:
1. **Bulk Operations**: The `get_all` and `delete_all` operations are not supported when using LangChain as the vector store provider. This is because LangChain's vector store interface doesn't provide standardized methods for these bulk operations across all providers.
2. **Provider-Specific Features**: Some advanced features may not be available depending on the specific vector store implementation you're using through LangChain.
## Provider-Specific Configuration
When using LangChain as a vector store provider, you'll need to:
1. Set the appropriate environment variables for your chosen vector store provider
2. Import and initialize the specific vector store class you want to use
3. Pass the initialized vector store instance to the config
<Note>
Make sure to install the necessary LangChain packages and any provider-specific dependencies.
</Note>
## Config
All available parameters for the `langchain` vector store config are present in [Master List of All Params in Config](../config).
@@ -1,43 +0,0 @@
[Milvus](https://milvus.io/) Milvus is an open-source vector database that suits AI applications of every size from running a demo chatbot in Jupyter notebook to building web-scale search that serves billions of users.
### Usage
```python
import os
from mem0 import Memory
config = {
"vector_store": {
"provider": "milvus",
"config": {
"collection_name": "test",
"embedding_model_dims": 1536",
"url": "127.0.0.1",
"token": "8e4b8ca8cf2c67",
"db_name": "my_database",
}
}
}
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"})
```
### Config
Here's the parameters available for configuring Milvus Database:
| Parameter | Description | Default Value |
| --- | --- | --- |
| `url` | Full URL/Uri for Milvus/Zilliz server | `http://localhost:19530` |
| `token` | Token for Zilliz server / for local setup defaults to None. | `None` |
| `collection_name` | The name of the collection | `mem0` |
| `embedding_model_dims` | Dimensions of the embedding model | `1536` |
| `metric_type` | Metric type for similarity search | `L2` |
| `db_name` | Name of the database | `""` |
@@ -1,45 +0,0 @@
# MongoDB
[MongoDB](https://www.mongodb.com/) is a versatile document database that supports vector search capabilities, allowing for efficient high-dimensional similarity searches over large datasets with robust scalability and performance.
## Usage
```python
import os
from mem0 import Memory
os.environ["OPENAI_API_KEY"] = "sk-xx"
config = {
"vector_store": {
"provider": "mongodb",
"config": {
"db_name": "mem0-db",
"collection_name": "mem0-collection",
"mongo_uri":"mongodb://username:password@localhost:27017"
}
}
}
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"})
```
## Config
Here are the parameters available for configuring MongoDB:
| Parameter | Description | Default Value |
| --- | --- | --- |
| db_name | Name of the MongoDB database | `"mem0_db"` |
| collection_name | Name of the MongoDB collection | `"mem0_collection"` |
| embedding_model_dims | Dimensions of the embedding vectors | `1536` |
| mongo_uri | The mongo URI connection string | mongodb://username:password@localhost:27017 |
> **Note**: If Mongo_uri is not provided it will default to mongodb://username:password@localhost:27017.
@@ -1,42 +0,0 @@
# Neptune Analytics Vector Store
[Neptune Analytics](https://docs.aws.amazon.com/neptune-analytics/latest/userguide/what-is-neptune-analytics.html/) is a memory-optimized graph database engine for analytics. With Neptune Analytics, you can get insights and find trends by processing large amounts of graph data in seconds, including vector search.
## Installation
```bash
pip install mem0ai[vector_stores]
```
## Usage
```python
config = {
"vector_store": {
"provider": "neptune",
"config": {
"collection_name": "mem0",
"endpoint": f"neptune-graph://my-graph-identifier",
},
},
}
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 `neptune` config:
| Parameter | Description | Default Value |
| --- | --- | --- |
| `collection_name` | The name of the collection to store the vectors | `mem0` |
| `endpoint` | Connection URL for the Neptune Analytics service | `neptune-graph://my-graph-identifier` |
@@ -1,81 +0,0 @@
[OpenSearch](https://opensearch.org/) is an enterprise-grade search and observability suite that brings order to unstructured data at scale. OpenSearch supports k-NN (k-Nearest Neighbors) and allows you to store and retrieve high-dimensional vector embeddings efficiently.
### Installation
OpenSearch support requires additional dependencies. Install them with:
```bash
pip install opensearch-py
```
### Prerequisites
Before using OpenSearch with Mem0, you need to set up a collection in AWS OpenSearch Service.
#### AWS OpenSearch Service
You can create a collection through the AWS Console:
- Navigate to [OpenSearch Service Console](https://console.aws.amazon.com/aos/home)
- Click "Create collection"
- Select "Serverless collection" and then enable "Vector search" capabilities
- Once created, note the endpoint URL (host) for your configuration
### Usage
```python
import os
from mem0 import Memory
import boto3
from opensearchpy import OpenSearch, RequestsHttpConnection, AWSV4SignerAuth
# For AWS OpenSearch Service with IAM authentication
region = 'us-west-2'
service = 'aoss'
credentials = boto3.Session().get_credentials()
auth = AWSV4SignerAuth(credentials, region, service)
config = {
"vector_store": {
"provider": "opensearch",
"config": {
"collection_name": "mem0",
"host": "your-domain.us-west-2.aoss.amazonaws.com",
"port": 443,
"http_auth": auth,
"embedding_model_dims": 1024,
"connection_class": RequestsHttpConnection,
"pool_maxsize": 20,
"use_ssl": True,
"verify_certs": True
}
}
}
```
### Add Memories
```python
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"})
```
### Search Memories
```python
results = m.search("What kind of movies does Alice like?", user_id="alice")
```
### Features
- Fast and Efficient Vector Search
- Can be deployed on-premises, in containers, or on cloud platforms like AWS OpenSearch Service.
- Multiple Authentication and Security Methods (Basic Authentication, API Keys, LDAP, SAML, and OpenID Connect)
- Automatic index creation with optimized mappings for vector search
- Memory Optimization through Disk-Based Vector Search and Quantization
- Real-Time Analytics and Observability
@@ -1,87 +0,0 @@
[pgvector](https://github.com/pgvector/pgvector) is open-source vector similarity search for Postgres. After connecting with postgres run `CREATE EXTENSION IF NOT EXISTS vector;` to create the vector extension.
### Usage
<CodeGroup>
```python Python
import os
from mem0 import Memory
os.environ["OPENAI_API_KEY"] = "sk-xx"
config = {
"vector_store": {
"provider": "pgvector",
"config": {
"user": "test",
"password": "123",
"host": "127.0.0.1",
"port": "5432",
}
}
}
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"})
```
```typescript TypeScript
import { Memory } from 'mem0ai/oss';
const config = {
vectorStore: {
provider: 'pgvector',
config: {
collectionName: 'memories',
embeddingModelDims: 1536,
user: 'test',
password: '123',
host: '127.0.0.1',
port: 5432,
dbname: 'vector_store', // Optional, defaults to 'postgres'
diskann: false, // Optional, requires pgvectorscale extension
hnsw: false, // Optional, for HNSW indexing
},
},
};
const memory = new Memory(config);
const 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."}
]
await memory.add(messages, { userId: "alice", metadata: { category: "movies" } });
```
</CodeGroup>
### Config
Here's the parameters available for configuring pgvector:
| Parameter | Description | Default Value |
| --- | --- | --- |
| `dbname` | The name of the database | `postgres` |
| `collection_name` | The name of the collection | `mem0` |
| `embedding_model_dims` | Dimensions of the embedding model | `1536` |
| `user` | User name to connect to the database | `None` |
| `password` | Password to connect to the database | `None` |
| `host` | The host where the Postgres server is running | `None` |
| `port` | The port where the Postgres server is running | `None` |
| `diskann` | Whether to use diskann for vector similarity search (requires pgvectorscale) | `True` |
| `hnsw` | Whether to use hnsw for vector similarity search | `False` |
| `sslmode` | SSL mode for PostgreSQL connection (e.g., 'require', 'prefer', 'disable') | `None` |
| `connection_string` | PostgreSQL connection string (overrides individual connection parameters) | `None` |
| `connection_pool` | psycopg2 connection pool object (overrides connection string and individual parameters) | `None` |
**Note**: The connection parameters have the following priority:
1. `connection_pool` (highest priority)
2. `connection_string`
3. Individual connection parameters (`user`, `password`, `host`, `port`, `sslmode`)
@@ -1,98 +0,0 @@
[Pinecone](https://www.pinecone.io/) is a fully managed vector database designed for machine learning applications, offering high performance vector search with low latency at scale. It's particularly well-suited for semantic search, recommendation systems, and other AI-powered applications.
> **New**: Pinecone integration now supports custom namespaces! Use the `namespace` parameter to logically separate data within the same index. This is especially useful for multi-tenant or multi-user applications.
> **Note**: Before configuring Pinecone, you need to select an embedding model (e.g., OpenAI, Cohere, or custom models) and ensure the `embedding_model_dims` in your config matches your chosen model's dimensions. For example, OpenAI's text-embedding-3-small uses 1536 dimensions.
### Usage
```python
import os
from mem0 import Memory
os.environ["OPENAI_API_KEY"] = "sk-xx"
os.environ["PINECONE_API_KEY"] = "your-api-key"
# Example using serverless configuration
config = {
"vector_store": {
"provider": "pinecone",
"config": {
"collection_name": "testing",
"embedding_model_dims": 1536, # Matches OpenAI's text-embedding-3-small
"namespace": "my-namespace", # Optional: specify a namespace for multi-tenancy
"serverless_config": {
"cloud": "aws", # Choose between 'aws' or 'gcp' or 'azure'
"region": "us-east-1"
},
"metric": "cosine"
}
}
}
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"})
```
### Config
Here are the parameters available for configuring Pinecone:
| Parameter | Description | Default Value |
| --- | --- | --- |
| `collection_name` | Name of the index/collection | Required |
| `embedding_model_dims` | Dimensions of the embedding model (must match your chosen embedding model) | Required |
| `client` | Existing Pinecone client instance | `None` |
| `api_key` | API key for Pinecone | Environment variable: `PINECONE_API_KEY` |
| `environment` | Pinecone environment | `None` |
| `serverless_config` | Configuration for serverless deployment (AWS or GCP or Azure) | `None` |
| `pod_config` | Configuration for pod-based deployment | `None` |
| `hybrid_search` | Whether to enable hybrid search | `False` |
| `metric` | Distance metric for vector similarity | `"cosine"` |
| `batch_size` | Batch size for operations | `100` |
| `namespace` | Namespace for the collection, useful for multi-tenancy. | `None` |
> **Important**: You must choose either `serverless_config` or `pod_config` for your deployment, but not both.
#### Serverless Config Example
```python
config = {
"vector_store": {
"provider": "pinecone",
"config": {
"collection_name": "memory_index",
"embedding_model_dims": 1536, # For OpenAI's text-embedding-3-small
"namespace": "my-namespace", # Optional: custom namespace
"serverless_config": {
"cloud": "aws", # or "gcp" or "azure"
"region": "us-east-1" # Choose appropriate region
}
}
}
}
```
#### Pod Config Example
```python
config = {
"vector_store": {
"provider": "pinecone",
"config": {
"collection_name": "memory_index",
"embedding_model_dims": 1536, # For OpenAI's text-embedding-ada-002
"namespace": "my-namespace", # Optional: custom namespace
"pod_config": {
"environment": "gcp-starter",
"replicas": 1,
"pod_type": "starter"
}
}
}
}
```
@@ -1,89 +0,0 @@
[Qdrant](https://qdrant.tech/) is an open-source vector search engine. It is designed to work with large-scale datasets and provides a high-performance search engine for vector data.
### Usage
<CodeGroup>
```python Python
import os
from mem0 import Memory
os.environ["OPENAI_API_KEY"] = "sk-xx"
config = {
"vector_store": {
"provider": "qdrant",
"config": {
"collection_name": "test",
"host": "localhost",
"port": 6333,
}
}
}
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"})
```
```typescript TypeScript
import { Memory } from 'mem0ai/oss';
const config = {
vectorStore: {
provider: 'qdrant',
config: {
collectionName: 'memories',
embeddingModelDims: 1536,
host: 'localhost',
port: 6333,
},
},
};
const memory = new Memory(config);
const 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."}
]
await memory.add(messages, { userId: "alice", metadata: { category: "movies" } });
```
</CodeGroup>
### Config
Let's see the available parameters for the `qdrant` config:
<Tabs>
<Tab title="Python">
| Parameter | Description | Default Value |
| --- | --- | --- |
| `collection_name` | The name of the collection to store the vectors | `mem0` |
| `embedding_model_dims` | Dimensions of the embedding model | `1536` |
| `client` | Custom client for qdrant | `None` |
| `host` | The host where the qdrant server is running | `None` |
| `port` | The port where the qdrant server is running | `None` |
| `path` | Path for the qdrant database | `/tmp/qdrant` |
| `url` | Full URL for the qdrant server | `None` |
| `api_key` | API key for the qdrant server | `None` |
| `on_disk` | For enabling persistent storage | `False` |
</Tab>
<Tab title="TypeScript">
| Parameter | Description | Default Value |
| --- | --- | --- |
| `collectionName` | The name of the collection to store the vectors | `mem0` |
| `embeddingModelDims` | Dimensions of the embedding model | `1536` |
| `host` | The host where the Qdrant server is running | `None` |
| `port` | The port where the Qdrant server is running | `None` |
| `path` | Path for the Qdrant database | `/tmp/qdrant` |
| `url` | Full URL for the Qdrant server | `None` |
| `apiKey` | API key for the Qdrant server | `None` |
| `onDisk` | For enabling persistent storage | `False` |
</Tab>
</Tabs>
@@ -1,92 +0,0 @@
[Redis](https://redis.io/) is a scalable, real-time database that can store, search, and analyze vector data.
### Installation
```bash
pip install redis redisvl
```
Redis Stack using Docker:
```bash
docker run -d --name redis-stack -p 6379:6379 -p 8001:8001 redis/redis-stack:latest
```
### Usage
<CodeGroup>
```python Python
import os
from mem0 import Memory
os.environ["OPENAI_API_KEY"] = "sk-xx"
config = {
"vector_store": {
"provider": "redis",
"config": {
"collection_name": "mem0",
"embedding_model_dims": 1536,
"redis_url": "redis://localhost:6379"
}
},
"version": "v1.1"
}
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"})
```
```typescript TypeScript
import { Memory } from 'mem0ai/oss';
const config = {
vectorStore: {
provider: 'redis',
config: {
collectionName: 'memories',
embeddingModelDims: 1536,
redisUrl: 'redis://localhost:6379',
username: 'your-redis-username',
password: 'your-redis-password',
},
},
};
const memory = new Memory(config);
const 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."}
]
await memory.add(messages, { userId: "alice", metadata: { category: "movies" } });
```
</CodeGroup>
### Config
Let's see the available parameters for the `redis` config:
<Tabs>
<Tab title="Python">
| Parameter | Description | Default Value |
| --- | --- | --- |
| `collection_name` | The name of the collection to store the vectors | `mem0` |
| `embedding_model_dims` | Dimensions of the embedding model | `1536` |
| `redis_url` | The URL of the Redis server | `None` |
</Tab>
<Tab title="TypeScript">
| Parameter | Description | Default Value |
| --- | --- | --- |
| `collectionName` | The name of the collection to store the vectors | `mem0` |
| `embeddingModelDims` | Dimensions of the embedding model | `1536` |
| `redisUrl` | The URL of the Redis server | `None` |
| `username` | Username for Redis connection | `None` |
| `password` | Password for Redis connection | `None` |
</Tab>
</Tabs>
@@ -1,78 +0,0 @@
---
title: Amazon S3 Vectors
---
[Amazon S3 Vectors](https://aws.amazon.com/s3/features/vectors/) is a purpose-built, cost-optimized vector storage and query service for semantic search and AI applications. It provides S3-level elasticity and durability with sub-second query performance.
### Installation
S3 Vectors support requires additional dependencies. Install them with:
```bash
pip install boto3
```
### Usage
To use Amazon S3 Vectors with Mem0, you need to have an AWS account and the necessary IAM permissions (`s3vectors:*`). Ensure your environment is configured with AWS credentials (e.g., via `~/.aws/credentials` or environment variables).
```python
import os
from mem0 import Memory
# Ensure your AWS credentials are configured in your environment
# e.g., by setting AWS_ACCESS_KEY_ID, AWS_SECRET_ACCESS_KEY, and AWS_DEFAULT_REGION
config = {
"vector_store": {
"provider": "s3_vectors",
"config": {
"vector_bucket_name": "my-mem0-vector-bucket",
"index_name": "my-memories-index",
"embedding_model_dims": 1536,
"distance_metric": "cosine",
"region_name": "us-east-1"
}
}
}
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 movie? 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"})
```
### Config
Here are the available parameters for the `s3_vectors` config:
| Parameter | Description | Default Value |
| ---------------------- | -------------------------------------------------------------------- | ------------- |
| `vector_bucket_name` | The name of the S3 Vector bucket to use. It will be created if it doesn't exist. | Required |
| `index_name` | The name of the vector index within the bucket. | `mem0` |
| `embedding_model_dims` | Dimensions of the embedding model. Must match your embedder. | `1536` |
| `distance_metric` | Distance metric for similarity search. Options: `cosine`, `euclidean`. | `cosine` |
| `region_name` | The AWS region where the bucket and index reside. | `None` (uses default from AWS config) |
### IAM Permissions
Your AWS identity (user or role) needs permissions to perform actions on S3 Vectors. A minimal policy would look like this:
```json
{
"Version": "2012-10-17",
"Statement": [
{
"Effect": "Allow",
"Action": "s3vectors:*",
"Resource": "*"
}
]
}
```
For production, it is recommended to scope down the resource ARN to your specific buckets and indexes.
@@ -1,170 +0,0 @@
[Supabase](https://supabase.com/) is an open-source Firebase alternative that provides a PostgreSQL database with pgvector extension for vector similarity search. It offers a powerful and scalable solution for storing and querying vector embeddings.
Create a [Supabase](https://supabase.com/dashboard/projects) account and project, then get your connection string from Project Settings > Database. See the [docs](https://supabase.github.io/vecs/hosting/) for details.
### Usage
<CodeGroup>
```python Python
import os
from mem0 import Memory
os.environ["OPENAI_API_KEY"] = "sk-xx"
config = {
"vector_store": {
"provider": "supabase",
"config": {
"connection_string": "postgresql://user:password@host:port/database",
"collection_name": "memories",
"index_method": "hnsw", # Optional: defaults to "auto"
"index_measure": "cosine_distance" # Optional: defaults to "cosine_distance"
}
}
}
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"})
```
```typescript Typescript
import { Memory } from "mem0ai/oss";
const config = {
vectorStore: {
provider: "supabase",
config: {
collectionName: "memories",
embeddingModelDims: 1536,
supabaseUrl: process.env.SUPABASE_URL || "",
supabaseKey: process.env.SUPABASE_KEY || "",
tableName: "memories",
},
},
}
const memory = new Memory(config);
const 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."}
]
await memory.add(messages, { userId: "alice", metadata: { category: "movies" } });
```
</CodeGroup>
### SQL Migrations for TypeScript Implementation
The following SQL migrations are required to enable the vector extension and create the memories table:
```sql
-- Enable the vector extension
create extension if not exists vector;
-- Create the memories table
create table if not exists memories (
id text primary key,
embedding vector(1536),
metadata jsonb,
created_at timestamp with time zone default timezone('utc', now()),
updated_at timestamp with time zone default timezone('utc', now())
);
-- Create the vector similarity search function
create or replace function match_vectors(
query_embedding vector(1536),
match_count int,
filter jsonb default '{}'::jsonb
)
returns table (
id text,
similarity float,
metadata jsonb
)
language plpgsql
as $$
begin
return query
select
t.id::text,
1 - (t.embedding <=> query_embedding) as similarity,
t.metadata
from memories t
where case
when filter::text = '{}'::text then true
else t.metadata @> filter
end
order by t.embedding <=> query_embedding
limit match_count;
end;
$$;
```
Goto [Supabase](https://supabase.com/dashboard/projects) and run the above SQL migrations inside the SQL Editor.
### Config
Here are the parameters available for configuring Supabase:
<Tabs>
<Tab title="Python">
| Parameter | Description | Default Value |
| --- | --- | --- |
| `connection_string` | PostgreSQL connection string (required) | None |
| `collection_name` | Name for the vector collection | `mem0` |
| `embedding_model_dims` | Dimensions of the embedding model | `1536` |
| `index_method` | Vector index method to use | `auto` |
| `index_measure` | Distance measure for similarity search | `cosine_distance` |
</Tab>
<Tab title="TypeScript">
| Parameter | Description | Default Value |
| --- | --- | --- |
| `collectionName` | Name for the vector collection | `mem0` |
| `embeddingModelDims` | Dimensions of the embedding model | `1536` |
| `supabaseUrl` | Supabase URL | None |
| `supabaseKey` | Supabase key | None |
| `tableName` | Name for the vector table | `memories` |
</Tab>
</Tabs>
### Index Methods
The following index methods are supported:
- `auto`: Automatically selects the best available index method
- `hnsw`: Hierarchical Navigable Small World graph index (faster search, more memory usage)
- `ivfflat`: Inverted File Flat index (good balance of speed and memory)
### Distance Measures
Available distance measures for similarity search:
- `cosine_distance`: Cosine similarity (recommended for most embedding models)
- `l2_distance`: Euclidean distance
- `l1_distance`: Manhattan distance
- `max_inner_product`: Maximum inner product similarity
### Best Practices
1. **Index Method Selection**:
- Use `hnsw` for fastest search performance when memory is not a constraint
- Use `ivfflat` for a good balance of search speed and memory usage
- Use `auto` if unsure, it will select the best method based on your data
2. **Distance Measure Selection**:
- Use `cosine_distance` for most embedding models (OpenAI, Hugging Face, etc.)
- Use `max_inner_product` if your vectors are normalized
- Use `l2_distance` or `l1_distance` if working with raw feature vectors
3. **Connection String**:
- Always use environment variables for sensitive information in the connection string
- Format: `postgresql://user:password@host:port/database`
@@ -1,70 +0,0 @@
[Upstash Vector](https://upstash.com/docs/vector) is a serverless vector database with built-in embedding models.
### Usage with Upstash embeddings
You can enable the built-in embedding models by setting `enable_embeddings` to `True`. This allows you to use Upstash's embedding models for vectorization.
```python
import os
from mem0 import Memory
os.environ["UPSTASH_VECTOR_REST_URL"] = "..."
os.environ["UPSTASH_VECTOR_REST_TOKEN"] = "..."
config = {
"vector_store": {
"provider": "upstash_vector",
"enable_embeddings": True,
}
}
m = Memory.from_config(config)
m.add("Likes to play cricket on weekends", user_id="alice", metadata={"category": "hobbies"})
```
<Note>
Setting `enable_embeddings` to `True` will bypass any external embedding provider you have configured.
</Note>
### Usage with external embedding providers
```python
import os
from mem0 import Memory
os.environ["OPENAI_API_KEY"] = "..."
os.environ["UPSTASH_VECTOR_REST_URL"] = "..."
os.environ["UPSTASH_VECTOR_REST_TOKEN"] = "..."
config = {
"vector_store": {
"provider": "upstash_vector",
},
"embedder": {
"provider": "openai",
"config": {
"model": "text-embedding-3-large"
},
}
}
m = Memory.from_config(config)
m.add("Likes to play cricket on weekends", user_id="alice", metadata={"category": "hobbies"})
```
### Config
Here are the parameters available for configuring Upstash Vector:
| Parameter | Description | Default Value |
| ------------------- | ---------------------------------- | ------------- |
| `url` | URL for the Upstash Vector index | `None` |
| `token` | Token for the Upstash Vector index | `None` |
| `client` | An `upstash_vector.Index` instance | `None` |
| `collection_name` | The default namespace used | `""` |
| `enable_embeddings` | Whether to use Upstash embeddings | `False` |
<Note>
When `url` and `token` are not provided, the `UPSTASH_VECTOR_REST_URL` and
`UPSTASH_VECTOR_REST_TOKEN` environment variables are used.
</Note>
@@ -1,49 +0,0 @@
# 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` |
@@ -1,45 +0,0 @@
[Cloudflare Vectorize](https://developers.cloudflare.com/vectorize/) is a vector database offering from Cloudflare, allowing you to build AI-powered applications with vector embeddings.
### Usage
<CodeGroup>
```typescript TypeScript
import { Memory } from 'mem0ai/oss';
const config = {
vectorStore: {
provider: 'vectorize',
config: {
indexName: 'my-memory-index',
accountId: 'your-cloudflare-account-id',
apiKey: 'your-cloudflare-api-key',
dimension: 1536, // Optional: defaults to 1536
},
},
};
const memory = new Memory(config);
const messages = [
{"role": "user", "content": "I'm looking for a good book to read."},
{"role": "assistant", "content": "Sure, what genre are you interested in?"},
{"role": "user", "content": "I enjoy fantasy novels with strong world-building."},
{"role": "assistant", "content": "Great! I'll keep that in mind for future recommendations."}
]
await memory.add(messages, { userId: "bob", metadata: { interest: "books" } });
```
</CodeGroup>
### Config
Let's see the available parameters for the `vectorize` config:
<Tabs>
<Tab title="TypeScript">
| Parameter | Description | Default Value |
| --- | --- | --- |
| `indexName` | The name of the Vectorize index | `None` (Required) |
| `accountId` | Your Cloudflare account ID | `None` (Required) |
| `apiKey` | Your Cloudflare API token | `None` (Required) |
| `dimension` | Dimensions of the embedding model | `1536` |
</Tab>
</Tabs>
@@ -1,48 +0,0 @@
---
title: Vertex AI Vector Search
---
### Usage
To use Google Cloud Vertex AI Vector Search with `mem0`, you need to configure the `vector_store` in your `mem0` config:
```python
import os
from mem0 import Memory
os.environ["GOOGLE_API_KEY"] = "sk-xx"
config = {
"vector_store": {
"provider": "vertex_ai_vector_search",
"config": {
"endpoint_id": "YOUR_ENDPOINT_ID", # Required: Vector Search endpoint ID
"index_id": "YOUR_INDEX_ID", # Required: Vector Search index ID
"deployment_index_id": "YOUR_DEPLOYMENT_INDEX_ID", # Required: Deployment-specific ID
"project_id": "YOUR_PROJECT_ID", # Required: Google Cloud project ID
"project_number": "YOUR_PROJECT_NUMBER", # Required: Google Cloud project number
"region": "YOUR_REGION", # Optional: Defaults to GOOGLE_CLOUD_REGION
"credentials_path": "path/to/credentials.json", # Optional: Defaults to GOOGLE_APPLICATION_CREDENTIALS
"vector_search_api_endpoint": "YOUR_API_ENDPOINT" # Required for get operations
}
}
}
m = Memory.from_config(config)
m.add("Your text here", user_id="user", metadata={"category": "example"})
```
### Required Parameters
| Parameter | Description | Required |
|-----------|-------------|----------|
| `endpoint_id` | Vector Search endpoint ID | Yes |
| `index_id` | Vector Search index ID | Yes |
| `deployment_index_id` | Deployment-specific index ID | Yes |
| `project_id` | Google Cloud project ID | Yes |
| `project_number` | Google Cloud project number | Yes |
| `vector_search_api_endpoint` | Vector search API endpoint | Yes (for get operations) |
| `region` | Google Cloud region | No (defaults to GOOGLE_CLOUD_REGION) |
| `credentials_path` | Path to service account credentials | No (defaults to GOOGLE_APPLICATION_CREDENTIALS) |
@@ -1,47 +0,0 @@
[Weaviate](https://weaviate.io/) is an open-source vector search engine. It allows efficient storage and retrieval of high-dimensional vector embeddings, enabling powerful search and retrieval capabilities.
### Installation
```bash
pip install weaviate weaviate-client
```
### Usage
```python Python
import os
from mem0 import Memory
os.environ["OPENAI_API_KEY"] = "sk-xx"
config = {
"vector_store": {
"provider": "weaviate",
"config": {
"collection_name": "test",
"cluster_url": "http://localhost:8080",
"auth_client_secret": None,
}
}
}
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 movie? 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"})
```
### Config
Let's see the available parameters for the `weaviate` config:
| Parameter | Description | Default Value |
| --- | --- | --- |
| `collection_name` | The name of the collection to store the vectors | `mem0` |
| `embedding_model_dims` | Dimensions of the embedding model | `1536` |
| `cluster_url` | URL for the Weaviate server | `None` |
| `auth_client_secret` | API key for Weaviate authentication | `None` |
@@ -1,55 +0,0 @@
---
title: Overview
icon: "info"
iconType: "solid"
---
Mem0 includes built-in support for various popular databases. Memory can utilize the database provided by the user, ensuring efficient use for specific needs.
## Supported Vector Databases
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, Valkey, Vectorize and in-memory vector database.
</Note>
<CardGroup cols={3}>
<Card title="Qdrant" href="/components/vectordbs/dbs/qdrant"></Card>
<Card title="Chroma" href="/components/vectordbs/dbs/chroma"></Card>
<Card title="Pgvector" href="/components/vectordbs/dbs/pgvector"></Card>
<Card title="Upstash Vector" href="/components/vectordbs/dbs/upstash-vector"></Card>
<Card title="Milvus" href="/components/vectordbs/dbs/milvus"></Card>
<Card title="Pinecone" href="/components/vectordbs/dbs/pinecone"></Card>
<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>
<Card title="Vertex AI" href="/components/vectordbs/dbs/vertex_ai"></Card>
<Card title="Weaviate" href="/components/vectordbs/dbs/weaviate"></Card>
<Card title="FAISS" href="/components/vectordbs/dbs/faiss"></Card>
<Card title="LangChain" href="/components/vectordbs/dbs/langchain"></Card>
<Card title="Amazon S3 Vectors" href="/components/vectordbs/dbs/s3_vectors"></Card>
<Card title="Databricks" href="/components/vectordbs/dbs/databricks"></Card>
</CardGroup>
## Usage
To utilize a vector database, you must provide a configuration to customize its usage. If no configuration is supplied, a default configuration will be applied, and `Qdrant` will be used as the vector database.
For a comprehensive list of available parameters for vector database configuration, please refer to [Config](./config).
## Common issues
### Using model with different dimensions
If you are using customized model, which is having different dimensions other than 1536
for example 768, you may encounter below error:
`ValueError: shapes (0,1536) and (768,) not aligned: 1536 (dim 1) != 768 (dim 0)`
you could add `"embedding_model_dims": 768,` to the config of the vector_store to overcome this issue.
@@ -1,153 +0,0 @@
---
title: Add Memory
description: Add memory into the Mem0 platform by storing user-assistant interactions and facts for later retrieval.
icon: "plus"
iconType: "solid"
---
## Overview
The `add` operation is how you store memory into Mem0. Whether you're working with a chatbot, a voice assistant, or a multi-agent system, this is the entry point to create long-term memory.
Memories typically come from a **user-assistant interaction** and Mem0 handles the extraction, transformation, and storage for you.
Mem0 offers two implementation flows:
- **Mem0 Platform** (Managed, scalable, with dashboard + API)
- **Mem0 Open Source** (Lightweight, fully local, flexible SDKs)
Each supports the same core memory operations, but with slightly different setup. Below, we walk through examples for both.
## Architecture
<Frame caption="Architecture diagram illustrating the process of adding memories.">
<img src="../../images/add_architecture.png" />
</Frame>
When you call `add`, Mem0 performs the following steps under the hood:
1. **Information Extraction**
The input messages are passed through an LLM that extracts key facts, decisions, preferences, or events worth remembering.
2. **Conflict Resolution**
Mem0 compares the new memory against existing ones to detect duplication or contradiction and handles updates accordingly.
3. **Memory Storage**
The result is stored in a vector database (for semantic search) and optionally in a graph structure (for relationship mapping).
You don’t need to handle any of this manually, Mem0 takes care of it with a single API call or SDK method.
---
## Example: Mem0 Platform
<CodeGroup>
```python Python
from mem0 import MemoryClient
client = MemoryClient(api_key="your-api-key")
messages = [
{"role": "user", "content": "I'm planning a trip to Tokyo next month."},
{"role": "assistant", "content": "Great! I’ll remember that for future suggestions."}
]
client.add(
messages=messages,
user_id="alice",
version="v2"
)
```
```javascript JavaScript
import { MemoryClient } from "mem0ai";
const client = new MemoryClient({apiKey: "your-api-key"});
const messages = [
{ role: "user", content: "I'm planning a trip to Tokyo next month." },
{ role: "assistant", content: "Great! I’ll remember that for future suggestions." }
];
await client.add({
messages,
user_id: "alice",
version: "v2"
});
```
</CodeGroup>
---
## Example: Mem0 Open Source
<CodeGroup>
```python Python
import os
from mem0 import Memory
os.environ["OPENAI_API_KEY"] = "your-api-key"
m = Memory()
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."}
]
# Store inferred memories (default behavior)
result = m.add(messages, user_id="alice", metadata={"category": "movie_recommendations"})
# Optionally store raw messages without inference
result = m.add(messages, user_id="alice", metadata={"category": "movie_recommendations"}, infer=False)
```
```javascript JavaScript
import { Memory } from 'mem0ai/oss';
const memory = new Memory();
const messages = [
{
role: "user",
content: "I like to drink coffee in the morning and go for a walk"
}
];
const result = memory.add(messages, {
userId: "alice",
metadata: { category: "preferences" }
});
```
</CodeGroup>
---
## When Should You Add Memory?
Add memory whenever your agent learns something useful:
- A new user preference is shared
- A decision or suggestion is made
- A goal or task is completed
- A new entity is introduced
- A user gives feedback or clarification
Storing this context allows the agent to reason better in future interactions.
### More Details
For full list of supported fields, required formats, and advanced options, see the
[Add Memory API Reference](/api-reference/memory/add-memories).
---
## Need help?
If you have any questions, please feel free to reach out to us using one of the following methods:
<Snippet file="get-help.mdx"/>
@@ -1,141 +0,0 @@
---
title: Delete Memory
description: Remove memories from Mem0 either individually, in bulk, or via filters.
icon: "trash"
iconType: "solid"
---
## Overview
Memories can become outdated, irrelevant, or need to be removed for privacy or compliance reasons. Mem0 offers flexible ways to delete memory:
1. **Delete a Single Memory**: Using a specific memory ID
2. **Batch Delete**: Delete multiple known memory IDs (up to 1000)
3. **Filtered Delete**: Delete memories matching a filter (e.g., `user_id`, `metadata`, `run_id`)
This page walks through code example for each method.
## Use Cases
- Forget a user’s past preferences by request
- Remove outdated or incorrect memory entries
- Clean up memory after session expiration
- Comply with data deletion requests (e.g., GDPR)
---
## 1. Delete a Single Memory by ID
<CodeGroup>
```python Python
from mem0 import MemoryClient
client = MemoryClient(api_key="your-api-key")
memory_id = "your_memory_id"
client.delete(memory_id=memory_id)
```
```javascript JavaScript
import MemoryClient from 'mem0ai';
const client = new MemoryClient({ apiKey: "your-api-key" });
client.delete("your_memory_id")
.then(result => console.log(result))
.catch(error => console.error(error));
```
</CodeGroup>
---
## 2. Batch Delete Multiple Memories
<CodeGroup>
```python Python
from mem0 import MemoryClient
client = MemoryClient(api_key="your-api-key")
delete_memories = [
{"memory_id": "id1"},
{"memory_id": "id2"}
]
response = client.batch_delete(delete_memories)
print(response)
```
```javascript JavaScript
import MemoryClient from 'mem0ai';
const client = new MemoryClient({ apiKey: "your-api-key" });
const deleteMemories = [
{ memory_id: "id1" },
{ memory_id: "id2" }
];
client.batchDelete(deleteMemories)
.then(response => console.log('Batch delete response:', response))
.catch(error => console.error(error));
```
</CodeGroup>
---
## 3. Delete Memories by Filter (e.g., user_id)
<CodeGroup>
```python Python
from mem0 import MemoryClient
client = MemoryClient(api_key="your-api-key")
# Delete all memories for a specific user
client.delete_all(user_id="alice")
```
```javascript JavaScript
import MemoryClient from 'mem0ai';
const client = new MemoryClient({ apiKey: "your-api-key" });
client.deleteAll({ user_id: "alice" })
.then(result => console.log(result))
.catch(error => console.error(error));
```
</CodeGroup>
You can also filter by other parameters such as:
- `agent_id`
- `run_id`
- `metadata` (as JSON string)
---
## Key Differences
| Method | Use When | IDs Needed | Filters |
|----------------------|-------------------------------------------|------------|----------|
| `delete(memory_id)` | You know exactly which memory to remove | ✔ | ✘ |
| `batch_delete([...])`| You have a known list of memory IDs | ✔ | ✘ |
| `delete_all(...)` | You want to delete by user/agent/run/etc | ✘ | ✔ |
### More Details
For request/response schema and additional filtering options, see:
- [Delete Memory API Reference](/api-reference/memory/delete-memory)
- [Batch Delete API Reference](/api-reference/memory/batch-delete)
- [Delete Memories by Filter Reference](/api-reference/memory/delete-memories)
You’ve now seen how to add, search, update, and delete memories in Mem0.
---
## Need help?
If you have any questions, please feel free to reach out to us using one of the following methods:
<Snippet file="get-help.mdx"/>
@@ -1,124 +0,0 @@
---
title: Search Memory
description: Retrieve relevant memories from Mem0 using powerful semantic and filtered search capabilities.
icon: "magnifying-glass"
iconType: "solid"
---
## Overview
The `search` operation allows you to retrieve relevant memories based on a natural language query and optional filters like user ID, agent ID, categories, and more. This is the foundation of giving your agents memory-aware behavior.
Mem0 supports:
- Semantic similarity search
- Metadata filtering (with advanced logic)
- Reranking and thresholds
- Cross-agent, multi-session context resolution
This applies to both:
- **Mem0 Platform** (hosted API with full-scale features)
- **Mem0 Open Source** (local-first with LLM inference and local vector DB)
## Architecture
<Frame caption="Architecture diagram illustrating the memory search process.">
<img src="../../images/search_architecture.png" />
</Frame>
The search flow follows these steps:
1. **Query Processing**
An LLM refines and optimizes your natural language query.
2. **Vector Search**
Semantic embeddings are used to find the most relevant memories using cosine similarity.
3. **Filtering & Ranking**
Logical and comparison-based filters are applied. Memories are scored, filtered, and optionally reranked.
4. **Results Delivery**
Relevant memories are returned with associated metadata and timestamps.
---
## Example: Mem0 Platform
<CodeGroup>
```python Python
from mem0 import MemoryClient
client = MemoryClient(api_key="your-api-key")
query = "What do you know about me?"
filters = {
"OR": [
{"user_id": "alice"},
{"agent_id": {"in": ["travel-assistant", "customer-support"]}}
]
}
results = client.search(query, version="v2", filters=filters)
```
```javascript JavaScript
import { MemoryClient } from "mem0ai";
const client = new MemoryClient({apiKey: "your-api-key"});
const query = "I'm craving some pizza. Any recommendations?";
const filters = {
AND: [
{ user_id: "alice" }
]
};
const results = await client.search(query, {
version: "v2",
filters
});
```
</CodeGroup>
---
## Example: Mem0 Open Source
<CodeGroup>
```python Python
from mem0 import Memory
m = Memory()
related_memories = m.search("Should I drink coffee or tea?", user_id="alice")
```
```javascript JavaScript
import { Memory } from 'mem0ai/oss';
const memory = new Memory();
const relatedMemories = memory.search("Should I drink coffee or tea?", { userId: "alice" });
```
</CodeGroup>
---
## Tips for Better Search
- Use descriptive natural queries (Mem0 can interpret intent)
- Apply filters for scoped, faster lookup
- Use `version: "v2"` for enhanced results
- Consider wildcard filters (e.g., `run_id: "*"`) for broader matches
- Tune with `top_k`, `threshold`, or `rerank` if needed
### More Details
For the full list of filter logic, comparison operators, and optional search parameters, see the
[Search Memory API Reference](/api-reference/memory/v2-search-memories).
---
## Need help?
If you have any questions, please feel free to reach out to us using one of the following methods:
<Snippet file="get-help.mdx"/>
@@ -1,117 +0,0 @@
---
title: Update Memory
description: Modify an existing memory by updating its content or metadata.
icon: "pencil"
iconType: "solid"
---
## Overview
User preferences, interests, and behaviors often evolve over time. The `update` operation lets you revise a stored memory, whether it's updating facts and memories, rephrasing a message, or enriching metadata.
Mem0 supports both:
- **Single Memory Update** for one specific memory using its ID
- **Batch Update** for updating many memories at once (up to 1000)
This guide includes usage for both single update and batch update of memories through **Mem0 Platform**
## Use Cases
- Refine a vague or incorrect memory after a correction
- Add or edit memory with new metadata (e.g., categories, tags)
- Evolve factual knowledge as the user’s profile changes
- A user profile evolves: “I love spicy food” → later says “Actually, I can’t handle spicy food.”
Updating memory ensures your agents remain accurate, adaptive, and personalized.
---
## Update Memory
<CodeGroup>
```python Python
from mem0 import MemoryClient
client = MemoryClient(api_key="your-api-key")
memory_id = "your_memory_id"
client.update(
memory_id=memory_id,
text="Updated memory content about the user",
metadata={"category": "profile-update"}
)
```
```javascript JavaScript
import MemoryClient from 'mem0ai';
const client = new MemoryClient({ apiKey: "your-api-key" });
const memory_id = "your_memory_id";
client.update(memory_id, {
text: "Updated memory content about the user",
metadata: { category: "profile-update" }
})
.then(result => console.log(result))
.catch(error => console.error(error));
```
</CodeGroup>
---
## Batch Update
Update up to 1000 memories in one call.
<CodeGroup>
```python Python
from mem0 import MemoryClient
client = MemoryClient(api_key="your-api-key")
update_memories = [
{"memory_id": "id1", "text": "Watches football"},
{"memory_id": "id2", "text": "Likes to travel"}
]
response = client.batch_update(update_memories)
print(response)
```
```javascript JavaScript
import MemoryClient from 'mem0ai';
const client = new MemoryClient({ apiKey: "your-api-key" });
const updateMemories = [
{ memoryId: "id1", text: "Watches football" },
{ memoryId: "id2", text: "Likes to travel" }
];
client.batchUpdate(updateMemories)
.then(response => console.log('Batch update response:', response))
.catch(error => console.error(error));
```
</CodeGroup>
---
## Tips
- You can update both `text` and `metadata` in the same call.
- Use `batchUpdate` when you're applying similar corrections at scale.
- If memory is marked `immutable`, it must first be deleted and re-added.
- Combine this with feedback mechanisms (e.g., user thumbs-up/down) to self-improve memory.
### More Details
Refer to the full [Update Memory API Reference](/api-reference/memory/update-memory) and [Batch Update Reference](/api-reference/memory/batch-update) for schema and advanced fields.
---
## Need help?
If you have any questions, please feel free to reach out to us using one of the following methods:
<Snippet file="get-help.mdx"/>
-49
View File
@@ -1,49 +0,0 @@
---
title: Memory Types
description: Understanding different types of memory in AI Applications
icon: "memory"
iconType: "solid"
---
To build useful AI applications, we need to understand how different memory systems work together. This guide explores the fundamental types of memory in AI systems and shows how Mem0 implements these concepts.
## Why Memory Matters
AI systems need memory for three key purposes:
1. Maintaining context during conversations
2. Learning from past interactions
3. Building personalized experiences over time
Without proper memory systems, AI applications would treat each interaction as completely new, losing valuable context and personalization opportunities.
## Short-Term Memory
The most basic form of memory in AI systems holds immediate context - like a person remembering what was just said in a conversation. This includes:
- **Conversation History**: Recent messages and their order
- **Working Memory**: Temporary variables and state
- **Attention Context**: Current focus of the conversation
## Long-Term Memory
More sophisticated AI applications implement long-term memory to retain information across conversations. This includes:
- **Factual Memory**: Stored knowledge about users, preferences, and domain-specific information
- **Episodic Memory**: Past interactions and experiences
- **Semantic Memory**: Understanding of concepts and their relationships
## Memory Characteristics
Each memory type has distinct characteristics:
| Type | Persistence | Access Speed | Use Case |
|------|-------------|--------------|-----------|
| Short-Term | Temporary | Instant | Active conversations |
| Long-Term | Persistent | Fast | User preferences and history |
## How Mem0 Implements Long-Term Memory
Mem0's long-term memory system builds on these foundations by:
1. Using vector embeddings to store and retrieve semantic information
2. Maintaining user-specific context across sessions
3. Implementing efficient retrieval mechanisms for relevant past interactions
-126
View File
@@ -1,126 +0,0 @@
---
title: AI Companion in Node.js
---
You can create a personalised AI Companion using Mem0. This guide will walk you through the necessary steps and provide the complete code to get you started.
## Overview
The Personalized AI Companion leverages Mem0 to retain information across interactions, enabling a tailored learning experience. It creates memories for each user interaction and integrates with OpenAI's GPT models to provide detailed and context-aware responses to user queries.
## Setup
Before you begin, ensure you have Node.js installed and create a new project. Install the required dependencies using npm:
```bash
npm install openai mem0ai
```
## Full Code Example
Below is the complete code to create and interact with an AI Companion using Mem0:
```javascript
import { OpenAI } from 'openai';
import { Memory } from 'mem0ai/oss';
import * as readline from 'readline';
const openaiClient = new OpenAI();
const memory = new Memory();
async function chatWithMemories(message, userId = "default_user") {
const relevantMemories = await memory.search(message, { userId: userId });
const memoriesStr = relevantMemories.results
.map(entry => `- ${entry.memory}`)
.join('\n');
const systemPrompt = `You are a helpful AI. Answer the question based on query and memories.
User Memories:
${memoriesStr}`;
const messages = [
{ role: "system", content: systemPrompt },
{ role: "user", content: message }
];
const response = await openaiClient.chat.completions.create({
model: "gpt-4.1-nano-2025-04-14",
messages: messages
});
const assistantResponse = response.choices[0].message.content || "";
messages.push({ role: "assistant", content: assistantResponse });
await memory.add(messages, { userId: userId });
return assistantResponse;
}
async function main() {
const rl = readline.createInterface({
input: process.stdin,
output: process.stdout
});
console.log("Chat with AI (type 'exit' to quit)");
const askQuestion = () => {
return new Promise((resolve) => {
rl.question("You: ", (input) => {
resolve(input.trim());
});
});
};
try {
while (true) {
const userInput = await askQuestion();
if (userInput.toLowerCase() === 'exit') {
console.log("Goodbye!");
rl.close();
break;
}
const response = await chatWithMemories(userInput, "sample_user");
console.log(`AI: ${response}`);
}
} catch (error) {
console.error("An error occurred:", error);
rl.close();
}
}
main().catch(console.error);
```
### Key Components
1. **Initialization**
- The code initializes both OpenAI and Mem0 Memory clients
- Uses Node.js's built-in readline module for command-line interaction
2. **Memory Management (chatWithMemories function)**
- Retrieves relevant memories using Mem0's search functionality
- Constructs a system prompt that includes past memories
- Makes API calls to OpenAI for generating responses
- Stores new interactions in memory
3. **Interactive Chat Interface (main function)**
- Creates a command-line interface for user interaction
- Handles user input and displays AI responses
- Includes graceful exit functionality
### Environment Setup
Make sure to set up your environment variables:
```bash
export OPENAI_API_KEY=your_api_key
```
### Conclusion
This implementation demonstrates how to create an AI Companion that maintains context across conversations using Mem0's memory capabilities. The system automatically stores and retrieves relevant information, creating a more personalized and context-aware interaction experience.
As users interact with the system, Mem0's memory system continuously learns and adapts, making future responses more relevant and personalized. This setup is ideal for creating long-term learning AI assistants that can maintain context and provide increasingly personalized responses over time.
-130
View File
@@ -1,130 +0,0 @@
---
title: "AWS Bedrock Example"
---
This example demonstrates how to configure and use the `mem0ai` SDK with **AWS Bedrock**, **OpenSearch Service (AOSS)**, and **AWS Neptune Analytics** for persistent memory capabilities in Python.
## Installation
Install the required dependencies to include the Amazon data stack, including **boto3**, **opensearch-py**, and **langchain-aws**:
```bash
pip install "mem0ai[graph,extras]"
```
## Environment Setup
Set your AWS environment variables:
```python
import os
# Set these in your environment or notebook
os.environ['AWS_REGION'] = 'us-west-2'
os.environ['AWS_ACCESS_KEY_ID'] = 'AK00000000000000000'
os.environ['AWS_SECRET_ACCESS_KEY'] = 'AS00000000000000000'
# Confirm they are set
print(os.environ['AWS_REGION'])
print(os.environ['AWS_ACCESS_KEY_ID'])
print(os.environ['AWS_SECRET_ACCESS_KEY'])
```
## Configuration and Usage
This sets up Mem0 with:
- [AWS Bedrock for LLM](https://docs.mem0.ai/components/llms/models/aws_bedrock)
- [AWS Bedrock for embeddings](https://docs.mem0.ai/components/embedders/models/aws_bedrock#aws-bedrock)
- [OpenSearch as the vector store](https://docs.mem0.ai/components/vectordbs/dbs/opensearch)
- [Graph Memory guide](https://docs.mem0.ai/open-source/features/graph-memory).
```python
import boto3
from opensearchpy import RequestsHttpConnection, AWSV4SignerAuth
from mem0.memory.main import Memory
region = 'us-west-2'
service = 'aoss'
credentials = boto3.Session().get_credentials()
auth = AWSV4SignerAuth(credentials, region, service)
config = {
"embedder": {
"provider": "aws_bedrock",
"config": {
"model": "amazon.titan-embed-text-v2:0"
}
},
"llm": {
"provider": "aws_bedrock",
"config": {
"model": "us.anthropic.claude-3-7-sonnet-20250219-v1:0",
"temperature": 0.1,
"max_tokens": 2000
}
},
"vector_store": {
"provider": "opensearch",
"config": {
"collection_name": "mem0",
"host": "your-opensearch-domain.us-west-2.es.amazonaws.com",
"port": 443,
"http_auth": auth,
"connection_class": RequestsHttpConnection,
"pool_maxsize": 20,
"use_ssl": True,
"verify_certs": True,
"embedding_model_dims": 1024,
}
},
"graph_store": {
"provider": "neptune",
"config": {
"endpoint": f"neptune-graph://my-graph-identifier",
},
},
}
# Initialize the memory system
m = Memory.from_config(config)
```
## Usage
Reference [Notebook example](https://github.com/mem0ai/mem0/blob/main/examples/graph-db-demo/neptune-example.ipynb)
#### Add a memory:
```python
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."}
]
# Store inferred memories (default behavior)
result = m.add(messages, user_id="alice", metadata={"category": "movie_recommendations"})
```
#### Search a memory:
```python
relevant_memories = m.search(query, user_id="alice")
```
#### Get all memories:
```python
all_memories = m.get_all(user_id="alice")
```
#### Get a specific memory:
```python
memory = m.get(memory_id)
```
---
## Conclusion
With Mem0 and AWS services like Bedrock, OpenSearch, and Neptune Analytics, you can build intelligent AI companions that remember, adapt, and personalize their responses over time. This makes them ideal for long-term assistants, tutors, or support bots with persistent memory and natural conversation abilities.
@@ -1,120 +0,0 @@
---
title: "AWS Neptune Analytics"
---
This example demonstrates how to configure and use the `mem0ai` SDK with **AWS Bedrock** and **AWS Neptune Analytics** for persistent memory capabilities in Python.
## Installation
Install the required dependencies to include the Amazon data stack, including **boto3** and **langchain-aws**:
```bash
pip install "mem0ai[graph,extras]"
```
## Environment Setup
Set your AWS environment variables:
```python
import os
# Set these in your environment or notebook
os.environ['AWS_REGION'] = 'us-west-2'
os.environ['AWS_ACCESS_KEY_ID'] = 'AK00000000000000000'
os.environ['AWS_SECRET_ACCESS_KEY'] = 'AS00000000000000000'
# Confirm they are set
print(os.environ['AWS_REGION'])
print(os.environ['AWS_ACCESS_KEY_ID'])
print(os.environ['AWS_SECRET_ACCESS_KEY'])
```
## Configuration and Usage
This sets up Mem0 with:
- [AWS Bedrock for LLM](https://docs.mem0.ai/components/llms/models/aws_bedrock)
- [AWS Bedrock for embeddings](https://docs.mem0.ai/components/embedders/models/aws_bedrock#aws-bedrock)
- [Neptune Analytics as the vector store](https://docs.mem0.ai/components/vectordbs/dbs/neptune_analytics)
- [Graph Memory guide](https://docs.mem0.ai/open-source/features/graph-memory).
```python
import boto3
from mem0.memory.main import Memory
region = 'us-west-2'
neptune_analytics_endpoint = 'neptune-graph://my-graph-identifier'
config = {
"embedder": {
"provider": "aws_bedrock",
"config": {
"model": "amazon.titan-embed-text-v2:0"
}
},
"llm": {
"provider": "aws_bedrock",
"config": {
"model": "us.anthropic.claude-3-7-sonnet-20250219-v1:0",
"temperature": 0.1,
"max_tokens": 2000
}
},
"vector_store": {
"provider": "neptune",
"config": {
"collection_name": "mem0",
"endpoint": neptune_analytics_endpoint,
},
},
"graph_store": {
"provider": "neptune",
"config": {
"endpoint": neptune_analytics_endpoint,
},
},
}
# Initialize the memory system
m = Memory.from_config(config)
```
## Usage
Reference [Notebook example](https://github.com/mem0ai/mem0/blob/main/examples/graph-db-demo/neptune-example.ipynb)
#### Add a memory:
```python
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."}
]
# Store inferred memories (default behavior)
result = m.add(messages, user_id="alice", metadata={"category": "movie_recommendations"})
```
#### Search a memory:
```python
relevant_memories = m.search(query, user_id="alice")
```
#### Get all memories:
```python
all_memories = m.get_all(user_id="alice")
```
#### Get a specific memory:
```python
memory = m.get(memory_id)
```
---
## Conclusion
With Mem0 and AWS services like Bedrock and Neptune Analytics, you can build intelligent AI companions that remember, adapt, and personalize their responses over time. This makes them ideal for long-term assistants, tutors, or support bots with persistent memory and natural conversation abilities.
-55
View File
@@ -1,55 +0,0 @@
# Mem0 Chrome Extension
Enhance your AI interactions with **Mem0**, a Chrome extension that introduces a universal memory layer across platforms like `ChatGPT`, `Claude`, and `Perplexity`. Mem0 ensures seamless context sharing, making your AI experiences more personalized and efficient.
<Note>
🎉 We now support Grok! The Mem0 Chrome Extension has been updated to work with Grok, bringing the same powerful memory capabilities to your Grok conversations.
</Note>
## Features
- **Universal Memory Layer**: Share context seamlessly across ChatGPT, Claude, Perplexity, and Grok.
- **Smart Context Detection**: Automatically captures relevant information from your conversations.
- **Intelligent Memory Retrieval**: Surfaces pertinent memories at the right time.
- **One-Click Sync**: Easily synchronize with existing ChatGPT memories.
- **Memory Dashboard**: Manage all your memories in one centralized location.
## Installation
You can install the Mem0 Chrome Extension using one of the following methods:
### Method 1: Chrome Web Store Installation
1. **Download the Extension**: Open Google Chrome and navigate to the [Mem0 Chrome Extension page](https://chromewebstore.google.com/detail/mem0/onihkkbipkfeijkadecaafbgagkhglop?hl=en).
2. **Add to Chrome**: Click on the "Add to Chrome" button.
3. **Confirm Installation**: In the pop-up dialog, click "Add extension" to confirm. The Mem0 icon should now appear in your Chrome toolbar.
### Method 2: Manual Installation
1. **Download the Extension**: Clone or download the extension files from the [Mem0 Chrome Extension GitHub repository](https://github.com/mem0ai/mem0-chrome-extension).
2. **Access Chrome Extensions**: Open Google Chrome and navigate to `chrome://extensions`.
3. **Enable Developer Mode**: Toggle the "Developer mode" switch in the top right corner.
4. **Load Unpacked Extension**: Click "Load unpacked" and select the directory containing the extension files.
5. **Confirm Installation**: The Mem0 Chrome Extension should now appear in your Chrome toolbar.
## Usage
1. **Locate the Mem0 Icon**: After installation, find the Mem0 icon in your Chrome toolbar.
2. **Sign In**: Click the icon and sign in with your Google account.
3. **Interact with AI Assistants**:
- **ChatGPT and Perplexity**: Continue your conversations as usual; Mem0 operates seamlessly in the background.
- **Claude**: Click the Mem0 button or use the shortcut `Ctrl + M` to activate memory functions.
## Configuration
- **API Key**: Obtain your API key from the Mem0 Dashboard to connect the extension to the Mem0 API.
- **User ID**: This is your unique identifier in the Mem0 system. If not provided, it defaults to 'chrome-extension-user'.
## Demo Video
<iframe width="700" height="400" src="https://www.youtube.com/embed/dqenCMMlfwQ?si=zhGVrkq6IS_0Jwyj" title="YouTube video player" frameborder="0" allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture; web-share" referrerpolicy="strict-origin-when-cross-origin" allowfullscreen></iframe>
## Privacy and Data Security
Your messages are sent to the Mem0 API for extracting and retrieving memories. Mem0 is committed to ensuring your data's privacy and security.
@@ -1,123 +0,0 @@
---
title: Multi-User Collaboration with Mem0
---
## Overview
Build a multi-user collaborative chat or task management system with Mem0. Each message is attributed to its author, and all messages are stored in a shared project space. Mem0 makes it easy to track contributions, sort and group messages, and collaborate in real time.
## Setup
Install the required packages:
```bash
pip install openai mem0ai
```
## Full Code Example
```python
from openai import OpenAI
from mem0 import Memory
import os
from datetime import datetime
from collections import defaultdict
# Set your OpenAI API key
os.environ["OPENAI_API_KEY"] = "sk-your-key"
# Shared project context
RUN_ID = "project-demo"
# Initialize Mem0
mem = Memory()
class CollaborativeAgent:
def __init__(self, run_id):
self.run_id = run_id
self.mem = mem
def add_message(self, role, name, content):
msg = {"role": role, "name": name, "content": content}
self.mem.add([msg], run_id=self.run_id, infer=False)
def brainstorm(self, prompt):
# Get recent messages for context
memories = self.mem.search(prompt, run_id=self.run_id, limit=5)["results"]
context = "\n".join(f"- {m['memory']} (by {m.get('actor_id', 'Unknown')})" for m in memories)
client = OpenAI()
messages = [
{"role": "system", "content": "You are a helpful project assistant."},
{"role": "user", "content": f"Prompt: {prompt}\nContext:\n{context}"}
]
reply = client.chat.completions.create(
model="gpt-4.1-nano-2025-04-14",
messages=messages
).choices[0].message.content.strip()
self.add_message("assistant", "assistant", reply)
return reply
def get_all_messages(self):
return self.mem.get_all(run_id=self.run_id)["results"]
def print_sorted_by_time(self):
messages = self.get_all_messages()
messages.sort(key=lambda m: m.get('created_at', ''))
print("\n--- Messages (sorted by time) ---")
for m in messages:
who = m.get("actor_id") or "Unknown"
ts = m.get('created_at', 'Timestamp N/A')
try:
dt = datetime.fromisoformat(ts.replace('Z', '+00:00'))
ts_fmt = dt.strftime('%Y-%m-%d %H:%M:%S')
except Exception:
ts_fmt = ts
print(f"[{ts_fmt}] [{who}] {m['memory']}")
def print_grouped_by_actor(self):
messages = self.get_all_messages()
grouped = defaultdict(list)
for m in messages:
grouped[m.get("actor_id") or "Unknown"].append(m)
print("\n--- Messages (grouped by actor) ---")
for actor, mems in grouped.items():
print(f"\n=== {actor} ===")
for m in mems:
ts = m.get('created_at', 'Timestamp N/A')
try:
dt = datetime.fromisoformat(ts.replace('Z', '+00:00'))
ts_fmt = dt.strftime('%Y-%m-%d %H:%M:%S')
except Exception:
ts_fmt = ts
print(f"[{ts_fmt}] {m['memory']}")
```
## Usage
```python
# Example usage
agent = CollaborativeAgent(RUN_ID)
agent.add_message("user", "alice", "Let's list tasks for the new landing page.")
agent.add_message("user", "bob", "I'll own the hero section copy.")
agent.add_message("user", "carol", "I'll choose product screenshots.")
# Brainstorm with context
print("\nAssistant reply:\n", agent.brainstorm("What are the current open tasks?"))
# Print all messages sorted by time
agent.print_sorted_by_time()
# Print all messages grouped by actor
agent.print_grouped_by_actor()
```
## Key Points
- Each message is attributed to a user or agent (actor)
- All messages are stored in a shared project space (`run_id`)
- You can sort messages by time, group by actor, and format timestamps for clarity
- Mem0 makes it easy to build collaborative, attributed chat/task systems
## Conclusion
Mem0 enables fast, transparent collaboration for teams and agents, with full attribution, flexible memory search, and easy message organization.
@@ -1,111 +0,0 @@
---
title: Customer Support AI Agent
---
You can create a personalized Customer Support AI Agent using Mem0. This guide will walk you through the necessary steps and provide the complete code to get you started.
## Overview
The Customer Support AI Agent leverages Mem0 to retain information across interactions, enabling a personalized and efficient support experience.
## Setup
Install the necessary packages using pip:
```bash
pip install openai mem0ai
```
## Full Code Example
Below is the simplified code to create and interact with a Customer Support AI Agent using Mem0:
```python
import os
from openai import OpenAI
from mem0 import Memory
# Set the OpenAI API key
os.environ['OPENAI_API_KEY'] = 'sk-xxx'
class CustomerSupportAIAgent:
def __init__(self):
"""
Initialize the CustomerSupportAIAgent with memory configuration and OpenAI client.
"""
config = {
"vector_store": {
"provider": "qdrant",
"config": {
"host": "localhost",
"port": 6333,
}
},
}
self.memory = Memory.from_config(config)
self.client = OpenAI()
self.app_id = "customer-support"
def handle_query(self, query, user_id=None):
"""
Handle a customer query and store the relevant information in memory.
:param query: The customer query to handle.
:param user_id: Optional user ID to associate with the memory.
"""
# Start a streaming chat completion request to the AI
stream = self.client.chat.completions.create(
model="gpt-4",
stream=True,
messages=[
{"role": "system", "content": "You are a customer support AI agent."},
{"role": "user", "content": query}
]
)
# Store the query in memory
self.memory.add(query, user_id=user_id, metadata={"app_id": self.app_id})
# Print the response from the AI in real-time
for chunk in stream:
if chunk.choices[0].delta.content is not None:
print(chunk.choices[0].delta.content, end="")
def get_memories(self, user_id=None):
"""
Retrieve all memories associated with the given customer ID.
:param user_id: Optional user ID to filter memories.
:return: List of memories.
"""
return self.memory.get_all(user_id=user_id)
# Instantiate the CustomerSupportAIAgent
support_agent = CustomerSupportAIAgent()
# Define a customer ID
customer_id = "jane_doe"
# Handle a customer query
support_agent.handle_query("I need help with my recent order. It hasn't arrived yet.", user_id=customer_id)
```
### Fetching Memories
You can fetch all the memories at any point in time using the following code:
```python
memories = support_agent.get_memories(user_id=customer_id)
for m in memories['results']:
print(m['memory'])
```
### Key Points
- **Initialization**: The CustomerSupportAIAgent class is initialized with the necessary memory configuration and OpenAI client setup.
- **Handling Queries**: The handle_query method sends a query to the AI and stores the relevant information in memory.
- **Retrieving Memories**: The get_memories method fetches all stored memories associated with a customer.
### Conclusion
As the conversation progresses, Mem0's memory automatically updates based on the interactions, providing a continuously improving personalized support experience.
-73
View File
@@ -1,73 +0,0 @@
---
title: Eliza OS Character
---
You can create a personalised Eliza OS Character using Mem0. This guide will walk you through the necessary steps and provide the complete code to get you started.
## Overview
ElizaOS is a powerful AI agent framework for autonomy & personality. It is a collection of tools that help you create a personalised AI agent.
## Setup
You can start by cloning the eliza-os repository:
```bash
git clone https://github.com/elizaOS/eliza.git
```
Change the directory to the eliza-os repository:
```bash
cd eliza
```
Install the dependencies:
```bash
pnpm install
```
Build the project:
```bash
pnpm build
```
## Setup ENVs
Create a `.env` file in the root of the project and add the following ( You can use the `.env.example` file as a reference):
```bash
# Mem0 Configuration
MEM0_API_KEY= # Mem0 API Key ( Get from https://app.mem0.ai/dashboard/api-keys )
MEM0_USER_ID= # Default: eliza-os-user
MEM0_PROVIDER= # Default: openai
MEM0_PROVIDER_API_KEY= # API Key for the provider (openai, anthropic, etc.)
SMALL_MEM0_MODEL= # Default: gpt-4.1-nano
MEDIUM_MEM0_MODEL= # Default: gpt-4o
LARGE_MEM0_MODEL= # Default: gpt-4o
```
## Make the default character use Mem0
By default, there is a character called `eliza` that uses the `ollama` model. You can make this character use Mem0 by changing the config in the `agent/src/defaultCharacter.ts` file.
```ts
modelProvider: ModelProviderName.MEM0,
```
This will make the character use Mem0 to generate responses.
## Run the project
```bash
pnpm start
```
## Conclusion
You have now created a personalised Eliza OS Character using Mem0. You can now start interacting with the character by running the project and talking to the character.
This is a simple example of how to use Mem0 to create a personalised AI agent. You can use this as a starting point to create your own AI agent.
-186
View File
@@ -1,186 +0,0 @@
---
title: Email Processing with Mem0
---
This guide demonstrates how to build an intelligent email processing system using Mem0's memory capabilities. You'll learn how to store, categorize, retrieve, and analyze emails to create a smart email management solution.
## Overview
Email overload is a common challenge for many professionals. By leveraging Mem0's memory capabilities, you can build an intelligent system that:
- Stores emails as searchable memories
- Categorizes emails automatically
- Retrieves relevant past conversations
- Prioritizes messages based on importance
- Generates summaries and action items
## Setup
Before you begin, ensure you have the required dependencies installed:
```bash
pip install mem0ai openai
```
## Implementation
### Basic Email Memory System
The following example shows how to create a basic email processing system with Mem0:
```python
import os
from mem0 import MemoryClient
from email.parser import Parser
# Configure API keys
os.environ["MEM0_API_KEY"] = "your-mem0-api-key"
# Initialize Mem0 client
client = MemoryClient()
class EmailProcessor:
def __init__(self):
"""Initialize the Email Processor with Mem0 memory client"""
self.client = client
def process_email(self, email_content, user_id):
"""
Process an email and store it in Mem0 memory
Args:
email_content (str): Raw email content
user_id (str): User identifier for memory association
"""
# Parse email
parser = Parser()
email = parser.parsestr(email_content)
# Extract email details
sender = email['from']
recipient = email['to']
subject = email['subject']
date = email['date']
body = self._get_email_body(email)
# Create message object for Mem0
message = {
"role": "user",
"content": f"Email from {sender}: {subject}\n\n{body}"
}
# Create metadata for better retrieval
metadata = {
"email_type": "incoming",
"sender": sender,
"recipient": recipient,
"subject": subject,
"date": date
}
# Store in Mem0 with appropriate categories
response = self.client.add(
messages=[message],
user_id=user_id,
metadata=metadata,
categories=["email", "correspondence"],
version="v2"
)
return response
def _get_email_body(self, email):
"""Extract the body content from an email"""
# Simplified extraction - in real-world, handle multipart emails
if email.is_multipart():
for part in email.walk():
if part.get_content_type() == "text/plain":
return part.get_payload(decode=True).decode()
else:
return email.get_payload(decode=True).decode()
def search_emails(self, query, user_id):
"""
Search through stored emails
Args:
query (str): Search query
user_id (str): User identifier
"""
# Search Mem0 for relevant emails
results = self.client.search(
query=query,
user_id=user_id,
categories=["email"],
output_format="v1.1",
version="v2"
)
return results
def get_email_thread(self, subject, user_id):
"""
Retrieve all emails in a thread based on subject
Args:
subject (str): Email subject to match
user_id (str): User identifier
"""
filters = {
"AND": [
{"user_id": user_id},
{"categories": {"contains": "email"}},
{"metadata": {"subject": {"contains": subject}}}
]
}
thread = self.client.get_all(
version="v2",
filters=filters,
output_format="v1.1"
)
return thread
# Initialize the processor
processor = EmailProcessor()
# Example raw email
sample_email = """From: alice@example.com
To: bob@example.com
Subject: Meeting Schedule Update
Date: Mon, 15 Jul 2024 14:22:05 -0700
Hi Bob,
I wanted to update you on the schedule for our upcoming project meeting.
We'll be meeting this Thursday at 2pm instead of Friday.
Could you please prepare your section of the presentation?
Thanks,
Alice
"""
# Process and store the email
user_id = "bob@example.com"
processor.process_email(sample_email, user_id)
# Later, search for emails about meetings
meeting_emails = processor.search_emails("meeting schedule", user_id)
print(f"Found {len(meeting_emails['results'])} relevant emails")
```
## Key Features and Benefits
- **Long-term Email Memory**: Store and retrieve email conversations across long periods
- **Semantic Search**: Find relevant emails even if they don't contain exact keywords
- **Intelligent Categorization**: Automatically sort emails into meaningful categories
- **Action Item Extraction**: Identify and track tasks mentioned in emails
- **Priority Management**: Focus on important emails based on AI-determined priority
- **Context Awareness**: Maintain thread context for more relevant interactions
## Conclusion
By combining Mem0's memory capabilities with email processing, you can create intelligent email management systems that help users organize, prioritize, and act on their inbox effectively. The advanced capabilities like automatic categorization, action item extraction, and priority management can significantly reduce the time spent on email management, allowing users to focus on more important tasks.
-173
View File
@@ -1,173 +0,0 @@
---
title: LlamaIndex ReAct Agent
---
Create a ReAct Agent with LlamaIndex which uses Mem0 as the memory store.
### Overview
A ReAct agent combines reasoning and action capabilities, making it versatile for tasks requiring both thought processes (reasoning) and interaction with tools or APIs (acting). Mem0 as memory enhances these capabilities by allowing the agent to store and retrieve contextual information from past interactions.
### Setup
```bash
pip install llama-index-core llama-index-memory-mem0
```
Initialize the LLM.
```python
import os
from llama_index.llms.openai import OpenAI
os.environ["OPENAI_API_KEY"] = "<your-openai-api-key>"
llm = OpenAI(model="gpt-4.1-nano-2025-04-14")
```
Initialize the Mem0 client. You can find your API key [here](https://app.mem0.ai/dashboard/api-keys). Read about Mem0 [Open Source](https://docs.mem0.ai/open-source/overview).
```python
os.environ["MEM0_API_KEY"] = "<your-mem0-api-key>"
from llama_index.memory.mem0 import Mem0Memory
context = {"user_id": "david"}
memory_from_client = Mem0Memory.from_client(
context=context,
api_key=os.environ["MEM0_API_KEY"],
search_msg_limit=4, # optional, default is 5
)
```
Create the tools. These tools will be used by the agent to perform actions.
```python
from llama_index.core.tools import FunctionTool
def call_fn(name: str):
"""Call the provided name.
Args:
name: str (Name of the person)
"""
return f"Calling... {name}"
def email_fn(name: str):
"""Email the provided name.
Args:
name: str (Name of the person)
"""
return f"Emailing... {name}"
def order_food(name: str, dish: str):
"""Order food for the provided name.
Args:
name: str (Name of the person)
dish: str (Name of the dish)
"""
return f"Ordering {dish} for {name}"
call_tool = FunctionTool.from_defaults(fn=call_fn)
email_tool = FunctionTool.from_defaults(fn=email_fn)
order_food_tool = FunctionTool.from_defaults(fn=order_food)
```
Initialize the agent with tools and memory.
```python
from llama_index.core.agent import FunctionCallingAgent
agent = FunctionCallingAgent.from_tools(
[call_tool, email_tool, order_food_tool],
llm=llm,
memory=memory_from_client, # or memory_from_config
verbose=True,
)
```
Start the chat.
<Note> The agent will use the Mem0 to store the relevant memories from the chat. </Note>
Input
```python
response = agent.chat("Hi, My name is David")
print(response)
```
Output
```text
> Running step bf44a75a-a920-4cf3-944e-b6e6b5695043. Step input: Hi, My name is David
Added user message to memory: Hi, My name is David
=== LLM Response ===
Hello, David! How can I assist you today?
```
Input
```python
response = agent.chat("I love to eat pizza on weekends")
print(response)
```
Output
```text
> Running step 845783b0-b85b-487c-baee-8460ebe8b38d. Step input: I love to eat pizza on weekends
Added user message to memory: I love to eat pizza on weekends
=== LLM Response ===
Pizza is a great choice for the weekend! If you'd like, I can help you order some. Just let me know what kind of pizza you prefer!
```
Input
```python
response = agent.chat("My preferred way of communication is email")
print(response)
```
Output
```text
> Running step 345842f0-f8a0-42ea-a1b7-612265d72a92. Step input: My preferred way of communication is email
Added user message to memory: My preferred way of communication is email
=== LLM Response ===
Got it! If you need any assistance or have any requests, feel free to let me know, and I can communicate with you via email.
```
### Using the agent WITHOUT memory
Input
```python
agent = FunctionCallingAgent.from_tools(
[call_tool, email_tool, order_food_tool],
# memory is not provided
llm=llm,
verbose=True,
)
response = agent.chat("I am feeling hungry, order me something and send me the bill")
print(response)
```
Output
```text
> Running step e89eb75d-75e1-4dea-a8c8-5c3d4b77882d. Step input: I am feeling hungry, order me something and send me the bill
Added user message to memory: I am feeling hungry, order me something and send me the bill
=== LLM Response ===
Please let me know your name and the dish you'd like to order, and I'll take care of it for you!
```
<Note> The agent is not able to remember the past preferences that user shared in previous chats. </Note>
### Using the agent WITH memory
Input
```python
agent = FunctionCallingAgent.from_tools(
[call_tool, email_tool, order_food_tool],
llm=llm,
# memory is provided
memory=memory_from_client, # or memory_from_config
verbose=True,
)
response = agent.chat("I am feeling hungry, order me something and send me the bill")
print(response)
```
Output
```text
> Running step 5e473db9-3973-4cb1-a5fd-860be0ab0006. Step input: I am feeling hungry, order me something and send me the bill
Added user message to memory: I am feeling hungry, order me something and send me the bill
=== Calling Function ===
Calling function: order_food with args: {"name": "David", "dish": "pizza"}
=== Function Output ===
Ordering pizza for David
=== Calling Function ===
Calling function: email_fn with args: {"name": "David"}
=== Function Output ===
Emailing... David
> Running step 38080544-6b37-4bb2-aab2-7670100d926e. Step input: None
=== LLM Response ===
I've ordered a pizza for you, and the bill has been sent to your email. Enjoy your meal! If there's anything else you need, feel free to let me know.
```
<Note> The agent is able to remember the past preferences that user shared and use them to perform actions. </Note>
@@ -1,360 +0,0 @@
---
title: LlamaIndex Multi-Agent Learning System
---
<Snippet file="blank-notif.mdx" />
Build an intelligent multi-agent learning system that uses Mem0 to maintain persistent memory across multiple specialized agents. This example demonstrates how to create a tutoring system where different agents collaborate while sharing a unified memory layer.
## Overview
This example showcases a **Multi-Agent Personal Learning System** that combines:
- **LlamaIndex AgentWorkflow** for multi-agent orchestration
- **Mem0** for persistent, shared memory across agents
- **Multi-agents** that collaborate on teaching tasks
The system consists of two agents:
- **TutorAgent**: Primary instructor for explanations and concept teaching
- **PracticeAgent**: Generates exercises and tracks learning progress
Both agents share the same memory context, enabling seamless collaboration and continuous learning from student interactions.
## Key Features
- **Persistent Memory**: Agents remember previous interactions across sessions
- **Multi-Agent Collaboration**: Agents can hand off tasks to each other
- **Personalized Learning**: Adapts to individual student needs and learning styles
- **Progress Tracking**: Monitors learning patterns and skill development
- **Memory-Driven Teaching**: References past struggles and successes
## Prerequisites
Install the required packages:
```bash
pip install llama-index-core llama-index-memory-mem0 openai python-dotenv
```
Set up your environment variables:
- `MEM0_API_KEY`: Your Mem0 Platform API key
- `OPENAI_API_KEY`: Your OpenAI API key
You can obtain your Mem0 Platform API key from the [Mem0 Platform](https://app.mem0.ai).
## Complete Implementation
```python
"""
Multi-Agent Personal Learning System: Mem0 + LlamaIndex AgentWorkflow Example
INSTALLATIONS:
!pip install llama-index-core llama-index-memory-mem0 openai
You need MEM0_API_KEY and OPENAI_API_KEY to run the example.
"""
import asyncio
from datetime import datetime
from dotenv import load_dotenv
# LlamaIndex imports
from llama_index.core.agent.workflow import AgentWorkflow, FunctionAgent
from llama_index.llms.openai import OpenAI
from llama_index.core.tools import FunctionTool
# Memory integration
from llama_index.memory.mem0 import Mem0Memory
import warnings
warnings.filterwarnings("ignore", category=DeprecationWarning)
load_dotenv()
class MultiAgentLearningSystem:
"""
Multi-Agent Architecture:
- TutorAgent: Main teaching and explanations
- PracticeAgent: Exercises and skill reinforcement
- Shared Memory: Both agents learn from student interactions
"""
def __init__(self, student_id: str):
self.student_id = student_id
self.llm = OpenAI(model="gpt-4.1-nano-2025-04-14", temperature=0.2)
# Memory context for this student
self.memory_context = {"user_id": student_id, "app": "learning_assistant"}
self.memory = Mem0Memory.from_client(
context=self.memory_context
)
self._setup_agents()
def _setup_agents(self):
"""Setup two agents that work together and share memory"""
# TOOLS
async def assess_understanding(topic: str, student_response: str) -> str:
"""Assess student's understanding of a topic and save insights"""
# Simulate assessment logic
if "confused" in student_response.lower() or "don't understand" in student_response.lower():
assessment = f"STRUGGLING with {topic}: {student_response}"
insight = f"Student needs more help with {topic}. Prefers step-by-step explanations."
elif "makes sense" in student_response.lower() or "got it" in student_response.lower():
assessment = f"UNDERSTANDS {topic}: {student_response}"
insight = f"Student grasped {topic} quickly. Can move to advanced concepts."
else:
assessment = f"PARTIAL understanding of {topic}: {student_response}"
insight = f"Student has basic understanding of {topic}. Needs reinforcement."
return f"Assessment: {assessment}\nInsight saved: {insight}"
async def track_progress(topic: str, success_rate: str) -> str:
"""Track learning progress and identify patterns"""
progress_note = f"Progress on {topic}: {success_rate} - {datetime.now().strftime('%Y-%m-%d')}"
return f"Progress tracked: {progress_note}"
# Convert to FunctionTools
tools = [
FunctionTool.from_defaults(async_fn=assess_understanding),
FunctionTool.from_defaults(async_fn=track_progress)
]
# AGENTS
# Tutor Agent - Main teaching and explanation
self.tutor_agent = FunctionAgent(
name="TutorAgent",
description="Primary instructor that explains concepts and adapts to student needs",
system_prompt="""
You are a patient, adaptive programming tutor. Your key strength is REMEMBERING and BUILDING on previous interactions.
Key Behaviors:
1. Always check what the student has learned before (use memory context)
2. Adapt explanations based on their preferred learning style
3. Reference previous struggles or successes
4. Build progressively on past lessons
5. Use assess_understanding to evaluate responses and save insights
MEMORY-DRIVEN TEACHING:
- "Last time you struggled with X, so let's approach Y differently..."
- "Since you prefer visual examples, here's a diagram..."
- "Building on the functions we covered yesterday..."
When student shows understanding, hand off to PracticeAgent for exercises.
""",
tools=tools,
llm=self.llm,
can_handoff_to=["PracticeAgent"]
)
# Practice Agent - Exercises and reinforcement
self.practice_agent = FunctionAgent(
name="PracticeAgent",
description="Creates practice exercises and tracks progress based on student's learning history",
system_prompt="""
You create personalized practice exercises based on the student's learning history and current level.
Key Behaviors:
1. Generate problems that match their skill level (from memory)
2. Focus on areas they've struggled with previously
3. Gradually increase difficulty based on their progress
4. Use track_progress to record their performance
5. Provide encouraging feedback that references their growth
MEMORY-DRIVEN PRACTICE:
- "Let's practice loops again since you wanted more examples..."
- "Here's a harder version of the problem you solved yesterday..."
- "You've improved a lot in functions, ready for the next level?"
After practice, can hand back to TutorAgent for concept review if needed.
""",
tools=tools,
llm=self.llm,
can_handoff_to=["TutorAgent"]
)
# Create the multi-agent workflow
self.workflow = AgentWorkflow(
agents=[self.tutor_agent, self.practice_agent],
root_agent=self.tutor_agent.name,
initial_state={
"current_topic": "",
"student_level": "beginner",
"learning_style": "unknown",
"session_goals": []
}
)
async def start_learning_session(self, topic: str, student_message: str = "") -> str:
"""
Start a learning session with multi-agent memory-aware teaching
"""
if student_message:
request = f"I want to learn about {topic}. {student_message}"
else:
request = f"I want to learn about {topic}."
# The magic happens here - multi-agent memory is automatically shared!
response = await self.workflow.run(
user_msg=request,
memory=self.memory
)
return str(response)
async def get_learning_history(self) -> str:
"""Show what the system remembers about this student"""
try:
# Search memory for learning patterns
memories = self.memory.search(
user_id=self.student_id,
query="learning machine learning"
)
if memories and memories.get('results'):
history = "\n".join(f"- {m['memory']}" for m in memories['results'])
return history
else:
return "No learning history found yet. Let's start building your profile!"
except Exception as e:
return f"Memory retrieval error: {str(e)}"
async def run_learning_agent():
learning_system = MultiAgentLearningSystem(student_id="Alexander")
# First session
print("Session 1:")
response = await learning_system.start_learning_session(
"Vision Language Models",
"I'm new to machine learning but I have good hold on Python and have 4 years of work experience.")
print(response)
# Second session - multi-agent memory will remember the first
print("\nSession 2:")
response2 = await learning_system.start_learning_session(
"Machine Learning", "what all did I cover so far?")
print(response2)
# Show what the multi-agent system remembers
print("\nLearning History:")
history = await learning_system.get_learning_history()
print(history)
if __name__ == "__main__":
"""Run the example"""
print("Multi-agent Learning System powered by LlamaIndex and Mem0")
async def main():
await run_learning_agent()
asyncio.run(main())
```
## How It Works
### 1. Memory Context Setup
```python
# Memory context for this student
self.memory_context = {"user_id": student_id, "app": "learning_assistant"}
self.memory = Mem0Memory.from_client(context=self.memory_context)
```
The memory context identifies the specific student and application, ensuring memory isolation and proper retrieval.
### 2. Agent Collaboration
```python
# Agents can hand off to each other
can_handoff_to=["PracticeAgent"] # TutorAgent can hand off to PracticeAgent
can_handoff_to=["TutorAgent"] # PracticeAgent can hand off back
```
Agents collaborate seamlessly, with the TutorAgent handling explanations and the PracticeAgent managing exercises.
### 3. Shared Memory
```python
# Both agents share the same memory instance
response = await self.workflow.run(
user_msg=request,
memory=self.memory # Shared across all agents
)
```
All agents in the workflow share the same memory context, enabling true collaborative learning.
### 4. Memory-Driven Interactions
The system prompts guide agents to:
- Reference previous learning sessions
- Adapt to discovered learning styles
- Build progressively on past lessons
- Track and respond to learning patterns
## Running the Example
```python
# Initialize the learning system
learning_system = MultiAgentLearningSystem(student_id="Alexander")
# Start a learning session
response = await learning_system.start_learning_session(
"Vision Language Models",
"I'm new to machine learning but I have good hold on Python and have 4 years of work experience."
)
# Continue learning in a new session (memory persists)
response2 = await learning_system.start_learning_session(
"Machine Learning",
"what all did I cover so far?"
)
# Check learning history
history = await learning_system.get_learning_history()
```
## Expected Output
The system will demonstrate memory-aware interactions:
```
Session 1:
I understand you want to learn about Vision Language Models and you mentioned you're new to machine learning but have a strong Python background with 4 years of experience. That's a great foundation to build on!
Let me start with an explanation tailored to your programming background...
[Agent provides explanation and may hand off to PracticeAgent for exercises]
Session 2:
Based on our previous session, I remember we covered Vision Language Models and I noted that you have a strong Python background with 4 years of experience. You mentioned being new to machine learning, so we started with foundational concepts...
[Agent references previous session and builds upon it]
```
## Key Benefits
1. **Persistent Learning**: Agents remember across sessions, creating continuity
2. **Collaborative Teaching**: Multiple specialized agents work together seamlessly
3. **Personalized Adaptation**: System learns and adapts to individual learning styles
4. **Scalable Architecture**: Easy to add more specialized agents
5. **Memory Efficiency**: Shared memory prevents duplication and ensures consistency
## Best Practices
1. **Clear Agent Roles**: Define specific responsibilities for each agent
2. **Memory Context**: Use descriptive context for memory isolation
3. **Handoff Strategy**: Design clear handoff criteria between agents
5. **Memory Hygiene**: Regularly review and clean memory for optimal performance
## Help & Resources
- [LlamaIndex Agent Workflows](https://docs.llamaindex.ai/en/stable/use_cases/agents/)
- [Mem0 Platform](https://app.mem0.ai/)
<Snippet file="get-help.mdx" />
-227
View File
@@ -1,227 +0,0 @@
---
title: Mem0 as an Agentic Tool
---
Integrate Mem0's memory capabilities with OpenAI's Agents SDK to create AI agents with persistent memory.
You can create agents that remember past conversations and use that context to provide better responses.
## Installation
First, install the required packages:
```bash
pip install mem0ai pydantic openai-agents
```
You'll also need a custom agents framework for this implementation.
## Setting Up Environment Variables
Store your Mem0 API key as an environment variable:
```bash
export MEM0_API_KEY="your_mem0_api_key"
```
Or in your Python script:
```python
import os
os.environ["MEM0_API_KEY"] = "your_mem0_api_key"
```
## Code Structure
The integration consists of three main components:
1. **Context Manager**: Defines user context for memory operations
2. **Memory Tools**: Functions to add, search, and retrieve memories
3. **Memory Agent**: An agent configured to use these memory tools
## Step-by-Step Implementation
### 1. Import Dependencies
```python
from __future__ import annotations
import os
import asyncio
from pydantic import BaseModel
try:
from mem0 import AsyncMemoryClient
except ImportError:
raise ImportError("mem0 is not installed. Please install it using 'pip install mem0ai'.")
from agents import (
Agent,
ItemHelpers,
MessageOutputItem,
RunContextWrapper,
Runner,
ToolCallItem,
ToolCallOutputItem,
TResponseInputItem,
function_tool,
)
```
### 2. Define Memory Context
```python
class Mem0Context(BaseModel):
user_id: str | None = None
```
### 3. Initialize the Mem0 Client
```python
client = AsyncMemoryClient(api_key=os.getenv("MEM0_API_KEY"))
```
### 4. Create Memory Tools
#### Add to Memory
```python
@function_tool
async def add_to_memory(
context: RunContextWrapper[Mem0Context],
content: str,
) -> str:
"""
Add a message to Mem0
Args:
content: The content to store in memory.
"""
messages = [{"role": "user", "content": content}]
user_id = context.context.user_id or "default_user"
await client.add(messages, user_id=user_id)
return f"Stored message: {content}"
```
#### Search Memory
```python
@function_tool
async def search_memory(
context: RunContextWrapper[Mem0Context],
query: str,
) -> str:
"""
Search for memories in Mem0
Args:
query: The search query.
"""
user_id = context.context.user_id or "default_user"
memories = await client.search(query, user_id=user_id, output_format="v1.1")
results = '\n'.join([result["memory"] for result in memories["results"]])
return str(results)
```
#### Get All Memories
```python
@function_tool
async def get_all_memory(
context: RunContextWrapper[Mem0Context],
) -> str:
"""Retrieve all memories from Mem0"""
user_id = context.context.user_id or "default_user"
memories = await client.get_all(user_id=user_id, output_format="v1.1")
results = '\n'.join([result["memory"] for result in memories["results"]])
return str(results)
```
### 5. Configure the Memory Agent
```python
memory_agent = Agent[Mem0Context](
name="Memory Assistant",
instructions="""You are a helpful assistant with memory capabilities. You can:
1. Store new information using add_to_memory
2. Search existing information using search_memory
3. Retrieve all stored information using get_all_memory
When users ask questions:
- If they want to store information, use add_to_memory
- If they're searching for specific information, use search_memory
- If they want to see everything stored, use get_all_memory""",
tools=[add_to_memory, search_memory, get_all_memory],
)
```
### 6. Implement the Main Runtime Loop
```python
async def main():
current_agent: Agent[Mem0Context] = memory_agent
input_items: list[TResponseInputItem] = []
context = Mem0Context()
while True:
user_input = input("Enter your message (or 'quit' to exit): ")
if user_input.lower() == 'quit':
break
input_items.append({"content": user_input, "role": "user"})
result = await Runner.run(current_agent, input_items, context=context)
for new_item in result.new_items:
agent_name = new_item.agent.name
if isinstance(new_item, MessageOutputItem):
print(f"{agent_name}: {ItemHelpers.text_message_output(new_item)}")
elif isinstance(new_item, ToolCallItem):
print(f"{agent_name}: Calling a tool")
elif isinstance(new_item, ToolCallOutputItem):
print(f"{agent_name}: Tool call output: {new_item.output}")
else:
print(f"{agent_name}: Skipping item: {new_item.__class__.__name__}")
input_items = result.to_input_list()
if __name__ == "__main__":
asyncio.run(main())
```
## Usage Examples
### Storing Information
```
User: Remember that my favorite color is blue
Agent: Calling a tool
Agent: Tool call output: Stored message: my favorite color is blue
Agent: I've stored that your favorite color is blue in my memory. I'll remember that for future conversations.
```
### Searching Memory
```
User: What's my favorite color?
Agent: Calling a tool
Agent: Tool call output: my favorite color is blue
Agent: Your favorite color is blue, based on what you've told me earlier.
```
### Retrieving All Memories
```
User: What do you know about me?
Agent: Calling a tool
Agent: Tool call output: favorite color is blue
my birthday is on March 15
Agent: Based on our previous conversations, I know that:
1. Your favorite color is blue
2. Your birthday is on March 15
```
## Advanced Configuration
### Custom User IDs
You can specify different user IDs to maintain separate memory stores for multiple users:
```python
context = Mem0Context(user_id="user123")
```
## Resources
- [Mem0 Documentation](https://docs.mem0.ai)
- [Mem0 Dashboard](https://app.mem0.ai/dashboard)
- [API Reference](https://docs.mem0.ai/api-reference)
-68
View File
@@ -1,68 +0,0 @@
---
title: Mem0 Demo
---
You can create a personalized AI Companion using Mem0. This guide will walk you through the necessary steps and provide the complete setup instructions to get you started.
<video
autoPlay
muted
loop
playsInline
className="w-full aspect-video rounded-lg"
src="https://github.com/user-attachments/assets/cebc4f8e-bdb9-4837-868d-13c5ab7bb433"
></video>
You can try the [Mem0 Demo](https://mem0-4vmi.vercel.app) live here.
## Overview
The Personalized AI Companion leverages Mem0 to retain information across interactions, enabling a tailored learning experience. It creates memories for each user interaction and integrates with OpenAI's GPT models to provide detailed and context-aware responses to user queries.
## Setup
Before you begin, follow these steps to set up the demo application:
1. Clone the Mem0 repository:
```bash
git clone https://github.com/mem0ai/mem0.git
```
2. Navigate to the demo application folder:
```bash
cd mem0/examples/mem0-demo
```
3. Install dependencies:
```bash
pnpm install
```
4. Set up environment variables by creating a `.env` file in the project root with the following content:
```bash
OPENAI_API_KEY=your_openai_api_key
MEM0_API_KEY=your_mem0_api_key
```
You can obtain your `MEM0_API_KEY` by signing up at [Mem0 API Dashboard](https://app.mem0.ai/dashboard/api-keys).
5. Start the development server:
```bash
pnpm run dev
```
## Enhancing the Next.js Application
Once the demo is running, you can customize and enhance the Next.js application by modifying the components in the `mem0-demo` folder. Consider:
- Adding new memory features to improve contextual retention.
- Customizing the UI to better suit your application needs.
- Integrating additional APIs or third-party services to extend functionality.
## Full Code
You can find the complete source code for this demo on GitHub:
[Mem0 Demo GitHub](https://github.com/mem0ai/mem0/tree/main/examples/mem0-demo)
## Conclusion
This setup demonstrates how to build an AI Companion that maintains memory across interactions using Mem0. The system continuously adapts to user interactions, making future responses more relevant and personalized. Experiment with the application and enhance it further to suit your use case!
@@ -1,293 +0,0 @@
---
title: 'Healthcare Assistant with Mem0 and Google ADK'
description: 'Build a personalized healthcare agent that remembers patient information across conversations using Mem0 and Google ADK'
---
# Healthcare Assistant with Memory
This example demonstrates how to build a healthcare assistant that remembers patient information across conversations using Google ADK and Mem0.
## Overview
The Healthcare Assistant helps patients by:
- Remembering their medical history and symptoms
- Providing general health information
- Scheduling appointment reminders
- Maintaining a personalized experience across conversations
By integrating Mem0's memory layer with Google ADK, the assistant maintains context about the patient without requiring them to repeat information.
## Setup
Before you begin, make sure you have:
Installed Google ADK and Mem0 SDK:
```bash
pip install google-adk mem0ai python-dotenv
```
## Code Breakdown
Let's get started and understand the different components required in building a healthcare assistant powered by memory
```python
# Import dependencies
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"
# Define a global user ID for simplicity
USER_ID = "Alex"
# Initialize Mem0 client
mem0 = MemoryClient()
```
## Define Memory Tools
First, we'll create tools that allow our agent to store and retrieve information using Mem0:
```python
def save_patient_info(information: str) -> dict:
"""Saves important patient information to memory."""
# Store in Mem0
response = mem0_client.add(
[{"role": "user", "content": information}],
user_id=USER_ID,
run_id="healthcare_session",
metadata={"type": "patient_information"}
)
def retrieve_patient_info(query: str) -> dict:
"""Retrieves relevant patient information from memory."""
# Search Mem0
results = mem0_client.search(
query,
user_id=USER_ID,
limit=5,
threshold=0.7, # Higher threshold for more relevant results
output_format="v1.1"
)
# Format and return the results
if results and len(results) > 0:
memories = [memory["memory"] for memory in results.get('results', [])]
return {
"status": "success",
"memories": memories,
"count": len(memories)
}
else:
return {
"status": "no_results",
"memories": [],
"count": 0
}
```
## Define Healthcare Tools
Next, we'll add tools specific to healthcare assistance:
```python
def schedule_appointment(date: str, time: str, reason: str) -> dict:
"""Schedules a doctor's appointment."""
# In a real app, this would connect to a scheduling system
appointment_id = f"APT-{hash(date + time) % 10000}"
return {
"status": "success",
"appointment_id": appointment_id,
"confirmation": f"Appointment scheduled for {date} at {time} for {reason}",
"message": "Please arrive 15 minutes early to complete paperwork."
}
```
## Create the Healthcare Assistant Agent
Now we'll create our main agent with all the tools:
```python
# Create the agent
healthcare_agent = Agent(
name="healthcare_assistant",
model="gemini-1.5-flash", # Using Gemini for healthcare assistant
description="Healthcare assistant that helps patients with health information and appointment scheduling.",
instruction="""You are a helpful Healthcare Assistant with memory capabilities.
Your primary responsibilities are to:
1. Remember patient information using the 'save_patient_info' tool when they share symptoms, conditions, or preferences.
2. Retrieve past patient information using the 'retrieve_patient_info' tool when relevant to the current conversation.
3. Help schedule appointments using the 'schedule_appointment' tool.
IMPORTANT GUIDELINES:
- Always be empathetic, professional, and helpful.
- Save important patient information like symptoms, conditions, allergies, and preferences.
- Check if you have relevant patient information before asking for details they may have shared previously.
- Make it clear you are not a doctor and cannot provide medical diagnosis or treatment.
- For serious symptoms, always recommend consulting a healthcare professional.
- Keep all patient information confidential.
""",
tools=[save_patient_info, retrieve_patient_info, schedule_appointment]
)
```
## Set Up Session and Runner
```python
# Set up Session Service and Runner
session_service = InMemorySessionService()
# Define constants for the conversation
APP_NAME = "healthcare_assistant_app"
USER_ID = "Alex"
SESSION_ID = "session_001"
# Create a session
session = session_service.create_session(
app_name=APP_NAME,
user_id=USER_ID,
session_id=SESSION_ID
)
# Create the runner
runner = Runner(
agent=healthcare_agent,
app_name=APP_NAME,
session_service=session_service
)
```
## Interact with the Healthcare Assistant
```python
# Function to interact with the agent
async def call_agent_async(query, runner, user_id, session_id):
"""Sends a query to the agent and returns the final response."""
print(f"\n>>> Patient: {query}")
# Format the user's message
content = types.Content(
role='user',
parts=[types.Part(text=query)]
)
# Set user_id for tools to access
save_patient_info.user_id = user_id
retrieve_patient_info.user_id = user_id
# Run the agent
async for event in runner.run_async(
user_id=user_id,
session_id=session_id,
new_message=content
):
if event.is_final_response():
if event.content and event.content.parts:
response = event.content.parts[0].text
print(f"<<< Assistant: {response}")
return response
return "No response received."
# Example conversation flow
async def run_conversation():
# First interaction - patient introduces themselves with key information
await call_agent_async(
"Hi, I'm Alex. I've been having headaches for the past week, and I have a penicillin allergy.",
runner=runner,
user_id=USER_ID,
session_id=SESSION_ID
)
# Request for health information
await call_agent_async(
"Can you tell me more about what might be causing my headaches?",
runner=runner,
user_id=USER_ID,
session_id=SESSION_ID
)
# Schedule an appointment
await call_agent_async(
"I think I should see a doctor. Can you help me schedule an appointment for next Monday at 2pm?",
runner=runner,
user_id=USER_ID,
session_id=SESSION_ID
)
# Test memory - should remember patient name, symptoms, and allergy
await call_agent_async(
"What medications should I avoid for my headaches?",
runner=runner,
user_id=USER_ID,
session_id=SESSION_ID
)
# Run the conversation example
if __name__ == "__main__":
asyncio.run(run_conversation())
```
## How It Works
This healthcare assistant demonstrates several key capabilities:
1. **Memory Storage**: When Alex mentions her headaches and penicillin allergy, the agent stores this information in Mem0 using the `save_patient_info` tool.
2. **Contextual Retrieval**: When Alex asks about headache causes, the agent uses the `retrieve_patient_info` tool to recall her specific situation.
3. **Memory Application**: When discussing medications, the agent remembers Alex's penicillin allergy without her needing to repeat it, providing safer and more personalized advice.
4. **Conversation Continuity**: The agent maintains context across the entire conversation session, creating a more natural and efficient interaction.
## Key Implementation Details
### User ID Management
Instead of passing the user ID as a parameter to the memory tools (which would require modifying the ADK's tool calling system), we attach it directly to the function object:
```python
# Set user_id for tools to access
save_patient_info.user_id = user_id
retrieve_patient_info.user_id = user_id
```
Inside the tool functions, we retrieve this attribute:
```python
# Get user_id from session state or use default
user_id = getattr(save_patient_info, 'user_id', 'default_user')
```
This approach allows our tools to maintain user context without complicating their parameter signatures.
### Mem0 Integration
The integration with Mem0 happens through two primary functions:
1. `mem0_client.add()` - Stores new information with appropriate metadata
2. `mem0_client.search()` - Retrieves relevant memories using semantic search
The `threshold` parameter in the search function ensures that only highly relevant memories are returned.
## Conclusion
This example demonstrates how to build a healthcare assistant with persistent memory using Google ADK and Mem0. The integration allows for a more personalized patient experience by maintaining context across conversation turns, which is particularly valuable in healthcare scenarios where continuity of information is crucial.
By storing and retrieving patient information intelligently, the assistant provides more relevant responses without requiring the patient to repeat their medical history, symptoms, or preferences.
-126
View File
@@ -1,126 +0,0 @@
---
title: Mem0 with Mastra
---
In this example you'll learn how to use the Mem0 to add long-term memory capabilities to [Mastra's agent](https://mastra.ai/) via tool-use.
This memory integration can work alongside Mastra's [agent memory features](https://mastra.ai/docs/agents/01-agent-memory).
You can find the complete example code in the [Mastra repository](https://github.com/mastra-ai/mastra/tree/main/examples/memory-with-mem0).
## Overview
This guide will show you how to integrate Mem0 with Mastra to add long-term memory capabilities to your agents. We'll create tools that allow agents to save and retrieve memories using Mem0's API.
### Installation
1. **Install the Integration Package**
To install the Mem0 integration, run:
```bash
npm install @mastra/mem0
```
2. **Add the Integration to Your Project**
Create a new file for your integrations and import the integration:
```typescript integrations/index.ts
import { Mem0Integration } from "@mastra/mem0";
export const mem0 = new Mem0Integration({
config: {
apiKey: process.env.MEM0_API_KEY!,
userId: "alice",
},
});
```
3. **Use the Integration in Tools or Workflows**
You can now use the integration when defining tools for your agents or in workflows.
```typescript tools/index.ts
import { createTool } from "@mastra/core";
import { z } from "zod";
import { mem0 } from "../integrations";
export const mem0RememberTool = createTool({
id: "Mem0-remember",
description:
"Remember your agent memories that you've previously saved using the Mem0-memorize tool.",
inputSchema: z.object({
question: z
.string()
.describe("Question used to look up the answer in saved memories."),
}),
outputSchema: z.object({
answer: z.string().describe("Remembered answer"),
}),
execute: async ({ context }) => {
console.log(`Searching memory "${context.question}"`);
const memory = await mem0.searchMemory(context.question);
console.log(`\nFound memory "${memory}"\n`);
return {
answer: memory,
};
},
});
export const mem0MemorizeTool = createTool({
id: "Mem0-memorize",
description:
"Save information to mem0 so you can remember it later using the Mem0-remember tool.",
inputSchema: z.object({
statement: z.string().describe("A statement to save into memory"),
}),
execute: async ({ context }) => {
console.log(`\nCreating memory "${context.statement}"\n`);
// to reduce latency memories can be saved async without blocking tool execution
void mem0.createMemory(context.statement).then(() => {
console.log(`\nMemory "${context.statement}" saved.\n`);
});
return { success: true };
},
});
```
4. **Create a new agent**
```typescript agents/index.ts
import { openai } from '@ai-sdk/openai';
import { Agent } from '@mastra/core/agent';
import { mem0MemorizeTool, mem0RememberTool } from '../tools';
export const mem0Agent = new Agent({
name: 'Mem0 Agent',
instructions: `
You are a helpful assistant that has the ability to memorize and remember facts using Mem0.
`,
model: openai('gpt-4.1-nano'),
tools: { mem0RememberTool, mem0MemorizeTool },
});
```
5. **Run the agent**
```typescript index.ts
import { Mastra } from '@mastra/core/mastra';
import { createLogger } from '@mastra/core/logger';
import { mem0Agent } from './agents';
export const mastra = new Mastra({
agents: { mem0Agent },
logger: createLogger({
name: 'Mastra',
level: 'error',
}),
});
```
In the example above:
- We import the `@mastra/mem0` integration.
- We define two tools that uses the Mem0 API client to create new memories and recall previously saved memories.
- The tool accepts `question` as an input and returns the memory as a string.
@@ -1,547 +0,0 @@
---
title: "Mem0 with OpenAI Agents SDK for Voice"
description: "Integrate memory capabilities into your voice agents using Mem0 and OpenAI Agents SDK"
---
# Building Voice Agents with Memory using Mem0 and OpenAI Agents SDK
This guide demonstrates how to combine OpenAI's Agents SDK for voice applications with Mem0's memory capabilities to create a voice assistant that remembers user preferences and past interactions.
## Prerequisites
Before you begin, make sure you have:
1. Installed OpenAI Agents SDK with voice dependencies:
```bash
pip install 'openai-agents[voice]'
```
2. Installed Mem0 SDK:
```bash
pip install mem0ai
```
3. Installed other required dependencies:
```bash
pip install numpy sounddevice pydantic
```
4. Set up your API keys:
- OpenAI API key for the Agents SDK
- Mem0 API key from the Mem0 Platform
## Code Breakdown
Let's break down the key components of this implementation:
### 1. Setting Up Dependencies and Environment
```python
# OpenAI Agents SDK imports
from agents import (
Agent,
function_tool
)
from agents.voice import (
AudioInput,
SingleAgentVoiceWorkflow,
VoicePipeline
)
from agents.extensions.handoff_prompt import prompt_with_handoff_instructions
# Mem0 imports
from mem0 import AsyncMemoryClient
# Set up API keys (replace with your actual keys)
os.environ["OPENAI_API_KEY"] = "your-openai-api-key"
os.environ["MEM0_API_KEY"] = "your-mem0-api-key"
# Define a global user ID for simplicity
USER_ID = "voice_user"
# Initialize Mem0 client
mem0_client = AsyncMemoryClient()
```
This section handles:
- Importing required modules from OpenAI Agents SDK and Mem0
- Setting up environment variables for API keys
- Defining a simple user identification system (using a global variable)
- Initializing the Mem0 client that will handle memory operations
### 2. Memory Tools with Function Decorators
The `@function_tool` decorator transforms Python functions into callable tools for the OpenAI agent. Here are the key memory tools:
#### Storing User Memories
```python
import logging
# Set up logging at the top of your file
logging.basicConfig(
level=logging.DEBUG,
format='%(asctime)s - %(name)s - %(levelname)s - %(message)s',
force=True
)
logger = logging.getLogger("memory_voice_agent")
# Then use logger in your function tools
@function_tool
async def save_memories(
memory: str
) -> str:
"""Store a user memory in memory."""
# This will be visible in your console
logger.debug(f"Saving memory: {memory} for user {USER_ID}")
# Store the preference in Mem0
memory_content = f"User memory - {memory}"
await mem0_client.add(
memory_content,
user_id=USER_ID,
)
return f"I've saved your memory: {memory}"
```
This function:
- Takes a memory string
- Creates a formatted memory string
- Stores it in Mem0 using the `add()` method
- Includes metadata to categorize the memory for easier retrieval
- Returns a confirmation message that the agent will speak
#### Finding Relevant Memories
```python
@function_tool
async def search_memories(
query: str
) -> str:
"""
Find memories relevant to the current conversation.
Args:
query: The search query to find relevant memories
"""
print(f"Finding memories related to: {query}")
results = await mem0_client.search(
query,
user_id=USER_ID,
limit=5,
threshold=0.7, # Higher threshold for more relevant results
output_format="v1.1"
)
# Format and return the results
if not results.get('results', []):
return "I don't have any relevant memories about this topic."
memories = [f"• {result['memory']}" for result in results.get('results', [])]
return "Here's what I remember that might be relevant:\n" + "\n".join(memories)
```
This tool:
- Takes a search query string
- Passes it to Mem0's semantic search to find related memories
- Sets a threshold for relevance to ensure quality results
- Returns a formatted list of relevant memories or a default message
### 3. Creating the Voice Agent
```python
def create_memory_voice_agent():
# Create the agent with memory-enabled tools
agent = Agent(
name="Memory Assistant",
instructions=prompt_with_handoff_instructions(
"""You're speaking to a human, so be polite and concise.
Always respond in clear, natural English.
You have the ability to remember information about the user.
Use the save_memories tool when the user shares an important information worth remembering.
Use the search_memories tool when you need context from past conversations or user asks you to recall something.
""",
),
model="gpt-4.1-nano-2025-04-14",
tools=[save_memories, search_memories],
)
return agent
```
This function:
- Creates an OpenAI Agent with specific instructions
- Configures it to use gpt-4.1-nano (you can use other models)
- Registers the memory-related tools with the agent
- Uses `prompt_with_handoff_instructions` to include standard voice agent behaviors
### 4. Microphone Recording Functionality
```python
async def record_from_microphone(duration=5, samplerate=24000):
"""Record audio from the microphone for a specified duration."""
print(f"Recording for {duration} seconds...")
# Create a buffer to store the recorded audio
frames = []
# Callback function to store audio data
def callback(indata, frames_count, time_info, status):
frames.append(indata.copy())
# Start recording
with sd.InputStream(samplerate=samplerate, channels=1, callback=callback, dtype=np.int16):
await asyncio.sleep(duration)
# Combine all frames into a single numpy array
audio_data = np.concatenate(frames)
return audio_data
```
This function:
- Creates a simple asynchronous microphone recording function
- Uses the sounddevice library to capture audio input
- Stores frames in a buffer during recording
- Combines frames into a single numpy array when complete
- Returns the audio data for processing
### 5. Main Loop and Voice Processing
```python
async def main():
# Create the agent
agent = create_memory_voice_agent()
# Set up the voice pipeline
pipeline = VoicePipeline(
workflow=SingleAgentVoiceWorkflow(agent)
)
# Configure TTS settings
pipeline.config.tts_settings.voice = "alloy"
pipeline.config.tts_settings.speed = 1.0
try:
while True:
# Get user input
print("\nPress Enter to start recording (or 'q' to quit)...")
user_input = input()
if user_input.lower() == 'q':
break
# Record and process audio
audio_data = await record_from_microphone(duration=5)
audio_input = AudioInput(buffer=audio_data)
result = await pipeline.run(audio_input)
# Play response and handle events
player = sd.OutputStream(samplerate=24000, channels=1, dtype=np.int16)
player.start()
agent_response = ""
print("\nAgent response:")
async for event in result.stream():
if event.type == "voice_stream_event_audio":
player.write(event.data)
elif event.type == "voice_stream_event_content":
content = event.data
agent_response += content
print(content, end="", flush=True)
# Save the agent's response to memory
if agent_response:
try:
await mem0_client.add(
f"Agent response: {agent_response}",
user_id=USER_ID,
metadata={"type": "agent_response"}
)
except Exception as e:
print(f"Failed to store memory: {e}")
except KeyboardInterrupt:
print("\nExiting...")
```
This main function orchestrates the entire process:
1. Creates the memory-enabled voice agent
2. Sets up the voice pipeline with TTS settings
3. Implements an interactive loop for recording and processing voice input
4. Handles streaming of response events (both audio and text)
5. Automatically saves the agent's responses to memory
6. Includes proper error handling and exit mechanisms
## Create a Memory-Enabled Voice Agent
Now that we've explained each component, here's the complete implementation that combines OpenAI Agents SDK for voice with Mem0's memory capabilities:
```python
import asyncio
import os
import logging
from typing import Optional, List, Dict, Any
import numpy as np
import sounddevice as sd
from pydantic import BaseModel
# OpenAI Agents SDK imports
from agents import (
Agent,
function_tool
)
from agents.voice import (
AudioInput,
SingleAgentVoiceWorkflow,
VoicePipeline
)
from agents.extensions.handoff_prompt import prompt_with_handoff_instructions
# Mem0 imports
from mem0 import AsyncMemoryClient
# Set up API keys (replace with your actual keys)
os.environ["OPENAI_API_KEY"] = "your-openai-api-key"
os.environ["MEM0_API_KEY"] = "your-mem0-api-key"
# Define a global user ID for simplicity
USER_ID = "voice_user"
# Initialize Mem0 client
mem0_client = AsyncMemoryClient()
# Create tools that utilize Mem0's memory
@function_tool
async def save_memories(
memory: str
) -> str:
"""
Store a user memory in memory.
Args:
memory: The memory to save
"""
print(f"Saving memory: {memory} for user {USER_ID}")
# Store the preference in Mem0
memory_content = f"User memory - {memory}"
await mem0_client.add(
memory_content,
user_id=USER_ID,
)
return f"I've saved your memory: {memory}"
@function_tool
async def search_memories(
query: str
) -> str:
"""
Find memories relevant to the current conversation.
Args:
query: The search query to find relevant memories
"""
print(f"Finding memories related to: {query}")
results = await mem0_client.search(
query,
user_id=USER_ID,
limit=5,
threshold=0.7, # Higher threshold for more relevant results
output_format="v1.1"
)
# Format and return the results
if not results.get('results', []):
return "I don't have any relevant memories about this topic."
memories = [f"• {result['memory']}" for result in results.get('results', [])]
return "Here's what I remember that might be relevant:\n" + "\n".join(memories)
# Create the agent with memory-enabled tools
def create_memory_voice_agent():
# Create the agent with memory-enabled tools
agent = Agent(
name="Memory Assistant",
instructions=prompt_with_handoff_instructions(
"""You're speaking to a human, so be polite and concise.
Always respond in clear, natural English.
You have the ability to remember information about the user.
Use the save_memories tool when the user shares an important information worth remembering.
Use the search_memories tool when you need context from past conversations or user asks you to recall something.
""",
),
model="gpt-4.1-nano-2025-04-14",
tools=[save_memories, search_memories],
)
return agent
async def record_from_microphone(duration=5, samplerate=24000):
"""Record audio from the microphone for a specified duration."""
print(f"Recording for {duration} seconds...")
# Create a buffer to store the recorded audio
frames = []
# Callback function to store audio data
def callback(indata, frames_count, time_info, status):
frames.append(indata.copy())
# Start recording
with sd.InputStream(samplerate=samplerate, channels=1, callback=callback, dtype=np.int16):
await asyncio.sleep(duration)
# Combine all frames into a single numpy array
audio_data = np.concatenate(frames)
return audio_data
async def main():
print("Starting Memory Voice Agent")
# Create the agent and context
agent = create_memory_voice_agent()
# Set up the voice pipeline
pipeline = VoicePipeline(
workflow=SingleAgentVoiceWorkflow(agent)
)
# Configure TTS settings
pipeline.config.tts_settings.voice = "alloy"
pipeline.config.tts_settings.speed = 1.0
try:
while True:
# Get user input
print("\nPress Enter to start recording (or 'q' to quit)...")
user_input = input()
if user_input.lower() == 'q':
break
# Record and process audio
audio_data = await record_from_microphone(duration=5)
audio_input = AudioInput(buffer=audio_data)
print("Processing your request...")
# Process the audio input
result = await pipeline.run(audio_input)
# Create an audio player
player = sd.OutputStream(samplerate=24000, channels=1, dtype=np.int16)
player.start()
# Store the agent's response for adding to memory
agent_response = ""
print("\nAgent response:")
# Play the audio stream as it comes in
async for event in result.stream():
if event.type == "voice_stream_event_audio":
player.write(event.data)
elif event.type == "voice_stream_event_content":
# Accumulate and print the text response
content = event.data
agent_response += content
print(content, end="", flush=True)
print("\n")
# Example of saving the conversation to Mem0 after completion
if agent_response:
try:
await mem0_client.add(
f"Agent response: {agent_response}",
user_id=USER_ID,
metadata={"type": "agent_response"}
)
except Exception as e:
print(f"Failed to store memory: {e}")
except KeyboardInterrupt:
print("\nExiting...")
if __name__ == "__main__":
asyncio.run(main())
```
## Key Features of This Implementation
This implementation offers several key features:
1. **Simplified User Management**: Uses a global `USER_ID` variable for simplicity, but can be extended to manage multiple users.
2. **Real Microphone Input**: Includes a `record_from_microphone()` function that captures actual voice input from your microphone.
3. **Interactive Voice Loop**: Implements a continuous interaction loop, allowing for multiple back-and-forth exchanges.
4. **Memory Management Tools**:
- `save_memories`: Stores user memories in Mem0
- `search_memories`: Searches for relevant past information
5. **Voice Configuration**: Demonstrates how to configure TTS settings for the voice response.
## Running the Example
To run this example:
1. Replace the placeholder API keys with your actual keys
2. Make sure your microphone is properly connected
3. Run the script with Python 3.10 or newer
4. Press Enter to start recording, then speak your request
5. Press 'q' to quit the application
The agent will listen to your request, process it through the OpenAI model, utilize Mem0 for memory operations as needed, and respond both through text output and voice speech.
## Best Practices for Voice Agents with Memory
1. **Optimizing Memory for Voice**: Keep memories concise and relevant for voice responses.
2. **Forgetting Mechanism**: Implement a way to delete or expire memories that are no longer relevant.
3. **Context Preservation**: Store enough context with each memory to make retrieval effective.
4. **Error Handling**: Implement robust error handling for memory operations, as voice interactions should continue smoothly even if memory operations fail.
## Conclusion
By combining OpenAI's Agents SDK with Mem0's memory capabilities, you can create voice agents that maintain persistent memory of user preferences and past interactions. This significantly enhances the user experience by making conversations more natural and personalized.
As you build your voice application, experiment with different memory strategies and filtering approaches to find the optimal balance between comprehensive memory and efficient retrieval for your specific use case.
## Debugging Function Tools
When working with the OpenAI Agents SDK, you might notice that regular `print()` statements inside `@function_tool` decorated functions don't appear in your console output. This is because the Agents SDK captures and redirects standard output when executing these functions.
To effectively debug your function tools, use Python's `logging` module instead:
```python
import logging
# Set up logging at the top of your file
logging.basicConfig(
level=logging.DEBUG,
format='%(asctime)s - %(name)s - %(levelname)s - %(message)s',
force=True
)
logger = logging.getLogger("memory_voice_agent")
# Then use logger in your function tools
@function_tool
async def save_memories(
memory: str
) -> str:
"""Store a user memory in memory."""
# This will be visible in your console
logger.debug(f"Saving memory: {memory} for user {USER_ID}")
# Rest of your function...
```
-72
View File
@@ -1,72 +0,0 @@
---
title: Mem0 with Ollama
---
## Running Mem0 Locally with Ollama
Mem0 can be utilized entirely locally by leveraging Ollama for both the embedding model and the language model (LLM). This guide will walk you through the necessary steps and provide the complete code to get you started.
### Overview
By using Ollama, you can run Mem0 locally, which allows for greater control over your data and models. This setup uses Ollama for both the embedding model and the language model, providing a fully local solution.
### Setup
Before you begin, ensure you have Mem0 and Ollama installed and properly configured on your local machine.
### Full Code Example
Below is the complete code to set up and use Mem0 locally with Ollama:
```python
from mem0 import Memory
config = {
"vector_store": {
"provider": "qdrant",
"config": {
"collection_name": "test",
"host": "localhost",
"port": 6333,
"embedding_model_dims": 768, # Change this according to your local model's dimensions
},
},
"llm": {
"provider": "ollama",
"config": {
"model": "llama3.1:latest",
"temperature": 0,
"max_tokens": 2000,
"ollama_base_url": "http://localhost:11434", # Ensure this URL is correct
},
},
"embedder": {
"provider": "ollama",
"config": {
"model": "nomic-embed-text:latest",
# Alternatively, you can use "snowflake-arctic-embed:latest"
"ollama_base_url": "http://localhost:11434",
},
},
}
# Initialize Memory with the configuration
m = Memory.from_config(config)
# Add a memory
m.add("I'm visiting Paris", user_id="john")
# Retrieve memories
memories = m.get_all(user_id="john")
```
### Key Points
- **Configuration**: The setup involves configuring the vector store, language model, and embedding model to use local resources.
- **Vector Store**: Qdrant is used as the vector store, running on localhost.
- **Language Model**: Ollama is used as the LLM provider, with the "llama3.1:latest" model.
- **Embedding Model**: Ollama is also used for embeddings, with the "nomic-embed-text:latest" model.
### Conclusion
This local setup of Mem0 using Ollama provides a fully self-contained solution for memory management and AI interactions. It allows for greater control over your data and models while still leveraging the powerful capabilities of Mem0.
@@ -1,218 +0,0 @@
---
title: Memory-Guided Content Writing
---
This guide demonstrates how to leverage **Mem0** to streamline content writing by applying your unique writing style and preferences using persistent memory.
## Why Use Mem0?
Integrating Mem0 into your writing workflow helps you:
1. **Store persistent writing preferences** ensuring consistent tone, formatting, and structure.
2. **Automate content refinement** by retrieving preferences when rewriting or reviewing content.
3. **Scale your writing style** so it applies consistently across multiple documents or sessions.
## Setup
```python
import os
from openai import OpenAI
from mem0 import MemoryClient
os.environ["MEM0_API_KEY"] = "your-mem0-api-key"
os.environ["OPENAI_API_KEY"] = "your-openai-api-key"
# Set up Mem0 and OpenAI client
client = MemoryClient()
openai = OpenAI()
USER_ID = "content_writer"
RUN_ID = "smart_editing_session"
```
## **Storing Your Writing Preferences in Mem0**
```python
def store_writing_preferences():
"""Store your writing preferences in Mem0."""
preferences = """My writing preferences:
1. Use headings and sub-headings for structure.
2. Keep paragraphs concise (8–10 sentences max).
3. Incorporate specific numbers and statistics.
4. Provide concrete examples.
5. Use bullet points for clarity.
6. Avoid jargon and buzzwords."""
messages = [
{"role": "user", "content": "Here are my writing style preferences."},
{"role": "assistant", "content": preferences}
]
response = client.add(
messages,
user_id=USER_ID,
run_id=RUN_ID,
metadata={"type": "preferences", "category": "writing_style"}
)
return response
```
## **Editing Content Using Stored Preferences**
```python
def apply_writing_style(original_content):
"""Use preferences stored in Mem0 to guide content rewriting."""
results = client.search(
query="What are my writing style preferences?",
version="v2",
filters={
"AND": [
{
"user_id": USER_ID
},
{
"run_id": RUN_ID
}
]
},
)
if not results:
print("No preferences found.")
return None
preferences = "\n".join(r["memory"] for r in results.get('results', []))
system_prompt = f"""
You are a writing assistant.
Apply the following writing style preferences to improve the user's content:
Preferences:
{preferences}
"""
messages = [
{"role": "system", "content": system_prompt},
{"role": "user", "content": f"""Original Content:
{original_content}"""}
]
response = openai.chat.completions.create(
model="gpt-4.1-nano-2025-04-14",
messages=messages
)
clean_response = response.choices[0].message.content.strip()
return clean_response
```
## **Complete Workflow: Content Editing**
```python
def content_writing_workflow(content):
"""Automated workflow for editing a document based on writing preferences."""
# Store writing preferences (if not already stored)
store_writing_preferences() # Ideally done once, or with a conditional check
# Edit the document with Mem0 preferences
edited_content = apply_writing_style(content)
if not edited_content:
return "Failed to edit document."
# Display results
print("\n=== ORIGINAL DOCUMENT ===\n")
print(content)
print("\n=== EDITED DOCUMENT ===\n")
print(edited_content)
return edited_content
```
## **Example Usage**
```python
# Define your document
original_content = """Project Proposal
The following proposal outlines our strategy for the Q3 marketing campaign.
We believe this approach will significantly increase our market share.
Increase brand awareness
Boost sales by 15%
Expand our social media following
We plan to launch the campaign in July and continue through September.
"""
# Run the workflow
result = content_writing_workflow(original_content)
```
## **Expected Output**
Your document will be transformed into a structured, well-formatted version based on your preferences.
### **Original Document**
```
Project Proposal
The following proposal outlines our strategy for the Q3 marketing campaign.
We believe this approach will significantly increase our market share.
Increase brand awareness
Boost sales by 15%
Expand our social media following
We plan to launch the campaign in July and continue through September.
```
### **Edited Document**
```
# **Project Proposal**
## **Q3 Marketing Campaign Strategy**
This proposal outlines our strategy for the Q3 marketing campaign. We aim to significantly increase our market share with this approach.
### **Objectives**
- **Increase Brand Awareness**: Implement targeted advertising and community engagement to enhance visibility.
- **Boost Sales by 15%**: Increase sales by 15% compared to Q2 figures.
- **Expand Social Media Following**: Grow our social media audience by 20%.
### **Timeline**
- **Launch Date**: July
- **Duration**: July – September
### **Key Actions**
- **Targeted Advertising**: Utilize platforms like Google Ads and Facebook to reach specific demographics.
- **Community Engagement**: Host webinars and live Q&A sessions.
- **Content Creation**: Produce engaging videos and infographics.
### **Supporting Data**
- **Previous Campaign Success**: Our Q2 campaign increased sales by 12%. We will refine similar strategies for Q3.
- **Social Media Growth**: Last year, our Instagram followers grew by 25% during a similar campaign.
### **Conclusion**
We believe this strategy will effectively increase our market share. To achieve these goals, we need your support and collaboration. Let’s work together to make this campaign a success. Please review the proposal and provide your feedback by the end of the week.
```
Mem0 enables a seamless, intelligent content-writing workflow, perfect for content creators, marketers, and technical writers looking to scale their personal tone and structure across work.
## Help & Resources
- [Mem0 Platform](https://app.mem0.ai/)
<Snippet file="get-help.mdx" />
-31
View File
@@ -1,31 +0,0 @@
---
title: Multimodal Demo with Mem0
---
Enhance your AI interactions with **Mem0**'s multimodal capabilities. Mem0 now supports image understanding, allowing for richer context and more natural interactions across supported AI platforms.
> Experience the power of multimodal AI! Test out Mem0's image understanding capabilities at [multimodal-demo.mem0.ai](https://multimodal-demo.mem0.ai)
## Features
- **Image Understanding**: Share and discuss images with AI assistants while maintaining context.
- **Smart Visual Context**: Automatically capture and reference visual elements in conversations.
- **Cross-Modal Memory**: Link visual and textual information seamlessly in your memory layer.
- **Cross-Session Recall**: Reference previously discussed visual content across different conversations.
- **Seamless Integration**: Works naturally with existing chat interfaces for a smooth experience.
## How It Works
1. **Upload Visual Content**: Simply drag and drop or paste images into your conversations.
2. **Natural Interaction**: Discuss the visual content naturally with AI assistants.
3. **Memory Integration**: Visual context is automatically stored and linked with your conversation history.
4. **Persistent Recall**: Retrieve and reference past visual content effortlessly.
## Demo Video
<iframe width="700" height="400" src="https://www.youtube.com/embed/2Md5AEFVpmg?si=rXXupn6CiDUPJsi3" title="YouTube video player" frameborder="0" allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture; web-share" referrerpolicy="strict-origin-when-cross-origin" allowfullscreen></iframe>
## Try It Out
Visit [multimodal-demo.mem0.ai](https://multimodal-demo.mem0.ai) to experience Mem0's multimodal capabilities firsthand. Upload images and see how Mem0 understands and remembers visual context across your conversations.
-312
View File
@@ -1,312 +0,0 @@
---
title: OpenAI Inbuilt Tools
---
Integrate Mem0’s memory capabilities with OpenAI’s Inbuilt Tools to create AI agents with persistent memory.
## Getting Started
### Installation
```bash
npm install mem0ai openai zod
```
## Environment Setup
Save your Mem0 and OpenAI API keys in a `.env` file:
```
MEM0_API_KEY=your_mem0_api_key
OPENAI_API_KEY=your_openai_api_key
```
Get your Mem0 API key from the [Mem0 Dashboard](https://app.mem0.ai/dashboard/api-keys).
### Configuration
```javascript
const mem0Config = {
apiKey: process.env.MEM0_API_KEY,
user_id: "sample-user",
};
const openAIClient = new OpenAI();
const mem0Client = new MemoryClient(mem0Config);
```
### Adding Memories
Store user preferences, past interactions, or any relevant information:
<CodeGroup>
```javascript JavaScript
async function addUserPreferences() {
const mem0Client = new MemoryClient(mem0Config);
const userPreferences = "I Love BMW, Audi and Porsche. I Hate Mercedes. I love Red cars and Maroon cars. I have a budget of 120K to 150K USD. I like Audi the most.";
await mem0Client.add([{
role: "user",
content: userPreferences,
}], mem0Config);
}
await addUserPreferences();
```
```json Output (Memories)
[
{
"id": "ff9f3367-9e83-415d-b9c5-dc8befd9a4b4",
"data": { "memory": "Loves BMW, Audi, and Porsche" },
"event": "ADD"
},
{
"id": "04172ce6-3d7b-45a3-b4a1-ee9798593cb4",
"data": { "memory": "Hates Mercedes" },
"event": "ADD"
},
{
"id": "db363a5d-d258-4953-9e4c-777c120de34d",
"data": { "memory": "Loves red cars and maroon cars" },
"event": "ADD"
},
{
"id": "5519aaad-a2ac-4c0d-81d7-0d55c6ecdba8",
"data": { "memory": "Has a budget of 120K to 150K USD" },
"event": "ADD"
},
{
"id": "523b7693-7344-4563-922f-5db08edc8634",
"data": { "memory": "Likes Audi the most" },
"event": "ADD"
}
]
```
</CodeGroup>
### Retrieving Memories
Search for relevant memories based on the current user input:
```javascript
const relevantMemories = await mem0Client.search(userInput, mem0Config);
```
### Structured Responses with Zod
Define structured response schemas to get consistent output formats:
```javascript
// Define the schema for a car recommendation
const CarSchema = z.object({
car_name: z.string(),
car_price: z.string(),
car_url: z.string(),
car_image: z.string(),
car_description: z.string(),
});
// Schema for a list of car recommendations
const Cars = z.object({
cars: z.array(CarSchema),
});
// Create a function tool based on the schema
const carRecommendationTool = zodResponsesFunction({
name: "carRecommendations",
parameters: Cars
});
// Use the tool in your OpenAI request
const response = await openAIClient.responses.create({
model: "gpt-4.1-nano-2025-04-14",
tools: [{ type: "web_search_preview" }, carRecommendationTool],
input: `${getMemoryString(relevantMemories)}\n${userInput}`,
});
```
### Using Web Search
Combine memory with web search for up-to-date recommendations:
```javascript
const response = await openAIClient.responses.create({
model: "gpt-4.1-nano-2025-04-14",
tools: [{ type: "web_search_preview" }, carRecommendationTool],
input: `${getMemoryString(relevantMemories)}\n${userInput}`,
});
```
## Examples
### Complete Car Recommendation System
```javascript
import MemoryClient from "mem0ai";
import { OpenAI } from "openai";
import { zodResponsesFunction } from "openai/helpers/zod";
import { z } from "zod";
import dotenv from 'dotenv';
dotenv.config();
const mem0Config = {
apiKey: process.env.MEM0_API_KEY,
user_id: "sample-user",
};
async function run() {
// Responses without memories
console.log("\n\nRESPONSES WITHOUT MEMORIES\n\n");
await main();
// Adding sample memories
await addSampleMemories();
// Responses with memories
console.log("\n\nRESPONSES WITH MEMORIES\n\n");
await main(true);
}
// OpenAI Response Schema
const CarSchema = z.object({
car_name: z.string(),
car_price: z.string(),
car_url: z.string(),
car_image: z.string(),
car_description: z.string(),
});
const Cars = z.object({
cars: z.array(CarSchema),
});
async function main(memory = false) {
const openAIClient = new OpenAI();
const mem0Client = new MemoryClient(mem0Config);
const input = "Suggest me some cars that I can buy today.";
const tool = zodResponsesFunction({ name: "carRecommendations", parameters: Cars });
// Store the user input as a memory
await mem0Client.add([{
role: "user",
content: input,
}], mem0Config);
// Search for relevant memories
let relevantMemories = []
if (memory) {
relevantMemories = await mem0Client.search(input, mem0Config);
}
const response = await openAIClient.responses.create({
model: "gpt-4.1-nano-2025-04-14",
tools: [{ type: "web_search_preview" }, tool],
input: `${getMemoryString(relevantMemories)}\n${input}`,
});
console.log(response.output);
}
async function addSampleMemories() {
const mem0Client = new MemoryClient(mem0Config);
const myInterests = "I Love BMW, Audi and Porsche. I Hate Mercedes. I love Red cars and Maroon cars. I have a budget of 120K to 150K USD. I like Audi the most.";
await mem0Client.add([{
role: "user",
content: myInterests,
}], mem0Config);
}
const getMemoryString = (memories) => {
const MEMORY_STRING_PREFIX = "These are the memories I have stored. Give more weightage to the question by users and try to answer that first. You have to modify your answer based on the memories I have provided. If the memories are irrelevant you can ignore them. Also don't reply to this section of the prompt, or the memories, they are only for your reference. The MEMORIES of the USER are: \n\n";
const memoryString = (memories?.results || memories).map((mem) => `${mem.memory}`).join("\n") ?? "";
return memoryString.length > 0 ? `${MEMORY_STRING_PREFIX}${memoryString}` : "";
};
run().catch(console.error);
```
### Responses
<CodeGroup>
```json Without Memories
{
"cars": [
{
"car_name": "Toyota Camry",
"car_price": "$25,000",
"car_url": "https://www.toyota.com/camry/",
"car_image": "https://link-to-toyota-camry-image.com",
"car_description": "Reliable mid-size sedan with great fuel efficiency."
},
{
"car_name": "Honda Accord",
"car_price": "$26,000",
"car_url": "https://www.honda.com/accord/",
"car_image": "https://link-to-honda-accord-image.com",
"car_description": "Comfortable and spacious with advanced safety features."
},
{
"car_name": "Ford Mustang",
"car_price": "$28,000",
"car_url": "https://www.ford.com/mustang/",
"car_image": "https://link-to-ford-mustang-image.com",
"car_description": "Iconic sports car with powerful engine options."
},
{
"car_name": "Tesla Model 3",
"car_price": "$38,000",
"car_url": "https://www.tesla.com/model3",
"car_image": "https://link-to-tesla-model3-image.com",
"car_description": "Electric vehicle with advanced technology and long range."
},
{
"car_name": "Chevrolet Equinox",
"car_price": "$24,000",
"car_url": "https://www.chevrolet.com/equinox/",
"car_image": "https://link-to-chevron-equinox-image.com",
"car_description": "Compact SUV with a spacious interior and user-friendly technology."
}
]
}
```
```json With Memories
{
"cars": [
{
"car_name": "Audi RS7",
"car_price": "$118,500",
"car_url": "https://www.audiusa.com/us/web/en/models/rs7/2023/overview.html",
"car_image": "https://www.audiusa.com/content/dam/nemo/us/models/rs7/my23/gallery/1920x1080_AOZ_A717_191004.jpg",
"car_description": "The Audi RS7 is a high-performance hatchback with a sleek design, powerful 591-hp twin-turbo V8, and luxurious interior. It's available in various colors including red."
},
{
"car_name": "Porsche Panamera GTS",
"car_price": "$129,300",
"car_url": "https://www.porsche.com/usa/models/panamera/panamera-models/panamera-gts/",
"car_image": "https://files.porsche.com/filestore/image/multimedia/noneporsche-panamera-gts-sample-m02-high/normal/8a6327c3-6c7f-4c6f-a9a8-fb9f58b21795;sP;twebp/porsche-normal.webp",
"car_description": "The Porsche Panamera GTS is a luxury sports sedan with a 473-hp V8 engine, exquisite handling, and available in stunning red. Balances sportiness and comfort."
},
{
"car_name": "BMW M5",
"car_price": "$105,500",
"car_url": "https://www.bmwusa.com/vehicles/m-models/m5/sedan/overview.html",
"car_image": "https://www.bmwusa.com/content/dam/bmwusa/M/m5/2023/bmw-my23-m5-sapphire-black-twilight-purple-exterior-02.jpg",
"car_description": "The BMW M5 is a powerhouse sedan with a 600-hp V8 engine, known for its great handling and luxury. It comes in several distinctive colors including maroon."
}
]
}
```
</CodeGroup>
## Resources
- [Mem0 Documentation](https://docs.mem0.ai)
- [Mem0 Dashboard](https://app.mem0.ai/dashboard)
- [API Reference](https://docs.mem0.ai/api-reference)
- [OpenAI Documentation](https://platform.openai.com/docs)
-111
View File
@@ -1,111 +0,0 @@
---
title: Personalized AI Tutor
---
You can create a personalized AI Tutor using Mem0. This guide will walk you through the necessary steps and provide the complete code to get you started.
## Overview
The Personalized AI Tutor leverages Mem0 to retain information across interactions, enabling a tailored learning experience. By integrating with OpenAI's GPT-4 model, the tutor can provide detailed and context-aware responses to user queries.
## Setup
Before you begin, ensure you have the required dependencies installed. You can install the necessary packages using pip:
```bash
pip install openai mem0ai
```
## Full Code Example
Below is the complete code to create and interact with a Personalized AI Tutor using Mem0:
```python
import os
from openai import OpenAI
from mem0 import Memory
# Set the OpenAI API key
os.environ['OPENAI_API_KEY'] = 'sk-xxx'
# Initialize the OpenAI client
client = OpenAI()
class PersonalAITutor:
def __init__(self):
"""
Initialize the PersonalAITutor with memory configuration and OpenAI client.
"""
config = {
"vector_store": {
"provider": "qdrant",
"config": {
"host": "localhost",
"port": 6333,
}
},
}
self.memory = Memory.from_config(config)
self.client = client
self.app_id = "app-1"
def ask(self, question, user_id=None):
"""
Ask a question to the AI and store the relevant facts in memory
:param question: The question to ask the AI.
:param user_id: Optional user ID to associate with the memory.
"""
# Start a streaming response request to the AI
response = self.client.responses.create(
model="gpt-4.1-nano-2025-04-14",
instructions="You are a personal AI Tutor.",
input=question,
stream=True
)
# Store the question in memory
self.memory.add(question, user_id=user_id, metadata={"app_id": self.app_id})
# Print the response from the AI in real-time
for event in response:
if event.type == "response.output_text.delta":
print(event.delta, end="")
def get_memories(self, user_id=None):
"""
Retrieve all memories associated with the given user ID.
:param user_id: Optional user ID to filter memories.
:return: List of memories.
"""
return self.memory.get_all(user_id=user_id)
# Instantiate the PersonalAITutor
ai_tutor = PersonalAITutor()
# Define a user ID
user_id = "john_doe"
# Ask a question
ai_tutor.ask("I am learning introduction to CS. What is queue? Briefly explain.", user_id=user_id)
```
### Fetching Memories
You can fetch all the memories at any point in time using the following code:
```python
memories = ai_tutor.get_memories(user_id=user_id)
for m in memories['results']:
print(m['memory'])
```
### Key Points
- **Initialization**: The PersonalAITutor class is initialized with the necessary memory configuration and OpenAI client setup.
- **Asking Questions**: The ask method sends a question to the AI and stores the relevant information in memory.
- **Retrieving Memories**: The get_memories method fetches all stored memories associated with a user.
### Conclusion
As the conversation progresses, Mem0's memory automatically updates based on the interactions, providing a continuously improving personalized learning experience. This setup ensures that the AI Tutor can offer contextually relevant and accurate responses, enhancing the overall educational process.
@@ -1,202 +0,0 @@
---
title: Personal AI Travel Assistant
---
Create a personalized AI Travel Assistant using Mem0. This guide provides step-by-step instructions and the complete code to get you started.
## Overview
The Personalized AI Travel Assistant uses Mem0 to store and retrieve information across interactions, enabling a tailored travel planning experience. It integrates with OpenAI's GPT-4 model to provide detailed and context-aware responses to user queries.
## Setup
Install the required dependencies using pip:
```bash
pip install openai mem0ai
```
## Full Code Example
Here's the complete code to create and interact with a Personalized AI Travel Assistant using Mem0:
<CodeGroup>
```python After v1.1
import os
from openai import OpenAI
from mem0 import Memory
# Set the OpenAI API key
os.environ['OPENAI_API_KEY'] = "sk-xxx"
config = {
"llm": {
"provider": "openai",
"config": {
"model": "gpt-4.1-nano-2025-04-14",
"temperature": 0.1,
"max_tokens": 2000,
}
},
"embedder": {
"provider": "openai",
"config": {
"model": "text-embedding-3-large"
}
},
"vector_store": {
"provider": "qdrant",
"config": {
"collection_name": "test",
"embedding_model_dims": 3072,
}
},
"version": "v1.1",
}
class PersonalTravelAssistant:
def __init__(self):
self.client = OpenAI()
self.memory = Memory.from_config(config)
self.messages = [{"role": "system", "content": "You are a personal AI Assistant."}]
def ask_question(self, question, user_id):
# Fetch previous related memories
previous_memories = self.search_memories(question, user_id=user_id)
# Build the prompt
system_message = "You are a personal AI Assistant."
if previous_memories:
prompt = f"{system_message}\n\nUser input: {question}\nPrevious memories: {', '.join(previous_memories)}"
else:
prompt = f"{system_message}\n\nUser input: {question}"
# Generate response using Responses API
response = self.client.responses.create(
model="gpt-4.1-nano-2025-04-14",
input=prompt
)
# Extract answer from the response
answer = response.output[0].content[0].text
# Store the question in memory
self.memory.add(question, user_id=user_id)
return answer
def get_memories(self, user_id):
memories = self.memory.get_all(user_id=user_id)
return [m['memory'] for m in memories['results']]
def search_memories(self, query, user_id):
memories = self.memory.search(query, user_id=user_id)
return [m['memory'] for m in memories['results']]
# Usage example
user_id = "traveler_123"
ai_assistant = PersonalTravelAssistant()
def main():
while True:
question = input("Question: ")
if question.lower() in ['q', 'exit']:
print("Exiting...")
break
answer = ai_assistant.ask_question(question, user_id=user_id)
print(f"Answer: {answer}")
memories = ai_assistant.get_memories(user_id=user_id)
print("Memories:")
for memory in memories:
print(f"- {memory}")
print("-----")
if __name__ == "__main__":
main()
```
```python Before v1.1
import os
from openai import OpenAI
from mem0 import Memory
# Set the OpenAI API key
os.environ['OPENAI_API_KEY'] = 'sk-xxx'
class PersonalTravelAssistant:
def __init__(self):
self.client = OpenAI()
self.memory = Memory()
self.messages = [{"role": "system", "content": "You are a personal AI Assistant."}]
def ask_question(self, question, user_id):
# Fetch previous related memories
previous_memories = self.search_memories(question, user_id=user_id)
prompt = question
if previous_memories:
prompt = f"User input: {question}\n Previous memories: {previous_memories}"
self.messages.append({"role": "user", "content": prompt})
# Generate response using gpt-4.1-nano
response = self.client.chat.completions.create(
model="gpt-4.1-nano-2025-04-14"2025-04-14",
messages=self.messages
)
answer = response.choices[0].message.content
self.messages.append({"role": "assistant", "content": answer})
# Store the question in memory
self.memory.add(question, user_id=user_id)
return answer
def get_memories(self, user_id):
memories = self.memory.get_all(user_id=user_id)
return [m['memory'] for m in memories.get('results', [])]
def search_memories(self, query, user_id):
memories = self.memory.search(query, user_id=user_id)
return [m['memory'] for m in memories.get('results', [])]
# Usage example
user_id = "traveler_123"
ai_assistant = PersonalTravelAssistant()
def main():
while True:
question = input("Question: ")
if question.lower() in ['q', 'exit']:
print("Exiting...")
break
answer = ai_assistant.ask_question(question, user_id=user_id)
print(f"Answer: {answer}")
memories = ai_assistant.get_memories(user_id=user_id)
print("Memories:")
for memory in memories:
print(f"- {memory}")
print("-----")
if __name__ == "__main__":
main()
```
</CodeGroup>
## Key Components
- **Initialization**: The `PersonalTravelAssistant` class is initialized with the OpenAI client and Mem0 memory setup.
- **Asking Questions**: The `ask_question` method sends a question to the AI, incorporates previous memories, and stores new information.
- **Memory Management**: The `get_memories` and search_memories methods handle retrieval and searching of stored memories.
## Usage
1. Set your OpenAI API key in the environment variable.
2. Instantiate the `PersonalTravelAssistant`.
3. Use the `main()` function to interact with the assistant in a loop.
## Conclusion
This Personalized AI Travel Assistant leverages Mem0's memory capabilities to provide context-aware responses. As you interact with it, the assistant learns and improves, offering increasingly personalized travel advice and information.
@@ -1,67 +0,0 @@
---
title: Personalized Deep Research
---
Deep Research is an intelligent agent that synthesizes large amounts of online data and completes complex research tasks, customized to your unique preferences and insights. Built on Mem0's technology, it enhances AI-driven online exploration with personalized memories.
You can checkout GitHub repositry here: [Personalized Deep Research](https://github.com/mem0ai/personalized-deep-research/tree/mem0)
## Overview
Deep Research leverages Mem0's memory capabilities to:
- Synthesize large amounts of online data
- Complete complex research tasks
- Customize results to your preferences
- Store and utilize personal insights
- Maintain context across research sessions
## Demo
Watch Deep Research in action:
<iframe
width="700"
height="400"
src="https://www.youtube.com/embed/8vQlCtXzF60?si=b8iTOgummAVzR7ia"
title="YouTube video player"
frameborder="0"
allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture; web-share"
referrerpolicy="strict-origin-when-cross-origin"
allowfullscreen
></iframe>
## Features
### 1. Personalized Research
- Analyzes your background and expertise
- Tailors research depth and complexity to your level
- Incorporates your previous research context
### 2. Comprehensive Data Synthesis
- Processes multiple online sources
- Extracts relevant information
- Provides coherent summaries
### 3. Memory Integration
- Stores research findings for future reference
- Maintains context across sessions
- Links related research topics
### 4. Interactive Exploration
- Allows real-time query refinement
- Supports follow-up questions
- Enables deep-diving into specific areas
## Use Cases
- **Academic Research**: Literature reviews, thesis research, paper writing
- **Market Research**: Industry analysis, competitor research, trend identification
- **Technical Research**: Technology evaluation, solution comparison
- **Business Research**: Strategic planning, opportunity analysis
## Try It Out
> To try it yourself, clone the repository and follow the instructions in the README to run it locally or deploy it.
- [Personalized Deep Research GitHub](https://github.com/mem0ai/personalized-deep-research/tree/mem0)
@@ -1,190 +0,0 @@
---
title: 'Personalized Search with Tavily'
---
<Snippet file="security-compliance.mdx" />
Imagine asking a search assistant for "coffee shops nearby" and instead of generic results, it shows remote-work-friendly cafes with great wifi in your city because it remembers you mentioned working remotely before. Or when you search for "lunchbox ideas for kids" it knows you have a **7-year-old daughter** and recommends **peanut-free options** that align with her allergy.
That's what we are going to build today, a **Personalized Search Assistant** powered by **Mem0** for memory and [Tavily](https://tavily.com) for real-time search.
## Why Personalized Search
Most assistants treat every query like they’ve never seen you before. That means repeating yourself about your location, diet, or preferences, and getting results that feel generic.
- With **Mem0**, your assistant builds a memory of the user’s world.
- With **Tavily**, it fetches fresh and accurate results in real time.
Together, they make every interaction **smarter, faster, and more personal**.
## Prerequisites
Before you begin, make sure you have:
1. Installed the dependencies:
```bash
pip install langchain mem0ai langchain-tavily langchain-openai
```
2. Set up your API keys in a .env file:
```bash
OPENAI_API_KEY=your-openai-key
TAVILY_API_KEY=your-tavily-key
MEM0_API_KEY=your-mem0-key
```
## Code Walkthrough
Let’s break down the main components.
### 1: Initialize Mem0 with Custom Instructions
We configure Mem0 with custom instructions that guide it to infer user memories tailored specifically for our usecase.
```python
from mem0 import MemoryClient
mem0_client = MemoryClient()
mem0_client.project.update(
custom_instructions='''
INFER THE MEMORIES FROM USER QUERIES EVEN IF IT'S A QUESTION.
We are building personalized search for which we need to understand about user's preferences and life
and extract facts and memories accordingly.
'''
)
```
Now, if a user casually mentions "I need to pick up my daughter", or "What's the weather at Los Angeles", Mem0 remembers they have a daughter or user is somewhat interested/connected with Los Angeles in terms of location, those will be referred for future searches.
### 2. Simulating User History
To test personalization, we preload some sample conversation history for a user:
```python
def setup_user_history(user_id):
conversations = [
[{"role": "user", "content": "What will be the weather today at Los Angeles? I need to pick up my daughter from office."},
{"role": "assistant", "content": "I'll check the weather in LA for you."}],
[{"role": "user", "content": "I'm looking for vegan restaurants in Santa Monica"},
{"role": "assistant", "content": "I'll find great vegan options in Santa Monica."}],
[{"role": "user", "content": "My 7-year-old daughter is allergic to peanuts"},
{"role": "assistant", "content": "I'll remember to check for peanut-free options."}],
[{"role": "user", "content": "I work remotely and need coffee shops with good wifi"},
{"role": "assistant", "content": "I'll find remote-work-friendly coffee shops."}],
[{"role": "user", "content": "We love hiking and outdoor activities on weekends"},
{"role": "assistant", "content": "Great! I'll keep your outdoor activity preferences in mind."}],
]
for conversation in conversations:
mem0_client.add(conversation, user_id=user_id, output_format="v1.1")
```
This gives the agent a baseline understanding of the user’s lifestyle and needs.
### 3. Retrieving User Context from Memory
When a user makes a new search query, we retrieve relevant memories to enhance the search query:
```python
def get_user_context(user_id, query):
filters = {"AND": [{"user_id": user_id}]}
user_memories = mem0_client.search(query=query, version="v2", filters=filters)
if user_memories:
context = "\n".join([f"- {memory['memory']}" for memory in user_memories])
return context
else:
return "No previous user context available."
```
This context is injected into the search agent so results are personalized.
### 4. Creating the Personalized Search Agent
The agent uses Tavily search, but always augments search queries with user context:
```python
def create_personalized_search_agent(user_context):
tavily_search = TavilySearch(
max_results=10,
search_depth="advanced",
include_answer=True,
topic="general"
)
tools = [tavily_search]
prompt = ChatPromptTemplate.from_messages([
("system", f"""You are a personalized search assistant.
USER CONTEXT AND PREFERENCES:
{user_context}
YOUR ROLE:
1. Analyze the user's query and context.
2. Enhance the query with relevant personal memories.
3. Always use tavily_search for results.
4. Explain which memories influenced personalization.
"""),
MessagesPlaceholder(variable_name="messages"),
MessagesPlaceholder(variable_name="agent_scratchpad"),
])
agent = create_openai_tools_agent(llm=llm, tools=tools, prompt=prompt)
return AgentExecutor(agent=agent, tools=tools, verbose=True, return_intermediate_steps=True)
```
### 5. Run a Personalized Search
The workflow ties everything together:
```python
def conduct_personalized_search(user_id, query):
user_context = get_user_context(user_id, query)
agent_executor = create_personalized_search_agent(user_context)
response = agent_executor.invoke({"messages": [HumanMessage(content=query)]})
return {"agent_response": response['output']}
```
### 6. Store New Interactions
Every new query/response pair is stored for future personalization:
```python
def store_search_interaction(user_id, original_query, agent_response):
interaction = [
{"role": "user", "content": f"Searched for: {original_query}"},
{"role": "assistant", "content": f"Results based on preferences: {agent_response}"}
]
mem0_client.add(messages=interaction, user_id=user_id, output_format="v1.1")
```
### Full Example Run
```python
if __name__ == "__main__":
user_id = "john"
setup_user_history(user_id)
queries = [
"good coffee shops nearby for working",
"what can I make for my kid in lunch?"
]
for q in queries:
results = conduct_personalized_search(user_id, q)
print(f"\nQuery: {q}")
print(f"Personalized Response: {results['agent_response']}")
```
## How It Works in Practice
Here’s how personalization plays out:
- Context Gathering: User previously mentioned living in Los Angeles, being vegan, and having a 7-year-old daughter allergic to peanuts.
- Enhanced Search Query:
Query -> "good coffee shops nearby for working"
Enhanced Query -> "good coffee shops in Los Angeles with strong wifi, remote-work-friendly"
- Personalized Results: The assistant only returns wifi-friendly, work-friendly cafes near Los Angeles.
- Memory Update: Interaction is saved for better future recommendations.
## Conclusion
With Mem0 + Tavily, you can build a search assistant that doesn’t just fetch results but it understands the person behind the query.
Whether for shopping, travel, or daily life, this approach turns a generic search into a truly personalized experience.
Full Code: [Personalized Search GitHub](https://github.com/mem0ai/mem0/blob/main/examples/misc/personalized_search.py)
-56
View File
@@ -1,56 +0,0 @@
---
title: YouTube Assistant Extension
---
Enhance your YouTube experience with Mem0's **YouTube Assistant**, a Chrome extension that brings AI-powered chat directly to your YouTube videos. Get instant, personalized answers about video content while leveraging your own knowledge and memories - all without leaving the page.
## Features
- **Contextual AI Chat**: Ask questions about videos you're watching
- **Seamless Integration**: Chat interface sits alongside YouTube's native UI
- **Memory Integration**: Personalized responses based on your knowledge through Mem0
- **Real-Time Memory**: Memories are updated in real-time based on your interactions
## Demo Video
<video
autoPlay
muted
loop
playsInline
width="700"
height="400"
src="https://github.com/user-attachments/assets/c0334ccd-311b-4dd7-8034-ef88204fc751"
></video>
## Installation
This extension is not available on the Chrome Web Store yet. You can install it manually using below method:
### Manual Installation (Developer Mode)
1. **Download the Extension**: Clone or download the extension files from the [Mem0 GitHub repository](https://github.com/mem0ai/mem0/tree/main/examples).
2. **Build**: Run `npm install` followed by `npm run build` to install the dependencies and build the extension.
3. **Access Chrome Extensions**: Open Google Chrome and navigate to `chrome://extensions`.
4. **Enable Developer Mode**: Toggle the "Developer mode" switch in the top right corner.
5. **Load Unpacked Extension**: Click "Load unpacked" and select the directory containing the extension files.
6. **Confirm Installation**: The Mem0 YouTube Assistant Extension should now appear in your Chrome toolbar.
## Setup
1. **Configure API Settings**: Click the extension icon and enter your OpenAI API key (required to use the extension)
2. **Customize Settings**: Configure additional settings such as model, temperature, and memory settings
3. **Navigate to YouTube**: Start using the assistant on any YouTube video
4. **Memories**: Enter your Mem0 API key to enable personalized responses, and feed initial memories from settings
## Example Prompts
- "Can you summarize the main points of this video?"
- "Explain the concept they just mentioned"
- "How does this relate to what I already know?"
- "What are some practical applications of this topic related to my work?"
## Privacy and Data Security
Your API keys are stored locally in your browser. Your messages are sent to the Mem0 API for extracting and retrieving memories. Mem0 is committed to ensuring your data's privacy and security.
-267
View File
@@ -1,267 +0,0 @@
---
title: FAQs (v0.x)
description: 'Frequently asked questions about Mem0 v0.x'
icon: "question"
iconType: "solid"
---
<Warning>
**This is legacy documentation for Mem0 v0.x.** For the latest FAQs, please refer to [v1.0.0 FAQs](/platform/faqs).
</Warning>
## General Questions
### What is Mem0 v0.x?
Mem0 v0.x is the legacy version of Mem0's memory layer for LLMs. While still functional, it lacks the advanced features and optimizations available in v1.0.0 .
### Should I upgrade to v1.0.0 ?
Yes! v1.0.0 offers significant improvements:
- Enhanced filtering with logical operators
- Reranking support for better search relevance
- Improved async performance
- Standardized API responses
- Better error handling
See our [migration guide](/migration/v0-to-v1) for upgrade instructions.
### Is v0.x still supported?
v0.x receives minimal maintenance but no new features. We recommend upgrading to v1.0.0 for the latest improvements and active support.
## API Questions
### Why do I get different response formats?
In v0.x, response format depends on the `output_format` parameter:
```python
# v1.0 format (list)
result = m.add("memory", user_id="alice", output_format="v1.0")
# Returns: [{"id": "...", "memory": "...", "event": "ADD"}]
# v1.1 format (dict)
result = m.add("memory", user_id="alice", output_format="v1.1")
# Returns: {"results": [{"id": "...", "memory": "...", "event": "ADD"}]}
```
**Solution:** Always use `output_format="v1.1"` for consistency.
### How do I handle both response formats?
```python
def normalize_response(result):
"""Normalize v0.x response formats"""
if isinstance(result, list):
return {"results": result}
return result
# Usage
result = m.add("memory", user_id="alice")
normalized = normalize_response(result)
for memory in normalized["results"]:
print(memory["memory"])
```
### Can I use async in v0.x?
Yes, but it's optional and less optimized:
```python
# Optional async mode
result = m.add("memory", user_id="alice", async_mode=True)
# Or use AsyncMemory
from mem0 import AsyncMemory
async_m = AsyncMemory()
result = await async_m.add("memory", user_id="alice")
```
## Configuration Questions
### What vector stores work with v0.x?
v0.x supports most vector stores:
- Qdrant
- Chroma
- Pinecone
- Weaviate
- PGVector
- And others
### How do I configure LLMs in v0.x?
```python
config = {
"llm": {
"provider": "openai",
"config": {
"model": "gpt-3.5-turbo",
"api_key": "your-api-key"
}
},
"version": "v1.0" # Supported in v0.x
}
m = Memory.from_config(config)
```
### Can I use custom prompts in v0.x?
Limited support:
```python
config = {
"custom_fact_extraction_prompt": "Your custom prompt here"
# custom_update_memory_prompt not available in v0.x
}
```
## Migration Questions
### Is migration difficult?
No! Most changes are simple parameter removals:
```python
# Before (v0.x)
result = m.add("memory", user_id="alice", output_format="v1.1", version="v1.0")
# After (v1.0.0 )
result = m.add("memory", user_id="alice")
```
### Will I lose my data?
No! Your existing memories remain fully compatible with v1.0.0 .
### Do I need to re-index my vectors?
No! Existing vector data works with v1.0.0 without changes.
### Can I rollback if needed?
Yes! You can always rollback:
```bash
pip install mem0ai==0.1.20 # Last stable v0.x
```
## Feature Questions
### Does v0.x support reranking?
No, reranking is only available in v1.0.0 :
```python
# v1.0.0 only
results = m.search("query", user_id="alice", rerank=True)
```
### Can I use advanced filtering in v0.x?
No, only basic key-value filtering:
```python
# v0.x - basic only
filters = {"category": "food", "user_id": "alice"}
# v1.0.0 - advanced operators
filters = {
"AND": [
{"category": "food"},
{"score": {"gte": 0.8}}
]
}
```
### Does v0.x support metadata filtering?
Yes, but basic:
```python
# Basic metadata filtering
results = m.search(
"query",
user_id="alice",
filters={"category": "work"}
)
```
## Performance Questions
### Is v0.x slower than v1.0.0 ?
Yes, v1.0.0 includes several performance optimizations:
- Better async handling
- Optimized vector operations
- Improved memory management
### How do I optimize v0.x performance?
1. Use async mode when possible
2. Configure appropriate vector store settings
3. Use efficient metadata filters
4. Consider upgrading to v1.0.0
### Can I batch operations in v0.x?
Limited support. Better batch processing available in v1.0.0 .
## Troubleshooting
### Common v0.x Issues
#### 1. Inconsistent Response Formats
**Problem:** Getting different response types
**Solution:** Always use `output_format="v1.1"`
#### 2. Async Mode Not Working
**Problem:** Async operations failing
**Solution:** Use `AsyncMemory` class or `async_mode=True`
#### 3. Configuration Errors
**Problem:** Config not loading properly
**Solution:** Check version parameter and config structure
### Error Messages
#### "Invalid output format"
```python
# Fix: Use supported format
result = m.add("memory", user_id="alice", output_format="v1.1")
```
#### "Version not supported"
```python
# Fix: Use supported version
config = {"version": "v1.0"} # Supported in v0.x
```
#### "Async mode not available"
```python
# Fix: Use AsyncMemory
from mem0 import AsyncMemory
async_m = AsyncMemory()
```
## Getting Help
### Documentation
- [v0.x Quickstart](/v0x/quickstart)
- [Migration Guide](/migration/v0-to-v1)
- [v1.0.0 Docs](/)
### Community
- [GitHub Discussions](https://github.com/mem0ai/mem0/discussions)
- [Discord Community](https://discord.gg/mem0)
### Migration Support
- [Step-by-step Migration](/migration/v0-to-v1)
- [Breaking Changes](/migration/breaking-changes)
- [API Changes](/migration/api-changes)
<Info>
**Ready to upgrade?** Check out our [migration guide](/migration/v0-to-v1) to move to v1.0.0 and access the latest features!
</Info>
Binary file not shown.

Before

Width:  |  Height:  |  Size: 276 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 227 KiB

-173
View File
@@ -1,173 +0,0 @@
---
title: AgentOps
---
Integrate [**Mem0**](https://github.com/mem0ai/mem0) with [AgentOps](https://agentops.ai), a comprehensive monitoring and analytics platform for AI agents. This integration enables automatic tracking and analysis of memory operations, providing insights into agent performance and memory usage patterns.
## Overview
1. Automatic monitoring of Mem0 operations and performance metrics
2. Real-time tracking of memory add, search, and retrieval operations
3. Analytics dashboard with memory usage patterns and insights
4. Error tracking and debugging capabilities for memory operations
## Prerequisites
Before setting up Mem0 with AgentOps, ensure you have:
1. Installed the required packages:
```bash
pip install mem0ai agentops python-dotenv
```
2. Valid API keys:
- [AgentOps API Key](https://app.agentops.ai/dashboard/api-keys)
- OpenAI API Key (for LLM operations)
- [Mem0 API Key](https://app.mem0.ai/dashboard/api-keys) (optional, for cloud operations)
## Basic Integration Example
The following example demonstrates how to integrate Mem0 with AgentOps monitoring for comprehensive memory operation tracking:
```python
#Import the required libraries for local memory management with Mem0
from mem0 import Memory, AsyncMemory
import os
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")
#Set up the configuration for local memory storage and define sample user data.
local_config = {
"llm": {
"provider": "openai",
"config": {
"model": "gpt-4.1-nano-2025-04-14",
"temperature": 0.1,
"max_tokens": 2000,
},
}
}
user_id = "alice_demo"
agent_id = "assistant_demo"
run_id = "session_001"
sample_messages = [
{"role": "user", "content": "I'm planning to watch a movie tonight. Any recommendations?"},
{"role": "assistant", "content": "How about a thriller? 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.",
},
]
sample_preferences = [
"I prefer dark roast coffee over light roast",
"I exercise every morning at 6 AM",
"I'm vegetarian and avoid all meat products",
"I love reading science fiction novels",
"I work in software engineering",
]
#This function demonstrates sequential memory operations using the synchronous Memory class
def demonstrate_sync_memory(local_config, sample_messages, sample_preferences, user_id):
"""
Demonstrate synchronous Memory class operations.
"""
agentops.start_trace("mem0_memory_example", tags=["mem0_memory_example"])
try:
memory = Memory.from_config(local_config)
result = memory.add(
sample_messages, user_id=user_id, metadata={"category": "movie_preferences", "session": "demo"}
)
for i, preference in enumerate(sample_preferences):
result = memory.add(preference, user_id=user_id, metadata={"type": "preference", "index": i})
search_queries = [
"What movies does the user like?",
"What are the user's food preferences?",
"When does the user exercise?",
]
for query in search_queries:
results = memory.search(query, user_id=user_id)
if results and "results" in results:
for j, result in enumerate(results['results']):
print(f"Result {j+1}: {result.get('memory', 'N/A')}")
else:
print("No results found")
all_memories = memory.get_all(user_id=user_id)
if all_memories and "results" in all_memories:
print(f"Total memories: {len(all_memories['results'])}")
delete_all_result = memory.delete_all(user_id=user_id)
print(f"Delete all result: {delete_all_result}")
agentops.end_trace(end_state="success")
except Exception as e:
agentops.end_trace(end_state="error")
# Execute sync demonstrations
demonstrate_sync_memory(local_config, sample_messages, sample_preferences, user_id)
```
For detailed information on this integration, refer to the official [Agentops Mem0 integration documentation](https://docs.agentops.ai/v2/integrations/mem0).
## Key Features
### 1. Automatic Operation Tracking
AgentOps automatically monitors all Mem0 operations:
- **Memory Operations**: Track add, search, get_all, delete operations and much more
- **Performance Metrics**: Monitor response times and success rates
- **Error Tracking**: Capture and analyze operation failures
### 2. Real-time Analytics Dashboard
Access comprehensive analytics through the AgentOps dashboard:
- **Usage Patterns**: Visualize memory usage trends over time
- **User Behavior**: Analyze how different users interact with memory
- **Performance Insights**: Identify bottlenecks and optimization opportunities
### 3. Session Management
Organize your monitoring with structured sessions:
- **Session Tracking**: Group related operations into logical sessions
- **Success/Failure Rates**: Track session outcomes for reliability monitoring
- **Custom Metadata**: Add context to sessions for better analysis
## Best Practices
1. **Initialize Early**: Always initialize AgentOps before importing Mem0 classes
2. **Session Management**: Use meaningful session names and end sessions appropriately
3. **Error Handling**: Wrap operations in try-catch blocks and report failures
4. **Tagging**: Use tags to organize different types of memory operations
5. **Environment Separation**: Use different projects or tags for dev/staging/prod
## Help & Resources
- [AgentOps Documentation](https://docs.agentops.ai/)
- [AgentOps Dashboard](https://app.agentops.ai/)
- [Mem0 Platform](https://app.mem0.ai/)
<Snippet file="get-help.mdx" />
-203
View File
@@ -1,203 +0,0 @@
---
title: Agno
---
This integration of [**Mem0**](https://github.com/mem0ai/mem0) with [Agno](https://github.com/agno-agi/agno, enables persistent, multimodal memory for Agno-based agents - improving personalization, context awareness, and continuity across conversations.
## Overview
1. Store and retrieve memories from Mem0 within Agno agents
2. Support for multimodal interactions (text and images)
3. Semantic search for relevant past conversations
4. Personalized responses based on user history
5. One-line memory integration via `Mem0Tools`
## Prerequisites
Before setting up Mem0 with Agno, ensure you have:
1. Installed the required packages:
```bash
pip install agno mem0ai python-dotenv
```
2. Valid API keys:
- [Mem0 API Key](https://app.mem0.ai/dashboard/api-keys)
- OpenAI API Key (for the agent model)
## Quick Integration (Using `Mem0Tools`)
The simplest way to integrate Mem0 with Agno Agents is to use Mem0 as a tool using built-in `Mem0Tools`:
```python
from agno.agent import Agent
from agno.models.openai import OpenAIChat
from agno.tools.mem0 import Mem0Tools
agent = Agent(
name="Memory Agent",
model=OpenAIChat(id="gpt-4.1-nano-2025-04-14"2025-04-14"),
tools=[Mem0Tools()],
description="An assistant that remembers and personalizes using Mem0 memory."
)
```
This enables memory functionality out of the box:
- **Persistent memory writing**: `Mem0Tools` uses `MemoryClient.add(...)` to store messages from user-agent interactions, including optional metadata such as user ID or session.
- **Contextual memory search**: Compatible queries use `MemoryClient.search(...)` to retrieve relevant past messages, improving contextual understanding.
- **Multimodal support**: Both text and image inputs are supported, allowing richer memory records.
> `Mem0Tools` uses the `MemoryClient` under the hood and requires no additional setup. You can customize its behavior by modifying your tools list or extending it in code.
## Full Manual Example
> Note: Mem0 can also be used with Agno Agents as a separate memory layer.
The following example demonstrates how to create an Agno agent with Mem0 memory integration, including support for image processing:
```python
import base64
from pathlib import Path
from typing import Optional
from agno.agent import Agent
from agno.media import Image
from agno.models.openai import OpenAIChat
from mem0 import MemoryClient
# Initialize the Mem0 client
client = MemoryClient()
# Define the agent
agent = Agent(
name="Personal Agent",
model=OpenAIChat(id="gpt-4"),
description="You are a helpful personal agent that helps me with day to day activities."
"You can process both text and images.",
markdown=True
)
def chat_user(
user_input: Optional[str] = None,
user_id: str = "alex",
image_path: Optional[str] = None
) -> str:
"""
Handle user input with memory integration, supporting both text and images.
Args:
user_input: The user's text input
user_id: Unique identifier for the user
image_path: Path to an image file if provided
Returns:
The agent's response as a string
"""
if image_path:
# Convert image to base64
with open(image_path, "rb") as image_file:
base64_image = base64.b64encode(image_file.read()).decode("utf-8")
# Create message objects for text and image
messages = []
if user_input:
messages.append({
"role": "user",
"content": user_input
})
messages.append({
"role": "user",
"content": {
"type": "image_url",
"image_url": {
"url": f"data:image/jpeg;base64,{base64_image}"
}
}
})
# Store messages in memory
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, output_format='v1.1')
memory_context = "\n".join(f"- {m['memory']}" for m in memories['results'])
# Construct the prompt
prompt = f"""
You are a helpful personal assistant who helps users with their day-to-day activities and keeps track of everything.
Your task is to:
1. Analyze the given image (if present) and extract meaningful details to answer the user's question.
2. Use your past memory of the user to personalize your answer.
3. Combine the image content and memory to generate a helpful, context-aware response.
Here is what I remember about the user:
{memory_context}
User question:
{user_input}
"""
# Get response from agent
if image_path:
response = agent.run(prompt, images=[Image(filepath=Path(image_path))])
else:
response = agent.run(prompt)
# Store the interaction in memory
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."
# Example Usage
if __name__ == "__main__":
response = chat_user(
"I like to travel and my favorite destination is London",
image_path="travel_items.jpeg",
user_id="alex"
)
print(response)
```
## Key Features
### 1. Multimodal Memory Storage
The integration supports storing both text and image data:
- **Text Storage**: Conversation history is saved in a structured format
- **Image Analysis**: Agents can analyze images and store visual information
- **Combined Context**: Memory retrieval combines both text and visual data
### 2. Personalized Agent Responses
Improve your agent's context awareness:
- **Memory Retrieval**: Semantic search finds relevant past interactions
- **User Preferences**: Personalize responses based on stored user information
- **Continuity**: Maintain conversation threads across multiple sessions
### 3. Flexible Configuration
Customize the integration to your needs:
- **Use `Mem0Tools()`** for drop-in memory support
- **Use `MemoryClient` directly** for advanced control
- **User Identification**: Organize memories by user ID
- **Memory Search**: Configure search relevance and result count
- **Memory Formatting**: Support for various OpenAI message formats
## Help & Resources
- [Agno Documentation](https://docs.agno.com/introduction)
- [Mem0 Platform](https://app.mem0.ai/)
<Snippet file="get-help.mdx" />
-138
View File
@@ -1,138 +0,0 @@
---
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
In this guide, we'll explore an example of creating a conversational AI system with memory:
- A customer service bot that can recall previous interactions and provide personalized responses.
## Setup and Configuration
Install necessary libraries:
```bash
pip install autogen mem0ai openai python-dotenv
```
First, we'll import the necessary libraries and set up our configurations.
<Note>Remember to get the Mem0 API key from [Mem0 Platform](https://app.mem0.ai).</Note>
```python
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 = "alice"
# Set up OpenAI 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()
agent = ConversableAgent(
"chatbot",
llm_config={"config_list": [{"model": "gpt-4", "api_key": OPENAI_API_KEY}]},
code_execution_config=False,
human_input_mode="NEVER",
)
```
## Storing Conversations in Memory
Add conversation history to Mem0 for future reference:
```python
conversation = [
{"role": "assistant", "content": "Hi, I'm Best Buy's chatbot! How can I help you?"},
{"role": "user", "content": "I'm seeing horizontal lines on my TV."},
{"role": "assistant", "content": "I'm sorry to hear that. Can you provide your TV model?"},
{"role": "user", "content": "It's a Sony - 77\" Class BRAVIA XR A80K OLED 4K UHD Smart Google TV"},
{"role": "assistant", "content": "Thank you for the information. Let's troubleshoot this issue..."}
]
memory_client.add(messages=conversation, user_id=USER_ID, output_format="v1.1")
print("Conversation added to memory.")
```
## Retrieving and Using Memory
Create a function to get context-aware responses based on user's question and previous interactions:
```python
def get_context_aware_response(question):
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:
Previous interactions:
{context}
Question: {question}
"""
reply = agent.generate_reply(messages=[{"content": prompt, "role": "user"}])
return reply
# Example usage
question = "What was the issue with my TV?"
answer = get_context_aware_response(question)
print("Context-aware answer:", answer)
```
## Multi-Agent Conversation
For more complex scenarios, you can create multiple agents:
```python
manager = ConversableAgent(
"manager",
system_message="You are a manager who helps in resolving complex customer issues.",
llm_config={"config_list": [{"model": "gpt-4", "api_key": OPENAI_API_KEY}]},
human_input_mode="NEVER"
)
def escalate_to_manager(question):
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"""
Context from previous interactions:
{context}
Customer question: {question}
As a manager, how would you address this issue?
"""
manager_response = manager.generate_reply(messages=[{"content": prompt, "role": "user"}])
return manager_response
# Example usage
complex_question = "I'm not satisfied with the troubleshooting steps. What else can be done?"
manager_answer = escalate_to_manager(complex_question)
print("Manager's response:", manager_answer)
```
## Conclusion
By integrating AutoGen with Mem0, you've created a conversational AI system with memory capabilities. This example demonstrates a customer service bot that can recall previous interactions and provide context-aware responses, with the ability to escalate complex issues to a manager agent.
This integration enables the creation of more intelligent and personalized AI agents for various applications, such as customer support, virtual assistants, and interactive chatbots.
## Help
In case of any questions, please feel free to reach out to us using one of the following methods:
<Snippet file="get-help.mdx" />
-129
View File
@@ -1,129 +0,0 @@
---
title: AWS Bedrock
---
This integration demonstrates how to use **Mem0** with **AWS Bedrock** and **Amazon OpenSearch Service (AOSS)** to enable persistent, semantic memory in intelligent agents.
## Overview
In this guide, you'll:
1. Configure AWS credentials to enable Bedrock and OpenSearch access
2. Set up the Mem0 SDK to use Bedrock for embeddings and LLM
3. Store and retrieve memories using OpenSearch as a vector store
4. Build memory-aware applications with scalable cloud infrastructure
## Prerequisites
- AWS account with access to:
- Bedrock foundation models (e.g., Titan, Claude)
- OpenSearch Service with a configured domain
- Python 3.10+
- Valid AWS credentials (via environment or IAM role)
## Setup and Installation
Install required packages:
```bash
pip install mem0ai boto3 opensearch-py
```
Set environment variables:
Be sure to configure your AWS credentials using environment variables, IAM roles, or the AWS CLI.
```python
import os
os.environ['AWS_REGION'] = 'us-west-2'
os.environ['AWS_ACCESS_KEY_ID'] = 'AKIA...'
os.environ['AWS_SECRET_ACCESS_KEY'] = 'AS...'
```
## Initialize Mem0 Integration
Import necessary modules and configure Mem0:
```python
import boto3
from opensearchpy import OpenSearch, RequestsHttpConnection, AWSV4SignerAuth
from mem0.memory.main import Memory
region = 'us-west-2'
service = 'aoss'
credentials = boto3.Session().get_credentials()
auth = AWSV4SignerAuth(credentials, region, service)
config = {
"embedder": {
"provider": "aws_bedrock",
"config": {
"model": "amazon.titan-embed-text-v2:0"
}
},
"llm": {
"provider": "aws_bedrock",
"config": {
"model": "anthropic.claude-3-5-haiku-20241022-v1:0",
"temperature": 0.1,
"max_tokens": 2000
}
},
"vector_store": {
"provider": "opensearch",
"config": {
"collection_name": "mem0",
"host": "your-opensearch-domain.us-west-2.es.amazonaws.com",
"port": 443,
"http_auth": auth,
"embedding_model_dims": 1024,
"connection_class": RequestsHttpConnection,
"pool_maxsize": 20,
"use_ssl": True,
"verify_certs": True
}
}
}
# Initialize memory system
m = Memory.from_config(config)
```
## Memory Operations
Use Mem0 with your Bedrock-powered LLM and OpenSearch storage backend:
```python
# Store conversational context
messages = [
{"role": "user", "content": "I'm planning to watch a movie tonight. Any recommendations?"},
{"role": "assistant", "content": "How about a thriller?"},
{"role": "user", "content": "I prefer sci-fi."},
{"role": "assistant", "content": "Noted! I'll suggest sci-fi movies next time."}
]
m.add(messages, user_id="alice", metadata={"category": "movie_recommendations"})
# Search for memory
relevant = m.search("What kind of movies does Alice like?", user_id="alice")
# Retrieve all user memories
all_memories = m.get_all(user_id="alice")
```
## Key Features
1. **Serverless Memory Embeddings**: Use Titan or other Bedrock models for fast, cloud-native embeddings
2. **Scalable Vector Search**: Store and retrieve vectorized memories via OpenSearch
3. **Seamless AWS Auth**: Uses AWS IAM or environment variables to securely authenticate
4. **User-specific Memory Spaces**: Memories are isolated per user ID
5. **Persistent Memory Context**: Maintain and recall history across sessions
## Help
- [AWS Bedrock Documentation](https://docs.aws.amazon.com/bedrock/)
- [Amazon OpenSearch Service Docs](https://docs.aws.amazon.com/opensearch-service/)
- [Mem0 Platform](https://app.mem0.ai)
<Snippet file="get-help.mdx" />
-168
View File
@@ -1,168 +0,0 @@
---
title: CrewAI
---
Build an AI system that combines CrewAI's agent-based architecture with Mem0's memory capabilities. This integration enables persistent memory across agent interactions and personalized task execution based on user history.
## Overview
In this guide, we'll create a CrewAI agent that:
1. Uses CrewAI to manage AI agents and tasks
2. Leverages Mem0 to store and retrieve conversation history
3. Creates personalized experiences based on stored user preferences
## Setup and Configuration
Install necessary libraries:
```bash
pip install crewai crewai-tools mem0ai
```
Import required modules and set up configurations:
<Note>Remember to get your API keys from [Mem0 Platform](https://app.mem0.ai), [OpenAI](https://platform.openai.com) and [Serper Dev](https://serper.dev) for search capabilities.</Note>
```python
import os
from mem0 import MemoryClient
from crewai import Agent, Task, Crew, Process
from crewai_tools import SerperDevTool
# Configuration
os.environ["MEM0_API_KEY"] = "your-mem0-api-key"
os.environ["OPENAI_API_KEY"] = "your-openai-api-key"
os.environ["SERPER_API_KEY"] = "your-serper-api-key"
# Initialize Mem0 client
client = MemoryClient()
```
## Store User Preferences
Set up initial conversation and preferences storage:
```python
def store_user_preferences(user_id: str, conversation: list):
"""Store user preferences from conversation history"""
client.add(conversation, user_id=user_id)
# Example conversation storage
messages = [
{
"role": "user",
"content": "Hi there! I'm planning a vacation and could use some advice.",
},
{
"role": "assistant",
"content": "Hello! I'd be happy to help with your vacation planning. What kind of destination do you prefer?",
},
{"role": "user", "content": "I am more of a beach person than a mountain person."},
{
"role": "assistant",
"content": "That's interesting. Do you like hotels or airbnb?",
},
{"role": "user", "content": "I like airbnb more."},
]
store_user_preferences("crew_user_1", messages)
```
## Create CrewAI Agent
Define an agent with memory capabilities:
```python
def create_travel_agent():
"""Create a travel planning agent with search capabilities"""
search_tool = SerperDevTool()
return Agent(
role="Personalized Travel Planner Agent",
goal="Plan personalized travel itineraries",
backstory="""You are a seasoned travel planner, known for your meticulous attention to detail.""",
allow_delegation=False,
memory=True,
tools=[search_tool],
)
```
## Define Tasks
Create tasks for your agent:
```python
def create_planning_task(agent, destination: str):
"""Create a travel planning task"""
return Task(
description=f"""Find places to live, eat, and visit in {destination}.""",
expected_output=f"A detailed list of places to live, eat, and visit in {destination}.",
agent=agent,
)
```
## Set Up Crew
Configure the crew with memory integration:
```python
def setup_crew(agents: list, tasks: list):
"""Set up a crew with Mem0 memory integration"""
return Crew(
agents=agents,
tasks=tasks,
process=Process.sequential,
memory=True,
memory_config={
"provider": "mem0",
"config": {"user_id": "crew_user_1"},
}
)
```
## Main Execution Function
Implement the main function to run the travel planning system:
```python
def plan_trip(destination: str, user_id: str):
# Create agent
travel_agent = create_travel_agent()
# Create task
planning_task = create_planning_task(travel_agent, destination)
# Setup crew
crew = setup_crew([travel_agent], [planning_task])
# Execute and return results
return crew.kickoff()
# Example usage
if __name__ == "__main__":
result = plan_trip("San Francisco", "crew_user_1")
print(result)
```
## Key Features
1. **Persistent Memory**: Uses Mem0 to maintain user preferences and conversation history
2. **Agent-Based Architecture**: Leverages CrewAI's agent system for task execution
3. **Search Integration**: Includes SerperDev tool for real-world information retrieval
4. **Personalization**: Utilizes stored preferences for tailored recommendations
## Benefits
1. **Persistent Context & Memory**: Maintains user preferences and interaction history across sessions
2. **Flexible & Scalable Design**: Easily extendable with new agents, tasks and capabilities
## Conclusion
By combining CrewAI with Mem0, you can create sophisticated AI systems that maintain context and provide personalized experiences while leveraging the power of autonomous agents.
## Help
- [CrewAI Documentation](https://docs.crewai.com/)
- [Mem0 Platform](https://app.mem0.ai/)
<Snippet file="get-help.mdx" />
-34
View File
@@ -1,34 +0,0 @@
---
title: Dify
---
# Integrating Mem0 with Dify AI
Mem0 brings a robust memory layer to Dify AI, empowering your AI agents with persistent conversation storage and retrieval capabilities. With Mem0, your Dify applications gain the ability to recall past interactions and maintain context, ensuring more natural and insightful conversations.
---
## How to Integrate Mem0 in Your Dify Workflow
1. **Install the Mem0 Plugin:**
Head to the [Dify Marketplace](https://marketplace.dify.ai/plugins/yevanchen/mem0) and install the Mem0 plugin. This is your first step toward adding intelligent memory to your AI applications.
2. **Create or Open Your Dify Project:**
Whether you're starting fresh or updating an existing project, simply create or open your Dify workspace.
3. **Add the Mem0 Plugin to Your Project:**
Within your project, add the Mem0 plugin. This integration connects Mem0’s memory management capabilities directly to your Dify application.
4. **Configure Your Mem0 Settings:**
Customize Mem0 to suit your needs—set preferences for how conversation history is stored, the search parameters, and any other context-aware features.
5. **Leverage Mem0 in Your Workflow:**
Use Mem0 to store every conversation turn and retrieve past interactions seamlessly. This integration ensures that your AI agents can refer back to important context, making multi-turn dialogues more effective and user-centric.
---
![Mem0 Dify Integration](/images/dify-mem0-integration.png)
Enhance your Dify-powered AI with Mem0 and transform your conversational experiences. Start integrating intelligent memory management today and give your agents the context they need to excel!
[Explore Mem0 on Dify Marketplace](https://marketplace.dify.ai/plugins/yevanchen/mem0)
-454
View File
@@ -1,454 +0,0 @@
---
title: ElevenLabs
---
Create voice-based conversational AI agents with memory capabilities by integrating ElevenLabs and Mem0. This integration enables persistent, context-aware voice interactions that remember past conversations.
## Overview
In this guide, we'll build a voice agent that:
1. Uses ElevenLabs Conversational AI for voice interaction
2. Leverages Mem0 to store and retrieve memories from past conversations
3. Provides personalized responses based on user history
## Setup and Configuration
Install necessary libraries:
```bash
pip install elevenlabs mem0ai python-dotenv
```
Configure your environment variables:
<Note>You'll need both an ElevenLabs API key and a Mem0 API key to use this integration.</Note>
```bash
# Create a .env file with these variables
AGENT_ID=your-agent-id
USER_ID=unique-user-identifier
ELEVENLABS_API_KEY=your-elevenlabs-api-key
MEM0_API_KEY=your-mem0-api-key
```
## Integration Code Breakdown
Let's break down the implementation into manageable parts:
### 1. Imports and Environment Setup
First, we import required libraries and set up the environment:
```python
import os
import signal
import sys
from mem0 import AsyncMemoryClient
from elevenlabs.client import ElevenLabs
from elevenlabs.conversational_ai.conversation import Conversation
from elevenlabs.conversational_ai.default_audio_interface import DefaultAudioInterface
from elevenlabs.conversational_ai.conversation import ClientTools
```
These imports provide:
- Standard Python libraries for system operations and signal handling
- `AsyncMemoryClient` from Mem0 for memory operations
- ElevenLabs components for voice interaction
### 2. Environment Variables and Validation
Next, we validate the required environment variables:
```python
def main():
# Required environment variables
AGENT_ID = os.environ.get('AGENT_ID')
USER_ID = os.environ.get('USER_ID')
API_KEY = os.environ.get('ELEVENLABS_API_KEY')
MEM0_API_KEY = os.environ.get('MEM0_API_KEY')
# Validate required environment variables
if not AGENT_ID:
sys.stderr.write("AGENT_ID environment variable must be set\n")
sys.exit(1)
if not USER_ID:
sys.stderr.write("USER_ID environment variable must be set\n")
sys.exit(1)
if not API_KEY:
sys.stderr.write("ELEVENLABS_API_KEY not set, assuming the agent is public\n")
if not MEM0_API_KEY:
sys.stderr.write("MEM0_API_KEY environment variable must be set\n")
sys.exit(1)
# Set up Mem0 API key in the environment
os.environ['MEM0_API_KEY'] = MEM0_API_KEY
```
This section:
- Retrieves required environment variables
- Performs validation to ensure required variables are present
- Exits the application with an error message if required variables are missing
- Sets the Mem0 API key in the environment for the Mem0 client to use
### 3. Client Initialization
Initialize both the ElevenLabs and Mem0 clients:
```python
# Initialize ElevenLabs client
client = ElevenLabs(api_key=API_KEY)
# Initialize memory client and tools
client_tools = ClientTools()
mem0_client = AsyncMemoryClient()
```
Here we:
- Create an ElevenLabs client with the API key
- Initialize a ClientTools object for registering function tools
- Create an AsyncMemoryClient instance for Mem0 interactions
### 4. Memory Function Definitions
Define the two key memory functions that will be registered as tools:
```python
# Define memory-related functions for the agent
async def add_memories(parameters):
"""Add a message to the memory store"""
message = parameters.get("message")
await mem0_client.add(
messages=message,
user_id=USER_ID,
output_format="v1.1",
version="v2"
)
return "Memory added successfully"
async def retrieve_memories(parameters):
"""Retrieve relevant memories based on the input message"""
message = parameters.get("message")
# Set up filters to retrieve memories for this specific user
filters = {
"AND": [
{
"user_id": USER_ID
}
]
}
# Search for relevant memories using the message as a query
results = await mem0_client.search(
query=message,
version="v2",
filters=filters
)
# Extract and join the memory texts
memories = ' '.join([result["memory"] for result in results.get('results', [])])
print("[ Memories ]", memories)
if memories:
return memories
return "No memories found"
```
These functions:
#### `add_memories`:
- Takes a message parameter containing information to remember
- Stores the message in Mem0 using the `add` method
- Associates the memory with the specific USER_ID
- Returns a success message to the agent
#### `retrieve_memories`:
- Takes a message parameter as the search query
- Sets up filters to only retrieve memories for the current user
- Uses semantic search to find relevant memories
- Joins all retrieved memories into a single text
- Prints retrieved memories to the console for debugging
- Returns the memories or a "No memories found" message if none are found
### 5. Registering Memory Functions as Tools
Register the memory functions with the ElevenLabs ClientTools system:
```python
# Register the memory functions as tools for the agent
client_tools.register("addMemories", add_memories, is_async=True)
client_tools.register("retrieveMemories", retrieve_memories, is_async=True)
```
This allows the ElevenLabs agent to:
- Access these functions through function calling
- Wait for asynchronous results (is_async=True)
- Call these functions by name ("addMemories" and "retrieveMemories")
### 6. Conversation Setup
Configure the conversation with ElevenLabs:
```python
# Initialize the conversation
conversation = Conversation(
client,
AGENT_ID,
# Assume auth is required when API_KEY is set
requires_auth=bool(API_KEY),
audio_interface=DefaultAudioInterface(),
client_tools=client_tools,
callback_agent_response=lambda response: print(f"Agent: {response}"),
callback_agent_response_correction=lambda original, corrected: print(f"Agent: {original} -> {corrected}"),
callback_user_transcript=lambda transcript: print(f"User: {transcript}"),
# callback_latency_measurement=lambda latency: print(f"Latency: {latency}ms"),
)
```
This sets up the conversation with:
- The ElevenLabs client and Agent ID
- Authentication requirements based on API key presence
- DefaultAudioInterface for handling audio I/O
- The client_tools with our memory functions
- Callback functions for:
- Displaying agent responses
- Showing corrected responses (when the agent self-corrects)
- Displaying user transcripts for debugging
- (Commented out) Latency measurements
### 7. Conversation Management
Start and manage the conversation:
```python
# Start the conversation
print(f"Starting conversation with user_id: {USER_ID}")
conversation.start_session()
# Handle Ctrl+C to gracefully end the session
signal.signal(signal.SIGINT, lambda sig, frame: conversation.end_session())
# Wait for the conversation to end and get the conversation ID
conversation_id = conversation.wait_for_session_end()
print(f"Conversation ID: {conversation_id}")
if __name__ == '__main__':
main()
```
This final section:
- Prints a message indicating the conversation has started
- Starts the conversation session
- Sets up a signal handler to gracefully end the session on Ctrl+C
- Waits for the session to end and gets the conversation ID
- Prints the conversation ID for reference
## Memory Tools Overview
This integration provides two key memory functions to your conversational AI agent:
### 1. Adding Memories (`addMemories`)
The `addMemories` tool allows your agent to store important information during a conversation, including:
- User preferences
- Important facts shared by the user
- Decisions or commitments made during the conversation
- Action items to follow up on
When the agent identifies information worth remembering, it calls this function to store it in the Mem0 database with the appropriate user ID.
#### How it works:
1. The agent identifies information that should be remembered
2. It formats the information as a message string
3. It calls the `addMemories` function with this message
4. The function stores the memory in Mem0 linked to the user's ID
5. Later conversations can retrieve this memory
#### Example usage in agent prompt:
```
When the user shares important information like preferences or personal details,
use the addMemories function to store this information for future reference.
```
### 2. Retrieving Memories (`retrieveMemories`)
The `retrieveMemories` tool allows your agent to search for and retrieve relevant memories from previous conversations. The agent can:
- Search for context related to the current topic
- Recall user preferences
- Remember previous interactions on similar topics
- Create continuity across multiple sessions
#### How it works:
1. The agent needs context for the current conversation
2. It calls `retrieveMemories` with the current conversation topic or question
3. The function performs a semantic search in Mem0
4. Relevant memories are returned to the agent
5. The agent incorporates these memories into its response
#### Example usage in agent prompt:
```
At the beginning of each conversation turn, use retrieveMemories to check if we've
discussed this topic before or if the user has shared relevant preferences.
```
## Configuring Your ElevenLabs Agent
To enable your agent to effectively use memory:
1. Add function calling capabilities to your agent in the ElevenLabs platform:
- Go to your agent settings in the ElevenLabs platform
- Navigate to the "Tools" section
- Enable function calling for your agent
- Add the memory tools as described below
2. Add the `addMemories` and `retrieveMemories` tools to your agent with these specifications:
For `addMemories`:
```json
{
"name": "addMemories",
"description": "Stores important information from the conversation to remember for future interactions",
"parameters": {
"type": "object",
"properties": {
"message": {
"type": "string",
"description": "The important information to remember"
}
},
"required": ["message"]
}
}
```
For `retrieveMemories`:
```json
{
"name": "retrieveMemories",
"description": "Retrieves relevant information from past conversations",
"parameters": {
"type": "object",
"properties": {
"message": {
"type": "string",
"description": "The query to search for in past memories"
}
},
"required": ["message"]
}
}
```
3. Update your agent's prompt to instruct it to use these memory functions. For example:
```
You are a helpful voice assistant that remembers past conversations with the user.
You have access to memory tools that allow you to remember important information:
- Use retrieveMemories at the beginning of the conversation to recall relevant context from prior conversations
- Use addMemories to store new important information such as:
* User preferences
* Personal details the user shares
* Important decisions made
* Tasks or follow-ups promised to the user
Before responding to complex questions, always check for relevant memories first.
When the user shares important information, make sure to store it for future reference.
```
## Example Conversation Flow
Here's how a typical conversation with memory might flow:
1. **User speaks**: "Hi, do you remember my favorite color?"
2. **Agent retrieves memories**:
```python
# Agent calls retrieve_memories
memories = retrieve_memories({"message": "user's favorite color"})
# If found: "The user's favorite color is blue"
```
3. **Agent processes with context**:
- If memories found: Prepares a personalized response
- If no memories: Prepares to ask and store the information
4. **Agent responds**:
- With memory: "Yes, your favorite color is blue!"
- Without memory: "I don't think you've told me your favorite color before. What is it?"
5. **User responds**: "It's actually green."
6. **Agent stores new information**:
```python
# Agent calls add_memories
add_memories({"message": "The user's favorite color is green"})
```
7. **Agent confirms**: "Thanks, I'll remember that your favorite color is green."
## Example Use Cases
- **Personal Assistant** - Remember user preferences, past requests, and important dates
```
User: "What restaurants did I say I liked last time?"
Agent: *retrieves memories* "You mentioned enjoying Bella Italia and The Golden Dragon."
```
- **Customer Support** - Recall previous issues a customer has had
```
User: "I'm having that same problem again!"
Agent: *retrieves memories* "Is this related to the login issue you reported last week?"
```
- **Educational AI** - Track student progress and tailor teaching accordingly
```
User: "Let's continue our math lesson."
Agent: *retrieves memories* "Last time we were working on quadratic equations. Would you like to continue with that?"
```
- **Healthcare Assistant** - Remember symptoms, medications, and health concerns
```
User: "Have I told you about my allergy medication?"
Agent: *retrieves memories* "Yes, you mentioned you're taking Claritin for your pollen allergies."
```
## Troubleshooting
- **Missing API Keys**:
- Error: "API_KEY environment variable must be set"
- Solution: Ensure all environment variables are set correctly in your .env file or system environment
- **Connection Issues**:
- Error: "Failed to connect to API"
- Solution: Check your network connection and API key permissions. Verify the API keys are valid and have the necessary permissions.
- **Empty Memory Results**:
- Symptom: Agent always responds with "No memories found"
- Solution: This is normal for new users. The memory database builds up over time as conversations occur. It's also possible your query isn't semantically similar to stored memories - try different phrasing.
- **Agent Not Using Memories**:
- Symptom: The agent retrieves memories but doesn't incorporate them in responses
- Solution: Update the agent's prompt to explicitly instruct it to use the retrieved memories in its responses
## Conclusion
By integrating ElevenLabs Conversational AI with Mem0, you can create voice agents that maintain context across conversations and provide personalized responses based on user history. This powerful combination enables:
- More natural, context-aware conversations
- Personalized user experiences that improve over time
- Reduced need for users to repeat information
- Long-term relationship building between users and AI agents
## Help
- For more details on ElevenLabs, visit the [ElevenLabs Conversational AI Documentation](https://elevenlabs.io/docs/api-reference/conversational-ai)
- For Mem0 documentation, refer to the [Mem0 Platform](https://app.mem0.ai/)
- If you need further assistance, please feel free to reach out to us through the following methods:
<Snippet file="get-help.mdx" />
-126
View File
@@ -1,126 +0,0 @@
---
title: Flowise
---
The [**Mem0 Memory**](https://github.com/mem0ai/mem0) integration with [Flowise](https://github.com/FlowiseAI/Flowise) enables persistent memory capabilities for your AI chatflows. [Flowise](https://flowiseai.com/) is an open-source low-code tool for developers to build customized LLM orchestration flows & AI agents using a drag & drop interface.
## Overview
1. 🧠 Provides persistent memory storage for Flowise chatflows
2. 🔄 Seamless integration with existing Flowise templates
3. 🚀 Compatible with various LLM nodes in Flowise
4. 📝 Supports custom memory configurations
5. ⚡ Easy to set up and manage
## Prerequisites
Before setting up Mem0 with Flowise, ensure you have:
1. [Flowise installed](https://github.com/FlowiseAI/Flowise#⚡quick-start) (NodeJS >= 18.15.0 required):
```bash
npm install -g flowise
npx flowise start
```
2. Access to the Flowise UI at http://localhost:3000
3. Basic familiarity with [Flowise's LLM orchestration](https://flowiseai.com/#features) concepts
## Setup and Configuration
### 1. Set Up Flowise
1. Open the Flowise application and create a new canvas, or select a template from the Flowise marketplace.
2. In this example, we use the **Conversation Chain** template.
3. Replace the default **Buffer Memory** with **Mem0 Memory**.
![Flowise Memory Integration](https://raw.githubusercontent.com/FlowiseAI/FlowiseDocs/main/en/.gitbook/assets/mem0/flowise-flow.png)
### 2. Obtain Your Mem0 API Key
1. Navigate to the [Mem0 API Key dashboard](https://app.mem0.ai/dashboard/api-keys).
2. Generate or copy your existing Mem0 API Key.
![Mem0 API Key](https://raw.githubusercontent.com/FlowiseAI/FlowiseDocs/main/en/.gitbook/assets/mem0/api-key.png)
### 3. Configure Mem0 Credentials
1. Enter the **Mem0 API Key** in the Mem0 Credentials section.
2. Configure additional settings as needed:
```typescript
{
"apiKey": "m0-xxx",
"userId": "user-123", // Optional: Specify user ID
"projectId": "proj-xxx", // Optional: Specify project ID
"orgId": "org-xxx" // Optional: Specify organization ID
}
```
<figure>
<img src="https://raw.githubusercontent.com/FlowiseAI/FlowiseDocs/main/en/.gitbook/assets/mem0/creds.png" alt="Mem0 Credentials" />
<figcaption>Configure API Credentials</figcaption>
</figure>
## Memory Features
### 1. Basic Memory Storage
Test your memory configuration:
1. Save your Flowise configuration
2. Run a test chat and store some information
3. Verify the stored memories in the [Mem0 Dashboard](https://app.mem0.ai/dashboard/requests)
![Flowise Test Chat](https://raw.githubusercontent.com/FlowiseAI/FlowiseDocs/main/en/.gitbook/assets/mem0/flowise-chat-1.png)
### 2. Memory Retention
Validate memory persistence:
1. Clear the chat history in Flowise
2. Ask a question about previously stored information
3. Confirm that the AI remembers the context
![Testing Memory Retention](https://raw.githubusercontent.com/FlowiseAI/FlowiseDocs/main/en/.gitbook/assets/mem0/flowise-chat-2.png)
## Advanced Configuration
### Memory Settings
![Mem0 Settings](https://raw.githubusercontent.com/FlowiseAI/FlowiseDocs/main/en/.gitbook/assets/mem0/settings.png)
Available settings include:
1. **Search Only Mode**: Enable memory retrieval without creating new memories
2. **Mem0 Entities**: Configure identifiers:
- `user_id`: Unique identifier for each user
- `run_id`: Specific conversation session ID
- `app_id`: Application identifier
- `agent_id`: AI agent identifier
3. **Project ID**: Assign memories to specific projects
4. **Organization ID**: Organize memories by organization
### Platform Configuration
Additional settings available in [Mem0 Project Settings](https://app.mem0.ai/dashboard/project-settings):
1. **Custom Instructions**: Define memory extraction rules
2. **Expiration Date**: Set automatic memory cleanup periods
![Mem0 Project Settings](https://raw.githubusercontent.com/FlowiseAI/FlowiseDocs/main/en/.gitbook/assets/mem0/mem0-settings.png)
## Best Practices
1. **User Identification**: Use consistent `user_id` values for reliable memory retrieval
2. **Memory Organization**: Utilize projects and organizations for better memory management
3. **Regular Maintenance**: Monitor and clean up unused memories periodically
## Help & Resources
- [Flowise Documentation](https://flowiseai.com/docs)
- [Flowise GitHub Repository](https://github.com/FlowiseAI/Flowise)
- [Flowise Website](https://flowiseai.com/)
- [Mem0 Platform](https://app.mem0.ai/)
- Need assistance? Reach out through:
<Snippet file="get-help.mdx" />
-287
View File
@@ -1,287 +0,0 @@
---
title: Google ADK
---
Integrate [**Mem0**](https://github.com/mem0ai/mem0) with [Google ADK (Agent Development Kit)](https://github.com/google/adk-python), an open-source framework for building multi-agent workflows. This integration enables agents to access persistent memory across conversations, enhancing context retention and personalization.
## Overview
1. Store and retrieve memories from Mem0 within Google ADK agents
2. Multi-agent workflows with shared memory across hierarchies
3. Retrieve relevant memories from past conversations
4. Personalized responses
## Prerequisites
Before setting up Mem0 with Google ADK, ensure you have:
1. Installed the required packages:
```bash
pip install google-adk mem0ai python-dotenv
```
2. Valid API keys:
- [Mem0 API Key](https://app.mem0.ai/dashboard/api-keys)
- Google AI Studio API Key
## Basic Integration Example
The following example demonstrates how to create a Google ADK agent with Mem0 memory integration:
```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"
# Initialize Mem0 client
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, output_format='v1.1')
if 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:
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)}"}
# Create agent with memory capabilities
personal_assistant = Agent(
name="personal_assistant",
model="gemini-2.0-flash",
instruction="""You are a helpful personal assistant with memory capabilities.
Use the search_memory function to recall past conversations and user preferences.
Use the save_memory function to store important information about the user.
Always personalize your responses based on available memory.""",
description="A personal assistant that remembers user preferences and past interactions",
tools=[search_memory, save_memory]
)
async def chat_with_agent(user_input: str, user_id: str) -> str:
"""
Handle user input with automatic memory integration.
Args:
user_input: The user's message
user_id: Unique identifier for the user
Returns:
The agent's response
"""
# Set up session and runner
session_service = InMemorySessionService()
session = await session_service.create_session(
app_name="memory_assistant",
user_id=user_id,
session_id=f"session_{user_id}"
)
runner = Runner(agent=personal_assistant, app_name="memory_assistant", session_service=session_service)
# Create content and run agent
content = types.Content(role='user', parts=[types.Part(text=user_input)])
events = runner.run(user_id=user_id, session_id=session.id, new_message=content)
# Extract final response
for event in events:
if event.is_final_response():
response = event.content.parts[0].text
return response
return "No response generated"
# Example usage
if __name__ == "__main__":
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)
```
## Multi-Agent Hierarchy with Shared Memory
Create specialized agents in a hierarchy that share memory:
```python
from google.adk.tools.agent_tool import AgentTool
# Travel specialist agent
travel_agent = Agent(
name="travel_specialist",
model="gemini-2.0-flash",
instruction="""You are a travel planning specialist. Use get_user_context to
understand the user's travel preferences and history before making recommendations.
After providing advice, use store_interaction to save travel-related information.""",
description="Specialist in travel planning and recommendations",
tools=[search_memory, save_memory]
)
# Health advisor agent
health_agent = Agent(
name="health_advisor",
model="gemini-2.0-flash",
instruction="""You are a health and wellness advisor. Use get_user_context to
understand the user's health goals and dietary preferences.
After providing advice, use store_interaction to save health-related information.""",
description="Specialist in health and wellness advice",
tools=[search_memory, save_memory]
)
# Coordinator agent that delegates to specialists
coordinator_agent = Agent(
name="coordinator",
model="gemini-2.0-flash",
instruction="""You are a coordinator that delegates requests to specialist agents.
For travel-related questions (trips, hotels, flights, destinations), delegate to the travel specialist.
For health-related questions (fitness, diet, wellness, exercise), delegate to the health advisor.
Use get_user_context to understand the user before delegation.""",
description="Coordinates requests between specialist agents",
tools=[
AgentTool(agent=travel_agent, skip_summarization=False),
AgentTool(agent=health_agent, skip_summarization=False)
]
)
def chat_with_specialists(user_input: str, user_id: str) -> str:
"""
Handle user input with specialist agent delegation and memory.
Args:
user_input: The user's message
user_id: Unique identifier for the user
Returns:
The specialist agent's response
"""
session_service = InMemorySessionService()
session = session_service.create_session(
app_name="specialist_system",
user_id=user_id,
session_id=f"session_{user_id}"
)
runner = Runner(agent=coordinator_agent, app_name="specialist_system", session_service=session_service)
content = types.Content(role='user', parts=[types.Part(text=user_input)])
events = runner.run(user_id=user_id, session_id=session.id, new_message=content)
for event in events:
if event.is_final_response():
response = event.content.parts[0].text
# Store the conversation in shared memory
conversation = [
{"role": "user", "content": user_input},
{"role": "assistant", "content": response}
]
mem0.add(conversation, user_id=user_id)
return response
return "No response generated"
# Example usage
response = chat_with_specialists("Plan a healthy meal for my Italy trip", user_id="alice")
print(response)
```
## Quick Start Chat Interface
Simple interactive chat with memory and Google ADK:
```python
def interactive_chat():
"""Interactive chat interface with memory and ADK"""
user_id = input("Enter your user ID: ") or "demo_user"
print(f"Chat started for user: {user_id}")
print("Type 'quit' to exit")
print("=" * 50)
while True:
user_input = input("\nYou: ")
if user_input.lower() == 'quit':
print("Goodbye! Your conversation has been saved to memory.")
break
else:
response = chat_with_specialists(user_input, user_id)
print(f"Assistant: {response}")
if __name__ == "__main__":
interactive_chat()
```
## Key Features
### 1. Memory-Enhanced Function Tools
- **Function Tools**: Standard Python functions that can search and save memories
- **Tool Context**: Access to session state and memory through function parameters
- **Structured Returns**: Dictionary-based returns with status indicators for better LLM understanding
### 2. Multi-Agent Memory Sharing
- **Agent-as-a-Tool**: Specialists can be called as tools while maintaining shared memory
- **Hierarchical Delegation**: Coordinator agents route to specialists based on context
- **Memory Categories**: Store interactions with metadata for better organization
### 3. Flexible Memory Operations
- **Search Capabilities**: Retrieve relevant memories through conversation history
- **User Segmentation**: Organize memories by user ID
- **Memory Management**: Built-in tools for saving and retrieving information
## Configuration Options
Customize memory behavior and agent setup:
```python
# Configure memory search with metadata
memories = mem0.search(
query="travel preferences",
user_id="alice",
limit=5,
filters={"category": "travel"} # Filter by category if supported
)
# Configure agent with custom model settings
agent = Agent(
name="custom_agent",
model="gemini-2.0-flash", # or use LiteLLM for other models
instruction="Custom agent behavior",
tools=[memory_tools],
# Additional ADK configurations
)
# Use Google Cloud Vertex AI instead of AI Studio
os.environ["GOOGLE_GENAI_USE_VERTEXAI"] = "True"
os.environ["GOOGLE_CLOUD_PROJECT"] = "your-project-id"
os.environ["GOOGLE_CLOUD_LOCATION"] = "us-central1"
```
## Help
- [Google ADK Documentation](https://google.github.io/adk-docs/)
- [Mem0 Platform](https://app.mem0.ai/)
- If you need further assistance, please feel free to reach out to us through the following methods:
<Snippet file="get-help.mdx" />
-140
View File
@@ -1,140 +0,0 @@
---
title: Keywords AI
---
Build AI applications with persistent memory and comprehensive LLM observability by integrating Mem0 with Keywords AI.
## Overview
Mem0 is a self-improving memory layer for LLM applications, enabling personalized AI experiences that save costs and delight users. Keywords AI provides complete LLM observability.
Combining Mem0 with Keywords AI allows you to:
1. Add persistent memory to your AI applications
2. Track interactions across sessions
3. Monitor memory usage and retrieval with Keywords AI observability
4. Optimize token usage and reduce costs
<Note>
You can get your Mem0 API key, user_id, and org_id from the [Mem0 dashboard](https://app.mem0.ai/). These are required for proper integration.
</Note>
## Setup and Configuration
Install the necessary libraries:
```bash
pip install mem0 keywordsai-sdk
```
Set up your environment variables:
```python
import os
# Set your API keys
os.environ["MEM0_API_KEY"] = "your-mem0-api-key"
os.environ["KEYWORDSAI_API_KEY"] = "your-keywords-api-key"
os.environ["KEYWORDSAI_BASE_URL"] = "https://api.keywordsai.co/api/"
```
## Basic Integration Example
Here's a simple example of using Mem0 with Keywords AI:
```python
from mem0 import Memory
import os
# Configuration
api_key = os.getenv("MEM0_API_KEY")
keywordsai_api_key = os.getenv("KEYWORDSAI_API_KEY")
base_url = os.getenv("KEYWORDSAI_BASE_URL") # "https://api.keywordsai.co/api/"
# Set up Mem0 with Keywords AI as the LLM provider
config = {
"llm": {
"provider": "openai",
"config": {
"model": "gpt-4.1-nano-2025-04-14",
"temperature": 0.0,
"api_key": keywordsai_api_key,
"openai_base_url": base_url,
},
}
}
# Initialize Memory
memory = Memory.from_config(config_dict=config)
# Add a memory
result = memory.add(
"I like to take long walks on weekends.",
user_id="alice",
metadata={"category": "hobbies"},
)
print(result)
```
## Advanced Integration with OpenAI SDK
For more advanced use cases, you can integrate Keywords AI with Mem0 through the OpenAI SDK:
```python
from openai import OpenAI
import os
import json
# Initialize client
client = OpenAI(
api_key=os.environ.get("KEYWORDSAI_API_KEY"),
base_url=os.environ.get("KEYWORDSAI_BASE_URL"),
)
# Sample conversation messages
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."}
]
# Add memory and generate a response
response = client.chat.completions.create(
model="openai/gpt-4.1-nano",
messages=messages,
extra_body={
"mem0_params": {
"user_id": "test_user",
"org_id": "org_1",
"api_key": os.environ.get("MEM0_API_KEY"),
"add_memories": {
"messages": messages,
},
}
},
)
print(json.dumps(response.model_dump(), indent=4))
```
For detailed information on this integration, refer to the official [Keywords AI Mem0 integration documentation](https://docs.keywordsai.co/integration/development-frameworks/mem0).
## Key Features
1. **Memory Integration**: Store and retrieve relevant information from past interactions
2. **LLM Observability**: Track memory usage and retrieval patterns with Keywords AI
3. **Session Persistence**: Maintain context across multiple user sessions
4. **Cost Optimization**: Reduce token usage through efficient memory retrieval
## Conclusion
Integrating Mem0 with Keywords AI provides a powerful combination for building AI applications with persistent memory and comprehensive observability. This integration enables more personalized user experiences while providing insights into your application's memory usage.
## Help
For more information, refer to:
- [Keywords AI Documentation](https://docs.keywordsai.co)
- [Mem0 Platform](https://app.mem0.ai/)
<Snippet file="get-help.mdx" />
-336
View File
@@ -1,336 +0,0 @@
---
title: Langchain Tools
description: 'Integrate Mem0 with LangChain tools to enable AI agents to store, search, and manage memories through structured interfaces'
---
## Overview
Mem0 provides a suite of tools for storing, searching, and retrieving memories, enabling agents to maintain context and learn from past interactions. The tools are built as Langchain tools, making them easily integrable with any AI agent implementation.
## Installation
Install the required dependencies:
```bash
pip install langchain_core
pip install mem0ai
```
## Authentication
Import the necessary dependencies and initialize the client:
```python
from langchain_core.tools import StructuredTool
from mem0 import MemoryClient
from pydantic import BaseModel, Field
from typing import List, Dict, Any, Optional
import os
os.environ["MEM0_API_KEY"] = "your-api-key"
client = MemoryClient(
org_id=your_org_id,
project_id=your_project_id
)
```
## Available Tools
Mem0 provides three main tools for memory management:
### 1. ADD Memory Tool
The ADD tool allows you to store new memories with associated metadata. It's particularly useful for saving conversation history and user preferences.
#### Schema
```python
class Message(BaseModel):
role: str = Field(description="Role of the message sender (user or assistant)")
content: str = Field(description="Content of the message")
class AddMemoryInput(BaseModel):
messages: List[Message] = Field(description="List of messages to add to memory")
user_id: str = Field(description="ID of the user associated with these messages")
output_format: str = Field(description="Version format for the output")
metadata: Optional[Dict[str, Any]] = Field(description="Additional metadata for the messages", default=None)
class Config:
json_schema_extra = {
"examples": [{
"messages": [
{"role": "user", "content": "Hi, I'm Alex. I'm a vegetarian and I'm allergic to nuts."},
{"role": "assistant", "content": "Hello Alex! I've noted that you're a vegetarian and have a nut allergy."}
],
"user_id": "alex",
"output_format": "v1.1",
"metadata": {"food": "vegan"}
}]
}
```
#### Implementation
```python
def add_memory(messages: List[Message], user_id: str, output_format: str, metadata: Optional[Dict[str, Any]] = None) -> Any:
"""Add messages to memory with associated user ID and metadata."""
message_dicts = [msg.dict() for msg in messages]
return client.add(message_dicts, user_id=user_id, output_format=output_format, metadata=metadata)
add_tool = StructuredTool(
name="add_memory",
description="Add new messages to memory with associated metadata",
func=add_memory,
args_schema=AddMemoryInput
)
```
#### Example Usage
<CodeGroup>
```python Code
add_input = {
"messages": [
{"role": "user", "content": "Hi, I'm Alex. I'm a vegetarian and I'm allergic to nuts."},
{"role": "assistant", "content": "Hello Alex! I've noted that you're a vegetarian and have a nut allergy."}
],
"user_id": "alex",
"output_format": "v1.1",
"metadata": {"food": "vegan"}
}
add_result = add_tool.invoke(add_input)
```
```json Output
{
"results": [
{
"memory": "Name is Alex",
"event": "ADD"
},
{
"memory": "Is a vegetarian",
"event": "ADD"
},
{
"memory": "Is allergic to nuts",
"event": "ADD"
}
]
}
```
</CodeGroup>
### 2. SEARCH Memory Tool
The SEARCH tool enables querying stored memories using natural language queries and advanced filtering options.
#### Schema
```python
class SearchMemoryInput(BaseModel):
query: str = Field(description="The search query string")
filters: Dict[str, Any] = Field(description="Filters to apply to the search")
version: str = Field(description="Version of the memory to search")
class Config:
json_schema_extra = {
"examples": [{
"query": "tell me about my allergies?",
"filters": {
"AND": [
{"user_id": "alex"},
{"created_at": {"gte": "2024-01-01", "lte": "2024-12-31"}}
]
},
"version": "v2"
}]
}
```
#### Implementation
```python
def search_memory(query: str, filters: Dict[str, Any], version: str) -> Any:
"""Search memory with the given query and filters."""
return client.search(query=query, version=version, filters=filters)
search_tool = StructuredTool(
name="search_memory",
description="Search through memories with a query and filters",
func=search_memory,
args_schema=SearchMemoryInput
)
```
#### Example Usage
<CodeGroup>
```python Code
search_input = {
"query": "what is my name?",
"filters": {
"AND": [
{"created_at": {"gte": "2024-07-20", "lte": "2024-12-10"}},
{"user_id": "alex"}
]
},
"version": "v2"
}
result = search_tool.invoke(search_input)
```
```json Output
[
{
"id": "1a75e827-7eca-45ea-8c5c-cfd43299f061",
"memory": "Name is Alex",
"user_id": "alex",
"hash": "d0fccc8fa47f7a149ee95750c37bb0ca",
"metadata": {
"food": "vegan"
},
"categories": [
"personal_details"
],
"created_at": "2024-11-27T16:53:43.276872-08:00",
"updated_at": "2024-11-27T16:53:43.276885-08:00",
"score": 0.3810526501504994
}
]
```
</CodeGroup>
### 3. GET_ALL Memory Tool
The GET_ALL tool retrieves all memories matching specified criteria, with support for pagination.
#### Schema
```python
class GetAllMemoryInput(BaseModel):
version: str = Field(description="Version of the memory to retrieve")
filters: Dict[str, Any] = Field(description="Filters to apply to the retrieval")
page: Optional[int] = Field(description="Page number for pagination", default=1)
page_size: Optional[int] = Field(description="Number of items per page", default=50)
class Config:
json_schema_extra = {
"examples": [{
"version": "v2",
"filters": {
"AND": [
{"user_id": "alex"},
{"created_at": {"gte": "2024-07-01", "lte": "2024-07-31"}},
{"categories": {"contains": "food_preferences"}}
]
},
"page": 1,
"page_size": 50
}]
}
```
#### Implementation
```python
def get_all_memory(version: str, filters: Dict[str, Any], page: int = 1, page_size: int = 50) -> Any:
"""Retrieve all memories matching the specified criteria."""
return client.get_all(version=version, filters=filters, page=page, page_size=page_size)
get_all_tool = StructuredTool(
name="get_all_memory",
description="Retrieve all memories matching specified filters",
func=get_all_memory,
args_schema=GetAllMemoryInput
)
```
#### Example Usage
<CodeGroup>
```python Code
get_all_input = {
"version": "v2",
"filters": {
"AND": [
{"user_id": "alex"},
{"created_at": {"gte": "2024-07-01", "lte": "2024-12-31"}}
]
},
"page": 1,
"page_size": 50
}
get_all_result = get_all_tool.invoke(get_all_input)
```
```json Output
{
"count": 3,
"next": null,
"previous": null,
"results": [
{
"id": "1a75e827-7eca-45ea-8c5c-cfd43299f061",
"memory": "Name is Alex",
"user_id": "alex",
"hash": "d0fccc8fa47f7a149ee95750c37bb0ca",
"metadata": {
"food": "vegan"
},
"categories": [
"personal_details"
],
"created_at": "2024-11-27T16:53:43.276872-08:00",
"updated_at": "2024-11-27T16:53:43.276885-08:00"
},
{
"id": "91509588-0b39-408a-8df3-84b3bce8c521",
"memory": "Is a vegetarian",
"user_id": "alex",
"hash": "ce6b1c84586772ab9995a9477032df99",
"metadata": {
"food": "vegan"
},
"categories": [
"user_preferences",
"food"
],
"created_at": "2024-11-27T16:53:43.308027-08:00",
"updated_at": "2024-11-27T16:53:43.308037-08:00"
},
{
"id": "8d74f7a0-6107-4589-bd6f-210f6bf4fbbb",
"memory": "Is allergic to nuts",
"user_id": "alex",
"hash": "7873cd0e5a29c513253d9fad038e758b",
"metadata": {
"food": "vegan"
},
"categories": [
"health"
],
"created_at": "2024-11-27T16:53:43.337253-08:00",
"updated_at": "2024-11-27T16:53:43.337262-08:00"
}
]
}
```
</CodeGroup>
## Integration with AI Agents
All tools are implemented as Langchain `StructuredTool` instances, making them compatible with any AI agent that supports the Langchain tools interface. To use these tools with your agent:
1. Initialize the tools as shown above
2. Add the tools to your agent's toolset
3. The agent can now use these tools to manage memories through natural language interactions
Each tool provides structured input validation through Pydantic models and returns consistent responses that can be processed by your agent.
## Help
In case of any questions, please feel free to reach out to us using one of the following methods:
<Snippet file="get-help.mdx" />
-171
View File
@@ -1,171 +0,0 @@
---
title: Langchain
---
Build a personalized Travel Agent AI using LangChain for conversation flow and Mem0 for memory retention. This integration enables context-aware and efficient travel planning experiences.
## Overview
In this guide, we'll create a Travel Agent AI that:
1. Uses LangChain to manage conversation flow
2. Leverages Mem0 to store and retrieve relevant information from past interactions
3. Provides personalized travel recommendations based on user history
## Setup and Configuration
Install necessary libraries:
```bash
pip install langchain langchain_openai mem0ai python-dotenv
```
Import required modules and set up configurations:
<Note>Remember to get the Mem0 API key from [Mem0 Platform](https://app.mem0.ai).</Note>
```python
import os
from typing import List, Dict
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"
# Initialize LangChain and Mem0
llm = ChatOpenAI(model="gpt-4.1-nano-2025-04-14")
mem0 = MemoryClient()
```
## Create Prompt Template
Set up the conversation prompt template:
```python
prompt = ChatPromptTemplate.from_messages([
SystemMessage(content="""You are a helpful travel agent AI. Use the provided context to personalize your responses and remember user preferences and past interactions.
Provide travel recommendations, itinerary suggestions, and answer questions about destinations.
If you don't have specific information, you can make general suggestions based on common travel knowledge."""),
MessagesPlaceholder(variable_name="context"),
HumanMessage(content="{input}")
])
```
## Define Helper Functions
Create functions to handle context retrieval, response generation, and addition to Mem0:
```python
def retrieve_context(query: str, user_id: str) -> List[Dict]:
"""Retrieve relevant context from Mem0"""
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"""
chain = prompt | llm
response = chain.invoke({
"context": context,
"input": input
})
return response.content
def save_interaction(user_id: str, user_input: str, assistant_response: str):
"""Save the interaction to Mem0"""
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
Implement the main function to manage a single turn of conversation:
```python
def chat_turn(user_input: str, user_id: str) -> str:
# Retrieve context
context = retrieve_context(user_input, user_id)
# Generate response
response = generate_response(user_input, context)
# Save interaction
save_interaction(user_id, user_input, response)
return response
```
## Main Interaction Loop
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 = "alice"
while True:
user_input = input("You: ")
if user_input.lower() in ['quit', 'exit', 'bye']:
print("Travel Agent: Thank you for using our travel planning service. Have a great trip!")
break
response = chat_turn(user_input, user_id)
print(f"Travel Agent: {response}")
```
## Key Features
1. **Memory Integration**: Uses Mem0 to store and retrieve relevant information from past interactions.
2. **Personalization**: Provides context-aware responses based on user history and preferences.
3. **Flexible Architecture**: LangChain structure allows for easy expansion of the conversation flow.
4. **Continuous Learning**: Each interaction is stored, improving future responses.
## Conclusion
By integrating LangChain with Mem0, you can build a personalized Travel Agent AI that can maintain context across interactions and provide tailored travel recommendations and assistance.
## Help
- For more details on LangChain, visit the [LangChain documentation](https://python.langchain.com/).
- [Mem0 Platform](https://app.mem0.ai/).
- If you need further assistance, please feel free to reach out to us through the following methods:
<Snippet file="get-help.mdx" />

Some files were not shown because too many files have changed in this diff Show More