Compare commits

..

38 Commits

Author SHA1 Message Date
Parshva Daftari 5e8d5e4664 Release 0.1.117 (#3411) 2025-09-03 23:09:00 +05:30
Shili Cao c8d864c1b6 fix: add missing provider for baidu vector db (#3405) 2025-09-03 15:24:33 +05:30
Prateek Chhikara 617aabe5b3 [FIX] Graph Docs page was missing on the side bar (#3402) 2025-09-02 13:32:23 -07:00
Prateek Chhikara 163dafb216 Add version param in search v2 API documentation (#3401) 2025-09-02 13:24:22 -07:00
Srishti Gureja cc15a22bf9 support store for openai (#3399) 2025-09-02 21:23:59 +05:30
Parshva Daftari 64cbe84089 Updated favicon logo (#3398) 2025-09-02 21:10:04 +05:30
Parshva Daftari c8f9f20dff Updated integration docs (#3392) 2025-09-02 04:26:43 +05:30
John Lockwood 97fd320bbf Fix/new mem mistaken for current fixing #2875 (#2876) 2025-09-01 19:46:01 +05:30
Saket Aryan 748620f29b fix(Vercel AI SDK): Streaming not working properly (#3386) 2025-08-30 21:58:30 +05:30
Srishti Gureja 0b2aa36e98 Bugfix: Pick AWS region from the environment variable correctly (#3384) 2025-08-30 01:43:02 +05:30
Sheharyar Ahmad 3d0ece1bcf Refactor PGVector to Use Internal Connection Pools and Context Managers (#3373) 2025-08-29 19:06:39 +05:30
Rupam Jana 458d7ab8a3 replace query_vector args in search method of mongodb vector_stores (#3379) 2025-08-29 19:05:25 +05:30
Tushar Chandra 84af5ad265 docs: fix typo in docs/platform/advanced-memory-operations.mdx (#3348) 2025-08-27 17:35:45 -07:00
VikramIyer125 6237a6acb9 Adding weaviate, faiss, pgvector, chroma, redis, elasticsearch, milvus vector store to openmemory (#3366)
Co-authored-by: Vikram Iyer <vikramiyer@mac.local.meter>
2025-08-27 01:47:39 +05:30
VikramIyer125 8c8368781d Adding custom connection to weaviate connection client to enable client connection to local container (#3360)
Co-authored-by: Vikram Iyer <vikramiyer@Vikrams-MacBook-Pro.local>
2025-08-25 23:54:02 +05:30
Padarn Wilson 3b2d0ad0eb Fix missing commas in Kuzu graph INSERT queries (#3358) 2025-08-24 12:33:51 +05:30
Andy Kwok 9337a873ec Fix: Missing app_id on Neptune Analytics client (#3278)
Signed-off-by: Andy Kwok <andy.kwok@improving.com>
2025-08-23 21:06:19 +05:30
Srishti Gureja 76411e2591 docs fix: remove user_id from from_config (#3320) 2025-08-23 17:11:56 +05:30
Andy Kwok d523070cbc fix: Inconsistent created and updated properties on graph (#3220)
Signed-off-by: Andy Kwok <andy.kwok@improving.com>
2025-08-23 16:51:13 +05:30
Enzo Biondo c72bfc3285 Add Amazon S3 Vectors Support (#3237) 2025-08-23 16:44:42 +05:30
Parshva Daftari ee00bd5731 Fix typescript docs (#3357) 2025-08-22 14:23:26 -07:00
VikramIyer125 f914dca659 Add export_openmemory.sh migration script (#3352)
Co-authored-by: Vikram Iyer <vikramiyer@Vikrams-MacBook-Pro.local>
2025-08-22 20:19:41 +05:30
VikramIyer125 b64792590e Add memory export / import feature (#3345)
Co-authored-by: Vikram Iyer <vikramiyer@Vikrams-MacBook-Pro.local>
2025-08-21 23:27:28 +05:30
Parshva Daftari a7ac8bf13b Updated discord and dashboard image (#3344) 2025-08-20 14:11:26 -07:00
David A. Torres 4487785cec feature: add Azure Identity for Azure OpenAI and Azure AI Search authentication (#3262) 2025-08-21 02:00:27 +05:30
NiLAy e4c5582808 fix-migration-collection-override (#3100)
Co-authored-by: parshvadaftari <daftariparshva@gmail.com>
2025-08-21 00:11:28 +05:30
Vương Hữu Hưng (Hans) ff399e5528 Fix: Ollama checking model exists (#2682) 2025-08-19 16:29:26 +05:30
Parshva Daftari e7013764f7 Update aws bedrock (#3334) 2025-08-19 02:20:34 +05:30
Parshva Daftari c8ee17b884 Fix dependency and tests and updated docstring (#3337) 2025-08-19 02:12:24 +05:30
AkisAya 346b913ace feat: add es headers config (#3088) 2025-08-19 01:15:23 +05:30
Parshva Daftari 49ad64708b Updated databricks docs (#3336) 2025-08-18 13:24:32 -05:00
Josh Hayes 3a1eff425b feat(vector-store): Add Databricks Mosaic AI vector store support (#3325) 2025-08-18 22:20:33 +05:30
Parshva Daftari ebb411b11a Refactor docs (#3335) 2025-08-18 20:45:09 +05:30
Archie Sengupta 8e8f13a48e feat(Vercel AI SDK): add a param in config called host (#2634)
Co-authored-by: Saket Aryan <94069182+whysosaket@users.noreply.github.com>
2025-08-17 16:21:06 +05:30
Siddhartha Sahu a6a3928091 Add support for graph memory using Kuzu (#2934) 2025-08-16 02:22:31 +05:30
Ankush Malaker a883b56aa8 AsyncMemory._add_to_vector_store bugfix when no facts found (#3313) 2025-08-15 22:15:00 +05:30
Deshraj Yadav 246d9e8f69 Update llms.txt file (#3321) 2025-08-14 14:51:03 -07:00
Deshraj Yadav 192db1844c Update Docs (#3315) 2025-08-13 21:37:15 -07:00
210 changed files with 11263 additions and 4397 deletions
+54 -3
View File
@@ -86,7 +86,6 @@ const memory = new Memory({
const result = await memory.add('My name is John', { userId: 'john' });
```
## Core API Reference
### Memory Class (Self-Hosted)
@@ -305,7 +304,7 @@ config = MemoryConfig(
- **langchain** - LangChain embeddings
- **aws_bedrock** - AWS Bedrock embeddings
#### Vector Store Providers (17 supported)
#### Vector Store Providers (19 supported)
- **qdrant** - Qdrant vector database (default)
- **chroma** - ChromaDB
- **pinecone** - Pinecone vector database
@@ -323,11 +322,14 @@ config = MemoryConfig(
- **supabase** - Supabase vector
- **baidu** - Baidu vector database
- **langchain** - LangChain vector stores
- **s3_vectors** - Amazon S3 Vectors
- **databricks** - Databricks vector stores
#### Graph Store Providers (3 supported)
#### Graph Store Providers (4 supported)
- **neo4j** - Neo4j graph database
- **memgraph** - Memgraph
- **neptune** - AWS Neptune Analytics
- **kuzu** - Kuzu Graph database
### Configuration Examples
@@ -415,6 +417,54 @@ config = MemoryConfig(
)
```
#### LLM Providers
- **OpenAI** - GPT-4, GPT-3.5-turbo, and structured outputs
- **Anthropic** - Claude models with advanced reasoning
- **Google AI** - Gemini models for multimodal applications
- **AWS Bedrock** - Enterprise-grade AWS managed models
- **Azure OpenAI** - Microsoft Azure hosted OpenAI models
- **Groq** - High-performance LPU optimized models
- **Together** - Open-source model inference platform
- **Ollama** - Local model deployment for privacy
- **vLLM** - High-performance inference framework
- **LM Studio** - Local model management
- **DeepSeek** - Advanced reasoning models
- **Sarvam** - Indian language models
- **XAI** - xAI models
- **LiteLLM** - Unified LLM interface
- **LangChain** - LangChain LLM integration
#### Vector Store Providers
- **Chroma** - AI-native open-source vector database
- **Qdrant** - High-performance vector similarity search
- **Pinecone** - Managed vector database with serverless options
- **Weaviate** - Open-source vector search engine
- **PGVector** - PostgreSQL extension for vector search
- **Milvus** - Open-source vector database for scale
- **Redis** - Real-time vector storage with Redis Stack
- **Supabase** - Open-source Firebase alternative
- **Upstash Vector** - Serverless vector database
- **Elasticsearch** - Distributed search and analytics
- **OpenSearch** - Open-source search and analytics
- **FAISS** - Facebook AI Similarity Search
- **MongoDB** - Document database with vector search
- **Azure AI Search** - Microsoft's search service
- **Vertex AI Vector Search** - Google Cloud vector search
- **Databricks Vector Search** - Delta Lake integration
- **Baidu** - Baidu vector database
- **LangChain** - LangChain vector store integration
#### Embedding Providers
- **OpenAI** - High-quality text embeddings
- **Azure OpenAI** - Enterprise Azure-hosted embeddings
- **Google AI** - Gemini embedding models
- **AWS Bedrock** - Amazon embedding models
- **Hugging Face** - Open-source embedding models
- **Vertex AI** - Google Cloud enterprise embeddings
- **Ollama** - Local embedding models
- **Together** - Open-source model embeddings
- **LM Studio** - Local model embeddings
- **LangChain** - LangChain embedder integration
## TypeScript/JavaScript SDK
@@ -569,6 +619,7 @@ print(result["relations"]) # Graph relationships
- **Neo4j**: Full-featured graph database with Cypher queries
- **Memgraph**: High-performance in-memory graph database
- **Neptune**: AWS managed graph database service
- **kuzu** - OSS Kuzu Graph database
### Multimodal Memory
+1 -1
View File
@@ -13,7 +13,7 @@ install:
install_all:
pip install ruff==0.6.9 groq together boto3 litellm ollama chromadb weaviate weaviate-client sentence_transformers vertexai \
google-generativeai elasticsearch opensearch-py vecs "pinecone<7.0.0" pinecone-text faiss-cpu langchain-community \
upstash-vector azure-search-documents langchain-memgraph langchain-neo4j langchain-aws rank-bm25 pymochow pymongo psycopg
upstash-vector azure-search-documents langchain-memgraph langchain-neo4j langchain-aws rank-bm25 pymochow pymongo psycopg kuzu databricks-sdk
# Format code with ruff
format:
+1 -1
View File
@@ -21,7 +21,7 @@
<p align="center">
<a href="https://mem0.dev/DiG">
<img src="https://dcbadge.vercel.app/api/server/6PzXDgEjG5?style=flat" alt="Mem0 Discord">
<img src="https://img.shields.io/badge/Discord-%235865F2.svg?&logo=discord&logoColor=white" alt="Mem0 Discord">
</a>
<a href="https://pepy.tech/project/mem0ai">
<img src="https://img.shields.io/pypi/dm/mem0ai" alt="Mem0 PyPI - Downloads">
-3
View File
@@ -1,3 +0,0 @@
<Note type="info">
🔐 Mem0 is now <strong>SOC 2</strong> and <strong>HIPAA</strong> compliant! We're committed to the highest standards of data security and privacy, enabling secure memory for enterprises, healthcare, and beyond. [Learn more](https://mem0.ai/security)
</Note>
-2
View File
@@ -4,8 +4,6 @@ icon: "info"
iconType: "solid"
---
<Snippet file="async-memory-add.mdx" />
Mem0 provides a powerful set of APIs that allow you to integrate advanced memory management capabilities into your applications. Our APIs are designed to be intuitive, efficient, and scalable, enabling you to create, retrieve, update, and delete memories across various entities such as users, agents, apps, and runs.
## Key Features
@@ -1,4 +0,0 @@
---
title: 'Delete Member'
openapi: delete /api/v1/orgs/organizations/{org_id}/members/
---
@@ -1,9 +0,0 @@
---
title: 'Update Member'
openapi: put /api/v1/orgs/organizations/{org_id}/members/
---
The API provides two roles for organization members:
- `READER`: Allows viewing of organization resources.
- `OWNER`: Grants full administrative access to manage the organization and its resources.
@@ -1,4 +0,0 @@
---
title: 'Delete Member'
openapi: delete /api/v1/orgs/organizations/{org_id}/projects/{project_id}/members/
---
@@ -1,9 +0,0 @@
---
title: 'Update Member'
openapi: put /api/v1/orgs/organizations/{org_id}/projects/{project_id}/members/
---
The API provides two roles for project members:
- `READER`: Allows viewing of project resources.
- `OWNER`: Grants full administrative access to manage the project and its resources.
@@ -1,4 +0,0 @@
---
title: 'Update Project'
openapi: patch /api/v1/orgs/organizations/{org_id}/projects/{project_id}/
---
+114 -14
View File
@@ -3,11 +3,102 @@ title: "Product Updates"
mode: "wide"
---
<Snippet file="blank-notif.mdx" />
<Tabs>
<Tab title="Python">
<Update label="2025-09-03" description="v0.1.117">
**New Features & Updates:**
- **OpenMemory:**
- Added memory export / import feature
- Added vector store integrations: Weaviate, FAISS, PGVector, Chroma, Redis, Elasticsearch, Milvus
- Added `export_openmemory.sh` migration script
- **Vector Stores:**
- Added Amazon S3 Vectors support
- Added Databricks Mosaic AI vector store support
- Added support for OpenAI Store
- **Graph Memory:** Added support for graph memory using Kuzu
- **Azure:** Added Azure Identity for Azure OpenAI and Azure AI Search authentication
- **Elasticsearch:** Added headers configuration support
**Improvements:**
- Added custom connection client to enable connecting to local containers for Weaviate
- Updated configuration AWS Bedrock
- Fixed dependency issues and tests; updated docstrings
- **Documentation:**
- Fixed Graph Docs page missing in sidebar
- Updated integration documentation
- Added version param in Search V2 API documentation
- Updated Databricks documentation and refactored docs
- Updated favicon logo
- Fixed typos and Typescript docs
**Bug Fixes:**
- Baidu: Added missing provider for Baidu vector DB
- MongoDB: Replaced `query_vector` args in search method
- Fixed new memory mistaken for current
- AsyncMemory._add_to_vector_store: handled edge case when no facts found
- Fixed missing commas in Kuzu graph INSERT queries
- Fixed inconsistent created and updated properties for Graph
- Fixed missing `app_id` on client for Neptune Analytics
- Correctly pick AWS region from environment variable
- Fixed Ollama model existence check
**Refactoring:**
- **PGVector:** Use internal connection pools and context managers
</Update>
<Update label="2025-08-14" description="v0.1.116">
**New Features & Updates:**
- **Pinecone:** Added namespace support and improved type safety
- **Milvus:** Added db_name field to MilvusDBConfig
- **Vector Stores:** Added multi-id filters support
- **Vercel AI SDK:** Migration to AI SDK V5.0
- **Python Support:** Added Python 3.12 support
- **Graph Memory:** Added sanitizer methods for nodes and relationships
- **LLM Monitoring:** Added monitoring callback support
**Improvements:**
- **Performance:**
- Improved async handling in AsyncMemory class
- **Documentation:**
- Added async add announcement
- Added personalized search docs
- Added Neptune examples
- Added V5 migration docs
- **Configuration:**
- Refactored base class config for LLMs
- Added sslmode for pgvector
- **Dependencies:**
- Updated psycopg to version 3
- Updated Docker compose
**Bug Fixes:**
- **Tests:**
- Fixed failing tests
- Restricted package versions
- **Memgraph:**
- Fixed async attribute errors
- Fixed n_embeddings usage
- Fixed indexing issues
- **Vector Stores:**
- Fixed Qdrant cloud indexing
- Fixed Neo4j Cypher syntax
- Fixed LLM parameters
- **Graph Store:**
- Fixed LM config prioritization
- **Dependencies:**
- Fixed JSON import for psycopg
**Refactoring:**
- **Google AI:** Refactored from Gemini to Google AI
- **Base Classes:** Refactored LLM base class configuration
</Update>
<Update label="2025-07-24" description="v0.1.115">
**New Features & Updates:**
@@ -153,7 +244,7 @@ mode: "wide"
<Update label="2025-06-11" description="v0.1.107">
**Improvements:**
- **Documentation:**
- **Documentation:**
- Updated Livekit documentation migration
- Updated OpenMemory hosted version documentation
- **Core:** Updated categorization flow
@@ -190,7 +281,7 @@ mode: "wide"
- **LLM:** Added support for OpenAI compatible LLM providers with baseUrl configuration
**Improvements:**
- **Documentation:**
- **Documentation:**
- Fixed broken links
- Improved Graph Memory features documentation clarity
- Updated enable_graph documentation
@@ -207,14 +298,14 @@ mode: "wide"
- **OpenMemory:** Added LLM and Embedding Providers support
**Improvements:**
- **Documentation:**
- **Documentation:**
- Updated memory export documentation
- Enhanced role-based memory attribution rules documentation
- Updated API reference and messages documentation
- Added Mastra and Raycast documentation
- Added NOT filter documentation for Search and GetAll V2
- Announced Claude 4 support
- **Core:**
- **Core:**
- Removed support for passing string as input in client.add()
- Added support for sarvam-m model
- **TypeScript SDK:** Fixed types from message interface
@@ -231,7 +322,7 @@ mode: "wide"
- **Neo4j:** Added base label configuration support
**Improvements:**
- **Documentation:**
- **Documentation:**
- Updated Healthcare example index
- Enhanced collaborative task agent documentation clarity
- Added criteria-based filtering documentation
@@ -327,7 +418,7 @@ mode: "wide"
- **Vector Stores:** Added reset function for VectorDBs
**Improvements:**
- **Documentation:**
- **Documentation:**
- Updated timestamp and expiration_date documentation
- Fixed v2 search documentation
- Added "memory" in EC "Custom config" section
@@ -366,12 +457,12 @@ mode: "wide"
**New Features:**
- **LLM Integrations:** Added Azure OpenAI Embedding Model
- **Examples:**
- **Examples:**
- Added movie recommendation using grok3
- Added Voice Assistant using Elevenlabs
**Improvements:**
- **Documentation:**
- **Documentation:**
- Added keywords AI
- Reformatted navbar page URLs
- Updated changelog
@@ -386,7 +477,7 @@ mode: "wide"
- **LLM Integrations:** Added Mistral AI as LLM provider
**Improvements:**
- **Documentation:**
- **Documentation:**
- Updated changelog
- Fixed memory exclusion example
- Updated xAI documentation
@@ -403,7 +494,7 @@ mode: "wide"
**New Features:**
- **Langchain Integration:** Added support for Langchain VectorStores
- **Examples:**
- **Examples:**
- Added personal assistant example
- Added personal study buddy example
- Added YouTube assistant Chrome extension example
@@ -577,7 +668,6 @@ mode: "wide"
**Improvements:**
- **OSS:** Added baseURL param in LLM Config.
</Update>
<Update label="2025-05-23" description="v2.1.26">
**Improvements:**
- **Client:** Removed type `string` from `messages` interface
@@ -992,6 +1082,16 @@ mode: "wide"
<Tab title="Vercel AI SDK">
<Update label="2025-09-03" description="v2.0.2">
**Bug Fix:**
- **Vercel AI SDK:** Fixed streaming response in the AI SDK.
</Update>
<Update label="2025-08-05" description="v2.0.1">
**New Features:**
- **Vercel AI SDK:** Added a new param `host` to the config.
</Update>
<Update label="2025-08-05" description="v2.0.0">
**New Features:**
- **Vercel AI SDK:** Migration to AI SDK V5.
@@ -1014,7 +1114,7 @@ mode: "wide"
<Update label="2025-05-08" description="v1.0.3">
**Improvements:**
- **Vercel AI SDK:** Added support for graceful failure in cases services are down.
- **Vercel AI SDK:** Added support for graceful failure in cases services are down.
</Update>
<Update label="2025-05-01" description="v1.0.1">
-1
View File
@@ -4,7 +4,6 @@ icon: "gear"
iconType: "solid"
---
<Snippet file="blank-notif.mdx" />
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.
@@ -77,6 +77,43 @@ 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:
+28 -2
View File
@@ -6,7 +6,8 @@ To use Google AI embedding models, set the `GOOGLE_API_KEY` environment variable
### Usage
```python
<CodeGroup>
```python Python
import os
from mem0 import Memory
@@ -26,12 +27,37 @@ 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": "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: 'text-embedding-004',
// The output dimensionality is fixed at 768 for Google AI embeddings
},
},
};
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:
+68 -18
View File
@@ -44,29 +44,33 @@ m.add(messages, user_id="alice", metadata={"category": "movies"})
```
```typescript TypeScript
import { Memory } from "mem0ai";
import { Memory } from 'mem0ai/oss';
import { OpenAIEmbeddings } from "@langchain/openai";
const embeddings = new OpenAIEmbeddings();
// 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": embeddings
}
}
}
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." }
{"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"})
await memory.add(messages, { userId: "alice", metadata: { category: "movies" } });
```
</CodeGroup>
@@ -96,9 +100,10 @@ When using LangChain as an embedder provider, you'll need to:
### Examples with Different Providers
<CodeGroup>
#### HuggingFace Embeddings
```python
```python Python
from langchain_huggingface import HuggingFaceEmbeddings
# Initialize a HuggingFace embeddings model
@@ -117,9 +122,33 @@ config = {
}
```
```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 Python
from langchain_ollama import OllamaEmbeddings
# Initialize an Ollama embeddings model
@@ -137,6 +166,27 @@ config = {
}
```
```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>
+39 -4
View File
@@ -2,7 +2,8 @@ You can use embedding models from Ollama to run Mem0 locally.
### Usage
```python
<CodeGroup>
```python Python
import os
from mem0 import Memory
@@ -21,18 +22,52 @@ 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": "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 OpenAI model to use | `nomic-embed-text` |
| `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` |
| `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` |
</Tab>
</Tabs>
-2
View File
@@ -4,8 +4,6 @@ icon: "info"
iconType: "solid"
---
<Snippet file="blank-notif.mdx" />
Mem0 offers support for various embedding models, allowing users to choose the one that best suits their needs.
## Supported Embedders
-2
View File
@@ -4,8 +4,6 @@ icon: "gear"
iconType: "solid"
---
<Snippet file="blank-notif.mdx" />
## How to define configurations?
<Tabs>
@@ -2,7 +2,6 @@
title: Anthropic
---
<Snippet file="blank-notif.mdx" />
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).
@@ -2,8 +2,6 @@
title: AWS Bedrock
---
<Snippet file="blank-notif.mdx" />
### 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)
+40 -2
View File
@@ -2,12 +2,12 @@
title: Azure OpenAI
---
<Snippet file="blank-notif.mdx" />
<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`
@@ -118,6 +118,44 @@ config = {
}
```
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).
-2
View File
@@ -2,8 +2,6 @@
title: DeepSeek
---
<Snippet file="blank-notif.mdx" />
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
@@ -2,8 +2,6 @@
title: Google AI
---
<Snippet file="blank-notif.mdx" />
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`.
-2
View File
@@ -2,8 +2,6 @@
title: Groq
---
<Snippet file="blank-notif.mdx" />
[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.
+19 -20
View File
@@ -2,7 +2,6 @@
title: LangChain
---
<Snippet file="blank-notif.mdx" />
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.
@@ -47,34 +46,34 @@ m.add(messages, user_id="alice", metadata={"category": "movies"})
```
```typescript TypeScript
import { Memory } from "mem0ai";
import { Memory } from 'mem0ai/oss';
import { ChatOpenAI } from "@langchain/openai";
const openai_model = new ChatOpenAI({
model: "gpt-4o",
// Initialize a LangChain model directly
const openaiModel = new ChatOpenAI({
modelName: "gpt-4",
temperature: 0.2,
max_tokens: 2000
})
maxTokens: 2000,
apiKey: process.env.OPENAI_API_KEY,
});
const config = {
"llm": {
"provider": "langchain",
"config": {
"model": openai_model
}
}
}
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." }
{"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"})
await memory.add(messages, { userId: "alice", metadata: { category: "movies" } });
```
</CodeGroup>
-2
View File
@@ -1,5 +1,3 @@
<Snippet file="blank-notif.mdx" />
[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
-2
View File
@@ -2,8 +2,6 @@
title: LM Studio
---
<Snippet file="blank-notif.mdx" />
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
@@ -2,8 +2,6 @@
title: Mistral AI
---
<Snippet file="blank-notif.mdx" />
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
+28 -4
View File
@@ -1,10 +1,9 @@
<Snippet file="blank-notif.mdx" />
You can use LLMs from Ollama to run Mem0 locally. These [models](https://ollama.com/search?c=tools) support tool support.
## Usage
```python
<CodeGroup>
```python Python
import os
from mem0 import Memory
@@ -25,12 +24,37 @@ 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": "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).
-2
View File
@@ -2,8 +2,6 @@
title: OpenAI
---
<Snippet file="blank-notif.mdx" />
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`
-2
View File
@@ -2,8 +2,6 @@
title: Sarvam AI
---
<Snippet file="blank-notif.mdx" />
**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/).
-2
View File
@@ -1,5 +1,3 @@
<Snippet file="blank-notif.mdx" />
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
-2
View File
@@ -2,8 +2,6 @@
title: vLLM
---
<Snippet file="blank-notif.mdx" />
[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
-2
View File
@@ -2,8 +2,6 @@
title: xAI
---
<Snippet file="blank-notif.mdx" />
[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.
-2
View File
@@ -4,8 +4,6 @@ icon: "info"
iconType: "solid"
---
<Snippet file="blank-notif.mdx" />
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
-2
View File
@@ -4,8 +4,6 @@ icon: "gear"
iconType: "solid"
---
<Snippet file="blank-notif.mdx" />
## How to define configurations?
The `config` is defined as an object with two main keys:
+87 -7
View File
@@ -16,8 +16,8 @@ config = {
"vector_store": {
"provider": "azure_ai_search",
"config": {
"service_name": "ai-search-test",
"api_key": "*****",
"service_name": "<your-azure-ai-search-service-name>",
"api_key": "<your-api-key>",
"collection_name": "mem0",
"embedding_model_dims": 1536
}
@@ -41,8 +41,8 @@ config = {
"vector_store": {
"provider": "azure_ai_search",
"config": {
"service_name": "ai-search-test",
"api_key": "*****",
"service_name": "<your-azure-ai-search-service-name>",
"api_key": "<your-api-key>",
"collection_name": "mem0",
"embedding_model_dims": 1536,
"compression_type": "binary",
@@ -59,8 +59,8 @@ config = {
"vector_store": {
"provider": "azure_ai_search",
"config": {
"service_name": "ai-search-test",
"api_key": "*****",
"service_name": "<your-azure-ai-search-service-name>",
"api_key": "<your-api-key>",
"collection_name": "mem0",
"embedding_model_dims": 1536,
"hybrid_search": True,
@@ -70,12 +70,92 @@ config = {
}
```
## 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 | 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` |
@@ -0,0 +1,130 @@
[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.
@@ -54,7 +54,8 @@ Let's see the available parameters for the `elasticsearch` config:
| `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` |
| `custom_search_query` | Function returning a custom search query | `None` |
| `headers` | Custom headers to include in requests | `None` |
### Features
+34 -2
View File
@@ -2,7 +2,8 @@
### Usage
```python
<CodeGroup>
```python Python
import os
from mem0 import Memory
@@ -24,12 +25,43 @@ 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": "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:
@@ -0,0 +1,78 @@
---
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.
+2 -2
View File
@@ -4,8 +4,6 @@ icon: "info"
iconType: "solid"
---
<Snippet file="blank-notif.mdx" />
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
@@ -33,6 +31,8 @@ See the list of supported vector databases below.
<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
-2
View File
@@ -3,8 +3,6 @@ title: Development
icon: "code"
---
<Snippet file="blank-notif.mdx" />
# Development Contributions
We strive to make contributions **easy, collaborative, and enjoyable**. Follow the steps below to ensure a smooth contribution process.
-2
View File
@@ -3,8 +3,6 @@ title: Documentation
icon: "book"
---
<Snippet file="blank-notif.mdx" />
# Documentation Contributions
## 📌 Prerequisites
-62
View File
@@ -1,62 +0,0 @@
---
title: Memory Operations
description: Understanding the core operations for managing memories in AI applications
icon: "gear"
iconType: "solid"
---
<Snippet file="blank-notif.mdx" />
Mem0 provides two core operations for managing memories in AI applications: adding new memories and searching existing ones. This guide covers how these operations work and how to use them effectively in your application.
## Core Operations
Mem0 exposes two main endpoints for interacting with memories:
- The `add` endpoint for ingesting conversations and storing them as memories
- The `search` endpoint for retrieving relevant memories based on queries
### Adding Memories
<Frame caption="Architecture diagram illustrating the process of adding memories.">
<img src="../images/add_architecture.png" />
</Frame>
The add operation processes conversations through several steps:
1. **Information Extraction**
* An LLM extracts relevant memories from the conversation
* It identifies important entities and their relationships
2. **Conflict Resolution**
* The system compares new information with existing data
* It identifies and resolves any contradictions
3. **Memory Storage**
* Vector database stores the actual memories
* Graph database maintains relationship information
* Information is continuously updated with each interaction
### Searching Memories
<Frame caption="Architecture diagram illustrating the memory search process.">
<img src="../images/search_architecture.png" />
</Frame>
The search operation retrieves memories through a multi-step process:
1. **Query Processing**
* LLM processes and optimizes the search query
* System prepares filters for targeted search
2. **Vector Search**
* Performs semantic search using the optimized query
* Ranks results by relevance to the query
* Applies specified filters (user, agent, metadata, etc.)
3. **Result Processing**
* Combines and ranks the search results
* Returns memories with relevance scores
* Includes associated metadata and timestamps
This semantic search approach ensures accurate memory retrieval, whether you're looking for specific information or exploring related concepts.
@@ -5,7 +5,6 @@ icon: "plus"
iconType: "solid"
---
<Snippet file="blank-notif.mdx" />
## Overview
@@ -5,8 +5,6 @@ icon: "trash"
iconType: "solid"
---
<Snippet file="blank-notif.mdx" />
## Overview
Memories can become outdated, irrelevant, or need to be removed for privacy or compliance reasons. Mem0 offers flexible ways to delete memory:
@@ -5,8 +5,6 @@ icon: "magnifying-glass"
iconType: "solid"
---
<Snippet file="blank-notif.mdx" />
## 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.
@@ -5,8 +5,6 @@ icon: "pencil"
iconType: "solid"
---
<Snippet file="blank-notif.mdx" />
## 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.
-2
View File
@@ -5,8 +5,6 @@ icon: "memory"
iconType: "solid"
---
<Snippet file="blank-notif.mdx" />
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
+10 -5
View File
@@ -1,6 +1,5 @@
{
"$schema": "https://mintlify.com/docs.json",
"theme": "maple",
"name": "Mem0",
"description": "Mem0 is a self-improving memory layer for LLM applications, enabling personalized AI experiences that save costs and delight users.",
"colors": {
@@ -22,7 +21,7 @@
"group": "Getting Started",
"icon": "rocket",
"pages": [
"what-is-mem0",
"introduction",
"quickstart",
"faqs"
]
@@ -46,10 +45,11 @@
},
{
"group": "Platform",
"icon": "cogs",
"icon": "globe",
"pages": [
"platform/overview",
"platform/quickstart",
"platform/advanced-memory-operations",
{
"group": "Features",
"icon": "star",
@@ -57,6 +57,7 @@
"platform/features/platform-overview",
"platform/features/contextual-add",
"platform/features/async-client",
"platform/features/graph-memory",
"platform/features/advanced-retrieval",
"platform/features/criteria-retrieval",
"platform/features/multimodal-support",
@@ -153,11 +154,15 @@
"components/vectordbs/dbs/elasticsearch",
"components/vectordbs/dbs/opensearch",
"components/vectordbs/dbs/supabase",
"components/vectordbs/dbs/upstash-vector",
"components/vectordbs/dbs/vectorize",
"components/vectordbs/dbs/vertex_ai",
"components/vectordbs/dbs/weaviate",
"components/vectordbs/dbs/faiss",
"components/vectordbs/dbs/langchain",
"components/vectordbs/dbs/baidu"
"components/vectordbs/dbs/baidu",
"components/vectordbs/dbs/s3_vectors",
"components/vectordbs/dbs/databricks"
]
}
]
@@ -375,7 +380,7 @@
"background": {
"color": {
"light": "#fff",
"dark": "#0f1117"
"dark": "#09090b"
}
},
"navbar": {
+46 -49
View File
@@ -3,9 +3,6 @@ title: Overview
description: How to use mem0 in your existing applications?
---
<Snippet file="blank-notif.mdx" />
With Mem0, you can create stateful LLM-based applications such as chatbots, virtual assistants, or AI agents. Mem0 enhances your applications by providing a memory layer that makes responses:
- More personalized
@@ -20,72 +17,72 @@ Here are some examples of how Mem0 can be integrated into various applications:
Explore how **Mem0** can power real-world applications and bring personalized, intelligent experiences to life:
<CardGroup cols={2}>
<Card title="AI Companion in Node.js" icon="node" href="/examples/ai_companion_js">
Build a personalized AI Companion in **Node.js** that remembers conversations and adapts over time using Mem0.
</Card>
<Card title="Mem0 with Ollama" icon="server" href="/examples/mem0-with-ollama">
Run **Mem0 locally** with **Ollama** to create private, stateful AI experiences without relying on cloud APIs.
</Card>
<Card title="Personal AI Tutor" icon="graduation-cap" href="/examples/personal-ai-tutor">
Create an **AI Tutor** that adapts to student progress, learning style, and history — for a truly customized learning experience.
</Card>
<Card title="Personal Travel Assistant" icon="plane" href="/examples/personal-travel-assistant">
Develop a **Personal Travel Assistant** that remembers your preferences, past trips, and helps plan future adventures.
</Card>
<Card title="Customer Support Agent" icon="headset" href="/examples/customer-support-agent">
Build a **Customer Support AI** that recalls user preferences, past chats, and provides context-aware, efficient help.
<CardGroup cols={2}>
<Card title="AI Companion in Node.js" icon="node" href="/examples/ai_companion_js">
Build a personalized AI Companion in **Node.js** that remembers conversations and adapts over time using Mem0.
</Card>
<Card title="Personalized Search Assistant" icon="magnifying-glass" href="/examples/personalized-search-tavily-mem0">
Build a **Personalized Search Assistant** that tailors search according to user preferences.
<Card title="Mem0 with Ollama" icon="server" href="/examples/mem0-with-ollama">
Run **Mem0 locally** with **Ollama** to create private, stateful AI experiences without relying on cloud APIs.
</Card>
<Card title="Personal AI Tutor" icon="graduation-cap" href="/examples/personal-ai-tutor">
Create an **AI Tutor** that adapts to student progress, learning style, and history — for a truly customized learning experience.
</Card>
<Card title="Personal Travel Assistant" icon="plane" href="/examples/personal-travel-assistant">
Develop a **Personal Travel Assistant** that remembers your preferences, past trips, and helps plan future adventures.
</Card>
<Card title="Customer Support Agent" icon="headset" href="/examples/customer-support-agent">
Build a **Customer Support AI** that recalls user preferences, past chats, and provides context-aware, efficient help.
</Card>
<Card title="LlamaIndex + Mem0" icon="book-open" href="/examples/llama-index-mem0">
Combine **LlamaIndex** and Mem0 to create a powerful **ReAct Agent** with persistent memory for smarter interactions.
</Card>
<Card title="LlamaIndex + Mem0 Learning System" icon="book-open" href="/examples/llama-index-mem0">
Multi-agent learning system powered by memory.
</Card>
</Card>
<Card title="Chrome Extension" icon="puzzle-piece" href="/examples/chrome-extension">
Add **long-term memory** to ChatGPT, Claude, or Perplexity via the **Mem0 Chrome Extension** — personalize your AI chats anywhere.
</Card>
<Card title="Chrome Extension" icon="puzzle-piece" href="/examples/chrome-extension">
Add **long-term memory** to ChatGPT, Claude, or Perplexity via the **Mem0 Chrome Extension** — personalize your AI chats anywhere.
</Card>
<Card title="YouTube Assistant" icon="puzzle-piece" href="/examples/youtube-assistant">
<Card title="YouTube Assistant" icon="puzzle-piece" href="/examples/youtube-assistant">
Integrate **Mem0** into **YouTube's** native UI, providing personalized responses with video context.
</Card>
<Card title="Document Writing Assistant" icon="pen" href="/examples/document-writing">
Create a **Writing Assistant** that understands and adapts to your unique style, improving consistency and productivity.
</Card>
<Card title="Document Writing Assistant" icon="pen" href="/examples/document-writing">
Create a **Writing Assistant** that understands and adapts to your unique style, improving consistency and productivity.
</Card>
<Card title="Multimodal AI Demo" icon="image" href="/examples/multimodal-demo">
Supercharge AI with **Mem0's multimodal memory** — blend text, images, and more for richer, context-aware interactions.
</Card>
<Card title="Multimodal AI Demo" icon="image" href="/examples/multimodal-demo">
Supercharge AI with **Mem0's multimodal memory** — blend text, images, and more for richer, context-aware interactions.
</Card>
<Card title="Personalized Research Agent" icon="magnifying-glass" href="/examples/personalized-deep-research">
Build a **Deep Research AI** that remembers your research goals and compiles insights from vast information sources.
</Card>
<Card title="Personalized Research Agent" icon="magnifying-glass" href="/examples/personalized-deep-research">
Build a **Deep Research AI** that remembers your research goals and compiles insights from vast information sources.
</Card>
<Card title="Mem0 as an Agentic Tool" icon="robot" href="/examples/mem0-agentic-tool">
Integrate Mem0's memory capabilities with OpenAI's Agents SDK to create AI agents with persistent memory.
</Card>
<Card title="Mem0 as an Agentic Tool" icon="robot" href="/examples/mem0-agentic-tool">
Integrate Mem0's memory capabilities with OpenAI's Agents SDK to create AI agents with persistent memory.
</Card>
<Card title="OpenAI Inbuilt Tools" icon="robot" href="/examples/openai-inbuilt-tools">
Use Mem0's memory capabilities with OpenAI's Inbuilt Tools to create AI agents with persistent memory.
</Card>
<Card title="OpenAI Inbuilt Tools" icon="robot" href="/examples/openai-inbuilt-tools">
Use Mem0's memory capabilities with OpenAI's Inbuilt Tools to create AI agents with persistent memory.
</Card>
<Card title="Mem0 OpenAI Voice Demo" icon="microphone" href="/examples/mem0-openai-voice-demo">
Use Mem0's memory capabilities with OpenAI's Inbuilt Tools to create AI agents with persistent memory.
<Card title="Mem0 OpenAI Voice Demo" icon="microphone" href="/examples/mem0-openai-voice-demo">
Use Mem0's memory capabilities with OpenAI's Inbuilt Tools to create AI agents with persistent memory.
</Card>
<Card title="Healthcare Assistant Google ADK" icon="microphone" href="/examples/mem0-google-adk-healthcare-assistant">
Build a personalized healthcare assistant with persistent memory using Google's ADK and Mem0.
</Card>
<Card title="Email Processing" icon="envelope" href="/examples/email_processing">
Use Mem0's memory capabilities to process emails and create AI agents with persistent memory.
</Card>
<Card title="Email Processing" icon="envelope" href="/examples/email_processing">
Use Mem0's memory capabilities to process emails and create AI agents with persistent memory.
</Card>
</CardGroup>
-168
View File
@@ -1,168 +0,0 @@
---
title: AI Companion
---
<Snippet file="blank-notif.mdx" />
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 separate memories for both the user and the companion. By integrating with OpenAI's GPT-4 model, the companion 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 an AI Companion using Mem0:
```python
from openai import OpenAI
from mem0 import Memory
import os
# Set the OpenAI API key
os.environ['OPENAI_API_KEY'] = 'sk-xxx'
# Initialize the OpenAI client
client = OpenAI()
class Companion:
def __init__(self, user_id, companion_id):
"""
Initialize the Companion with memory configuration, OpenAI client, and user IDs.
:param user_id: ID for storing user-related memories
:param companion_id: ID for storing companion-related memories
"""
config = {
"vector_store": {
"provider": "qdrant",
"config": {
"host": "localhost",
"port": 6333,
}
},
}
self.memory = Memory.from_config(config)
self.client = client
self.app_id = "app-1"
self.USER_ID = user_id
self.companion_id = companion_id
def analyze_question(self, question):
"""
Analyze the question to determine whether it's about the user or the companion.
"""
check_prompt = f"""
Analyze the given input and determine whether the user is primarily:
1) Talking about themselves or asking for personal advice. They may use words like "I" for this.
2) Inquiring about the AI companion's capabilities or characteristics They may use words like "you" for this.
Respond with a single word:
- 'user' if the input is focused on the user
- 'companion' if the input is focused on the AI companion
If the input is ambiguous or doesn't clearly fit either category, respond with 'user'.
Input: {question}
"""
response = self.client.chat.completions.create(
model="gpt-4",
messages=[{"role": "user", "content": check_prompt}]
)
return response.choices[0].message.content
def ask(self, question):
"""
Ask a question to the AI and store the relevant facts in memory
:param question: The question to ask the AI.
"""
check_answer = self.analyze_question(question)
user_id_to_use = self.USER_ID if check_answer == "user" else self.companion_id
previous_memories = self.memory.search(question, user_id=user_id_to_use)
relevant_memories_text = ""
if previous_memories and previous_memories.get('results'):
relevant_memories_text = '\n'.join(mem["memory"] for mem in previous_memories['results'])
prompt = f"User input: {question}\nPrevious {check_answer} memories: {relevant_memories_text}"
messages = [
{
"role": "system",
"content": "You are the user's romantic companion. Use the user's input and previous memories to respond. Answer based on the context provided."
},
{
"role": "user",
"content": prompt
}
]
stream = self.client.chat.completions.create(
model="gpt-4",
stream=True,
messages=messages
)
answer = ""
for chunk in stream:
if chunk.choices[0].delta.content is not None:
content = chunk.choices[0].delta.content
print(content, end="")
answer += content
# Store the question and answer in memory
self.memory.add(question, user_id=self.USER_ID, metadata={"app_id": self.app_id})
self.memory.add(answer, user_id=self.companion_id, metadata={"app_id": self.app_id})
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)
# Example usage:
user_id = "user"
companion_id = "companion"
ai_companion = Companion(user_id, companion_id)
# Ask a question
ai_companion.ask("Ive been missing you. What have you been up to off late?")
```
### Fetching Memories
You can fetch all the memories at any point in time using the following code:
```python
def print_memories(user_id, label):
print(f"\n{label} Memories:")
memories = ai_companion.get_memories(user_id=user_id)
if memories:
for m in memories:
print(f"- {m['memory']}")
else:
print("No memories found.")
# Print user memories
print_memories(user_id, "User")
# Print companion memories
print_memories(companion_id, "Companion")
```
### Key Points
- **Initialization**: The Companion 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 experience. This setup ensures that the AI Companion can offer contextually relevant and accurate responses, enhancing the user's experience.
-2
View File
@@ -2,8 +2,6 @@
title: AI Companion in Node.js
---
<Snippet file="blank-notif.mdx" />
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
+1 -3
View File
@@ -1,9 +1,7 @@
---
title: Amazon Stack: AWS Bedrock, AOSS, and Neptune Analytics
title: "Amazon Stack: AWS Bedrock, AOSS, and Neptune Analytics"
---
<Snippet file="blank-notif.mdx" />
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
-2
View File
@@ -1,7 +1,5 @@
# Mem0 Chrome Extension
<Snippet file="blank-notif.mdx" />
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>
@@ -2,8 +2,6 @@
title: Multi-User Collaboration with Mem0
---
<Snippet file="blank-notif.mdx" />
## 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.
-1
View File
@@ -2,7 +2,6 @@
title: Customer Support AI Agent
---
<Snippet file="blank-notif.mdx" />
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.
-2
View File
@@ -2,8 +2,6 @@
title: Eliza OS Character
---
<Snippet file="blank-notif.mdx" />
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
-2
View File
@@ -2,8 +2,6 @@
title: Email Processing with Mem0
---
<Snippet file="blank-notif.mdx" />
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
-1
View File
@@ -1,7 +1,6 @@
---
title: LlamaIndex ReAct Agent
---
<Snippet file="blank-notif.mdx" />
Create a ReAct Agent with LlamaIndex which uses Mem0 as the memory store.
-1
View File
@@ -2,7 +2,6 @@
title: Mem0 as an Agentic Tool
---
<Snippet file="blank-notif.mdx" />
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.
-3
View File
@@ -2,9 +2,6 @@
title: Mem0 Demo
---
<Snippet file="blank-notif.mdx" />
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
@@ -3,7 +3,6 @@ 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'
---
<Snippet file="blank-notif.mdx" />
# Healthcare Assistant with Memory
@@ -25,8 +24,7 @@ Before you begin, make sure you have:
Installed Google ADK and Mem0 SDK:
```bash
pip install google-adk
pip install mem0ai
pip install google-adk mem0ai python-dotenv
```
## Code Breakdown
@@ -36,21 +34,25 @@ Let's get started and understand the different components required in building a
```python
# Import dependencies
import os
import asyncio
from google.adk.agents import Agent
from google.adk.sessions import InMemorySessionService
from google.adk.runners import Runner
from google.adk.sessions import InMemorySessionService
from google.genai import types
from mem0 import MemoryClient
from dotenv import load_dotenv
# Set up API keys (replace with your actual keys)
os.environ["GOOGLE_API_KEY"] = "your-google-api-key"
os.environ["MEM0_API_KEY"] = "your-mem0-api-key"
load_dotenv()
# Set up environment variables
# os.environ["GOOGLE_API_KEY"] = "your-google-api-key"
# os.environ["MEM0_API_KEY"] = "your-mem0-api-key"
# Define a global user ID for simplicity
USER_ID = "Alex"
# Initialize Mem0 client
mem0_client = MemoryClient()
mem0 = MemoryClient()
```
## Define Memory Tools
-2
View File
@@ -2,8 +2,6 @@
title: Mem0 with Mastra
---
<Snippet file="blank-notif.mdx" />
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).
-2
View File
@@ -3,8 +3,6 @@ title: 'Mem0 with OpenAI Agents SDK for Voice'
description: 'Integrate memory capabilities into your voice agents using Mem0 and OpenAI Agents SDK'
---
<Snippet file="blank-notif.mdx" />
# 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.
-2
View File
@@ -2,8 +2,6 @@
title: Mem0 with Ollama
---
<Snippet file="blank-notif.mdx" />
## 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.
@@ -1,7 +1,6 @@
---
title: Memory-Guided Content Writing
---
<Snippet file="blank-notif.mdx" />
This guide demonstrates how to leverage **Mem0** to streamline content writing by applying your unique writing style and preferences using persistent memory.
-2
View File
@@ -2,8 +2,6 @@
title: Multimodal Demo with Mem0
---
<Snippet file="blank-notif.mdx" />
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)
-2
View File
@@ -2,8 +2,6 @@
title: OpenAI Inbuilt Tools
---
<Snippet file="blank-notif.mdx" />
Integrate Mem0’s memory capabilities with OpenAI’s Inbuilt Tools to create AI agents with persistent memory.
## Getting Started
-2
View File
@@ -2,8 +2,6 @@
title: Personalized AI Tutor
---
<Snippet file="blank-notif.mdx" />
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
@@ -2,7 +2,6 @@
title: Personal AI Travel Assistant
---
<Snippet file="blank-notif.mdx" />
Create a personalized AI Travel Assistant using Mem0. This guide provides step-by-step instructions and the complete code to get you started.
@@ -2,8 +2,6 @@
title: Personalized Deep Research
---
<Snippet file="blank-notif.mdx" />
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)
-2
View File
@@ -2,8 +2,6 @@
title: YouTube Assistant Extension
---
<Snippet file="blank-notif.mdx" />
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
-2
View File
@@ -4,8 +4,6 @@ icon: "question"
iconType: "solid"
---
<Snippet file="async-memory-add.mdx" />
<AccordionGroup>
<Accordion title="How does Mem0 work?">
Mem0 utilizes a sophisticated hybrid database system to efficiently manage and retrieve memories for AI agents and assistants. Each memory is linked to a unique identifier, such as a user ID or agent ID, enabling Mem0 to organize and access memories tailored to specific individuals or contexts.
-23
View File
@@ -1,23 +0,0 @@
---
title: Features
icon: "wrench"
iconType: "solid"
---
<Snippet file="blank-notif.mdx" />
## Core features
- **User, Session, and AI Agent Memory**: Retains information across sessions and interactions for users and AI agents, ensuring continuity and context.
- **Adaptive Personalization**: Continuously updates memories based on user interactions and feedback.
- **Developer-Friendly API**: Offers a straightforward API for seamless integration into various applications.
- **Platform Consistency**: Ensures consistent behavior and data across different platforms and devices.
- **Managed Service**: Provides a hosted solution for easy deployment and maintenance.
- **Save Costs**: Saves costs by adding relevant memories instead of complete transcripts to context window
If you have any questions, please feel free to reach out to us using one of the following methods:
<Snippet file="get-help.mdx" />
Binary file not shown.

Before

Width:  |  Height:  |  Size: 601 KiB

After

Width:  |  Height:  |  Size: 1.1 MiB

+1 -4
View File
@@ -3,8 +3,6 @@ title: Overview
description: How to integrate Mem0 into other frameworks
---
<Snippet file="blank-notif.mdx" />
Mem0 seamlessly integrates with popular AI frameworks and tools to enhance your LLM-based applications with persistent memory capabilities. By integrating Mem0, your applications benefit from:
- Enhanced context management across multiple frameworks
@@ -300,8 +298,7 @@ Here are the available integrations for Mem0:
<path d="M17.5 12c-.83 0-1.5-.67-1.5-1.5s.67-1.5 1.5-1.5 1.5.67 1.5 1.5-.67 1.5-1.5 1.5z" fill="currentColor"/>
<path d="M6.5 12c-.83 0-1.5-.67-1.5-1.5S5.67 9 6.5 9s1.5.67 1.5 1.5S7.33 12 6.5 12z" fill="currentColor"/>
</svg>
}
href="/integrations/pipecat"
} href="/integrations/pipecat"
>
Build conversational AI agents with memory using Pipecat.
</Card>
+3 -2
View File
@@ -1,7 +1,6 @@
---
title: AgentOps
---
<Snippet file="blank-notif.mdx" />
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.
@@ -18,7 +17,7 @@ Before setting up Mem0 with AgentOps, ensure you have:
1. Installed the required packages:
```bash
pip install mem0ai agentops
pip install mem0ai agentops python-dotenv
```
2. Valid API keys:
@@ -38,7 +37,9 @@ import asyncio
import logging
from dotenv import load_dotenv
import agentops
import openai
load_dotenv()
#Set up environment variables for API keys
os.environ["AGENTOPS_API_KEY"] = os.getenv("AGENTOPS_API_KEY")
os.environ["OPENAI_API_KEY"] = os.getenv("OPENAI_API_KEY")
+9 -10
View File
@@ -1,8 +1,6 @@
---
title: Agno
---
<Snippet file="blank-notif.mdx" />
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.
@@ -20,7 +18,7 @@ Before setting up Mem0 with Agno, ensure you have:
1. Installed the required packages:
```bash
pip install agno mem0ai
pip install agno mem0ai python-dotenv
```
2. Valid API keys:
@@ -83,7 +81,7 @@ agent = Agent(
def chat_user(
user_input: Optional[str] = None,
user_id: str = "user_123",
user_id: str = "alex",
image_path: Optional[str] = None
) -> str:
"""
@@ -122,13 +120,13 @@ def chat_user(
})
# Store messages in memory
client.add(messages, user_id=user_id)
client.add(messages, user_id=user_id, output_format='v1.1')
print("✅ Image and text stored in memory.")
if user_input:
# Search for relevant memories
memories = client.search(user_input, user_id=user_id)
memory_context = "\n".join(f"- {m['memory']}" for m in memories.get('results', []))
memories = client.search(user_input, user_id=user_id, output_format='v1.1')
memory_context = "\n".join(f"- {m['memory']}" for m in memories['results'])
# Construct the prompt
prompt = f"""
@@ -152,7 +150,8 @@ User question:
response = agent.run(prompt)
# Store the interaction in memory
client.add(f"User: {user_input}\nAssistant: {response.content}", user_id=user_id)
interaction_message = [{"role": "user", "content": f"User: {user_input}\nAssistant: {response.content}"}]
client.add(interaction_message, user_id=user_id, output_format='v1.1')
return response.content
return "No user input or image provided."
@@ -161,9 +160,9 @@ User question:
# Example Usage
if __name__ == "__main__":
response = chat_user(
"This is the picture of what I brought with me in the trip to Bahamas",
"I like to travel and my favorite destination is London",
image_path="travel_items.jpeg",
user_id="user_123"
user_id="alex"
)
print(response)
```
+16 -11
View File
@@ -1,6 +1,8 @@
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.
---
title: AutoGen
---
<Snippet file="blank-notif.mdx" />
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
@@ -12,7 +14,7 @@ In this guide, we'll explore an example of creating a conversational AI system w
Install necessary libraries:
```bash
pip install pyautogen mem0ai openai
pip install autogen mem0ai openai python-dotenv
```
First, we'll import the necessary libraries and set up our configurations.
@@ -24,15 +26,18 @@ import os
from autogen import ConversableAgent
from mem0 import MemoryClient
from openai import OpenAI
from dotenv import load_dotenv
load_dotenv()
# Configuration
OPENAI_API_KEY = 'sk-xxx' # Replace with your actual OpenAI API key
MEM0_API_KEY = 'your-mem0-key' # Replace with your actual Mem0 API key from https://app.mem0.ai
USER_ID = "customer_service_bot"
# OPENAI_API_KEY = 'sk-xxx' # Replace with your actual OpenAI API key
# MEM0_API_KEY = 'your-mem0-key' # Replace with your actual Mem0 API key from https://app.mem0.ai
USER_ID = "alice"
# Set up OpenAI API key
os.environ['OPENAI_API_KEY'] = OPENAI_API_KEY
os.environ['MEM0_API_KEY'] = MEM0_API_KEY
OPENAI_API_KEY = os.environ.get('OPENAI_API_KEY')
# os.environ['MEM0_API_KEY'] = MEM0_API_KEY
# Initialize Mem0 and AutoGen agents
memory_client = MemoryClient()
@@ -57,7 +62,7 @@ conversation = [
{"role": "assistant", "content": "Thank you for the information. Let's troubleshoot this issue..."}
]
memory_client.add(messages=conversation, user_id=USER_ID)
memory_client.add(messages=conversation, user_id=USER_ID, output_format="v1.1")
print("Conversation added to memory.")
```
@@ -67,7 +72,7 @@ Create a function to get context-aware responses based on user's question and pr
```python
def get_context_aware_response(question):
relevant_memories = memory_client.search(question, user_id=USER_ID)
relevant_memories = memory_client.search(question, user_id=USER_ID, output_format='v1.1')
context = "\n".join([m["memory"] for m in relevant_memories.get('results', [])])
prompt = f"""Answer the user question considering the previous interactions:
@@ -99,7 +104,7 @@ manager = ConversableAgent(
)
def escalate_to_manager(question):
relevant_memories = memory_client.search(question, user_id=USER_ID)
relevant_memories = memory_client.search(question, user_id=USER_ID, output_format='v1.1')
context = "\n".join([m["memory"] for m in relevant_memories.get('results', [])])
prompt = f"""
-2
View File
@@ -2,8 +2,6 @@
title: AWS Bedrock
---
<Snippet file="blank-notif.mdx" />
This integration demonstrates how to use **Mem0** with **AWS Bedrock** and **Amazon OpenSearch Service (AOSS)** to enable persistent, semantic memory in intelligent agents.
## Overview
-2
View File
@@ -2,8 +2,6 @@
title: CrewAI
---
<Snippet file="blank-notif.mdx" />
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
-2
View File
@@ -2,8 +2,6 @@
title: Dify
---
<Snippet file="blank-notif.mdx" />
# 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.
+1 -3
View File
@@ -2,8 +2,6 @@
title: ElevenLabs
---
<Snippet file="blank-notif.mdx" />
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
@@ -18,7 +16,7 @@ In this guide, we'll build a voice agent that:
Install necessary libraries:
```bash
pip install elevenlabs mem0 python-dotenv
pip install elevenlabs mem0ai python-dotenv
```
Configure your environment variables:
-2
View File
@@ -2,8 +2,6 @@
title: Flowise
---
<Snippet file="blank-notif.mdx" />
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
+16 -13
View File
@@ -2,8 +2,6 @@
title: Google Agent Development Kit
---
<Snippet file="blank-notif.mdx" />
Integrate [**Mem0**](https://github.com/mem0ai/mem0) with [Google Agent Development Kit (ADK)](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
@@ -19,7 +17,7 @@ Before setting up Mem0 with Google ADK, ensure you have:
1. Installed the required packages:
```bash
pip install google-adk mem0ai
pip install google-adk mem0ai python-dotenv
```
2. Valid API keys:
@@ -32,15 +30,19 @@ The following example demonstrates how to create a Google ADK agent with Mem0 me
```python
import os
import asyncio
from google.adk.agents import Agent
from google.adk.runners import Runner
from google.adk.sessions import InMemorySessionService
from google.genai import types
from mem0 import MemoryClient
from dotenv import load_dotenv
load_dotenv()
# Set up environment variables
os.environ["GOOGLE_API_KEY"] = "your-google-api-key"
os.environ["MEM0_API_KEY"] = "your-mem0-api-key"
# os.environ["GOOGLE_API_KEY"] = "your-google-api-key"
# os.environ["MEM0_API_KEY"] = "your-mem0-api-key"
# Initialize Mem0 client
mem0 = MemoryClient()
@@ -48,17 +50,18 @@ mem0 = MemoryClient()
# Define memory function tools
def search_memory(query: str, user_id: str) -> dict:
"""Search through past conversations and memories"""
memories = mem0.search(query, user_id=user_id)
memories = mem0.search(query, user_id=user_id, output_format='v1.1')
if memories.get('results', []):
memory_context = "\n".join([f"- {mem['memory']}" for mem in memories.get('results', [])])
memory_list = memories['results']
memory_context = "\n".join([f"- {mem['memory']}" for mem in memory_list])
return {"status": "success", "memories": memory_context}
return {"status": "no_memories", "message": "No relevant memories found"}
def save_memory(content: str, user_id: str) -> dict:
"""Save important information to memory"""
try:
mem0.add([{"role": "user", "content": content}], user_id=user_id)
return {"status": "success", "message": "Information saved to memory"}
result = mem0.add([{"role": "user", "content": content}], user_id=user_id, output_format='v1.1')
return {"status": "success", "message": "Information saved to memory", "result": result}
except Exception as e:
return {"status": "error", "message": f"Failed to save memory: {str(e)}"}
@@ -74,7 +77,7 @@ personal_assistant = Agent(
tools=[search_memory, save_memory]
)
def chat_with_agent(user_input: str, user_id: str) -> str:
async def chat_with_agent(user_input: str, user_id: str) -> str:
"""
Handle user input with automatic memory integration.
@@ -87,7 +90,7 @@ def chat_with_agent(user_input: str, user_id: str) -> str:
"""
# Set up session and runner
session_service = InMemorySessionService()
session = session_service.create_session(
session = await session_service.create_session(
app_name="memory_assistant",
user_id=user_id,
session_id=f"session_{user_id}"
@@ -109,10 +112,10 @@ def chat_with_agent(user_input: str, user_id: str) -> str:
# Example usage
if __name__ == "__main__":
response = chat_with_agent(
response = asyncio.run(chat_with_agent(
"I love Italian food and I'm planning a trip to Rome next month",
user_id="alice"
)
))
print(response)
```
-2
View File
@@ -2,8 +2,6 @@
title: Keywords AI
---
<Snippet file="blank-notif.mdx" />
Build AI applications with persistent memory and comprehensive LLM observability by integrating Mem0 with Keywords AI.
## Overview
-2
View File
@@ -3,8 +3,6 @@ title: Langchain Tools
description: 'Integrate Mem0 with LangChain tools to enable AI agents to store, search, and manage memories through structured interfaces'
---
<Snippet file="blank-notif.mdx" />
## 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.
+42 -30
View File
@@ -2,8 +2,6 @@
title: Langchain
---
<Snippet file="blank-notif.mdx" />
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
@@ -18,7 +16,7 @@ In this guide, we'll create a Travel Agent AI that:
Install necessary libraries:
```bash
pip install langchain langchain_openai mem0ai
pip install langchain langchain_openai mem0ai python-dotenv
```
Import required modules and set up configurations:
@@ -32,10 +30,13 @@ from langchain_openai import ChatOpenAI
from langchain_core.messages import SystemMessage, HumanMessage, AIMessage
from langchain_core.prompts import ChatPromptTemplate, MessagesPlaceholder
from mem0 import MemoryClient
from dotenv import load_dotenv
load_dotenv()
# Configuration
os.environ["OPENAI_API_KEY"] = "your-openai-api-key"
os.environ["MEM0_API_KEY"] = "your-mem0-api-key"
# os.environ["OPENAI_API_KEY"] = "your-openai-api-key"
# os.environ["MEM0_API_KEY"] = "your-mem0-api-key"
# Initialize LangChain and Mem0
llm = ChatOpenAI(model="gpt-4o-mini")
@@ -63,19 +64,26 @@ Create functions to handle context retrieval, response generation, and addition
```python
def retrieve_context(query: str, user_id: str) -> List[Dict]:
"""Retrieve relevant context from Mem0"""
memories = mem0.search(query, user_id=user_id)
serialized_memories = ' '.join([mem["memory"] for mem in memories.get('results', [])])
context = [
{
"role": "system",
"content": f"Relevant information: {serialized_memories}"
},
{
"role": "user",
"content": query
}
]
return context
try:
memories = mem0.search(query, user_id=user_id, output_format='v1.1')
memory_list = memories['results']
serialized_memories = ' '.join([mem["memory"] for mem in memory_list])
context = [
{
"role": "system",
"content": f"Relevant information: {serialized_memories}"
},
{
"role": "user",
"content": query
}
]
return context
except Exception as e:
print(f"Error retrieving memories: {e}")
# Return empty context if there's an error
return [{"role": "user", "content": query}]
def generate_response(input: str, context: List[Dict]) -> str:
"""Generate a response using the language model"""
@@ -88,17 +96,21 @@ def generate_response(input: str, context: List[Dict]) -> str:
def save_interaction(user_id: str, user_input: str, assistant_response: str):
"""Save the interaction to Mem0"""
interaction = [
{
"role": "user",
"content": user_input
},
{
"role": "assistant",
"content": assistant_response
}
]
mem0.add(interaction, user_id=user_id)
try:
interaction = [
{
"role": "user",
"content": user_input
},
{
"role": "assistant",
"content": assistant_response
}
]
result = mem0.add(interaction, user_id=user_id, output_format='v1.1')
print(f"Memory saved successfully: {len(result.get('results', []))} memories added")
except Exception as e:
print(f"Error saving interaction: {e}")
```
## Create Chat Turn Function
@@ -126,7 +138,7 @@ Set up the main program loop for user interaction:
```python
if __name__ == "__main__":
print("Welcome to your personal Travel Agent Planner! How can I assist you with your travel plans today?")
user_id = "john"
user_id = "alice"
while True:
user_input = input("You: ")
+45 -19
View File
@@ -2,8 +2,6 @@
title: LangGraph
---
<Snippet file="blank-notif.mdx" />
Build a personalized Customer Support AI Agent using LangGraph for conversation flow and Mem0 for memory retention. This integration enables context-aware and efficient support experiences.
## Overview
@@ -18,7 +16,7 @@ In this guide, we'll create a Customer Support AI Agent that:
Install necessary libraries:
```bash
pip install langgraph langchain-openai mem0ai
pip install langgraph langchain-openai mem0ai python-dotenv
```
@@ -33,14 +31,17 @@ from langgraph.graph.message import add_messages
from langchain_openai import ChatOpenAI
from mem0 import MemoryClient
from langchain_core.messages import SystemMessage, HumanMessage, AIMessage
from dotenv import load_dotenv
load_dotenv()
# Configuration
OPENAI_API_KEY = 'sk-xxx' # Replace with your actual OpenAI API key
MEM0_API_KEY = 'your-mem0-key' # Replace with your actual Mem0 API key
# OPENAI_API_KEY = 'sk-xxx' # Replace with your actual OpenAI API key
# MEM0_API_KEY = 'your-mem0-key' # Replace with your actual Mem0 API key
# Initialize LangChain and Mem0
llm = ChatOpenAI(model="gpt-4", api_key=OPENAI_API_KEY)
mem0 = MemoryClient(api_key=MEM0_API_KEY)
llm = ChatOpenAI(model="gpt-4")
mem0 = MemoryClient()
```
## Define State and Graph
@@ -64,22 +65,47 @@ def chatbot(state: State):
messages = state["messages"]
user_id = state["mem0_user_id"]
# Retrieve relevant memories
memories = mem0.search(messages[-1].content, user_id=user_id)
try:
# Retrieve relevant memories
memories = mem0.search(messages[-1].content, user_id=user_id, output_format='v1.1')
# Handle dict response format
memory_list = memories['results']
context = "Relevant information from previous conversations:\n"
for memory in memories.get('results', []):
context += f"- {memory['memory']}\n"
context = "Relevant information from previous conversations:\n"
for memory in memory_list:
context += f"- {memory['memory']}\n"
system_message = SystemMessage(content=f"""You are a helpful customer support assistant. Use the provided context to personalize your responses and remember user preferences and past interactions.
system_message = SystemMessage(content=f"""You are a helpful customer support assistant. Use the provided context to personalize your responses and remember user preferences and past interactions.
{context}""")
full_messages = [system_message] + messages
response = llm.invoke(full_messages)
full_messages = [system_message] + messages
response = llm.invoke(full_messages)
# Store the interaction in Mem0
mem0.add(f"User: {messages[-1].content}\nAssistant: {response.content}", user_id=user_id)
return {"messages": [response]}
# Store the interaction in Mem0
try:
interaction = [
{
"role": "user",
"content": messages[-1].content
},
{
"role": "assistant",
"content": response.content
}
]
result = mem0.add(interaction, user_id=user_id, output_format='v1.1')
print(f"Memory saved: {len(result.get('results', []))} memories added")
except Exception as e:
print(f"Error saving memory: {e}")
return {"messages": [response]}
except Exception as e:
print(f"Error in chatbot: {e}")
# Fallback response without memory context
response = llm.invoke(messages)
return {"messages": [response]}
```
## Set Up Graph Structure
@@ -117,7 +143,7 @@ Set up the main program loop for user interaction:
```python
if __name__ == "__main__":
print("Welcome to Customer Support! How can I assist you today?")
mem0_user_id = "customer_123" # You can generate or retrieve this based on your user management system
mem0_user_id = "alice" # You can generate or retrieve this based on your user management system
while True:
user_input = input("You: ")
if user_input.lower() in ['quit', 'exit', 'bye']:
-2
View File
@@ -2,8 +2,6 @@
title: Livekit
---
<Snippet file="blank-notif.mdx" />
This guide demonstrates how to create a memory-enabled voice assistant using LiveKit, Deepgram, OpenAI, and Mem0, focusing on creating an intelligent, context-aware travel planning agent.
## Prerequisites
+20 -14
View File
@@ -2,8 +2,6 @@
title: LlamaIndex
---
<Snippet file="blank-notif.mdx" />
LlamaIndex supports Mem0 as a [memory store](https://llamahub.ai/l/memory/llama-index-memory-mem0). In this guide, we'll show you how to use it.
<Note type="info">
@@ -15,7 +13,7 @@ LlamaIndex supports Mem0 as a [memory store](https://llamahub.ai/l/memory/llama-
To install the required package, run:
```bash
pip install llama-index-core llama-index-memory-mem0
pip install llama-index-core llama-index-memory-mem0 python-dotenv
```
### Setup with Mem0 Platform
@@ -27,18 +25,23 @@ Set your Mem0 Platform API key as an environment variable. You can replace `<you
</Note>
```python
os.environ["MEM0_API_KEY"] = "<your-mem0-api-key>"
from dotenv import load_dotenv
import os
load_dotenv()
# os.environ["MEM0_API_KEY"] = "<your-mem0-api-key>"
```
Import the necessary modules and create a Mem0Memory instance:
```python
from llama_index.memory.mem0 import Mem0Memory
context = {"user_id": "user_1"}
context = {"user_id": "alice"}
memory_from_client = Mem0Memory.from_client(
context=context,
api_key="<your-mem0-api-key>",
search_msg_limit=4, # optional, default is 5
output_format='v1.1', # Remove deprecation warnings
)
```
@@ -46,8 +49,8 @@ Context is used to identify the user, agent or the conversation in the Mem0. It
```python
context = {
"user_id": "user_1",
"agent_id": "agent_1",
"user_id": "alice",
"agent_id": "llama_agent_1",
"run_id": "run_1",
}
```
@@ -100,17 +103,20 @@ memory_from_config = Mem0Memory.from_config(
context=context,
config=config,
search_msg_limit=4, # optional, default is 5
output_format='v1.1', # Remove deprecation warnings
)
```
Initialize the LLM
```python
import os
from llama_index.llms.openai import OpenAI
from dotenv import load_dotenv
os.environ["OPENAI_API_KEY"] = "<your-openai-api-key>"
llm = OpenAI(model="gpt-4o")
load_dotenv()
# os.environ["OPENAI_API_KEY"] = "<your-openai-api-key>"
llm = OpenAI(model="gpt-4o-mini")
```
### SimpleChatEngine
@@ -124,7 +130,7 @@ agent = SimpleChatEngine.from_defaults(
)
# Start the chat
response = agent.chat("Hi, My name is Mayank")
response = agent.chat("Hi, My name is Alice")
print(response)
```
Now we will learn how to use Mem0 with FunctionCalling and ReAct agents.
@@ -167,7 +173,7 @@ agent = FunctionCallingAgent.from_tools(
)
# Start the chat
response = agent.chat("Hi, My name is Mayank")
response = agent.chat("Hi, My name is Alice")
print(response)
```
@@ -184,7 +190,7 @@ agent = ReActAgent.from_tools(
)
# Start the chat
response = agent.chat("Hi, My name is Mayank")
response = agent.chat("Hi, My name is Alice")
print(response)
```
-2
View File
@@ -2,8 +2,6 @@
title: Mastra
---
<Snippet file="blank-notif.mdx" />
The [**Mastra**](https://mastra.ai/) integration demonstrates how to use Mastra's agent system with Mem0 as the memory backend through custom tools. This enables agents to remember and recall information across conversations.
## Overview
-62
View File
@@ -1,62 +0,0 @@
---
title: MCP Server
---
<Snippet file="blank-notif.mdx" />
## Integrating mem0 as an MCP Server in Cursor
[mem0](https://github.com/mem0ai/mem0-mcp) is a powerful tool designed to enhance AI-driven workflows, particularly in code generation and contextual memory. In this guide, we'll walk through integrating mem0 as an **MCP (Model Context Protocol) server** within [Cursor](https://cursor.sh/), an AI-powered coding editor.
## Prerequisites
Before proceeding, ensure you have the following installed:
- Cursor IDE
- Python (>=3.8)
- Git
- [mem0-mcp](https://github.com/mem0ai/mem0-mcp) (Clone the repository and set up as per the instructions in the README)
## Configuring Cursor to use mem0 as an MCP Server
1. **Open Cursor.**
2. **Navigate to `Settings` > `Cursor Settings` > `Features` > `MCP Servers`.**
3. **Add a new provider using the MCP server:**
- Click on **`Add new MCP server`**
- Provide a name for the server, e.g. `mem0` and select type as `sse`
- Enter the **SSE Endpoint**: `http://0.0.0.0:8080/sse`
4. **Save and Restart Cursor** to apply changes.
## Demo
<iframe width="560" height="315" src="https://www.youtube.com/embed/fWa6KX7cpG8?si=cmJDz2sQevGnItSI" 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>
## Using mem0 in Cursor
Once integrated, mem0 can assist with contextual memory and AI-driven coding enhancements. Some key functionalities include:
### 1. Storing Coding Preferences
Mem0 can store and manage coding preferences, including:
- Complete code snippets with dependencies
- Language/framework versions
- Documentation and comments
- Best practices and example usage
### 2. Retrieving Stored Preferences
Access all stored coding references to:
- Review implementations
- Maintain consistency in coding practices
### 3. Semantic Search for Preferences
Use natural language queries to find:
- Code snippets
- Technical documentation
- Best practices
- Setup guides
## Benefits of Using mem0 in Cursor
- **Persistent Context Storage**: Retain and reuse coding insights across sessions.
- **Seamless Integration**: Works directly within Cursor as an MCP server.
- **Efficient Search**: Retrieve relevant coding insights using semantic search.
## Conclusion
By integrating mem0 as an MCP server within Cursor, you enhance your development workflow with AI-powered memory and context-aware assistance. Follow the steps above to set up and start leveraging mem0 in your coding environment.
For more details on MCP integration, refer to Cursor's [Model Context Protocol documentation](https://docs.cursor.com/context/model-context-protocol).
-216
View File
@@ -1,216 +0,0 @@
---
title: MultiOn
---
<Snippet file="blank-notif.mdx" />
Build a personal browser agent that remembers user preferences and automates web tasks. It integrates Mem0 for memory management with MultiOn for executing browser actions, enabling personalized and efficient web interactions.
## Overview
In this guide, we'll explore two examples of creating Browser-based AI Agents:
1. An agent that searches [arxiv.org](https://arxiv.org) for research papers relevant to user's research interests.
2. A travel agent that provides personalized travel information based on user preferences. Refer to the [notebook](https://github.com/MULTI-ON/cookbook/blob/main/personalized-travel-agent/mem0_travel_agent.ipynb) for detailed code.
## Setup and Configuration
Install necessary libraries:
```bash
pip install mem0ai multion openai
```
First, we'll import the necessary libraries and set up our configurations.
```python
import os
from mem0 import Memory, MemoryClient
from multion.client import MultiOn
from openai import OpenAI
# Configuration
OPENAI_API_KEY = 'sk-xxx' # Replace with your actual OpenAI API key
MULTION_API_KEY = 'your-multion-key' # Replace with your actual MultiOn API key
MEM0_API_KEY = 'your-mem0-key' # Replace with your actual Mem0 API key
USER_ID = "your-user-id"
# Set up OpenAI API key
os.environ['OPENAI_API_KEY'] = OPENAI_API_KEY
os.environ['MEM0_API_KEY'] = MEM0_API_KEY
# Initialize Mem0 and MultiOn
memory = Memory() # For local usage
memory_client = MemoryClient() # For API usage
multion = MultiOn(api_key=MULTION_API_KEY)
```
## Example 1: Research Paper Search Agent
### Add memories to Mem0
Define user data and add it to Mem0.
```python
USER_DATA = """
About me
- I'm Deshraj Yadav, Co-founder and CTO at Mem0, interested in AI and ML Infrastructure.
- Previously, I was a Senior Autopilot Engineer at Tesla, leading the AI Platform for Autopilot.
- I built EvalAI at Georgia Tech, an open-source platform for evaluating ML algorithms.
- Outside of work, I enjoy playing cricket in two leagues in the San Francisco.
"""
memory.add(USER_DATA, user_id=USER_ID)
print("User data added to memory.")
```
### Retrieving Relevant Memories
Define search command and retrieve relevant memories from Mem0.
```python
command = "Find papers on arxiv that I should read based on my interests."
relevant_memories = memory.search(command, user_id=USER_ID, limit=3)
relevant_memories_text = '\n'.join(mem['memory'] for mem in relevant_memories['results'])
print(f"Relevant memories:")
print(relevant_memories_text)
```
### Browsing arXiv
Use MultiOn to browse arXiv based on the command and relevant memories.
```python
prompt = f"{command}\n My past memories: {relevant_memories_text}"
browse_result = multion.browse(cmd=prompt, url="https://arxiv.org/")
print(browse_result)
```
## Example 2: Travel Agent
### Get Travel Information
Add conversation to Mem0 and create a function to get travel information based on user's question and optionally their preferences from memory.
<CodeGroup>
```python Code
def get_travel_info(question, use_memory=True):
if use_memory:
previous_memories = memory_client.search(question, user_id=USER_ID)
relevant_memories_text = ""
if previous_memories and previous_memories.get('results'):
print("Using previous memories to enhance the search...")
relevant_memories_text = '\n'.join(mem["memory"] for mem in previous_memories['results'])
command = "Find travel information based on my interests:"
prompt = f"{command}\n Question: {question} \n My preferences: {relevant_memories_text}"
else:
command = "Find travel information based on my interests:"
prompt = f"{command}\n Question: {question}"
print("Searching for travel information...")
browse_result = multion.browse(cmd=prompt)
return browse_result.message
# Example usage
question = "Show me flight details for it."
answer_without_memory = get_travel_info(question, use_memory=False)
answer_with_memory = get_travel_info(question, use_memory=True)
print("Answer without memory:", answer_without_memory)
print("Answer with memory:", answer_with_memory)
# Another example
question = "What is the best place to eat there?"
answer_without_memory = get_travel_info(question, use_memory=False)
answer_with_memory = get_travel_info(question, use_memory=True)
print("Answer without memory:", answer_without_memory)
print("Answer with memory:", answer_with_memory)
```
```json Conversation
# Add conversation to Mem0
conversation = [
{
"role": "user",
"content": "What are the best travel destinations in the world?"
},
{
"role": "assistant",
"content": "Could you please specify your interests or the type of travel information you are looking for? This will help me find the most relevant information for you."
},
{
"role": "user",
"content": "Sure, I want to travel to San Francisco."
},
{
"role": "assistant",
"content": """
Based on the information gathered from TripAdvisor, here are some popular attractions, activities, and travel tips for San Francisco: \
1. **Golden Gate Bridge**: A must-see iconic landmark. \
2. **Alcatraz Island**: Famous former prison offering tours. \
3. **Fisherman's Wharf**: Popular tourist area with shops, restaurants, and sea lions. \
4. **Chinatown**: The largest Chinatown outside of Asia. \
5. **Golden Gate Park**: Large urban park with gardens, museums, and recreational activities. \
6. **Cable Cars**: Historic streetcars offering a unique way to see the city. \
7. **Exploratorium**: Interactive science museum. \
8. **San Francisco Museum of Modern Art (SFMOMA)**: Modern and contemporary art museum. \
9. **Lombard Street**: Known for its steep, one-block section with eight hairpin turns. \
10. **Union Square**: Major shopping and cultural hub. \
Travel Tips: \
- **Weather**: San Francisco has a mild climate, but it can be foggy and windy. Dress in layers. \
- **Transportation**: Use public transportation like BART, Muni, and cable cars to get around. \
- **Safety**: Be aware of your surroundings, especially in crowded tourist areas. \
- **Dining**: Try local specialities like sourdough bread, seafood, and Mission-style burritos. \
"""
},
{
"role": "user",
"content": "Show me hotels around Golden Gate Bridge."
},
{
"role": "assistant",
"content": """The search results for hotels around Golden Gate Bridge in San Francisco include: \
1. Hilton Hotels In San Francisco - Hotel Near Fishermans Wharf (hilton.com) \
2. The 10 Closest Hotels to Golden Gate Bridge (tripadvisor.com) \
3. Hotels near Golden Gate Bridge (expedia.com) \
4. Hotels near Golden Gate Bridge (hotels.com) \
5. Holiday Inn Express & Suites San Francisco Fishermans Wharf, an IHG Hotel $146 (1.8K) 3-star hotel Golden Gate Bridge • 3.5 mi DEAL 19% less than usual \
6. Holiday Inn San Francisco-Golden Gateway, an IHG Hotel $151 (3.5K) 3-star hotel Golden Gate Bridge • 3.7 mi Casual hotel with dining, a bar & a pool \
7. Hotel Zephyr San Francisco $159 (3.8K) 4-star hotel Golden Gate Bridge • 3.7 mi Nautical-themed lodging with bay views \
8. Lodge at the Presidio \
9. The Inn Above Tide \
10. Cavallo Point \
11. Casa Madrona Hotel and Spa \
12. Cow Hollow Inn and Suites \
13. Samesun San Francisco \
14. Inn on Broadway \
15. Coventry Motor Inn \
16. HI San Francisco Fisherman's Wharf Hostel \
17. Loews Regency San Francisco Hotel \
18. Fairmont Heritage Place Ghirardelli Square \
19. Hotel Drisco Pacific Heights \
20. Travelodge by Wyndham Presidio San Francisco \
"""
}
]
```
</CodeGroup>
## Conclusion
By integrating Mem0 with MultiOn, you've created personalized browser agents that remember user preferences and automate web tasks. The first example demonstrates a research-focused agent, while the second example shows a travel agent capable of providing personalized recommendations.
These examples illustrate how combining memory management with web browsing capabilities can create powerful, context-aware AI agents for various applications.
## Help
- For more details and advanced usage, refer to the full [cookbooks here](https://github.com/mem0ai/mem0/blob/main/cookbooks).
- Feel free to visit our [Github](https://github.com/mem0ai/mem0) or [Mem0 Platform](https://app.mem0.ai/).
- For any questions or assistance, please reach out to `taranjeetio` on [Discord](https://mem0.dev/DiD).
<Snippet file="get-help.mdx" />
-2
View File
@@ -2,8 +2,6 @@
title: OpenAI Agents SDK
---
<Snippet file="blank-notif.mdx" />
Integrate [**Mem0**](https://github.com/mem0ai/mem0) with [OpenAI Agents SDK](https://github.com/openai/openai-agents-python), a lightweight framework for building multi-agent workflows. This integration enables agents to access persistent memory across conversations, enhancing context retention and personalization.
## Overview
+1 -3
View File
@@ -3,8 +3,6 @@ title: 'Pipecat'
description: 'Integrate Mem0 with Pipecat for conversational memory in AI agents'
---
<Snippet file="blank-notif.mdx" />
# Pipecat Integration
Mem0 seamlessly integrates with [Pipecat](https://pipecat.ai), providing long-term memory capabilities for conversational AI agents. This integration allows your Pipecat-powered applications to remember past conversations and provide personalized responses based on user history.
@@ -94,7 +92,7 @@ async def websocket_endpoint(websocket: WebSocket):
await websocket.accept()
# Basic setup with minimal configuration
user_id = "user123"
user_id = "alice"
# WebSocket transport
transport = FastAPIWebsocketTransport(
-2
View File
@@ -3,8 +3,6 @@ title: "Raycast Extension"
description: "Mem0 Raycast extension for intelligent memory management"
---
<Snippet file="blank-notif.mdx" />
Mem0 is a self-improving memory layer for LLM applications, enabling personalized AI experiences that save costs and delight users. This extension lets you store and retrieve text snippets using Mem0's intelligent memory system. Find Mem0 in [Raycast Store](https://www.raycast.com/dev_khant/mem0) for using it.
## Getting Started
-2
View File
@@ -2,8 +2,6 @@
title: Vercel AI SDK
---
<Snippet file="blank-notif.mdx" />
The [**Mem0 AI SDK Provider**](https://www.npmjs.com/package/@mem0/vercel-ai-provider) is a library developed by **Mem0** to integrate with the Vercel AI SDK. This library brings enhanced AI interaction capabilities to your applications by introducing persistent memory functionality.
<Note type="info">

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