Compare commits

...
109 Commits
Author SHA1 Message Date
Saket AryanandGitHub 5e895c240a Update version to 0.1.116 (#3312) 2025-08-14 00:06:34 +05:30
Parshva DaftariandGitHub b4bd7b48df Fixing Json import for the psycopg and psycopg2 (#3310) 2025-08-13 23:52:58 +05:30
Parshva DaftariandGitHub 1bc31b6ae3 Added sanitation for better relationship mapping (#3300) 2025-08-13 11:06:05 -05:00
Parshva DaftariandGitHub 7159221d2e Restrict package version (#3305) 2025-08-12 16:53:21 -05:00
Parshva DaftariandGitHub c89dc72f79 Fix failing tests (#3304) 2025-08-12 15:23:54 -05:00
Parshva DaftariandGitHub 2145ffdb1c Updated docs for agent_id and run_id (#3294) 2025-08-12 15:03:39 -05:00
Parshva DaftariandGitHub 23d31a830b Added support for python 3.12 (#3295) 2025-08-12 15:01:41 -05:00
Andrew CarbonettoandGitHub ab099312d5 Add neptune example notebook and documentation (#3224)
Signed-off-by: Andrew Carbonetto <andrew.carbonetto@improving.com>
2025-08-12 15:00:18 -05:00
8557533b8f DOC: Fix missing Neptune Analytics mention on doc (#3264)
Signed-off-by: Andy Kwok <andy.kwok@improving.com>
Co-authored-by: Andrew Carbonetto <andrew.carbonetto@improving.com>
2025-08-12 14:59:28 -05:00
AymenandGitHub 72e5a4fcc4 docs: Remove unused and missing OS module from examples (#3090) 2025-08-12 14:58:43 -05:00
Bruce WangandGitHub b199186163 Fix: refer to 61~62, self.config.graph_store.lm.config should be prioritized for usage (#3043) 2025-08-12 14:56:24 -05:00
Anirudh SandGitHub 9e9dcd70e1 refactor: Update batch update method documentation to clarify optiona… (#2982) 2025-08-12 14:55:53 -05:00
Stefan GajanovicandGitHub dbe909c352 added simple sanitizer methods for nodes and realtionships (#3021) 2025-08-12 14:54:12 -05:00
YuriyTWandGitHub d65a39c125 refactor: Improve async handling in AsyncMemory class for better performance (#3250) 2025-08-12 22:43:00 +05:30
Parshva DaftariandGitHub b60a208c2f Fixes n_embeddings use and error for memgraph (#3296) 2025-08-11 12:57:29 -05:00
cnScarbandGitHub c2792c6558 docs: fix search method return value handling in integration and example docs (#3208) 2025-08-11 12:16:01 -05:00
Parshva DaftariandGitHub 2307dc8613 Fix/supported llm params (#3290) 2025-08-08 14:39:42 -07:00
John LockwoodandGitHub 4c748423fc Feat/llm monitoring callback (#2877) 2025-08-08 14:26:51 -07:00
26732771eb Fix Neo4j Cypher syntax error with agent_id filtering (#3158)
Co-authored-by: parshvadaftari <daftariparshva@gmail.com>
2025-08-08 09:08:13 -07:00
Parshva DaftariandGitHub 148bbf0a5c Add sslmode pgvector (#3265) 2025-08-06 10:28:02 -07:00
Parshva DaftariandGitHub 6e8c6c1cb7 Refactored base class config for llms (#3241) 2025-08-05 15:42:06 -07:00
Parshva DaftariandGitHub f59ef3f2e2 Update docker compose (#3258) 2025-08-05 15:40:14 -07:00
VimpasandGitHub 7a0dc7391e feat: Add db_name field to MilvusDBConfig and MilvusDB initialization (#3229) 2025-08-05 11:16:34 -07:00
Saket AryanandGitHub 7fac6311f4 ai-sdk/docs: V5 Migration Docs (#3277) 2025-08-05 09:49:45 -07:00
0e18f54d36 Vercel AI SDK migration to V5 (#3223)
Co-authored-by: Saket Aryan <94069182+whysosaket@users.noreply.github.com>
2025-08-05 20:27:57 +05:30
Parshva DaftariandGitHub 42e60d6724 Added mulit id filters support for all vectorstores (#3269) 2025-08-04 14:52:57 -07:00
Parshva DaftariandGitHub 57a16aeb4b Updated psycopg -> 3 (#3271) 2025-08-04 14:46:44 -07:00
5ea2d56d88 fix: add RedisCloud search module check (#3192)
Co-authored-by: Saket Aryan <94069182+whysosaket@users.noreply.github.com>
2025-08-04 22:08:07 +05:30
Parshva DaftariandGitHub 7d1d0ca806 fixes memgraph async attirbute error (#3209) 2025-08-01 13:19:08 -07:00
Parshva DaftariandGitHub 89b67e0834 Refactoring from gemini to google ai (#3244) 2025-08-01 11:56:42 -07:00
Parshva DaftariandGitHub fbe8a2e90f Fix indexing when using Qdrant cloud (#3228) 2025-08-01 11:55:11 -07:00
Enam BiswasandGitHub 907328aafe feat (pinecone): Add namespace support and improve type safety (#3216) 2025-08-01 11:53:34 -07:00
Antaripa SahaandGitHub 0e03d69ed1 Personalized Search Example Docs (#3259) 2025-08-01 17:02:58 +05:30
Prateek ChhikaraandGitHub 0412e62cb1 Update field in docs (#3254) 2025-07-30 12:22:56 -07:00
Antaripa SahaandGitHub 724c553a2e Personalized Search using Tavily + Mem0 (#3232) 2025-07-29 15:20:11 +05:30
Saket AryanandGitHub 08e7ae02de docs: Async Add Announcement (#3231) 2025-07-29 00:26:59 +05:30
ColsrchandGitHub d0f61d5995 fix: Ignore memgraph index duplicate creation errors (#3203) 2025-07-25 01:07:23 +05:30
Parshva DaftariandGitHub 4433666117 Fix failing tests (#3162) 2025-07-25 00:58:45 +05:30
Saket AryanandGitHub 37ee3c5eb2 docs: Update for new Project API and deprecation notices (#3212) 2025-07-24 15:16:47 +05:30
Dev KhantandGitHub c8892bb1fe Update Changelog (#3211) 2025-07-24 10:17:51 +05:30
Antaripa SahaandGitHub 1a8d175570 Content Writing Example Rewrite (#3142) 2025-07-16 11:47:50 +05:30
Antaripa SahaandGitHub 0560d87160 Multiagent Learning System with LlamaIndex (#3063) 2025-07-16 11:47:17 +05:30
Antaripa SahaandGitHub 9f3fd06334 Agno Mem0Tools update (#3139) 2025-07-16 11:46:51 +05:30
Antaripa SahaandGitHub c1ca366edd Multi-LLM Research Team powered by memory (#3160) 2025-07-16 11:46:31 +05:30
askdevai-botandGitHub cba3217280 docs: Add comprehensive LLM-friendly documentation (#3154) 2025-07-16 06:06:31 +05:30
Parshva DaftariandGitHub 77ea103b5d Updated livekit 1.0 integration (#3073) 2025-07-16 00:27:14 +05:30
Saket AryanandGitHub bcc5f42941 Restore and update handle_post_message implementation (#3152) 2025-07-14 21:25:45 +05:30
Saket AryanandGitHub 3bc5090371 Update personalized deep research example with GitHub link (#3136) 2025-07-10 18:01:33 -07:00
Antaripa SahaandGitHub de0513fc9f AWS Bedrock Integration and spell checks (#3124) 2025-07-08 10:16:44 -07:00
Saket AryanandGitHub ec9b0688d8 Add structured_data_schema to MemoryOptions interface (#3125) 2025-07-08 10:07:44 -07:00
Saket AryanandGitHub 0f5612b96d Add JavaScript examples for memory export API (#3119) 2025-07-08 13:46:26 +05:30
Saket AryanandGitHub 842903b1b1 feat: Memory Exports (#3117) 2025-07-08 11:34:49 +05:30
Dev KhantandGitHub 70d6f9231b Abstraction for Project in MemoryClient (#3067) 2025-07-08 11:33:20 +05:30
Varun MohantaandGitHub aae5989e78 Fix: Changed keyword from assisstant to secretary (#2937) 2025-07-08 10:57:25 +05:30
Saket AryanandGitHub 6866e56d7a Add metadata field to memory update schema (#3115) 2025-07-07 09:49:13 -07:00
Antaripa SahaandGitHub 2992c298cb Security Link updated (#3108) 2025-07-05 10:25:35 -07:00
Akshat JainandGitHub 4491e7f9f4 Fix: Memgraph Graph Generation Issue (#3109) 2025-07-05 10:06:13 -07:00
Deshraj YadavandGitHub c0a930a7d3 Update version to 0.1.114 (#3107) 2025-07-04 16:28:39 -07:00
Andrew CarbonettoandGitHub 05c404d8d3 Add Amazon Neptune Analytics graph_store configuration & integration (#2949) 2025-07-04 16:26:21 -07:00
Deshraj YadavandGitHub 7484eed4b2 Fix CI issues related to missing dependency (#3096) 2025-07-03 18:52:50 -07:00
MingxiangyuandGitHub 2c496e6376 Fix the error that occurs when VLLM is called (#3076) 2025-07-03 14:41:10 -07:00
JainishandGitHub a20b68fcec Fixes: Mem0 Setup, Logging, Docs (#3080) 2025-07-03 14:40:39 -07:00
Sakshi SrivastavaandGitHub eb7c712aa6 Fix: Add missing OpenAI import in vLLM module (#3091) 2025-07-03 14:37:20 -07:00
Saket AryanandGitHub 7476c39257 Add Gemini Model Support to Vercel AI SDK Provider (#3094) 2025-07-03 09:54:11 -07:00
Saket AryanandGitHub 5b0f1a7cf8 feat: Add Gemini support to TypeScript SDK (#3093) 2025-07-03 09:53:52 -07:00
Antaripa SahaandGitHub b336cdf018 Image fixes (#3089) 2025-07-02 11:40:55 -07:00
Antaripa SahaandGitHub 60e4e8a662 Google AI ADK Integration Docs (#3086) 2025-07-02 10:23:37 -07:00
Chaithanya KumarandGitHub 6d4a78b7c7 Enhance documentation: Add group chat feature to the list of platform… (#3077) 2025-07-02 11:13:01 +05:30
Antaripa SahaandGitHub d39a1d5541 Openai agents sdk added (#3081) 2025-07-01 17:02:59 -07:00
Parshva DaftariandGitHub 044ad4f131 Reverting the changes of pip install (#3010) 2025-07-01 15:49:39 +05:30
Antaripa SahaandGitHub 75482fdb29 Docs SOC2 and HIPAA update (#3075) 2025-07-01 01:21:53 -07:00
Antaripa SahaandGitHub 6c69599db9 Docs Update Images (#3072) 2025-07-01 00:36:30 -07:00
Kade ShockeyandGitHub b79bfb7c1e MongoDB Vector Store misaligned strings and classes (#3064) 2025-07-01 11:12:28 +05:30
Dev KhantandGitHub 5a1083b709 Fix: Gemini embedder config and version bump -> 0.1.113 (#3070) 2025-06-30 13:31:51 +05:30
Dev KhantandGitHub ac085db500 version bump -> 0.1.112 (#3058) 2025-06-27 15:19:57 +05:30
Dev KhantandGitHub 2cc253341c Fix mongodb config name (#3052) 2025-06-26 23:06:21 +05:30
Dev KhantandGitHub e3e2da6d45 Fix: Gemini Embeddings and LLM (#3050) 2025-06-26 21:05:00 +05:30
Dev KhantandGitHub acf7a30d32 Doc: Add async_mode (#3037) 2025-06-25 10:51:49 -07:00
Saket AryanandGitHub a4f6751741 fix(ui-backend): resolve provider name format inconsistency in form configuration (#3041) 2025-06-25 09:48:22 -07:00
6f3fbd087d fix: Fix memory categorization by updating dependencies and correcting API usage (#3005)
Co-authored-by: Claude <noreply@anthropic.com>
Co-authored-by: Saket Aryan <94069182+whysosaket@users.noreply.github.com>
2025-06-25 22:02:26 +05:30
Antaripa SahaandGitHub a98842422b doc: Broken links fixed in docs (#3034) 2025-06-25 17:18:29 +05:30
Antaripa SahaandGitHub aaf879322c Platform feature docs revamp (#3007) 2025-06-25 00:57:08 -07:00
Laith Al-SaadoonandGitHub 8139b5887f fix: bedrock llm, embeddings, tools, temporary creds (#3023) 2025-06-24 20:46:06 +05:30
Saket AryanandGitHub b4b27f099e Add immutable param to add method and bump version (#3022) 2025-06-24 05:03:35 +05:30
Dev KhantandGitHub dc877fd3ba version bump -> 0.1.111 (#3016) 2025-06-23 21:52:03 +05:30
Akshat JainandGitHub 2bb0653e67 Add: Json Parsing to solve Hallucination Errors (#3013) 2025-06-23 21:50:16 +05:30
eb24b92227 Add : Openmemory Local Support using New Library (#3014)
Co-authored-by: Saket Aryan <saketaryan2002@gmail.com>
2025-06-23 20:45:46 +05:30
Akshat JainandGitHub a5ec286fd4 Add: Openmemory Augment support (#3015) 2025-06-23 20:45:01 +05:30
NiLAyandGitHub 89499aedbe Feature/vllm support (#2981) 2025-06-23 13:18:38 +05:30
386d8b87ae Fix: Migrate Gemini Embeddings (#3002)
Co-authored-by: Dev-Khant <devkhant24@gmail.com>
2025-06-23 13:16:10 +05:30
Akshat JainandGitHub c173ec32d0 Improve Docs: Agent Id - Mem0 OSS Graph Memory (#2969) 2025-06-21 23:34:28 +05:30
Akshat JainandGitHub dd6f6f7a2e Fix: Add MCP Client Integration Guide and update installation commands (#2956) 2025-06-20 22:09:10 +05:30
Dev KhantandGitHub b6684b96f7 version bump -> 0.1.110 (#3001) 2025-06-20 20:30:51 +05:30
Akarsha SehwagandGitHub 1fa0f0a157 fix(opensearch): update logger warning (#2999) 2025-06-20 20:28:51 +05:30
Saket AryanandGitHub 2754f45387 Make V2 Add as Default (#2997) 2025-06-20 16:56:42 +05:30
Parshva DaftariandGitHub ecd4d91046 Fix failing CI pipeline (#2979) 2025-06-20 15:19:11 +05:30
Prateek ChhikaraandGitHub a5a247b161 Update client.update() method documentation in OpenAPI specification (#2990) 2025-06-19 14:04:12 -07:00
Dev KhantandGitHub d47cb8d284 Doc: Fix example in quickstart page (#2986) 2025-06-19 13:51:20 +05:30
Dev KhantandGitHub fa15db089d Update Changelog (#2985) 2025-06-19 12:32:33 +05:30
Shili CaoandGitHub d35065c887 Feature: baidu vector db integration (#2929) 2025-06-19 11:12:12 +05:30
Prateek ChhikaraandGitHub cdee6a4ff0 Enhance update method to support metadata (#2976) 2025-06-18 10:07:18 -07:00
Dev KhantandGitHub 9eb4e77c75 Fix pinecone for async memory (#2975) 2025-06-18 01:37:45 +05:30
Akshat JainandGitHub c700d790db Fix Build CI Failure (#2973) 2025-06-17 09:39:19 -07:00
Antaripa SahaandGitHub a90b572389 Memory agent powered by voice (Cartesia + Agno) (#2970) 2025-06-17 18:54:53 +05:30
i-sunandGitHub 62c330e5b3 feat(LM Studio): Add response_format param for LM Studio to config (#2502) 2025-06-17 17:55:18 +05:30
Akshat JainandGitHub c70dc7614b Fix: Add Google Genai library support (#2941) 2025-06-17 17:47:09 +05:30
Fenil FalduandGitHub e0003247c3 feat: add AgentOps integration (#2898) 2025-06-17 11:38:39 +05:30
Saket AryanandGitHub 888ee766c5 TS SDK - filter memories param (#2971) 2025-06-17 10:54:35 +05:30
Saket AryanandGitHub c7e91171a0 Added Param output_format in AI SDK (#2960) 2025-06-15 06:42:56 +05:30
299 changed files with 21943 additions and 3277 deletions
+10 -10
View File
@@ -37,7 +37,7 @@ jobs:
runs-on: ubuntu-latest
strategy:
matrix:
python-version: ["3.10", "3.11"]
python-version: ["3.10", "3.11", "3.12"]
steps:
- uses: actions/checkout@v3
- name: Set up Python ${{ matrix.python-version }}
@@ -52,16 +52,16 @@ jobs:
with:
path: .venv
key: venv-mem0-${{ runner.os }}-${{ hashFiles('**/pyproject.toml') }}
- name: Install GEOS Libraries
run: sudo apt-get update && sudo apt-get install -y libgeos-dev
- name: Install dependencies
run: |
make install_all
pip install -e ".[test]"
pip install pinecone pinecone-text
pip install --upgrade pip
pip install -e ".[test,graph,vector_stores,llms,extras]"
pip install ruff
if: steps.cached-hatch-dependencies.outputs.cache-hit != 'true'
- name: Run Formatting
run: |
mkdir -p .ruff_cache && chmod -R 777 .ruff_cache
hatch run format
- name: Run Linting
run: make lint
- name: Run tests and generate coverage report
run: make test
@@ -71,7 +71,7 @@ jobs:
runs-on: ubuntu-latest
strategy:
matrix:
python-version: ["3.9", "3.10", "3.11"]
python-version: ["3.9", "3.10", "3.11", "3.12"]
steps:
- uses: actions/checkout@v3
- name: Set up Python ${{ matrix.python-version }}
@@ -102,4 +102,4 @@ jobs:
with:
file: coverage.xml
env:
CODECOV_TOKEN: ${{ secrets.CODECOV_TOKEN }}
CODECOV_TOKEN: ${{ secrets.CODECOV_TOKEN }}
+2
View File
@@ -25,6 +25,7 @@ We use `hatch` for managing development environments. To set up:
hatch shell dev_py_3_9 # Python 3.9
hatch shell dev_py_3_10 # Python 3.10
hatch shell dev_py_3_11 # Python 3.11
hatch shell dev_py_3_12 # Python 3.12
# The environment will automatically install all dev dependencies
# Run tests within the activated shell:
@@ -51,6 +52,7 @@ make test
make test-py-3.9 # Python 3.9 environment
make test-py-3.10 # Python 3.10 environment
make test-py-3.11 # Python 3.11 environment
make test-py-3.12 # Python 3.12 environment
# When using hatch shells, run tests with:
make test # After activating a shell with hatch shell test_XX
+1271
View File
File diff suppressed because it is too large Load Diff
+5 -2
View File
@@ -12,8 +12,8 @@ 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 rank-bm25
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
# Format code with ruff
format:
@@ -50,3 +50,6 @@ test-py-3.10:
test-py-3.11:
hatch run dev_py_3_11:test
test-py-3.12:
hatch run dev_py_3_12:test
+5
View File
@@ -0,0 +1,5 @@
<Note type="info">
📢 Heads up!
We're moving to async memory add for a faster experience.
If you signed up after July 1st, 2025, your add requests will work in the background and return right away.
</Note>
+3
View File
@@ -0,0 +1,3 @@
<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>
+123 -1
View File
@@ -4,7 +4,7 @@ icon: "info"
iconType: "solid"
---
<Snippet file="paper-release.mdx" />
<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.
@@ -60,6 +60,128 @@ const client = new MemoryClient({organizationId: "YOUR_ORG_ID", projectId: "YOUR
</Tab>
</Tabs>
### Project Management Methods
The Mem0 client provides comprehensive project management capabilities through the `client.project` interface:
#### Get Project Details
Retrieve information about the current project:
```python
# Get all project details
project_info = client.project.get()
# Get specific fields only
project_info = client.project.get(fields=["name", "description", "custom_categories"])
```
#### Create a New Project
Create a new project within your organization:
```python
# Create a project with name and description
new_project = client.project.create(
name="My New Project",
description="A project for managing customer support memories"
)
```
#### Update Project Settings
Modify project configuration including custom instructions, categories, and graph settings:
```python
# Update project with custom categories
client.project.update(
custom_categories=[
{"customer_preferences": "Customer likes, dislikes, and preferences"},
{"support_history": "Previous support interactions and resolutions"}
]
)
# Update project with custom instructions
client.project.update(
custom_instructions="..."
)
# Enable graph memory for the project
client.project.update(enable_graph=True)
# Update multiple settings at once
client.project.update(
custom_instructions="...",
custom_categories=[
{"personal_info": "User personal information and preferences"},
{"work_context": "Professional context and work-related information"}
],
enable_graph=True
)
```
#### Delete Project
<Note>
This action will remove all memories, messages, and other related data in the project. This operation is irreversible.
</Note>
Remove a project and all its associated data:
```python
# Delete the current project (irreversible)
result = client.project.delete()
```
#### Member Management
Manage project members and their access levels:
```python
# Get all project members
members = client.project.get_members()
# Add a new member as a reader
client.project.add_member(
email="colleague@company.com",
role="READER" # or "OWNER"
)
# Update a member's role
client.project.update_member(
email="colleague@company.com",
role="OWNER"
)
# Remove a member from the project
client.project.remove_member(email="colleague@company.com")
```
#### Member Roles
- **READER**: Can view and search memories, but cannot modify project settings or manage members
- **OWNER**: Full access including project modification, member management, and all reader permissions
#### Async Support
All project methods are also available in async mode:
```python
from mem0 import AsyncMemoryClient
async def manage_project():
client = AsyncMemoryClient(org_id='YOUR_ORG_ID', project_id='YOUR_PROJECT_ID')
# All methods support async/await
project_info = await client.project.get()
await client.project.update(enable_graph=True)
members = await client.project.get_members()
# To call the async function properly
import asyncio
asyncio.run(manage_project())
```
## Getting Started
To begin using the Mem0 API, you'll need to:
+557 -247
View File
@@ -3,11 +3,243 @@ title: "Product Updates"
mode: "wide"
---
<Snippet file="paper-release.mdx" />
<Snippet file="blank-notif.mdx" />
<Tabs>
<Tab title="Python">
<Update label="2025-07-24" description="v0.1.115">
**New Features & Updates:**
- Enhanced project management via `client.project` and `AsyncMemoryClient.project` interfaces
- Full support for project CRUD operations (create, read, update, delete)
- Project member management: add, update, remove, and list members
- Manage project settings including custom instructions, categories, retrieval criteria, and graph enablement
- Both sync and async support for all project management operations
**Improvements:**
- **Documentation:**
- Added detailed API reference and usage examples for new project management methods.
- Updated all docs to use `client.project.get()` and `client.project.update()` instead of deprecated methods.
- **Deprecation:**
- Marked `get_project()` and `update_project()` as deprecated (these methods were already present); added warnings to guide users to the new API.
**Bug Fixes:**
- **Tests:**
- Fixed Gemini embedder and LLM test mocks for correct error handling and argument structure.
- **vLLM:**
- Fixed duplicate import in vLLM module.
</Update>
<Update label="2025-07-05" description="v0.1.114">
**New Features:**
- **OpenAI Agents:** Added OpenAI agents SDK support
- **Amazon Neptune:** Added Amazon Neptune Analytics graph_store configuration and integration
- **vLLM:** Added vLLM support
**Improvements:**
- **Documentation:**
- Added SOC2 and HIPAA compliance documentation
- Enhanced group chat feature documentation for platform
- Added Google AI ADK Integration documentation
- Fixed documentation images and links
- **Setup:** Fixed Mem0 setup, logging, and documentation issues
**Bug Fixes:**
- **MongoDB:** Fixed MongoDB Vector Store misaligned strings and classes
- **vLLM:** Fixed missing OpenAI import in vLLM module and call errors
- **Dependencies:** Fixed CI issues related to missing dependencies
- **Installation:** Reverted pip install changes
</Update>
<Update label="2025-06-30" description="v0.1.113">
**Bug Fixes:**
- **Gemini:** Fixed Gemini embedder configuration
</Update>
<Update label="2025-06-27" description="v0.1.112">
**New Features:**
- **Memory:** Added immutable parameter to add method
- **OpenMemory:** Added async_mode parameter support
**Improvements:**
- **Documentation:**
- Enhanced platform feature documentation
- Fixed documentation links
- Added async_mode documentation
- **MongoDB:** Fixed MongoDB configuration name
**Bug Fixes:**
- **Bedrock:** Fixed Bedrock LLM, embeddings, tools, and temporary credentials
- **Memory:** Fixed memory categorization by updating dependencies and correcting API usage
- **Gemini:** Fixed Gemini Embeddings and LLM issues
</Update>
<Update label="2025-06-23" description="v0.1.111">
**New Features:**
- **OpenMemory:**
- Added OpenMemory augment support
- Added OpenMemory Local Support using new library
- **vLLM:** Added vLLM support integration
**Improvements:**
- **Documentation:**
- Added MCP Client Integration Guide and updated installation commands
- Improved Agent Id documentation for Mem0 OSS Graph Memory
- **Core:** Added JSON parsing to solve hallucination errors
**Bug Fixes:**
- **Gemini:** Fixed Gemini Embeddings migration
</Update>
<Update label="2025-06-20" description="v0.1.110">
**New Features:**
- **Baidu:** Added Baidu vector database integration
**Improvements:**
- **Documentation:**
- Updated changelog
- Fixed example in quickstart page
- Updated client.update() method documentation in OpenAPI specification
- **OpenSearch:** Updated logger warning
**Bug Fixes:**
- **CI:** Fixed failing CI pipeline
</Update>
<Update label="2025-06-19" description="v0.1.109">
**New Features:**
- **AgentOps:** Added AgentOps integration
- **LM Studio:** Added response_format parameter for LM Studio configuration
- **Examples:** Added Memory agent powered by voice (Cartesia + Agno)
**Improvements:**
- **AI SDK:** Added output_format parameter
- **Client:** Enhanced update method to support metadata
- **Google:** Added Google Genai library support
**Bug Fixes:**
- **Build:** Fixed Build CI failure
- **Pinecone:** Fixed pinecone for async memory
</Update>
<Update label="2025-06-14" description="v0.1.108">
**New Features:**
- **MongoDB:** Added MongoDB Vector Store support
- **Client:** Added client support for summary functionality
**Improvements:**
- **Pinecone:** Fixed pinecone version issues
- **OpenSearch:** Added logger support
- **Testing:** Added python version test environments
</Update>
<Update label="2025-06-11" description="v0.1.107">
**Improvements:**
- **Documentation:**
- Updated Livekit documentation migration
- Updated OpenMemory hosted version documentation
- **Core:** Updated categorization flow
- **Storage:** Fixed migration issues
</Update>
<Update label="2025-06-09" description="v0.1.106">
**New Features:**
- **Cloudflare:** Added Cloudflare vector store support
- **Search:** Added threshold parameter to search functionality
- **API:** Added wildcard character support for v2 Memory APIs
**Improvements:**
- **Documentation:** Updated README docs for OpenMemory environment setup
- **Core:** Added support for unique user IDs
**Bug Fixes:**
- **Core:** Fixed error handling exceptions
</Update>
<Update label="2025-06-03" description="v0.1.104">
**Bug Fixes:**
- **Vector Stores:** Fixed GET_ALL functionality for FAISS and OpenSearch
</Update>
<Update label="2025-06-02" description="v0.1.103">
**New Features:**
- **LLM:** Added support for OpenAI compatible LLM providers with baseUrl configuration
**Improvements:**
- **Documentation:**
- Fixed broken links
- Improved Graph Memory features documentation clarity
- Updated enable_graph documentation
- **TypeScript SDK:** Updated Google SDK peer dependency version
- **Client:** Added async mode parameter
</Update>
<Update label="2025-05-26" description="v0.1.102">
**New Features:**
- **Examples:** Added Neo4j example
- **AI SDK:** Added Google provider support
- **OpenMemory:** Added LLM and Embedding Providers support
**Improvements:**
- **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:**
- Removed support for passing string as input in client.add()
- Added support for sarvam-m model
- **TypeScript SDK:** Fixed types from message interface
**Bug Fixes:**
- **Memory:** Prevented saving prompt artifacts as memory when no new facts are present
- **OpenMemory:** Fixed typos in MCP tool description
</Update>
<Update label="2025-05-15" description="v0.1.101">
**New Features:**
- **Neo4j:** Added base label configuration support
**Improvements:**
- **Documentation:**
- Updated Healthcare example index
- Enhanced collaborative task agent documentation clarity
- Added criteria-based filtering documentation
- **OpenMemory:** Added cURL command for easy installation
- **Build:** Migrated to Hatch build system
</Update>
<Update label="2025-05-10" description="v0.1.100">
**New Features:**
@@ -288,6 +520,41 @@ mode: "wide"
<Tab title="TypeScript">
<Update label="2025-08-04" description="v2.1.37">
**New Features:**
- **OSS:** Added `RedisCloud` search module check
</Update>
<Update label="2025-07-08" description="v2.1.36">
**New Features:**
- **Client:** Added `structured_data_schema` param to `add` method.
</Update>
<Update label="2025-07-08" description="v2.1.35">
**New Features:**
- **Client:** Added `createMemoryExport` and `getMemoryExport` methods.
</Update>
<Update label="2025-07-03" description="v2.1.34">
**New Features:**
- **OSS:** Added Gemini support
</Update>
<Update label="2025-06-24" description="v2.1.33">
**Improvement :**
- **Client:** Added `immutable` param to `add` method.
</Update>
<Update label="2025-06-20" description="v2.1.32">
**Improvement :**
- **Client:** Made `api_version` V2 as default.
</Update>
<Update label="2025-06-17" description="v2.1.31">
**Improvement :**
- **Client:** Added param `filter_memories`.
</Update>
<Update label="2025-06-06" description="v2.1.30">
**New Features:**
- **OSS:** Added Cloudflare support
@@ -345,7 +612,7 @@ mode: "wide"
<Update label="2025-04-28" description="v2.1.20">
**Improvements:**
- **Client:** Fixed `organizationId` and `projectId` being asssigned to default in `ping` method
- **Client:** Fixed `organizationId` and `projectId` being assigned to default in `ping` method
</Update>
<Update label="2025-04-22" description="v2.1.19">
@@ -404,7 +671,7 @@ mode: "wide"
<Update label="2025-03-29" description="v2.1.13">
**Improvements:**
- **Introuced `ping` method to check if API key is valid and populate org/project id**
- **Introduced `ping` method to check if API key is valid and populate org/project id**
</Update>
<Update label="2025-03-29" description="AI SDK v1.0.0">
@@ -437,6 +704,283 @@ mode: "wide"
<Tab title="Platform">
<Update label="2025-07-23" description="">
**Bug Fixes:**
- **Memory:** Fixed ADD functionality
</Update>
<Update label="2025-07-19" description="">
**New Features:**
- **UI:** Added Settings UI and latency display
- **Performance:** Neo4j query optimization
**Bug Fixes:**
- **OpenMemory:** Fixed OMM raising unnecessary exceptions
</Update>
<Update label="2025-07-18" description="">
**Improvements:**
- **UI:** Updated Event UI
- **Performance:** Fixed N+1 query issue in semantic_search_v2 by optimizing MemorySerializer field selection
**Bug Fixes:**
- **Memory:** Fixed duplicate memory index sentry error
</Update>
<Update label="2025-07-17" description="">
**New Features:**
- **UI:** New Settings Page
- **Memory:** Duplicate memories entities support
**Improvements:**
- **Performance:** Optimized semantic search and get_all APIs by eliminating N+1 queries
</Update>
<Update label="2025-07-16" description="">
**New Features:**
- **Database:** Implemented read replica routing with enhanced logging and app-specific DB routing
**Improvements:**
- **Performance:** Improved query performance in search v2 and get all v2 endpoints
**Bug Fixes:**
- **API:** Fixed pagination for get all API
</Update>
<Update label="2025-07-12" description="">
**Bug Fixes:**
- **Graph:** Fixed social graph bugs and connection issues
</Update>
<Update label="2025-07-11" description="">
**Improvements:**
- **Rate Limiting:** New rate limit for V2 Search
**Bug Fixes:**
- **Slack:** Fixed Slack rate limit error with backend improvements
</Update>
<Update label="2025-07-10" description="">
**Improvements:**
- **Performance:**
- Changed connection pooling time to 5 minutes
- Separated graph lambdas for better performance
</Update>
<Update label="2025-07-09" description="">
**Improvements:**
- **Graph:** Graph Optimizations V2 and memory improvements
</Update>
<Update label="2025-07-08" description="">
**New Features:**
- **Database:** Added read replica support for improved database performance
- **UI:** Implemented UI changes for Users Page
- **Feedback:** Enabled feedback functionality
**Bug Fixes:**
- **Serializer:** Fixed GET ALL Serializer
</Update>
<Update label="2025-07-05" description="">
**New Features:**
- **UI:** User Page Revamp and New Users Page
</Update>
<Update label="2025-07-04" description="">
**New Features:**
- **Users:** New Users Page implementation
- **Tools:** Added script to backfill memory categories
**Bug Fixes:**
- **Filters:** Fixed Filters Get All functionality
</Update>
<Update label="2025-07-03" description="">
**Improvements:**
- **Graph:** Graph Memory optimization
- **Memory:** Fixed exact memories and semantically similar memories retrieval
</Update>
<Update label="2025-07-02" description="">
**Improvements:**
- **Categorization:** Refactored categorization logic to utilize Gemini 2.5 Flash and improve message handling
</Update>
<Update label="2025-07-01" description="">
**Bug Fixes:**
- **Memory:** Fixed old_memory issue in Async memory addition lambda
- **Events:** Fixed missing events
</Update>
<Update label="2025-06-30" description="">
**Improvements:**
- **Graph:** Improvements to graph memory and added user to LTM-STM
</Update>
<Update label="2025-06-28" description="">
**New Features:**
- **Graph:** Added support for SQS in graph memory addition
- **Testing:** Added Locust load testing script and Grafana Dashboard
</Update>
<Update label="2025-06-27" description="">
**Improvements:**
- **Rate Limiting:** Updated rate limiting for ADD API to 1000/min
- **Performance:** Improved Neo4j performance
</Update>
<Update label="2025-06-26" description="">
**New Features:**
- **Memory:** Edit Memory From Drawer functionality
- **API:** Added Topic Suggestions API Endpoint
</Update>
<Update label="2025-06-25" description="">
**New Features:**
- **Group Chat:** Group-Chat v2 with Actor-Aware Memories
- **Memory:** Editable Metadata in Memories
- **UI:** Memory Actions Badges
</Update>
<Update label="2025-06-19" description="">
**New Features:**
- **Rate Limiting:** Implemented comprehensive rate limiting system
**Improvements:**
- **Performance:** Added performance indexes for memory stats query
**Bug Fixes:**
- **Search:** Fixed search events not respecting top-k parameter
</Update>
<Update label="2025-06-18" description="">
**New Features:**
- **Memory Management:** Implemented OpenAI Batch API for Memory Cleaning with fallback
- **Playground:** Added Claude 4 support on Playground
**Improvements:**
- **Memory:** Added ability to update memory metadata
</Update>
<Update label="2025-06-17" description="">
**New Features:**
- **UI:** New Memories Page UI design
</Update>
<Update label="2025-06-16" description="">
**Improvements:**
- **Infrastructure:** Migrated to Application Load Balancer (ALB)
</Update>
<Update label="2025-06-13" description="">
**Improvements:**
- **Memory Management:** Enhanced Memory Management with Cosine Similarity Fallback
</Update>
<Update label="2025-06-11" description="">
**New Features:**
- **OMM:** Added OMM Script and UI functionality
**Improvements:**
- **API:** Added filters validation to semantic_search_v2 endpoint
</Update>
<Update label="2025-06-09" description="">
**New Features:**
- **Intercom:** Set Intercom events for ADD and SEARCH operations
- **OpenMemory:** Added Posthog integration and feedback functionality
- **MCP:** New JavaScript MCP Server with feedback support
**Improvements:**
- **Structured Data:** Enhanced structured data handling in memory management
</Update>
<Update label="2025-06-06" description="">
**New Features:**
- **OAuth:** Added Mem0 OAuth integration
- **OMM:** Added OMM-Mem0 sync for deleted memories
</Update>
<Update label="2025-06-05" description="">
**New Features:**
- **Filters:** Implemented Wildcard Filters and refactored filter logic in V2 Views
</Update>
<Update label="2025-06-02" description="">
**New Features:**
- **OpenMemory Cloud:** Added OpenMemory Cloud support
- **Structured Data:** Added 'structured_attributes' field to Memory model
</Update>
<Update label="2025-05-30" description="">
**New Features:**
- **Projects:** Added version and enable_graph to project views
- **OpenMemory:** Added Postgres support for OpenMemory
</Update>
<Update label="2025-05-19" description="">
**Bug Fixes:**
@@ -444,254 +988,20 @@ mode: "wide"
</Update>
<Update label="2025-05-17" description="">
**New Features:**
- **Graph:** Added Neo4J Graph Migration
- **API:** Added API to set custom instructions
</Update>
<Update label="2025-05-16" description="">
**New Features:**
- **API:** Added Org-wide API Limit and Usage
**Improvements:**
- **Database:** Added migration for "is_deleted" column
- **Graph:** Improved graph queries
</Update>
<Update label="2025-05-15" description="">
**New Features:**
- **Lambda:** Added actions to lambda
- **Core:** Added background runs support
- **Models:** Added o4-mini for pro users
</Update>
<Update label="2025-05-10" description="">
**New Features:**
- **Integrations:** Added Intercom Events integration
- **Billing:** Added prefilled email for payments
- **Organizations:** Added Pro organization marking
**Improvements:**
- **UI:** Fixed loading jitter for organization selection
- **Infrastructure:** Improved production scaling
</Update>
<Update label="2025-05-09" description="">
**Improvements:**
- **Memory:** Fixed filters in Memory Page
- **Deployment:** Added custom categories for on-premise
</Update>
<Update label="2025-05-08" description="">
**Improvements:**
- **Backend:** Updated Django settings for metrics
- **Memory:** Added retries to memory filtering
- **Search:** Added scoring mechanism
</Update>
<Update label="2025-05-07" description="">
**Improvements:**
- **Deployment:** Updated deployment scripts
- **Testing:** Added code coverage tracking
- **Memory:** Added background cron job for memory quality
</Update>
<Update label="2025-05-06" description="">
**New Features:**
- **Models:** Added support for 4.1-mini model
**Improvements:**
- **Infrastructure:** Increased instance count
- **API:** Added V2 for Manage Entities
</Update>
<Update label="2025-05-04" description="">
**New Features:**
- **Testing:** Added code coverage tracking
- **AI:** Added Keywords AI integration
**Improvements:**
- **UI:** Updated UI with tabs
- **Database:** Added migrations for custom instructions
- **Search:** Added criteria filtering
</Update>
<Update label="2025-04-26" description="">
**Improvements:**
- **Performance:** Parallelized embedding calls
- **Monitoring:** Added timing for LLM calls
- **Search:** Added category checking in Search V2
- **Bug Fixes:** Fixed issues with ADD filters
- **Graph:** Implemented new graph updates
</Update>
<Update label="2025-04-25" description="">
**Improvements:**
- **Memory:** Fixed memory export functionality
- **Analytics:** Added logging for project
</Update>
<Update label="2025-04-24" description="">
**Improvements:**
- **Output:** Added memory_type display for ADD output
</Update>
<Update label="2025-04-23" description="">
**New Features:**
- **UI:** Added new Pricing Component
- **Memory:** Implemented Long/Short term memory categorization
- **Output:** Modified serializer to hide memory_type
**Documentation:**
- Updated README for deployment
</Update>
<Update label="2025-04-22" description="">
**New Features:**
- **Memory:** Added timestamp to ADD call
**Bug Fixes:**
- Fixed issues with coreV2
</Update>
<Update label="2025-04-21" description="">
**New Features:**
- **Memory:** Implemented backdating with migrations and backfilling script
</Update>
<Update label="2025-04-17" description="">
**New Features:**
- **Billing:** Integrated Stripe Billing Dashboard
- **Admin:** Added webhook creation functionality
**Bug Fixes:**
- Fixed Users Page issues
- Fixed Custom Categories
- Fixed Table components
- Updated Stripe configuration
</Update>
<Update label="2025-04-16" description="">
**Improvements:**
- **Performance:** Made Admin panel and Memory Page faster
- **Security:** Implemented active session cancellation
- **Analytics:** Added Stripe customer ID capture
</Update>
<Update label="2025-04-12" description="">
**New Features:**
- **Memory Management:**
- Added ability to delete memories from Project level with filters
- Added delete memories capability on Memories Page
- **Memory Visualization:** Released V1 Graph Memory Visualization
- **Graph Playground:** Enabled for @mem0.ai users
- **Notifications:** Added email alerts to organization owners when new members join
- **Memory Export:** Added date support for filtering memory exports
**Improvements:**
- **Performance:**
- Optimized graph for better performance
- Optimized database calls in ADD method
- **Analytics:** Added flagging of paid users in Posthog
- **CI/CD:** Improved CI pipeline and fixed lint issues
</Update>
<Update label="2025-04-10" description="">
**New Features:**
- **Notifications:** Implemented email notifications for organization owners when new members join
**Improvements:**
- **CI/CD:** Fixed Dockerfile for CI tests
</Update>
<Update label="2025-04-09" description="">
**Improvements:**
- **Integrations:** Updated chat model for Together Qwen
- **Platform:** Removed older platforms
- **Bug Fixes:** Fixed FILTER_MAPPING
</Update>
<Update label="2025-04-03" description="">
**New Features:**
- **Memory:** Added implicit memory capabilities
- **API:** Improved implicit lambda and get_all v2 functionality
</Update>
<Update label="2025-04-02" description="">
**New Features:**
- **Integrations:** Added Clay integration
**Improvements:**
- **Integrations:** Removed deepseek coder from Together
- **API:** Added custom instructions for add v2
</Update>
<Update label="2025-03-31" description="">
**Security:**
- **Validation:** Added key validation in messages
</Update>
<Update label="2025-03-28" description="">
- **Updated Playground Prompt**
- **Send Email on User Addition to Org/Proj**
- **Fix Search Entity**
</Update>
<Update label="2025-03-19" description="">
- **General Stability & Performance Improvements**
</Update>
</Tab>
<Tab title="Vercel AI SDK">
<Update label="2025-08-05" description="v2.0.0">
**New Features:**
- **Vercel AI SDK:** Migration to AI SDK V5.
</Update>
<Update label="2025-06-15" description="v1.0.6">
**New Features:**
- **Vercel AI SDK:** Added param `filter_memories`.
</Update>
<Update label="2025-05-23" description="v1.0.5">
**New Features:**
- **Vercel AI SDK:** Added support for Google provider.
+1 -1
View File
@@ -4,7 +4,7 @@ icon: "gear"
iconType: "solid"
---
<Snippet file="paper-release.mdx" />
<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.
@@ -1,8 +1,8 @@
---
title: Gemini
title: Google AI
---
To use Gemini embedding models, set the `GOOGLE_API_KEY` environment variables. You can obtain the Gemini API key from [here](https://aistudio.google.com/app/apikey).
To use Google AI embedding models, set the `GOOGLE_API_KEY` environment variables. You can obtain the Gemini API key from [here](https://aistudio.google.com/app/apikey).
### Usage
@@ -39,5 +39,5 @@ Here are the parameters available for configuring Gemini embedder:
| Parameter | Description | Default Value |
| --- | --- | --- |
| `model` | The name of the embedding model to use | `models/text-embedding-004` |
| `embedding_dims` | Dimensions of the embedding model | `768` |
| `api_key` | The Gemini API key | `None` |
| `embedding_dims` | Dimensions of the embedding model (output_dimensionality will be considered as embedding_dims, so please set embedding_dims accordingly) | `768` |
| `api_key` | The Google API key | `None` |
+2 -2
View File
@@ -4,7 +4,7 @@ icon: "info"
iconType: "solid"
---
<Snippet file="paper-release.mdx" />
<Snippet file="blank-notif.mdx" />
Mem0 offers support for various embedding models, allowing users to choose the one that best suits their needs.
@@ -21,7 +21,7 @@ See the list of supported embedders below.
<Card title="Azure OpenAI" href="/components/embedders/models/azure_openai"></Card>
<Card title="Ollama" href="/components/embedders/models/ollama"></Card>
<Card title="Hugging Face" href="/components/embedders/models/huggingface"></Card>
<Card title="Gemini" href="/components/embedders/models/gemini"></Card>
<Card title="Google AI" href="/components/embedders/models/google_AI"></Card>
<Card title="Vertex AI" href="/components/embedders/models/vertexai"></Card>
<Card title="Together" href="/components/embedders/models/together"></Card>
<Card title="LM Studio" href="/components/embedders/models/lmstudio"></Card>
+4 -1
View File
@@ -4,7 +4,7 @@ icon: "gear"
iconType: "solid"
---
<Snippet file="paper-release.mdx" />
<Snippet file="blank-notif.mdx" />
## How to define configurations?
@@ -58,6 +58,7 @@ config = {
m = Memory.from_config(config)
m.add("Your text here", user_id="user", metadata={"category": "example"})
```
```typescript TypeScript
@@ -76,6 +77,7 @@ const config = {
const memory = new Memory(config);
await memory.add("Your text here", { userId: "user123", metadata: { category: "example" } });
```
</CodeGroup>
## Why is Config Needed?
@@ -117,6 +119,7 @@ Here's a comprehensive list of all parameters that can be used across different
| `seed` | Seed for deterministic sampling | Sarvam |
| `stop` | Stop sequences (max 4) | Sarvam |
| `lmstudio_base_url` | Base URL for LM Studio API | LM Studio |
| `response_callback` | LLM response callback function | OpenAI |
</Tab>
<Tab title="TypeScript">
| Parameter | Description | Provider |
+2 -2
View File
@@ -2,9 +2,9 @@
title: Anthropic
---
<Snippet file="paper-release.mdx" />
<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).
To use Anthropic's models, please set the `ANTHROPIC_API_KEY` which you find on their [Account Settings Page](https://console.anthropic.com/account/keys).
## Usage
+1 -1
View File
@@ -2,7 +2,7 @@
title: AWS Bedrock
---
<Snippet file="paper-release.mdx" />
<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).
+1 -1
View File
@@ -2,7 +2,7 @@
title: Azure OpenAI
---
<Snippet file="paper-release.mdx" />
<Snippet file="blank-notif.mdx" />
<Note> Mem0 Now Supports Azure OpenAI Models in TypeScript SDK </Note>
+1 -1
View File
@@ -2,7 +2,7 @@
title: DeepSeek
---
<Snippet file="paper-release.mdx" />
<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").
-41
View File
@@ -1,41 +0,0 @@
---
title: Gemini
---
<Snippet file="paper-release.mdx" />
To use Gemini model, you have to set the `GEMINI_API_KEY` environment variable. You can obtain the Gemini API key from the [Google AI Studio](https://aistudio.google.com/app/apikey)
## Usage
```python
import os
from mem0 import Memory
os.environ["OPENAI_API_KEY"] = "your-api-key" # used for embedding model
os.environ["GEMINI_API_KEY"] = "your-api-key"
config = {
"llm": {
"provider": "gemini",
"config": {
"model": "gemini-1.5-flash-latest",
"temperature": 0.2,
"max_tokens": 2000,
}
}
}
m = Memory.from_config(config)
messages = [
{"role": "user", "content": "I'm planning to watch a movie tonight. Any recommendations?"},
{"role": "assistant", "content": "How about a thriller movies? They can be quite engaging."},
{"role": "user", "content": "I’m not a big fan of thriller movies but I love sci-fi movies."},
{"role": "assistant", "content": "Got it! I'll avoid thriller recommendations and suggest sci-fi movies in the future."}
]
m.add(messages, user_id="alice", metadata={"category": "movies"})
```
## Config
All available parameters for the `Gemini` config are present in [Master List of All Params in Config](../config).
+46 -11
View File
@@ -2,40 +2,75 @@
title: Google AI
---
<Snippet file="paper-release.mdx" />
<Snippet file="blank-notif.mdx" />
To use Google AI model, you have to set the `GOOGLE_API_KEY` environment variable. You can obtain the Google API key from the [Google Maker Suite](https://makersuite.google.com/app/apikey)
To use the Gemini model, set the `GOOGLE_API_KEY` environment variable. You can obtain the Google/Gemini API key from [Google AI Studio](https://aistudio.google.com/app/apikey).
> **Note:** As of the latest release, Mem0 uses the new `google.genai` SDK instead of the deprecated `google.generativeai`. All message formatting and model interaction now use the updated `types` module from `google.genai`.
> **Note:** Some Gemini models are being deprecated and will retire soon. It is recommended to migrate to the latest stable models like `"gemini-2.0-flash-001"` or `"gemini-2.0-flash-lite-001"` to ensure ongoing support and improvements.
## Usage
```python
<CodeGroup>
```python Python
import os
from mem0 import Memory
os.environ["OPENAI_API_KEY"] = "your-api-key" # used for embedding model
os.environ["GEMINI_API_KEY"] = "your-api-key"
os.environ["OPENAI_API_KEY"] = "your-openai-api-key" # Used for embedding model
os.environ["GOOGLE_API_KEY"] = "your-gemini-api-key"
config = {
"llm": {
"provider": "litellm",
"provider": "gemini",
"config": {
"model": "gemini/gemini-pro",
"model": "gemini-2.0-flash-001",
"temperature": 0.2,
"max_tokens": 2000,
"top_p": 1.0
}
}
}
m = Memory.from_config(config)
messages = [
{"role": "user", "content": "I'm planning to watch a movie tonight. Any recommendations?"},
{"role": "assistant", "content": "How about 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": "assistant", "content": "How about thriller movies? They can be quite engaging."},
{"role": "user", "content": "I’m not a big fan of thrillers, but I love sci-fi movies."},
{"role": "assistant", "content": "Got it! I'll avoid thrillers and suggest sci-fi movies instead."}
]
m.add(messages, user_id="alice", metadata={"category": "movies"})
```
```typescript TypeScript
import { Memory } from "mem0ai/oss";
const config = {
llm: {
// You can also use "google" as provider ( for backward compatibility )
provider: "gemini",
config: {
model: "gemini-2.0-flash-001",
temperature: 0.1
}
}
}
const memory = new Memory(config);
const messages = [
{ role: "user", content: "I'm planning to watch a movie tonight. Any recommendations?" },
{ role: "assistant", content: "How about thriller movies? They can be quite engaging." },
{ role: "user", content: "I’m not a big fan of thrillers, but I love sci-fi movies." },
{ role: "assistant", content: "Got it! I'll avoid thrillers and suggest sci-fi movies instead." }
]
await memory.add(messages, { userId: "alice", metadata: { category: "movies" } });
```
</CodeGroup>
## Config
All available parameters for the `litellm` config are present in [Master List of All Params in Config](../config).
All available parameters for the `Gemini` config are present in [Master List of All Params in Config](../config).
+1 -1
View File
@@ -2,7 +2,7 @@
title: Groq
---
<Snippet file="paper-release.mdx" />
<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.
+1 -1
View File
@@ -2,7 +2,7 @@
title: LangChain
---
<Snippet file="paper-release.mdx" />
<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.
+1 -1
View File
@@ -1,4 +1,4 @@
<Snippet file="paper-release.mdx" />
<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.
+2 -1
View File
@@ -2,7 +2,7 @@
title: LM Studio
---
<Snippet file="paper-release.mdx" />
<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.
@@ -23,6 +23,7 @@ config = {
"temperature": 0.2,
"max_tokens": 2000,
"lmstudio_base_url": "http://localhost:1234/v1", # default LM Studio API URL
"lmstudio_response_format": {"type": "json_schema", "json_schema": {"type": "object", "schema": {}}},
}
}
}
+1 -1
View File
@@ -2,7 +2,7 @@
title: Mistral AI
---
<Snippet file="paper-release.mdx" />
<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.
+1 -1
View File
@@ -1,4 +1,4 @@
<Snippet file="paper-release.mdx" />
<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.
+3 -1
View File
@@ -2,10 +2,12 @@
title: OpenAI
---
<Snippet file="paper-release.mdx" />
<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`
## Usage
<CodeGroup>
+1 -1
View File
@@ -2,7 +2,7 @@
title: Sarvam AI
---
<Snippet file="paper-release.mdx" />
<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.
+1 -1
View File
@@ -1,4 +1,4 @@
<Snippet file="paper-release.mdx" />
<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).
+109
View File
@@ -0,0 +1,109 @@
---
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
1. **Install vLLM**:
```bash
pip install vllm
```
2. **Start vLLM server**:
```bash
# For testing with a small model
vllm serve microsoft/DialoGPT-medium --port 8000
# For production with a larger model (requires GPU)
vllm serve Qwen/Qwen2.5-32B-Instruct --port 8000
```
## Usage
```python
import os
from mem0 import Memory
os.environ["OPENAI_API_KEY"] = "your-api-key" # used for embedding model
config = {
"llm": {
"provider": "vllm",
"config": {
"model": "Qwen/Qwen2.5-32B-Instruct",
"vllm_base_url": "http://localhost:8000/v1",
"temperature": 0.1,
"max_tokens": 2000,
}
}
}
m = Memory.from_config(config)
messages = [
{"role": "user", "content": "I'm planning to watch a movie tonight. Any recommendations?"},
{"role": "assistant", "content": "How about thriller movies? They can be quite engaging."},
{"role": "user", "content": "I'm not a big fan of thrillers, but I love sci-fi movies."},
{"role": "assistant", "content": "Got it! I'll avoid thrillers and suggest sci-fi movies instead."}
]
m.add(messages, user_id="alice", metadata={"category": "movies"})
```
## Configuration Parameters
| Parameter | Description | Default | Environment Variable |
| --------------- | --------------------------------- | ----------------------------- | -------------------- |
| `model` | Model name running on vLLM server | `"Qwen/Qwen2.5-32B-Instruct"` | - |
| `vllm_base_url` | vLLM server URL | `"http://localhost:8000/v1"` | `VLLM_BASE_URL` |
| `api_key` | API key (dummy for local) | `"vllm-api-key"` | `VLLM_API_KEY` |
| `temperature` | Sampling temperature | `0.1` | - |
| `max_tokens` | Maximum tokens to generate | `2000` | - |
## Environment Variables
You can set these environment variables instead of specifying them in config:
```bash
export VLLM_BASE_URL="http://localhost:8000/v1"
export VLLM_API_KEY="your-vllm-api-key"
export OPENAI_API_KEY="your-openai-api-key" # for embeddings
```
## Benefits
- **High Performance**: 2-24x faster inference than standard implementations
- **Memory Efficient**: Optimized memory usage with PagedAttention
- **Local Deployment**: Keep your data private and reduce API costs
- **Easy Integration**: Drop-in replacement for other LLM providers
- **Flexible**: Works with any model supported by vLLM
## Troubleshooting
1. **Server not responding**: Make sure vLLM server is running
```bash
curl http://localhost:8000/health
```
2. **404 errors**: Ensure correct base URL format
```python
"vllm_base_url": "http://localhost:8000/v1" # Note the /v1
```
3. **Model not found**: Check model name matches server
4. **Out of memory**: Try smaller models or reduce `max_model_len`
```bash
vllm serve Qwen/Qwen2.5-32B-Instruct --max-model-len 4096
```
## Config
All available parameters for the `vllm` config are present in [Master List of All Params in Config](../config).
+1 -1
View File
@@ -2,7 +2,7 @@
title: xAI
---
<Snippet file="paper-release.mdx" />
<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.
+4 -3
View File
@@ -4,7 +4,7 @@ icon: "info"
iconType: "solid"
---
<Snippet file="paper-release.mdx" />
<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.
@@ -14,7 +14,9 @@ To use a llm, you must provide a configuration to customize its usage. If no con
For a comprehensive list of available parameters for llm configuration, please refer to [Config](./config).
To view all supported llms, visit the [Supported LLMs](./models).
## Supported LLMs
See the list of supported LLMs below.
<Note>
All LLMs are supported in Python. The following LLMs are also supported in TypeScript: **OpenAI**, **Anthropic**, and **Groq**.
@@ -31,7 +33,6 @@ To view all supported llms, visit the [Supported LLMs](./models).
<Card title="Mistral AI" href="/components/llms/models/mistral_ai" />
<Card title="Google AI" href="/components/llms/models/google_ai" />
<Card title="AWS bedrock" href="/components/llms/models/aws_bedrock" />
<Card title="Gemini" href="/components/llms/models/gemini" />
<Card title="DeepSeek" href="/components/llms/models/deepseek" />
<Card title="xAI" href="/components/llms/models/xAI" />
<Card title="Sarvam AI" href="/components/llms/models/sarvam" />
+1 -1
View File
@@ -4,7 +4,7 @@ icon: "gear"
iconType: "solid"
---
<Snippet file="paper-release.mdx" />
<Snippet file="blank-notif.mdx" />
## How to define configurations?
+67
View File
@@ -0,0 +1,67 @@
---
title: Baidu VectorDB (Mochow)
---
[Baidu VectorDB](https://cloud.baidu.com/doc/VDB/index.html) is an enterprise-level distributed vector database service developed by Baidu Intelligent Cloud. It is powered by Baidu's proprietary "Mochow" vector database kernel, providing high performance, availability, and security for vector search.
### Usage
```python
import os
from mem0 import Memory
config = {
"vector_store": {
"provider": "baidu",
"config": {
"endpoint": "http://your-mochow-endpoint:8287",
"account": "root",
"api_key": "your-api-key",
"database_name": "mem0",
"table_name": "mem0_table",
"embedding_model_dims": 1536,
"metric_type": "COSINE"
}
}
}
m = Memory.from_config(config)
messages = [
{"role": "user", "content": "I'm planning to watch a movie tonight. Any recommendations?"},
{"role": "assistant", "content": "How about a thriller movie? They can be quite engaging."},
{"role": "user", "content": "I'm not a big fan of thriller movies but I love sci-fi movies."},
{"role": "assistant", "content": "Got it! I'll avoid thriller recommendations and suggest sci-fi movies in the future."}
]
m.add(messages, user_id="alice", metadata={"category": "movies"})
```
### Config
Here are the available parameters for the `mochow` config:
| Parameter | Description | Default Value |
| --- | --- | --- |
| `endpoint` | Endpoint URL for your Baidu VectorDB instance | Required |
| `account` | Baidu VectorDB account name | `root` |
| `api_key` | API key for accessing Baidu VectorDB | Required |
| `database_name` | Name of the database | `mem0` |
| `table_name` | Name of the table | `mem0_table` |
| `embedding_model_dims` | Dimensions of the embedding model | `1536` |
| `metric_type` | Distance metric for similarity search | `L2` |
### Distance Metrics
The following distance metrics are supported:
- `L2`: Euclidean distance (default)
- `IP`: Inner product
- `COSINE`: Cosine similarity
### Index Configuration
The vector index is automatically configured with the following HNSW parameters:
- `m`: 16 (number of connections per element)
- `efconstruction`: 200 (size of the dynamic candidate list)
- `auto_build`: true (automatically build index)
- `auto_build_index_policy`: Incremental build with 10000 rows increment
+2
View File
@@ -14,6 +14,7 @@ config = {
"embedding_model_dims": "123",
"url": "127.0.0.1",
"token": "8e4b8ca8cf2c67",
"db_name": "my_database",
}
}
}
@@ -39,3 +40,4 @@ Here's the parameters available for configuring Milvus Database:
| `collection_name` | The name of the collection | `mem0` |
| `embedding_model_dims` | Dimensions of the embedding model | `1536` |
| `metric_type` | Metric type for similarity search | `L2` |
| `db_name` | Name of the database | `""` |
+3 -7
View File
@@ -16,8 +16,7 @@ config = {
"config": {
"db_name": "mem0-db",
"collection_name": "mem0-collection",
"user": "my-user",
"password": "my-password",
"mongo_uri":"mongodb://username:password@localhost:27017"
}
}
}
@@ -41,9 +40,6 @@ Here are the parameters available for configuring MongoDB:
| db_name | Name of the MongoDB database | `"mem0_db"` |
| collection_name | Name of the MongoDB collection | `"mem0_collection"` |
| embedding_model_dims | Dimensions of the embedding vectors | `1536` |
| user | MongoDB user for authentication | `None` |
| password | Password for the MongoDB user | `None` |
| host | MongoDB host | `"localhost"` |
| port | MongoDB port | `27017` |
| mongo_uri | The mongo URI connection string | mongodb://username:password@localhost:27017 |
> **Note**: `user` and `password` must either be provided together or omitted together.
> **Note**: If Mongo_uri is not provided it will default to mongodb://username:password@localhost:27017.
+10 -2
View File
@@ -36,7 +36,7 @@ Here's the parameters available for configuring pgvector:
| Parameter | Description | Default Value |
| --- | --- | --- |
| `dbname` | The name of the | `postgres` |
| `dbname` | The name of the database | `postgres` |
| `collection_name` | The name of the collection | `mem0` |
| `embedding_model_dims` | Dimensions of the embedding model | `1536` |
| `user` | User name to connect to the database | `None` |
@@ -44,4 +44,12 @@ Here's the parameters available for configuring pgvector:
| `host` | The host where the Postgres server is running | `None` |
| `port` | The port where the Postgres server is running | `None` |
| `diskann` | Whether to use diskann for vector similarity search (requires pgvectorscale) | `True` |
| `hnsw` | Whether to use hnsw for vector similarity search | `False` |
| `hnsw` | Whether to use hnsw for vector similarity search | `False` |
| `sslmode` | SSL mode for PostgreSQL connection (e.g., 'require', 'prefer', 'disable') | `None` |
| `connection_string` | PostgreSQL connection string (overrides individual connection parameters) | `None` |
| `connection_pool` | psycopg2 connection pool object (overrides connection string and individual parameters) | `None` |
**Note**: The connection parameters have the following priority:
1. `connection_pool` (highest priority)
2. `connection_string`
3. Individual connection parameters (`user`, `password`, `host`, `port`, `sslmode`)
@@ -1,5 +1,7 @@
[Pinecone](https://www.pinecone.io/) is a fully managed vector database designed for machine learning applications, offering high performance vector search with low latency at scale. It's particularly well-suited for semantic search, recommendation systems, and other AI-powered applications.
> **New**: Pinecone integration now supports custom namespaces! Use the `namespace` parameter to logically separate data within the same index. This is especially useful for multi-tenant or multi-user applications.
> **Note**: Before configuring Pinecone, you need to select an embedding model (e.g., OpenAI, Cohere, or custom models) and ensure the `embedding_model_dims` in your config matches your chosen model's dimensions. For example, OpenAI's text-embedding-3-small uses 1536 dimensions.
### Usage
@@ -18,6 +20,7 @@ config = {
"config": {
"collection_name": "testing",
"embedding_model_dims": 1536, # Matches OpenAI's text-embedding-3-small
"namespace": "my-namespace", # Optional: specify a namespace for multi-tenancy
"serverless_config": {
"cloud": "aws", # Choose between 'aws' or 'gcp' or 'azure'
"region": "us-east-1"
@@ -53,6 +56,7 @@ Here are the parameters available for configuring Pinecone:
| `hybrid_search` | Whether to enable hybrid search | `False` |
| `metric` | Distance metric for vector similarity | `"cosine"` |
| `batch_size` | Batch size for operations | `100` |
| `namespace` | Namespace for the collection, useful for multi-tenancy. | `None` |
> **Important**: You must choose either `serverless_config` or `pod_config` for your deployment, but not both.
@@ -64,6 +68,7 @@ config = {
"config": {
"collection_name": "memory_index",
"embedding_model_dims": 1536, # For OpenAI's text-embedding-3-small
"namespace": "my-namespace", # Optional: custom namespace
"serverless_config": {
"cloud": "aws", # or "gcp" or "azure"
"region": "us-east-1" # Choose appropriate region
@@ -81,6 +86,7 @@ config = {
"config": {
"collection_name": "memory_index",
"embedding_model_dims": 1536, # For OpenAI's text-embedding-ada-002
"namespace": "my-namespace", # Optional: custom namespace
"pod_config": {
"environment": "gcp-starter",
"replicas": 1,
+1 -1
View File
@@ -12,7 +12,7 @@ To use Google Cloud Vertex AI Vector Search with `mem0`, you need to configure t
import os
from mem0 import Memory
os.environ["GEMINI_API_KEY"] = = "sk-xx"
os.environ["GOOGLE_API_KEY"] = "sk-xx"
config = {
"vector_store": {
+1 -1
View File
@@ -4,7 +4,7 @@ icon: "info"
iconType: "solid"
---
<Snippet file="paper-release.mdx" />
<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.
+10 -5
View File
@@ -3,7 +3,7 @@ title: Development
icon: "code"
---
<Snippet file="paper-release.mdx" />
<Snippet file="blank-notif.mdx" />
# Development Contributions
@@ -31,13 +31,18 @@ For detailed guidance on pull requests, refer to [GitHub's documentation](https:
We use `hatch` as our package manager. Install it by following the [official instructions](https://hatch.pypa.io/latest/install/).
⚠️ **Do NOT use `pip` or `conda` for dependency management.** Instead, run:
⚠️ **Do NOT use `pip` or `conda` for dependency management.** Instead, follow these steps in order:
```bash
make install_all
# 1. Install base dependencies
make install
# Activate virtual environment
hatch shell
# 2. Activate virtual environment (this will install deps.)
hatch shell (for default env)
hatch -e dev_py_3_11 shell (for dev_py_3_11) (differences are mentioned in pyproject.toml)
# 3. Install all optional dependencies
make install_all
```
---
+1 -1
View File
@@ -3,7 +3,7 @@ title: Documentation
icon: "book"
---
<Snippet file="paper-release.mdx" />
<Snippet file="blank-notif.mdx" />
# Documentation Contributions
+1 -1
View File
@@ -5,7 +5,7 @@ icon: "gear"
iconType: "solid"
---
<Snippet file="paper-release.mdx" />
<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.
@@ -0,0 +1,154 @@
---
title: Add Memory
description: Add memory into the Mem0 platform by storing user-assistant interactions and facts for later retrieval.
icon: "plus"
iconType: "solid"
---
<Snippet file="blank-notif.mdx" />
## Overview
The `add` operation is how you store memory into Mem0. Whether you're working with a chatbot, a voice assistant, or a multi-agent system, this is the entry point to create long-term memory.
Memories typically come from a **user-assistant interaction** and Mem0 handles the extraction, transformation, and storage for you.
Mem0 offers two implementation flows:
- **Mem0 Platform** (Managed, scalable, with dashboard + API)
- **Mem0 Open Source** (Lightweight, fully local, flexible SDKs)
Each supports the same core memory operations, but with slightly different setup. Below, we walk through examples for both.
## Architecture
<Frame caption="Architecture diagram illustrating the process of adding memories.">
<img src="../../images/add_architecture.png" />
</Frame>
When you call `add`, Mem0 performs the following steps under the hood:
1. **Information Extraction**
The input messages are passed through an LLM that extracts key facts, decisions, preferences, or events worth remembering.
2. **Conflict Resolution**
Mem0 compares the new memory against existing ones to detect duplication or contradiction and handles updates accordingly.
3. **Memory Storage**
The result is stored in a vector database (for semantic search) and optionally in a graph structure (for relationship mapping).
You don’t need to handle any of this manually, Mem0 takes care of it with a single API call or SDK method.
---
## Example: Mem0 Platform
<CodeGroup>
```python Python
from mem0 import MemoryClient
client = MemoryClient(api_key="your-api-key")
messages = [
{"role": "user", "content": "I'm planning a trip to Tokyo next month."},
{"role": "assistant", "content": "Great! I’ll remember that for future suggestions."}
]
client.add(
messages=messages,
user_id="alice",
version="v2"
)
```
```javascript JavaScript
import { MemoryClient } from "mem0ai";
const client = new MemoryClient({apiKey: "your-api-key"});
const messages = [
{ role: "user", content: "I'm planning a trip to Tokyo next month." },
{ role: "assistant", content: "Great! I’ll remember that for future suggestions." }
];
await client.add({
messages,
user_id: "alice",
version: "v2"
});
```
</CodeGroup>
---
## Example: Mem0 Open Source
<CodeGroup>
```python Python
import os
from mem0 import Memory
os.environ["OPENAI_API_KEY"] = "your-api-key"
m = Memory()
messages = [
{"role": "user", "content": "I'm planning to watch a movie tonight. Any recommendations?"},
{"role": "assistant", "content": "How about a thriller movies? They can be quite engaging."},
{"role": "user", "content": "I'm not a big fan of thriller movies but I love sci-fi movies."},
{"role": "assistant", "content": "Got it! I'll avoid thriller recommendations and suggest sci-fi movies in the future."}
]
# Store inferred memories (default behavior)
result = m.add(messages, user_id="alice", metadata={"category": "movie_recommendations"})
# Optionally store raw messages without inference
result = m.add(messages, user_id="alice", metadata={"category": "movie_recommendations"}, infer=False)
```
```javascript JavaScript
import { Memory } from 'mem0ai/oss';
const memory = new Memory();
const messages = [
{
role: "user",
content: "I like to drink coffee in the morning and go for a walk"
}
];
const result = memory.add(messages, {
userId: "alice",
metadata: { category: "preferences" }
});
```
</CodeGroup>
---
## When Should You Add Memory?
Add memory whenever your agent learns something useful:
- A new user preference is shared
- A decision or suggestion is made
- A goal or task is completed
- A new entity is introduced
- A user gives feedback or clarification
Storing this context allows the agent to reason better in future interactions.
### More Details
For full list of supported fields, required formats, and advanced options, see the
[Add Memory API Reference](/api-reference/memory/add-memories).
---
## Need help?
If you have any questions, please feel free to reach out to us using one of the following methods:
<Snippet file="get-help.mdx"/>
@@ -0,0 +1,143 @@
---
title: Delete Memory
description: Remove memories from Mem0 either individually, in bulk, or via filters.
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:
1. **Delete a Single Memory**: Using a specific memory ID
2. **Batch Delete**: Delete multiple known memory IDs (up to 1000)
3. **Filtered Delete**: Delete memories matching a filter (e.g., `user_id`, `metadata`, `run_id`)
This page walks through code example for each method.
## Use Cases
- Forget a user’s past preferences by request
- Remove outdated or incorrect memory entries
- Clean up memory after session expiration
- Comply with data deletion requests (e.g., GDPR)
---
## 1. Delete a Single Memory by ID
<CodeGroup>
```python Python
from mem0 import MemoryClient
client = MemoryClient(api_key="your-api-key")
memory_id = "your_memory_id"
client.delete(memory_id=memory_id)
```
```javascript JavaScript
import MemoryClient from 'mem0ai';
const client = new MemoryClient({ apiKey: "your-api-key" });
client.delete("your_memory_id")
.then(result => console.log(result))
.catch(error => console.error(error));
```
</CodeGroup>
---
## 2. Batch Delete Multiple Memories
<CodeGroup>
```python Python
from mem0 import MemoryClient
client = MemoryClient(api_key="your-api-key")
delete_memories = [
{"memory_id": "id1"},
{"memory_id": "id2"}
]
response = client.batch_delete(delete_memories)
print(response)
```
```javascript JavaScript
import MemoryClient from 'mem0ai';
const client = new MemoryClient({ apiKey: "your-api-key" });
const deleteMemories = [
{ memory_id: "id1" },
{ memory_id: "id2" }
];
client.batchDelete(deleteMemories)
.then(response => console.log('Batch delete response:', response))
.catch(error => console.error(error));
```
</CodeGroup>
---
## 3. Delete Memories by Filter (e.g., user_id)
<CodeGroup>
```python Python
from mem0 import MemoryClient
client = MemoryClient(api_key="your-api-key")
# Delete all memories for a specific user
client.delete_all(user_id="alice")
```
```javascript JavaScript
import MemoryClient from 'mem0ai';
const client = new MemoryClient({ apiKey: "your-api-key" });
client.deleteAll({ user_id: "alice" })
.then(result => console.log(result))
.catch(error => console.error(error));
```
</CodeGroup>
You can also filter by other parameters such as:
- `agent_id`
- `run_id`
- `metadata` (as JSON string)
---
## Key Differences
| Method | Use When | IDs Needed | Filters |
|----------------------|-------------------------------------------|------------|----------|
| `delete(memory_id)` | You know exactly which memory to remove | ✔ | ✘ |
| `batch_delete([...])`| You have a known list of memory IDs | ✔ | ✘ |
| `delete_all(...)` | You want to delete by user/agent/run/etc | ✘ | ✔ |
### More Details
For request/response schema and additional filtering options, see:
- [Delete Memory API Reference](/api-reference/memory/delete-memory)
- [Batch Delete API Reference](/api-reference/memory/batch-delete)
- [Delete Memories by Filter Reference](/api-reference/memory/delete-memories)
You’ve now seen how to add, search, update, and delete memories in Mem0.
---
## Need help?
If you have any questions, please feel free to reach out to us using one of the following methods:
<Snippet file="get-help.mdx"/>
@@ -0,0 +1,126 @@
---
title: Search Memory
description: Retrieve relevant memories from Mem0 using powerful semantic and filtered search capabilities.
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.
Mem0 supports:
- Semantic similarity search
- Metadata filtering (with advanced logic)
- Reranking and thresholds
- Cross-agent, multi-session context resolution
This applies to both:
- **Mem0 Platform** (hosted API with full-scale features)
- **Mem0 Open Source** (local-first with LLM inference and local vector DB)
## Architecture
<Frame caption="Architecture diagram illustrating the memory search process.">
<img src="../../images/search_architecture.png" />
</Frame>
The search flow follows these steps:
1. **Query Processing**
An LLM refines and optimizes your natural language query.
2. **Vector Search**
Semantic embeddings are used to find the most relevant memories using cosine similarity.
3. **Filtering & Ranking**
Logical and comparison-based filters are applied. Memories are scored, filtered, and optionally reranked.
4. **Results Delivery**
Relevant memories are returned with associated metadata and timestamps.
---
## Example: Mem0 Platform
<CodeGroup>
```python Python
from mem0 import MemoryClient
client = MemoryClient(api_key="your-api-key")
query = "What do you know about me?"
filters = {
"OR": [
{"user_id": "alice"},
{"agent_id": {"in": ["travel-assistant", "customer-support"]}}
]
}
results = client.search(query, version="v2", filters=filters)
```
```javascript JavaScript
import { MemoryClient } from "mem0ai";
const client = new MemoryClient({apiKey: "your-api-key"});
const query = "I'm craving some pizza. Any recommendations?";
const filters = {
AND: [
{ user_id: "alice" }
]
};
const results = await client.search(query, {
version: "v2",
filters
});
```
</CodeGroup>
---
## Example: Mem0 Open Source
<CodeGroup>
```python Python
from mem0 import Memory
m = Memory()
related_memories = m.search("Should I drink coffee or tea?", user_id="alice")
```
```javascript JavaScript
import { Memory } from 'mem0ai/oss';
const memory = new Memory();
const relatedMemories = memory.search("Should I drink coffee or tea?", { userId: "alice" });
```
</CodeGroup>
---
## Tips for Better Search
- Use descriptive natural queries (Mem0 can interpret intent)
- Apply filters for scoped, faster lookup
- Use `version: "v2"` for enhanced results
- Consider wildcard filters (e.g., `run_id: "*"`) for broader matches
- Tune with `top_k`, `threshold`, or `rerank` if needed
### More Details
For the full list of filter logic, comparison operators, and optional search parameters, see the
[Search Memory API Reference](/api-reference/memory/v2-search-memories).
---
## Need help?
If you have any questions, please feel free to reach out to us using one of the following methods:
<Snippet file="get-help.mdx"/>
@@ -0,0 +1,119 @@
---
title: Update Memory
description: Modify an existing memory by updating its content or metadata.
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.
Mem0 supports both:
- **Single Memory Update** for one specific memory using its ID
- **Batch Update** for updating many memories at once (up to 1000)
This guide includes usage for both single update and batch update of memories through **Mem0 Platform**
## Use Cases
- Refine a vague or incorrect memory after a correction
- Add or edit memory with new metadata (e.g., categories, tags)
- Evolve factual knowledge as the user’s profile changes
- A user profile evolves: “I love spicy food” → later says “Actually, I can’t handle spicy food.”
Updating memory ensures your agents remain accurate, adaptive, and personalized.
---
## Update Memory
<CodeGroup>
```python Python
from mem0 import MemoryClient
client = MemoryClient(api_key="your-api-key")
memory_id = "your_memory_id"
client.update(
memory_id=memory_id,
text="Updated memory content about the user",
metadata={"category": "profile-update"}
)
```
```javascript JavaScript
import MemoryClient from 'mem0ai';
const client = new MemoryClient({ apiKey: "your-api-key" });
const memory_id = "your_memory_id";
client.update(memory_id, {
text: "Updated memory content about the user",
metadata: { category: "profile-update" }
})
.then(result => console.log(result))
.catch(error => console.error(error));
```
</CodeGroup>
---
## Batch Update
Update up to 1000 memories in one call.
<CodeGroup>
```python Python
from mem0 import MemoryClient
client = MemoryClient(api_key="your-api-key")
update_memories = [
{"memory_id": "id1", "text": "Watches football"},
{"memory_id": "id2", "text": "Likes to travel"}
]
response = client.batch_update(update_memories)
print(response)
```
```javascript JavaScript
import MemoryClient from 'mem0ai';
const client = new MemoryClient({ apiKey: "your-api-key" });
const updateMemories = [
{ memoryId: "id1", text: "Watches football" },
{ memoryId: "id2", text: "Likes to travel" }
];
client.batchUpdate(updateMemories)
.then(response => console.log('Batch update response:', response))
.catch(error => console.error(error));
```
</CodeGroup>
---
## Tips
- You can update both `text` and `metadata` in the same call.
- Use `batchUpdate` when you're applying similar corrections at scale.
- If memory is marked `immutable`, it must first be deleted and re-added.
- Combine this with feedback mechanisms (e.g., user thumbs-up/down) to self-improve memory.
### More Details
Refer to the full [Update Memory API Reference](/api-reference/memory/update-memory) and [Batch Update Reference](/api-reference/memory/batch-update) for schema and advanced fields.
---
## Need help?
If you have any questions, please feel free to reach out to us using one of the following methods:
<Snippet file="get-help.mdx"/>
+1 -1
View File
@@ -5,7 +5,7 @@ icon: "memory"
iconType: "solid"
---
<Snippet file="paper-release.mdx" />
<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.
+45 -53
View File
@@ -19,10 +19,10 @@
"tab": "Documentation",
"groups": [
{
"group": "Get Started",
"group": "Getting Started",
"icon": "rocket",
"pages": [
"overview",
"what-is-mem0",
"quickstart",
"faqs"
]
@@ -32,7 +32,16 @@
"icon": "brain",
"pages": [
"core-concepts/memory-types",
"core-concepts/memory-operations"
{
"group": "Memory Operations",
"icon": "gear",
"pages": [
"core-concepts/memory-operations/add",
"core-concepts/memory-operations/search",
"core-concepts/memory-operations/update",
"core-concepts/memory-operations/delete"
]
}
]
},
{
@@ -46,21 +55,21 @@
"icon": "star",
"pages": [
"platform/features/platform-overview",
"platform/features/contextual-add",
"platform/features/async-client",
"platform/features/advanced-retrieval",
"platform/features/criteria-retrieval",
"platform/features/contextual-add",
"platform/features/multimodal-support",
"platform/features/timestamp",
"platform/features/selective-memory",
"platform/features/custom-categories",
"platform/features/custom-instructions",
"platform/features/direct-import",
"platform/features/async-client",
"platform/features/memory-export",
"platform/features/timestamp",
"platform/features/expiration-date",
"platform/features/webhooks",
"platform/features/graph-memory",
"platform/features/feedback-mechanism",
"platform/features/expiration-date"
"platform/features/group-chat"
]
}
]
@@ -69,13 +78,14 @@
"group": "Open Source",
"icon": "code-branch",
"pages": [
"open-source/quickstart",
"open-source/overview",
"open-source/python-quickstart",
"open-source/node-quickstart",
{
"group": "Features",
"icon": "wrench",
"icon": "star",
"pages": [
"open-source/features/overview",
"open-source/features/async-memory",
"open-source/features/openai_compatibility",
"open-source/features/custom-fact-extraction-prompt",
@@ -112,12 +122,12 @@
"components/llms/models/mistral_AI",
"components/llms/models/google_AI",
"components/llms/models/aws_bedrock",
"components/llms/models/gemini",
"components/llms/models/deepseek",
"components/llms/models/xAI",
"components/llms/models/sarvam",
"components/llms/models/lmstudio",
"components/llms/models/langchain"
"components/llms/models/langchain",
"components/llms/models/vllm"
]
}
]
@@ -146,7 +156,8 @@
"components/vectordbs/dbs/vertex_ai",
"components/vectordbs/dbs/weaviate",
"components/vectordbs/dbs/faiss",
"components/vectordbs/dbs/langchain"
"components/vectordbs/dbs/langchain",
"components/vectordbs/dbs/baidu"
]
}
]
@@ -166,7 +177,7 @@
"components/embedders/models/ollama",
"components/embedders/models/huggingface",
"components/embedders/models/vertexai",
"components/embedders/models/gemini",
"components/embedders/models/google_AI",
"components/embedders/models/lmstudio",
"components/embedders/models/together",
"components/embedders/models/langchain",
@@ -192,7 +203,8 @@
"icon": "square-terminal",
"pages": [
"openmemory/overview",
"openmemory/quickstart"
"openmemory/quickstart",
"openmemory/integrations"
]
},
{
@@ -207,6 +219,8 @@
"examples/mem0-demo",
"examples/ai_companion_js",
"examples/collaborative-task-agent",
"examples/llamaindex-multiagent-learning-system",
"examples/personalized-search-tavily-mem0",
"examples/eliza_os",
"examples/mem0-mastra",
"examples/mem0-with-ollama",
@@ -215,7 +229,7 @@
"examples/personal-travel-assistant",
"examples/llama-index-mem0",
"examples/chrome-extension",
"examples/document-writing",
"examples/memory-guided-content-writing",
"examples/multimodal-demo",
"examples/personalized-deep-research",
"examples/mem0-agentic-tool",
@@ -236,23 +250,26 @@
"icon": "plug",
"pages": [
"integrations",
"integrations/vercel-ai-sdk",
"integrations/flowise",
"integrations/crewai",
"integrations/autogen",
"integrations/langchain",
"integrations/langgraph",
"integrations/llama-index",
"integrations/langchain-tools",
"integrations/dify",
"integrations/mcp-server",
"integrations/livekit",
"integrations/elevenlabs",
"integrations/pipecat",
"integrations/agno",
"integrations/autogen",
"integrations/crewai",
"integrations/openai-agents-sdk",
"integrations/google-ai-adk",
"integrations/mastra",
"integrations/vercel-ai-sdk",
"integrations/livekit",
"integrations/pipecat",
"integrations/elevenlabs",
"integrations/aws-bedrock",
"integrations/flowise",
"integrations/langchain-tools",
"integrations/agentops",
"integrations/keywords",
"integrations/raycast",
"integrations/mastra"
"integrations/dify",
"integrations/raycast"
]
}
]
@@ -347,31 +364,6 @@
]
}
]
},
{
"anchor": "Your Dashboard",
"href": "https://app.mem0.ai",
"icon": "chart-simple"
},
{
"anchor": "Demo",
"href": "https://mem0.dev/demo",
"icon": "play"
},
{
"anchor": "Discord",
"href": "https://mem0.dev/DiD",
"icon": "discord"
},
{
"anchor": "GitHub",
"href": "https://github.com/mem0ai/mem0",
"icon": "github"
},
{
"anchor": "Support",
"href": "mailto:founders@mem0.ai",
"icon": "envelope"
}
]
},
+8 -4
View File
@@ -3,7 +3,7 @@ title: Overview
description: How to use mem0 in your existing applications?
---
<Snippet file="paper-release.mdx" />
<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:
@@ -39,10 +39,14 @@ Explore how **Mem0** can power real-world applications and bring personalized, i
<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>
<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 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>
<Card title="LlamaIndex + Mem0 Learning System" icon="book-open" href="/examples/llama-index-mem0">
Multi-agent learning system powered by memory.
</Card>
<Card title="Chrome Extension" icon="puzzle-piece" href="/examples/chrome-extension">
+5 -5
View File
@@ -2,7 +2,7 @@
title: AI Companion
---
<Snippet file="paper-release.mdx" />
<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.
@@ -61,7 +61,7 @@ class 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 companions's capabilities or characteristics They may use words like "you" 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
@@ -87,8 +87,8 @@ class Companion:
previous_memories = self.memory.search(question, user_id=user_id_to_use)
relevant_memories_text = ""
if previous_memories:
relevant_memories_text = '\n'.join(mem["memory"] for mem in previous_memories)
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}"
@@ -146,7 +146,7 @@ def print_memories(user_id, label):
memories = ai_companion.get_memories(user_id=user_id)
if memories:
for m in memories:
print(f"- {m['text']}")
print(f"- {m['memory']}")
else:
print("No memories found.")
+1 -1
View File
@@ -2,7 +2,7 @@
title: AI Companion in Node.js
---
<Snippet file="paper-release.mdx" />
<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.
+25 -13
View File
@@ -1,17 +1,17 @@
---
title: AWS Bedrock and AOSS
title: Amazon Stack: AWS Bedrock, AOSS, and Neptune Analytics
---
<Snippet file="paper-release.mdx" />
<Snippet file="blank-notif.mdx" />
This example demonstrates how to configure and use the `mem0ai` SDK with **AWS Bedrock** and **OpenSearch Service (AOSS)** for persistent memory capabilities in Python.
This example demonstrates how to configure and use the `mem0ai` SDK with **AWS Bedrock**, **OpenSearch Service (AOSS)**, and **AWS Neptune Analytics** for persistent memory capabilities in Python.
## Installation
Install the required dependencies:
Install the required dependencies to include the Amazon data stack, including **boto3**, **opensearch-py**, and **langchain-aws**:
```bash
pip install mem0ai boto3 opensearch-py
pip install "mem0ai[graph,extras]"
```
## Environment Setup
@@ -34,11 +34,15 @@ print(os.environ['AWS_SECRET_ACCESS_KEY'])
## Configuration and Usage
This sets up Mem0 with AWS Bedrock for embeddings and LLM, and OpenSearch as the vector store.
This sets up Mem0 with:
- [AWS Bedrock for LLM](https://docs.mem0.ai/components/llms/models/aws_bedrock)
- [AWS Bedrock for embeddings](https://docs.mem0.ai/components/embedders/models/aws_bedrock#aws-bedrock)
- [OpenSearch as the vector store](https://docs.mem0.ai/components/vectordbs/dbs/opensearch)
- [Neptune Analytics as your graph store](https://docs.mem0.ai/open-source/graph_memory/overview#initialize-neptune-analytics).
```python
import boto3
from opensearchpy import OpenSearch, RequestsHttpConnection, AWSV4SignerAuth
from opensearchpy import RequestsHttpConnection, AWSV4SignerAuth
from mem0.memory.main import Memory
region = 'us-west-2'
@@ -56,7 +60,7 @@ config = {
"llm": {
"provider": "aws_bedrock",
"config": {
"model": "anthropic.claude-3-5-haiku-20241022-v1:0",
"model": "us.anthropic.claude-3-7-sonnet-20250219-v1:0",
"temperature": 0.1,
"max_tokens": 2000
}
@@ -68,21 +72,29 @@ config = {
"host": "your-opensearch-domain.us-west-2.es.amazonaws.com",
"port": 443,
"http_auth": auth,
"embedding_model_dims": 1024,
"connection_class": RequestsHttpConnection,
"pool_maxsize": 20,
"use_ssl": True,
"verify_certs": True
"verify_certs": True,
"embedding_model_dims": 1024,
}
}
},
"graph_store": {
"provider": "neptune",
"config": {
"endpoint": f"neptune-graph://my-graph-identifier",
},
},
}
# Initialize memory system
# Initialize the memory system
m = Memory.from_config(config)
```
## Usage
Reference [Notebook example](https://github.com/mem0ai/mem0/blob/main/examples/graph-db-demo/neptune-example.ipynb)
#### Add a memory:
```python
@@ -117,4 +129,4 @@ memory = m.get(memory_id)
## Conclusion
With Mem0 and AWS services like Bedrock and OpenSearch, you can build intelligent AI companions that remember, adapt, and personalize their responses over time. This makes them ideal for long-term assistants, tutors, or support bots with persistent memory and natural conversation abilities.
With Mem0 and AWS services like Bedrock, OpenSearch, and Neptune Analytics, you can build intelligent AI companions that remember, adapt, and personalize their responses over time. This makes them ideal for long-term assistants, tutors, or support bots with persistent memory and natural conversation abilities.
+1 -1
View File
@@ -1,6 +1,6 @@
# Mem0 Chrome Extension
<Snippet file="paper-release.mdx" />
<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.
+1 -1
View File
@@ -2,7 +2,7 @@
title: Multi-User Collaboration with Mem0
---
<Snippet file="paper-release.mdx" />
<Snippet file="blank-notif.mdx" />
## Overview
+2 -1
View File
@@ -2,7 +2,7 @@
title: Customer Support AI Agent
---
<Snippet file="paper-release.mdx" />
<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.
@@ -23,6 +23,7 @@ pip install openai mem0ai
Below is the simplified code to create and interact with a Customer Support AI Agent using Mem0:
```python
import os
from openai import OpenAI
from mem0 import Memory
+1 -1
View File
@@ -2,7 +2,7 @@
title: Eliza OS Character
---
<Snippet file="paper-release.mdx" />
<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.
+1 -1
View File
@@ -2,7 +2,7 @@
title: Email Processing with Mem0
---
<Snippet file="paper-release.mdx" />
<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.
+5 -5
View File
@@ -1,7 +1,7 @@
---
title: LlamaIndex ReAct Agent
---
<Snippet file="paper-release.mdx" />
<Snippet file="blank-notif.mdx" />
Create a ReAct Agent with LlamaIndex which uses Mem0 as the memory store.
@@ -22,7 +22,7 @@ os.environ["OPENAI_API_KEY"] = "<your-openai-api-key>"
llm = OpenAI(model="gpt-4o")
```
Initialize the Mem0 client. You can find your API key [here](https://app.mem0.ai/dashboard/). Read about Mem0 [Open Source](https://docs.mem0.ai/open-source/quickstart).
Initialize the Mem0 client. You can find your API key [here](https://app.mem0.ai/dashboard/api-keys). Read about Mem0 [Open Source](https://docs.mem0.ai/open-source/overview).
```python
os.environ["MEM0_API_KEY"] = "<your-mem0-api-key>"
@@ -80,7 +80,7 @@ agent = FunctionCallingAgent.from_tools(
```
Start the chat.
<Note> The agent will use the Mem0 to store the relavant memories from the chat. </Note>
<Note> The agent will use the Mem0 to store the relevant memories from the chat. </Note>
Input
```python
@@ -139,7 +139,7 @@ Added user message to memory: I am feeling hungry, order me something and send m
=== LLM Response ===
Please let me know your name and the dish you'd like to order, and I'll take care of it for you!
```
<Note> The agent is not able to remember the past prefernces that user shared in previous chats. </Note>
<Note> The agent is not able to remember the past preferences that user shared in previous chats. </Note>
### Using the agent WITH memory
Input
@@ -171,4 +171,4 @@ Emailing... David
=== LLM Response ===
I've ordered a pizza for you, and the bill has been sent to your email. Enjoy your meal! If there's anything else you need, feel free to let me know.
```
<Note> The agent is able to remember the past prefernces that user shared and use them to perform actions. </Note>
<Note> The agent is able to remember the past preferences that user shared and use them to perform actions. </Note>
@@ -0,0 +1,360 @@
---
title: LlamaIndex Multi-Agent Learning System
---
<Snippet file="blank-notif.mdx" />
Build an intelligent multi-agent learning system that uses Mem0 to maintain persistent memory across multiple specialized agents. This example demonstrates how to create a tutoring system where different agents collaborate while sharing a unified memory layer.
## Overview
This example showcases a **Multi-Agent Personal Learning System** that combines:
- **LlamaIndex AgentWorkflow** for multi-agent orchestration
- **Mem0** for persistent, shared memory across agents
- **Multi-agents** that collaborate on teaching tasks
The system consists of two agents:
- **TutorAgent**: Primary instructor for explanations and concept teaching
- **PracticeAgent**: Generates exercises and tracks learning progress
Both agents share the same memory context, enabling seamless collaboration and continuous learning from student interactions.
## Key Features
- **Persistent Memory**: Agents remember previous interactions across sessions
- **Multi-Agent Collaboration**: Agents can hand off tasks to each other
- **Personalized Learning**: Adapts to individual student needs and learning styles
- **Progress Tracking**: Monitors learning patterns and skill development
- **Memory-Driven Teaching**: References past struggles and successes
## Prerequisites
Install the required packages:
```bash
pip install llama-index-core llama-index-memory-mem0 openai python-dotenv
```
Set up your environment variables:
- `MEM0_API_KEY`: Your Mem0 Platform API key
- `OPENAI_API_KEY`: Your OpenAI API key
You can obtain your Mem0 Platform API key from the [Mem0 Platform](https://app.mem0.ai).
## Complete Implementation
```python
"""
Multi-Agent Personal Learning System: Mem0 + LlamaIndex AgentWorkflow Example
INSTALLATIONS:
!pip install llama-index-core llama-index-memory-mem0 openai
You need MEM0_API_KEY and OPENAI_API_KEY to run the example.
"""
import asyncio
from datetime import datetime
from dotenv import load_dotenv
# LlamaIndex imports
from llama_index.core.agent.workflow import AgentWorkflow, FunctionAgent
from llama_index.llms.openai import OpenAI
from llama_index.core.tools import FunctionTool
# Memory integration
from llama_index.memory.mem0 import Mem0Memory
import warnings
warnings.filterwarnings("ignore", category=DeprecationWarning)
load_dotenv()
class MultiAgentLearningSystem:
"""
Multi-Agent Architecture:
- TutorAgent: Main teaching and explanations
- PracticeAgent: Exercises and skill reinforcement
- Shared Memory: Both agents learn from student interactions
"""
def __init__(self, student_id: str):
self.student_id = student_id
self.llm = OpenAI(model="gpt-4o", temperature=0.2)
# Memory context for this student
self.memory_context = {"user_id": student_id, "app": "learning_assistant"}
self.memory = Mem0Memory.from_client(
context=self.memory_context
)
self._setup_agents()
def _setup_agents(self):
"""Setup two agents that work together and share memory"""
# TOOLS
async def assess_understanding(topic: str, student_response: str) -> str:
"""Assess student's understanding of a topic and save insights"""
# Simulate assessment logic
if "confused" in student_response.lower() or "don't understand" in student_response.lower():
assessment = f"STRUGGLING with {topic}: {student_response}"
insight = f"Student needs more help with {topic}. Prefers step-by-step explanations."
elif "makes sense" in student_response.lower() or "got it" in student_response.lower():
assessment = f"UNDERSTANDS {topic}: {student_response}"
insight = f"Student grasped {topic} quickly. Can move to advanced concepts."
else:
assessment = f"PARTIAL understanding of {topic}: {student_response}"
insight = f"Student has basic understanding of {topic}. Needs reinforcement."
return f"Assessment: {assessment}\nInsight saved: {insight}"
async def track_progress(topic: str, success_rate: str) -> str:
"""Track learning progress and identify patterns"""
progress_note = f"Progress on {topic}: {success_rate} - {datetime.now().strftime('%Y-%m-%d')}"
return f"Progress tracked: {progress_note}"
# Convert to FunctionTools
tools = [
FunctionTool.from_defaults(async_fn=assess_understanding),
FunctionTool.from_defaults(async_fn=track_progress)
]
# AGENTS
# Tutor Agent - Main teaching and explanation
self.tutor_agent = FunctionAgent(
name="TutorAgent",
description="Primary instructor that explains concepts and adapts to student needs",
system_prompt="""
You are a patient, adaptive programming tutor. Your key strength is REMEMBERING and BUILDING on previous interactions.
Key Behaviors:
1. Always check what the student has learned before (use memory context)
2. Adapt explanations based on their preferred learning style
3. Reference previous struggles or successes
4. Build progressively on past lessons
5. Use assess_understanding to evaluate responses and save insights
MEMORY-DRIVEN TEACHING:
- "Last time you struggled with X, so let's approach Y differently..."
- "Since you prefer visual examples, here's a diagram..."
- "Building on the functions we covered yesterday..."
When student shows understanding, hand off to PracticeAgent for exercises.
""",
tools=tools,
llm=self.llm,
can_handoff_to=["PracticeAgent"]
)
# Practice Agent - Exercises and reinforcement
self.practice_agent = FunctionAgent(
name="PracticeAgent",
description="Creates practice exercises and tracks progress based on student's learning history",
system_prompt="""
You create personalized practice exercises based on the student's learning history and current level.
Key Behaviors:
1. Generate problems that match their skill level (from memory)
2. Focus on areas they've struggled with previously
3. Gradually increase difficulty based on their progress
4. Use track_progress to record their performance
5. Provide encouraging feedback that references their growth
MEMORY-DRIVEN PRACTICE:
- "Let's practice loops again since you wanted more examples..."
- "Here's a harder version of the problem you solved yesterday..."
- "You've improved a lot in functions, ready for the next level?"
After practice, can hand back to TutorAgent for concept review if needed.
""",
tools=tools,
llm=self.llm,
can_handoff_to=["TutorAgent"]
)
# Create the multi-agent workflow
self.workflow = AgentWorkflow(
agents=[self.tutor_agent, self.practice_agent],
root_agent=self.tutor_agent.name,
initial_state={
"current_topic": "",
"student_level": "beginner",
"learning_style": "unknown",
"session_goals": []
}
)
async def start_learning_session(self, topic: str, student_message: str = "") -> str:
"""
Start a learning session with multi-agent memory-aware teaching
"""
if student_message:
request = f"I want to learn about {topic}. {student_message}"
else:
request = f"I want to learn about {topic}."
# The magic happens here - multi-agent memory is automatically shared!
response = await self.workflow.run(
user_msg=request,
memory=self.memory
)
return str(response)
async def get_learning_history(self) -> str:
"""Show what the system remembers about this student"""
try:
# Search memory for learning patterns
memories = self.memory.search(
user_id=self.student_id,
query="learning machine learning"
)
if memories and memories.get('results'):
history = "\n".join(f"- {m['memory']}" for m in memories['results'])
return history
else:
return "No learning history found yet. Let's start building your profile!"
except Exception as e:
return f"Memory retrieval error: {str(e)}"
async def run_learning_agent():
learning_system = MultiAgentLearningSystem(student_id="Alexander")
# First session
print("Session 1:")
response = await learning_system.start_learning_session(
"Vision Language Models",
"I'm new to machine learning but I have good hold on Python and have 4 years of work experience.")
print(response)
# Second session - multi-agent memory will remember the first
print("\nSession 2:")
response2 = await learning_system.start_learning_session(
"Machine Learning", "what all did I cover so far?")
print(response2)
# Show what the multi-agent system remembers
print("\nLearning History:")
history = await learning_system.get_learning_history()
print(history)
if __name__ == "__main__":
"""Run the example"""
print("Multi-agent Learning System powered by LlamaIndex and Mem0")
async def main():
await run_learning_agent()
asyncio.run(main())
```
## How It Works
### 1. Memory Context Setup
```python
# Memory context for this student
self.memory_context = {"user_id": student_id, "app": "learning_assistant"}
self.memory = Mem0Memory.from_client(context=self.memory_context)
```
The memory context identifies the specific student and application, ensuring memory isolation and proper retrieval.
### 2. Agent Collaboration
```python
# Agents can hand off to each other
can_handoff_to=["PracticeAgent"] # TutorAgent can hand off to PracticeAgent
can_handoff_to=["TutorAgent"] # PracticeAgent can hand off back
```
Agents collaborate seamlessly, with the TutorAgent handling explanations and the PracticeAgent managing exercises.
### 3. Shared Memory
```python
# Both agents share the same memory instance
response = await self.workflow.run(
user_msg=request,
memory=self.memory # Shared across all agents
)
```
All agents in the workflow share the same memory context, enabling true collaborative learning.
### 4. Memory-Driven Interactions
The system prompts guide agents to:
- Reference previous learning sessions
- Adapt to discovered learning styles
- Build progressively on past lessons
- Track and respond to learning patterns
## Running the Example
```python
# Initialize the learning system
learning_system = MultiAgentLearningSystem(student_id="Alexander")
# Start a learning session
response = await learning_system.start_learning_session(
"Vision Language Models",
"I'm new to machine learning but I have good hold on Python and have 4 years of work experience."
)
# Continue learning in a new session (memory persists)
response2 = await learning_system.start_learning_session(
"Machine Learning",
"what all did I cover so far?"
)
# Check learning history
history = await learning_system.get_learning_history()
```
## Expected Output
The system will demonstrate memory-aware interactions:
```
Session 1:
I understand you want to learn about Vision Language Models and you mentioned you're new to machine learning but have a strong Python background with 4 years of experience. That's a great foundation to build on!
Let me start with an explanation tailored to your programming background...
[Agent provides explanation and may hand off to PracticeAgent for exercises]
Session 2:
Based on our previous session, I remember we covered Vision Language Models and I noted that you have a strong Python background with 4 years of experience. You mentioned being new to machine learning, so we started with foundational concepts...
[Agent references previous session and builds upon it]
```
## Key Benefits
1. **Persistent Learning**: Agents remember across sessions, creating continuity
2. **Collaborative Teaching**: Multiple specialized agents work together seamlessly
3. **Personalized Adaptation**: System learns and adapts to individual learning styles
4. **Scalable Architecture**: Easy to add more specialized agents
5. **Memory Efficiency**: Shared memory prevents duplication and ensures consistency
## Best Practices
1. **Clear Agent Roles**: Define specific responsibilities for each agent
2. **Memory Context**: Use descriptive context for memory isolation
3. **Handoff Strategy**: Design clear handoff criteria between agents
5. **Memory Hygiene**: Regularly review and clean memory for optimal performance
## Help & Resources
- [LlamaIndex Agent Workflows](https://docs.llamaindex.ai/en/stable/use_cases/agents/)
- [Mem0 Platform](https://app.mem0.ai/)
<Snippet file="get-help.mdx" />
+1 -1
View File
@@ -2,7 +2,7 @@
title: Mem0 as an Agentic Tool
---
<Snippet file="paper-release.mdx" />
<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.
+1 -1
View File
@@ -3,7 +3,7 @@ title: Mem0 Demo
---
<Snippet file="paper-release.mdx" />
<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.
@@ -3,7 +3,7 @@ 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="paper-release.mdx" />
<Snippet file="blank-notif.mdx" />
# Healthcare Assistant with Memory
+1 -1
View File
@@ -2,7 +2,7 @@
title: Mem0 with Mastra
---
<Snippet file="paper-release.mdx" />
<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).
+1 -1
View File
@@ -3,7 +3,7 @@ title: 'Mem0 with OpenAI Agents SDK for Voice'
description: 'Integrate memory capabilities into your voice agents using Mem0 and OpenAI Agents SDK'
---
<Snippet file="paper-release.mdx" />
<Snippet file="blank-notif.mdx" />
# Building Voice Agents with Memory using Mem0 and OpenAI Agents SDK
+1 -2
View File
@@ -2,7 +2,7 @@
title: Mem0 with Ollama
---
<Snippet file="paper-release.mdx" />
<Snippet file="blank-notif.mdx" />
## Running Mem0 Locally with Ollama
@@ -21,7 +21,6 @@ Before you begin, ensure you have Mem0 and Ollama installed and properly configu
Below is the complete code to set up and use Mem0 locally with Ollama:
```python
import os
from mem0 import Memory
config = {
@@ -1,103 +1,133 @@
---
title: Document Editing with Mem0
title: Memory-Guided Content Writing
---
<Snippet file="paper-release.mdx" />
<Snippet file="blank-notif.mdx" />
This guide demonstrates how to leverage **Mem0** to edit documents efficiently, ensuring they align with your unique writing style and preferences.
This guide demonstrates how to leverage **Mem0** to streamline content writing by applying your unique writing style and preferences using persistent memory.
## **Why Use Mem0?**
## Why Use Mem0?
By integrating Mem0 into your workflow, you can streamline your document editing process with:
Integrating Mem0 into your writing workflow helps you:
1. **Persistent Writing Preferences**: Mem0 stores and recalls your style preferences, ensuring consistency across all documents.
2. **Automated Enhancements**: Your stored preferences guide document refinements, making edits seamless and efficient.
3. **Scalability & Reusability**: Your writing style can be applied to multiple documents, saving time and effort.
1. **Store persistent writing preferences** ensuring consistent tone, formatting, and structure.
2. **Automate content refinement** by retrieving preferences when rewriting or reviewing content.
3. **Scale your writing style** so it applies consistently across multiple documents or sessions.
---
## **Setup**
## Setup
```python
import os
from openai import OpenAI
from mem0 import MemoryClient
# Set up Mem0 client
os.environ["MEM0_API_KEY"] = "your-mem0-api-key"
os.environ["OPENAI_API_KEY"] = "your-openai-api-key"
# Set up Mem0 and OpenAI client
client = MemoryClient()
openai = OpenAI()
# Define constants
USER_ID = "content_writer"
RUN_ID = "smart_editing_session"
```
---
## **Storing Your Writing Preferences in Mem0**
```python
def store_writing_preferences():
"""Store your writing preferences in Mem0."""
# Define writing preferences
preferences = """My writing preferences:
1. Use headings and sub-headings for structure.
2. Keep paragraphs concise (8-10 sentences max).
2. Keep paragraphs concise (8–10 sentences max).
3. Incorporate specific numbers and statistics.
4. Provide concrete examples.
5. Use bullet points for clarity.
6. Avoid jargon and buzzwords."""
# Store preferences in Mem0
preference_message = [
{"role": "user", "content": "Here are my writing style preferences"},
messages = [
{"role": "user", "content": "Here are my writing style preferences."},
{"role": "assistant", "content": preferences}
]
response = client.add(preference_message, user_id=USER_ID, run_id=RUN_ID, metadata={"type": "preferences", "category": "writing_style"})
print("Writing preferences stored successfully.")
response = client.add(
messages,
user_id=USER_ID,
run_id=RUN_ID,
metadata={"type": "preferences", "category": "writing_style"}
)
return response
```
---
## **Editing Documents with Mem0**
## **Editing Content Using Stored Preferences**
```python
def edit_document_based_on_preferences(original_content):
"""Edit a document using Mem0-based stored preferences."""
# Retrieve stored preferences
query = "What are my writing style preferences?"
preferences_results = client.search(query, user_id=USER_ID, run_id=RUN_ID)
if not preferences_results:
print("No writing preferences found.")
def apply_writing_style(original_content):
"""Use preferences stored in Mem0 to guide content rewriting."""
results = client.search(
query="What are my writing style preferences?",
version="v2",
filters={
"AND": [
{
"user_id": USER_ID
},
{
"run_id": RUN_ID
}
]
},
)
if not results:
print("No preferences found.")
return None
# Extract preferences
preferences = ' '.join(memory["memory"] for memory in preferences_results)
# Apply stored preferences to refine the document
edited_content = f"Applying stored preferences:\n{preferences}\n\nEdited Document:\n{original_content}"
return edited_content
preferences = "\n".join(r["memory"] for r in results.get('results', []))
system_prompt = f"""
You are a writing assistant.
Apply the following writing style preferences to improve the user's content:
Preferences:
{preferences}
"""
messages = [
{"role": "system", "content": system_prompt},
{"role": "user", "content": f"""Original Content:
{original_content}"""}
]
response = openai.chat.completions.create(
model="gpt-4o-mini",
messages=messages
)
clean_response = response.choices[0].message.content.strip()
return clean_response
```
---
## **Complete Workflow: Document Editing**
## **Complete Workflow: Content Editing**
```python
def document_editing_workflow(content):
def content_writing_workflow(content):
"""Automated workflow for editing a document based on writing preferences."""
# Step 1: Store writing preferences (if not already stored)
store_writing_preferences()
# Store writing preferences (if not already stored)
store_writing_preferences() # Ideally done once, or with a conditional check
# Step 2: Edit the document with Mem0 preferences
edited_content = edit_document_based_on_preferences(content)
# Edit the document with Mem0 preferences
edited_content = apply_writing_style(content)
if not edited_content:
return "Failed to edit document."
# Step 3: Display results
# Display results
print("\n=== ORIGINAL DOCUMENT ===\n")
print(content)
@@ -107,7 +137,6 @@ def document_editing_workflow(content):
return edited_content
```
---
## **Example Usage**
```python
@@ -125,10 +154,9 @@ We plan to launch the campaign in July and continue through September.
"""
# Run the workflow
result = document_editing_workflow(original_content)
result = content_writing_workflow(original_content)
```
---
## **Expected Output**
Your document will be transformed into a structured, well-formatted version based on your preferences.
@@ -182,4 +210,10 @@ This proposal outlines our strategy for the Q3 marketing campaign. We aim to sig
We believe this strategy will effectively increase our market share. To achieve these goals, we need your support and collaboration. Let’s work together to make this campaign a success. Please review the proposal and provide your feedback by the end of the week.
```
Mem0 creates a seamless, intelligent document editing experience—perfect for content creators, technical writers, and businesses alike!
Mem0 enables a seamless, intelligent content-writing workflow, perfect for content creators, marketers, and technical writers looking to scale their personal tone and structure across work.
## Help & Resources
- [Mem0 Platform](https://app.mem0.ai/)
<Snippet file="get-help.mdx" />
+14 -14
View File
@@ -2,32 +2,32 @@
title: Multimodal Demo with Mem0
---
<Snippet file="paper-release.mdx" />
<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)
> Experience the power of multimodal AI! Test out Mem0's image understanding capabilities at [multimodal-demo.mem0.ai](https://multimodal-demo.mem0.ai)
## 🚀 Features
## Features
- **🖼️ Image Understanding**: Share and discuss images with AI assistants while maintaining context.
- **🔍 Smart Visual Context**: Automatically capture and reference visual elements in conversations.
- **🔗 Cross-Modal Memory**: Link visual and textual information seamlessly in your memory layer.
- **📌 Cross-Session Recall**: Reference previously discussed visual content across different conversations.
- **⚡ Seamless Integration**: Works naturally with existing chat interfaces for a smooth experience.
- **Image Understanding**: Share and discuss images with AI assistants while maintaining context.
- **Smart Visual Context**: Automatically capture and reference visual elements in conversations.
- **Cross-Modal Memory**: Link visual and textual information seamlessly in your memory layer.
- **Cross-Session Recall**: Reference previously discussed visual content across different conversations.
- **Seamless Integration**: Works naturally with existing chat interfaces for a smooth experience.
## 📖 How It Works
## How It Works
1. **📂 Upload Visual Content**: Simply drag and drop or paste images into your conversations.
2. **💬 Natural Interaction**: Discuss the visual content naturally with AI assistants.
3. **📚 Memory Integration**: Visual context is automatically stored and linked with your conversation history.
4. **🔄 Persistent Recall**: Retrieve and reference past visual content effortlessly.
1. **Upload Visual Content**: Simply drag and drop or paste images into your conversations.
2. **Natural Interaction**: Discuss the visual content naturally with AI assistants.
3. **Memory Integration**: Visual context is automatically stored and linked with your conversation history.
4. **Persistent Recall**: Retrieve and reference past visual content effortlessly.
## Demo Video
<iframe width="700" height="400" src="https://www.youtube.com/embed/2Md5AEFVpmg?si=rXXupn6CiDUPJsi3" title="YouTube video player" frameborder="0" allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture; web-share" referrerpolicy="strict-origin-when-cross-origin" allowfullscreen></iframe>
## 🔥 Try It Out
## Try It Out
Visit [multimodal-demo.mem0.ai](https://multimodal-demo.mem0.ai) to experience Mem0's multimodal capabilities firsthand. Upload images and see how Mem0 understands and remembers visual context across your conversations.
+2 -2
View File
@@ -2,7 +2,7 @@
title: OpenAI Inbuilt Tools
---
<Snippet file="paper-release.mdx" />
<Snippet file="blank-notif.mdx" />
Integrate Mem0’s memory capabilities with OpenAI’s Inbuilt Tools to create AI agents with persistent memory.
@@ -225,7 +225,7 @@ async function addSampleMemories() {
const getMemoryString = (memories) => {
const MEMORY_STRING_PREFIX = "These are the memories I have stored. Give more weightage to the question by users and try to answer that first. You have to modify your answer based on the memories I have provided. If the memories are irrelevant you can ignore them. Also don't reply to this section of the prompt, or the memories, they are only for your reference. The MEMORIES of the USER are: \n\n";
const memoryString = memories.map((mem) => `${mem.memory}`).join("\n") ?? "";
const memoryString = (memories?.results || memories).map((mem) => `${mem.memory}`).join("\n") ?? "";
return memoryString.length > 0 ? `${MEMORY_STRING_PREFIX}${memoryString}` : "";
};
+1 -1
View File
@@ -2,7 +2,7 @@
title: Personalized AI Tutor
---
<Snippet file="paper-release.mdx" />
<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.
+3 -3
View File
@@ -2,7 +2,7 @@
title: Personal AI Travel Assistant
---
<Snippet file="paper-release.mdx" />
<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.
@@ -155,11 +155,11 @@ class PersonalTravelAssistant:
def get_memories(self, user_id):
memories = self.memory.get_all(user_id=user_id)
return [m['memory'] for m in memories['memories']]
return [m['memory'] for m in memories.get('results', [])]
def search_memories(self, query, user_id):
memories = self.memory.search(query, user_id=user_id)
return [m['memory'] for m in memories['memories']]
return [m['memory'] for m in memories.get('results', [])]
# Usage example
user_id = "traveler_123"
+6 -9
View File
@@ -2,10 +2,12 @@
title: Personalized Deep Research
---
<Snippet file="paper-release.mdx" />
<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)
## Overview
Deep Research leverages Mem0's memory capabilities to:
@@ -30,13 +32,6 @@ Watch Deep Research in action:
allowfullscreen
></iframe>
## Getting Started
1. Visit [deep-research.mem0.ai](https://deep-research.mem0.ai/)
2. Upload your resume (PDF or text) or manually enter information about yourself
3. Enter your research topic
4. Click "Start Research" to begin
## Features
### 1. Personalized Research
@@ -69,4 +64,6 @@ Watch Deep Research in action:
## Try It Out
Experience AI-powered research personalization at [deep-research.mem0.ai](https://deep-research.mem0.ai/)
> To try it yourself, clone the repository and follow the instructions in the README to run it locally or deploy it.
- [Personalized Deep Research GitHub](https://github.com/mem0ai/personalized-deep-research/tree/mem0)
@@ -0,0 +1,190 @@
---
title: 'Personalized Search with Mem0 and Tavily'
---
<Snippet file="security-compliance.mdx" />
Imagine asking a search assistant for "coffee shops nearby" and instead of generic results, it shows remote-work-friendly cafes with great wifi in your city because it remembers you mentioned working remotely before. Or when you search for "lunchbox ideas for kids" it knows you have a **7-year-old daughter** and recommends **peanut-free options** that align with her allergy.
That's what we are going to build today, a **Personalized Search Assistant** powered by **Mem0** for memory and [Tavily](https://tavily.com) for real-time search.
## Why Personalized Search
Most assistants treat every query like they’ve never seen you before. That means repeating yourself about your location, diet, or preferences, and getting results that feel generic.
- With **Mem0**, your assistant builds a memory of the user’s world.
- With **Tavily**, it fetches fresh and accurate results in real time.
Together, they make every interaction **smarter, faster, and more personal**.
## Prerequisites
Before you begin, make sure you have:
1. Installed the dependencies:
```bash
pip install langchain mem0ai langchain-tavily langchain-openai
```
2. Set up your API keys in a .env file:
```bash
OPENAI_API_KEY=your-openai-key
TAVILY_API_KEY=your-tavily-key
MEM0_API_KEY=your-mem0-key
```
## Code Walkthrough
Let’s break down the main components.
### 1: Initialize Mem0 with Custom Instructions
We configure Mem0 with custom instructions that guide it to infer user memories tailored specifically for our usecase.
```python
from mem0 import MemoryClient
mem0_client = MemoryClient()
mem0_client.project.update(
custom_instructions='''
INFER THE MEMORIES FROM USER QUERIES EVEN IF IT'S A QUESTION.
We are building personalized search for which we need to understand about user's preferences and life
and extract facts and memories accordingly.
'''
)
```
Now, if a user casually mentions "I need to pick up my daughter", or "What's the weather at Los Angeles", Mem0 remembers they have a daughter or user is somewhat interested/connected with Los Angeles in terms of location, those will be referred for future searches.
### 2. Simulating User History
To test personalization, we preload some sample conversation history for a user:
```python
def setup_user_history(user_id):
conversations = [
[{"role": "user", "content": "What will be the weather today at Los Angeles? I need to pick up my daughter from office."},
{"role": "assistant", "content": "I'll check the weather in LA for you."}],
[{"role": "user", "content": "I'm looking for vegan restaurants in Santa Monica"},
{"role": "assistant", "content": "I'll find great vegan options in Santa Monica."}],
[{"role": "user", "content": "My 7-year-old daughter is allergic to peanuts"},
{"role": "assistant", "content": "I'll remember to check for peanut-free options."}],
[{"role": "user", "content": "I work remotely and need coffee shops with good wifi"},
{"role": "assistant", "content": "I'll find remote-work-friendly coffee shops."}],
[{"role": "user", "content": "We love hiking and outdoor activities on weekends"},
{"role": "assistant", "content": "Great! I'll keep your outdoor activity preferences in mind."}],
]
for conversation in conversations:
mem0_client.add(conversation, user_id=user_id, output_format="v1.1")
```
This gives the agent a baseline understanding of the user’s lifestyle and needs.
### 3. Retrieving User Context from Memory
When a user makes a new search query, we retrieve relevant memories to enhance the search query:
```python
def get_user_context(user_id, query):
filters = {"AND": [{"user_id": user_id}]}
user_memories = mem0_client.search(query=query, version="v2", filters=filters)
if user_memories:
context = "\n".join([f"- {memory['memory']}" for memory in user_memories])
return context
else:
return "No previous user context available."
```
This context is injected into the search agent so results are personalized.
### 4. Creating the Personalized Search Agent
The agent uses Tavily search, but always augments search queries with user context:
```python
def create_personalized_search_agent(user_context):
tavily_search = TavilySearch(
max_results=10,
search_depth="advanced",
include_answer=True,
topic="general"
)
tools = [tavily_search]
prompt = ChatPromptTemplate.from_messages([
("system", f"""You are a personalized search assistant.
USER CONTEXT AND PREFERENCES:
{user_context}
YOUR ROLE:
1. Analyze the user's query and context.
2. Enhance the query with relevant personal memories.
3. Always use tavily_search for results.
4. Explain which memories influenced personalization.
"""),
MessagesPlaceholder(variable_name="messages"),
MessagesPlaceholder(variable_name="agent_scratchpad"),
])
agent = create_openai_tools_agent(llm=llm, tools=tools, prompt=prompt)
return AgentExecutor(agent=agent, tools=tools, verbose=True, return_intermediate_steps=True)
```
### 5. Run a Personalized Search
The workflow ties everything together:
```python
def conduct_personalized_search(user_id, query):
user_context = get_user_context(user_id, query)
agent_executor = create_personalized_search_agent(user_context)
response = agent_executor.invoke({"messages": [HumanMessage(content=query)]})
return {"agent_response": response['output']}
```
### 6. Store New Interactions
Every new query/response pair is stored for future personalization:
```python
def store_search_interaction(user_id, original_query, agent_response):
interaction = [
{"role": "user", "content": f"Searched for: {original_query}"},
{"role": "assistant", "content": f"Results based on preferences: {agent_response}"}
]
mem0_client.add(messages=interaction, user_id=user_id, output_format="v1.1")
```
### Full Example Run
```python
if __name__ == "__main__":
user_id = "john"
setup_user_history(user_id)
queries = [
"good coffee shops nearby for working",
"what can I make for my kid in lunch?"
]
for q in queries:
results = conduct_personalized_search(user_id, q)
print(f"\nQuery: {q}")
print(f"Personalized Response: {results['agent_response']}")
```
## How It Works in Practice
Here’s how personalization plays out:
- Context Gathering: User previously mentioned living in Los Angeles, being vegan, and having a 7-year-old daughter allergic to peanuts.
- Enhanced Search Query:
Query -> "good coffee shops nearby for working"
Enhanced Query -> "good coffee shops in Los Angeles with strong wifi, remote-work-friendly"
- Personalized Results: The assistant only returns wifi-friendly, work-friendly cafes near Los Angeles.
- Memory Update: Interaction is saved for better future recommendations.
## Conclusion
With Mem0 + Tavily, you can build a search assistant that doesn’t just fetch results but it understands the person behind the query.
Whether for shopping, travel, or daily life, this approach turns a generic search into a truly personalized experience.
Full Code: [Personalized Search GitHub](https://github.com/mem0ai/mem0/blob/main/examples/misc/personalized_search.py)
+1 -1
View File
@@ -2,7 +2,7 @@
title: YouTube Assistant Extension
---
<Snippet file="paper-release.mdx" />
<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.
+3 -3
View File
@@ -4,7 +4,7 @@ icon: "question"
iconType: "solid"
---
<Snippet file="paper-release.mdx" />
<Snippet file="async-memory-add.mdx" />
<AccordionGroup>
<Accordion title="How does Mem0 work?">
@@ -14,7 +14,7 @@ iconType: "solid"
When an AI agent or LLM needs to access memories, it employs the `search` method. Mem0 conducts a comprehensive search across these data stores, retrieving relevant information from each.
The retrieved memories can be seamlessly integrated into the LLM's prompt as required, enhancing the personalization and relevance of responses.
The retrieved memories can be seamlessly integrated into the system prompt as required, enhancing the personalization and relevance of responses.
</Accordion>
<Accordion title="What are the key features of Mem0?">
@@ -23,7 +23,7 @@ iconType: "solid"
- **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 relevent memories instead of complete transcripts to context window
- **Save Costs**: Saves costs by adding relevant memories instead of complete transcripts to context window
</Accordion>
<Accordion title="How Mem0 is different from traditional RAG?">
+2 -2
View File
@@ -4,7 +4,7 @@ icon: "wrench"
iconType: "solid"
---
<Snippet file="paper-release.mdx" />
<Snippet file="blank-notif.mdx" />
## Core features
@@ -13,7 +13,7 @@ iconType: "solid"
- **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 relevent memories instead of complete transcripts to context window
- **Save Costs**: Saves costs by adding relevant memories instead of complete transcripts to context window
Binary file not shown.

After

Width:  |  Height:  |  Size: 184 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 285 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 195 KiB

+19 -1
View File
@@ -3,7 +3,7 @@ title: Overview
description: How to integrate Mem0 into other frameworks
---
<Snippet file="paper-release.mdx" />
<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:
@@ -18,6 +18,23 @@ Here are the available integrations for Mem0:
## Integrations
<CardGroup cols={2}>
<Card
title="AgentOps"
icon={
<svg
xmlns="http://www.w3.org/2000/svg"
width="25"
height="26"
viewBox="0 0 30 36"
fill="none"
>
<path d="M10.4659 6.47277C10.45 6.37428 10.4381 6.27986 10.4303 6.18101L10.4285 6.16388C10.4212 6.09482 10.414 6.02566 10.4106 5.95626L1.18538 21.8752C0.505422 23.0493 0.323356 24.4208 0.675227 25.7289C0.849119 26.3869 1.14971 26.9859 1.55323 27.5098C1.95675 28.0338 2.46282 28.4751 3.05175 28.8143C3.83464 29.2675 4.70856 29.5 5.59028 29.5C6.03318 29.5 6.4798 29.4408 6.91899 29.3226C8.23581 28.972 9.3349 28.1326 10.0152 26.9545L15.9268 16.749V16.7449L16.5001 15.7637L17.6431 13.7936L16.5001 11.8234L15.9309 10.8381L15.9268 10.8341L13.7836 7.13406C13.6651 6.933 13.5741 6.72418 13.5109 6.51165C13.2817 5.80223 13.3292 5.04172 13.6097 4.37599L13.8115 4.02535C14.3532 3.09155 15.31 2.53987 16.3184 2.47692C16.3738 2.46915 16.4251 2.46915 16.4804 2.46915C16.5421 2.46915 16.6038 2.47257 16.6654 2.47599L16.6822 2.47692C17.6906 2.53987 18.6474 3.09155 19.1892 4.02535L21.2216 7.52838L21.8146 8.55289L21.8421 8.60399L30.1024 22.8601C30.5174 23.5814 30.6281 24.4167 30.4148 25.2205C30.1975 26.0244 29.6832 26.6942 28.9598 27.1081C28.2364 27.5258 27.3977 27.6361 26.5911 27.4195C25.7844 27.2066 25.1123 26.6905 24.6968 25.9696L18.2119 14.7788L17.069 16.7449L22.9847 26.9545C23.6646 28.1326 24.7641 28.972 26.0809 29.3226C26.5197 29.4408 26.9626 29.5 27.4096 29.5C28.2914 29.5 29.1612 29.2675 29.9482 28.8143C31.1264 28.1367 31.9728 27.0411 32.3247 25.7289C32.6766 24.4208 32.4949 23.0493 31.8145 21.8752L21.1261 3.43034C20.7029 2.51617 20.0033 1.72011 19.0621 1.18027C18.5281 0.877027 17.9708 0.675975 17.3975 0.581189C17.3027 0.565268 17.2076 0.549717 17.1129 0.537868C17.0099 0.52602 16.9074 0.518244 16.8045 0.510469C16.6027 0.498621 16.3972 0.494548 16.1914 0.510469C16.0885 0.518244 15.9859 0.52639 15.883 0.537868C15.795 0.54887 15.7067 0.563384 15.6187 0.577852L15.5984 0.581189C15.0291 0.675605 14.4673 0.876657 13.9375 1.18027C12.9885 1.72789 12.2766 2.53579 11.8537 3.46181C11.7742 3.63473 11.707 3.81282 11.6471 3.99314C11.6361 4.02668 11.6269 4.06051 11.6177 4.09435C11.612 4.11503 11.6064 4.13579 11.6003 4.15642C11.5624 4.28601 11.5275 4.41634 11.4996 4.54853C11.4885 4.60231 11.4794 4.65668 11.4703 4.71111L11.4666 4.73329C11.4443 4.86399 11.4264 4.99543 11.4145 5.12762C11.4093 5.18686 11.4045 5.24573 11.4012 5.30534C11.3934 5.44567 11.3923 5.58637 11.3963 5.72744C11.3969 5.74403 11.3962 5.76062 11.3956 5.7772C11.3949 5.79616 11.3942 5.81512 11.3952 5.83407C11.3952 5.86184 11.3952 5.88924 11.3993 5.92071C11.3998 5.9291 11.4006 5.93736 11.4014 5.94564C11.402 5.95125 11.4026 5.95687 11.403 5.96255C11.4045 5.98181 11.4064 6.00106 11.4082 6.02031C11.4097 6.03577 11.4109 6.05122 11.4122 6.06674C11.4142 6.09134 11.4163 6.11621 11.419 6.14139L11.4428 6.32282C11.4506 6.38983 11.4625 6.46092 11.4744 6.52757C11.5063 6.68863 11.5468 6.84896 11.5936 7.0078C11.5944 7.0102 11.5949 7.0127 11.5955 7.0152C11.5958 7.01662 11.5961 7.01804 11.5965 7.01944C11.5967 7.02051 11.597 7.02157 11.5974 7.02261C11.6483 7.19293 11.7081 7.36177 11.7787 7.52838C11.8619 7.72943 11.9607 7.92641 12.0715 8.11932L12.3245 8.5566V8.56067L12.4984 8.85614L12.7199 9.24232H12.7239L12.728 9.25417L14.7802 12.7927V12.7968L14.7883 12.805V12.809L15.3576 13.7943L14.7883 14.7796L8.30344 25.9703C7.88431 26.6912 7.21216 27.2077 6.40921 27.4202C6.14019 27.4913 5.86338 27.5306 5.59474 27.5306C5.053 27.5306 4.51906 27.3888 4.04085 27.1089C3.31705 26.6953 2.79909 26.0251 2.58581 25.2213C2.36845 24.4174 2.47917 23.5821 2.89829 22.8609L11.1585 8.60473L11.186 8.56141V8.55734C11.1266 8.45478 11.0753 8.35629 11.024 8.25409C11.0105 8.22496 10.9969 8.19611 10.9834 8.16739C10.9458 8.08735 10.9086 8.00836 10.8739 7.92715C10.8718 7.92504 10.8708 7.92194 10.8698 7.91887C10.8688 7.91602 10.8679 7.91319 10.8661 7.91123V7.90346C10.8423 7.8483 10.8186 7.79311 10.7989 7.73795C10.7476 7.60799 10.7041 7.47803 10.6644 7.3477C10.6012 7.15479 10.5536 6.96152 10.518 6.76861C10.4942 6.67012 10.4786 6.5757 10.4667 6.47684C10.4667 6.47684 10.47 6.47684 10.4659 6.47277Z" fill="currentColor"></path>
</svg>
}
href="/integrations/agentops"
>
Monitor and analyze Mem0 operations with comprehensive AI agent analytics and LLM observability.
</Card>
<Card
title="LangChain"
icon={
@@ -305,6 +322,7 @@ Here are the available integrations for Mem0:
>
Build autonomous agents with memory using Agno framework.
</Card>
<Card
title="Keywords AI"
icon={
+172
View File
@@ -0,0 +1,172 @@
---
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.
## Overview
1. Automatic monitoring of Mem0 operations and performance metrics
2. Real-time tracking of memory add, search, and retrieval operations
3. Analytics dashboard with memory usage patterns and insights
4. Error tracking and debugging capabilities for memory operations
## Prerequisites
Before setting up Mem0 with AgentOps, ensure you have:
1. Installed the required packages:
```bash
pip install mem0ai agentops
```
2. Valid API keys:
- [AgentOps API Key](https://app.agentops.ai/dashboard/api-keys)
- OpenAI API Key (for LLM operations)
- [Mem0 API Key](https://app.mem0.ai/dashboard/api-keys) (optional, for cloud operations)
## Basic Integration Example
The following example demonstrates how to integrate Mem0 with AgentOps monitoring for comprehensive memory operation tracking:
```python
#Import the required libraries for local memory management with Mem0
from mem0 import Memory, AsyncMemory
import os
import asyncio
import logging
from dotenv import load_dotenv
import agentops
#Set up environment variables for API keys
os.environ["AGENTOPS_API_KEY"] = os.getenv("AGENTOPS_API_KEY")
os.environ["OPENAI_API_KEY"] = os.getenv("OPENAI_API_KEY")
#Set up the configuration for local memory storage and define sample user data.
local_config = {
"llm": {
"provider": "openai",
"config": {
"model": "gpt-4o-mini",
"temperature": 0.1,
"max_tokens": 2000,
},
}
}
user_id = "alice_demo"
agent_id = "assistant_demo"
run_id = "session_001"
sample_messages = [
{"role": "user", "content": "I'm planning to watch a movie tonight. Any recommendations?"},
{"role": "assistant", "content": "How about a thriller? They can be quite engaging."},
{"role": "user", "content": "I'm not a big fan of thriller movies but I love sci-fi movies."},
{
"role": "assistant",
"content": "Got it! I'll avoid thriller recommendations and suggest sci-fi movies in the future.",
},
]
sample_preferences = [
"I prefer dark roast coffee over light roast",
"I exercise every morning at 6 AM",
"I'm vegetarian and avoid all meat products",
"I love reading science fiction novels",
"I work in software engineering",
]
#This function demonstrates sequential memory operations using the synchronous Memory class
def demonstrate_sync_memory(local_config, sample_messages, sample_preferences, user_id):
"""
Demonstrate synchronous Memory class operations.
"""
agentops.start_trace("mem0_memory_example", tags=["mem0_memory_example"])
try:
memory = Memory.from_config(local_config)
result = memory.add(
sample_messages, user_id=user_id, metadata={"category": "movie_preferences", "session": "demo"}
)
for i, preference in enumerate(sample_preferences):
result = memory.add(preference, user_id=user_id, metadata={"type": "preference", "index": i})
search_queries = [
"What movies does the user like?",
"What are the user's food preferences?",
"When does the user exercise?",
]
for query in search_queries:
results = memory.search(query, user_id=user_id)
if results and "results" in results:
for j, result in enumerate(results['results']):
print(f"Result {j+1}: {result.get('memory', 'N/A')}")
else:
print("No results found")
all_memories = memory.get_all(user_id=user_id)
if all_memories and "results" in all_memories:
print(f"Total memories: {len(all_memories['results'])}")
delete_all_result = memory.delete_all(user_id=user_id)
print(f"Delete all result: {delete_all_result}")
agentops.end_trace(end_state="success")
except Exception as e:
agentops.end_trace(end_state="error")
# Execute sync demonstrations
demonstrate_sync_memory(local_config, sample_messages, sample_preferences, user_id)
```
For detailed information on this integration, refer to the official [Agentops Mem0 integration documentation](https://docs.agentops.ai/v2/integrations/mem0).
## Key Features
### 1. Automatic Operation Tracking
AgentOps automatically monitors all Mem0 operations:
- **Memory Operations**: Track add, search, get_all, delete operations and much more
- **Performance Metrics**: Monitor response times and success rates
- **Error Tracking**: Capture and analyze operation failures
### 2. Real-time Analytics Dashboard
Access comprehensive analytics through the AgentOps dashboard:
- **Usage Patterns**: Visualize memory usage trends over time
- **User Behavior**: Analyze how different users interact with memory
- **Performance Insights**: Identify bottlenecks and optimization opportunities
### 3. Session Management
Organize your monitoring with structured sessions:
- **Session Tracking**: Group related operations into logical sessions
- **Success/Failure Rates**: Track session outcomes for reliability monitoring
- **Custom Metadata**: Add context to sessions for better analysis
## Best Practices
1. **Initialize Early**: Always initialize AgentOps before importing Mem0 classes
2. **Session Management**: Use meaningful session names and end sessions appropriately
3. **Error Handling**: Wrap operations in try-catch blocks and report failures
4. **Tagging**: Use tags to organize different types of memory operations
5. **Environment Separation**: Use different projects or tags for dev/staging/prod
## Help & Resources
- [AgentOps Documentation](https://docs.agentops.ai/)
- [AgentOps Dashboard](https://app.agentops.ai/)
- [Mem0 Platform](https://app.mem0.ai/)
<Snippet file="get-help.mdx" />
+40 -10
View File
@@ -1,16 +1,18 @@
---
title: Agno
---
<Snippet file="paper-release.mdx" />
<Snippet file="blank-notif.mdx" />
Integrate [**Mem0**](https://github.com/mem0ai/mem0) with [Agno](https://github.com/agno-agi/agno), a Python framework for building autonomous agents. This integration enables Agno agents to access persistent memory across conversations, enhancing context retention and personalization.
This integration of [**Mem0**](https://github.com/mem0ai/mem0) with [Agno](https://github.com/agno-agi/agno, enables persistent, multimodal memory for Agno-based agents - improving personalization, context awareness, and continuity across conversations.
## Overview
1. 🧠 Store and retrieve memories from Mem0 within Agno agents
2. 🖼️ Support for multimodal interactions (text and images)
3. 🔍 Semantic search for relevant past conversations
4. 🌐 Personalized responses based on user history
1. Store and retrieve memories from Mem0 within Agno agents
2. Support for multimodal interactions (text and images)
3. Semantic search for relevant past conversations
4. Personalized responses based on user history
5. One-line memory integration via `Mem0Tools`
## Prerequisites
@@ -18,14 +20,41 @@ Before setting up Mem0 with Agno, ensure you have:
1. Installed the required packages:
```bash
pip install agno-ai mem0ai
pip install agno mem0ai
```
2. Valid API keys:
- [Mem0 API Key](https://app.mem0.ai/dashboard/api-keys)
- OpenAI API Key (for the agent model)
## Integration Example
## Quick Integration (Using `Mem0Tools`)
The simplest way to integrate Mem0 with Agno Agents is to use Mem0 as a tool using built-in `Mem0Tools`:
```python
from agno.agent import Agent
from agno.models.openai import OpenAIChat
from agno.tools.mem0 import Mem0Tools
agent = Agent(
name="Memory Agent",
model=OpenAIChat(id="gpt-4o-mini"),
tools=[Mem0Tools()],
description="An assistant that remembers and personalizes using Mem0 memory."
)
```
This enables memory functionality out of the box:
- **Persistent memory writing**: `Mem0Tools` uses `MemoryClient.add(...)` to store messages from user-agent interactions, including optional metadata such as user ID or session.
- **Contextual memory search**: Compatible queries use `MemoryClient.search(...)` to retrieve relevant past messages, improving contextual understanding.
- **Multimodal support**: Both text and image inputs are supported, allowing richer memory records.
> `Mem0Tools` uses the `MemoryClient` under the hood and requires no additional setup. You can customize its behavior by modifying your tools list or extending it in code.
## Full Manual Example
> Note: Mem0 can also be used with Agno Agents as a separate memory layer.
The following example demonstrates how to create an Agno agent with Mem0 memory integration, including support for image processing:
@@ -39,7 +68,6 @@ from agno.media import Image
from agno.models.openai import OpenAIChat
from mem0 import MemoryClient
# Initialize the Mem0 client
client = MemoryClient()
@@ -100,7 +128,7 @@ def chat_user(
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)
memory_context = "\n".join(f"- {m['memory']}" for m in memories.get('results', []))
# Construct the prompt
prompt = f"""
@@ -162,6 +190,8 @@ Improve your agent's context awareness:
Customize the integration to your needs:
- **Use `Mem0Tools()`** for drop-in memory support
- **Use `MemoryClient` directly** for advanced control
- **User Identification**: Organize memories by user ID
- **Memory Search**: Configure search relevance and result count
- **Memory Formatting**: Support for various OpenAI message formats
+3 -3
View File
@@ -1,6 +1,6 @@
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.
<Snippet file="paper-release.mdx" />
<Snippet file="blank-notif.mdx" />
## Overview
@@ -68,7 +68,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)
context = "\n".join([m["memory"] for m in relevant_memories])
context = "\n".join([m["memory"] for m in relevant_memories.get('results', [])])
prompt = f"""Answer the user question considering the previous interactions:
Previous interactions:
@@ -100,7 +100,7 @@ manager = ConversableAgent(
def escalate_to_manager(question):
relevant_memories = memory_client.search(question, user_id=USER_ID)
context = "\n".join([m["memory"] for m in relevant_memories])
context = "\n".join([m["memory"] for m in relevant_memories.get('results', [])])
prompt = f"""
Context from previous interactions:
+132
View File
@@ -0,0 +1,132 @@
---
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
In this guide, you'll:
1. Configure AWS credentials to enable Bedrock and OpenSearch access
2. Set up the Mem0 SDK to use Bedrock for embeddings and LLM
3. Store and retrieve memories using OpenSearch as a vector store
4. Build memory-aware applications with scalable cloud infrastructure
## Prerequisites
- AWS account with access to:
- Bedrock foundation models (e.g., Titan, Claude)
- OpenSearch Service with a configured domain
- Python 3.8+
- Valid AWS credentials (via environment or IAM role)
## Setup and Installation
Install required packages:
```bash
pip install mem0ai boto3 opensearch-py
```
Set environment variables:
Be sure to configure your AWS credentials using environment variables, IAM roles, or the AWS CLI.
```python
import os
os.environ['AWS_REGION'] = 'us-west-2'
os.environ['AWS_ACCESS_KEY_ID'] = 'AKIA...'
os.environ['AWS_SECRET_ACCESS_KEY'] = 'AS...'
```
## Initialize Mem0 Integration
Import necessary modules and configure Mem0:
```python
import boto3
from opensearchpy import OpenSearch, RequestsHttpConnection, AWSV4SignerAuth
from mem0.memory.main import Memory
region = 'us-west-2'
service = 'aoss'
credentials = boto3.Session().get_credentials()
auth = AWSV4SignerAuth(credentials, region, service)
config = {
"embedder": {
"provider": "aws_bedrock",
"config": {
"model": "amazon.titan-embed-text-v2:0"
}
},
"llm": {
"provider": "aws_bedrock",
"config": {
"model": "anthropic.claude-3-5-haiku-20241022-v1:0",
"temperature": 0.1,
"max_tokens": 2000
}
},
"vector_store": {
"provider": "opensearch",
"config": {
"collection_name": "mem0",
"host": "your-opensearch-domain.us-west-2.es.amazonaws.com",
"port": 443,
"http_auth": auth,
"embedding_model_dims": 1024,
"connection_class": RequestsHttpConnection,
"pool_maxsize": 20,
"use_ssl": True,
"verify_certs": True
}
}
}
# Initialize memory system
m = Memory.from_config(config)
```
## Memory Operations
Use Mem0 with your Bedrock-powered LLM and OpenSearch storage backend:
```python
# Store conversational context
messages = [
{"role": "user", "content": "I'm planning to watch a movie tonight. Any recommendations?"},
{"role": "assistant", "content": "How about a thriller?"},
{"role": "user", "content": "I prefer sci-fi."},
{"role": "assistant", "content": "Noted! I'll suggest sci-fi movies next time."}
]
m.add(messages, user_id="alice", metadata={"category": "movie_recommendations"})
# Search for memory
relevant = m.search("What kind of movies does Alice like?", user_id="alice")
# Retrieve all user memories
all_memories = m.get_all(user_id="alice")
```
## Key Features
1. **Serverless Memory Embeddings**: Use Titan or other Bedrock models for fast, cloud-native embeddings
2. **Scalable Vector Search**: Store and retrieve vectorized memories via OpenSearch
3. **Seamless AWS Auth**: Uses AWS IAM or environment variables to securely authenticate
4. **User-specific Memory Spaces**: Memories are isolated per user ID
5. **Persistent Memory Context**: Maintain and recall history across sessions
## Help
- [AWS Bedrock Documentation](https://docs.aws.amazon.com/bedrock/)
- [Amazon OpenSearch Service Docs](https://docs.aws.amazon.com/opensearch-service/)
- [Mem0 Platform](https://app.mem0.ai)
<Snippet file="get-help.mdx" />
+3 -3
View File
@@ -2,7 +2,7 @@
title: CrewAI
---
<Snippet file="paper-release.mdx" />
<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.
@@ -164,7 +164,7 @@ By combining CrewAI with Mem0, you can create sophisticated AI systems that main
## Help
- For CrewAI documentation, visit [CrewAI Documentation](https://docs.crewai.com/)
- For Mem0 documentation, refer to the [Mem0 Platform](https://app.mem0.ai/)
- [CrewAI Documentation](https://docs.crewai.com/)
- [Mem0 Platform](https://app.mem0.ai/)
<Snippet file="get-help.mdx" />
+1 -1
View File
@@ -2,7 +2,7 @@
title: Dify
---
<Snippet file="paper-release.mdx" />
<Snippet file="blank-notif.mdx" />
# Integrating Mem0 with Dify AI
+2 -2
View File
@@ -2,7 +2,7 @@
title: ElevenLabs
---
<Snippet file="paper-release.mdx" />
<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.
@@ -152,7 +152,7 @@ Define the two key memory functions that will be registered as tools:
)
# Extract and join the memory texts
memories = ' '.join([result["memory"] for result in results])
memories = ' '.join([result["memory"] for result in results.get('results', [])])
print("[ Memories ]", memories)
if memories:
+1 -1
View File
@@ -2,7 +2,7 @@
title: Flowise
---
<Snippet file="paper-release.mdx" />
<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.
+284
View File
@@ -0,0 +1,284 @@
---
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
1. Store and retrieve memories from Mem0 within Google ADK agents
2. Multi-agent workflows with shared memory across hierarchies
3. Retrieve relevant memories from past conversations
4. Personalized responses
## Prerequisites
Before setting up Mem0 with Google ADK, ensure you have:
1. Installed the required packages:
```bash
pip install google-adk mem0ai
```
2. Valid API keys:
- [Mem0 API Key](https://app.mem0.ai/dashboard/api-keys)
- Google AI Studio API Key
## Basic Integration Example
The following example demonstrates how to create a Google ADK agent with Mem0 memory integration:
```python
import os
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
# Set up environment variables
os.environ["GOOGLE_API_KEY"] = "your-google-api-key"
os.environ["MEM0_API_KEY"] = "your-mem0-api-key"
# Initialize Mem0 client
mem0 = MemoryClient()
# Define memory function tools
def search_memory(query: str, user_id: str) -> dict:
"""Search through past conversations and memories"""
memories = mem0.search(query, user_id=user_id)
if memories.get('results', []):
memory_context = "\n".join([f"- {mem['memory']}" for mem in memories.get('results', [])])
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"}
except Exception as e:
return {"status": "error", "message": f"Failed to save memory: {str(e)}"}
# Create agent with memory capabilities
personal_assistant = Agent(
name="personal_assistant",
model="gemini-2.0-flash",
instruction="""You are a helpful personal assistant with memory capabilities.
Use the search_memory function to recall past conversations and user preferences.
Use the save_memory function to store important information about the user.
Always personalize your responses based on available memory.""",
description="A personal assistant that remembers user preferences and past interactions",
tools=[search_memory, save_memory]
)
def chat_with_agent(user_input: str, user_id: str) -> str:
"""
Handle user input with automatic memory integration.
Args:
user_input: The user's message
user_id: Unique identifier for the user
Returns:
The agent's response
"""
# Set up session and runner
session_service = InMemorySessionService()
session = session_service.create_session(
app_name="memory_assistant",
user_id=user_id,
session_id=f"session_{user_id}"
)
runner = Runner(agent=personal_assistant, app_name="memory_assistant", session_service=session_service)
# Create content and run agent
content = types.Content(role='user', parts=[types.Part(text=user_input)])
events = runner.run(user_id=user_id, session_id=session.id, new_message=content)
# Extract final response
for event in events:
if event.is_final_response():
response = event.content.parts[0].text
return response
return "No response generated"
# Example usage
if __name__ == "__main__":
response = chat_with_agent(
"I love Italian food and I'm planning a trip to Rome next month",
user_id="alice"
)
print(response)
```
## Multi-Agent Hierarchy with Shared Memory
Create specialized agents in a hierarchy that share memory:
```python
from google.adk.tools.agent_tool import AgentTool
# Travel specialist agent
travel_agent = Agent(
name="travel_specialist",
model="gemini-2.0-flash",
instruction="""You are a travel planning specialist. Use get_user_context to
understand the user's travel preferences and history before making recommendations.
After providing advice, use store_interaction to save travel-related information.""",
description="Specialist in travel planning and recommendations",
tools=[search_memory, save_memory]
)
# Health advisor agent
health_agent = Agent(
name="health_advisor",
model="gemini-2.0-flash",
instruction="""You are a health and wellness advisor. Use get_user_context to
understand the user's health goals and dietary preferences.
After providing advice, use store_interaction to save health-related information.""",
description="Specialist in health and wellness advice",
tools=[search_memory, save_memory]
)
# Coordinator agent that delegates to specialists
coordinator_agent = Agent(
name="coordinator",
model="gemini-2.0-flash",
instruction="""You are a coordinator that delegates requests to specialist agents.
For travel-related questions (trips, hotels, flights, destinations), delegate to the travel specialist.
For health-related questions (fitness, diet, wellness, exercise), delegate to the health advisor.
Use get_user_context to understand the user before delegation.""",
description="Coordinates requests between specialist agents",
tools=[
AgentTool(agent=travel_agent, skip_summarization=False),
AgentTool(agent=health_agent, skip_summarization=False)
]
)
def chat_with_specialists(user_input: str, user_id: str) -> str:
"""
Handle user input with specialist agent delegation and memory.
Args:
user_input: The user's message
user_id: Unique identifier for the user
Returns:
The specialist agent's response
"""
session_service = InMemorySessionService()
session = session_service.create_session(
app_name="specialist_system",
user_id=user_id,
session_id=f"session_{user_id}"
)
runner = Runner(agent=coordinator_agent, app_name="specialist_system", session_service=session_service)
content = types.Content(role='user', parts=[types.Part(text=user_input)])
events = runner.run(user_id=user_id, session_id=session.id, new_message=content)
for event in events:
if event.is_final_response():
response = event.content.parts[0].text
# Store the conversation in shared memory
conversation = [
{"role": "user", "content": user_input},
{"role": "assistant", "content": response}
]
mem0.add(conversation, user_id=user_id)
return response
return "No response generated"
# Example usage
response = chat_with_specialists("Plan a healthy meal for my Italy trip", user_id="alice")
print(response)
```
## Quick Start Chat Interface
Simple interactive chat with memory and Google ADK:
```python
def interactive_chat():
"""Interactive chat interface with memory and ADK"""
user_id = input("Enter your user ID: ") or "demo_user"
print(f"Chat started for user: {user_id}")
print("Type 'quit' to exit")
print("=" * 50)
while True:
user_input = input("\nYou: ")
if user_input.lower() == 'quit':
print("Goodbye! Your conversation has been saved to memory.")
break
else:
response = chat_with_specialists(user_input, user_id)
print(f"Assistant: {response}")
if __name__ == "__main__":
interactive_chat()
```
## Key Features
### 1. Memory-Enhanced Function Tools
- **Function Tools**: Standard Python functions that can search and save memories
- **Tool Context**: Access to session state and memory through function parameters
- **Structured Returns**: Dictionary-based returns with status indicators for better LLM understanding
### 2. Multi-Agent Memory Sharing
- **Agent-as-a-Tool**: Specialists can be called as tools while maintaining shared memory
- **Hierarchical Delegation**: Coordinator agents route to specialists based on context
- **Memory Categories**: Store interactions with metadata for better organization
### 3. Flexible Memory Operations
- **Search Capabilities**: Retrieve relevant memories through conversation history
- **User Segmentation**: Organize memories by user ID
- **Memory Management**: Built-in tools for saving and retrieving information
## Configuration Options
Customize memory behavior and agent setup:
```python
# Configure memory search with metadata
memories = mem0.search(
query="travel preferences",
user_id="alice",
limit=5,
filters={"category": "travel"} # Filter by category if supported
)
# Configure agent with custom model settings
agent = Agent(
name="custom_agent",
model="gemini-2.0-flash", # or use LiteLLM for other models
instruction="Custom agent behavior",
tools=[memory_tools],
# Additional ADK configurations
)
# Use Google Cloud Vertex AI instead of AI Studio
os.environ["GOOGLE_GENAI_USE_VERTEXAI"] = "True"
os.environ["GOOGLE_CLOUD_PROJECT"] = "your-project-id"
os.environ["GOOGLE_CLOUD_LOCATION"] = "us-central1"
```
## Help
- [Google ADK Documentation](https://google.github.io/adk-docs/)
- [Mem0 Platform](https://app.mem0.ai/)
- If you need further assistance, please feel free to reach out to us through the following methods:
<Snippet file="get-help.mdx" />
+3 -3
View File
@@ -2,7 +2,7 @@
title: Keywords AI
---
<Snippet file="paper-release.mdx" />
<Snippet file="blank-notif.mdx" />
Build AI applications with persistent memory and comprehensive LLM observability by integrating Mem0 with Keywords AI.
@@ -135,8 +135,8 @@ Integrating Mem0 with Keywords AI provides a powerful combination for building A
## Help
For more information on using Mem0 and Keywords AI together, refer to:
- [Mem0 Documentation](https://docs.mem0.ai)
For more information, refer to:
- [Keywords AI Documentation](https://docs.keywordsai.co)
- [Mem0 Platform]((https://app.mem0.ai/))
<Snippet file="get-help.mdx" />
+1 -1
View File
@@ -3,7 +3,7 @@ title: Langchain Tools
description: 'Integrate Mem0 with LangChain tools to enable AI agents to store, search, and manage memories through structured interfaces'
---
<Snippet file="paper-release.mdx" />
<Snippet file="blank-notif.mdx" />
## Overview
+4 -4
View File
@@ -2,7 +2,7 @@
title: Langchain
---
<Snippet file="paper-release.mdx" />
<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.
@@ -64,11 +64,11 @@ Create functions to handle context retrieval, response generation, and addition
def retrieve_context(query: str, user_id: str) -> List[Dict]:
"""Retrieve relevant context from Mem0"""
memories = mem0.search(query, user_id=user_id)
seralized_memories = ' '.join([mem["memory"] for mem in memories])
serialized_memories = ' '.join([mem["memory"] for mem in memories.get('results', [])])
context = [
{
"role": "system",
"content": f"Relevant information: {seralized_memories}"
"content": f"Relevant information: {serialized_memories}"
},
{
"role": "user",
@@ -152,7 +152,7 @@ By integrating LangChain with Mem0, you can build a personalized Travel Agent AI
## Help
- For more details on LangChain, visit the [LangChain documentation](https://python.langchain.com/).
- For Mem0 documentation, refer to the [Mem0 Platform](https://app.mem0.ai/).
- [Mem0 Platform](https://app.mem0.ai/).
- If you need further assistance, please feel free to reach out to us through the following methods:
<Snippet file="get-help.mdx" />
+3 -3
View File
@@ -2,7 +2,7 @@
title: LangGraph
---
<Snippet file="paper-release.mdx" />
<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.
@@ -68,7 +68,7 @@ def chatbot(state: State):
memories = mem0.search(messages[-1].content, user_id=user_id)
context = "Relevant information from previous conversations:\n"
for memory in memories:
for memory in memories.get('results', []):
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.
@@ -140,7 +140,7 @@ By integrating LangGraph with Mem0, you can build a personalized Customer Suppor
## Help
- For more details on LangGraph, visit the [LangChain documentation](https://python.langchain.com/docs/langgraph).
- For Mem0 documentation, refer to the [Mem0 Platform](https://app.mem0.ai/).
- [Mem0 Platform](https://app.mem0.ai/).
- If you need further assistance, please feel free to reach out to us through following methods:
<Snippet file="get-help.mdx" />
+107 -252
View File
@@ -2,7 +2,7 @@
title: Livekit
---
<Snippet file="paper-release.mdx" />
<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.
@@ -12,10 +12,12 @@ Before you begin, make sure you have:
1. Installed Livekit Agents SDK with voice dependencies of silero and deepgram:
```bash
pip install livekit-agents[voice] \
pip install livekit livekit-agents \
livekit-plugins-silero \
livekit-plugins-deepgram \
livekit-plugins-openai
livekit-plugins-openai \
livekit-plugins-turn-detector \
livekit-plugins-noise-cancellation
```
2. Installed Mem0 SDK:
@@ -42,284 +44,123 @@ Let's break down the key components of this implementation using LiveKit Agents:
### 1. Setting Up Dependencies and Environment
```python
import asyncio
import logging
import os
from typing import List, Dict, Any, Annotated
import aiohttp
import logging
from pathlib import Path
from dotenv import load_dotenv
from mem0 import AsyncMemoryClient
from livekit.agents import (
JobContext,
WorkerOptions,
cli,
ChatContext,
ChatMessage,
RoomInputOptions,
Agent,
AgentSession,
AutoSubscribe,
JobContext,
llm,
function_tool,
RunContext,
cli,
WorkerOptions,
ModelSettings,
)
from livekit.plugins import deepgram, openai, silero
from livekit.plugins.turn_detector.multilingual import MultilingualModel
from mem0 import AsyncMemoryClient
from livekit.plugins import openai, silero, deepgram, noise_cancellation
from livekit.plugins.turn_detector.english import EnglishModel
# Load environment variables
load_dotenv()
# Configure logging
logger = logging.getLogger("memory-assistant")
logger.setLevel(logging.INFO)
# Define a global user ID for simplicity
USER_ID = "voice_user"
# Initialize Mem0 client
mem0 = AsyncMemoryClient()
```
This section handles:
- Importing required modules
- Loading environment variables
- Setting up logging
- Extracting user identification
- Initializing the Mem0 client
### 2. Memory Enrichment Function
### 2. Mem0 Client and Agent Definition
```python
async def _enrich_with_memory(chat_ctx: llm.ChatContext):
"""Add memories and augment chat context with relevant memories"""
if not chat_ctx.messages:
return
# Get the latest user message
user_msg = chat_ctx.messages[-1]
if user_msg.role != "user":
return
user_content = user_msg.text_content()
if not user_content:
return
# Store user message in Mem0
await mem0.add(
[{"role": "user", "content": user_content}],
user_id=USER_ID
)
# Search for relevant memories
results = await mem0.search(
user_content,
user_id=USER_ID,
)
# Augment context with retrieved memories
if results:
memories = ' '.join([result["memory"] for result in results])
logger.info(f"Enriching with memory: {memories}")
# Add memory context as a assistant message
memory_msg = llm.ChatMessage.create(
text=f"Relevant Memory: {memories}\n",
role="assistant",
)
# Modify chat context with retrieved memories
chat_ctx.messages[-1] = memory_msg
chat_ctx.messages.append(user_msg)
```
This function:
- Stores user messages in Mem0
- Performs semantic search for relevant memories
- Augments the chat context with retrieved memories
- Enables contextually aware responses
### 3. Prewarm and Entrypoint Functions
```python
def prewarm_process(proc):
"""Preload components to speed up session start"""
proc.userdata["vad"] = silero.VAD.load()
async def entrypoint(ctx: JobContext):
"""Main entrypoint for the memory-enabled voice agent"""
# Connect to LiveKit room
await ctx.connect(auto_subscribe=AutoSubscribe.AUDIO_ONLY)
# Create agent session with modern 1.0 architecture
session = AgentSession(
stt=deepgram.STT(),
llm=openai.LLM(model="gpt-4o-mini"),
tts=openai.TTS(),
vad=silero.VAD.load(),
turn_detection=MultilingualModel(),
)
# Create memory-enabled agent
agent = MemoryEnabledAgent()
# Start the session
await session.start(
room=ctx.room,
agent=agent,
)
# Initial greeting
await session.generate_reply(
instructions="Greet the user warmly as George the travel guide and ask how you can help them plan their next adventure."
)
```
The entrypoint function:
- Connects to LiveKit room
- Initializes Mem0 memory client
- Create agent session using `AgentSession` orchestrator with memory enrichment
- Uses modern turn detection with `MultilingualModel()`
- Starts the agent with an initial greeting
## Create a Memory-Enabled Voice Agent
Now that we've explained each component, here's the complete implementation that combines OpenAI Agents SDK for voice with Mem0's memory capabilities:
```python
import asyncio
import logging
import os
from typing import AsyncIterable, Any
from dotenv import load_dotenv
from livekit.agents import (
Agent,
AgentSession,
JobContext,
llm,
function_tool,
RunContext,
cli,
WorkerOptions,
ModelSettings,
)
from livekit.plugins import deepgram, openai, silero
from livekit.plugins.turn_detector.multilingual import MultilingualModel
from mem0 import AsyncMemoryClient
# Load environment variables
load_dotenv()
# Configure logging
logger = logging.getLogger("memory-assistant")
logger.setLevel(logging.INFO)
# Define a global user ID for simplicity
USER_ID = "voice_user"
# Initialize Mem0 memory client
mem0 = AsyncMemoryClient()
# User ID for RAG data in Mem0
RAG_USER_ID = "livekit-mem0"
mem0_client = AsyncMemoryClient()
class MemoryEnabledAgent(Agent):
"""Travel guide agent with Mem0 memory integration"""
def __init__(self):
"""
An agent that can answer questions using RAG (Retrieval Augmented Generation) with Mem0.
"""
def __init__(self) -> None:
super().__init__(
instructions="""
You are a helpful voice assistant.
You are a travel guide named George and will help the user to plan a travel trip of their dreams.
You should help the user plan for various adventures like work retreats, family vacations or solo backpacking trips.
You should be careful to not suggest anything that would be dangerous, illegal or inappropriate.
You can remember past interactions and use them to inform your answers.
Use semantic memory retrieval to provide contextually relevant responses.
"""
You are a helpful voice assistant.
You are a travel guide named George and will help the user to plan a travel trip of their dreams.
You should help the user plan for various adventures like work retreats, family vacations or solo backpacking trips.
You should be careful to not suggest anything that would be dangerous, illegal or inappropriate.
You can remember past interactions and use them to inform your answers.
Use semantic memory retrieval to provide contextually relevant responses.
""",
)
self._seen_results = set() # Track previously seen result IDs
logger.info(f"Mem0 Agent initialized. Using user_id: {RAG_USER_ID}")
async def on_enter(self):
self.session.generate_reply(
instructions="Briefly greet the user and offer your assistance."
)
async def llm_node(
self,
chat_ctx: llm.ChatContext,
tools: list[llm.FunctionTool],
model_settings: ModelSettings,
) -> AsyncIterable[llm.ChatChunk]:
"""Override LLM node to add memory enrichment before inference"""
# Enrich context with memory before LLM inference
await self._enrich_with_memory(chat_ctx)
# Call default LLM node with enriched context
async for chunk in Agent.default.llm_node(self, chat_ctx, tools, model_settings):
yield chunk
async def _enrich_with_memory(self, chat_ctx: llm.ChatContext):
"""Add memories and augment chat context with relevant memories"""
if not chat_ctx.messages:
return
# Get the latest user message
user_msg = chat_ctx.messages[-1]
if user_msg.role != "user":
return
user_content = user_msg.text_content()
if not user_content:
return
# Store user message in Mem0
await mem0.add(
[{"role": "user", "content": user_content}],
user_id=USER_ID
)
# Search for relevant memories
results = await mem0.search(
user_content,
user_id=USER_ID,
)
# Augment context with retrieved memories
if results:
memories = ' '.join([result["memory"] for result in results])
logger.info(f"Enriching with memory: {memories}")
# Add memory context as a assistant message
memory_msg = llm.ChatMessage.create(
text=f"Relevant Memory: {memories}\n",
role="assistant",
async def on_user_turn_completed(self, turn_ctx: ChatContext, new_message: ChatMessage) -> None:
# Persist the user message in Mem0
try:
logger.info(f"Adding user message to Mem0: {new_message.text_content}")
add_result = await mem0_client.add(
[{"role": "user", "content": new_message.text_content}],
user_id=RAG_USER_ID
)
logger.info(f"Mem0 add result (user): {add_result}")
except Exception as e:
logger.warning(f"Failed to store user message in Mem0: {e}")
# Modify chat context with retrieved memories
chat_ctx.messages[-1] = memory_msg
chat_ctx.messages.append(user_msg)
# RAG: Retrieve relevant context from Mem0 and inject as assistant message
try:
logger.info("About to await mem0_client.search for RAG context")
search_results = await mem0_client.search(
new_message.text_content,
user_id=RAG_USER_ID,
)
logger.info(f"mem0_client.search returned: {search_results}")
if search_results and search_results.get('results', []):
context_parts = []
for result in search_results.get('results', []):
paragraph = result.get("memory") or result.get("text")
if paragraph:
source = "mem0 Memories"
if "from [" in paragraph:
source = paragraph.split("from [")[1].split("]")[0]
paragraph = paragraph.split("]")[1].strip()
context_parts.append(f"Source: {source}\nContent: {paragraph}\n")
if context_parts:
full_context = "\n\n".join(context_parts)
logger.info(f"Injecting RAG context: {full_context}")
turn_ctx.add_message(role="assistant", content=full_context)
await self.update_chat_ctx(turn_ctx)
except Exception as e:
logger.warning(f"Failed to inject RAG context from Mem0: {e}")
def prewarm_process(proc):
"""Preload components to speed up session start"""
proc.userdata["vad"] = silero.VAD.load()
await super().on_user_turn_completed(turn_ctx, new_message)
```
### 3. Entrypoint and Session Setup
```python
async def entrypoint(ctx: JobContext):
"""Main entrypoint for the memory-enabled voice agent"""
"""Main entrypoint for the agent."""
await ctx.connect()
# Connect to LiveKit room
await ctx.connect(auto_subscribe=AutoSubscribe.AUDIO_ONLY)
# Initialize Mem0 client
mem0 = AsyncMemoryClient()
# Create agent session with modern 1.0 architecture
session = AgentSession(
stt=deepgram.STT(),
llm=openai.LLM(model="gpt-4o-mini"),
tts=openai.TTS(),
tts=openai.TTS(voice="ash",),
turn_detection=EnglishModel(),
vad=silero.VAD.load(),
turn_detection=MultilingualModel(),
)
# Create memory-enabled agent
agent = MemoryEnabledAgent()
# Start the session
await session.start(
agent=MemoryEnabledAgent(),
room=ctx.room,
agent=agent,
room_input_options=RoomInputOptions(
noise_cancellation=noise_cancellation.BVC(),
),
)
# Initial greeting
@@ -330,10 +171,7 @@ async def entrypoint(ctx: JobContext):
# Run the application
if __name__ == "__main__":
cli.run_app(WorkerOptions(
entrypoint_fnc=entrypoint,
prewarm_fnc=prewarm_process
))
cli.run_app(WorkerOptions(entrypoint_fnc=entrypoint))
```
## Key Features of This Implementation
@@ -355,6 +193,11 @@ To run this example:
```sh
python mem0-livekit-voice-agent.py start
```
or to start your agent in console mode to run inside your terminal:
```sh
python mem0-livekit-voice-agent.py console
```
5. After the script starts, you can interact with the voice agent using [Livekit's Agent Platform](https://agents-playground.livekit.io/) and connect to the agent inorder to start conversations.
## Best Practices for Voice Agents with Memory
@@ -382,4 +225,16 @@ logging.basicConfig(
format='%(asctime)s - %(name)s - %(levelname)s - %(message)s'
)
logger = logging.getLogger("memory_voice_agent")
```
```
- Check the logs for any issues with API keys, connectivity, or memory operations.
- Ensure your `.env` file is correctly configured and loaded.
## Help & Resources
- [LiveKit Documentation](https://docs.livekit.io/)
- [Mem0 Platform](https://app.mem0.ai/)
- Need assistance? Reach out through:
<Snippet file="get-help.mdx" />
+4 -4
View File
@@ -2,7 +2,7 @@
title: LlamaIndex
---
<Snippet file="paper-release.mdx" />
<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.
@@ -63,7 +63,7 @@ context = {
Set your Mem0 OSS by providing configuration details:
<Note type="info">
To know more about Mem0 OSS, read [Mem0 OSS Quickstart](https://docs.mem0.ai/open-source/quickstart).
To know more about Mem0 OSS, read [Mem0 OSS Quickstart](https://docs.mem0.ai/open-source/overview).
</Note>
```python
@@ -103,7 +103,7 @@ memory_from_config = Mem0Memory.from_config(
)
```
Intilaize the LLM
Initialize the LLM
```python
import os
@@ -202,7 +202,7 @@ By integrating LlamaIndex with Mem0, you can build a personalized agent that can
## Help
- For more details on LlamaIndex, visit the [LlamaIndex documentation](https://llamahub.ai/l/memory/llama-index-memory-mem0).
- For Mem0 documentation, refer to the [Mem0 Platform](https://app.mem0.ai/).
- [Mem0 Platform](https://app.mem0.ai/).
- If you need further assistance, please feel free to reach out to us through following methods:
<Snippet file="get-help.mdx" />
+2 -2
View File
@@ -2,7 +2,7 @@
title: Mastra
---
<Snippet file="paper-release.mdx" />
<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.
@@ -130,7 +130,7 @@ By integrating Mastra with Mem0, you can build intelligent agents that learn and
## Help
- For more details on Mastra, visit the [Mastra documentation](https://docs.mastra.ai/).
- For Mem0 documentation, refer to the [Mem0 Platform](https://app.mem0.ai/).
- [Mem0 Platform](https://app.mem0.ai/).
- If you need further assistance, please feel free to reach out to us through the following methods:
<Snippet file="get-help.mdx" />
+1 -1
View File
@@ -2,7 +2,7 @@
title: MCP Server
---
<Snippet file="paper-release.mdx" />
<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.
+4 -4
View File
@@ -2,7 +2,7 @@
title: MultiOn
---
<Snippet file="paper-release.mdx" />
<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.
@@ -71,7 +71,7 @@ Define search command and retrieve relevant memories from Mem0.
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['text'] for mem in relevant_memories)
relevant_memories_text = '\n'.join(mem['memory'] for mem in relevant_memories['results'])
print(f"Relevant memories:")
print(relevant_memories_text)
```
@@ -98,9 +98,9 @@ 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:
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)
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}"
+236
View File
@@ -0,0 +1,236 @@
---
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. Store and retrieve memories from Mem0 within OpenAI agents
2. Multi-agent workflows with shared memory
3. Retrieve relevant memories for past conversations
4. Personalized responses based on user history
## Prerequisites
Before setting up Mem0 with OpenAI Agents SDK, ensure you have:
1. Installed the required packages:
```bash
pip install openai-agents mem0ai
```
2. Valid API keys:
- [Mem0 API Key](https://app.mem0.ai/dashboard/api-keys)
- [OpenAI API Key](https://platform.openai.com/api-keys)
## Basic Integration Example
The following example demonstrates how to create an OpenAI agent with Mem0 memory integration:
```python
import os
from agents import Agent, Runner, function_tool
from mem0 import MemoryClient
# Set up environment variables
os.environ["OPENAI_API_KEY"] = "your-openai-api-key"
os.environ["MEM0_API_KEY"] = "your-mem0-api-key"
# Initialize Mem0 client
mem0 = MemoryClient()
# Define memory tools for the agent
@function_tool
def search_memory(query: str, user_id: str) -> str:
"""Search through past conversations and memories"""
memories = mem0.search(query, user_id=user_id, limit=3)
if memories and memories.get('results'):
return "\n".join([f"- {mem['memory']}" for mem in memories['results']])
return "No relevant memories found."
@function_tool
def save_memory(content: str, user_id: str) -> str:
"""Save important information to memory"""
mem0.add([{"role": "user", "content": content}], user_id=user_id)
return "Information saved to memory."
# Create agent with memory capabilities
agent = Agent(
name="Personal Assistant",
instructions="""You are a helpful personal assistant with memory capabilities.
Use the search_memory tool to recall past conversations and user preferences.
Use the save_memory tool to store important information about the user.
Always personalize your responses based on available memory.""",
tools=[search_memory, save_memory],
model="gpt-4o"
)
def chat_with_agent(user_input: str, user_id: str) -> str:
"""
Handle user input with automatic memory integration.
Args:
user_input: The user's message
user_id: Unique identifier for the user
Returns:
The agent's response
"""
# Run the agent (it will automatically use memory tools when needed)
result = Runner.run_sync(agent, user_input)
return result.final_output
# Example usage
if __name__ == "__main__":
# preferences will be saved in memory (using save_memory tool)
response_1 = chat_with_agent(
"I love Italian food and I'm planning a trip to Rome next month",
user_id="alice"
)
print(response_1)
# memory will be retrieved using search_memory tool to answer the user query
response_2 = chat_with_agent(
"Give me some recommendations for food",
user_id="alice"
)
print(response_2)
```
## Multi-Agent Workflow with Handoffs
Create multiple specialized agents with proper handoffs and shared memory:
```python
from agents import Agent, Runner, handoffs, function_tool
# Specialized agents
travel_agent = Agent(
name="Travel Planner",
instructions="""You are a travel planning specialist. Use get_user_context to
understand the user's travel preferences and history before making recommendations.
After providing your response, use store_conversation to save important details.""",
tools=[search_memory, save_memory],
model="gpt-4o"
)
health_agent = Agent(
name="Health Advisor",
instructions="""You are a health and wellness advisor. Use get_user_context to
understand the user's health goals and dietary preferences.
After providing advice, use store_conversation to save relevant information.""",
tools=[search_memory, save_memory],
model="gpt-4o"
)
# Triage agent with handoffs
triage_agent = Agent(
name="Personal Assistant",
instructions="""You are a helpful personal assistant that routes requests to specialists.
For travel-related questions (trips, hotels, flights, destinations), hand off to Travel Planner.
For health-related questions (fitness, diet, wellness, exercise), hand off to Health Advisor.
For general questions, you can handle them directly using available tools.""",
handoffs=[travel_agent, health_agent],
model="gpt-4o"
)
def chat_with_handoffs(user_input: str, user_id: str) -> str:
"""
Handle user input with automatic agent handoffs and memory integration.
Args:
user_input: The user's message
user_id: Unique identifier for the user
Returns:
The agent's response
"""
# Run the triage agent (it will automatically handoff when needed)
result = Runner.run_sync(triage_agent, user_input)
# Store the original conversation in memory
conversation = [
{"role": "user", "content": user_input},
{"role": "assistant", "content": result.final_output}
]
mem0.add(conversation, user_id=user_id)
return result.final_output
# Example usage
response = chat_with_handoffs("Plan a healthy meal for my Italy trip", user_id="alex")
print(response)
```
## Quick Start Chat Interface
Simple interactive chat with memory:
```python
def interactive_chat():
"""Interactive chat interface with memory and handoffs"""
user_id = input("Enter your user ID: ") or "demo_user"
print(f"Chat started for user: {user_id}")
print("Type 'quit' to exit\n")
while True:
user_input = input("You: ")
if user_input.lower() == 'quit':
break
response = chat_with_handoffs(user_input, user_id)
print(f"Assistant: {response}\n")
if __name__ == "__main__":
interactive_chat()
```
## Key Features
### 1. Automatic Memory Integration
- **Tool-Based Memory**: Agents use function tools to search and save memories
- **Conversation Storage**: All interactions are automatically stored
- **Context Retrieval**: Agents can access relevant past conversations
### 2. Multi-Agent Memory Sharing
- **Shared Context**: Multiple agents access the same memory store
- **Specialized Agents**: Create domain-specific agents with shared memory
- **Seamless Handoffs**: Agents maintain context across handoffs
### 3. Flexible Memory Operations
- **Retrieve Capabilities**: Retrieve relevant memories from previous conversation
- **User Segmentation**: Organize memories by user ID
- **Memory Management**: Built-in tools for saving and retrieving information
## Configuration Options
Customize memory behavior:
```python
# Configure memory search
memories = mem0.search(
query="travel preferences",
user_id="alex",
limit=5 # Number of memories to retrieve
)
# Add metadata to memories
mem0.add(
messages=[{"role": "user", "content": "I prefer luxury hotels"}],
user_id="alex",
metadata={"category": "travel", "importance": "high"}
)
```
## Help
- [OpenAI Agents SDK Documentation](https://openai.github.io/openai-agents-python/)
- [Mem0 Platform](https://app.mem0.ai/)
- If you need further assistance, please feel free to reach out to us through the following methods:
<Snippet file="get-help.mdx" />
+1 -1
View File
@@ -3,7 +3,7 @@ title: 'Pipecat'
description: 'Integrate Mem0 with Pipecat for conversational memory in AI agents'
---
<Snippet file="paper-release.mdx" />
<Snippet file="blank-notif.mdx" />
# Pipecat Integration
+2 -2
View File
@@ -3,11 +3,11 @@ title: "Raycast Extension"
description: "Mem0 Raycast extension for intelligent memory management"
---
# Mem0
<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
## Getting Started
**Get your API Key**: You'll need a Mem0 API key to use this extension:

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