Compare commits

..

258 Commits

Author SHA1 Message Date
Parshva Daftari ed5a1e9fc6 Update version to 0.1.118 (#3505) 2025-09-26 02:03:37 +05:30
Karthikeya Kollu dc883b0f9e [test] Add comprehensive test suite for SQLiteManager (#3494) 2025-09-25 22:30:03 +05:30
Saket Aryan 5616844b9c docs-fix: Quickstart cURL example fixed (#3503) 2025-09-25 20:44:39 +05:30
Saket Aryan 6e1d02c137 feat(ai-sdk): added file support for multimodal capabilities with memory context (#3500) 2025-09-25 10:32:06 +05:30
Parshva Daftari a199ee4ff8 Refactored example title for aws (#3492) 2025-09-22 18:28:28 +05:30
Parshva Daftari 88ae952483 [DOCS] Changing 1.0 to 1.0.0 (#3486) 2025-09-20 20:07:23 +05:30
Abdullah Irfan 9df392b26a Fixed s3 vectors memory initialization issue from configuration (#3481) 2025-09-20 12:43:18 +05:30
Parshva Daftari ead210ffe4 Added weaviate db test (#3483) 2025-09-18 14:40:44 -07:00
Andrew Carbonetto a015e2ff4a Add Neptune-DB graph store with vector store (#3443)
Signed-off-by: Andrew Carbonetto <andrew.carbonetto@improving.com>
Co-authored-by: Siddhartha Sahu <dev@sdht.in>
2025-09-19 02:54:33 +05:30
Brinlee Kidd d4e98dba38 feat: implement structured exception classes with error codes and sug… (#3279) 2025-09-19 02:31:35 +05:30
Parshva Daftari ac72eb5ecc Aspen theme for 1.x (#3473) 2025-09-18 21:03:17 +05:30
Andy Kwok 6b5582f474 Feat: Mem0 vector store backend integration for Neptune Analytics (#3453)
Signed-off-by: Andy Kwok <andy.kwok@improving.com>
2025-09-17 19:26:03 +05:30
Parshva Daftari d38e3f1962 Fix json parsing with new memories (#3456) 2025-09-12 17:29:34 +05:30
◢ 徇 ◤ a0685f3e8c fix: correct typo in knowledge graph extraction guidelines (#3449) 2025-09-12 15:07:37 +05:30
Parshva Daftari d48b1832c7 Fixes ollama and updates openai dependency (#3452) 2025-09-12 01:39:39 +05:30
Saket Aryan 21d69307dc docs: Update Search V2/Get All V2 Filters (#3450) 2025-09-11 19:10:19 +05:30
Andrew Carbonetto 9e5810dfb7 Fix bedrock anthropic models to use system field (#3438)
Signed-off-by: Andrew Carbonetto <andrew.carbonetto@improving.com>
2025-09-11 02:55:45 +05:30
Swarnaprakash Udayakumar e3f0277cb9 feat(vector-store): Add Valkey vector store support (#3272) 2025-09-10 04:01:53 +05:30
Prateek Chhikara e64488b598 updates to the category docs (#3437) 2025-09-09 11:47:09 -07:00
Parshva Daftari f5e0fb9e4b Added support for chromadb cloud (#3436) 2025-09-09 22:22:09 +05:30
Ranjith kumar 77b4b6a2b9 fix: 🐛 replace hardcoded llm provider with provider from config (#3423) 2025-09-05 22:38:04 +05:30
Josh Hayes 9477184582 databricks bug fixes (#3416) 2025-09-05 16:22:09 +05:30
Gabe Goodhart b27879bfd4 fix: Use ConfigDict instead of class-based Config (#3409)
Signed-off-by: Gabe Goodhart <ghart@us.ibm.com>
2025-09-04 20:18:25 +05:30
Saket Aryan f0e8c3f760 feat: Add metadata param to TS-SDK in client.update (#3415) 2025-09-04 03:22:12 +05:30
Parshva Daftari 5e8d5e4664 Release 0.1.117 (#3411) 2025-09-03 23:09:00 +05:30
Shili Cao c8d864c1b6 fix: add missing provider for baidu vector db (#3405) 2025-09-03 15:24:33 +05:30
Prateek Chhikara 617aabe5b3 [FIX] Graph Docs page was missing on the side bar (#3402) 2025-09-02 13:32:23 -07:00
Prateek Chhikara 163dafb216 Add version param in search v2 API documentation (#3401) 2025-09-02 13:24:22 -07:00
Srishti Gureja cc15a22bf9 support store for openai (#3399) 2025-09-02 21:23:59 +05:30
Parshva Daftari 64cbe84089 Updated favicon logo (#3398) 2025-09-02 21:10:04 +05:30
Parshva Daftari c8f9f20dff Updated integration docs (#3392) 2025-09-02 04:26:43 +05:30
John Lockwood 97fd320bbf Fix/new mem mistaken for current fixing #2875 (#2876) 2025-09-01 19:46:01 +05:30
Saket Aryan 748620f29b fix(Vercel AI SDK): Streaming not working properly (#3386) 2025-08-30 21:58:30 +05:30
Srishti Gureja 0b2aa36e98 Bugfix: Pick AWS region from the environment variable correctly (#3384) 2025-08-30 01:43:02 +05:30
Sheharyar Ahmad 3d0ece1bcf Refactor PGVector to Use Internal Connection Pools and Context Managers (#3373) 2025-08-29 19:06:39 +05:30
Rupam Jana 458d7ab8a3 replace query_vector args in search method of mongodb vector_stores (#3379) 2025-08-29 19:05:25 +05:30
Tushar Chandra 84af5ad265 docs: fix typo in docs/platform/advanced-memory-operations.mdx (#3348) 2025-08-27 17:35:45 -07:00
VikramIyer125 6237a6acb9 Adding weaviate, faiss, pgvector, chroma, redis, elasticsearch, milvus vector store to openmemory (#3366)
Co-authored-by: Vikram Iyer <vikramiyer@mac.local.meter>
2025-08-27 01:47:39 +05:30
VikramIyer125 8c8368781d Adding custom connection to weaviate connection client to enable client connection to local container (#3360)
Co-authored-by: Vikram Iyer <vikramiyer@Vikrams-MacBook-Pro.local>
2025-08-25 23:54:02 +05:30
Padarn Wilson 3b2d0ad0eb Fix missing commas in Kuzu graph INSERT queries (#3358) 2025-08-24 12:33:51 +05:30
Andy Kwok 9337a873ec Fix: Missing app_id on Neptune Analytics client (#3278)
Signed-off-by: Andy Kwok <andy.kwok@improving.com>
2025-08-23 21:06:19 +05:30
Srishti Gureja 76411e2591 docs fix: remove user_id from from_config (#3320) 2025-08-23 17:11:56 +05:30
Andy Kwok d523070cbc fix: Inconsistent created and updated properties on graph (#3220)
Signed-off-by: Andy Kwok <andy.kwok@improving.com>
2025-08-23 16:51:13 +05:30
Enzo Biondo c72bfc3285 Add Amazon S3 Vectors Support (#3237) 2025-08-23 16:44:42 +05:30
Parshva Daftari ee00bd5731 Fix typescript docs (#3357) 2025-08-22 14:23:26 -07:00
VikramIyer125 f914dca659 Add export_openmemory.sh migration script (#3352)
Co-authored-by: Vikram Iyer <vikramiyer@Vikrams-MacBook-Pro.local>
2025-08-22 20:19:41 +05:30
VikramIyer125 b64792590e Add memory export / import feature (#3345)
Co-authored-by: Vikram Iyer <vikramiyer@Vikrams-MacBook-Pro.local>
2025-08-21 23:27:28 +05:30
Parshva Daftari a7ac8bf13b Updated discord and dashboard image (#3344) 2025-08-20 14:11:26 -07:00
David A. Torres 4487785cec feature: add Azure Identity for Azure OpenAI and Azure AI Search authentication (#3262) 2025-08-21 02:00:27 +05:30
NiLAy e4c5582808 fix-migration-collection-override (#3100)
Co-authored-by: parshvadaftari <daftariparshva@gmail.com>
2025-08-21 00:11:28 +05:30
Vương Hữu Hưng (Hans) ff399e5528 Fix: Ollama checking model exists (#2682) 2025-08-19 16:29:26 +05:30
Parshva Daftari e7013764f7 Update aws bedrock (#3334) 2025-08-19 02:20:34 +05:30
Parshva Daftari c8ee17b884 Fix dependency and tests and updated docstring (#3337) 2025-08-19 02:12:24 +05:30
AkisAya 346b913ace feat: add es headers config (#3088) 2025-08-19 01:15:23 +05:30
Parshva Daftari 49ad64708b Updated databricks docs (#3336) 2025-08-18 13:24:32 -05:00
Josh Hayes 3a1eff425b feat(vector-store): Add Databricks Mosaic AI vector store support (#3325) 2025-08-18 22:20:33 +05:30
Parshva Daftari ebb411b11a Refactor docs (#3335) 2025-08-18 20:45:09 +05:30
Archie Sengupta 8e8f13a48e feat(Vercel AI SDK): add a param in config called host (#2634)
Co-authored-by: Saket Aryan <94069182+whysosaket@users.noreply.github.com>
2025-08-17 16:21:06 +05:30
Siddhartha Sahu a6a3928091 Add support for graph memory using Kuzu (#2934) 2025-08-16 02:22:31 +05:30
Ankush Malaker a883b56aa8 AsyncMemory._add_to_vector_store bugfix when no facts found (#3313) 2025-08-15 22:15:00 +05:30
Deshraj Yadav 246d9e8f69 Update llms.txt file (#3321) 2025-08-14 14:51:03 -07:00
Deshraj Yadav 192db1844c Update Docs (#3315) 2025-08-13 21:37:15 -07:00
Saket Aryan 5e895c240a Update version to 0.1.116 (#3312) 2025-08-14 00:06:34 +05:30
Parshva Daftari b4bd7b48df Fixing Json import for the psycopg and psycopg2 (#3310) 2025-08-13 23:52:58 +05:30
Parshva Daftari 1bc31b6ae3 Added sanitation for better relationship mapping (#3300) 2025-08-13 11:06:05 -05:00
Parshva Daftari 7159221d2e Restrict package version (#3305) 2025-08-12 16:53:21 -05:00
Parshva Daftari c89dc72f79 Fix failing tests (#3304) 2025-08-12 15:23:54 -05:00
Parshva Daftari 2145ffdb1c Updated docs for agent_id and run_id (#3294) 2025-08-12 15:03:39 -05:00
Parshva Daftari 23d31a830b Added support for python 3.12 (#3295) 2025-08-12 15:01:41 -05:00
Andrew Carbonetto 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
Andy Kwok 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
Aymen 72e5a4fcc4 docs: Remove unused and missing OS module from examples (#3090) 2025-08-12 14:58:43 -05:00
Bruce Wang 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 S 9e9dcd70e1 refactor: Update batch update method documentation to clarify optiona… (#2982) 2025-08-12 14:55:53 -05:00
Stefan Gajanovic dbe909c352 added simple sanitizer methods for nodes and realtionships (#3021) 2025-08-12 14:54:12 -05:00
YuriyTW d65a39c125 refactor: Improve async handling in AsyncMemory class for better performance (#3250) 2025-08-12 22:43:00 +05:30
Parshva Daftari b60a208c2f Fixes n_embeddings use and error for memgraph (#3296) 2025-08-11 12:57:29 -05:00
cnScarb c2792c6558 docs: fix search method return value handling in integration and example docs (#3208) 2025-08-11 12:16:01 -05:00
Parshva Daftari 2307dc8613 Fix/supported llm params (#3290) 2025-08-08 14:39:42 -07:00
John Lockwood 4c748423fc Feat/llm monitoring callback (#2877) 2025-08-08 14:26:51 -07:00
DrJsPBs 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 Daftari 148bbf0a5c Add sslmode pgvector (#3265) 2025-08-06 10:28:02 -07:00
Parshva Daftari 6e8c6c1cb7 Refactored base class config for llms (#3241) 2025-08-05 15:42:06 -07:00
Parshva Daftari f59ef3f2e2 Update docker compose (#3258) 2025-08-05 15:40:14 -07:00
Vimpas 7a0dc7391e feat: Add db_name field to MilvusDBConfig and MilvusDB initialization (#3229) 2025-08-05 11:16:34 -07:00
Saket Aryan 7fac6311f4 ai-sdk/docs: V5 Migration Docs (#3277) 2025-08-05 09:49:45 -07:00
Parshva Daftari 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 Daftari 42e60d6724 Added mulit id filters support for all vectorstores (#3269) 2025-08-04 14:52:57 -07:00
Parshva Daftari 57a16aeb4b Updated psycopg -> 3 (#3271) 2025-08-04 14:46:44 -07:00
lazakrisz 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 Daftari 7d1d0ca806 fixes memgraph async attirbute error (#3209) 2025-08-01 13:19:08 -07:00
Parshva Daftari 89b67e0834 Refactoring from gemini to google ai (#3244) 2025-08-01 11:56:42 -07:00
Parshva Daftari fbe8a2e90f Fix indexing when using Qdrant cloud (#3228) 2025-08-01 11:55:11 -07:00
Enam Biswas 907328aafe feat (pinecone): Add namespace support and improve type safety (#3216) 2025-08-01 11:53:34 -07:00
Antaripa Saha 0e03d69ed1 Personalized Search Example Docs (#3259) 2025-08-01 17:02:58 +05:30
Prateek Chhikara 0412e62cb1 Update field in docs (#3254) 2025-07-30 12:22:56 -07:00
Antaripa Saha 724c553a2e Personalized Search using Tavily + Mem0 (#3232) 2025-07-29 15:20:11 +05:30
Saket Aryan 08e7ae02de docs: Async Add Announcement (#3231) 2025-07-29 00:26:59 +05:30
Colsrch d0f61d5995 fix: Ignore memgraph index duplicate creation errors (#3203) 2025-07-25 01:07:23 +05:30
Parshva Daftari 4433666117 Fix failing tests (#3162) 2025-07-25 00:58:45 +05:30
Saket Aryan 37ee3c5eb2 docs: Update for new Project API and deprecation notices (#3212) 2025-07-24 15:16:47 +05:30
Dev Khant c8892bb1fe Update Changelog (#3211) 2025-07-24 10:17:51 +05:30
Antaripa Saha 1a8d175570 Content Writing Example Rewrite (#3142) 2025-07-16 11:47:50 +05:30
Antaripa Saha 0560d87160 Multiagent Learning System with LlamaIndex (#3063) 2025-07-16 11:47:17 +05:30
Antaripa Saha 9f3fd06334 Agno Mem0Tools update (#3139) 2025-07-16 11:46:51 +05:30
Antaripa Saha c1ca366edd Multi-LLM Research Team powered by memory (#3160) 2025-07-16 11:46:31 +05:30
askdevai-bot cba3217280 docs: Add comprehensive LLM-friendly documentation (#3154) 2025-07-16 06:06:31 +05:30
Parshva Daftari 77ea103b5d Updated livekit 1.0 integration (#3073) 2025-07-16 00:27:14 +05:30
Saket Aryan bcc5f42941 Restore and update handle_post_message implementation (#3152) 2025-07-14 21:25:45 +05:30
Saket Aryan 3bc5090371 Update personalized deep research example with GitHub link (#3136) 2025-07-10 18:01:33 -07:00
Antaripa Saha de0513fc9f AWS Bedrock Integration and spell checks (#3124) 2025-07-08 10:16:44 -07:00
Saket Aryan ec9b0688d8 Add structured_data_schema to MemoryOptions interface (#3125) 2025-07-08 10:07:44 -07:00
Saket Aryan 0f5612b96d Add JavaScript examples for memory export API (#3119) 2025-07-08 13:46:26 +05:30
Saket Aryan 842903b1b1 feat: Memory Exports (#3117) 2025-07-08 11:34:49 +05:30
Dev Khant 70d6f9231b Abstraction for Project in MemoryClient (#3067) 2025-07-08 11:33:20 +05:30
Varun Mohanta aae5989e78 Fix: Changed keyword from assisstant to secretary (#2937) 2025-07-08 10:57:25 +05:30
Saket Aryan 6866e56d7a Add metadata field to memory update schema (#3115) 2025-07-07 09:49:13 -07:00
Antaripa Saha 2992c298cb Security Link updated (#3108) 2025-07-05 10:25:35 -07:00
Akshat Jain 4491e7f9f4 Fix: Memgraph Graph Generation Issue (#3109) 2025-07-05 10:06:13 -07:00
Deshraj Yadav c0a930a7d3 Update version to 0.1.114 (#3107) 2025-07-04 16:28:39 -07:00
Andrew Carbonetto 05c404d8d3 Add Amazon Neptune Analytics graph_store configuration & integration (#2949) 2025-07-04 16:26:21 -07:00
Deshraj Yadav 7484eed4b2 Fix CI issues related to missing dependency (#3096) 2025-07-03 18:52:50 -07:00
Mingxiangyu 2c496e6376 Fix the error that occurs when VLLM is called (#3076) 2025-07-03 14:41:10 -07:00
Jainish a20b68fcec Fixes: Mem0 Setup, Logging, Docs (#3080) 2025-07-03 14:40:39 -07:00
Sakshi Srivastava eb7c712aa6 Fix: Add missing OpenAI import in vLLM module (#3091) 2025-07-03 14:37:20 -07:00
Saket Aryan 7476c39257 Add Gemini Model Support to Vercel AI SDK Provider (#3094) 2025-07-03 09:54:11 -07:00
Saket Aryan 5b0f1a7cf8 feat: Add Gemini support to TypeScript SDK (#3093) 2025-07-03 09:53:52 -07:00
Antaripa Saha b336cdf018 Image fixes (#3089) 2025-07-02 11:40:55 -07:00
Antaripa Saha 60e4e8a662 Google AI ADK Integration Docs (#3086) 2025-07-02 10:23:37 -07:00
Chaithanya Kumar 6d4a78b7c7 Enhance documentation: Add group chat feature to the list of platform… (#3077) 2025-07-02 11:13:01 +05:30
Antaripa Saha d39a1d5541 Openai agents sdk added (#3081) 2025-07-01 17:02:59 -07:00
Parshva Daftari 044ad4f131 Reverting the changes of pip install (#3010) 2025-07-01 15:49:39 +05:30
Antaripa Saha 75482fdb29 Docs SOC2 and HIPAA update (#3075) 2025-07-01 01:21:53 -07:00
Antaripa Saha 6c69599db9 Docs Update Images (#3072) 2025-07-01 00:36:30 -07:00
Kade Shockey b79bfb7c1e MongoDB Vector Store misaligned strings and classes (#3064) 2025-07-01 11:12:28 +05:30
Dev Khant 5a1083b709 Fix: Gemini embedder config and version bump -> 0.1.113 (#3070) 2025-06-30 13:31:51 +05:30
Dev Khant ac085db500 version bump -> 0.1.112 (#3058) 2025-06-27 15:19:57 +05:30
Dev Khant 2cc253341c Fix mongodb config name (#3052) 2025-06-26 23:06:21 +05:30
Dev Khant e3e2da6d45 Fix: Gemini Embeddings and LLM (#3050) 2025-06-26 21:05:00 +05:30
Dev Khant acf7a30d32 Doc: Add async_mode (#3037) 2025-06-25 10:51:49 -07:00
Saket Aryan a4f6751741 fix(ui-backend): resolve provider name format inconsistency in form configuration (#3041) 2025-06-25 09:48:22 -07:00
Ryan Rozich 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 Saha a98842422b doc: Broken links fixed in docs (#3034) 2025-06-25 17:18:29 +05:30
Antaripa Saha aaf879322c Platform feature docs revamp (#3007) 2025-06-25 00:57:08 -07:00
Laith Al-Saadoon 8139b5887f fix: bedrock llm, embeddings, tools, temporary creds (#3023) 2025-06-24 20:46:06 +05:30
Saket Aryan b4b27f099e Add immutable param to add method and bump version (#3022) 2025-06-24 05:03:35 +05:30
Dev Khant dc877fd3ba version bump -> 0.1.111 (#3016) 2025-06-23 21:52:03 +05:30
Akshat Jain 2bb0653e67 Add: Json Parsing to solve Hallucination Errors (#3013) 2025-06-23 21:50:16 +05:30
Akshat Jain 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 Jain a5ec286fd4 Add: Openmemory Augment support (#3015) 2025-06-23 20:45:01 +05:30
NiLAy 89499aedbe Feature/vllm support (#2981) 2025-06-23 13:18:38 +05:30
Akshat Jain 386d8b87ae Fix: Migrate Gemini Embeddings (#3002)
Co-authored-by: Dev-Khant <devkhant24@gmail.com>
2025-06-23 13:16:10 +05:30
Akshat Jain c173ec32d0 Improve Docs: Agent Id - Mem0 OSS Graph Memory (#2969) 2025-06-21 23:34:28 +05:30
Akshat Jain dd6f6f7a2e Fix: Add MCP Client Integration Guide and update installation commands (#2956) 2025-06-20 22:09:10 +05:30
Dev Khant b6684b96f7 version bump -> 0.1.110 (#3001) 2025-06-20 20:30:51 +05:30
Akarsha Sehwag 1fa0f0a157 fix(opensearch): update logger warning (#2999) 2025-06-20 20:28:51 +05:30
Saket Aryan 2754f45387 Make V2 Add as Default (#2997) 2025-06-20 16:56:42 +05:30
Parshva Daftari ecd4d91046 Fix failing CI pipeline (#2979) 2025-06-20 15:19:11 +05:30
Prateek Chhikara a5a247b161 Update client.update() method documentation in OpenAPI specification (#2990) 2025-06-19 14:04:12 -07:00
Dev Khant d47cb8d284 Doc: Fix example in quickstart page (#2986) 2025-06-19 13:51:20 +05:30
Dev Khant fa15db089d Update Changelog (#2985) 2025-06-19 12:32:33 +05:30
Shili Cao d35065c887 Feature: baidu vector db integration (#2929) 2025-06-19 11:12:12 +05:30
Prateek Chhikara cdee6a4ff0 Enhance update method to support metadata (#2976) 2025-06-18 10:07:18 -07:00
Dev Khant 9eb4e77c75 Fix pinecone for async memory (#2975) 2025-06-18 01:37:45 +05:30
Akshat Jain c700d790db Fix Build CI Failure (#2973) 2025-06-17 09:39:19 -07:00
Antaripa Saha a90b572389 Memory agent powered by voice (Cartesia + Agno) (#2970) 2025-06-17 18:54:53 +05:30
i-sun 62c330e5b3 feat(LM Studio): Add response_format param for LM Studio to config (#2502) 2025-06-17 17:55:18 +05:30
Akshat Jain c70dc7614b Fix: Add Google Genai library support (#2941) 2025-06-17 17:47:09 +05:30
Fenil Faldu e0003247c3 feat: add AgentOps integration (#2898) 2025-06-17 11:38:39 +05:30
Saket Aryan 888ee766c5 TS SDK - filter memories param (#2971) 2025-06-17 10:54:35 +05:30
Saket Aryan c7e91171a0 Added Param output_format in AI SDK (#2960) 2025-06-15 06:42:56 +05:30
Dev Khant 18c870ec79 version bump -> 0.1.108 (#2958) 2025-06-14 21:58:12 +05:30
Dev Khant 3e5f68ee90 Add logger in Opensearch (#2957) 2025-06-14 21:55:22 +05:30
Fabian Valle a0cd4065d9 +MongoDB Vector Support (#2367)
Co-authored-by: Divya Gupta <divya.gupta@mongodb.com>
2025-06-14 17:57:06 +05:30
John Lockwood 7c0c4a03c4 Feat/add python version test envs (#2774) 2025-06-14 17:43:16 +05:30
John Lockwood a8ace18607 Fix/pin pinecone issue #2772 (#2773) 2025-06-14 17:38:32 +05:30
Dev Khant df43f904d1 deploy minor version -> 0.1.107rc2 (#2953) 2025-06-13 12:09:54 +05:30
Prateek Chhikara a5a07d711b Updates in client to support summary (#2951) 2025-06-13 12:04:38 +05:30
Dev Khant a40268dd51 Fix: Migration in storage and version bump -> -0.1.107 (#2943) 2025-06-11 21:48:43 +05:30
Akshat Jain c59752c6d6 Update Categorisation Flow (#2922)
Co-authored-by: Deshraj Yadav <deshraj@gatech.edu>
2025-06-11 21:24:15 +05:30
Saket Aryan aa334fb569 Updated Docs for OMM Hosted Version (#2945) 2025-06-11 08:19:03 -07:00
Antaripa Saha 40a5e87022 Livekit Docs Update (#2933) 2025-06-09 10:20:41 -07:00
Akshat Jain 4dec9ace88 Update support for unique user IDs (#2921) 2025-06-07 21:20:40 +05:30
Dev Khant e1dc27276b Formatting and version bump -> 0.1.107 (#2927) 2025-06-07 12:27:22 +05:30
Saket Aryan 9a12ea7b3c Version Bump/Formatting (#2923) 2025-06-06 21:49:03 +05:30
Mrinank Bhowmick e10a509645 Added cloudflare vector-store (#2607) 2025-06-06 21:35:40 +05:30
Prateek Chhikara fe3f10adb8 Add Wildcard Character Support Documentation for v2 Memory APIs (#2919) 2025-06-06 12:23:04 +05:30
Akshat Jain 53c91fb107 Doc : Update Readme Docs for OpenMemory environment setup (#2913) 2025-06-05 21:52:04 +05:30
Prateek Chhikara ecc596b11f fix error of wrong exception (#2911) 2025-06-04 16:56:52 -07:00
Prateek Chhikara be37fca1bb Added threshold to search (#2899) 2025-06-03 02:58:21 -07:00
Dev Khant 849452cc93 version bump -> 0.1.104 (#2897) 2025-06-03 01:15:16 +05:30
Dev Khant 1f2df450bb Fix: GET_ALL for faiss and opensearch (#2896) 2025-06-03 01:10:07 +05:30
Dev Khant 06d86996f2 version bump -> 0.1.103 (#2894) 2025-06-02 22:26:37 +05:30
Dev Khant bb14cc42a0 Doc: update for enable_graph and Version bump -> 0.1.103 (#2893) 2025-06-02 22:23:22 +05:30
Saket Aryan fbee8d5c20 Added Async Mode Param (#2882) 2025-05-30 09:06:41 -07:00
Saket Aryan 855c322da6 deps(ts-sdk): Updates Google SDK Peer Dependency Version (#2878) 2025-05-30 09:51:01 +05:30
Prateek Chhikara 240acca3de Fix: Improve clarity and conciseness of Graph Memory features documen… (#2874) 2025-05-29 13:47:16 -07:00
Saket Aryan 7ef1378304 Fixed Broken Links (#2871) 2025-05-29 21:20:30 +05:30
Frank Zhao 9622ac7dff feat: support openai compatible llm provider by adding baseUrl to config (#2674)
Signed-off-by: frank-zsy <syzhao1988@126.com>
Co-authored-by: Saket Aryan <94069182+whysosaket@users.noreply.github.com>
Co-authored-by: Saket Aryan <saketaryan2002@gmail.com>
2025-05-27 00:25:23 +05:30
Dev Khant 8a280b4a54 version bump -> 0.1.102 (#2805) 2025-05-26 23:24:51 +05:30
Antaripa Saha 1ba9c71f54 Add support for sarvam-m model (#2802) 2025-05-26 23:19:37 +05:30
Saket Aryan 5c6fbcaab0 Feature (OpenMemory): Add support for LLM and Embedding Providers in OpenMemory (#2794) 2025-05-25 01:01:23 -07:00
Olivier Blin b339cab3c1 Fix: Typos in openmemory MCP tool description (#2793) 2025-05-24 15:17:00 -07:00
Dev Khant a952df0953 Doc: Add NOT filter for Search and GetAll V2 (#2785) 2025-05-23 23:29:21 +05:30
Dev Khant 6cebddebbe Doc: Mastra and Raycast (#2781) 2025-05-23 16:10:47 +05:30
Chaithanya Kumar b3d340f59c Fix: Prevent saving prompt artifacts as memory when no new facts are … (#2744)
Co-authored-by: Deshraj Yadav <deshraj@gatech.edu>
2025-05-23 15:05:07 +05:30
Dev Khant 78e2efc0f2 Doc: update messages in api reference (#2777) 2025-05-23 14:41:13 +05:30
Saket Aryan d21970efcc feat(ai-sdk): Added Support for Google Provider in AI SDK (#2771) 2025-05-23 00:37:58 +05:30
Prateek Chhikara 816039036d Improve documentation on role-based memory attribution rules (#2770) 2025-05-22 12:07:18 -07:00
Dev Khant faf1a34f70 Doc: announce claude 4 (#2769) 2025-05-22 22:48:04 +05:30
Prateek Chhikara 6986153c90 Improve documentation on role-based memory attribution rules (#2768) 2025-05-22 09:39:50 -07:00
Saket Aryan 8048e0b32f fix(ts-sdk): Fixed Types from Message Interface (#2763) 2025-05-22 21:56:45 +05:30
Dev Khant af1cfd8139 Doc: Update output of Org/Proj creation APIs (#2761) 2025-05-22 15:05:23 +05:30
Dev Khant f5c3804f79 Doc: Update API Reference (#2760) 2025-05-22 11:54:44 +05:30
Dev Khant 443816365a Doc: Feature docs changes (#2756) 2025-05-22 10:59:18 +05:30
Dev Khant 097959d5cc Remove support for passing string as input in the client.add() (#2749) 2025-05-22 10:16:32 +05:30
Tomaz Bratanic bad6e12972 Add neo4j example (#2738) 2025-05-21 17:58:11 -07:00
Dev Khant d85fcda037 Formatting (#2750) 2025-05-22 01:17:29 +05:30
Dev Khant dff91154a7 Doc: Update memory export (#2741) 2025-05-21 13:14:34 +05:30
Dev Khant c3f3f82a3e Migrate to Hatch and version bump -> 0.1.101 (#2727) 2025-05-20 22:58:51 +05:30
Saket Aryan 70af43c08c improvement(OMM): Added CurL Command to Easy Install OMM (#2731) 2025-05-20 20:18:07 +05:30
Tomaz Bratanic 1786d907f7 Add neo4j base label config (#2675) 2025-05-19 18:22:20 -07:00
Prateek Chhikara 12a268da30 Added docs for criteria based filtering (#2726) 2025-05-19 14:52:43 -07:00
Chaithanya Kumar 0aefdf5251 Refactored collaborative task agent documentation to enhance clarity and simplified (#2725) 2025-05-19 09:58:22 -07:00
Antaripa Saha df72245b6b Update Index of Healthcare Example in docs (#2722) 2025-05-19 02:18:14 -07:00
Dev Khant fe872d0776 Update Changelog (#2720) 2025-05-19 12:54:15 +05:30
Dev Khant 052d31939d version bump -> 0.1.100 (#2719) 2025-05-19 12:27:38 +05:30
Antaripa Saha 1c44b675d9 Healthcare assistant using Mem0 and Google ADK (#2705) 2025-05-18 07:50:06 -07:00
Chaithanya Kumar a1c9a63074 # feat: Add Group Chat Memory Feature support to Python SDK enhancing mem0 (#2669) 2025-05-16 11:08:36 -07:00
Saket Aryan 931df14e25 fix(OMM): Memories not appearing in MCP clients added from Dashboard (#2704)
Co-authored-by: Deshraj Yadav <deshraj@gatech.edu>
2025-05-16 22:11:22 +05:30
heng 1b0d8bdd2e improvement(OMM)- fix the sse failed to connect issue (#2696) 2025-05-16 15:57:46 +05:30
Saket Aryan 5c67a5e6bc improvement(OSS): Fix AOSS and AWS BedRock LLM (#2697)
Co-authored-by: Prateek Chhikara <prateekchhikara24@gmail.com>
Co-authored-by: Deshraj Yadav <deshrajdry@gmail.com>
2025-05-16 04:49:29 +05:30
GongRzhe 267e5b13ea Update README.md (#2687) 2025-05-15 00:16:05 -07:00
Saket Aryan a22287a3ba improvement(OpenMemory MCP): Improves Docker Compose commands (#2681)
Co-authored-by: Deshraj Yadav <deshrajdry@gmail.com>
2025-05-14 13:44:08 +05:30
Saket Aryan da59412150 Remove OpenMemory Directory from pyproject and Update Link (#2678) 2025-05-13 21:50:56 +05:30
Saket Aryan c41719ff9a Fix Backend Link in OpenMemory (#2677) 2025-05-13 08:36:59 -07:00
Deshraj Yadav f51b39db91 Add OpenMemory (#2676)
Co-authored-by: Saket Aryan <94069182+whysosaket@users.noreply.github.com>
Co-authored-by: Saket Aryan <saketaryan2002@gmail.com>
2025-05-13 08:30:59 -07:00
Saket Aryan 8d61d73d2f Added ElizaOS Example (#2670) 2025-05-12 10:05:11 -07:00
Saket Aryan 10acf78618 Added Missing Param in AI SDK and Updated Demo Application (#2667) 2025-05-12 04:22:23 +05:30
Tomaz Bratanic caeae60dda Add weights to Neo4j model (#2657) 2025-05-10 14:51:34 -07:00
Dev Khant d7b8497b24 Doc: update azure ai (#2661) 2025-05-09 20:03:34 +05:30
Dev Khant a96e1d58f7 Support for AWS Bedrock Embeddings (#2660) 2025-05-09 19:44:35 +05:30
Tomaz Bratanic 0d895b28ae Improve neo4j queries (#2654) 2025-05-08 11:11:46 -07:00
Saket Aryan 84910b40da Added support for graceful failure in cases services are down. (#2650) 2025-05-08 16:03:26 +05:30
Prateek Chhikara 0e7c34f541 Renamed unknown node type (#2649) 2025-05-07 23:19:58 -07:00
Prateek Chhikara 2b58775c17 updated docs (#2647) 2025-05-07 14:09:48 -07:00
Dev Khant 326f33757b Update Client (#2640) 2025-05-08 00:09:43 +05:30
Tomaz Bratanic c01221d4aa Add support for neo4j database (#2644) 2025-05-07 10:54:18 -07:00
Tomaz Bratanic 73d9ccac69 remove warnings and refresh schema from neo4j (#2643) 2025-05-07 10:16:39 -07:00
Wonbin Kim 5bbd0d9ca9 Fix duplicated metadata issue while adding or updating memories (#2592) 2025-05-07 21:10:32 +05:30
John Lockwood 641be2878d Fix/new memories wrong type (#2635) 2025-05-07 17:35:24 +05:30
Prateek Chhikara eb7f5a774c Update Documentation: Clarify Dual-Identity Memory Management (#2642) 2025-05-06 23:08:32 -07:00
Saket Aryan 6e9f8cf218 Added New Param, output_format (#2639) 2025-05-06 22:56:48 +05:30
Dev Khant 02a2b59555 Doc: update timestamp (#2638) 2025-05-06 17:39:31 +05:30
Dev Khant ec1d7a45d3 Fix all lint errors (#2627) 2025-05-06 01:16:02 +05:30
Saket Aryan 725a1aa114 Updated deleteUsers to use V2 API Endpoints (#2624) 2025-05-05 23:23:13 +05:30
Dev Khant d41f19b9ce Update delete_users() (#2623) 2025-05-05 23:21:06 +05:30
Saket Aryan a0fe9ca5b2 Fix AI SDK Filters (#2625) 2025-05-05 19:38:58 +05:30
729 changed files with 84341 additions and 8989 deletions
+4 -7
View File
@@ -18,20 +18,17 @@ jobs:
with:
python-version: '3.11'
- name: Install Poetry
- name: Install Hatch
run: |
curl -sSL https://install.python-poetry.org | python3 -
echo "$HOME/.local/bin" >> $GITHUB_PATH
pip install hatch
- name: Install dependencies
run: |
cd mem0
poetry install
hatch env create
- name: Build a binary wheel and a source tarball
run: |
cd mem0
poetry build
hatch build --clean
# TODO: Needs to setup mem0 repo on Test PyPI
# - name: Publish distribution 📦 to Test PyPI
+25 -22
View File
@@ -37,28 +37,31 @@ 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 }}
uses: actions/setup-python@v4
with:
python-version: ${{ matrix.python-version }}
- name: Install poetry
uses: snok/install-poetry@v1
with:
version: 1.4.2
virtualenvs-create: true
virtualenvs-in-project: true
- name: Install Hatch
run: pip install hatch
- name: Load cached venv
id: cached-poetry-dependencies
id: cached-hatch-dependencies
uses: actions/cache@v3
with:
path: .venv
key: venv-mem0-${{ runner.os }}-${{ hashFiles('**/poetry.lock') }}
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
if: steps.cached-poetry-dependencies.outputs.cache-hit != 'true'
run: |
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 Linting
run: make lint
- name: Run tests and generate coverage report
run: make test
@@ -68,28 +71,28 @@ 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 }}
uses: actions/setup-python@v4
with:
python-version: ${{ matrix.python-version }}
- name: Install poetry
uses: snok/install-poetry@v1
with:
version: 1.4.2
virtualenvs-create: true
virtualenvs-in-project: true
- name: Install Hatch
run: pip install hatch
- name: Load cached venv
id: cached-poetry-dependencies
id: cached-hatch-dependencies
uses: actions/cache@v3
with:
path: .venv
key: venv-embedchain-${{ runner.os }}-${{ hashFiles('**/poetry.lock') }}
key: venv-embedchain-${{ runner.os }}-${{ hashFiles('**/pyproject.toml') }}
- name: Install dependencies
run: cd embedchain && make install_all
if: steps.cached-poetry-dependencies.outputs.cache-hit != 'true'
if: steps.cached-hatch-dependencies.outputs.cache-hit != 'true'
- name: Run Formatting
run: |
mkdir -p embedchain/.ruff_cache && chmod -R 777 embedchain/.ruff_cache
cd embedchain && hatch run format
- name: Lint with ruff
run: cd embedchain && make lint
- name: Run tests and generate coverage report
@@ -99,4 +102,4 @@ jobs:
with:
file: coverage.xml
env:
CODECOV_TOKEN: ${{ secrets.CODECOV_TOKEN }}
CODECOV_TOKEN: ${{ secrets.CODECOV_TOKEN }}
+23 -15
View File
@@ -16,18 +16,20 @@ To make a contribution, follow these steps:
For more details about pull requests, please read [GitHub's guides](https://docs.github.com/en/pull-requests/collaborating-with-pull-requests/proposing-changes-to-your-work-with-pull-requests/creating-a-pull-request).
### 📦 Package manager
### 📦 Development Environment
We use `poetry` as our package manager. You can install poetry by following the instructions [here](https://python-poetry.org/docs/#installation).
Please DO NOT use pip or conda to install the dependencies. Instead, use poetry:
We use `hatch` for managing development environments. To set up:
```bash
make install_all
# Activate environment for specific Python version:
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
#activate
poetry shell
# The environment will automatically install all dev dependencies
# Run tests within the activated shell:
make test
```
### 📌 Pre-commit
@@ -40,16 +42,22 @@ pre-commit install
### 🧪 Testing
We use `pytest` to test our code. You can run the tests by running the following command:
We use `pytest` to test our code across multiple Python versions. You can run tests using:
```bash
poetry run pytest tests
# or
# Run tests with default Python version
make test
# Test specific Python versions:
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
```
Several packages have been removed from Poetry to make the package lighter. Therefore, it is recommended to run `make install_all` to install the remaining packages and ensure all tests pass. Make sure that all tests pass before submitting a pull request.
Make sure that all tests pass across all supported Python versions before submitting a pull request.
We look forward to your pull requests and can't wait to see your contributions!
We look forward to your pull requests and can't wait to see your contributions!
+1322
View File
File diff suppressed because it is too large Load Diff
+23 -12
View File
@@ -8,37 +8,48 @@ PROJECT_NAME := mem0ai
all: format sort lint
install:
poetry install
hatch env create
install_all:
poetry install
poetry run pip install groq together boto3 litellm ollama chromadb weaviate weaviate-client sentence_transformers vertexai \
google-generativeai elasticsearch opensearch-py vecs pinecone pinecone-text faiss-cpu langchain-community \
upstash-vector azure-search-documents langchain-memgraph
pip install ruff==0.6.9 groq together boto3 litellm ollama chromadb weaviate weaviate-client sentence_transformers vertexai \
google-generativeai elasticsearch opensearch-py vecs "pinecone<7.0.0" pinecone-text faiss-cpu langchain-community \
upstash-vector azure-search-documents langchain-memgraph langchain-neo4j langchain-aws rank-bm25 pymochow pymongo psycopg kuzu databricks-sdk valkey
# Format code with ruff
format:
poetry run ruff format mem0/
hatch run format
# Sort imports with isort
sort:
poetry run isort mem0/
hatch run isort mem0/
# Lint code with ruff
lint:
poetry run ruff check mem0/
hatch run lint
docs:
cd docs && mintlify dev
build:
poetry build
hatch build
publish:
poetry publish
hatch publish
clean:
poetry run rm -rf dist
rm -rf dist
test:
poetry run pytest tests
hatch run test
test-py-3.9:
hatch run dev_py_3_9:test
test-py-3.10:
hatch run dev_py_3_10:test
test-py-3.11:
hatch run dev_py_3_11:test
test-py-3.12:
hatch run dev_py_3_12:test
+3 -1
View File
@@ -15,11 +15,13 @@
<a href="https://mem0.dev/DiG">Join Discord</a>
·
<a href="https://mem0.dev/demo">Demo</a>
·
<a href="https://mem0.dev/openmemory">OpenMemory</a>
</p>
<p align="center">
<a href="https://mem0.dev/DiG">
<img src="https://dcbadge.vercel.app/api/server/6PzXDgEjG5?style=flat" alt="Mem0 Discord">
<img src="https://img.shields.io/badge/Discord-%235865F2.svg?&logo=discord&logoColor=white" alt="Mem0 Discord">
</a>
<a href="https://pepy.tech/project/mem0ai">
<img src="https://img.shields.io/pypi/dm/mem0ai" alt="Mem0 PyPI - Downloads">
+11 -25
View File
@@ -13,7 +13,7 @@
"import anthropic\n",
"\n",
"# Set up environment variables\n",
"os.environ[\"OPENAI_API_KEY\"] = \"your_openai_api_key\" # needed for embedding model\n",
"os.environ[\"OPENAI_API_KEY\"] = \"your_openai_api_key\" # needed for embedding model\n",
"os.environ[\"ANTHROPIC_API_KEY\"] = \"your_anthropic_api_key\""
]
},
@@ -33,7 +33,7 @@
" \"model\": \"claude-3-5-sonnet-latest\",\n",
" \"temperature\": 0.1,\n",
" \"max_tokens\": 2000,\n",
" }\n",
" },\n",
" }\n",
" }\n",
" self.client = anthropic.Client(api_key=os.environ[\"ANTHROPIC_API_KEY\"])\n",
@@ -50,11 +50,7 @@
" - Keep track of open issues and follow-ups\n",
" \"\"\"\n",
"\n",
" def store_customer_interaction(self,\n",
" user_id: str,\n",
" message: str,\n",
" response: str,\n",
" metadata: Dict = None):\n",
" def store_customer_interaction(self, user_id: str, message: str, response: str, metadata: Dict = None):\n",
" \"\"\"Store customer interaction in memory.\"\"\"\n",
" if metadata is None:\n",
" metadata = {}\n",
@@ -63,24 +59,17 @@
" metadata[\"timestamp\"] = datetime.now().isoformat()\n",
"\n",
" # Format conversation for storage\n",
" conversation = [\n",
" {\"role\": \"user\", \"content\": message},\n",
" {\"role\": \"assistant\", \"content\": response}\n",
" ]\n",
" conversation = [{\"role\": \"user\", \"content\": message}, {\"role\": \"assistant\", \"content\": response}]\n",
"\n",
" # Store in Mem0\n",
" self.memory.add(\n",
" conversation,\n",
" user_id=user_id,\n",
" metadata=metadata\n",
" )\n",
" self.memory.add(conversation, user_id=user_id, metadata=metadata)\n",
"\n",
" def get_relevant_history(self, user_id: str, query: str) -> List[Dict]:\n",
" \"\"\"Retrieve relevant past interactions.\"\"\"\n",
" return self.memory.search(\n",
" query=query,\n",
" user_id=user_id,\n",
" limit=5 # Adjust based on needs\n",
" limit=5, # Adjust based on needs\n",
" )\n",
"\n",
" def handle_customer_query(self, user_id: str, query: str) -> str:\n",
@@ -112,15 +101,12 @@
" model=\"claude-3-5-sonnet-latest\",\n",
" messages=[{\"role\": \"user\", \"content\": prompt}],\n",
" max_tokens=2000,\n",
" temperature=0.1\n",
" temperature=0.1,\n",
" )\n",
"\n",
" # Store interaction\n",
" self.store_customer_interaction(\n",
" user_id=user_id,\n",
" message=query,\n",
" response=response,\n",
" metadata={\"type\": \"support_query\"}\n",
" user_id=user_id, message=query, response=response, metadata={\"type\": \"support_query\"}\n",
" )\n",
"\n",
" return response.content[0].text"
@@ -203,12 +189,12 @@
" # Get user input\n",
" query = input()\n",
" print(\"Customer:\", query)\n",
" \n",
"\n",
" # Check if user wants to exit\n",
" if query.lower() == 'exit':\n",
" if query.lower() == \"exit\":\n",
" print(\"Thank you for using our support service. Goodbye!\")\n",
" break\n",
" \n",
"\n",
" # Handle the query and print the response\n",
" response = chatbot.handle_customer_query(user_id, query)\n",
" print(\"Support:\", response, \"\\n\\n\")"
+2
View File
@@ -7,10 +7,12 @@
# forked from autogen.agentchat.contrib.capabilities.teachability.Teachability
from typing import Dict, Optional, Union
from autogen.agentchat.assistant_agent import ConversableAgent
from autogen.agentchat.contrib.capabilities.agent_capability import AgentCapability
from autogen.agentchat.contrib.text_analyzer_agent import TextAnalyzerAgent
from termcolor import colored
from mem0 import Memory
File diff suppressed because it is too large Load Diff
+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>
+122 -2
View File
@@ -4,8 +4,6 @@ icon: "info"
iconType: "solid"
---
<Snippet file="paper-release.mdx" />
Mem0 provides a powerful set of APIs that allow you to integrate advanced memory management capabilities into your applications. Our APIs are designed to be intuitive, efficient, and scalable, enabling you to create, retrieve, update, and delete memories across various entities such as users, agents, apps, and runs.
## Key Features
@@ -60,6 +58,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:
+23 -1
View File
@@ -3,12 +3,15 @@ title: 'Get Memories (v2)'
openapi: post /v2/memories/
---
The v2 get memories API is powerful and flexible, allowing for more precise memory listing without the need for a search query. It supports complex logical operations (AND, OR) and comparison operators for advanced filtering capabilities. The comparison operators include:
The v2 get memories API is powerful and flexible, allowing for more precise memory listing without the need for a search query. It supports complex logical operations (AND, OR, NOT) and comparison operators for advanced filtering capabilities. The comparison operators include:
- `in`: Matches any of the values specified
- `gte`: Greater than or equal to
- `lte`: Less than or equal to
- `gt`: Greater than
- `lt`: Less than
- `ne`: Not equal to
- `icontains`: Case-insensitive containment check
- `*`: Wildcard character that matches everything
<CodeGroup>
```python Code
@@ -41,3 +44,22 @@ memories = m.get_all(
]
```
</CodeGroup>
<CodeGroup>
```python Wildcard Example
# Using wildcard to get all memories for a specific user across all run_ids
memories = m.get_all(
filters={
"AND": [
{
"user_id": "alex"
},
{
"run_id": "*"
}
]
},
version="v2"
)
```
</CodeGroup>
@@ -3,7 +3,7 @@ title: 'Search Memories (v2)'
openapi: post /v2/memories/search/
---
The v2 search API is powerful and flexible, allowing for more precise memory retrieval. It supports complex logical operations (AND, OR) and comparison operators for advanced filtering capabilities. The comparison operators include:
The v2 search API is powerful and flexible, allowing for more precise memory retrieval. It supports complex logical operations (AND, OR, NOT) and comparison operators for advanced filtering capabilities. The comparison operators include:
- `in`: Matches any of the values specified
- `gte`: Greater than or equal to
- `lte`: Less than or equal to
@@ -11,6 +11,7 @@ The v2 search API is powerful and flexible, allowing for more precise memory ret
- `lt`: Less than
- `ne`: Not equal to
- `icontains`: Case-insensitive containment check
- `*`: Wildcard character that matches everything
<CodeGroup>
```python Code
@@ -18,7 +19,7 @@ The v2 search API is powerful and flexible, allowing for more precise memory ret
query="What are Alice's hobbies?",
version="v2",
filters={
"AND": [
"OR": [
{
"user_id": "alice"
},
@@ -49,3 +50,59 @@ The v2 search API is powerful and flexible, allowing for more precise memory ret
}
```
</CodeGroup>
<CodeGroup>
```python Wildcard Example
# Using wildcard to match all run_ids for a specific user
all_memories = m.search(
query="What are Alice's hobbies?",
version="v2",
filters={
"AND": [
{
"user_id": "alice"
},
{
"run_id": "*"
}
]
},
)
```
</CodeGroup>
<CodeGroup>
```python Categories Filter Examples
# Example 1: Using 'contains' for partial matching
finance_memories = m.search(
query="What are my financial goals?",
version="v2",
filters={
"AND": [
{ "user_id": "alice" },
{
"categories": {
"contains": "finance"
}
}
]
},
)
# Example 2: Using 'in' for exact matching
personal_memories = m.search(
query="What personal information do you have?",
version="v2",
filters={
"AND": [
{ "user_id": "alice" },
{
"categories": {
"in": ["personal_information"]
}
}
]
},
)
```
</CodeGroup>
@@ -1,4 +0,0 @@
---
title: 'Delete Member'
openapi: delete /api/v1/orgs/organizations/{org_id}/members/
---
@@ -1,9 +0,0 @@
---
title: 'Update Member'
openapi: put /api/v1/orgs/organizations/{org_id}/members/
---
The API provides two roles for organization members:
- `READER`: Allows viewing of organization resources.
- `OWNER`: Grants full administrative access to manage the organization and its resources.
@@ -1,4 +0,0 @@
---
title: 'Delete Member'
openapi: delete /api/v1/orgs/organizations/{org_id}/projects/{project_id}/members/
---
@@ -1,9 +0,0 @@
---
title: 'Update Member'
openapi: put /api/v1/orgs/organizations/{org_id}/projects/{project_id}/members/
---
The API provides two roles for project members:
- `READER`: Allows viewing of project resources.
- `OWNER`: Grants full administrative access to manage the project and its resources.
@@ -1,4 +0,0 @@
---
title: 'Update Project'
openapi: patch /api/v1/orgs/organizations/{org_id}/projects/{project_id}/
---
+805 -112
View File
File diff suppressed because it is too large Load Diff
-1
View File
@@ -4,7 +4,6 @@ icon: "gear"
iconType: "solid"
---
<Snippet file="paper-release.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.
@@ -0,0 +1,62 @@
---
title: AWS Bedrock
---
To use AWS Bedrock embedding models, you need to have the appropriate AWS credentials and permissions. The embeddings implementation relies on the `boto3` library.
### Setup
- Ensure you have model access from the [AWS Bedrock Console](https://us-east-1.console.aws.amazon.com/bedrock/home?region=us-east-1#/modelaccess)
- Authenticate the boto3 client using a method described in the [AWS documentation](https://boto3.amazonaws.com/v1/documentation/api/latest/guide/credentials.html)
- Set up environment variables for authentication:
```bash
export AWS_REGION=us-east-1
export AWS_ACCESS_KEY_ID=your-access-key
export AWS_SECRET_ACCESS_KEY=your-secret-key
```
### Usage
<CodeGroup>
```python Python
import os
from mem0 import Memory
# For LLM if needed
os.environ["OPENAI_API_KEY"] = "your-openai-api-key"
# AWS credentials
os.environ["AWS_REGION"] = "us-west-2"
os.environ["AWS_ACCESS_KEY_ID"] = "your-access-key"
os.environ["AWS_SECRET_ACCESS_KEY"] = "your-secret-key"
config = {
"embedder": {
"provider": "aws_bedrock",
"config": {
"model": "amazon.titan-embed-text-v2:0"
}
}
}
m = Memory.from_config(config)
messages = [
{"role": "user", "content": "I'm planning to watch a movie tonight. Any recommendations?"},
{"role": "assistant", "content": "How about a thriller movies? They can be quite engaging."},
{"role": "user", "content": "I'm not a big fan of thriller movies but I love sci-fi movies."},
{"role": "assistant", "content": "Got it! I'll avoid thriller recommendations and suggest sci-fi movies in the future."}
]
m.add(messages, user_id="alice")
```
</CodeGroup>
### Config
Here are the parameters available for configuring AWS Bedrock embedder:
<Tabs>
<Tab title="Python">
| Parameter | Description | Default Value |
| --- | --- | --- |
| `model` | The name of the embedding model to use | `amazon.titan-embed-text-v1` |
</Tab>
</Tabs>
@@ -77,6 +77,43 @@ await memory.add(messages, { userId: "john" });
```
</CodeGroup>
As an alternative to using an API key, the Azure Identity credential chain can be used to authenticate with [Azure OpenAI role-based security](https://learn.microsoft.com/en-us/azure/ai-foundry/openai/how-to/role-based-access-control).
<Note> If an API key is provided, it will be used for authentication over an Azure Identity </Note>
Below is a sample configuration for using Mem0 with Azure OpenAI and Azure Identity:
```python
import os
from mem0 import Memory
# You can set the values directly in the config dictionary or use environment variables
os.environ["LLM_AZURE_DEPLOYMENT"] = "your-deployment-name"
os.environ["LLM_AZURE_ENDPOINT"] = "your-api-base-url"
os.environ["LLM_AZURE_API_VERSION"] = "version-to-use"
config = {
"llm": {
"provider": "azure_openai_structured",
"config": {
"model": "your-deployment-name",
"temperature": 0.1,
"max_tokens": 2000,
"azure_kwargs": {
"azure_deployment": "<your-deployment-name>",
"api_version": "<version-to-use>",
"azure_endpoint": "<your-api-base-url>",
"default_headers": {
"CustomHeader": "your-custom-header",
}
}
}
}
}
```
Refer to [Azure Identity troubleshooting tips](https://github.com/Azure/azure-sdk-for-python/blob/main/sdk/identity/azure-identity/TROUBLESHOOTING.md#troubleshoot-environmentcredential-authentication-issues) for setting up an Azure Identity credential.
### Config
Here are the parameters available for configuring Azure OpenAI embedder:
@@ -0,0 +1,69 @@
---
title: Google AI
---
To use Google AI embedding models, set the `GOOGLE_API_KEY` environment variables. You can obtain the Gemini API key from [here](https://aistudio.google.com/app/apikey).
### Usage
<CodeGroup>
```python Python
import os
from mem0 import Memory
os.environ["GOOGLE_API_KEY"] = "key"
os.environ["OPENAI_API_KEY"] = "your_api_key" # For LLM
config = {
"embedder": {
"provider": "gemini",
"config": {
"model": "models/text-embedding-004",
}
}
}
m = Memory.from_config(config)
messages = [
{"role": "user", "content": "I'm planning to watch a movie tonight. Any recommendations?"},
{"role": "assistant", "content": "How about a thriller movies? They can be quite engaging."},
{"role": "user", "content": "I'm not a big fan of thriller movies but I love sci-fi movies."},
{"role": "assistant", "content": "Got it! I'll avoid thriller recommendations and suggest sci-fi movies in the future."}
]
m.add(messages, user_id="john")
```
```typescript TypeScript
import { Memory } from 'mem0ai/oss';
const config = {
embedder: {
provider: 'google',
config: {
apiKey: process.env.GOOGLE_API_KEY || '',
model: 'text-embedding-004',
// The output dimensionality is fixed at 768 for Google AI embeddings
},
},
};
const memory = new Memory(config);
const messages = [
{"role": "user", "content": "I'm planning to watch a movie tonight. Any recommendations?"},
{"role": "assistant", "content": "How about a thriller movies? They can be quite engaging."},
{"role": "user", "content": "I'm not a big fan of thriller movies but I love sci-fi movies."},
{"role": "assistant", "content": "Got it! I'll avoid thriller recommendations and suggest sci-fi movies in the future."}
]
await memory.add(messages, { userId: "john" });
```
</CodeGroup>
### Config
Here are the parameters available for configuring Gemini embedder:
| Parameter | Description | Default Value |
| --- | --- | --- |
| `model` | The name of the embedding model to use | `models/text-embedding-004` |
| `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` |
+68 -18
View File
@@ -44,29 +44,33 @@ m.add(messages, user_id="alice", metadata={"category": "movies"})
```
```typescript TypeScript
import { Memory } from "mem0ai";
import { Memory } from 'mem0ai/oss';
import { OpenAIEmbeddings } from "@langchain/openai";
const embeddings = new OpenAIEmbeddings();
// Initialize a LangChain embeddings model directly
const openaiEmbeddings = new OpenAIEmbeddings({
modelName: "text-embedding-3-small",
dimensions: 1536,
apiKey: process.env.OPENAI_API_KEY,
});
const config = {
"embedder": {
"provider": "langchain",
"config": {
"model": embeddings
}
}
}
embedder: {
provider: 'langchain',
config: {
model: openaiEmbeddings,
},
},
};
const memory = new Memory(config);
const messages = [
{ role: "user", content: "I'm planning to watch a movie tonight. Any recommendations?" },
{ role: "assistant", content: "How about a thriller movies? They can be quite engaging." },
{ role: "user", content: "I'm not a big fan of thriller movies but I love sci-fi movies." },
{ role: "assistant", content: "Got it! I'll avoid thriller recommendations and suggest sci-fi movies in the future." }
{"role": "user", "content": "I'm planning to watch a movie tonight. Any recommendations?"},
{"role": "assistant", "content": "How about a thriller movies? They can be quite engaging."},
{"role": "user", "content": "I'm not a big fan of thriller movies but I love sci-fi movies."},
{"role": "assistant", "content": "Got it! I'll avoid thriller recommendations and suggest sci-fi movies in the future."}
]
memory.add(messages, user_id="alice", metadata={"category": "movies"})
await memory.add(messages, { userId: "alice", metadata: { category: "movies" } });
```
</CodeGroup>
@@ -96,9 +100,10 @@ When using LangChain as an embedder provider, you'll need to:
### Examples with Different Providers
<CodeGroup>
#### HuggingFace Embeddings
```python
```python Python
from langchain_huggingface import HuggingFaceEmbeddings
# Initialize a HuggingFace embeddings model
@@ -117,9 +122,33 @@ config = {
}
```
```typescript TypeScript
import { Memory } from 'mem0ai/oss';
import { HuggingFaceEmbeddings } from "@langchain/community/embeddings/hf";
// Initialize a HuggingFace embeddings model
const hfEmbeddings = new HuggingFaceEmbeddings({
modelName: "BAAI/bge-small-en-v1.5",
encode: {
normalize_embeddings: true,
},
});
const config = {
embedder: {
provider: 'langchain',
config: {
model: hfEmbeddings,
},
},
};
```
</CodeGroup>
<CodeGroup>
#### Ollama Embeddings
```python
```python Python
from langchain_ollama import OllamaEmbeddings
# Initialize an Ollama embeddings model
@@ -137,6 +166,27 @@ config = {
}
```
```typescript TypeScript
import { Memory } from 'mem0ai/oss';
import { OllamaEmbeddings } from "@langchain/community/embeddings/ollama";
// Initialize an Ollama embeddings model
const ollamaEmbeddings = new OllamaEmbeddings({
model: "nomic-embed-text",
baseUrl: "http://localhost:11434", // Ollama server URL
});
const config = {
embedder: {
provider: 'langchain',
config: {
model: ollamaEmbeddings,
},
},
};
```
</CodeGroup>
<Note>
Make sure to install the necessary LangChain packages and any provider-specific dependencies.
</Note>
+39 -4
View File
@@ -2,7 +2,8 @@ You can use embedding models from Ollama to run Mem0 locally.
### Usage
```python
<CodeGroup>
```python Python
import os
from mem0 import Memory
@@ -21,18 +22,52 @@ m = Memory.from_config(config)
messages = [
{"role": "user", "content": "I'm planning to watch a movie tonight. Any recommendations?"},
{"role": "assistant", "content": "How about a thriller movies? They can be quite engaging."},
{"role": "user", "content": "I’m not a big fan of thriller movies but I love sci-fi movies."},
{"role": "user", "content": "I'm not a big fan of thriller movies but I love sci-fi movies."},
{"role": "assistant", "content": "Got it! I'll avoid thriller recommendations and suggest sci-fi movies in the future."}
]
m.add(messages, user_id="john")
```
```typescript TypeScript
import { Memory } from 'mem0ai/oss';
const config = {
embedder: {
provider: 'ollama',
config: {
model: 'nomic-embed-text:latest', // or any other Ollama embedding model
url: 'http://localhost:11434', // Ollama server URL
},
},
};
const memory = new Memory(config);
const messages = [
{"role": "user", "content": "I'm planning to watch a movie tonight. Any recommendations?"},
{"role": "assistant", "content": "How about a thriller movies? They can be quite engaging."},
{"role": "user", "content": "I'm not a big fan of thriller movies but I love sci-fi movies."},
{"role": "assistant", "content": "Got it! I'll avoid thriller recommendations and suggest sci-fi movies in the future."}
]
await memory.add(messages, { userId: "john" });
```
</CodeGroup>
### Config
Here are the parameters available for configuring Ollama embedder:
<Tabs>
<Tab title="Python">
| Parameter | Description | Default Value |
| --- | --- | --- |
| `model` | The name of the OpenAI model to use | `nomic-embed-text` |
| `model` | The name of the Ollama model to use | `nomic-embed-text` |
| `embedding_dims` | Dimensions of the embedding model | `512` |
| `ollama_base_url` | Base URL for ollama connection | `None` |
| `ollama_base_url` | Base URL for ollama connection | `None` |
</Tab>
<Tab title="TypeScript">
| Parameter | Description | Default Value |
| --- | --- | --- |
| `model` | The name of the Ollama model to use | `nomic-embed-text:latest` |
| `url` | Base URL for Ollama server | `http://localhost:11434` |
</Tab>
</Tabs>
+2 -3
View File
@@ -4,8 +4,6 @@ icon: "info"
iconType: "solid"
---
<Snippet file="paper-release.mdx" />
Mem0 offers support for various embedding models, allowing users to choose the one that best suits their needs.
## Supported Embedders
@@ -21,11 +19,12 @@ 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>
<Card title="Langchain" href="/components/embedders/models/langchain"></Card>
<Card title="AWS Bedrock" href="/components/embedders/models/aws_bedrock"></Card>
</CardGroup>
## Usage
+9 -2
View File
@@ -4,8 +4,6 @@ icon: "gear"
iconType: "solid"
---
<Snippet file="paper-release.mdx" />
## How to define configurations?
<Tabs>
@@ -58,6 +56,7 @@ config = {
m = Memory.from_config(config)
m.add("Your text here", user_id="user", metadata={"category": "example"})
```
```typescript TypeScript
@@ -76,6 +75,7 @@ const config = {
const memory = new Memory(config);
await memory.add("Your text here", { userId: "user123", metadata: { category: "example" } });
```
</CodeGroup>
## Why is Config Needed?
@@ -110,7 +110,14 @@ Here's a comprehensive list of all parameters that can be used across different
| `azure_kwargs` | Azure LLM args for initialization | AzureOpenAI |
| `deepseek_base_url` | Base URL for DeepSeek API | DeepSeek |
| `xai_base_url` | Base URL for XAI API | XAI |
| `sarvam_base_url` | Base URL for Sarvam API | Sarvam |
| `reasoning_effort` | Reasoning level (low, medium, high) | Sarvam |
| `frequency_penalty` | Penalize frequent tokens (-2.0 to 2.0) | Sarvam |
| `presence_penalty` | Penalize existing tokens (-2.0 to 2.0) | Sarvam |
| `seed` | Seed for deterministic sampling | Sarvam |
| `stop` | Stop sequences (max 4) | Sarvam |
| `lmstudio_base_url` | Base URL for LM Studio API | LM Studio |
| `response_callback` | LLM response callback function | OpenAI |
</Tab>
<Tab title="TypeScript">
| Parameter | Description | Provider |
+3 -4
View File
@@ -2,9 +2,8 @@
title: Anthropic
---
<Snippet file="paper-release.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
@@ -20,7 +19,7 @@ config = {
"llm": {
"provider": "anthropic",
"config": {
"model": "claude-3-7-sonnet-latest",
"model": "claude-sonnet-4-20250514",
"temperature": 0.1,
"max_tokens": 2000,
}
@@ -45,7 +44,7 @@ const config = {
provider: 'anthropic',
config: {
apiKey: process.env.ANTHROPIC_API_KEY || '',
model: 'claude-3-7-sonnet-latest',
model: 'claude-sonnet-4-20250514',
temperature: 0.1,
maxTokens: 2000,
},
+3 -6
View File
@@ -2,8 +2,6 @@
title: AWS Bedrock
---
<Snippet file="paper-release.mdx" />
### Setup
- Before using the AWS Bedrock LLM, make sure you have the appropriate model access from [Bedrock Console](https://us-east-1.console.aws.amazon.com/bedrock/home?region=us-east-1#/modelaccess).
- You will also need to authenticate the `boto3` client by using a method in the [AWS documentation](https://boto3.amazonaws.com/v1/documentation/api/latest/guide/credentials.html#configuring-credentials)
@@ -15,16 +13,15 @@ title: AWS Bedrock
import os
from mem0 import Memory
os.environ["OPENAI_API_KEY"] = "your-api-key" # used for embedding model
os.environ['AWS_REGION'] = 'us-east-1'
os.environ["AWS_ACCESS_KEY"] = "xx"
os.environ['AWS_REGION'] = 'us-west-2'
os.environ["AWS_ACCESS_KEY_ID"] = "xx"
os.environ["AWS_SECRET_ACCESS_KEY"] = "xx"
config = {
"llm": {
"provider": "aws_bedrock",
"config": {
"model": "arn:aws:bedrock:us-east-1:123456789012:model/your-model-name",
"model": "anthropic.claude-3-5-haiku-20241022-v1:0",
"temperature": 0.2,
"max_tokens": 2000,
}
+42 -2
View File
@@ -2,12 +2,12 @@
title: Azure OpenAI
---
<Snippet file="paper-release.mdx" />
<Note> Mem0 Now Supports Azure OpenAI Models in TypeScript SDK </Note>
To use Azure OpenAI models, you have to set the `LLM_AZURE_OPENAI_API_KEY`, `LLM_AZURE_ENDPOINT`, `LLM_AZURE_DEPLOYMENT` and `LLM_AZURE_API_VERSION` environment variables. You can obtain the Azure API key from the [Azure](https://azure.microsoft.com/).
Optionally, you can use Azure Identity to authenticate with Azure OpenAI, which allows you to use managed identities or service principals for production and Azure CLI login for development instead of an API key. If an Azure Identity is to be used, ***do not*** set the `LLM_AZURE_OPENAI_API_KEY` environment variable or the api_key in the config dictionary.
> **Note**: The following are currently unsupported with reasoning models `Parallel tool calling`,`temperature`, `top_p`, `presence_penalty`, `frequency_penalty`, `logprobs`, `top_logprobs`, `logit_bias`, `max_tokens`
@@ -18,6 +18,8 @@ To use Azure OpenAI models, you have to set the `LLM_AZURE_OPENAI_API_KEY`, `LLM
import os
from mem0 import Memory
os.environ["OPENAI_API_KEY"] = "your-api-key" # used for embedding model
os.environ["LLM_AZURE_OPENAI_API_KEY"] = "your-api-key"
os.environ["LLM_AZURE_DEPLOYMENT"] = "your-deployment-name"
os.environ["LLM_AZURE_ENDPOINT"] = "your-api-base-url"
@@ -116,6 +118,44 @@ config = {
}
```
As an alternative to using an API key, the Azure Identity credential chain can be used to authenticate with [Azure OpenAI role-based security](https://learn.microsoft.com/en-us/azure/ai-foundry/openai/how-to/role-based-access-control).
<Note> If an API key is provided, it will be used for authentication over an Azure Identity </Note>
Below is a sample configuration for using Mem0 with Azure OpenAI and Azure Identity:
```python
import os
from mem0 import Memory
# You can set the values directly in the config dictionary or use environment variables
os.environ["LLM_AZURE_DEPLOYMENT"] = "your-deployment-name"
os.environ["LLM_AZURE_ENDPOINT"] = "your-api-base-url"
os.environ["LLM_AZURE_API_VERSION"] = "version-to-use"
config = {
"llm": {
"provider": "azure_openai_structured",
"config": {
"model": "your-deployment-name",
"temperature": 0.1,
"max_tokens": 2000,
"azure_kwargs": {
"azure_deployment": "<your-deployment-name>",
"api_version": "<version-to-use>",
"azure_endpoint": "<your-api-base-url>",
"default_headers": {
"CustomHeader": "your-custom-header",
}
}
}
}
}
```
Refer to [Azure Identity troubleshooting tips](https://github.com/Azure/azure-sdk-for-python/blob/main/sdk/identity/azure-identity/TROUBLESHOOTING.md#troubleshoot-environmentcredential-authentication-issues) for setting up an Azure Identity credential.
## Config
All available parameters for the `azure_openai` config are present in [Master List of All Params in Config](../config).
-2
View File
@@ -2,8 +2,6 @@
title: DeepSeek
---
<Snippet file="paper-release.mdx" />
To use DeepSeek LLM models, you have to set the `DEEPSEEK_API_KEY` environment variable. You can also optionally set `DEEPSEEK_API_BASE` if you need to use a different API endpoint (defaults to "https://api.deepseek.com").
## Usage
+44 -11
View File
@@ -2,40 +2,73 @@
title: Google AI
---
<Snippet file="paper-release.mdx" />
To use the Gemini model, set the `GOOGLE_API_KEY` environment variable. You can obtain the Google/Gemini API key from [Google AI Studio](https://aistudio.google.com/app/apikey).
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)
> **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).
-2
View File
@@ -2,8 +2,6 @@
title: Groq
---
<Snippet file="paper-release.mdx" />
[Groq](https://groq.com/) is the creator of the world's first Language Processing Unit (LPU), providing exceptional speed performance for AI workloads running on their LPU Inference Engine.
In order to use LLMs from Groq, go to their [platform](https://console.groq.com/keys) and get the API key. Set the API key as `GROQ_API_KEY` environment variable to use the model as given below in the example.
+19 -20
View File
@@ -2,7 +2,6 @@
title: LangChain
---
<Snippet file="paper-release.mdx" />
Mem0 supports LangChain as a provider to access a wide range of LLM models. LangChain is a framework for developing applications powered by language models, making it easy to integrate various LLM providers through a consistent interface.
@@ -47,34 +46,34 @@ m.add(messages, user_id="alice", metadata={"category": "movies"})
```
```typescript TypeScript
import { Memory } from "mem0ai";
import { Memory } from 'mem0ai/oss';
import { ChatOpenAI } from "@langchain/openai";
const openai_model = new ChatOpenAI({
model: "gpt-4o",
// Initialize a LangChain model directly
const openaiModel = new ChatOpenAI({
modelName: "gpt-4",
temperature: 0.2,
max_tokens: 2000
})
maxTokens: 2000,
apiKey: process.env.OPENAI_API_KEY,
});
const config = {
"llm": {
"provider": "langchain",
"config": {
"model": openai_model
}
}
}
llm: {
provider: 'langchain',
config: {
model: openaiModel,
},
},
};
const memory = new Memory(config);
const messages = [
{ role: "user", content: "I'm planning to watch a movie tonight. Any recommendations?" },
{ role: "assistant", content: "How about a thriller movies? They can be quite engaging." },
{ role: "user", content: "I'm not a big fan of thriller movies but I love sci-fi movies." },
{ role: "assistant", content: "Got it! I'll avoid thriller recommendations and suggest sci-fi movies in the future." }
{"role": "user", "content": "I'm planning to watch a movie tonight. Any recommendations?"},
{"role": "assistant", "content": "How about a thriller movies? They can be quite engaging."},
{"role": "user", "content": "I'm not a big fan of thriller movies but I love sci-fi movies."},
{"role": "assistant", "content": "Got it! I'll avoid thriller recommendations and suggest sci-fi movies in the future."}
]
memory.add(messages, user_id="alice", metadata={"category": "movies"})
await memory.add(messages, { userId: "alice", metadata: { category: "movies" } });
```
</CodeGroup>
-2
View File
@@ -1,5 +1,3 @@
<Snippet file="paper-release.mdx" />
[Litellm](https://litellm.vercel.app/docs/) is compatible with over 100 large language models (LLMs), all using a standardized input/output format. You can explore the [available models](https://litellm.vercel.app/docs/providers) to use with Litellm. Ensure you set the `API_KEY` for the model you choose to use.
## Usage
+1 -2
View File
@@ -2,8 +2,6 @@
title: LM Studio
---
<Snippet file="paper-release.mdx" />
To use LM Studio with Mem0, you'll need to have LM Studio running locally with its server enabled. LM Studio provides a way to run local LLMs with an OpenAI-compatible API.
## Usage
@@ -23,6 +21,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": {}}},
}
}
}
@@ -2,8 +2,6 @@
title: Mistral AI
---
<Snippet file="paper-release.mdx" />
To use mistral's models, please obtain the Mistral AI api key from their [console](https://console.mistral.ai/). Set the `MISTRAL_API_KEY` environment variable to use the model as given below in the example.
## Usage
+28 -4
View File
@@ -1,10 +1,9 @@
<Snippet file="paper-release.mdx" />
You can use LLMs from Ollama to run Mem0 locally. These [models](https://ollama.com/search?c=tools) support tool support.
## Usage
```python
<CodeGroup>
```python Python
import os
from mem0 import Memory
@@ -25,12 +24,37 @@ m = Memory.from_config(config)
messages = [
{"role": "user", "content": "I'm planning to watch a movie tonight. Any recommendations?"},
{"role": "assistant", "content": "How about a thriller movies? They can be quite engaging."},
{"role": "user", "content": "I’m not a big fan of thriller movies but I love sci-fi movies."},
{"role": "user", "content": "I'm not a big fan of thriller movies but I love sci-fi movies."},
{"role": "assistant", "content": "Got it! I'll avoid thriller recommendations and suggest sci-fi movies in the future."}
]
m.add(messages, user_id="alice", metadata={"category": "movies"})
```
```typescript TypeScript
import { Memory } from 'mem0ai/oss';
const config = {
llm: {
provider: 'ollama',
config: {
model: 'llama3.1:8b', // or any other Ollama model
url: 'http://localhost:11434', // Ollama server URL
temperature: 0.1,
},
},
};
const memory = new Memory(config);
const messages = [
{"role": "user", "content": "I'm planning to watch a movie tonight. Any recommendations?"},
{"role": "assistant", "content": "How about a thriller movies? They can be quite engaging."},
{"role": "user", "content": "I'm not a big fan of thriller movies but I love sci-fi movies."},
{"role": "assistant", "content": "Got it! I'll avoid thriller recommendations and suggest sci-fi movies in the future."}
]
await memory.add(messages, { userId: "alice", metadata: { category: "movies" } });
```
</CodeGroup>
## Config
All available parameters for the `ollama` config are present in [Master List of All Params in Config](../config).
+2 -2
View File
@@ -2,10 +2,10 @@
title: OpenAI
---
<Snippet file="paper-release.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>
+73
View File
@@ -0,0 +1,73 @@
---
title: Sarvam AI
---
**Sarvam AI** is an Indian AI company developing language models with a focus on Indian languages and cultural context. Their latest model **Sarvam-M** is designed to understand and generate content in multiple Indian languages while maintaining high performance in English.
To use Sarvam AI's models, please set the `SARVAM_API_KEY` which you can get from their [platform](https://dashboard.sarvam.ai/).
## Usage
```python
import os
from mem0 import Memory
os.environ["OPENAI_API_KEY"] = "your-api-key" # used for embedding model
os.environ["SARVAM_API_KEY"] = "your-api-key"
config = {
"llm": {
"provider": "sarvam",
"config": {
"model": "sarvam-m",
"temperature": 0.7,
}
}
}
m = Memory.from_config(config)
messages = [
{"role": "user", "content": "I'm planning to watch a movie tonight. Any recommendations?"},
{"role": "assistant", "content": "How about a thriller movies? They can be quite engaging."},
{"role": "user", "content": "I'm not a big fan of thriller movies but I love sci-fi movies."},
{"role": "assistant", "content": "Got it! I'll avoid thriller recommendations and suggest sci-fi movies in the future."}
]
m.add(messages, user_id="alex")
```
## Advanced Usage with Sarvam-Specific Features
```python
import os
from mem0 import Memory
config = {
"llm": {
"provider": "sarvam",
"config": {
"model": {
"name": "sarvam-m",
"reasoning_effort": "high", # Enable advanced reasoning
"frequency_penalty": 0.1, # Reduce repetition
"seed": 42 # For deterministic outputs
},
"temperature": 0.3,
"max_tokens": 2000,
"api_key": "your-sarvam-api-key"
}
}
}
m = Memory.from_config(config)
# Example with Hindi conversation
messages = [
{"role": "user", "content": "मैं SBI में joint account खोलना चाहता हूँ।"},
{"role": "assistant", "content": "SBI में joint account खोलने के लिए आपको कुछ documents की जरूरत होगी। क्या आप जानना चाहते हैं कि कौन से documents चाहिए?"}
]
m.add(messages, user_id="rajesh", metadata={"language": "hindi", "topic": "banking"})
```
## Config
All available parameters for the `sarvam` config are present in [Master List of All Params in Config](../config).
-2
View File
@@ -1,5 +1,3 @@
<Snippet file="paper-release.mdx" />
To use TogetherAI LLM models, you have to set the `TOGETHER_API_KEY` environment variable. You can obtain the TogetherAI API key from their [Account settings page](https://api.together.xyz/settings/api-keys).
## Usage
+107
View File
@@ -0,0 +1,107 @@
---
title: vLLM
---
[vLLM](https://docs.vllm.ai/) is a high-performance inference engine for large language models that provides significant performance improvements for local inference. It's designed to maximize throughput and memory efficiency for serving LLMs.
## Prerequisites
1. **Install vLLM**:
```bash
pip install vllm
```
2. **Start vLLM server**:
```bash
# For testing with a small model
vllm serve microsoft/DialoGPT-medium --port 8000
# For production with a larger model (requires GPU)
vllm serve Qwen/Qwen2.5-32B-Instruct --port 8000
```
## Usage
```python
import os
from mem0 import Memory
os.environ["OPENAI_API_KEY"] = "your-api-key" # used for embedding model
config = {
"llm": {
"provider": "vllm",
"config": {
"model": "Qwen/Qwen2.5-32B-Instruct",
"vllm_base_url": "http://localhost:8000/v1",
"temperature": 0.1,
"max_tokens": 2000,
}
}
}
m = Memory.from_config(config)
messages = [
{"role": "user", "content": "I'm planning to watch a movie tonight. Any recommendations?"},
{"role": "assistant", "content": "How about thriller movies? They can be quite engaging."},
{"role": "user", "content": "I'm not a big fan of thrillers, but I love sci-fi movies."},
{"role": "assistant", "content": "Got it! I'll avoid thrillers and suggest sci-fi movies instead."}
]
m.add(messages, user_id="alice", metadata={"category": "movies"})
```
## Configuration Parameters
| Parameter | Description | Default | Environment Variable |
| --------------- | --------------------------------- | ----------------------------- | -------------------- |
| `model` | Model name running on vLLM server | `"Qwen/Qwen2.5-32B-Instruct"` | - |
| `vllm_base_url` | vLLM server URL | `"http://localhost:8000/v1"` | `VLLM_BASE_URL` |
| `api_key` | API key (dummy for local) | `"vllm-api-key"` | `VLLM_API_KEY` |
| `temperature` | Sampling temperature | `0.1` | - |
| `max_tokens` | Maximum tokens to generate | `2000` | - |
## Environment Variables
You can set these environment variables instead of specifying them in config:
```bash
export VLLM_BASE_URL="http://localhost:8000/v1"
export VLLM_API_KEY="your-vllm-api-key"
export OPENAI_API_KEY="your-openai-api-key" # for embeddings
```
## Benefits
- **High Performance**: 2-24x faster inference than standard implementations
- **Memory Efficient**: Optimized memory usage with PagedAttention
- **Local Deployment**: Keep your data private and reduce API costs
- **Easy Integration**: Drop-in replacement for other LLM providers
- **Flexible**: Works with any model supported by vLLM
## Troubleshooting
1. **Server not responding**: Make sure vLLM server is running
```bash
curl http://localhost:8000/health
```
2. **404 errors**: Ensure correct base URL format
```python
"vllm_base_url": "http://localhost:8000/v1" # Note the /v1
```
3. **Model not found**: Check model name matches server
4. **Out of memory**: Try smaller models or reduce `max_model_len`
```bash
vllm serve Qwen/Qwen2.5-32B-Instruct --max-model-len 4096
```
## Config
All available parameters for the `vllm` config are present in [Master List of All Params in Config](../config).
-2
View File
@@ -2,8 +2,6 @@
title: xAI
---
<Snippet file="paper-release.mdx" />
[xAI](https://x.ai/) is a new AI company founded by Elon Musk that develops large language models, including Grok. Grok is trained on real-time data from X (formerly Twitter) and aims to provide accurate, up-to-date responses with a touch of wit and humor.
In order to use LLMs from xAI, go to their [platform](https://console.x.ai) and get the API key. Set the API key as `XAI_API_KEY` environment variable to use the model as given below in the example.
+6 -6
View File
@@ -4,8 +4,6 @@ icon: "info"
iconType: "solid"
---
<Snippet file="paper-release.mdx" />
Mem0 includes built-in support for various popular large language models. Memory can utilize the LLM provided by the user, ensuring efficient use for specific needs.
## Usage
@@ -14,7 +12,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**.
@@ -28,12 +28,12 @@ To view all supported llms, visit the [Supported LLMs](./models).
<Card title="Together" href="/components/llms/models/together" />
<Card title="Groq" href="/components/llms/models/groq" />
<Card title="Litellm" href="/components/llms/models/litellm" />
<Card title="Mistral AI" href="/components/llms/models/mistral_ai" />
<Card title="Google AI" href="/components/llms/models/google_ai" />
<Card title="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" />
<Card title="LM Studio" href="/components/llms/models/lmstudio" />
<Card title="Langchain" href="/components/llms/models/langchain" />
</CardGroup>
+145
View File
@@ -0,0 +1,145 @@
---
title: Configuration
icon: "gear"
iconType: "solid"
---
## How to define configurations?
The `reranker` configuration is defined as an object with two main keys:
- `provider`: The name of the reranker provider (e.g., "cohere", "sentence_transformer", "huggingface", "llm_reranker")
- `config`: A nested dictionary containing provider-specific settings
## Basic Configuration
Here's how to configure a reranker with Mem0:
```python
from mem0 import Memory
config = {
"reranker": {
"provider": "cohere",
"config": {
"api_key": "your-api-key",
"top_n": 10,
"model": "rerank-english-v3.0"
}
}
}
memory = Memory.from_config(config)
```
## Configuration Parameters
| Parameter | Description | Required | Default |
|-----------|-------------|----------|---------|
| `provider` | Reranker provider name | Yes | - |
| `config` | Provider-specific configuration | Yes | - |
### Common Config Parameters
| Parameter | Description | Providers |
|-----------|-------------|-----------|
| `api_key` | API key for the service | Cohere, Hugging Face |
| `model` | Model name to use | All |
| `top_n` | Number of results to return | All |
| `device` | Device to run on (cpu/cuda/mps) | Sentence Transformer, Hugging Face |
## Provider-Specific Examples
### Cohere
```python
config = {
"reranker": {
"provider": "cohere",
"config": {
"api_key": "your-cohere-api-key",
"model": "rerank-english-v3.0",
"top_n": 5
}
}
}
```
### Sentence Transformer
```python
config = {
"reranker": {
"provider": "sentence_transformer",
"config": {
"model": "cross-encoder/ms-marco-MiniLM-L-6-v2",
"device": "cpu",
"top_n": 10
}
}
}
```
### Hugging Face
```python
config = {
"reranker": {
"provider": "huggingface",
"config": {
"api_key": "your-hf-token",
"model": "BAAI/bge-reranker-large",
"top_n": 8
}
}
}
```
### LLM Reranker
```python
config = {
"reranker": {
"provider": "llm_reranker",
"config": {
"llm": {
"provider": "openai",
"config": {
"model": "gpt-4",
"api_key": "your-openai-key"
}
},
"top_n": 5
}
}
}
```
## Advanced Configuration
You can combine rerankers with other components:
```python
config = {
"llm": {
"provider": "openai",
"config": {
"model": "gpt-4",
"api_key": "your-openai-key"
}
},
"vector_store": {
"provider": "qdrant",
"config": {
"collection_name": "memories",
"host": "localhost",
"port": 6333
}
},
"reranker": {
"provider": "cohere",
"config": {
"api_key": "your-cohere-key",
"model": "rerank-english-v3.0",
"top_n": 10
}
}
}
```
For provider-specific configuration details, visit the individual reranker pages.
@@ -0,0 +1,217 @@
---
title: Custom Prompts
icon: "pencil"
iconType: "solid"
---
When using LLM rerankers, you can customize the prompts used for ranking to better suit your specific use case and domain.
## Default Prompt
The default LLM reranker prompt is designed to be general-purpose:
```
Given a query and a list of memory entries, rank the memory entries based on their relevance to the query.
Rate each memory on a scale of 1-10 where 10 is most relevant.
Query: {query}
Memory entries:
{memories}
Provide your ranking as a JSON array with scores for each memory.
```
## Custom Prompt Configuration
You can provide a custom prompt template when configuring the LLM reranker:
```python
from mem0 import Memory
custom_prompt = """
You are an expert at ranking memories for a personal AI assistant.
Given a user query and a list of memory entries, rank each memory based on:
1. Direct relevance to the query
2. Temporal relevance (recent memories may be more important)
3. Emotional significance
4. Actionability
Query: {query}
User Context: {user_context}
Memory entries:
{memories}
Rate each memory from 1-10 and provide reasoning.
Return as JSON: {{"rankings": [{{"index": 0, "score": 8, "reason": "..."}}]}}
"""
config = {
"reranker": {
"provider": "llm_reranker",
"config": {
"llm": {
"provider": "openai",
"config": {
"model": "gpt-4",
"api_key": "your-openai-key"
}
},
"custom_prompt": custom_prompt,
"top_n": 5
}
}
}
memory = Memory.from_config(config)
```
## Prompt Variables
Your custom prompt can use the following variables:
| Variable | Description |
|----------|-------------|
| `{query}` | The search query |
| `{memories}` | The list of memory entries to rank |
| `{user_id}` | The user ID (if available) |
| `{user_context}` | Additional user context (if provided) |
## Domain-Specific Examples
### Customer Support
```python
customer_support_prompt = """
You are ranking customer support conversation memories.
Prioritize memories that:
- Relate to the current customer issue
- Show previous resolution patterns
- Indicate customer preferences or constraints
Query: {query}
Customer Context: Previous interactions with this customer
Memories:
{memories}
Rank each memory 1-10 based on support relevance.
"""
```
### Educational Content
```python
educational_prompt = """
Rank these learning memories for a student query.
Consider:
- Prerequisite knowledge requirements
- Learning progression and difficulty
- Relevance to current learning objectives
Student Query: {query}
Learning Context: {user_context}
Available memories:
{memories}
Score each memory for educational value (1-10).
"""
```
### Personal Assistant
```python
personal_assistant_prompt = """
Rank personal memories for relevance to the user's query.
Consider:
- Recent vs. historical importance
- Personal preferences and habits
- Contextual relationships between memories
Query: {query}
Personal context: {user_context}
Memories to rank:
{memories}
Provide relevance scores (1-10) with brief explanations.
"""
```
## Advanced Prompt Techniques
### Multi-Criteria Ranking
```python
multi_criteria_prompt = """
Evaluate memories using multiple criteria:
1. RELEVANCE (40%): How directly related to the query
2. RECENCY (20%): How recent the memory is
3. IMPORTANCE (25%): Personal or business significance
4. ACTIONABILITY (15%): How useful for next steps
Query: {query}
Context: {user_context}
Memories:
{memories}
For each memory, provide:
- Overall score (1-10)
- Breakdown by criteria
- Final ranking recommendation
Format: JSON with detailed scoring
"""
```
### Contextual Ranking
```python
contextual_prompt = """
Consider the following context when ranking memories:
- Current user situation: {user_context}
- Time of day: {current_time}
- Recent activities: {recent_activities}
Query: {query}
Rank these memories considering both direct relevance and contextual appropriateness:
{memories}
Provide contextually-aware relevance scores (1-10).
"""
```
## Best Practices
1. **Be Specific**: Clearly define what makes a memory relevant for your use case
2. **Use Examples**: Include examples in your prompt for better model understanding
3. **Structure Output**: Specify the exact JSON format you want returned
4. **Test Iteratively**: Refine your prompt based on actual ranking performance
5. **Consider Token Limits**: Keep prompts concise while being comprehensive
## Prompt Testing
You can test different prompts by comparing ranking results:
```python
# Test multiple prompt variations
prompts = [
default_prompt,
custom_prompt_v1,
custom_prompt_v2
]
for i, prompt in enumerate(prompts):
config["reranker"]["config"]["custom_prompt"] = prompt
memory = Memory.from_config(config)
results = memory.search("test query", user_id="test_user")
print(f"Prompt {i+1} results: {results}")
```
## Common Issues
- **Too Long**: Keep prompts under token limits for your chosen LLM
- **Too Vague**: Be specific about ranking criteria
- **Inconsistent Format**: Ensure JSON output format is clearly specified
- **Missing Context**: Include relevant variables for your use case
+116
View File
@@ -0,0 +1,116 @@
---
title: Cohere
---
Cohere provides state-of-the-art reranking models that can significantly improve the relevance of search results. Cohere's rerankers are optimized for various languages and use cases.
## Usage
To use Cohere's reranker with Mem0:
```python
import os
from mem0 import Memory
os.environ["COHERE_API_KEY"] = "your-cohere-api-key"
config = {
"reranker": {
"provider": "cohere",
"config": {
"api_key": "your-cohere-api-key", # Can also use environment variable
"model": "rerank-english-v3.0",
"top_n": 10
}
}
}
memory = Memory.from_config(config)
# Use memory as usual
memory.add("I love playing basketball", user_id="alice")
memory.add("I enjoy watching movies", user_id="alice")
# Search will now use Cohere reranking
results = memory.search("What sports does Alice like?", user_id="alice")
```
## Configuration
| Parameter | Description | Default |
|-----------|-------------|---------|
| `api_key` | Cohere API key | Required |
| `model` | Cohere rerank model | `rerank-english-v3.0` |
| `top_n` | Number of results to return | `10` |
## Available Models
- `rerank-english-v3.0`: Latest English reranking model
- `rerank-multilingual-v3.0`: Multilingual reranking model
- `rerank-english-v2.0`: Previous English model
- `rerank-multilingual-v2.0`: Previous multilingual model
## Example with Different Models
### English Reranker
```python
config = {
"reranker": {
"provider": "cohere",
"config": {
"api_key": "your-cohere-api-key",
"model": "rerank-english-v3.0",
"top_n": 5
}
}
}
```
### Multilingual Reranker
```python
config = {
"reranker": {
"provider": "cohere",
"config": {
"api_key": "your-cohere-api-key",
"model": "rerank-multilingual-v3.0",
"top_n": 8
}
}
}
```
## Environment Variables
You can set your Cohere API key as an environment variable:
```bash
export COHERE_API_KEY="your-cohere-api-key"
```
Then use the config without specifying the API key:
```python
config = {
"reranker": {
"provider": "cohere",
"config": {
"model": "rerank-english-v3.0",
"top_n": 10
}
}
}
```
## Getting Your API Key
1. Sign up at [Cohere](https://cohere.ai/)
2. Navigate to the API keys section in your dashboard
3. Generate a new API key
4. Use this key in your configuration
## Performance Considerations
- Cohere rerankers work best with 10-100 candidate documents
- Higher `top_n` values provide more comprehensive reranking but may increase latency
- The v3.0 models generally provide better performance than v2.0 models
@@ -0,0 +1,352 @@
---
title: Hugging Face Reranker
description: 'Access thousands of reranking models from Hugging Face Hub'
icon: "face-smile"
iconType: "solid"
---
## Overview
The Hugging Face reranker provider gives you access to thousands of reranking models available on the Hugging Face Hub. This includes popular models like BAAI's BGE rerankers and other state-of-the-art cross-encoder models.
## Configuration
### Basic Setup
```python
from mem0 import Memory
config = {
"reranker": {
"provider": "huggingface",
"config": {
"model": "BAAI/bge-reranker-base",
"device": "cpu"
}
}
}
m = Memory.from_config(config)
```
### Configuration Parameters
| Parameter | Type | Default | Description |
|-----------|------|---------|-------------|
| `model` | str | Required | Hugging Face model identifier |
| `device` | str | "cpu" | Device to run model on ("cpu", "cuda", "mps") |
| `batch_size` | int | 32 | Batch size for processing |
| `max_length` | int | 512 | Maximum input sequence length |
| `trust_remote_code` | bool | False | Allow remote code execution |
### Advanced Configuration
```python
config = {
"reranker": {
"provider": "huggingface",
"config": {
"model": "BAAI/bge-reranker-large",
"device": "cuda",
"batch_size": 16,
"max_length": 512,
"trust_remote_code": False,
"model_kwargs": {
"torch_dtype": "float16"
}
}
}
}
```
## Popular Models
### BGE Rerankers (Recommended)
```python
# Base model - good balance of speed and quality
config = {
"reranker": {
"provider": "huggingface",
"config": {
"model": "BAAI/bge-reranker-base",
"device": "cuda"
}
}
}
# Large model - better quality, slower
config = {
"reranker": {
"provider": "huggingface",
"config": {
"model": "BAAI/bge-reranker-large",
"device": "cuda"
}
}
}
# v2 models - latest improvements
config = {
"reranker": {
"provider": "huggingface",
"config": {
"model": "BAAI/bge-reranker-v2-m3",
"device": "cuda"
}
}
}
```
### Multilingual Models
```python
# Multilingual BGE reranker
config = {
"reranker": {
"provider": "huggingface",
"config": {
"model": "BAAI/bge-reranker-v2-multilingual",
"device": "cuda"
}
}
}
```
### Domain-Specific Models
```python
# For code search
config = {
"reranker": {
"provider": "huggingface",
"config": {
"model": "microsoft/codebert-base",
"device": "cuda"
}
}
}
# For biomedical content
config = {
"reranker": {
"provider": "huggingface",
"config": {
"model": "dmis-lab/biobert-base-cased-v1.1",
"device": "cuda"
}
}
}
```
## Usage Examples
### Basic Usage
```python
from mem0 import Memory
m = Memory.from_config(config)
# Add some memories
m.add("I love hiking in the mountains", user_id="alice")
m.add("Pizza is my favorite food", user_id="alice")
m.add("I enjoy reading science fiction books", user_id="alice")
# Search with reranking
results = m.search(
"What outdoor activities do I enjoy?",
user_id="alice",
rerank=True
)
for result in results["results"]:
print(f"Memory: {result['memory']}")
print(f"Score: {result['score']:.3f}")
```
### Batch Processing
```python
# Process multiple queries efficiently
queries = [
"What are my hobbies?",
"What food do I like?",
"What books interest me?"
]
results = []
for query in queries:
result = m.search(query, user_id="alice", rerank=True)
results.append(result)
```
## Performance Optimization
### GPU Acceleration
```python
# Use GPU for better performance
config = {
"reranker": {
"provider": "huggingface",
"config": {
"model": "BAAI/bge-reranker-base",
"device": "cuda",
"batch_size": 64, # Increase batch size for GPU
}
}
}
```
### Memory Optimization
```python
# For limited memory environments
config = {
"reranker": {
"provider": "huggingface",
"config": {
"model": "BAAI/bge-reranker-base",
"device": "cpu",
"batch_size": 8, # Smaller batch size
"max_length": 256, # Shorter sequences
"model_kwargs": {
"torch_dtype": "float16" # Half precision
}
}
}
}
```
## Model Comparison
| Model | Size | Quality | Speed | Memory | Best For |
|-------|------|---------|-------|---------|----------|
| bge-reranker-base | 278M | Good | Fast | Low | General use |
| bge-reranker-large | 560M | Better | Medium | Medium | High quality needs |
| bge-reranker-v2-m3 | 568M | Best | Medium | Medium | Latest improvements |
| bge-reranker-v2-multilingual | 568M | Good | Medium | Medium | Multiple languages |
## Error Handling
```python
try:
results = m.search(
"test query",
user_id="alice",
rerank=True
)
except Exception as e:
print(f"Reranking failed: {e}")
# Fall back to vector search only
results = m.search(
"test query",
user_id="alice",
rerank=False
)
```
## Custom Models
### Using Private Models
```python
# Use a private model from Hugging Face
config = {
"reranker": {
"provider": "huggingface",
"config": {
"model": "your-org/custom-reranker",
"device": "cuda",
"use_auth_token": "your-hf-token"
}
}
}
```
### Local Model Path
```python
# Use a locally downloaded model
config = {
"reranker": {
"provider": "huggingface",
"config": {
"model": "/path/to/local/model",
"device": "cuda"
}
}
}
```
## Best Practices
1. **Choose the Right Model**: Balance quality vs speed based on your needs
2. **Use GPU**: Significantly faster than CPU for larger models
3. **Optimize Batch Size**: Tune based on your hardware capabilities
4. **Monitor Memory**: Watch GPU/CPU memory usage with large models
5. **Cache Models**: Download once and reuse to avoid repeated downloads
## Troubleshooting
### Common Issues
**Out of Memory Error**
```python
# Reduce batch size and sequence length
config = {
"reranker": {
"provider": "huggingface",
"config": {
"model": "BAAI/bge-reranker-base",
"batch_size": 4,
"max_length": 256
}
}
}
```
**Model Download Issues**
```python
# Set cache directory
import os
os.environ["TRANSFORMERS_CACHE"] = "/path/to/cache"
# Or use offline mode
config = {
"reranker": {
"provider": "huggingface",
"config": {
"model": "BAAI/bge-reranker-base",
"local_files_only": True
}
}
}
```
**CUDA Not Available**
```python
import torch
config = {
"reranker": {
"provider": "huggingface",
"config": {
"model": "BAAI/bge-reranker-base",
"device": "cuda" if torch.cuda.is_available() else "cpu"
}
}
}
```
## Next Steps
<CardGroup cols={2}>
<Card title="Reranker Overview" icon="sort" href="/components/rerankers/overview">
Learn about reranking concepts
</Card>
<Card title="Configuration Guide" icon="gear" href="/components/rerankers/config">
Detailed configuration options
</Card>
</CardGroup>
@@ -0,0 +1,491 @@
---
title: LLM Reranker
description: 'Use any language model as a reranker with custom prompts'
icon: "robot"
iconType: "solid"
---
## Overview
The LLM reranker allows you to use any supported language model as a reranker. This approach uses prompts to instruct the LLM to score and rank memories based on their relevance to the query. While slower than specialized rerankers, it offers maximum flexibility and can be fine-tuned with custom prompts.
## Configuration
### Basic Setup
```python
from mem0 import Memory
config = {
"reranker": {
"provider": "llm_reranker",
"config": {
"llm": {
"provider": "openai",
"config": {
"model": "gpt-4",
"api_key": "your-openai-api-key"
}
}
}
}
}
m = Memory.from_config(config)
```
### Configuration Parameters
| Parameter | Type | Default | Description |
|-----------|------|---------|-------------|
| `llm` | dict | Required | LLM configuration object |
| `top_k` | int | 10 | Number of results to rerank |
| `temperature` | float | 0.0 | LLM temperature for consistency |
| `custom_prompt` | str | None | Custom reranking prompt |
| `score_range` | tuple | (0, 10) | Score range for relevance |
### Advanced Configuration
```python
config = {
"reranker": {
"provider": "llm_reranker",
"config": {
"llm": {
"provider": "anthropic",
"config": {
"model": "claude-3-sonnet-20240229",
"api_key": "your-anthropic-api-key"
}
},
"top_k": 15,
"temperature": 0.0,
"score_range": (1, 5),
"custom_prompt": """
Rate the relevance of each memory to the query on a scale of 1-5.
Consider semantic similarity, context, and practical utility.
Only provide the numeric score.
"""
}
}
}
```
## Supported LLM Providers
### OpenAI
```python
config = {
"reranker": {
"provider": "llm_reranker",
"config": {
"llm": {
"provider": "openai",
"config": {
"model": "gpt-4",
"api_key": "your-openai-api-key",
"temperature": 0.0
}
}
}
}
}
```
### Anthropic
```python
config = {
"reranker": {
"provider": "llm_reranker",
"config": {
"llm": {
"provider": "anthropic",
"config": {
"model": "claude-3-sonnet-20240229",
"api_key": "your-anthropic-api-key"
}
}
}
}
}
```
### Ollama (Local)
```python
config = {
"reranker": {
"provider": "llm_reranker",
"config": {
"llm": {
"provider": "ollama",
"config": {
"model": "llama2",
"ollama_base_url": "http://localhost:11434"
}
}
}
}
}
```
### Azure OpenAI
```python
config = {
"reranker": {
"provider": "llm_reranker",
"config": {
"llm": {
"provider": "azure_openai",
"config": {
"model": "gpt-4",
"api_key": "your-azure-api-key",
"azure_endpoint": "https://your-resource.openai.azure.com/",
"azure_deployment": "gpt-4-deployment"
}
}
}
}
}
```
## Custom Prompts
### Default Prompt Behavior
The default prompt asks the LLM to score relevance on a 0-10 scale:
```
Given a query and a memory, rate how relevant the memory is to answering the query.
Score from 0 (completely irrelevant) to 10 (perfectly relevant).
Only provide the numeric score.
Query: {query}
Memory: {memory}
Score:
```
### Custom Prompt Examples
#### Domain-Specific Scoring
```python
custom_prompt = """
You are a medical information specialist. Rate how relevant each memory is for answering the medical query.
Consider clinical accuracy, specificity, and practical applicability.
Rate from 1-10 where:
- 1-3: Irrelevant or potentially harmful
- 4-6: Somewhat relevant but incomplete
- 7-8: Relevant and helpful
- 9-10: Highly relevant and clinically useful
Query: {query}
Memory: {memory}
Score:
"""
config = {
"reranker": {
"provider": "llm_reranker",
"config": {
"llm": {
"provider": "openai",
"config": {
"model": "gpt-4",
"api_key": "your-api-key"
}
},
"custom_prompt": custom_prompt
}
}
}
```
#### Contextual Relevance
```python
contextual_prompt = """
Rate how well this memory answers the specific question asked.
Consider:
- Direct relevance to the question
- Completeness of information
- Recency and accuracy
- Practical usefulness
Rate 1-5:
1 = Not relevant
2 = Slightly relevant
3 = Moderately relevant
4 = Very relevant
5 = Perfectly answers the question
Query: {query}
Memory: {memory}
Score:
"""
```
#### Conversational Context
```python
conversation_prompt = """
You are helping evaluate which memories are most useful for a conversational AI assistant.
Rate how helpful this memory would be for generating a relevant response.
Consider:
- Direct relevance to user's intent
- Emotional appropriateness
- Factual accuracy
- Conversation flow
Rate 0-10:
Query: {query}
Memory: {memory}
Score:
"""
```
## Usage Examples
### Basic Usage
```python
from mem0 import Memory
m = Memory.from_config(config)
# Add memories
m.add("I'm allergic to peanuts", user_id="alice")
m.add("I love Italian food", user_id="alice")
m.add("I'm vegetarian", user_id="alice")
# Search with LLM reranking
results = m.search(
"What foods should I avoid?",
user_id="alice",
rerank=True
)
for result in results["results"]:
print(f"Memory: {result['memory']}")
print(f"LLM Score: {result['score']:.2f}")
```
### Batch Processing with Error Handling
```python
def safe_llm_rerank_search(query, user_id, max_retries=3):
for attempt in range(max_retries):
try:
return m.search(query, user_id=user_id, rerank=True)
except Exception as e:
print(f"Attempt {attempt + 1} failed: {e}")
if attempt == max_retries - 1:
# Fall back to vector search
return m.search(query, user_id=user_id, rerank=False)
# Use the safe function
results = safe_llm_rerank_search("What are my preferences?", "alice")
```
## Performance Considerations
### Speed vs Quality Trade-offs
| Model Type | Speed | Quality | Cost | Best For |
|------------|-------|---------|------|----------|
| GPT-3.5 Turbo | Fast | Good | Low | High-volume applications |
| GPT-4 | Medium | Excellent | Medium | Quality-critical applications |
| Claude 3 Sonnet | Medium | Excellent | Medium | Balanced performance |
| Ollama Local | Variable | Good | Free | Privacy-sensitive applications |
### Optimization Strategies
```python
# Fast configuration for high-volume use
fast_config = {
"reranker": {
"provider": "llm_reranker",
"config": {
"llm": {
"provider": "openai",
"config": {
"model": "gpt-3.5-turbo",
"api_key": "your-api-key"
}
},
"top_k": 5, # Limit candidates
"temperature": 0.0
}
}
}
# High-quality configuration
quality_config = {
"reranker": {
"provider": "llm_reranker",
"config": {
"llm": {
"provider": "openai",
"config": {
"model": "gpt-4",
"api_key": "your-api-key"
}
},
"top_k": 15,
"temperature": 0.0
}
}
}
```
## Advanced Use Cases
### Multi-Step Reasoning
```python
reasoning_prompt = """
Evaluate this memory's relevance using multi-step reasoning:
1. What is the main intent of the query?
2. What key information does the memory contain?
3. How directly does the memory address the query?
4. What additional context might be needed?
Based on this analysis, rate relevance 1-10:
Query: {query}
Memory: {memory}
Analysis:
Step 1 (Intent):
Step 2 (Information):
Step 3 (Directness):
Step 4 (Context):
Final Score:
"""
```
### Comparative Ranking
```python
comparative_prompt = """
You will see a query and multiple memories. Rank them in order of relevance.
Consider which memories best answer the question and would be most helpful.
Query: {query}
Memories to rank:
{memories}
Provide scores 1-10 for each memory, considering their relative usefulness.
"""
```
### Emotional Intelligence
```python
emotional_prompt = """
Consider both factual relevance and emotional appropriateness.
Rate how suitable this memory is for responding to the user's query.
Factors to consider:
- Factual accuracy and relevance
- Emotional tone and sensitivity
- User's likely emotional state
- Appropriateness of response
Query: {query}
Memory: {memory}
Emotional Context: {context}
Score (1-10):
"""
```
## Error Handling and Fallbacks
```python
class RobustLLMReranker:
def __init__(self, primary_config, fallback_config=None):
self.primary = Memory.from_config(primary_config)
self.fallback = Memory.from_config(fallback_config) if fallback_config else None
def search(self, query, user_id, max_retries=2):
# Try primary LLM reranker
for attempt in range(max_retries):
try:
return self.primary.search(query, user_id=user_id, rerank=True)
except Exception as e:
print(f"Primary reranker attempt {attempt + 1} failed: {e}")
# Try fallback reranker
if self.fallback:
try:
return self.fallback.search(query, user_id=user_id, rerank=True)
except Exception as e:
print(f"Fallback reranker failed: {e}")
# Final fallback: vector search only
return self.primary.search(query, user_id=user_id, rerank=False)
# Usage
primary_config = {
"reranker": {
"provider": "llm_reranker",
"config": {"llm": {"provider": "openai", "config": {"model": "gpt-4"}}}
}
}
fallback_config = {
"reranker": {
"provider": "llm_reranker",
"config": {"llm": {"provider": "openai", "config": {"model": "gpt-3.5-turbo"}}}
}
}
reranker = RobustLLMReranker(primary_config, fallback_config)
results = reranker.search("What are my preferences?", "alice")
```
## Best Practices
1. **Use Specific Prompts**: Tailor prompts to your domain and use case
2. **Set Temperature to 0**: Ensure consistent scoring across runs
3. **Limit Top-K**: Don't rerank too many candidates to control costs
4. **Implement Fallbacks**: Always have a backup plan for API failures
5. **Monitor Costs**: Track API usage, especially with expensive models
6. **Cache Results**: Consider caching reranking results for repeated queries
7. **Test Prompts**: Experiment with different prompts to find what works best
## Troubleshooting
### Common Issues
**Inconsistent Scores**
- Set temperature to 0.0
- Use more specific prompts
- Consider using multiple calls and averaging
**API Rate Limits**
- Implement exponential backoff
- Use cheaper models for high-volume scenarios
- Add retry logic with delays
**Poor Ranking Quality**
- Refine your custom prompt
- Try different LLM models
- Add examples to your prompt
## Next Steps
<CardGroup cols={2}>
<Card title="Custom Prompts Guide" icon="pencil" href="/components/rerankers/custom-prompts">
Learn to craft effective reranking prompts
</Card>
<Card title="Performance Optimization" icon="bolt" href="/components/rerankers/optimization">
Optimize LLM reranker performance
</Card>
</CardGroup>
@@ -0,0 +1,162 @@
---
title: Sentence Transformer
---
Sentence Transformer rerankers use cross-encoder models that are specifically designed for ranking tasks. These models can run locally and provide good reranking performance without external API calls.
## Usage
To use Sentence Transformer reranker with Mem0:
```python
from mem0 import Memory
config = {
"reranker": {
"provider": "sentence_transformer",
"config": {
"model": "cross-encoder/ms-marco-MiniLM-L-6-v2",
"device": "cpu",
"top_n": 10
}
}
}
memory = Memory.from_config(config)
# Use memory as usual
memory.add("I love playing basketball", user_id="alice")
memory.add("I enjoy watching movies", user_id="alice")
# Search will now use Sentence Transformer reranking
results = memory.search("What sports does Alice like?", user_id="alice")
```
## Configuration
| Parameter | Description | Default |
|-----------|-------------|---------|
| `model` | Sentence Transformer cross-encoder model | `cross-encoder/ms-marco-MiniLM-L-6-v2` |
| `device` | Device to run on (`cpu`, `cuda`, `mps`) | `cpu` |
| `top_n` | Number of results to return | `10` |
## Popular Models
### Lightweight Models
- `cross-encoder/ms-marco-MiniLM-L-6-v2`: Fast and efficient
- `cross-encoder/ms-marco-MiniLM-L-4-v2`: Even faster, slightly lower accuracy
- `cross-encoder/ms-marco-MiniLM-L-2-v2`: Fastest, good for real-time applications
### High-Performance Models
- `cross-encoder/ms-marco-electra-base`: Better accuracy, larger model
- `ms-marco-MiniLM-L-12-v2`: Balanced performance and speed
- `cross-encoder/qnli-electra-base`: Good for question-answering tasks
## Device Configuration
### CPU Usage
```python
config = {
"reranker": {
"provider": "sentence_transformer",
"config": {
"model": "cross-encoder/ms-marco-MiniLM-L-6-v2",
"device": "cpu",
"top_n": 10
}
}
}
```
### GPU Usage (CUDA)
```python
config = {
"reranker": {
"provider": "sentence_transformer",
"config": {
"model": "cross-encoder/ms-marco-electra-base",
"device": "cuda",
"top_n": 15
}
}
}
```
### Apple Silicon (MPS)
```python
config = {
"reranker": {
"provider": "sentence_transformer",
"config": {
"model": "cross-encoder/ms-marco-MiniLM-L-6-v2",
"device": "mps",
"top_n": 10
}
}
}
```
## Installation
The sentence-transformers library is required:
```bash
pip install sentence-transformers
```
For GPU support with CUDA:
```bash
pip install sentence-transformers torch
```
## Performance Optimization
### Model Selection
- Use MiniLM models for faster inference
- Use larger models (electra-base) for better accuracy
- Consider the trade-off between speed and quality
### Device Optimization
- Use GPU (`cuda` or `mps`) for larger models
- CPU is sufficient for MiniLM models
- Batch processing improves GPU utilization
### Memory Considerations
```python
# For memory-constrained environments
config = {
"reranker": {
"provider": "sentence_transformer",
"config": {
"model": "cross-encoder/ms-marco-MiniLM-L-2-v2", # Smallest model
"device": "cpu",
"top_n": 5 # Fewer results to process
}
}
}
```
## Custom Models
You can use any Sentence Transformer cross-encoder model:
```python
config = {
"reranker": {
"provider": "sentence_transformer",
"config": {
"model": "your-custom-model-name",
"device": "cpu",
"top_n": 10
}
}
}
```
## Advantages
- **Local Processing**: No external API calls required
- **Privacy**: Data stays on your infrastructure
- **Cost Effective**: No per-request charges
- **Fast**: Especially with GPU acceleration
- **Customizable**: Can fine-tune on your specific data
+312
View File
@@ -0,0 +1,312 @@
---
title: Performance Optimization
icon: "bolt"
iconType: "solid"
---
Optimizing reranker performance is crucial for maintaining fast search response times while improving result quality. This guide covers best practices for different reranker types.
## General Optimization Principles
### Candidate Set Size
The number of candidates sent to the reranker significantly impacts performance:
```python
# Optimal candidate sizes for different rerankers
config_map = {
"cohere": {"initial_candidates": 100, "top_n": 10},
"sentence_transformer": {"initial_candidates": 50, "top_n": 10},
"huggingface": {"initial_candidates": 30, "top_n": 5},
"llm_reranker": {"initial_candidates": 20, "top_n": 5}
}
```
### Batching Strategy
Process multiple queries efficiently:
```python
# Configure for batch processing
config = {
"reranker": {
"provider": "sentence_transformer",
"config": {
"model": "cross-encoder/ms-marco-MiniLM-L-6-v2",
"batch_size": 16, # Process multiple candidates at once
"top_n": 10
}
}
}
```
## Provider-Specific Optimizations
### Cohere Optimization
```python
# Optimized Cohere configuration
config = {
"reranker": {
"provider": "cohere",
"config": {
"model": "rerank-english-v3.0",
"top_n": 10,
"max_chunks_per_doc": 10, # Limit chunk processing
"return_documents": False # Reduce response size
}
}
}
```
**Best Practices:**
- Use v3.0 models for better speed/accuracy balance
- Limit candidates to 100 or fewer
- Cache API responses when possible
- Monitor API rate limits
### Sentence Transformer Optimization
```python
# Performance-optimized configuration
config = {
"reranker": {
"provider": "sentence_transformer",
"config": {
"model": "cross-encoder/ms-marco-MiniLM-L-6-v2",
"device": "cuda", # Use GPU when available
"batch_size": 32,
"top_n": 10,
"max_length": 512 # Limit input length
}
}
}
```
**Device Optimization:**
```python
import torch
# Auto-detect best device
device = "cuda" if torch.cuda.is_available() else "mps" if torch.backends.mps.is_available() else "cpu"
config = {
"reranker": {
"provider": "sentence_transformer",
"config": {
"device": device,
"model": "cross-encoder/ms-marco-MiniLM-L-6-v2"
}
}
}
```
### Hugging Face Optimization
```python
# Optimized for Hugging Face models
config = {
"reranker": {
"provider": "huggingface",
"config": {
"model": "BAAI/bge-reranker-base",
"use_fp16": True, # Half precision for speed
"max_length": 512,
"batch_size": 8,
"top_n": 10
}
}
}
```
### LLM Reranker Optimization
```python
# Optimized LLM reranker configuration
config = {
"reranker": {
"provider": "llm_reranker",
"config": {
"llm": {
"provider": "openai",
"config": {
"model": "gpt-3.5-turbo", # Faster than gpt-4
"temperature": 0, # Deterministic results
"max_tokens": 500 # Limit response length
}
},
"batch_ranking": True, # Rank multiple at once
"top_n": 5, # Fewer results for faster processing
"timeout": 10 # Request timeout
}
}
}
```
## Performance Monitoring
### Latency Tracking
```python
import time
from mem0 import Memory
def measure_reranker_performance(config, queries, user_id):
memory = Memory.from_config(config)
latencies = []
for query in queries:
start_time = time.time()
results = memory.search(query, user_id=user_id)
latency = time.time() - start_time
latencies.append(latency)
return {
"avg_latency": sum(latencies) / len(latencies),
"max_latency": max(latencies),
"min_latency": min(latencies)
}
```
### Memory Usage Monitoring
```python
import psutil
import os
def monitor_memory_usage():
process = psutil.Process(os.getpid())
return {
"memory_mb": process.memory_info().rss / 1024 / 1024,
"memory_percent": process.memory_percent()
}
```
## Caching Strategies
### Result Caching
```python
from functools import lru_cache
import hashlib
class CachedReranker:
def __init__(self, config):
self.memory = Memory.from_config(config)
self.cache_size = 1000
@lru_cache(maxsize=1000)
def search_cached(self, query_hash, user_id):
return self.memory.search(query, user_id=user_id)
def search(self, query, user_id):
query_hash = hashlib.md5(f"{query}_{user_id}".encode()).hexdigest()
return self.search_cached(query_hash, user_id)
```
### Model Caching
```python
# Pre-load models to avoid initialization overhead
config = {
"reranker": {
"provider": "sentence_transformer",
"config": {
"model": "cross-encoder/ms-marco-MiniLM-L-6-v2",
"cache_folder": "/path/to/model/cache",
"device": "cuda"
}
}
}
```
## Parallel Processing
### Async Configuration
```python
import asyncio
from mem0 import Memory
async def parallel_search(config, queries, user_id):
memory = Memory.from_config(config)
# Process multiple queries concurrently
tasks = [
memory.search_async(query, user_id=user_id)
for query in queries
]
results = await asyncio.gather(*tasks)
return results
```
## Hardware Optimization
### GPU Configuration
```python
# Optimize for GPU usage
import torch
if torch.cuda.is_available():
torch.cuda.set_per_process_memory_fraction(0.8) # Reserve GPU memory
config = {
"reranker": {
"provider": "sentence_transformer",
"config": {
"device": "cuda",
"model": "cross-encoder/ms-marco-electra-base",
"batch_size": 64, # Larger batch for GPU
"fp16": True # Half precision
}
}
}
```
### CPU Optimization
```python
import torch
# Optimize CPU threading
torch.set_num_threads(4) # Adjust based on your CPU
config = {
"reranker": {
"provider": "sentence_transformer",
"config": {
"device": "cpu",
"model": "cross-encoder/ms-marco-MiniLM-L-6-v2",
"num_workers": 4 # Parallel processing
}
}
}
```
## Benchmarking Different Configurations
```python
def benchmark_rerankers():
configs = [
{"provider": "cohere", "model": "rerank-english-v3.0"},
{"provider": "sentence_transformer", "model": "cross-encoder/ms-marco-MiniLM-L-6-v2"},
{"provider": "huggingface", "model": "BAAI/bge-reranker-base"}
]
test_queries = ["sample query 1", "sample query 2", "sample query 3"]
results = {}
for config in configs:
provider = config["provider"]
performance = measure_reranker_performance(
{"reranker": {"provider": provider, "config": config}},
test_queries,
"test_user"
)
results[provider] = performance
return results
```
## Production Best Practices
1. **Model Selection**: Choose the right balance of speed vs. accuracy
2. **Resource Allocation**: Monitor CPU/GPU usage and memory consumption
3. **Error Handling**: Implement fallbacks for reranker failures
4. **Load Balancing**: Distribute reranking load across multiple instances
5. **Monitoring**: Track latency, throughput, and error rates
6. **Caching**: Cache frequent queries and model predictions
7. **Batch Processing**: Group similar queries for efficient processing
+52
View File
@@ -0,0 +1,52 @@
---
title: Overview
icon: "info"
iconType: "solid"
---
Rerankers enhance the quality of search results by re-ordering the initial retrieval results using more sophisticated scoring mechanisms. They act as a secondary ranking layer that can significantly improve the relevance of retrieved memories.
## How Rerankers Work
1. **Initial Retrieval**: Vector search returns candidate memories based on semantic similarity
2. **Reranking**: The reranker evaluates and re-scores these candidates using more complex criteria
3. **Final Results**: Returns the top-k memories with improved relevance ordering
## Benefits
- **Improved Precision**: Better ranking of relevant memories
- **Context Awareness**: More sophisticated understanding of query-memory relationships
- **Performance**: Can improve results without changing the underlying vector store
## Supported Rerankers
Mem0 supports several reranker models:
<CardGroup cols={2}>
<Card title="Cohere" href="/components/rerankers/models/cohere" />
<Card title="Sentence Transformer" href="/components/rerankers/models/sentence_transformer" />
<Card title="Hugging Face" href="/components/rerankers/models/huggingface" />
<Card title="LLM Reranker" href="/components/rerankers/models/llm_reranker" />
</CardGroup>
## Usage
Rerankers are configured as part of the memory configuration:
```python
from mem0 import Memory
config = {
"reranker": {
"provider": "cohere",
"config": {
"api_key": "your-api-key",
"top_n": 10
}
}
}
memory = Memory.from_config(config)
```
For detailed configuration options, see the [Config](./config) page.
+1 -3
View File
@@ -4,13 +4,11 @@ icon: "gear"
iconType: "solid"
---
<Snippet file="paper-release.mdx" />
## How to define configurations?
The `config` is defined as an object with two main keys:
- `vector_store`: Specifies the vector database provider and its configuration
- `provider`: The name of the vector database (e.g., "chroma", "pgvector", "qdrant", "milvus", "upstash_vector", "azure_ai_search", "vertex_ai_vector_search")
- `provider`: The name of the vector database (e.g., "chroma", "pgvector", "qdrant", "milvus", "upstash_vector", "azure_ai_search", "vertex_ai_vector_search", "valkey")
- `config`: A nested dictionary containing provider-specific settings
+87 -7
View File
@@ -16,8 +16,8 @@ config = {
"vector_store": {
"provider": "azure_ai_search",
"config": {
"service_name": "ai-search-test",
"api_key": "*****",
"service_name": "<your-azure-ai-search-service-name>",
"api_key": "<your-api-key>",
"collection_name": "mem0",
"embedding_model_dims": 1536
}
@@ -41,8 +41,8 @@ config = {
"vector_store": {
"provider": "azure_ai_search",
"config": {
"service_name": "ai-search-test",
"api_key": "*****",
"service_name": "<your-azure-ai-search-service-name>",
"api_key": "<your-api-key>",
"collection_name": "mem0",
"embedding_model_dims": 1536,
"compression_type": "binary",
@@ -59,8 +59,8 @@ config = {
"vector_store": {
"provider": "azure_ai_search",
"config": {
"service_name": "ai-search-test",
"api_key": "*****",
"service_name": "<your-azure-ai-search-service-name>",
"api_key": "<your-api-key>",
"collection_name": "mem0",
"embedding_model_dims": 1536,
"hybrid_search": True,
@@ -70,12 +70,92 @@ config = {
}
```
## Using Azure Identity for Authentication
As an alternative to using an API key, the Azure Identity credential chain can be used to authenticate with Azure OpenAI. The list below shows the order of precedence for credential application:
1. **Environment Credential:**
Azure client ID, secret, tenant ID, or certificate in environment variables for service principal authentication.
2. **Workload Identity Credential:**
Utilizes Azure Workload Identity (relevant for Kubernetes and Azure workloads).
3. **Managed Identity Credential:**
Authenticates as a Managed Identity (for apps/services hosted in Azure with Managed Identity enabled), this is the most secure production credential.
4. **Shared Token Cache Credential / Visual Studio Credential (Windows only):**
Uses cached credentials from Visual Studio sign-ins (and sometimes VS Code if SSO is enabled).
5. **Azure CLI Credential:**
Uses the currently logged-in user from the Azure CLI (`az login`), this is the most common development credential.
6. **Azure PowerShell Credential:**
Uses the identity from Azure PowerShell (`Connect-AzAccount`).
7. **Azure Developer CLI Credential:**
Uses the session from Azure Developer CLI (`azd auth login`).
<Note> If an API is provided, it will be used for authentication over an Azure Identity </Note>
To enable Role-Based Access Control (RBAC) for Azure AI Search, follow these steps:
1. In the Azure Portal, navigate to your **Azure AI Search** service.
2. In the left menu, select **Settings** > **Keys**.
3. Change the authentication setting to **Role-based access control**, or **Both** if you need API key compatibility. The default is “Key-based authentication”—you must switch it to use Azure roles.
4. **Go to Access Control (IAM):**
- In the Azure Portal, select your Search service.
- Click **Access Control (IAM)** on the left.
5. **Add a Role Assignment:**
- Click **Add** > **Add role assignment**.
6. **Choose Role:**
- Mem0 requires the **Search Index Data Contributor** and **Search Service Contributor** role.
7. **Choose Member**
- To assign to a User, Group, Service Principle or Managed Identity:
- For production it is recommended to use a service principal or managed identity.
- For a service principal: select **User, group, or service principal** and search for the service principal.
- For a managed identity: select **Managed identity** and choose the managed identity.
- For development, you can assign the role to a user account.
- For development: select ***User, group, or service principal** and pick a Azure Entra ID account (the same used with `az login`).
8. **Complete the Assignment:**
- Click **Review + Assign**.
If you are using Azure Identity, do not set the `api_key` in the configuration.
```python
config = {
"vector_store": {
"provider": "azure_ai_search",
"config": {
"service_name": "<your-azure-ai-search-service-name>",
"collection_name": "mem0",
"embedding_model_dims": 1536,
"compression_type": "binary",
"use_float16": True # Use half precision for storage efficiency
}
}
}
```
### Environment Variables to set to use Azure Identity Credential:
* For an Environment Credential, you will need to setup a Service Principal and set the following environment variables:
- `AZURE_TENANT_ID`: Your Azure Active Directory tenant ID.
- `AZURE_CLIENT_ID`: The client ID of your service principal or managed identity.
- `AZURE_CLIENT_SECRET`: The client secret of your service principal.
* For a User-Assigned Managed Identity, you will need to set the following environment variable:
- `AZURE_CLIENT_ID`: The client ID of the user-assigned managed identity.
* For a System-Assigned Managed Identity, no additional environment variables are needed.
### Developer logins to use for a Azure Identity Credential:
* For an Azure CLI Credential, you need to have the Azure CLI installed and logged in with `az login`.
* For an Azure PowerShell Credential, you need to have the Azure PowerShell module installed and logged in with `Connect-AzAccount`.
* For an Azure Developer CLI Credential, you need to have the Azure Developer CLI installed and logged in with `azd auth login`.
Troubleshooting tips for [Azure Identity](https://github.com/Azure/azure-sdk-for-python/blob/main/sdk/identity/azure-identity/TROUBLESHOOTING.md#troubleshoot-environmentcredential-authentication-issues).
## Configuration Parameters
| Parameter | Description | Default Value | Options |
| --- | --- | --- | --- |
| `service_name` | Azure AI Search service name | Required | - |
| `api_key` | API key of the Azure AI Search service | Required | - |
| `api_key` | API key of the Azure AI Search service | Optional | If not present, the [Azure Identity](#using-azure-identity-for-authentication) credential chain will be used |
| `collection_name` | The name of the collection/index to store vectors | `mem0` | Any valid index name |
| `embedding_model_dims` | Dimensions of the embedding model | `1536` | Any integer value |
| `compression_type` | Type of vector compression to use | `none` | `none`, `scalar`, `binary` |
+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
+9 -2
View File
@@ -1,7 +1,9 @@
[Chroma](https://www.trychroma.com/) is an AI-native open-source vector database that simplifies building LLM apps by providing tools for storing, embedding, and searching embeddings with a focus on simplicity and speed.
[Chroma](https://www.trychroma.com/) is an AI-native open-source vector database that simplifies building LLM apps by providing tools for storing, embedding, and searching embeddings with a focus on simplicity and speed. It supports both local deployment and cloud hosting through ChromaDB Cloud.
### Usage
#### Local Installation
```python
import os
from mem0 import Memory
@@ -14,6 +16,9 @@ config = {
"config": {
"collection_name": "test",
"path": "db",
# Optional: ChromaDB Cloud configuration
# "api_key": "your-chroma-cloud-api-key",
# "tenant": "your-chroma-cloud-tenant-id",
}
}
}
@@ -38,4 +43,6 @@ Here are the parameters available for configuring Chroma:
| `client` | Custom client for Chroma | `None` |
| `path` | Path for the Chroma database | `db` |
| `host` | The host where the Chroma server is running | `None` |
| `port` | The port where the Chroma server is running | `None` |
| `port` | The port where the Chroma server is running | `None` |
| `api_key` | ChromaDB Cloud API key (for cloud usage) | `None` |
| `tenant` | ChromaDB Cloud tenant ID (for cloud usage) | `None` |
@@ -0,0 +1,130 @@
[Databricks Vector Search](https://docs.databricks.com/en/generative-ai/vector-search.html) is a serverless similarity search engine that allows you to store a vector representation of your data, including metadata, in a vector database. With Vector Search, you can create auto-updating vector search indexes from Delta tables managed by Unity Catalog and query them with a simple API to return the most similar vectors.
### Usage
```python
import os
from mem0 import Memory
config = {
"vector_store": {
"provider": "databricks",
"config": {
"workspace_url": "https://your-workspace.databricks.com",
"access_token": "your-access-token",
"endpoint_name": "your-vector-search-endpoint",
"index_name": "catalog.schema.index_name",
"source_table_name": "catalog.schema.source_table",
"embedding_dimension": 1536
}
}
}
m = Memory.from_config(config)
messages = [
{"role": "user", "content": "I'm planning to watch a movie tonight. Any recommendations?"},
{"role": "assistant", "content": "How about thriller movies? They can be quite engaging."},
{"role": "user", "content": "I'm not a big fan of thriller movies but I love sci-fi movies."},
{"role": "assistant", "content": "Got it! I'll avoid thriller recommendations and suggest sci-fi movies in the future."}
]
m.add(messages, user_id="alice", metadata={"category": "movies"})
```
### Config
Here are the parameters available for configuring Databricks Vector Search:
| Parameter | Description | Default Value |
| --- | --- | --- |
| `workspace_url` | The URL of your Databricks workspace | **Required** |
| `access_token` | Personal Access Token for authentication | `None` |
| `service_principal_client_id` | Service principal client ID (alternative to access_token) | `None` |
| `service_principal_client_secret` | Service principal client secret (required with client_id) | `None` |
| `endpoint_name` | Name of the Vector Search endpoint | **Required** |
| `index_name` | Name of the vector index (Unity Catalog format: catalog.schema.index) | **Required** |
| `source_table_name` | Name of the source Delta table (Unity Catalog format: catalog.schema.table) | **Required** |
| `embedding_dimension` | Dimension of self-managed embeddings | `1536` |
| `embedding_source_column` | Column name for text when using Databricks-computed embeddings | `None` |
| `embedding_model_endpoint_name` | Databricks serving endpoint for embeddings | `None` |
| `embedding_vector_column` | Column name for self-managed embedding vectors | `embedding` |
| `endpoint_type` | Type of endpoint (`STANDARD` or `STORAGE_OPTIMIZED`) | `STANDARD` |
| `sync_computed_embeddings` | Whether to sync computed embeddings automatically | `True` |
### Authentication
Databricks Vector Search supports two authentication methods:
#### Service Principal (Recommended for Production)
```python
config = {
"vector_store": {
"provider": "databricks",
"config": {
"workspace_url": "https://your-workspace.databricks.com",
"service_principal_client_id": "your-service-principal-id",
"service_principal_client_secret": "your-service-principal-secret",
"endpoint_name": "your-endpoint",
"index_name": "catalog.schema.index_name",
"source_table_name": "catalog.schema.source_table"
}
}
}
```
#### Personal Access Token (for Development)
```python
config = {
"vector_store": {
"provider": "databricks",
"config": {
"workspace_url": "https://your-workspace.databricks.com",
"access_token": "your-personal-access-token",
"endpoint_name": "your-endpoint",
"index_name": "catalog.schema.index_name",
"source_table_name": "catalog.schema.source_table"
}
}
}
```
### Embedding Options
#### Self-Managed Embeddings (Default)
Use your own embedding model and provide vectors directly:
```python
config = {
"vector_store": {
"provider": "databricks",
"config": {
# ... authentication config ...
"embedding_dimension": 768, # Match your embedding model
"embedding_vector_column": "embedding"
}
}
}
```
#### Databricks-Computed Embeddings
Let Databricks compute embeddings from text using a serving endpoint:
```python
config = {
"vector_store": {
"provider": "databricks",
"config": {
# ... authentication config ...
"embedding_source_column": "text",
"embedding_model_endpoint_name": "e5-small-v2"
}
}
}
```
### Important Notes
- **Delta Sync Index**: This implementation uses Delta Sync Index, which automatically syncs with your source Delta table. Direct vector insertion/deletion/update operations will log warnings as they're not supported with Delta Sync.
- **Unity Catalog**: Both the source table and index must be in Unity Catalog format (`catalog.schema.table_name`).
- **Endpoint Auto-Creation**: If the specified endpoint doesn't exist, it will be created automatically.
- **Index Auto-Creation**: If the specified index doesn't exist, it will be created automatically with the provided configuration.
- **Filter Support**: Supports filtering by metadata fields, with different syntax for STANDARD vs STORAGE_OPTIMIZED endpoints.
@@ -54,7 +54,8 @@ Let's see the available parameters for the `elasticsearch` config:
| `password` | Password for basic authentication | `None` |
| `verify_certs` | Whether to verify SSL certificates | `True` |
| `auto_create_index` | Whether to automatically create the index | `True` |
| `custom_search_query` | Function returning a custom search query | `None` |
| `custom_search_query` | Function returning a custom search query | `None` |
| `headers` | Custom headers to include in requests | `None` |
### Features
+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 | `""` |
+45
View File
@@ -0,0 +1,45 @@
# MongoDB
[MongoDB](https://www.mongodb.com/) is a versatile document database that supports vector search capabilities, allowing for efficient high-dimensional similarity searches over large datasets with robust scalability and performance.
## Usage
```python
import os
from mem0 import Memory
os.environ["OPENAI_API_KEY"] = "sk-xx"
config = {
"vector_store": {
"provider": "mongodb",
"config": {
"db_name": "mem0-db",
"collection_name": "mem0-collection",
"mongo_uri":"mongodb://username:password@localhost:27017"
}
}
}
m = Memory.from_config(config)
messages = [
{"role": "user", "content": "I'm planning to watch a movie tonight. Any recommendations?"},
{"role": "assistant", "content": "How about a thriller movies? They can be quite engaging."},
{"role": "user", "content": "I’m not a big fan of thriller movies but I love sci-fi movies."},
{"role": "assistant", "content": "Got it! I'll avoid thriller recommendations and suggest sci-fi movies in the future."}
]
m.add(messages, user_id="alice", metadata={"category": "movies"})
```
## Config
Here are the parameters available for configuring MongoDB:
| Parameter | Description | Default Value |
| --- | --- | --- |
| db_name | Name of the MongoDB database | `"mem0_db"` |
| collection_name | Name of the MongoDB collection | `"mem0_collection"` |
| embedding_model_dims | Dimensions of the embedding vectors | `1536` |
| mongo_uri | The mongo URI connection string | mongodb://username:password@localhost:27017 |
> **Note**: If Mongo_uri is not provided it will default to mongodb://username:password@localhost:27017.
@@ -0,0 +1,42 @@
# Neptune Analytics Vector Store
[Neptune Analytics](https://docs.aws.amazon.com/neptune-analytics/latest/userguide/what-is-neptune-analytics.html/) is a memory-optimized graph database engine for analytics. With Neptune Analytics, you can get insights and find trends by processing large amounts of graph data in seconds, including vector search.
## Installation
```bash
pip install mem0ai[vector_stores]
```
## Usage
```python
config = {
"vector_store": {
"provider": "neptune",
"config": {
"collection_name": "mem0",
"endpoint": f"neptune-graph://my-graph-identifier",
},
},
}
m = Memory.from_config(config)
messages = [
{"role": "user", "content": "I'm planning to watch a movie tonight. Any recommendations?"},
{"role": "assistant", "content": "How about a thriller movies? They can be quite engaging."},
{"role": "user", "content": "I'm not a big fan of thriller movies but I love sci-fi movies."},
{"role": "assistant", "content": "Got it! I'll avoid thriller recommendations and suggest sci-fi movies in the future."}
]
m.add(messages, user_id="alice", metadata={"category": "movies"})
```
## Parameters
Let's see the available parameters for the `neptune` config:
| Parameter | Description | Default Value |
| --- | --- | --- |
| `collection_name` | The name of the collection to store the vectors | `mem0` |
| `endpoint` | Connection URL for the Neptune Analytics service | `neptune-graph://my-graph-identifier` |
+38 -22
View File
@@ -1,59 +1,75 @@
[OpenSearch](https://opensearch.org/) is an open-source, enterprise-grade search and observability suite that brings order to unstructured data at scale. OpenSearch supports k-NN (k-Nearest Neighbors) and allows you to store and retrieve high-dimensional vector embeddings efficiently.
[OpenSearch](https://opensearch.org/) is an enterprise-grade search and observability suite that brings order to unstructured data at scale. OpenSearch supports k-NN (k-Nearest Neighbors) and allows you to store and retrieve high-dimensional vector embeddings efficiently.
### Installation
OpenSearch support requires additional dependencies. Install them with:
```bash
pip install opensearch>=2.8.0
pip install opensearch-py
```
### Prerequisites
Before using OpenSearch with Mem0, you need to set up a collection in AWS OpenSearch Service.
#### AWS OpenSearch Service
You can create a collection through the AWS Console:
- Navigate to [OpenSearch Service Console](https://console.aws.amazon.com/aos/home)
- Click "Create collection"
- Select "Serverless collection" and then enable "Vector search" capabilities
- Once created, note the endpoint URL (host) for your configuration
### Usage
```python
import os
from mem0 import Memory
import boto3
from opensearchpy import OpenSearch, RequestsHttpConnection, AWSV4SignerAuth
os.environ["OPENAI_API_KEY"] = "sk-xx"
# For AWS OpenSearch Service with IAM authentication
region = 'us-west-2'
service = 'aoss'
credentials = boto3.Session().get_credentials()
auth = AWSV4SignerAuth(credentials, region, service)
config = {
"vector_store": {
"provider": "opensearch",
"config": {
"collection_name": "mem0",
"host": "localhost",
"port": 9200,
"embedding_model_dims": 1536
"host": "your-domain.us-west-2.aoss.amazonaws.com",
"port": 443,
"http_auth": auth,
"embedding_model_dims": 1024,
"connection_class": RequestsHttpConnection,
"pool_maxsize": 20,
"use_ssl": True,
"verify_certs": True
}
}
}
```
### Add Memories
```python
m = Memory.from_config(config)
messages = [
{"role": "user", "content": "I'm planning to watch a movie tonight. Any recommendations?"},
{"role": "assistant", "content": "How about a thriller movies? They can be quite engaging."},
{"role": "user", "content": "I’m not a big fan of thriller movies but I love sci-fi movies."},
{"role": "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
### Search Memories
Let's see the available parameters for the `opensearch` config:
| Parameter | Description | Default Value |
| ---------------------- | -------------------------------------------------- | ------------- |
| `collection_name` | The name of the index to store the vectors | `mem0` |
| `embedding_model_dims` | Dimensions of the embedding model | `1536` |
| `host` | The host where the OpenSearch server is running | `localhost` |
| `port` | The port where the OpenSearch server is running | `9200` |
| `api_key` | API key for authentication | `None` |
| `user` | Username for basic authentication | `None` |
| `password` | Password for basic authentication | `None` |
| `verify_certs` | Whether to verify SSL certificates | `False` |
| `auto_create_index` | Whether to automatically create the index | `True` |
| `use_ssl` | Whether to use SSL for connection | `False` |
```python
results = m.search("What kind of movies does Alice like?", user_id="alice")
```
### Features
+44 -4
View File
@@ -2,7 +2,8 @@
### Usage
```python
<CodeGroup>
```python Python
import os
from mem0 import Memory
@@ -24,19 +25,50 @@ m = Memory.from_config(config)
messages = [
{"role": "user", "content": "I'm planning to watch a movie tonight. Any recommendations?"},
{"role": "assistant", "content": "How about a thriller movies? They can be quite engaging."},
{"role": "user", "content": "I’m not a big fan of thriller movies but I love sci-fi movies."},
{"role": "user", "content": "I'm not a big fan of thriller movies but I love sci-fi movies."},
{"role": "assistant", "content": "Got it! I'll avoid thriller recommendations and suggest sci-fi movies in the future."}
]
m.add(messages, user_id="alice", metadata={"category": "movies"})
```
```typescript TypeScript
import { Memory } from 'mem0ai/oss';
const config = {
vectorStore: {
provider: 'pgvector',
config: {
collectionName: 'memories',
embeddingModelDims: 1536,
user: 'test',
password: '123',
host: '127.0.0.1',
port: 5432,
dbname: 'vector_store', // Optional, defaults to 'postgres'
diskann: false, // Optional, requires pgvectorscale extension
hnsw: false, // Optional, for HNSW indexing
},
},
};
const memory = new Memory(config);
const messages = [
{"role": "user", "content": "I'm planning to watch a movie tonight. Any recommendations?"},
{"role": "assistant", "content": "How about a thriller movies? They can be quite engaging."},
{"role": "user", "content": "I'm not a big fan of thriller movies but I love sci-fi movies."},
{"role": "assistant", "content": "Got it! I'll avoid thriller recommendations and suggest sci-fi movies in the future."}
]
await memory.add(messages, { userId: "alice", metadata: { category: "movies" } });
```
</CodeGroup>
### Config
Here's the parameters available for configuring pgvector:
| 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 +76,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,
@@ -0,0 +1,78 @@
---
title: Amazon S3 Vectors
---
[Amazon S3 Vectors](https://aws.amazon.com/s3/features/vectors/) is a purpose-built, cost-optimized vector storage and query service for semantic search and AI applications. It provides S3-level elasticity and durability with sub-second query performance.
### Installation
S3 Vectors support requires additional dependencies. Install them with:
```bash
pip install boto3
```
### Usage
To use Amazon S3 Vectors with Mem0, you need to have an AWS account and the necessary IAM permissions (`s3vectors:*`). Ensure your environment is configured with AWS credentials (e.g., via `~/.aws/credentials` or environment variables).
```python
import os
from mem0 import Memory
# Ensure your AWS credentials are configured in your environment
# e.g., by setting AWS_ACCESS_KEY_ID, AWS_SECRET_ACCESS_KEY, and AWS_DEFAULT_REGION
config = {
"vector_store": {
"provider": "s3_vectors",
"config": {
"vector_bucket_name": "my-mem0-vector-bucket",
"collection_name": "my-memories-index",
"embedding_model_dims": 1536,
"distance_metric": "cosine",
"region_name": "us-east-1"
}
}
}
m = Memory.from_config(config)
messages = [
{"role": "user", "content": "I'm planning to watch a movie tonight. Any recommendations?"},
{"role": "assistant", "content": "How about a thriller movie? They can be quite engaging."},
{"role": "user", "content": "I'm not a big fan of thriller movies but I love sci-fi movies."},
{"role": "assistant", "content": "Got it! I'll avoid thriller recommendations and suggest sci-fi movies in the future."}
]
m.add(messages, user_id="alice", metadata={"category": "movies"})
```
### Config
Here are the available parameters for the `s3_vectors` config:
| Parameter | Description | Default Value |
| ---------------------- | -------------------------------------------------------------------------------- | ------------------------------------- |
| `vector_bucket_name` | The name of the S3 Vector bucket to use. It will be created if it doesn't exist. | Required |
| `collection_name` | The name of the vector index within the bucket. | `mem0` |
| `embedding_model_dims` | Dimensions of the embedding model. Must match your embedder. | `1536` |
| `distance_metric` | Distance metric for similarity search. Options: `cosine`, `euclidean`. | `cosine` |
| `region_name` | The AWS region where the bucket and index reside. | `None` (uses default from AWS config) |
### IAM Permissions
Your AWS identity (user or role) needs permissions to perform actions on S3 Vectors. A minimal policy would look like this:
```json
{
"Version": "2012-10-17",
"Statement": [
{
"Effect": "Allow",
"Action": "s3vectors:*",
"Resource": "*"
}
]
}
```
For production, it is recommended to scope down the resource ARN to your specific buckets and indexes.
+49
View File
@@ -0,0 +1,49 @@
# Valkey Vector Store
[Valkey](https://valkey.io/) is an open source (BSD) high-performance key/value datastore that supports a variety of workloads and rich datastructures including vector search.
## Installation
```bash
pip install mem0ai[vector_stores]
```
## Usage
```python
config = {
"vector_store": {
"provider": "valkey",
"config": {
"collection_name": "test",
"valkey_url": "valkey://localhost:6379",
"embedding_model_dims": 1536,
"index_type": "flat"
}
}
}
m = Memory.from_config(config)
messages = [
{"role": "user", "content": "I'm planning to watch a movie tonight. Any recommendations?"},
{"role": "assistant", "content": "How about a thriller movies? They can be quite engaging."},
{"role": "user", "content": "I'm not a big fan of thriller movies but I love sci-fi movies."},
{"role": "assistant", "content": "Got it! I'll avoid thriller recommendations and suggest sci-fi movies in the future."}
]
m.add(messages, user_id="alice", metadata={"category": "movies"})
```
## Parameters
Let's see the available parameters for the `valkey` config:
| Parameter | Description | Default Value |
| --- | --- | --- |
| `collection_name` | The name of the collection to store the vectors | `mem0` |
| `valkey_url` | Connection URL for the Valkey server | `valkey://localhost:6379` |
| `embedding_model_dims` | Dimensions of the embedding model | `1536` |
| `index_type` | Vector index algorithm (`hnsw` or `flat`) | `hnsw` |
| `hnsw_m` | Number of bi-directional links for HNSW | `16` |
| `hnsw_ef_construction` | Size of dynamic candidate list for HNSW | `200` |
| `hnsw_ef_runtime` | Size of dynamic candidate list for search | `10` |
| `distance_metric` | Distance metric for vector similarity | `cosine` |
@@ -0,0 +1,45 @@
[Cloudflare Vectorize](https://developers.cloudflare.com/vectorize/) is a vector database offering from Cloudflare, allowing you to build AI-powered applications with vector embeddings.
### Usage
<CodeGroup>
```typescript TypeScript
import { Memory } from 'mem0ai/oss';
const config = {
vectorStore: {
provider: 'vectorize',
config: {
indexName: 'my-memory-index',
accountId: 'your-cloudflare-account-id',
apiKey: 'your-cloudflare-api-key',
dimension: 1536, // Optional: defaults to 1536
},
},
};
const memory = new Memory(config);
const messages = [
{"role": "user", "content": "I'm looking for a good book to read."},
{"role": "assistant", "content": "Sure, what genre are you interested in?"},
{"role": "user", "content": "I enjoy fantasy novels with strong world-building."},
{"role": "assistant", "content": "Great! I'll keep that in mind for future recommendations."}
]
await memory.add(messages, { userId: "bob", metadata: { interest: "books" } });
```
</CodeGroup>
### Config
Let's see the available parameters for the `vectorize` config:
<Tabs>
<Tab title="TypeScript">
| Parameter | Description | Default Value |
| --- | --- | --- |
| `indexName` | The name of the Vectorize index | `None` (Required) |
| `accountId` | Your Cloudflare account ID | `None` (Required) |
| `apiKey` | Your Cloudflare API token | `None` (Required) |
| `dimension` | Dimensions of the embedding model | `1536` |
</Tab>
</Tabs>
+1 -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": {
+5 -3
View File
@@ -4,8 +4,6 @@ icon: "info"
iconType: "solid"
---
<Snippet file="paper-release.mdx" />
Mem0 includes built-in support for various popular databases. Memory can utilize the database provided by the user, ensuring efficient use for specific needs.
## Supported Vector Databases
@@ -13,7 +11,7 @@ Mem0 includes built-in support for various popular databases. Memory can utilize
See the list of supported vector databases below.
<Note>
The following vector databases are supported in the Python implementation. The TypeScript implementation currently only supports Qdrant, Redis and in-memory vector database.
The following vector databases are supported in the Python implementation. The TypeScript implementation currently only supports Qdrant, Redis, Valkey, Vectorize and in-memory vector database.
</Note>
<CardGroup cols={3}>
@@ -23,8 +21,10 @@ See the list of supported vector databases below.
<Card title="Upstash Vector" href="/components/vectordbs/dbs/upstash-vector"></Card>
<Card title="Milvus" href="/components/vectordbs/dbs/milvus"></Card>
<Card title="Pinecone" href="/components/vectordbs/dbs/pinecone"></Card>
<Card title="MongoDB" href="/components/vectordbs/dbs/mongodb"></Card>
<Card title="Azure" href="/components/vectordbs/dbs/azure"></Card>
<Card title="Redis" href="/components/vectordbs/dbs/redis"></Card>
<Card title="Valkey" href="/components/vectordbs/dbs/valkey"></Card>
<Card title="Elasticsearch" href="/components/vectordbs/dbs/elasticsearch"></Card>
<Card title="OpenSearch" href="/components/vectordbs/dbs/opensearch"></Card>
<Card title="Supabase" href="/components/vectordbs/dbs/supabase"></Card>
@@ -32,6 +32,8 @@ See the list of supported vector databases below.
<Card title="Weaviate" href="/components/vectordbs/dbs/weaviate"></Card>
<Card title="FAISS" href="/components/vectordbs/dbs/faiss"></Card>
<Card title="LangChain" href="/components/vectordbs/dbs/langchain"></Card>
<Card title="Amazon S3 Vectors" href="/components/vectordbs/dbs/s3_vectors"></Card>
<Card title="Databricks" href="/components/vectordbs/dbs/databricks"></Card>
</CardGroup>
## Usage
+13 -10
View File
@@ -3,8 +3,6 @@ title: Development
icon: "code"
---
<Snippet file="paper-release.mdx" />
# Development Contributions
We strive to make contributions **easy, collaborative, and enjoyable**. Follow the steps below to ensure a smooth contribution process.
@@ -29,15 +27,20 @@ For detailed guidance on pull requests, refer to [GitHub's documentation](https:
## 📦 Dependency Management
We use `poetry` as our package manager. Install it by following the [official instructions](https://python-poetry.org/docs/#installation).
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
poetry 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
```
---
@@ -60,9 +63,9 @@ Run the linter and fix any reported issues before submitting your PR:
make lint
```
### 🎨 Code Formatting with `black`
### 🎨 Code Formatting
To maintain a consistent code style, format your code using `black`:
To maintain a consistent code style, format your code:
```bash
make format
@@ -76,7 +79,7 @@ Run tests to verify functionality before submitting your PR:
make test
```
💡 **Note:** Some dependencies have been removed from Poetry to reduce package size. Run `make install_all` to install necessary dependencies before running tests.
💡 **Note:** Some dependencies have been removed from the main dependencies to reduce package size. Run `make install_all` to install necessary dependencies before running tests.
---
-2
View File
@@ -3,8 +3,6 @@ title: Documentation
icon: "book"
---
<Snippet file="paper-release.mdx" />
# Documentation Contributions
## 📌 Prerequisites
-62
View File
@@ -1,62 +0,0 @@
---
title: Memory Operations
description: Understanding the core operations for managing memories in AI applications
icon: "gear"
iconType: "solid"
---
<Snippet file="paper-release.mdx" />
Mem0 provides two core operations for managing memories in AI applications: adding new memories and searching existing ones. This guide covers how these operations work and how to use them effectively in your application.
## Core Operations
Mem0 exposes two main endpoints for interacting with memories:
- The `add` endpoint for ingesting conversations and storing them as memories
- The `search` endpoint for retrieving relevant memories based on queries
### Adding Memories
<Frame caption="Architecture diagram illustrating the process of adding memories.">
<img src="../images/add_architecture.png" />
</Frame>
The add operation processes conversations through several steps:
1. **Information Extraction**
* An LLM extracts relevant memories from the conversation
* It identifies important entities and their relationships
2. **Conflict Resolution**
* The system compares new information with existing data
* It identifies and resolves any contradictions
3. **Memory Storage**
* Vector database stores the actual memories
* Graph database maintains relationship information
* Information is continuously updated with each interaction
### Searching Memories
<Frame caption="Architecture diagram illustrating the memory search process.">
<img src="../images/search_architecture.png" />
</Frame>
The search operation retrieves memories through a multi-step process:
1. **Query Processing**
* LLM processes and optimizes the search query
* System prepares filters for targeted search
2. **Vector Search**
* Performs semantic search using the optimized query
* Ranks results by relevance to the query
* Applies specified filters (user, agent, metadata, etc.)
3. **Result Processing**
* Combines and ranks the search results
* Returns memories with relevance scores
* Includes associated metadata and timestamps
This semantic search approach ensures accurate memory retrieval, whether you're looking for specific information or exploring related concepts.
@@ -0,0 +1,153 @@
---
title: Add Memory
description: Add memory into the Mem0 platform by storing user-assistant interactions and facts for later retrieval.
icon: "plus"
iconType: "solid"
---
## Overview
The `add` operation is how you store memory into Mem0. Whether you're working with a chatbot, a voice assistant, or a multi-agent system, this is the entry point to create long-term memory.
Memories typically come from a **user-assistant interaction** and Mem0 handles the extraction, transformation, and storage for you.
Mem0 offers two implementation flows:
- **Mem0 Platform** (Managed, scalable, with dashboard + API)
- **Mem0 Open Source** (Lightweight, fully local, flexible SDKs)
Each supports the same core memory operations, but with slightly different setup. Below, we walk through examples for both.
## Architecture
<Frame caption="Architecture diagram illustrating the process of adding memories.">
<img src="../../images/add_architecture.png" />
</Frame>
When you call `add`, Mem0 performs the following steps under the hood:
1. **Information Extraction**
The input messages are passed through an LLM that extracts key facts, decisions, preferences, or events worth remembering.
2. **Conflict Resolution**
Mem0 compares the new memory against existing ones to detect duplication or contradiction and handles updates accordingly.
3. **Memory Storage**
The result is stored in a vector database (for semantic search) and optionally in a graph structure (for relationship mapping).
You don’t need to handle any of this manually, Mem0 takes care of it with a single API call or SDK method.
---
## Example: Mem0 Platform
<CodeGroup>
```python Python
from mem0 import MemoryClient
client = MemoryClient(api_key="your-api-key")
messages = [
{"role": "user", "content": "I'm planning a trip to Tokyo next month."},
{"role": "assistant", "content": "Great! I’ll remember that for future suggestions."}
]
client.add(
messages=messages,
user_id="alice",
version="v2"
)
```
```javascript JavaScript
import { MemoryClient } from "mem0ai";
const client = new MemoryClient({apiKey: "your-api-key"});
const messages = [
{ role: "user", content: "I'm planning a trip to Tokyo next month." },
{ role: "assistant", content: "Great! I’ll remember that for future suggestions." }
];
await client.add({
messages,
user_id: "alice",
version: "v2"
});
```
</CodeGroup>
---
## Example: Mem0 Open Source
<CodeGroup>
```python Python
import os
from mem0 import Memory
os.environ["OPENAI_API_KEY"] = "your-api-key"
m = Memory()
messages = [
{"role": "user", "content": "I'm planning to watch a movie tonight. Any recommendations?"},
{"role": "assistant", "content": "How about a thriller movies? They can be quite engaging."},
{"role": "user", "content": "I'm not a big fan of thriller movies but I love sci-fi movies."},
{"role": "assistant", "content": "Got it! I'll avoid thriller recommendations and suggest sci-fi movies in the future."}
]
# Store inferred memories (default behavior)
result = m.add(messages, user_id="alice", metadata={"category": "movie_recommendations"})
# Optionally store raw messages without inference
result = m.add(messages, user_id="alice", metadata={"category": "movie_recommendations"}, infer=False)
```
```javascript JavaScript
import { Memory } from 'mem0ai/oss';
const memory = new Memory();
const messages = [
{
role: "user",
content: "I like to drink coffee in the morning and go for a walk"
}
];
const result = memory.add(messages, {
userId: "alice",
metadata: { category: "preferences" }
});
```
</CodeGroup>
---
## When Should You Add Memory?
Add memory whenever your agent learns something useful:
- A new user preference is shared
- A decision or suggestion is made
- A goal or task is completed
- A new entity is introduced
- A user gives feedback or clarification
Storing this context allows the agent to reason better in future interactions.
### More Details
For full list of supported fields, required formats, and advanced options, see the
[Add Memory API Reference](/api-reference/memory/add-memories).
---
## Need help?
If you have any questions, please feel free to reach out to us using one of the following methods:
<Snippet file="get-help.mdx"/>
@@ -0,0 +1,141 @@
---
title: Delete Memory
description: Remove memories from Mem0 either individually, in bulk, or via filters.
icon: "trash"
iconType: "solid"
---
## Overview
Memories can become outdated, irrelevant, or need to be removed for privacy or compliance reasons. Mem0 offers flexible ways to delete memory:
1. **Delete a Single Memory**: Using a specific memory ID
2. **Batch Delete**: Delete multiple known memory IDs (up to 1000)
3. **Filtered Delete**: Delete memories matching a filter (e.g., `user_id`, `metadata`, `run_id`)
This page walks through code example for each method.
## Use Cases
- Forget a user’s past preferences by request
- Remove outdated or incorrect memory entries
- Clean up memory after session expiration
- Comply with data deletion requests (e.g., GDPR)
---
## 1. Delete a Single Memory by ID
<CodeGroup>
```python Python
from mem0 import MemoryClient
client = MemoryClient(api_key="your-api-key")
memory_id = "your_memory_id"
client.delete(memory_id=memory_id)
```
```javascript JavaScript
import MemoryClient from 'mem0ai';
const client = new MemoryClient({ apiKey: "your-api-key" });
client.delete("your_memory_id")
.then(result => console.log(result))
.catch(error => console.error(error));
```
</CodeGroup>
---
## 2. Batch Delete Multiple Memories
<CodeGroup>
```python Python
from mem0 import MemoryClient
client = MemoryClient(api_key="your-api-key")
delete_memories = [
{"memory_id": "id1"},
{"memory_id": "id2"}
]
response = client.batch_delete(delete_memories)
print(response)
```
```javascript JavaScript
import MemoryClient from 'mem0ai';
const client = new MemoryClient({ apiKey: "your-api-key" });
const deleteMemories = [
{ memory_id: "id1" },
{ memory_id: "id2" }
];
client.batchDelete(deleteMemories)
.then(response => console.log('Batch delete response:', response))
.catch(error => console.error(error));
```
</CodeGroup>
---
## 3. Delete Memories by Filter (e.g., user_id)
<CodeGroup>
```python Python
from mem0 import MemoryClient
client = MemoryClient(api_key="your-api-key")
# Delete all memories for a specific user
client.delete_all(user_id="alice")
```
```javascript JavaScript
import MemoryClient from 'mem0ai';
const client = new MemoryClient({ apiKey: "your-api-key" });
client.deleteAll({ user_id: "alice" })
.then(result => console.log(result))
.catch(error => console.error(error));
```
</CodeGroup>
You can also filter by other parameters such as:
- `agent_id`
- `run_id`
- `metadata` (as JSON string)
---
## Key Differences
| Method | Use When | IDs Needed | Filters |
|----------------------|-------------------------------------------|------------|----------|
| `delete(memory_id)` | You know exactly which memory to remove | ✔ | ✘ |
| `batch_delete([...])`| You have a known list of memory IDs | ✔ | ✘ |
| `delete_all(...)` | You want to delete by user/agent/run/etc | ✘ | ✔ |
### More Details
For request/response schema and additional filtering options, see:
- [Delete Memory API Reference](/api-reference/memory/delete-memory)
- [Batch Delete API Reference](/api-reference/memory/batch-delete)
- [Delete Memories by Filter Reference](/api-reference/memory/delete-memories)
You’ve now seen how to add, search, update, and delete memories in Mem0.
---
## Need help?
If you have any questions, please feel free to reach out to us using one of the following methods:
<Snippet file="get-help.mdx"/>
@@ -0,0 +1,124 @@
---
title: Search Memory
description: Retrieve relevant memories from Mem0 using powerful semantic and filtered search capabilities.
icon: "magnifying-glass"
iconType: "solid"
---
## Overview
The `search` operation allows you to retrieve relevant memories based on a natural language query and optional filters like user ID, agent ID, categories, and more. This is the foundation of giving your agents memory-aware behavior.
Mem0 supports:
- Semantic similarity search
- Metadata filtering (with advanced logic)
- Reranking and thresholds
- Cross-agent, multi-session context resolution
This applies to both:
- **Mem0 Platform** (hosted API with full-scale features)
- **Mem0 Open Source** (local-first with LLM inference and local vector DB)
## Architecture
<Frame caption="Architecture diagram illustrating the memory search process.">
<img src="../../images/search_architecture.png" />
</Frame>
The search flow follows these steps:
1. **Query Processing**
An LLM refines and optimizes your natural language query.
2. **Vector Search**
Semantic embeddings are used to find the most relevant memories using cosine similarity.
3. **Filtering & Ranking**
Logical and comparison-based filters are applied. Memories are scored, filtered, and optionally reranked.
4. **Results Delivery**
Relevant memories are returned with associated metadata and timestamps.
---
## Example: Mem0 Platform
<CodeGroup>
```python Python
from mem0 import MemoryClient
client = MemoryClient(api_key="your-api-key")
query = "What do you know about me?"
filters = {
"OR": [
{"user_id": "alice"},
{"agent_id": {"in": ["travel-assistant", "customer-support"]}}
]
}
results = client.search(query, version="v2", filters=filters)
```
```javascript JavaScript
import { MemoryClient } from "mem0ai";
const client = new MemoryClient({apiKey: "your-api-key"});
const query = "I'm craving some pizza. Any recommendations?";
const filters = {
AND: [
{ user_id: "alice" }
]
};
const results = await client.search(query, {
version: "v2",
filters
});
```
</CodeGroup>
---
## Example: Mem0 Open Source
<CodeGroup>
```python Python
from mem0 import Memory
m = Memory()
related_memories = m.search("Should I drink coffee or tea?", user_id="alice")
```
```javascript JavaScript
import { Memory } from 'mem0ai/oss';
const memory = new Memory();
const relatedMemories = memory.search("Should I drink coffee or tea?", { userId: "alice" });
```
</CodeGroup>
---
## Tips for Better Search
- Use descriptive natural queries (Mem0 can interpret intent)
- Apply filters for scoped, faster lookup
- Use `version: "v2"` for enhanced results
- Consider wildcard filters (e.g., `run_id: "*"`) for broader matches
- Tune with `top_k`, `threshold`, or `rerank` if needed
### More Details
For the full list of filter logic, comparison operators, and optional search parameters, see the
[Search Memory API Reference](/api-reference/memory/v2-search-memories).
---
## Need help?
If you have any questions, please feel free to reach out to us using one of the following methods:
<Snippet file="get-help.mdx"/>
@@ -0,0 +1,117 @@
---
title: Update Memory
description: Modify an existing memory by updating its content or metadata.
icon: "pencil"
iconType: "solid"
---
## Overview
User preferences, interests, and behaviors often evolve over time. The `update` operation lets you revise a stored memory, whether it's updating facts and memories, rephrasing a message, or enriching metadata.
Mem0 supports both:
- **Single Memory Update** for one specific memory using its ID
- **Batch Update** for updating many memories at once (up to 1000)
This guide includes usage for both single update and batch update of memories through **Mem0 Platform**
## Use Cases
- Refine a vague or incorrect memory after a correction
- Add or edit memory with new metadata (e.g., categories, tags)
- Evolve factual knowledge as the user’s profile changes
- A user profile evolves: “I love spicy food” → later says “Actually, I can’t handle spicy food.”
Updating memory ensures your agents remain accurate, adaptive, and personalized.
---
## Update Memory
<CodeGroup>
```python Python
from mem0 import MemoryClient
client = MemoryClient(api_key="your-api-key")
memory_id = "your_memory_id"
client.update(
memory_id=memory_id,
text="Updated memory content about the user",
metadata={"category": "profile-update"}
)
```
```javascript JavaScript
import MemoryClient from 'mem0ai';
const client = new MemoryClient({ apiKey: "your-api-key" });
const memory_id = "your_memory_id";
client.update(memory_id, {
text: "Updated memory content about the user",
metadata: { category: "profile-update" }
})
.then(result => console.log(result))
.catch(error => console.error(error));
```
</CodeGroup>
---
## Batch Update
Update up to 1000 memories in one call.
<CodeGroup>
```python Python
from mem0 import MemoryClient
client = MemoryClient(api_key="your-api-key")
update_memories = [
{"memory_id": "id1", "text": "Watches football"},
{"memory_id": "id2", "text": "Likes to travel"}
]
response = client.batch_update(update_memories)
print(response)
```
```javascript JavaScript
import MemoryClient from 'mem0ai';
const client = new MemoryClient({ apiKey: "your-api-key" });
const updateMemories = [
{ memoryId: "id1", text: "Watches football" },
{ memoryId: "id2", text: "Likes to travel" }
];
client.batchUpdate(updateMemories)
.then(response => console.log('Batch update response:', response))
.catch(error => console.error(error));
```
</CodeGroup>
---
## Tips
- You can update both `text` and `metadata` in the same call.
- Use `batchUpdate` when you're applying similar corrections at scale.
- If memory is marked `immutable`, it must first be deleted and re-added.
- Combine this with feedback mechanisms (e.g., user thumbs-up/down) to self-improve memory.
### More Details
Refer to the full [Update Memory API Reference](/api-reference/memory/update-memory) and [Batch Update Reference](/api-reference/memory/batch-update) for schema and advanced fields.
---
## Need help?
If you have any questions, please feel free to reach out to us using one of the following methods:
<Snippet file="get-help.mdx"/>
-2
View File
@@ -5,8 +5,6 @@ icon: "memory"
iconType: "solid"
---
<Snippet file="paper-release.mdx" />
To build useful AI applications, we need to understand how different memory systems work together. This guide explores the fundamental types of memory in AI systems and shows how Mem0 implements these concepts.
## Why Memory Matters
+563 -303
View File
@@ -1,172 +1,390 @@
{
"$schema": "https://mintlify.com/docs.json",
"theme": "maple",
"name": "Mem0",
"description": "Mem0 is a self-improving memory layer for LLM applications, enabling personalized AI experiences that save costs and delight users.",
"theme": "aspen",
"colors": {
"primary": "#6c60f0",
"light": "#E6FFA2",
"dark": "#a3df02"
"primary": "#2553eb",
"light": "#6084fa",
"dark": "#2553eb"
},
"favicon": "/logo/favicon.png",
"navigation": {
"anchors": [
"versions": [
{
"anchor": "Documentation",
"icon": "book-open",
"tabs": [
"version": "v1.0.0 Beta",
"anchors": [
{
"tab": "Documentation",
"groups": [
"anchor": "Documentation",
"icon": "book-open",
"tabs": [
{
"group": "Get Started",
"icon": "rocket",
"pages": [
"overview",
"quickstart",
"faqs"
]
},
{
"group": "Core Concepts",
"icon": "brain",
"pages": [
"core-concepts/memory-types",
"core-concepts/memory-operations"
]
},
{
"group": "Platform",
"icon": "cogs",
"pages": [
"platform/overview",
"platform/quickstart",
"tab": "Documentation",
"groups": [
{
"group": "Features",
"icon": "star",
"group": "Getting Started",
"icon": "rocket",
"pages": [
"features/platform-overview",
"features/advanced-retrieval",
"features/contextual-add",
"features/multimodal-support",
"features/timestamp",
"features/selective-memory",
"features/custom-categories",
"features/custom-instructions",
"features/direct-import",
"features/async-client",
"features/memory-export",
"features/webhooks",
"features/graph-memory",
"features/feedback-mechanism",
"features/expiration-date"
]
}
]
},
{
"group": "Open Source",
"icon": "code-branch",
"pages": [
"open-source/quickstart",
"open-source/python-quickstart",
"open-source/node-quickstart",
{
"group": "Features",
"icon": "wrench",
"pages": [
"open-source/features/async-memory",
"features/openai_compatibility",
"features/custom-fact-extraction-prompt",
"features/custom-update-memory-prompt",
"open-source/multimodal-support",
"open-source/features/rest-api"
"introduction",
"quickstart",
"faqs"
]
},
{
"group": "Graph Memory",
"icon": "spider-web",
"pages": [
"open-source/graph_memory/overview",
"open-source/graph_memory/features"
]
},
{
"group": "LLMs",
"group": "Core Concepts",
"icon": "brain",
"pages": [
"components/llms/overview",
"components/llms/config",
"core-concepts/memory-types",
{
"group": "Supported LLMs",
"icon": "list",
"group": "Memory Operations",
"icon": "gear",
"pages": [
"components/llms/models/openai",
"components/llms/models/anthropic",
"components/llms/models/azure_openai",
"components/llms/models/ollama",
"components/llms/models/together",
"components/llms/models/groq",
"components/llms/models/litellm",
"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/lmstudio",
"components/llms/models/langchain"
"core-concepts/memory-operations/add",
"core-concepts/memory-operations/search",
"core-concepts/memory-operations/update",
"core-concepts/memory-operations/delete"
]
}
]
},
{
"group": "Vector Databases",
"icon": "database",
"group": "Platform",
"icon": "globe",
"pages": [
"components/vectordbs/overview",
"components/vectordbs/config",
"platform/overview",
"platform/quickstart",
"platform/advanced-memory-operations",
{
"group": "Supported Vector Databases",
"icon": "server",
"group": "Features",
"icon": "star",
"pages": [
"components/vectordbs/dbs/qdrant",
"components/vectordbs/dbs/chroma",
"components/vectordbs/dbs/pgvector",
"components/vectordbs/dbs/milvus",
"components/vectordbs/dbs/pinecone",
"components/vectordbs/dbs/azure",
"components/vectordbs/dbs/redis",
"components/vectordbs/dbs/elasticsearch",
"components/vectordbs/dbs/opensearch",
"components/vectordbs/dbs/supabase",
"components/vectordbs/dbs/vertex_ai",
"components/vectordbs/dbs/weaviate",
"components/vectordbs/dbs/faiss",
"components/vectordbs/dbs/langchain"
"platform/features/platform-overview",
"platform/features/contextual-add",
"platform/features/async-client",
"platform/features/graph-memory",
"platform/features/advanced-retrieval",
"platform/features/criteria-retrieval",
"platform/features/multimodal-support",
"platform/features/selective-memory",
"platform/features/custom-categories",
"platform/features/custom-instructions",
"platform/features/direct-import",
"platform/features/memory-export",
"platform/features/timestamp",
"platform/features/expiration-date",
"platform/features/webhooks",
"platform/features/feedback-mechanism",
"platform/features/group-chat"
]
}
]
},
{
"group": "Embedding Models",
"icon": "layer-group",
"group": "Open Source",
"icon": "code-branch",
"pages": [
"components/embedders/overview",
"components/embedders/config",
"open-source/overview",
"open-source/python-quickstart",
"open-source/node-quickstart",
{
"group": "Supported Embedding Models",
"icon": "list",
"group": "Features",
"icon": "star",
"pages": [
"components/embedders/models/openai",
"components/embedders/models/azure_openai",
"components/embedders/models/ollama",
"components/embedders/models/huggingface",
"components/embedders/models/vertexai",
"components/embedders/models/gemini",
"components/embedders/models/lmstudio",
"components/embedders/models/together",
"components/embedders/models/langchain"
"open-source/features/overview",
"open-source/features/async-memory",
"open-source/features/openai_compatibility",
"open-source/features/custom-fact-extraction-prompt",
"open-source/features/custom-update-memory-prompt",
"open-source/features/multimodal-support",
"open-source/features/rest-api",
"open-source/features/metadata-filtering",
"open-source/features/reranker-search"
]
},
{
"group": "Graph Memory",
"icon": "spider-web",
"pages": [
"open-source/graph_memory/overview",
"open-source/graph_memory/features"
]
},
{
"group": "LLMs",
"icon": "brain",
"pages": [
"components/llms/overview",
"components/llms/config",
{
"group": "Supported LLMs",
"icon": "list",
"pages": [
"components/llms/models/openai",
"components/llms/models/anthropic",
"components/llms/models/azure_openai",
"components/llms/models/ollama",
"components/llms/models/together",
"components/llms/models/groq",
"components/llms/models/litellm",
"components/llms/models/mistral_AI",
"components/llms/models/google_AI",
"components/llms/models/aws_bedrock",
"components/llms/models/deepseek",
"components/llms/models/xAI",
"components/llms/models/sarvam",
"components/llms/models/lmstudio",
"components/llms/models/langchain",
"components/llms/models/vllm"
]
}
]
},
{
"group": "Vector Databases",
"icon": "database",
"pages": [
"components/vectordbs/overview",
"components/vectordbs/config",
{
"group": "Supported Vector Databases",
"icon": "server",
"pages": [
"components/vectordbs/dbs/qdrant",
"components/vectordbs/dbs/chroma",
"components/vectordbs/dbs/pgvector",
"components/vectordbs/dbs/milvus",
"components/vectordbs/dbs/pinecone",
"components/vectordbs/dbs/mongodb",
"components/vectordbs/dbs/azure",
"components/vectordbs/dbs/redis",
"components/vectordbs/dbs/valkey",
"components/vectordbs/dbs/elasticsearch",
"components/vectordbs/dbs/opensearch",
"components/vectordbs/dbs/supabase",
"components/vectordbs/dbs/upstash-vector",
"components/vectordbs/dbs/vectorize",
"components/vectordbs/dbs/vertex_ai",
"components/vectordbs/dbs/weaviate",
"components/vectordbs/dbs/faiss",
"components/vectordbs/dbs/langchain",
"components/vectordbs/dbs/baidu",
"components/vectordbs/dbs/s3_vectors",
"components/vectordbs/dbs/databricks",
"components/vectordbs/dbs/neptune_analytics"
]
}
]
},
{
"group": "Embedding Models",
"icon": "layer-group",
"pages": [
"components/embedders/overview",
"components/embedders/config",
{
"group": "Supported Embedding Models",
"icon": "list",
"pages": [
"components/embedders/models/openai",
"components/embedders/models/azure_openai",
"components/embedders/models/ollama",
"components/embedders/models/huggingface",
"components/embedders/models/vertexai",
"components/embedders/models/google_AI",
"components/embedders/models/lmstudio",
"components/embedders/models/together",
"components/embedders/models/langchain",
"components/embedders/models/aws_bedrock"
]
}
]
},
{
"group": "Rerankers (New in v1.0)",
"icon": "sort",
"pages": [
"components/rerankers/overview",
"components/rerankers/config",
{
"group": "Supported Rerankers",
"icon": "list",
"pages": [
"components/rerankers/models/cohere",
"components/rerankers/models/sentence_transformer",
"components/rerankers/models/huggingface",
"components/rerankers/models/llm_reranker"
]
}
]
}
]
},
{
"group": "Migration Guide",
"icon": "arrow-right",
"pages": [
"migration/v0-to-v1",
"migration/breaking-changes",
"migration/api-changes"
]
},
{
"group": "OpenMemory",
"icon": "square-terminal",
"pages": [
"openmemory/overview",
"openmemory/quickstart",
"openmemory/integrations"
]
},
{
"group": "Contribution",
"icon": "handshake",
"pages": [
"contributing/development",
"contributing/documentation"
]
}
]
},
{
"tab": "Examples",
"groups": [
{
"group": "💡 Examples",
"icon": "lightbulb",
"pages": [
"examples",
"examples/aws_example",
"examples/aws_neptune_analytics_hybrid_store",
"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",
"examples/personal-ai-tutor",
"examples/customer-support-agent",
"examples/personal-travel-assistant",
"examples/llama-index-mem0",
"examples/chrome-extension",
"examples/memory-guided-content-writing",
"examples/multimodal-demo",
"examples/personalized-deep-research",
"examples/mem0-agentic-tool",
"examples/openai-inbuilt-tools",
"examples/mem0-openai-voice-demo",
"examples/mem0-google-adk-healthcare-assistant",
"examples/email_processing",
"examples/youtube-assistant"
]
}
]
},
{
"tab": "Integrations",
"groups": [
{
"group": "Integrations",
"icon": "plug",
"pages": [
"integrations",
"integrations/langchain",
"integrations/langgraph",
"integrations/llama-index",
"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/dify",
"integrations/raycast"
]
}
]
},
{
"tab": "API Reference",
"icon": "square-terminal",
"groups": [
{
"group": "API Reference",
"icon": "terminal",
"pages": [
"api-reference",
{
"group": "Memory APIs",
"icon": "microchip",
"pages": [
"api-reference/memory/add-memories",
"api-reference/memory/v2-search-memories",
"api-reference/memory/v1-search-memories",
"api-reference/memory/v2-get-memories",
"api-reference/memory/v1-get-memories",
"api-reference/memory/history-memory",
"api-reference/memory/get-memory",
"api-reference/memory/update-memory",
"api-reference/memory/batch-update",
"api-reference/memory/delete-memory",
"api-reference/memory/batch-delete",
"api-reference/memory/delete-memories",
"api-reference/memory/create-memory-export",
"api-reference/memory/get-memory-export",
"api-reference/memory/feedback"
]
},
{
"group": "Entities APIs",
"icon": "users",
"pages": [
"api-reference/entities/get-users",
"api-reference/entities/delete-user"
]
},
{
"group": "Organizations APIs",
"icon": "building",
"pages": [
"api-reference/organization/create-org",
"api-reference/organization/get-orgs",
"api-reference/organization/get-org",
"api-reference/organization/get-org-members",
"api-reference/organization/add-org-member",
"api-reference/organization/delete-org"
]
},
{
"group": "Project APIs",
"icon": "folder",
"pages": [
"api-reference/project/create-project",
"api-reference/project/get-projects",
"api-reference/project/get-project",
"api-reference/project/get-project-members",
"api-reference/project/add-project-member",
"api-reference/project/delete-project"
]
},
{
"group": "Webhook APIs",
"icon": "webhook",
"pages": [
"api-reference/webhook/create-webhook",
"api-reference/webhook/get-webhook",
"api-reference/webhook/update-webhook",
"api-reference/webhook/delete-webhook"
]
}
]
@@ -174,186 +392,228 @@
]
},
{
"group": "Contribution",
"icon": "handshake",
"pages": [
"contributing/development",
"contributing/documentation"
]
}
]
},
{
"tab": "Examples",
"groups": [
{
"group": "💡 Examples",
"icon": "lightbulb",
"pages": [
"examples",
"examples/mem0-demo",
"examples/ai_companion_js",
"examples/mem0-mastra",
"examples/mem0-with-ollama",
"examples/personal-ai-tutor",
"examples/customer-support-agent",
"examples/personal-travel-assistant",
"examples/llama-index-mem0",
"examples/chrome-extension",
"examples/document-writing",
"examples/multimodal-demo",
"examples/personalized-deep-research",
"examples/mem0-agentic-tool",
"examples/openai-inbuilt-tools",
"examples/mem0-openai-voice-demo",
"examples/email_processing",
"examples/youtube-assistant"
]
}
]
},
{
"tab": "Integrations",
"groups": [
{
"group": "Integrations",
"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/keywords"
]
}
]
},
{
"tab": "API Reference",
"icon": "square-terminal",
"groups": [
{
"group": "API Reference",
"icon": "terminal",
"pages": [
"api-reference",
"tab": "Changelog",
"icon": "clock",
"groups": [
{
"group": "Memory APIs",
"icon": "microchip",
"group": "Product Updates",
"icon": "rocket",
"pages": [
"api-reference/memory/add-memories",
"api-reference/memory/v2-search-memories",
"api-reference/memory/v1-search-memories",
"api-reference/memory/v2-get-memories",
"api-reference/memory/v1-get-memories",
"api-reference/memory/history-memory",
"api-reference/memory/get-memory",
"api-reference/memory/update-memory",
"api-reference/memory/batch-update",
"api-reference/memory/delete-memory",
"api-reference/memory/batch-delete",
"api-reference/memory/delete-memories",
"api-reference/memory/create-memory-export",
"api-reference/memory/get-memory-export",
"api-reference/memory/feedback"
]
},
{
"group": "Entities APIs",
"icon": "users",
"pages": [
"api-reference/entities/get-users",
"api-reference/entities/delete-user"
]
},
{
"group": "Organizations APIs",
"icon": "building",
"pages": [
"api-reference/organization/create-org",
"api-reference/organization/get-orgs",
"api-reference/organization/get-org",
"api-reference/organization/get-org-members",
"api-reference/organization/add-org-member",
"api-reference/organization/delete-org"
]
},
{
"group": "Project APIs",
"icon": "folder",
"pages": [
"api-reference/project/create-project",
"api-reference/project/get-projects",
"api-reference/project/get-project",
"api-reference/project/get-project-members",
"api-reference/project/add-project-member",
"api-reference/project/delete-project"
]
},
{
"group": "Webhook APIs",
"icon": "webhook",
"pages": [
"api-reference/webhook/create-webhook",
"api-reference/webhook/get-webhook",
"api-reference/webhook/update-webhook",
"api-reference/webhook/delete-webhook"
"changelog"
]
}
]
}
]
},
{
"tab": "Changelog",
"icon": "clock",
"groups": [
{
"group": "Product Updates",
"icon": "rocket",
"pages": [
"changelog"
]
}
]
}
]
},
{
"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"
"version": "v0.x Legacy",
"anchors": [
{
"anchor": "Documentation",
"icon": "book-open",
"tabs": [
{
"tab": "Documentation",
"groups": [
{
"group": "Getting Started",
"icon": "rocket",
"pages": [
"v0x/introduction",
"v0x/quickstart",
"v0x/faqs"
]
},
{
"group": "Core Concepts",
"icon": "brain",
"pages": [
"v0x/core-concepts/memory-types",
{
"group": "Memory Operations",
"icon": "gear",
"pages": [
"v0x/core-concepts/memory-operations/add",
"v0x/core-concepts/memory-operations/search",
"v0x/core-concepts/memory-operations/update",
"v0x/core-concepts/memory-operations/delete"
]
}
]
},
{
"group": "Open Source",
"icon": "code-branch",
"pages": [
"v0x/open-source/overview",
"v0x/open-source/python-quickstart",
"v0x/open-source/node-quickstart",
{
"group": "LLMs",
"icon": "brain",
"pages": [
"v0x/components/llms/overview",
"v0x/components/llms/config",
{
"group": "Supported LLMs",
"icon": "list",
"pages": [
"v0x/components/llms/models/openai",
"v0x/components/llms/models/anthropic",
"v0x/components/llms/models/azure_openai",
"v0x/components/llms/models/ollama",
"v0x/components/llms/models/together",
"v0x/components/llms/models/groq",
"v0x/components/llms/models/litellm",
"v0x/components/llms/models/mistral_AI",
"v0x/components/llms/models/google_AI",
"v0x/components/llms/models/aws_bedrock",
"v0x/components/llms/models/deepseek",
"v0x/components/llms/models/xAI",
"v0x/components/llms/models/sarvam",
"v0x/components/llms/models/lmstudio",
"v0x/components/llms/models/langchain",
"v0x/components/llms/models/vllm"
]
}
]
},
{
"group": "Vector Databases",
"icon": "database",
"pages": [
"v0x/components/vectordbs/overview",
"v0x/components/vectordbs/config",
{
"group": "Supported Vector Databases",
"icon": "server",
"pages": [
"v0x/components/vectordbs/dbs/qdrant",
"v0x/components/vectordbs/dbs/chroma",
"v0x/components/vectordbs/dbs/pgvector",
"v0x/components/vectordbs/dbs/milvus",
"v0x/components/vectordbs/dbs/pinecone",
"v0x/components/vectordbs/dbs/mongodb",
"v0x/components/vectordbs/dbs/azure",
"v0x/components/vectordbs/dbs/redis",
"v0x/components/vectordbs/dbs/valkey",
"v0x/components/vectordbs/dbs/elasticsearch",
"v0x/components/vectordbs/dbs/opensearch",
"v0x/components/vectordbs/dbs/supabase",
"v0x/components/vectordbs/dbs/upstash-vector",
"v0x/components/vectordbs/dbs/vectorize",
"v0x/components/vectordbs/dbs/vertex_ai",
"v0x/components/vectordbs/dbs/weaviate",
"v0x/components/vectordbs/dbs/faiss",
"v0x/components/vectordbs/dbs/langchain",
"v0x/components/vectordbs/dbs/baidu",
"v0x/components/vectordbs/dbs/s3_vectors",
"v0x/components/vectordbs/dbs/databricks",
"v0x/components/vectordbs/dbs/neptune_analytics"
]
}
]
},
{
"group": "Embedding Models",
"icon": "layer-group",
"pages": [
"v0x/components/embedders/overview",
"v0x/components/embedders/config",
{
"group": "Supported Embedding Models",
"icon": "list",
"pages": [
"v0x/components/embedders/models/openai",
"v0x/components/embedders/models/azure_openai",
"v0x/components/embedders/models/ollama",
"v0x/components/embedders/models/huggingface",
"v0x/components/embedders/models/vertexai",
"v0x/components/embedders/models/google_AI",
"v0x/components/embedders/models/lmstudio",
"v0x/components/embedders/models/together",
"v0x/components/embedders/models/langchain",
"v0x/components/embedders/models/aws_bedrock"
]
}
]
}
]
}
]
},
{
"tab": "Examples",
"groups": [
{
"group": "💡 Examples",
"icon": "lightbulb",
"pages": [
"v0x/examples/aws_example",
"v0x/examples/aws_neptune_analytics_hybrid_store",
"v0x/examples/mem0-demo",
"v0x/examples/ai_companion_js",
"v0x/examples/collaborative-task-agent",
"v0x/examples/llamaindex-multiagent-learning-system",
"v0x/examples/personalized-search-tavily-mem0",
"v0x/examples/eliza_os",
"v0x/examples/mem0-mastra",
"v0x/examples/mem0-with-ollama",
"v0x/examples/personal-ai-tutor",
"v0x/examples/customer-support-agent",
"v0x/examples/personal-travel-assistant",
"v0x/examples/llama-index-mem0",
"v0x/examples/chrome-extension",
"v0x/examples/memory-guided-content-writing",
"v0x/examples/multimodal-demo",
"v0x/examples/personalized-deep-research",
"v0x/examples/mem0-agentic-tool",
"v0x/examples/openai-inbuilt-tools",
"v0x/examples/mem0-openai-voice-demo",
"v0x/examples/mem0-google-adk-healthcare-assistant",
"v0x/examples/email_processing",
"v0x/examples/youtube-assistant"
]
}
]
},
{
"tab": "Integrations",
"groups": [
{
"group": "Integrations",
"icon": "plug",
"pages": [
"v0x/integrations/langchain",
"v0x/integrations/langgraph",
"v0x/integrations/llama-index",
"v0x/integrations/agno",
"v0x/integrations/autogen",
"v0x/integrations/crewai",
"v0x/integrations/openai-agents-sdk",
"v0x/integrations/google-ai-adk",
"v0x/integrations/mastra",
"v0x/integrations/vercel-ai-sdk",
"v0x/integrations/livekit",
"v0x/integrations/pipecat",
"v0x/integrations/elevenlabs",
"v0x/integrations/aws-bedrock",
"v0x/integrations/flowise",
"v0x/integrations/langchain-tools",
"v0x/integrations/agentops",
"v0x/integrations/keywords",
"v0x/integrations/dify",
"v0x/integrations/raycast"
]
}
]
}
]
}
]
}
]
},
@@ -365,7 +625,7 @@
"background": {
"color": {
"light": "#fff",
"dark": "#0f1117"
"dark": "#09090b"
}
},
"navbar": {
+52 -47
View File
@@ -3,9 +3,6 @@ title: Overview
description: How to use mem0 in your existing applications?
---
<Snippet file="paper-release.mdx" />
With Mem0, you can create stateful LLM-based applications such as chatbots, virtual assistants, or AI agents. Mem0 enhances your applications by providing a memory layer that makes responses:
- More personalized
@@ -20,64 +17,72 @@ Here are some examples of how Mem0 can be integrated into various applications:
Explore how **Mem0** can power real-world applications and bring personalized, intelligent experiences to life:
<CardGroup cols={2}>
<Card title="AI Companion in Node.js" icon="node" href="/examples/ai_companion_js">
Build a personalized AI Companion in **Node.js** that remembers conversations and adapts over time using Mem0.
</Card>
<CardGroup cols={2}>
<Card title="AI Companion in Node.js" icon="node" href="/examples/ai_companion_js">
Build a personalized AI Companion in **Node.js** that remembers conversations and adapts over time using Mem0.
</Card>
<Card title="Mem0 with Ollama" icon="server" href="/examples/mem0-with-ollama">
Run **Mem0 locally** with **Ollama** to create private, stateful AI experiences without relying on cloud APIs.
</Card>
<Card title="Mem0 with Ollama" icon="server" href="/examples/mem0-with-ollama">
Run **Mem0 locally** with **Ollama** to create private, stateful AI experiences without relying on cloud APIs.
</Card>
<Card title="Personal AI Tutor" icon="graduation-cap" href="/examples/personal-ai-tutor">
Create an **AI Tutor** that adapts to student progress, learning style, and history — for a truly customized learning experience.
</Card>
<Card title="Personal AI Tutor" icon="graduation-cap" href="/examples/personal-ai-tutor">
Create an **AI Tutor** that adapts to student progress, learning style, and history — for a truly customized learning experience.
</Card>
<Card title="Personal Travel Assistant" icon="plane" href="/examples/personal-travel-assistant">
Develop a **Personal Travel Assistant** that remembers your preferences, past trips, and helps plan future adventures.
</Card>
<Card title="Personal Travel Assistant" icon="plane" href="/examples/personal-travel-assistant">
Develop a **Personal Travel Assistant** that remembers your preferences, past trips, and helps plan future adventures.
</Card>
<Card title="Customer Support Agent" icon="headset" href="/examples/customer-support-agent">
Build a **Customer Support AI** that recalls user preferences, past chats, and provides context-aware, efficient help.
</Card>
<Card title="Customer Support Agent" icon="headset" href="/examples/customer-support-agent">
Build a **Customer Support AI** that recalls user preferences, past chats, and provides context-aware, efficient help.
</Card>
<Card title="LlamaIndex + Mem0" icon="book-open" href="/examples/llama-index-mem0">
Combine **LlamaIndex** and Mem0 to create a powerful **ReAct Agent** with persistent memory for smarter interactions.
</Card>
<Card title="LlamaIndex + Mem0" icon="book-open" href="/examples/llama-index-mem0">
Combine **LlamaIndex** and Mem0 to create a powerful **ReAct Agent** with persistent memory for smarter interactions.
</Card>
<Card title="Chrome Extension" icon="puzzle-piece" href="/examples/chrome-extension">
Add **long-term memory** to ChatGPT, Claude, or Perplexity via the **Mem0 Chrome Extension** — personalize your AI chats anywhere.
</Card>
<Card title="LlamaIndex + Mem0 Learning System" icon="book-open" href="/examples/llama-index-mem0">
Multi-agent learning system powered by memory.
</Card>
<Card title="YouTube Assistant" icon="puzzle-piece" href="/examples/youtube-assistant">
<Card title="Chrome Extension" icon="puzzle-piece" href="/examples/chrome-extension">
Add **long-term memory** to ChatGPT, Claude, or Perplexity via the **Mem0 Chrome Extension** — personalize your AI chats anywhere.
</Card>
<Card title="YouTube Assistant" icon="puzzle-piece" href="/examples/youtube-assistant">
Integrate **Mem0** into **YouTube's** native UI, providing personalized responses with video context.
</Card>
<Card title="Document Writing Assistant" icon="pen" href="/examples/document-writing">
Create a **Writing Assistant** that understands and adapts to your unique style, improving consistency and productivity.
</Card>
<Card title="Memory-Guided Content Writing" icon="pen" href="/examples/memory-guided-content-writing">
Create a **Writing Assistant** that understands and adapts to your unique style, improving consistency and productivity.
</Card>
<Card title="Multimodal AI Demo" icon="image" href="/examples/multimodal-demo">
Supercharge AI with **Mem0's multimodal memory** — blend text, images, and more for richer, context-aware interactions.
</Card>
<Card title="Multimodal AI Demo" icon="image" href="/examples/multimodal-demo">
Supercharge AI with **Mem0's multimodal memory** — blend text, images, and more for richer, context-aware interactions.
</Card>
<Card title="Personalized Research Agent" icon="magnifying-glass" href="/examples/personalized-deep-research">
Build a **Deep Research AI** that remembers your research goals and compiles insights from vast information sources.
</Card>
<Card title="Personalized Research Agent" icon="magnifying-glass" href="/examples/personalized-deep-research">
Build a **Deep Research AI** that remembers your research goals and compiles insights from vast information sources.
</Card>
<Card title="Mem0 as an Agentic Tool" icon="robot" href="/examples/mem0-agentic-tool">
Integrate Mem0's memory capabilities with OpenAI's Agents SDK to create AI agents with persistent memory.
</Card>
<Card title="Mem0 as an Agentic Tool" icon="robot" href="/examples/mem0-agentic-tool">
Integrate Mem0's memory capabilities with OpenAI's Agents SDK to create AI agents with persistent memory.
</Card>
<Card title="OpenAI Inbuilt Tools" icon="robot" href="/examples/openai-inbuilt-tools">
Use Mem0's memory capabilities with OpenAI's Inbuilt Tools to create AI agents with persistent memory.
</Card>
<Card title="OpenAI Inbuilt Tools" icon="robot" href="/examples/openai-inbuilt-tools">
Use Mem0's memory capabilities with OpenAI's Inbuilt Tools to create AI agents with persistent memory.
</Card>
<Card title="Mem0 OpenAI Voice Demo" icon="microphone" href="/examples/mem0-openai-voice-demo">
Use Mem0's memory capabilities with OpenAI's Inbuilt Tools to create AI agents with persistent memory.
</Card>
<Card title="Mem0 OpenAI Voice Demo" icon="microphone" href="/examples/mem0-openai-voice-demo">
Use Mem0's memory capabilities with OpenAI's Inbuilt Tools to create AI agents with persistent memory.
</Card>
<Card title="Email Processing" icon="envelope" href="/examples/email_processing">
Use Mem0's memory capabilities to process emails and create AI agents with persistent memory.
</Card>
<Card title="Healthcare Assistant Google ADK" icon="microphone" href="/examples/mem0-google-adk-healthcare-assistant">
Build a personalized healthcare assistant with persistent memory using Google's ADK and Mem0.
</Card>
<Card title="Email Processing" icon="envelope" href="/examples/email_processing">
Use Mem0's memory capabilities to process emails and create AI agents with persistent memory.
</Card>
</CardGroup>
-168
View File
@@ -1,168 +0,0 @@
---
title: AI Companion
---
<Snippet file="paper-release.mdx" />
You can create a personalised AI Companion using Mem0. This guide will walk you through the necessary steps and provide the complete code to get you started.
## Overview
The Personalized AI Companion leverages Mem0 to retain information across interactions, enabling a tailored learning experience. It creates separate memories for both the user and the companion. By integrating with OpenAI's GPT-4 model, the companion can provide detailed and context-aware responses to user queries.
## Setup
Before you begin, ensure you have the required dependencies installed. You can install the necessary packages using pip:
```bash
pip install openai mem0ai
```
## Full Code Example
Below is the complete code to create and interact with an AI Companion using Mem0:
```python
from openai import OpenAI
from mem0 import Memory
import os
# Set the OpenAI API key
os.environ['OPENAI_API_KEY'] = 'sk-xxx'
# Initialize the OpenAI client
client = OpenAI()
class Companion:
def __init__(self, user_id, companion_id):
"""
Initialize the Companion with memory configuration, OpenAI client, and user IDs.
:param user_id: ID for storing user-related memories
:param companion_id: ID for storing companion-related memories
"""
config = {
"vector_store": {
"provider": "qdrant",
"config": {
"host": "localhost",
"port": 6333,
}
},
}
self.memory = Memory.from_config(config)
self.client = client
self.app_id = "app-1"
self.USER_ID = user_id
self.companion_id = companion_id
def analyze_question(self, question):
"""
Analyze the question to determine whether it's about the user or the companion.
"""
check_prompt = f"""
Analyze the given input and determine whether the user is primarily:
1) Talking about themselves or asking for personal advice. They may use words like "I" for this.
2) Inquiring about the AI companions's capabilities or characteristics They may use words like "you" for this.
Respond with a single word:
- 'user' if the input is focused on the user
- 'companion' if the input is focused on the AI companion
If the input is ambiguous or doesn't clearly fit either category, respond with 'user'.
Input: {question}
"""
response = self.client.chat.completions.create(
model="gpt-4",
messages=[{"role": "user", "content": check_prompt}]
)
return response.choices[0].message.content
def ask(self, question):
"""
Ask a question to the AI and store the relevant facts in memory
:param question: The question to ask the AI.
"""
check_answer = self.analyze_question(question)
user_id_to_use = self.USER_ID if check_answer == "user" else self.companion_id
previous_memories = self.memory.search(question, user_id=user_id_to_use)
relevant_memories_text = ""
if previous_memories:
relevant_memories_text = '\n'.join(mem["memory"] for mem in previous_memories)
prompt = f"User input: {question}\nPrevious {check_answer} memories: {relevant_memories_text}"
messages = [
{
"role": "system",
"content": "You are the user's romantic companion. Use the user's input and previous memories to respond. Answer based on the context provided."
},
{
"role": "user",
"content": prompt
}
]
stream = self.client.chat.completions.create(
model="gpt-4",
stream=True,
messages=messages
)
answer = ""
for chunk in stream:
if chunk.choices[0].delta.content is not None:
content = chunk.choices[0].delta.content
print(content, end="")
answer += content
# Store the question and answer in memory
self.memory.add(question, user_id=self.USER_ID, metadata={"app_id": self.app_id})
self.memory.add(answer, user_id=self.companion_id, metadata={"app_id": self.app_id})
def get_memories(self, user_id=None):
"""
Retrieve all memories associated with the given user ID.
:param user_id: Optional user ID to filter memories.
:return: List of memories.
"""
return self.memory.get_all(user_id=user_id)
# Example usage:
user_id = "user"
companion_id = "companion"
ai_companion = Companion(user_id, companion_id)
# Ask a question
ai_companion.ask("Ive been missing you. What have you been up to off late?")
```
### Fetching Memories
You can fetch all the memories at any point in time using the following code:
```python
def print_memories(user_id, label):
print(f"\n{label} Memories:")
memories = ai_companion.get_memories(user_id=user_id)
if memories:
for m in memories:
print(f"- {m['text']}")
else:
print("No memories found.")
# Print user memories
print_memories(user_id, "User")
# Print companion memories
print_memories(companion_id, "Companion")
```
### Key Points
- **Initialization**: The Companion class is initialized with the necessary memory configuration and OpenAI client setup.
- **Asking Questions**: The ask method sends a question to the AI and stores the relevant information in memory.
- **Retrieving Memories**: The get_memories method fetches all stored memories associated with a user.
### Conclusion
As the conversation progresses, Mem0's memory automatically updates based on the interactions, providing a continuously improving personalized experience. This setup ensures that the AI Companion can offer contextually relevant and accurate responses, enhancing the user's experience.
-2
View File
@@ -2,8 +2,6 @@
title: AI Companion in Node.js
---
<Snippet file="paper-release.mdx" />
You can create a personalised AI Companion using Mem0. This guide will walk you through the necessary steps and provide the complete code to get you started.
## Overview
+130
View File
@@ -0,0 +1,130 @@
---
title: "AWS bedrock, OpenSearch and Neptune Analytics"
---
This example demonstrates how to configure and use the `mem0ai` SDK with **AWS Bedrock**, **OpenSearch Service (AOSS)**, and **AWS Neptune Analytics** for persistent memory capabilities in Python.
## Installation
Install the required dependencies to include the Amazon data stack, including **boto3**, **opensearch-py**, and **langchain-aws**:
```bash
pip install "mem0ai[graph,extras]"
```
## Environment Setup
Set your AWS environment variables:
```python
import os
# Set these in your environment or notebook
os.environ['AWS_REGION'] = 'us-west-2'
os.environ['AWS_ACCESS_KEY_ID'] = 'AK00000000000000000'
os.environ['AWS_SECRET_ACCESS_KEY'] = 'AS00000000000000000'
# Confirm they are set
print(os.environ['AWS_REGION'])
print(os.environ['AWS_ACCESS_KEY_ID'])
print(os.environ['AWS_SECRET_ACCESS_KEY'])
```
## Configuration and Usage
This sets up Mem0 with:
- [AWS Bedrock for LLM](https://docs.mem0.ai/components/llms/models/aws_bedrock)
- [AWS Bedrock for embeddings](https://docs.mem0.ai/components/embedders/models/aws_bedrock#aws-bedrock)
- [OpenSearch as the vector store](https://docs.mem0.ai/components/vectordbs/dbs/opensearch)
- [Neptune Analytics as your graph store](https://docs.mem0.ai/open-source/graph_memory/overview#initialize-neptune-analytics).
```python
import boto3
from opensearchpy import RequestsHttpConnection, AWSV4SignerAuth
from mem0.memory.main import Memory
region = 'us-west-2'
service = 'aoss'
credentials = boto3.Session().get_credentials()
auth = AWSV4SignerAuth(credentials, region, service)
config = {
"embedder": {
"provider": "aws_bedrock",
"config": {
"model": "amazon.titan-embed-text-v2:0"
}
},
"llm": {
"provider": "aws_bedrock",
"config": {
"model": "us.anthropic.claude-3-7-sonnet-20250219-v1:0",
"temperature": 0.1,
"max_tokens": 2000
}
},
"vector_store": {
"provider": "opensearch",
"config": {
"collection_name": "mem0",
"host": "your-opensearch-domain.us-west-2.es.amazonaws.com",
"port": 443,
"http_auth": auth,
"connection_class": RequestsHttpConnection,
"pool_maxsize": 20,
"use_ssl": True,
"verify_certs": True,
"embedding_model_dims": 1024,
}
},
"graph_store": {
"provider": "neptune",
"config": {
"endpoint": f"neptune-graph://my-graph-identifier",
},
},
}
# Initialize the memory system
m = Memory.from_config(config)
```
## Usage
Reference [Notebook example](https://github.com/mem0ai/mem0/blob/main/examples/graph-db-demo/neptune-example.ipynb)
#### Add a memory:
```python
messages = [
{"role": "user", "content": "I'm planning to watch a movie tonight. Any recommendations?"},
{"role": "assistant", "content": "How about a thriller movies? They can be quite engaging."},
{"role": "user", "content": "I'm not a big fan of thriller movies but I love sci-fi movies."},
{"role": "assistant", "content": "Got it! I'll avoid thriller recommendations and suggest sci-fi movies in the future."}
]
# Store inferred memories (default behavior)
result = m.add(messages, user_id="alice", metadata={"category": "movie_recommendations"})
```
#### Search a memory:
```python
relevant_memories = m.search(query, user_id="alice")
```
#### Get all memories:
```python
all_memories = m.get_all(user_id="alice")
```
#### Get a specific memory:
```python
memory = m.get(memory_id)
```
---
## Conclusion
With Mem0 and AWS services like Bedrock, OpenSearch, and Neptune Analytics, you can build intelligent AI companions that remember, adapt, and personalize their responses over time. This makes them ideal for long-term assistants, tutors, or support bots with persistent memory and natural conversation abilities.
@@ -0,0 +1,120 @@
---
title: "Neptune Analytics Hybrid Store"
---
This example demonstrates how to configure and use the `mem0ai` SDK with **AWS Bedrock** and **AWS Neptune Analytics** for persistent memory capabilities in Python.
## Installation
Install the required dependencies to include the Amazon data stack, including **boto3** and **langchain-aws**:
```bash
pip install "mem0ai[graph,extras]"
```
## Environment Setup
Set your AWS environment variables:
```python
import os
# Set these in your environment or notebook
os.environ['AWS_REGION'] = 'us-west-2'
os.environ['AWS_ACCESS_KEY_ID'] = 'AK00000000000000000'
os.environ['AWS_SECRET_ACCESS_KEY'] = 'AS00000000000000000'
# Confirm they are set
print(os.environ['AWS_REGION'])
print(os.environ['AWS_ACCESS_KEY_ID'])
print(os.environ['AWS_SECRET_ACCESS_KEY'])
```
## Configuration and Usage
This sets up Mem0 with:
- [AWS Bedrock for LLM](https://docs.mem0.ai/components/llms/models/aws_bedrock)
- [AWS Bedrock for embeddings](https://docs.mem0.ai/components/embedders/models/aws_bedrock#aws-bedrock)
- [Neptune Analytics as the vector store](https://docs.mem0.ai/components/vectordbs/dbs/neptune_analytics)
- [Neptune Analytics as the graph store](https://docs.mem0.ai/open-source/graph_memory/overview#initialize-neptune-analytics).
```python
import boto3
from mem0.memory.main import Memory
region = 'us-west-2'
neptune_analytics_endpoint = 'neptune-graph://my-graph-identifier'
config = {
"embedder": {
"provider": "aws_bedrock",
"config": {
"model": "amazon.titan-embed-text-v2:0"
}
},
"llm": {
"provider": "aws_bedrock",
"config": {
"model": "us.anthropic.claude-3-7-sonnet-20250219-v1:0",
"temperature": 0.1,
"max_tokens": 2000
}
},
"vector_store": {
"provider": "neptune",
"config": {
"collection_name": "mem0",
"endpoint": neptune_analytics_endpoint,
},
},
"graph_store": {
"provider": "neptune",
"config": {
"endpoint": neptune_analytics_endpoint,
},
},
}
# Initialize the memory system
m = Memory.from_config(config)
```
## Usage
Reference [Notebook example](https://github.com/mem0ai/mem0/blob/main/examples/graph-db-demo/neptune-example.ipynb)
#### Add a memory:
```python
messages = [
{"role": "user", "content": "I'm planning to watch a movie tonight. Any recommendations?"},
{"role": "assistant", "content": "How about a thriller movies? They can be quite engaging."},
{"role": "user", "content": "I'm not a big fan of thriller movies but I love sci-fi movies."},
{"role": "assistant", "content": "Got it! I'll avoid thriller recommendations and suggest sci-fi movies in the future."}
]
# Store inferred memories (default behavior)
result = m.add(messages, user_id="alice", metadata={"category": "movie_recommendations"})
```
#### Search a memory:
```python
relevant_memories = m.search(query, user_id="alice")
```
#### Get all memories:
```python
all_memories = m.get_all(user_id="alice")
```
#### Get a specific memory:
```python
memory = m.get(memory_id)
```
---
## Conclusion
With Mem0 and AWS services like Bedrock and Neptune Analytics, you can build intelligent AI companions that remember, adapt, and personalize their responses over time. This makes them ideal for long-term assistants, tutors, or support bots with persistent memory and natural conversation abilities.
-2
View File
@@ -1,7 +1,5 @@
# Mem0 Chrome Extension
<Snippet file="paper-release.mdx" />
Enhance your AI interactions with **Mem0**, a Chrome extension that introduces a universal memory layer across platforms like `ChatGPT`, `Claude`, and `Perplexity`. Mem0 ensures seamless context sharing, making your AI experiences more personalized and efficient.
<Note>
+123
View File
@@ -0,0 +1,123 @@
---
title: Multi-User Collaboration with Mem0
---
## Overview
Build a multi-user collaborative chat or task management system with Mem0. Each message is attributed to its author, and all messages are stored in a shared project space. Mem0 makes it easy to track contributions, sort and group messages, and collaborate in real time.
## Setup
Install the required packages:
```bash
pip install openai mem0ai
```
## Full Code Example
```python
from openai import OpenAI
from mem0 import Memory
import os
from datetime import datetime
from collections import defaultdict
# Set your OpenAI API key
os.environ["OPENAI_API_KEY"] = "sk-your-key"
# Shared project context
RUN_ID = "project-demo"
# Initialize Mem0
mem = Memory()
class CollaborativeAgent:
def __init__(self, run_id):
self.run_id = run_id
self.mem = mem
def add_message(self, role, name, content):
msg = {"role": role, "name": name, "content": content}
self.mem.add([msg], run_id=self.run_id, infer=False)
def brainstorm(self, prompt):
# Get recent messages for context
memories = self.mem.search(prompt, run_id=self.run_id, limit=5)["results"]
context = "\n".join(f"- {m['memory']} (by {m.get('actor_id', 'Unknown')})" for m in memories)
client = OpenAI()
messages = [
{"role": "system", "content": "You are a helpful project assistant."},
{"role": "user", "content": f"Prompt: {prompt}\nContext:\n{context}"}
]
reply = client.chat.completions.create(
model="gpt-4o-mini",
messages=messages
).choices[0].message.content.strip()
self.add_message("assistant", "assistant", reply)
return reply
def get_all_messages(self):
return self.mem.get_all(run_id=self.run_id)["results"]
def print_sorted_by_time(self):
messages = self.get_all_messages()
messages.sort(key=lambda m: m.get('created_at', ''))
print("\n--- Messages (sorted by time) ---")
for m in messages:
who = m.get("actor_id") or "Unknown"
ts = m.get('created_at', 'Timestamp N/A')
try:
dt = datetime.fromisoformat(ts.replace('Z', '+00:00'))
ts_fmt = dt.strftime('%Y-%m-%d %H:%M:%S')
except Exception:
ts_fmt = ts
print(f"[{ts_fmt}] [{who}] {m['memory']}")
def print_grouped_by_actor(self):
messages = self.get_all_messages()
grouped = defaultdict(list)
for m in messages:
grouped[m.get("actor_id") or "Unknown"].append(m)
print("\n--- Messages (grouped by actor) ---")
for actor, mems in grouped.items():
print(f"\n=== {actor} ===")
for m in mems:
ts = m.get('created_at', 'Timestamp N/A')
try:
dt = datetime.fromisoformat(ts.replace('Z', '+00:00'))
ts_fmt = dt.strftime('%Y-%m-%d %H:%M:%S')
except Exception:
ts_fmt = ts
print(f"[{ts_fmt}] {m['memory']}")
```
## Usage
```python
# Example usage
agent = CollaborativeAgent(RUN_ID)
agent.add_message("user", "alice", "Let's list tasks for the new landing page.")
agent.add_message("user", "bob", "I'll own the hero section copy.")
agent.add_message("user", "carol", "I'll choose product screenshots.")
# Brainstorm with context
print("\nAssistant reply:\n", agent.brainstorm("What are the current open tasks?"))
# Print all messages sorted by time
agent.print_sorted_by_time()
# Print all messages grouped by actor
agent.print_grouped_by_actor()
```
## Key Points
- Each message is attributed to a user or agent (actor)
- All messages are stored in a shared project space (`run_id`)
- You can sort messages by time, group by actor, and format timestamps for clarity
- Mem0 makes it easy to build collaborative, attributed chat/task systems
## Conclusion
Mem0 enables fast, transparent collaboration for teams and agents, with full attribution, flexible memory search, and easy message organization.
+1 -1
View File
@@ -2,7 +2,6 @@
title: Customer Support AI Agent
---
<Snippet file="paper-release.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 +22,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
+73
View File
@@ -0,0 +1,73 @@
---
title: Eliza OS Character
---
You can create a personalised Eliza OS Character using Mem0. This guide will walk you through the necessary steps and provide the complete code to get you started.
## Overview
ElizaOS is a powerful AI agent framework for autonomy & personality. It is a collection of tools that help you create a personalised AI agent.
## Setup
You can start by cloning the eliza-os repository:
```bash
git clone https://github.com/elizaOS/eliza.git
```
Change the directory to the eliza-os repository:
```bash
cd eliza
```
Install the dependencies:
```bash
pnpm install
```
Build the project:
```bash
pnpm build
```
## Setup ENVs
Create a `.env` file in the root of the project and add the following ( You can use the `.env.example` file as a reference):
```bash
# Mem0 Configuration
MEM0_API_KEY= # Mem0 API Key ( Get from https://app.mem0.ai/dashboard/api-keys )
MEM0_USER_ID= # Default: eliza-os-user
MEM0_PROVIDER= # Default: openai
MEM0_PROVIDER_API_KEY= # API Key for the provider (openai, anthropic, etc.)
SMALL_MEM0_MODEL= # Default: gpt-4o-mini
MEDIUM_MEM0_MODEL= # Default: gpt-4o
LARGE_MEM0_MODEL= # Default: gpt-4o
```
## Make the default character use Mem0
By default, there is a character called `eliza` that uses the `ollama` model. You can make this character use Mem0 by changing the config in the `agent/src/defaultCharacter.ts` file.
```ts
modelProvider: ModelProviderName.MEM0,
```
This will make the character use Mem0 to generate responses.
## Run the project
```bash
pnpm start
```
## Conclusion
You have now created a personalised Eliza OS Character using Mem0. You can now start interacting with the character by running the project and talking to the character.
This is a simple example of how to use Mem0 to create a personalised AI agent. You can use this as a starting point to create your own AI agent.
-2
View File
@@ -2,8 +2,6 @@
title: Email Processing with Mem0
---
<Snippet file="paper-release.mdx" />
This guide demonstrates how to build an intelligent email processing system using Mem0's memory capabilities. You'll learn how to store, categorize, retrieve, and analyze emails to create a smart email management solution.
## Overview
+4 -5
View File
@@ -1,7 +1,6 @@
---
title: LlamaIndex ReAct Agent
---
<Snippet file="paper-release.mdx" />
Create a ReAct Agent with LlamaIndex which uses Mem0 as the memory store.
@@ -22,7 +21,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 +79,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 +138,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 +170,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
View File
@@ -2,7 +2,6 @@
title: Mem0 as an Agentic Tool
---
<Snippet file="paper-release.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 -4
View File
@@ -2,9 +2,6 @@
title: Mem0 Demo
---
<Snippet file="paper-release.mdx" />
You can create a personalized AI Companion using Mem0. This guide will walk you through the necessary steps and provide the complete setup instructions to get you started.
<video
@@ -16,7 +13,7 @@ You can create a personalized AI Companion using Mem0. This guide will walk you
src="https://github.com/user-attachments/assets/cebc4f8e-bdb9-4837-868d-13c5ab7bb433"
></video>
You can try the [Mem0 Demo](https://mem0.dev/demo) live here.
You can try the [Mem0 Demo](https://mem0-4vmi.vercel.app) live here.
## Overview
@@ -0,0 +1,293 @@
---
title: 'Healthcare Assistant with Mem0 and Google ADK'
description: 'Build a personalized healthcare agent that remembers patient information across conversations using Mem0 and Google ADK'
---
# Healthcare Assistant with Memory
This example demonstrates how to build a healthcare assistant that remembers patient information across conversations using Google ADK and Mem0.
## Overview
The Healthcare Assistant helps patients by:
- Remembering their medical history and symptoms
- Providing general health information
- Scheduling appointment reminders
- Maintaining a personalized experience across conversations
By integrating Mem0's memory layer with Google ADK, the assistant maintains context about the patient without requiring them to repeat information.
## Setup
Before you begin, make sure you have:
Installed Google ADK and Mem0 SDK:
```bash
pip install google-adk mem0ai python-dotenv
```
## Code Breakdown
Let's get started and understand the different components required in building a healthcare assistant powered by memory
```python
# Import dependencies
import os
import asyncio
from google.adk.agents import Agent
from google.adk.runners import Runner
from google.adk.sessions import InMemorySessionService
from google.genai import types
from mem0 import MemoryClient
from dotenv import load_dotenv
load_dotenv()
# Set up environment variables
# os.environ["GOOGLE_API_KEY"] = "your-google-api-key"
# os.environ["MEM0_API_KEY"] = "your-mem0-api-key"
# Define a global user ID for simplicity
USER_ID = "Alex"
# Initialize Mem0 client
mem0 = MemoryClient()
```
## Define Memory Tools
First, we'll create tools that allow our agent to store and retrieve information using Mem0:
```python
def save_patient_info(information: str) -> dict:
"""Saves important patient information to memory."""
# Store in Mem0
response = mem0_client.add(
[{"role": "user", "content": information}],
user_id=USER_ID,
run_id="healthcare_session",
metadata={"type": "patient_information"}
)
def retrieve_patient_info(query: str) -> dict:
"""Retrieves relevant patient information from memory."""
# Search Mem0
results = mem0_client.search(
query,
user_id=USER_ID,
limit=5,
threshold=0.7, # Higher threshold for more relevant results
output_format="v1.1"
)
# Format and return the results
if results and len(results) > 0:
memories = [memory["memory"] for memory in results.get('results', [])]
return {
"status": "success",
"memories": memories,
"count": len(memories)
}
else:
return {
"status": "no_results",
"memories": [],
"count": 0
}
```
## Define Healthcare Tools
Next, we'll add tools specific to healthcare assistance:
```python
def schedule_appointment(date: str, time: str, reason: str) -> dict:
"""Schedules a doctor's appointment."""
# In a real app, this would connect to a scheduling system
appointment_id = f"APT-{hash(date + time) % 10000}"
return {
"status": "success",
"appointment_id": appointment_id,
"confirmation": f"Appointment scheduled for {date} at {time} for {reason}",
"message": "Please arrive 15 minutes early to complete paperwork."
}
```
## Create the Healthcare Assistant Agent
Now we'll create our main agent with all the tools:
```python
# Create the agent
healthcare_agent = Agent(
name="healthcare_assistant",
model="gemini-1.5-flash", # Using Gemini for healthcare assistant
description="Healthcare assistant that helps patients with health information and appointment scheduling.",
instruction="""You are a helpful Healthcare Assistant with memory capabilities.
Your primary responsibilities are to:
1. Remember patient information using the 'save_patient_info' tool when they share symptoms, conditions, or preferences.
2. Retrieve past patient information using the 'retrieve_patient_info' tool when relevant to the current conversation.
3. Help schedule appointments using the 'schedule_appointment' tool.
IMPORTANT GUIDELINES:
- Always be empathetic, professional, and helpful.
- Save important patient information like symptoms, conditions, allergies, and preferences.
- Check if you have relevant patient information before asking for details they may have shared previously.
- Make it clear you are not a doctor and cannot provide medical diagnosis or treatment.
- For serious symptoms, always recommend consulting a healthcare professional.
- Keep all patient information confidential.
""",
tools=[save_patient_info, retrieve_patient_info, schedule_appointment]
)
```
## Set Up Session and Runner
```python
# Set up Session Service and Runner
session_service = InMemorySessionService()
# Define constants for the conversation
APP_NAME = "healthcare_assistant_app"
USER_ID = "Alex"
SESSION_ID = "session_001"
# Create a session
session = session_service.create_session(
app_name=APP_NAME,
user_id=USER_ID,
session_id=SESSION_ID
)
# Create the runner
runner = Runner(
agent=healthcare_agent,
app_name=APP_NAME,
session_service=session_service
)
```
## Interact with the Healthcare Assistant
```python
# Function to interact with the agent
async def call_agent_async(query, runner, user_id, session_id):
"""Sends a query to the agent and returns the final response."""
print(f"\n>>> Patient: {query}")
# Format the user's message
content = types.Content(
role='user',
parts=[types.Part(text=query)]
)
# Set user_id for tools to access
save_patient_info.user_id = user_id
retrieve_patient_info.user_id = user_id
# Run the agent
async for event in runner.run_async(
user_id=user_id,
session_id=session_id,
new_message=content
):
if event.is_final_response():
if event.content and event.content.parts:
response = event.content.parts[0].text
print(f"<<< Assistant: {response}")
return response
return "No response received."
# Example conversation flow
async def run_conversation():
# First interaction - patient introduces themselves with key information
await call_agent_async(
"Hi, I'm Alex. I've been having headaches for the past week, and I have a penicillin allergy.",
runner=runner,
user_id=USER_ID,
session_id=SESSION_ID
)
# Request for health information
await call_agent_async(
"Can you tell me more about what might be causing my headaches?",
runner=runner,
user_id=USER_ID,
session_id=SESSION_ID
)
# Schedule an appointment
await call_agent_async(
"I think I should see a doctor. Can you help me schedule an appointment for next Monday at 2pm?",
runner=runner,
user_id=USER_ID,
session_id=SESSION_ID
)
# Test memory - should remember patient name, symptoms, and allergy
await call_agent_async(
"What medications should I avoid for my headaches?",
runner=runner,
user_id=USER_ID,
session_id=SESSION_ID
)
# Run the conversation example
if __name__ == "__main__":
asyncio.run(run_conversation())
```
## How It Works
This healthcare assistant demonstrates several key capabilities:
1. **Memory Storage**: When Alex mentions her headaches and penicillin allergy, the agent stores this information in Mem0 using the `save_patient_info` tool.
2. **Contextual Retrieval**: When Alex asks about headache causes, the agent uses the `retrieve_patient_info` tool to recall her specific situation.
3. **Memory Application**: When discussing medications, the agent remembers Alex's penicillin allergy without her needing to repeat it, providing safer and more personalized advice.
4. **Conversation Continuity**: The agent maintains context across the entire conversation session, creating a more natural and efficient interaction.
## Key Implementation Details
### User ID Management
Instead of passing the user ID as a parameter to the memory tools (which would require modifying the ADK's tool calling system), we attach it directly to the function object:
```python
# Set user_id for tools to access
save_patient_info.user_id = user_id
retrieve_patient_info.user_id = user_id
```
Inside the tool functions, we retrieve this attribute:
```python
# Get user_id from session state or use default
user_id = getattr(save_patient_info, 'user_id', 'default_user')
```
This approach allows our tools to maintain user context without complicating their parameter signatures.
### Mem0 Integration
The integration with Mem0 happens through two primary functions:
1. `mem0_client.add()` - Stores new information with appropriate metadata
2. `mem0_client.search()` - Retrieves relevant memories using semantic search
The `threshold` parameter in the search function ensures that only highly relevant memories are returned.
## Conclusion
This example demonstrates how to build a healthcare assistant with persistent memory using Google ADK and Mem0. The integration allows for a more personalized patient experience by maintaining context across conversation turns, which is particularly valuable in healthcare scenarios where continuity of information is crucial.
By storing and retrieving patient information intelligently, the assistant provides more relevant responses without requiring the patient to repeat their medical history, symptoms, or preferences.
-2
View File
@@ -2,8 +2,6 @@
title: Mem0 with Mastra
---
<Snippet file="paper-release.mdx" />
In this example you'll learn how to use the Mem0 to add long-term memory capabilities to [Mastra's agent](https://mastra.ai/) via tool-use.
This memory integration can work alongside Mastra's [agent memory features](https://mastra.ai/docs/agents/01-agent-memory).
-2
View File
@@ -3,8 +3,6 @@ title: 'Mem0 with OpenAI Agents SDK for Voice'
description: 'Integrate memory capabilities into your voice agents using Mem0 and OpenAI Agents SDK'
---
<Snippet file="paper-release.mdx" />
# Building Voice Agents with Memory using Mem0 and OpenAI Agents SDK
This guide demonstrates how to combine OpenAI's Agents SDK for voice applications with Mem0's memory capabilities to create a voice assistant that remembers user preferences and past interactions.
-3
View File
@@ -2,8 +2,6 @@
title: Mem0 with Ollama
---
<Snippet file="paper-release.mdx" />
## Running Mem0 Locally with Ollama
Mem0 can be utilized entirely locally by leveraging Ollama for both the embedding model and the language model (LLM). This guide will walk you through the necessary steps and provide the complete code to get you started.
@@ -21,7 +19,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,132 @@
---
title: Document Editing with Mem0
title: Memory-Guided Content Writing
---
<Snippet file="paper-release.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"
client = MemoryClient()
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 +136,6 @@ def document_editing_workflow(content):
return edited_content
```
---
## **Example Usage**
```python
@@ -125,10 +153,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 +209,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" />
+13 -15
View File
@@ -2,32 +2,30 @@
title: Multimodal Demo with Mem0
---
<Snippet file="paper-release.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.
+1 -3
View File
@@ -2,8 +2,6 @@
title: OpenAI Inbuilt Tools
---
<Snippet file="paper-release.mdx" />
Integrate Mem0’s memory capabilities with OpenAI’s Inbuilt Tools to create AI agents with persistent memory.
## Getting Started
@@ -225,7 +223,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}` : "";
};

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