Compare commits

..

189 Commits

Author SHA1 Message Date
Dev Khant 9cb2a13f3b fix for Azure AI and version bump -> 0.1.76 (#2438) 2025-03-25 18:10:36 +05:30
Dev Khant 5ec7889d9a embedchain version bump -> 0.1.128 (#2437) 2025-03-25 13:18:34 +05:30
Dev Khant b54845bcc9 Add feeback method to client and doc changes (#2435) 2025-03-25 11:39:19 +05:30
Saket Aryan 1ae2747ff8 Add Supabase History DB to run Mem0 OSS on Serverless (#2429) 2025-03-24 16:14:29 -07:00
Parshva Daftari 953a5a4a2d Azure openai fixes (#2428) 2025-03-25 00:34:21 +05:30
Saket Aryan 2b49c9eedd Supabase Vector Store (#2427) 2025-03-25 00:15:50 +05:30
Anusha Yella 9db5f62262 fix-azure-ai-search-test-cases (#2422) 2025-03-24 15:20:02 +05:30
Dev Khant a1bd4285db version bump -> 0.1.75 (#2426) 2025-03-24 15:17:00 +05:30
Dev Khant e77a10a8da Add LM Studio support (#2425) 2025-03-24 13:32:26 +05:30
Gaurav Agerwala e4307ae420 Fix: Export ollama (#2421)
Co-authored-by: Gaurav Agerwala <ice@Gauravs-MacBook-Pro.local>
2025-03-23 02:06:23 +05:30
Saket Aryan 7c89d00079 Adds Langchain Community Package (#2417) 2025-03-22 10:44:40 +05:30
Dev Khant 563eaae5ee Openai Agents SDK voice demo (#2416) 2025-03-22 01:09:37 +05:30
Dev Khant 6733f78f81 Doc: Support for expiration date in ADD (#2419) 2025-03-21 23:38:25 +05:30
Saket Aryan c11637bd2f Update Node SDK Docs for Update Method (#2418) 2025-03-21 21:23:57 +05:30
Dev-Khant ff30cb8ddd version bump -> 0.1.74 2025-03-21 13:06:40 +05:30
Parshva Daftari 2e853c3d22 Updated VDB Docs (#2409) 2025-03-20 23:47:57 +05:30
Dev Khant 3cc7013fde fix pinecone (#2414) 2025-03-20 23:47:09 +05:30
Dev Khant 8e6a08aa83 Support for hybrid search in Azure AI vector store (#2408)
Co-authored-by: Deshraj Yadav <deshrajdry@gmail.com>
2025-03-20 22:57:00 +05:30
Wonbin Kim 8b9a8e5825 URGENT Hotfix - update default Elasticsearch search query (#2413) 2025-03-20 20:50:18 +05:30
Dev Khant afc630272d bump version -> 0.1.73 (#2412) 2025-03-20 19:30:29 +05:30
Parshva Daftari e33008e3a4 Add: Pinecone integration (#2395) 2025-03-20 12:57:32 +05:30
Mauricio A 7b516328a8 Feature/fix opensearch vector mapping (#2399) 2025-03-20 09:37:57 +05:30
Dev Khant 6d5889d98f version bump -> 0.1.72 (#2405) 2025-03-20 00:10:27 +05:30
Parshva Daftari ee66e0c954 Reverting the tools commit (#2404) 2025-03-20 00:09:00 +05:30
Prateek Chhikara 1aed611539 Added graph memory (#2403) 2025-03-19 09:51:15 -07:00
Saket Aryan 6c2b131d6e Added Feedback in SDK (#2393) 2025-03-19 09:11:45 -07:00
Gaurav Agerwala 2ffe9922f3 Added support for Ollama in TS SDK (#2345)
Co-authored-by: Dev Khant <devkhant24@gmail.com>
2025-03-19 21:38:19 +05:30
Dev Khant 540ada489b version bump -> 0.1.71 (#2402) 2025-03-19 21:36:06 +05:30
Dev Khant 65cffa0369 Fix: made tools support for graph (#2400) 2025-03-19 21:29:36 +05:30
Dev Khant 9f937943ba Doc: update oss quickstart page (#2401) 2025-03-19 17:27:09 +05:30
Dev-Khant 51a68bf7c5 Doc: update azure ai vector store 2025-03-18 14:32:12 +05:30
Dev-Khant 92541d8955 Doc: azure ai vector search 2025-03-18 14:17:56 +05:30
Dev Khant 0e0be18ecc Fix azure ai vector store (#2396) 2025-03-18 14:13:19 +05:30
Wonbin Kim 66d3f9b93c Support Custom Prompt for Memory Action Decision (#2371) 2025-03-18 10:43:01 +05:30
Wonbin Kim b8f40f728f Support Custom Search Query for Elasticsearch (#2372) 2025-03-18 10:34:34 +05:30
Prateek Chhikara 00a2ea9ff0 Added export instructions to docs (#2394) 2025-03-17 17:41:56 -07:00
Prateek Chhikara 9545836469 Added docs for add-v2 (#2381) 2025-03-17 15:39:17 -07:00
Saket Aryan 3acd9e20da Fix Redis Search (#2392) 2025-03-17 15:30:40 -07:00
Dev Khant d48ecd52ef update poetry lock file (#2391) 2025-03-18 01:11:05 +05:30
Saket Aryan 2fbea7705b Add Intercom to Docs (#2390) 2025-03-17 12:37:56 -07:00
Dev Khant d7a26bd0c3 Add infer param and version bump (#2389)
Co-authored-by: Deshraj Yadav <deshrajdry@gmail.com>
2025-03-18 01:04:58 +05:30
Farzad Sunavala e25dc4b504 bugfix: update Azure AI Search Config (#2380) 2025-03-17 22:19:46 +05:30
Parshva Daftari dab3349990 Neo4j embeddings error (#2377) 2025-03-17 21:57:23 +05:30
Saket Aryan 6db87e8d07 Make DEMO UI Responsive (#2382) 2025-03-14 20:00:28 -07:00
Saket Aryan faf811ee2d Added Custom Categories in Mem0-TS (#2370) 2025-03-14 22:07:46 +05:30
Anusha Yella ee80a43810 Remove tools from LLMs (#2363) 2025-03-14 17:42:48 +05:30
Dev Khant 4be426f762 version bump -> 0.1.68 (#2369) 2025-03-12 21:22:49 +05:30
Farzad Sunavala ba9c61938b feat: enhance Azure AI Search Integration with Binary Quantization, Pre/Post Filter Options, and user agent header (#2354) 2025-03-12 21:20:25 +05:30
Parshva Daftari 65f826e064 Fix langchain neo4j deprecation warning (#2350) 2025-03-12 15:30:45 +05:30
Saket Aryan b43363cdf3 OpenAI Inbuilt Tools (#2362) 2025-03-11 15:33:49 -07:00
Prateek Chhikara 89e786a88e Added agentic tool in docs (#2361) 2025-03-11 13:36:20 -07:00
Saket Aryan 2d5062bd40 Updated Demo (#2360) 2025-03-12 01:49:08 +05:30
Parshva Daftari b89628322d WeaviateDB Integration (#2339) 2025-03-11 00:12:17 +05:30
Dev Khant 6e4fb22a7c version bump -> 0.1.67 (#2357) 2025-03-10 23:51:30 +05:30
Dev Khant 9c0954133f Improve multimodal functionality (#2297) 2025-03-10 23:33:18 +05:30
Dev Khant e9a0be66d8 Doc: Fix examples (#2355) 2025-03-10 20:08:58 +05:30
Dev Khant 192c33f190 Doc: update examples page (#2348) 2025-03-10 12:04:44 +05:30
Dev Khant 75ca528666 Doc: Fix examples page (#2346) 2025-03-10 11:36:02 +05:30
Saket Aryan e30e4967ae Added Cloudflare Worker Compatible Configs (#2343) 2025-03-09 13:11:47 -07:00
Prateek Chhikara d3911b92cf Docs Update (#2337) 2025-03-08 10:30:42 -08:00
Dev Khant 92cfc1c8ef Doc: update examples name (#2342) 2025-03-08 23:56:00 +05:30
Dev Khant 33fcc53e4b Doc: Update name of deepresearch example (#2338) 2025-03-08 12:25:06 +05:30
Dev Khant e761a1e865 Doc: Deepresearch example (#2336) 2025-03-08 01:02:51 +05:30
Dev Khant f2ce92ebcc Update multimodal example (#2335) 2025-03-08 00:06:45 +05:30
Dev Khant bbb812e0a0 version bump -> 0.1.66 (#2334) 2025-03-07 23:56:40 +05:30
Parshva Daftari 9a302cef30 [ Fix ] for the vertex_ai_vector_search documentation (#2323) 2025-03-07 23:54:07 +05:30
Dev Khant ae729da4d1 Doc: Multimodality usecase (#2333) 2025-03-07 23:52:27 +05:30
Dev Khant 655ae794b6 Examples: Add multimodal app (#2328) 2025-03-07 23:36:32 +05:30
Dev Khant 1aef468ebe Handle empty field in new_memories_with_actions (#2330) 2025-03-07 16:51:10 +05:30
Dev Khant 78baf7495d Doc: Document editing with Mem0 (#2325) 2025-03-07 16:40:41 +05:30
Dev Khant 6cf7ac3e30 Fixes for new_memories_with_actions (#2326) 2025-03-07 13:13:00 +05:30
Dev Khant 07d2f11081 Catch json error for new_memories_with_action (#2324) 2025-03-07 13:12:00 +05:30
Prateek Chhikara c6fbba6a4d Changed multimodal prompt to extract better text from images (#2322) 2025-03-06 11:57:20 -08:00
Dev Khant b701a50b51 Doc: Update chrome extension placement (#2321) 2025-03-06 23:58:23 +05:30
Dev Khant 5865d79de7 Doc: Chrome extension (#2319) 2025-03-06 21:41:34 +05:30
Dev Khant 41a42da774 Doc: Mem0 mcp with cursor (#2318) 2025-03-06 07:46:14 -08:00
Saket Aryan 6d7ef3ae45 Multimodal Support NodeSDK (#2320) 2025-03-06 17:50:41 +05:30
yanzz 2c31a930a3 Update README.md (#2187) 2025-03-05 12:41:43 -08:00
Dev Khant c7e2a71cd5 Update cd.yml 2025-03-06 00:19:12 +05:30
Dev Khant 4237b9220b CD changes (#2316) 2025-03-06 00:10:57 +05:30
Dev-Khant cabe29c7c7 version bump -> 0.1.65 2025-03-06 00:02:18 +05:30
Mini256 80b7202db6 fix: fix sample code on README.md (#2312) 2025-03-06 00:00:13 +05:30
Rafael Nico T. Maniquiz 8c6d16a6f0 Fix Embedding Dimension Parameter Not Being Passed (#2304) 2025-03-05 20:23:36 +05:30
Dev Khant dd1f2989bc revert cd changes (#2315) 2025-03-05 17:33:17 +05:30
Dev Khant 540ec1b816 fix cd (#2314) 2025-03-05 17:14:37 +05:30
Dev Khant 728ef98d6e Doc: Update doc for both user and agent (#2313) 2025-03-05 17:05:28 +05:30
Dev Khant 329d0cc945 version bump -> 0.1.64 (#2310) 2025-03-05 16:17:19 +05:30
Dev Khant 0234c85be5 Fix CD (#2309) 2025-03-05 16:10:59 +05:30
Dev Khant eca1e06711 Doc: Update add memories (#2306) 2025-03-05 01:57:44 -08:00
Saket Aryan 2611343cbe Updated Docs to add Mem0 Demo Link/ Updated Mem0 Demo (#2305) 2025-03-05 01:11:33 -08:00
Dev Khant 8bde881e2c Add AWS lambda issue to FAQ (#2303) 2025-03-04 23:43:28 -08:00
Saket Aryan 6fdc63504a Graph Support for NodeSDK (#2298) 2025-03-04 23:22:50 -08:00
anchit-nishant 23dbce4f59 Added support for google vector search - (matching engine) (#2177) 2025-03-05 11:45:47 +05:30
Deshraj Yadav 7c8628eadc Update pyproject.toml (#2301) 2025-03-04 14:22:12 -08:00
Deshraj Yadav 20c03eaa92 [Misc] Clean up unnecessary checks in chromadb vector store integration (#2284) 2025-03-04 14:21:27 -08:00
Saket Aryan aa7ab9736d Add Mem0 Demo (#2291) 2025-03-04 10:04:59 -08:00
Dev Khant f7500c925e fix multimodal functionality and version bump -> 0.1.62 (#2296) 2025-03-04 17:51:27 +05:30
Dev Khant 8b53b1473a Add contribution docs (#2294) 2025-03-04 15:47:38 +05:30
Dev Khant c611e3e0e7 Docs: Add dify integration (#2293) 2025-03-04 14:29:25 +05:30
Taranjeet Singh bc4c15962a Fix: improve url of node js sdk (#2292) 2025-03-03 23:08:44 -08:00
Dev-Khant 6e65730b0e version bump -> 0.1.61 2025-03-03 23:32:41 +05:30
Dev Khant 8452dd598f Integrate Supabase VectorDB (#2290) 2025-03-03 23:16:24 +05:30
Dev Khant 2556c5fe88 Doc: Update examples in LLMs, VectorDBs and Embedding models pages (#2288) 2025-03-03 13:21:19 +05:30
Dev Khant a4340b2336 Fix Qdrant Tests (#2287) 2025-03-03 10:46:56 +05:30
Dev Khant f4dc5f6c71 version bump -> 0.1.60 (#2280) 2025-03-01 13:11:38 +05:30
Deshraj Yadav 32ebdaef2f [Bug Fix] Fix issue with chromadb not working with 0.6.0 and onwards (#2279) 2025-03-01 13:09:59 +05:30
Dev Khant 4318663697 Make api_version=v1.1 default and version bump -> 0.1.59 (#2278)
Co-authored-by: Deshraj Yadav <deshrajdry@gmail.com>
2025-03-01 11:36:20 +05:30
Saket Aryan 5606c3ffb8 Update Docs (#2277) 2025-02-28 16:37:05 -08:00
Saket Aryan c1aba35884 Mem0 TS Spec/Docs Update (#2275) 2025-02-28 21:43:51 +05:30
Dev Khant d9b48191de Doc: Update embeddings config page (#2276) 2025-02-28 21:43:00 +05:30
Dev Khant e06f95cea4 fix deprecation warning: qdrant and version bump -> 0.1.58 (#2274) 2025-02-28 16:41:45 +05:30
Dev Khant b131c4bfc4 Update max_token and formatting (#2273) 2025-02-28 15:59:34 +05:30
Wonbin Kim 6acb00731d Add config option for vertex embedding tasks (#2266) 2025-02-28 15:20:05 +05:30
Dev Khant 8143f86be6 Fix proxy pytests (#2272) 2025-02-28 15:05:26 +05:30
Dev-Khant 8d07469ba7 bump version -> 0.1.57 2025-02-28 10:55:12 +05:30
Saket Aryan 434b555a29 Updated docs for typescript package (#2269) 2025-02-27 18:22:28 -08:00
Saket Aryan f8071a753b Update AI SDK Example (#2271) 2025-02-27 18:11:59 -08:00
Saket Aryan d200691e9b Added Mem0 TS Library (#2270) 2025-02-27 15:19:17 -08:00
Dev Khant ecff6315e7 User_id creation for client and formatting (#2264) 2025-02-28 00:00:11 +05:30
Dev Khant ff4510f83d Doc: add param fields in v2 get_all (#2268) 2025-02-27 15:49:57 +05:30
Dev Khant 308e79bb68 Docs: Update v2 GET ALL endpoint (#2267) 2025-02-27 02:11:28 -08:00
Dev-Khant 48176bd194 doc: fix xai tile 2025-02-26 13:56:09 +05:30
Dev Khant 5cebe9ab52 Rename xai.mdx to xAI.mdx 2025-02-26 13:45:32 +05:30
Dev Khant 371848cfbc Doc: fix xai (#2263) 2025-02-26 13:43:38 +05:30
Dev Khant 8e3ed634d1 version bump -> 0.1.56 (#2262) 2025-02-26 13:35:25 +05:30
Dev Khant e9bc4cdc95 Add Grok Support (#2260) 2025-02-26 13:34:01 +05:30
Dev Khant a236aa2315 Doc: fix integrations page (#2261) 2025-02-26 13:18:52 +05:30
Dev Khant 5660fffa96 Doc: update example on quickstart (#2255) 2025-02-26 00:04:38 +05:30
Dev Khant eba6f77330 Doc: update anthropic model (#2254) 2025-02-25 00:59:14 +05:30
Dev Khant b5d00e9b6c Docs: set api_key to env (#2252) 2025-02-24 13:42:39 +05:30
Dev Khant 1be0d70d02 Doc: api_key changes (#2251) 2025-02-24 10:23:28 +05:30
Taranjeet Singh edb53209ef improvement: Update multimodal docs. (#2250) 2025-02-23 16:43:23 -08:00
Taranjeet Singh 7443e58a9d improvement: Update webhook docs. (#2249) 2025-02-23 16:10:21 -08:00
Dev Khant 7f25caba47 version bump -> 0.1.55 (#2248) 2025-02-23 18:07:11 +05:30
Dev Khant c42934b7fb Formatting and Client changes (#2247) 2025-02-23 00:39:26 +05:30
Dev Khant 17887b5959 Docs: Add immutable param to ADD (#2246) 2025-02-22 23:37:30 +05:30
Dev Khant 5d47f4f060 Doc: Update quickstart and Webhook page (#2245) 2025-02-22 01:24:10 +05:30
Dev-Khant 600c9fae63 update webhook js doc 2025-02-21 21:32:54 +05:30
Dev Khant 2d0c8fe94e embedchain: version bump -> 0.1.127 (#2244) 2025-02-21 17:51:47 +05:30
Dev Khant 369d5325f9 version bump -> 0.1.54 (#2243) 2025-02-21 16:03:18 +05:30
Dev Khant 29d63306a4 Webhook API reference and update/delete function change (#2242) 2025-02-21 16:01:53 +05:30
Deshraj Yadav 96628d7791 Update docs for running REST API Server (#2241) 2025-02-21 01:26:57 -08:00
Deshraj Yadav 244fd2231d Add support for Mem0 REST API Server in OSS package (#2240) 2025-02-21 01:05:55 -08:00
Dev Khant 3db028c719 Docs: update webhook (#2238) 2025-02-21 00:48:59 +05:30
Dev Khant c86b1e4d4c Docs: update webhooks (#2237) 2025-02-21 00:42:02 +05:30
Dev Khant 5f5b738745 version bump -> 0.1.53 (#2236) 2025-02-20 23:58:54 +05:30
Dev Khant acaf47ed54 Project_id mandatory for Webhooks (#2232)
Co-authored-by: Deshraj Yadav <deshrajdry@gmail.com>
2025-02-20 23:57:29 +05:30
cola 9734b2db7e delete same vector in retrieved_old_memory (#2201) 2025-02-20 10:10:09 -08:00
Saket Aryan 3fe31e1c31 Fix Build Errors (#2235) 2025-02-20 22:47:15 +05:30
Seetha Rama Guptha f4c0f98fde Adding Native OpenSearch support for Mem0 (#2211) 2025-02-20 11:42:12 +05:30
Dev Khant 6e781f616c Doc: Update Redis config (#2233) 2025-02-20 11:24:00 +05:30
Prateek Chhikara dcba83186a Updated docs (#2231) 2025-02-19 18:37:01 -08:00
Saket Aryan a6d305f8d0 Update Docs for Mem0 AI SDK (#2230) 2025-02-19 14:39:49 -08:00
Lennex Zinyando db512950b9 Docs updates (#2229) 2025-02-19 13:48:48 -08:00
Dev-Khant d4df9f6dfe fix webhook doc 2025-02-20 01:27:26 +05:30
Dev Khant 0e6b20982a Docs: webhook announcement (#2228) 2025-02-19 15:52:13 +05:30
Dev Khant 92e1a9b433 Docs: Update webhook (#2227) 2025-02-19 14:06:46 +05:30
Dev-Khant 3be356a0e9 Webhook doc update 2025-02-19 13:46:00 +05:30
Dev Khant 760cd54ddf Webhook Support (#2225) 2025-02-19 00:04:01 -08:00
Deshraj Yadav 1436da18b1 Update docs (#2222) 2025-02-18 17:52:32 -08:00
Prateek Chhikara cc9acb7493 Added support of vision input 2025-02-18 11:47:13 -08:00
Dev Khant cbee71a63e Proper error msg for API Key validation (#2220) 2025-02-18 23:59:59 +05:30
Dev Khant b052a86424 Update API reference to remove Org/Proj (#2221) 2025-02-18 22:34:58 +05:30
Saket Aryan 95f5fb3ab4 Fix Vercel AI SDK Build Errors (#2219)
Co-authored-by: Dev Khant <devkhant24@gmail.com>
Co-authored-by: Deshraj Yadav <deshraj@gatech.edu>
2025-02-18 16:03:36 +05:30
Dev Khant 04d7f2e48c Fix deprecation warning of output_format for ADD and Version Bump (#2216) 2025-02-18 10:50:56 +05:30
Lennex Zinyando be46f4eb40 [Docs] Docs update (#2199) 2025-02-17 10:30:40 -08:00
Dev Khant f16a580ef6 Fix Azure OpenAI test (#2217) 2025-02-17 19:21:12 +05:30
Dev Khant 095189d39a Update client in README (#2215) 2025-02-17 00:14:23 +05:30
Dev Khant 064d28626b Doc: Update search output (#2208) 2025-02-14 06:34:47 +05:30
Dev Khant cd31c5897a increase timeout and version bump (#2205) 2025-02-14 06:00:40 +05:30
Prateek Chhikara 0bb6137877 updated custom categories docs (#2207) 2025-02-13 11:55:04 -08:00
Saket Aryan 2c63f4d866 Added Typescript Docs and fixed a broken url (#2204) 2025-02-12 09:48:23 -08:00
Prateek Chhikara 3984b90f62 docs update (#2196) 2025-02-06 11:59:18 -08:00
Prateek Chhikara b08b50cbc6 added enhanced search params (#2195) 2025-02-05 12:34:52 -08:00
Dev Khant 90096d6954 Doc: Add config params for Memory() (#2193) 2025-02-05 12:44:41 +05:30
Prateek Chhikara 7581974805 updated docs and resolved some bugs (#2186) 2025-02-01 12:29:46 -08:00
Prateek Chhikara a8fafb9368 updated docs for mem0 architecture diagram (#2185) 2025-02-01 11:43:17 -08:00
Dev Khant 75a4a253f7 Doc: Fix full stack link (#2184) 2025-02-01 10:53:37 +05:30
Dev Khant f9995d144f Update README.md 2025-02-01 00:37:08 +05:30
junmo1215 8d3c8c695d Fix query filter in azure ai search (#2171) 2025-01-31 15:38:06 +05:30
Dev Khant 9f27b88843 Update README.md 2025-01-31 12:00:24 +05:30
Dev Khant d2f0e23dc8 Update README.md 2025-01-31 10:42:41 +05:30
Dev Khant 6e23a6f00e Update README.md 2025-01-30 23:51:28 +05:30
Dev Khant a06c9a99ae Doc changes and Storage fix (#2181) 2025-01-30 10:16:33 -08:00
Dev Khant 63fbd2dc2c Doc: update banner link (#2180) 2025-01-28 12:41:44 +05:30
Dev Khant 203943919b version bump - 0.1.48 (#2174) 2025-01-23 17:47:24 +05:30
Dev Khant 04bbad67ac DeepSeek Integration (#2173) 2025-01-23 17:45:03 +05:30
Dev Khant e1b527b73f Doc: update delete_users (#2169) 2025-01-22 13:28:12 +05:30
Dev Khant 625846caf8 Doc: update delete_users (#2168) 2025-01-22 13:25:13 +05:30
381 changed files with 37564 additions and 3696 deletions
+9 -8
View File
@@ -25,22 +25,23 @@ jobs:
- name: Install dependencies
run: |
cd embedchain
cd mem0
poetry install
- name: Build a binary wheel and a source tarball
run: |
cd embedchain
cd mem0
poetry build
- name: Publish distribution 📦 to Test PyPI
uses: pypa/gh-action-pypi-publish@release/v1
with:
repository_url: https://test.pypi.org/legacy/
packages_dir: embedchain/dist/
# TODO: Needs to setup mem0 repo on Test PyPI
# - name: Publish distribution 📦 to Test PyPI
# uses: pypa/gh-action-pypi-publish@release/v1
# with:
# repository_url: https://test.pypi.org/legacy/
# packages_dir: dist/
- name: Publish distribution 📦 to PyPI
if: startsWith(github.ref, 'refs/tags')
uses: pypa/gh-action-pypi-publish@release/v1
with:
packages_dir: embedchain/dist/
packages_dir: dist/
+2 -2
View File
@@ -52,7 +52,7 @@ jobs:
virtualenvs-in-project: true
- name: Load cached venv
id: cached-poetry-dependencies
uses: actions/cache@v2
uses: actions/cache@v3
with:
path: .venv
key: venv-mem0-${{ runner.os }}-${{ hashFiles('**/poetry.lock') }}
@@ -83,7 +83,7 @@ jobs:
virtualenvs-in-project: true
- name: Load cached venv
id: cached-poetry-dependencies
uses: actions/cache@v2
uses: actions/cache@v3
with:
path: .venv
key: venv-embedchain-${{ runner.os }}-${{ hashFiles('**/poetry.lock') }}
+1
View File
@@ -2,6 +2,7 @@
__pycache__/
*.py[cod]
*$py.class
**/node_modules/
# C extensions
*.so
+2 -2
View File
@@ -12,8 +12,8 @@ install:
install_all:
poetry install
poetry run pip install groq together boto3 litellm ollama chromadb sentence_transformers vertexai \
google-generativeai elasticsearch
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
# Format code with ruff
format:
+93 -132
View File
@@ -16,6 +16,8 @@
<a href="https://mem0.ai">Learn more</a>
·
<a href="https://mem0.dev/DiG">Join Discord</a>
·
<a href="https://mem0.dev/demo">Demo</a>
</p>
</p>
@@ -45,50 +47,25 @@
[Mem0](https://mem0.ai) (pronounced as "mem-zero") enhances AI assistants and agents with an intelligent memory layer, enabling personalized AI interactions. Mem0 remembers user preferences, adapts to individual needs, and continuously improves over time, making it ideal for customer support chatbots, AI assistants, and autonomous systems.
<!-- Start of Selection -->
<p style="display: flex;">
<span style="font-size: 1.2em;">New Feature: Introducing Graph Memory. Check out our <a href="https://docs.mem0.ai/open-source/graph-memory" target="_blank">documentation</a>.</span>
</p>
<!-- End of Selection -->
### Features & Use Cases
Core Capabilities:
- **Multi-Level Memory**: User, Session, and AI Agent memory retention with adaptive personalization
- **Developer-Friendly**: Simple API integration, cross-platform consistency, and hassle-free managed service
### Core Features
- **Multi-Level Memory**: User, Session, and AI Agent memory retention
- **Adaptive Personalization**: Continuous improvement based on interactions
- **Developer-Friendly API**: Simple integration into various applications
- **Cross-Platform Consistency**: Uniform behavior across devices
- **Managed Service**: Hassle-free hosted solution
### How Mem0 works?
Mem0 leverages a hybrid database approach to manage and retrieve long-term memories for AI agents and assistants. Each memory is associated with a unique identifier, such as a user ID or agent ID, allowing Mem0 to organize and access memories specific to an individual or context.
When a message is added to the Mem0 using add() method, the system extracts relevant facts and preferences and stores it across data stores: a vector database, a key-value database, and a graph database. This hybrid approach ensures that different types of information are stored in the most efficient manner, making subsequent searches quick and effective.
When an AI agent or LLM needs to recall memories, it uses the search() method. Mem0 then performs search across these data stores, retrieving relevant information from each source. This information is then passed through a scoring layer, which evaluates their importance based on relevance, importance, and recency. This ensures that only the most personalized and useful context is surfaced.
The retrieved memories can then be appended to the LLM's prompt as needed, enhancing the personalization and relevance of its responses.
### Use Cases
Mem0 empowers organizations and individuals to enhance:
- **AI Assistants and agents**: Seamless conversations with a touch of déjà vu
- **Personalized Learning**: Tailored content recommendations and progress tracking
- **Customer Support**: Context-aware assistance with user preference memory
- **Healthcare**: Patient history and treatment plan management
- **Virtual Companions**: Deeper user relationships through conversation memory
- **Productivity**: Streamlined workflows based on user habits and task history
- **Gaming**: Adaptive environments reflecting player choices and progress
Applications:
- **AI Assistants**: Seamless conversations with context and personalization
- **Learning & Support**: Tailored content recommendations and context-aware customer assistance
- **Healthcare & Companions**: Patient history tracking and deeper relationship building
- **Productivity & Gaming**: Streamlined workflows and adaptive environments based on user behavior
## Get Started
The easiest way to set up Mem0 is through the managed [Mem0 Platform](https://app.mem0.ai). This hosted solution offers automatic updates, advanced analytics, and dedicated support. [Sign up](https://app.mem0.ai) to get started.
Get started quickly with [Mem0 Platform](https://app.mem0.ai) - our fully managed solution that provides automatic updates, advanced analytics, enterprise security, and dedicated support. [Create a free account](https://app.mem0.ai) to begin.
If you prefer to self-host, use the open-source Mem0 package. Follow the [installation instructions](#install) to get started.
For complete control, you can self-host Mem0 using our open-source package. See the [Quickstart guide](#quickstart) below to set up your own instance.
## Installation Instructions <a name="install"></a>
## Quickstart Guide <a name="quickstart"></a>
Install the Mem0 package via pip:
@@ -96,110 +73,108 @@ Install the Mem0 package via pip:
pip install mem0ai
```
Alternatively, you can use Mem0 with one click on the hosted platform [here](https://app.mem0.ai/).
Install the Mem0 package via npm:
```bash
npm install mem0ai
```
### Basic Usage
Mem0 requires an LLM to function, with `gpt-4o` from OpenAI as the default. However, it supports a variety of LLMs; for details, refer to our [Supported LLMs documentation](https://docs.mem0.ai/llms).
Mem0 requires an LLM to function, with `gpt-4o-mini` from OpenAI as the default. However, it supports a variety of LLMs; for details, refer to our [Supported LLMs documentation](https://docs.mem0.ai/llms).
First step is to instantiate the memory:
```python
from openai import OpenAI
from mem0 import Memory
m = Memory()
openai_client = OpenAI()
memory = Memory()
def chat_with_memories(message: str, user_id: str = "default_user") -> str:
# Retrieve relevant memories
relevant_memories = memory.search(query=message, user_id=user_id, limit=3)
memories_str = "\n".join(f"- {entry['memory']}" for entry in relevant_memories["results"])
# Generate Assistant response
system_prompt = f"You are a helpful AI. Answer the question based on query and memories.\nUser Memories:\n{memories_str}"
messages = [{"role": "system", "content": system_prompt}, {"role": "user", "content": message}]
response = openai_client.chat.completions.create(model="gpt-4o-mini", messages=messages)
assistant_response = response.choices[0].message.content
# Create new memories from the conversation
messages.append({"role": "assistant", "content": assistant_response})
memory.add(messages, user_id=user_id)
return assistant_response
def main():
print("Chat with AI (type 'exit' to quit)")
while True:
user_input = input("You: ").strip()
if user_input.lower() == 'exit':
print("Goodbye!")
break
print(f"AI: {chat_with_memories(user_input)}")
if __name__ == "__main__":
main()
```
<details>
<summary>How to set OPENAI_API_KEY</summary>
See the example for [Node.js](https://docs.mem0.ai/examples/ai_companion_js).
```python
import os
os.environ["OPENAI_API_KEY"] = "sk-xxx"
```
</details>
You can perform the following task on the memory:
1. Add: Store a memory from any unstructured text
2. Update: Update memory of a given memory_id
3. Search: Fetch memories based on a query
4. Get: Return memories for a certain user/agent/session
5. History: Describe how a memory has changed over time for a specific memory ID
```python
# 1. Add: Store a memory from any unstructured text
result = m.add("I am working on improving my tennis skills. Suggest some online courses.", user_id="alice", metadata={"category": "hobbies"})
# Created memory --> 'Improving her tennis skills.' and 'Looking for online suggestions.'
```
```python
# 2. Update: update the memory
result = m.update(memory_id=<memory_id_1>, data="Likes to play tennis on weekends")
# Updated memory --> 'Likes to play tennis on weekends.' and 'Looking for online suggestions.'
```
```python
# 3. Search: search related memories
related_memories = m.search(query="What are Alice's hobbies?", user_id="alice")
# Retrieved memory --> 'Likes to play tennis on weekends'
```
```python
# 4. Get all memories
all_memories = m.get_all()
memory_id = all_memories["memories"][0] ["id"] # get a memory_id
# All memory items --> 'Likes to play tennis on weekends.' and 'Looking for online suggestions.'
```
```python
# 5. Get memory history for a particular memory_id
history = m.history(memory_id=<memory_id_1>)
# Logs corresponding to memory_id_1 --> {'prev_value': 'Working on improving tennis skills and interested in online courses for tennis.', 'new_value': 'Likes to play tennis on weekends' }
```
For more advanced usage and API documentation, visit our [documentation](https://docs.mem0.ai).
> [!TIP]
> If you prefer a hosted version without the need to set up infrastructure yourself, check out the [Mem0 Platform](https://app.mem0.ai/) to get started in minutes.
> For a hassle-free experience, try our [hosted platform](https://app.mem0.ai) with automatic updates and enterprise features.
## Demos
- Mem0 - ChatGPT with Memory: A personalized AI chat app powered by Mem0 that remembers your preferences, facts, and memories.
[Mem0 - ChatGPT with Memory](https://github.com/user-attachments/assets/cebc4f8e-bdb9-4837-868d-13c5ab7bb433)
Try live [demo](https://mem0.dev/demo/)
<br/><br/>
- AI Companion: Experience personalized conversations with an AI that remembers your preferences and past interactions
[AI Companion Demo](https://github.com/user-attachments/assets/3fc72023-a72c-4593-8be0-3cee3ba744da)
<br/><br/>
- Enhance your AI interactions by storing memories across ChatGPT, Perplexity, and Claude using our browser extension. Get [chrome extension](https://chromewebstore.google.com/detail/mem0/onihkkbipkfeijkadecaafbgagkhglop?hl=en).
### Graph Memory
To initialize Graph Memory you'll need to set up your configuration with graph store providers.
Currently, we support Neo4j as a graph store provider. You can setup [Neo4j](https://neo4j.com/) locally or use the hosted [Neo4j AuraDB](https://neo4j.com/product/auradb/).
Moreover, you also need to set the version to `v1.1` (*prior versions are not supported*).
Here's how you can do it:
[Chrome Extension Demo](https://github.com/user-attachments/assets/ca92e40b-c453-4ff6-b25e-739fb18a8650)
```python
from mem0 import Memory
<br/><br/>
config = {
"graph_store": {
"provider": "neo4j",
"config": {
"url": "neo4j+s://xxx",
"username": "neo4j",
"password": "xxx"
}
},
"version": "v1.1"
}
- Customer support bot using <strong>Langgraph and Mem0</strong>. Get the complete code from [here](https://docs.mem0.ai/integrations/langgraph)
[Langgraph: Customer Bot](https://github.com/user-attachments/assets/ca6b482e-7f46-42c8-aa08-f88d1d93a5f4)
<br/><br/>
- Use Mem0 with CrewAI to get personalized results. Full example [here](https://docs.mem0.ai/integrations/crewai)
[CrewAI Demo](https://github.com/user-attachments/assets/69172a79-ccb9-4340-91f1-caa7d2dd4213)
m = Memory.from_config(config_dict=config)
```
## Documentation
For detailed usage instructions and API reference, visit our documentation at [docs.mem0.ai](https://docs.mem0.ai). Here, you can find more information on both the open-source version and the hosted [Mem0 Platform](https://app.mem0.ai).
## Star History
[![Star History Chart](https://api.star-history.com/svg?repos=mem0ai/mem0&type=Date)](https://star-history.com/#mem0ai/mem0&Date)
For detailed usage instructions and API reference, visit our [documentation](https://docs.mem0.ai). You'll find:
- Complete API reference
- Integration guides
- Advanced configuration options
- Best practices and examples
- More details about:
- Open-source version
- [Hosted Mem0 Platform](https://app.mem0.ai)
## Support
@@ -209,20 +184,6 @@ Join our community for support and discussions. If you have any questions, feel
- [Follow us on Twitter](https://x.com/mem0ai)
- [Email founders](mailto:founders@mem0.ai)
## Contributors
Join our [Discord community](https://mem0.dev/DiG) to learn about memory management for AI agents and LLMs, and connect with Mem0 users and contributors. Share your ideas, questions, or feedback in our [GitHub Issues](https://github.com/mem0ai/mem0/issues).
We value and appreciate the contributions of our community. Special thanks to our contributors for helping us improve Mem0.
<a href="https://github.com/mem0ai/mem0/graphs/contributors">
<img src="https://contrib.rocks/image?repo=mem0ai/mem0" />
</a>
## Anonymous Telemetry
We collect anonymous usage metrics to enhance our package's quality and user experience. This includes data like feature usage frequency and system info, but never personal details. The data helps us prioritize improvements and ensure compatibility. If you wish to opt-out, set the environment variable MEM0_TELEMETRY=false. We prioritize data security and don't share this data externally.
## License
This project is licensed under the Apache 2.0 License - see the [LICENSE](LICENSE) file for details.
+4
View File
@@ -0,0 +1,4 @@
---
title: 'Feedback'
openapi: post /v1/feedback/
---
@@ -1,4 +1,4 @@
---
title: 'V1 Get Memories'
title: 'Get Memories (v1 - Deprecated)'
openapi: get /v1/memories/
---
@@ -1,4 +1,4 @@
---
title: 'V1 Search Memories'
title: 'Search Memories (v1 - Deprecated)'
openapi: post /v1/memories/search/
---
---
+36 -67
View File
@@ -1,74 +1,43 @@
---
title: 'V2 Get Memories'
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:
- `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
Mem0 offers two versions of the get memories API: v1 and v2. Here's how they differ:
<CodeGroup>
```python Code
memories = m.get_all(
filters={
"AND": [
{
"user_id": "alex"
},
{
"created_at": {"gte": "2024-07-01", "lte": "2024-07-31"}
}
]
},
version="v2"
)
```
<Tabs>
<Tab title="v1 Get Memories">
<CodeGroup>
```python Code
memories = m.get_all(user_id="alex")
```
```json Output
[
{
"id":"f38b689d-6b24-45b7-bced-17fbb4d8bac7",
"memory":"travelling to Paris",
"user_id":"alex",
"hash":"62bc074f56d1f909f1b4c2b639f56f6a",
"metadata":null,
"created_at":"2023-02-25T23:57:00.108347-07:00",
"updated_at":"2024-07-25T23:57:00.108367-07:00"
}
```json Output
[
{
"id":"f38b689d-6b24-45b7-bced-17fbb4d8bac7",
"memory":"Name: Alex. Vegetarian. Allergic to nuts.",
"user_id":"alex",
"hash":"62bc074f56d1f909f1b4c2b639f56f6a",
"metadata":null,
"created_at":"2024-07-25T23:57:00.108347-07:00",
"updated_at":"2024-07-25T23:57:00.108367-07:00"
}
]
```
</CodeGroup>
</Tab>
<Tab title="v2 Get Memories">
<CodeGroup>
```python Code
memories = m.get_all(
filters={
"AND": [
{
"user_id": "alex"
},
{
"created_at": {
"gte": "2024-07-01",
"lte": "2024-07-31"
}
}
]
},
version="v2"
)
```
```json Output
[
{
"id":"f38b689d-6b24-45b7-bced-17fbb4d8bac7",
"memory":"Name: Alex. Vegetarian. Allergic to nuts.",
"user_id":"alex",
"hash":"62bc074f56d1f909f1b4c2b639f56f6a",
"metadata":null,
"created_at":"2024-07-25T23:57:00.108347-07:00",
"updated_at":"2024-07-25T23:57:00.108367-07:00"
}
]
```
</CodeGroup>
</Tab>
</Tabs>
Key difference between v1 and v2 get memories:
• **Filters**: v2 allows you to apply filters to narrow down memory retrieval based on specific criteria. This includes support for complex logical operations (AND, OR) and comparison operators (IN, gte, lte, gt, lt, ne, icontains) for advanced filtering capabilities.
The v2 get memories API is more powerful and flexible, allowing for more precise memory retrieval without the need for a search query.
```
</CodeGroup>
@@ -1,85 +1,51 @@
---
title: 'V2 Search Memories'
title: 'Search Memories (v2)'
openapi: post /v2/memories/search/
---
Mem0 offers two versions of the search API: v1 and v2. Here's how they differ:
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:
- `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
<Tabs>
<Tab title="v1 Search">
<CodeGroup>
```python Code
related_memories = m.search(query="What are Alice's hobbies?", user_id="alice")
```
<CodeGroup>
```python Code
related_memories = m.vsearch(
query="What are Alice's hobbies?",
version="v2",
filters={
"AND": [
{
"user_id": "alice"
},
{
"agent_id": {"in": ["travel-agent", "sports-agent"]}
}
]
},
)
```
```json Output
[
{
"id":"ea925981-272f-40dd-b576-be64e4871429",
"memory":"Likes to play cricket and plays cricket on weekends.",
"hash":"c8809002-25c1-4c97-a3a2-227ce9c20c53",
"metadata":{
"category":"hobbies"
},
"score":0.32116443111457704,
"created_at":"2024-07-26T10:29:36.630547-07:00",
"updated_at":"None",
"user_id":"alice"
}
]
```
</CodeGroup>
</Tab>
<Tab title="v2 Search">
<CodeGroup>
```python Code
related_memories = m.vsearch(
query="What are Alice's hobbies?",
filters={
"AND":[
{
"user_id":"alice"
},
{
"agent_id":{
"in":[
"travelling",
"sports"
]
}
}
]
},
version="v2"
)
```
```json Output
{
"memories": [
{
"id": "ea925981-272f-40dd-b576-be64e4871429",
"memory": "Likes to play cricket and plays cricket on weekends.",
"hash": "c8809002-25c1-4c97-a3a2-227ce9c20c53",
"metadata": {
"category": "hobbies"
},
"score": 0.32116443111457704,
"created_at": "2024-07-26T10:29:36.630547-07:00",
"updated_at": null,
"user_id": "alice",
"agent_id": "sports"
}
],
}
```
</CodeGroup>
</Tab>
</Tabs>
Key difference between v1 and v2 search:
• **Filters**: v2 allows you to apply filters to narrow down search results based on specific criteria. This includes support for complex logical operations (AND, OR) and comparison operators (IN, gte, lte, gt, lt, ne, icontains) for advanced filtering capabilities.
The v2 search API is more powerful and flexible, allowing for more precise memory retrieval.
```json Output
{
"memories": [
{
"id": "ea925981-272f-40dd-b576-be64e4871429",
"memory": "Likes to play cricket and plays cricket on weekends.",
"metadata": {
"category": "hobbies"
},
"score": 0.32116443111457704,
"created_at": "2024-07-26T10:29:36.630547-07:00",
"updated_at": null,
"user_id": "alice",
"agent_id": "sports-agent"
}
],
}
```
</CodeGroup>
+15 -15
View File
@@ -1,4 +1,8 @@
# Mem0 API Overview
---
title: Overview
icon: "info"
iconType: "solid"
---
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.
@@ -34,30 +38,26 @@ Organizations and projects provide the following capabilities:
Example with the mem0 Python package:
<Tabs>
<Tab title="Python">
```python
from mem0 import MemoryClient
# Recommended: Using organization and project IDs
client = MemoryClient(
org_id='YOUR_ORG_ID', # It can be found on the organization settings page in dashboard
project_id='YOUR_PROJECT_ID',
)
client = MemoryClient(org_id='YOUR_ORG_ID', project_id='YOUR_PROJECT_ID')
```
> **Note**: The use of `organization` and `project` parameters is deprecated and will be removed in version `0.1.40`. Please use `org_id` and `project_id` instead.
</Tab>
Example with the mem0 Node.js package:
<Tab title="Node.js">
```javascript
import { MemoryClient } from "mem0ai";
# Recommended: Using organization and project IDs
const client = new MemoryClient({
organizationId: "YOUR_ORG_ID",
projectId: "YOUR_PROJECT_ID"
});
const client = new MemoryClient({organizationId: "YOUR_ORG_ID", projectId: "YOUR_PROJECT_ID"});
```
</Tab>
</Tabs>
## Getting Started
To begin using the Mem0 API, you'll need to:
@@ -0,0 +1,9 @@
---
title: 'Create Webhook'
openapi: post /api/v1/webhooks/projects/{project_id}/
---
## Create Webhook
Create a webhook by providing the project ID and the webhook details.
@@ -0,0 +1,8 @@
---
title: 'Delete Webhook'
openapi: delete /api/v1/webhooks/{webhook_id}/
---
## Delete Webhook
Delete a webhook by providing the webhook ID.
@@ -0,0 +1,9 @@
---
title: 'Get Webhook'
openapi: get /api/v1/webhooks/projects/{project_id}/
---
## Get Webhook
Get a webhook by providing the project ID.
@@ -0,0 +1,9 @@
---
title: 'Update Webhook'
openapi: put /api/v1/webhooks/{webhook_id}/
---
## Update Webhook
Update a webhook by providing the webhook ID and the fields to update.
+56 -17
View File
@@ -1,19 +1,25 @@
## What is Config?
---
title: Configurations
icon: "gear"
iconType: "solid"
---
Config in mem0 is a dictionary that specifies the settings for your embedding models. It allows you to customize the behavior and connection details of your chosen embedder.
## How to Define Config
## How to define configurations?
The config is defined as a Python dictionary with two main keys:
The config is defined as an object (or dictionary) with two main keys:
- `embedder`: Specifies the embedder provider and its configuration
- `provider`: The name of the embedder (e.g., "openai", "ollama")
- `config`: A nested dictionary containing provider-specific settings
- `config`: A nested object or dictionary containing provider-specific settings
## How to Use Config
## How to use configurations?
Here's a general example of how to use the config with mem0:
```python
<CodeGroup>
```python Python
import os
from mem0 import Memory
@@ -32,6 +38,25 @@ m = Memory.from_config(config)
m.add("Your text here", user_id="user", metadata={"category": "example"})
```
```typescript TypeScript
import { Memory } from 'mem0ai/oss';
const config = {
embedder: {
provider: 'openai',
config: {
apiKey: process.env.OPENAI_API_KEY || '',
model: 'text-embedding-3-small',
// Provider-specific settings go here
},
},
};
const memory = new Memory(config);
await memory.add("Your text here", { userId: "user", metadata: { category: "example" } });
```
</CodeGroup>
## Why is Config Needed?
Config is essential for:
@@ -43,18 +68,32 @@ Config is essential for:
Here's a comprehensive list of all parameters that can be used across different embedders:
| Parameter | Description |
|-----------|-------------|
| `model` | Embedding model to use |
| `api_key` | API key of the provider |
| `embedding_dims` | Dimensions of the embedding model |
| `http_client_proxies` | Allow proxy server settings |
| `ollama_base_url` | Base URL for the Ollama embedding model |
| `model_kwargs` | Key-Value arguments for the Huggingface embedding model |
| `azure_kwargs` | Key-Value arguments for the AzureOpenAI embedding model |
<Tabs>
<Tab title="Python">
| Parameter | Description | Provider |
|-----------|-------------|----------|
| `model` | Embedding model to use | All |
| `api_key` | API key of the provider | All |
| `embedding_dims` | Dimensions of the embedding model | All |
| `http_client_proxies` | Allow proxy server settings | All |
| `ollama_base_url` | Base URL for the Ollama embedding model | Ollama |
| `model_kwargs` | Key-Value arguments for the Huggingface embedding model | Huggingface |
| `azure_kwargs` | Key-Value arguments for the AzureOpenAI embedding model | Azure OpenAI |
| `openai_base_url` | Base URL for OpenAI API | OpenAI |
| `vertex_credentials_json` | Path to the Google Cloud credentials JSON file for VertexAI |
| `vertex_credentials_json` | Path to the Google Cloud credentials JSON file for VertexAI | VertexAI |
| `memory_add_embedding_type` | The type of embedding to use for the add memory action | VertexAI |
| `memory_update_embedding_type` | The type of embedding to use for the update memory action | VertexAI |
| `memory_search_embedding_type` | The type of embedding to use for the search memory action | VertexAI |
| `lmstudio_base_url` | Base URL for LM Studio API | LM Studio |
</Tab>
<Tab title="TypeScript">
| Parameter | Description | Provider |
|-----------|-------------|----------|
| `model` | Embedding model to use | All |
| `apiKey` | API key of the provider | All |
| `embeddingDims` | Dimensions of the embedding model | All |
</Tab>
</Tabs>
## Supported Embedding Models
@@ -37,7 +37,13 @@ config = {
}
m = Memory.from_config(config)
m.add("I'm visiting Paris", user_id="john")
messages = [
{"role": "user", "content": "I'm planning to watch a movie tonight. Any recommendations?"},
{"role": "assistant", "content": "How about a thriller movies? They can be quite engaging."},
{"role": "user", "content": "I’m not a big fan of thriller movies but I love sci-fi movies."},
{"role": "assistant", "content": "Got it! I'll avoid thriller recommendations and suggest sci-fi movies in the future."}
]
m.add(messages, user_id="john")
```
### Config
+7 -1
View File
@@ -23,7 +23,13 @@ config = {
}
m = Memory.from_config(config)
m.add("I'm visiting Paris", user_id="john")
messages = [
{"role": "user", "content": "I'm planning to watch a movie tonight. Any recommendations?"},
{"role": "assistant", "content": "How about a thriller movies? They can be quite engaging."},
{"role": "user", "content": "I’m not a big fan of thriller movies but I love sci-fi movies."},
{"role": "assistant", "content": "Got it! I'll avoid thriller recommendations and suggest sci-fi movies in the future."}
]
m.add(messages, user_id="john")
```
### Config
@@ -22,7 +22,13 @@ config = {
}
m = Memory.from_config(config)
m.add("I'm visiting Paris", user_id="john")
messages = [
{"role": "user", "content": "I'm planning to watch a movie tonight. Any recommendations?"},
{"role": "assistant", "content": "How about a thriller movies? They can be quite engaging."},
{"role": "user", "content": "I’m not a big fan of thriller movies but I love sci-fi movies."},
{"role": "assistant", "content": "Got it! I'll avoid thriller recommendations and suggest sci-fi movies in the future."}
]
m.add(messages, user_id="john")
```
### Config
@@ -0,0 +1,38 @@
You can use embedding models from LM Studio to run Mem0 locally.
### Usage
```python
import os
from mem0 import Memory
os.environ["OPENAI_API_KEY"] = "your_api_key" # For LLM
config = {
"embedder": {
"provider": "lmstudio",
"config": {
"model": "nomic-embed-text-v1.5-GGUF/nomic-embed-text-v1.5.f16.gguf"
}
}
}
m = Memory.from_config(config)
messages = [
{"role": "user", "content": "I'm planning to watch a movie tonight. Any recommendations?"},
{"role": "assistant", "content": "How about a thriller movies? They can be quite engaging."},
{"role": "user", "content": "I’m not a big fan of thriller movies but I love sci-fi movies."},
{"role": "assistant", "content": "Got it! I'll avoid thriller recommendations and suggest sci-fi movies in the future."}
]
m.add(messages, user_id="john")
```
### Config
Here are the parameters available for configuring Ollama embedder:
| Parameter | Description | Default Value |
| --- | --- | --- |
| `model` | The name of the OpenAI model to use | `nomic-embed-text-v1.5-GGUF/nomic-embed-text-v1.5.f16.gguf` |
| `embedding_dims` | Dimensions of the embedding model | `1536` |
| `lmstudio_base_url` | Base URL for LM Studio connection | `http://localhost:1234/v1` |
+7 -1
View File
@@ -18,7 +18,13 @@ config = {
}
m = Memory.from_config(config)
m.add("I'm visiting Paris", user_id="john")
messages = [
{"role": "user", "content": "I'm planning to watch a movie tonight. Any recommendations?"},
{"role": "assistant", "content": "How about a thriller movies? They can be quite engaging."},
{"role": "user", "content": "I’m not a big fan of thriller movies but I love sci-fi movies."},
{"role": "assistant", "content": "Got it! I'll avoid thriller recommendations and suggest sci-fi movies in the future."}
]
m.add(messages, user_id="john")
```
### Config
+38 -2
View File
@@ -6,7 +6,8 @@ To use OpenAI embedding models, set the `OPENAI_API_KEY` environment variable. Y
### Usage
```python
<CodeGroup>
```python Python
import os
from mem0 import Memory
@@ -22,15 +23,50 @@ config = {
}
m = Memory.from_config(config)
m.add("I'm visiting Paris", user_id="john")
messages = [
{"role": "user", "content": "I'm planning to watch a movie tonight. Any recommendations?"},
{"role": "assistant", "content": "How about a thriller movies? They can be quite engaging."},
{"role": "user", "content": "I’m not a big fan of thriller movies but I love sci-fi movies."},
{"role": "assistant", "content": "Got it! I'll avoid thriller recommendations and suggest sci-fi movies in the future."}
]
m.add(messages, user_id="john")
```
```typescript TypeScript
import { Memory } from 'mem0ai/oss';
const config = {
embedder: {
provider: 'openai',
config: {
apiKey: 'your-openai-api-key',
model: 'text-embedding-3-large',
},
},
};
const memory = new Memory(config);
await memory.add("I'm visiting Paris", { userId: "john" });
```
</CodeGroup>
### Config
Here are the parameters available for configuring OpenAI embedder:
<Tabs>
<Tab title="Python">
| Parameter | Description | Default Value |
| --- | --- | --- |
| `model` | The name of the embedding model to use | `text-embedding-3-small` |
| `embedding_dims` | Dimensions of the embedding model | `1536` |
| `api_key` | The OpenAI API key | `None` |
</Tab>
<Tab title="TypeScript">
| Parameter | Description | Default Value |
| --- | --- | --- |
| `model` | The name of the embedding model to use | `text-embedding-3-small` |
| `embeddingDims` | Dimensions of the embedding model | `1536` |
| `apiKey` | The OpenAI API key | `None` |
</Tab>
</Tabs>
@@ -25,7 +25,13 @@ config = {
}
m = Memory.from_config(config)
m.add("I'm visiting Paris", user_id="john")
messages = [
{"role": "user", "content": "I'm planning to watch a movie tonight. Any recommendations?"},
{"role": "assistant", "content": "How about a thriller movies? They can be quite engaging."},
{"role": "user", "content": "I’m not a big fan of thriller movies but I love sci-fi movies."},
{"role": "assistant", "content": "Got it! I'll avoid thriller recommendations and suggest sci-fi movies in the future."}
]
m.add(messages, user_id="john")
```
### Config
+22 -3
View File
@@ -16,15 +16,31 @@ config = {
"embedder": {
"provider": "vertexai",
"config": {
"model": "text-embedding-004"
"model": "text-embedding-004",
"memory_add_embedding_type": "RETRIEVAL_DOCUMENT",
"memory_update_embedding_type": "RETRIEVAL_DOCUMENT",
"memory_search_embedding_type": "RETRIEVAL_QUERY"
}
}
}
m = Memory.from_config(config)
m.add("I'm visiting Paris", user_id="john")
messages = [
{"role": "user", "content": "I'm planning to watch a movie tonight. Any recommendations?"},
{"role": "assistant", "content": "How about a thriller movies? They can be quite engaging."},
{"role": "user", "content": "I’m not a big fan of thriller movies but I love sci-fi movies."},
{"role": "assistant", "content": "Got it! I'll avoid thriller recommendations and suggest sci-fi movies in the future."}
]
m.add(messages, user_id="john")
```
The embedding types can be one of the following:
- SEMANTIC_SIMILARITY
- CLASSIFICATION
- CLUSTERING
- RETRIEVAL_DOCUMENT, RETRIEVAL_QUERY, QUESTION_ANSWERING, FACT_VERIFICATION
- CODE_RETRIEVAL_QUERY
Check out the [Vertex AI documentation](https://cloud.google.com/vertex-ai/generative-ai/docs/embeddings/task-types#supported_task_types) for more information.
### Config
Here are the parameters available for configuring the Vertex AI embedder:
@@ -34,3 +50,6 @@ Here are the parameters available for configuring the Vertex AI embedder:
| `model` | The name of the Vertex AI embedding model to use | `text-embedding-004` |
| `vertex_credentials_json` | Path to the Google Cloud credentials JSON file | `None` |
| `embedding_dims` | Dimensions of the embedding model | `256` |
| `memory_add_embedding_type` | The type of embedding to use for the add memory action | `RETRIEVAL_DOCUMENT` |
| `memory_update_embedding_type` | The type of embedding to use for the update memory action | `RETRIEVAL_DOCUMENT` |
| `memory_search_embedding_type` | The type of embedding to use for the search memory action | `RETRIEVAL_QUERY` |
+7
View File
@@ -1,5 +1,7 @@
---
title: Overview
icon: "info"
iconType: "solid"
---
Mem0 offers support for various embedding models, allowing users to choose the one that best suits their needs.
@@ -8,6 +10,10 @@ Mem0 offers support for various embedding models, allowing users to choose the o
See the list of supported embedders below.
<Note>
The following embedders are supported in the Python implementation. The TypeScript implementation currently only supports OpenAI.
</Note>
<CardGroup cols={4}>
<Card title="OpenAI" href="/components/embedders/models/openai"></Card>
<Card title="Azure OpenAI" href="/components/embedders/models/azure_openai"></Card>
@@ -16,6 +22,7 @@ See the list of supported embedders below.
<Card title="Gemini" href="/components/embedders/models/gemini"></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>
</CardGroup>
## Usage
+85 -36
View File
@@ -1,29 +1,45 @@
## What is Config?
---
title: Configurations
icon: "gear"
iconType: "solid"
---
Config in mem0 is a dictionary that specifies the settings for your llms. It allows you to customize the behavior and connection details of your chosen llm.
## How to define configurations?
## How to Define Config
The config is defined as a Python dictionary with two main keys:
- `llm`: Specifies the llm provider and its configuration
- `provider`: The name of the llm (e.g., "openai", "groq")
- `config`: A nested dictionary containing provider-specific settings
<Tabs>
<Tab title="Python">
The `config` is defined as a Python dictionary with two main keys:
- `llm`: Specifies the llm provider and its configuration
- `provider`: The name of the llm (e.g., "openai", "groq")
- `config`: A nested dictionary containing provider-specific settings
</Tab>
<Tab title="TypeScript">
The `config` is defined as a TypeScript object with these keys:
- `llm`: Specifies the LLM provider and its configuration (required)
- `provider`: The name of the LLM (e.g., "openai", "groq")
- `config`: A nested object containing provider-specific settings
- `embedder`: Specifies the embedder provider and its configuration (optional)
- `vectorStore`: Specifies the vector store provider and its configuration (optional)
- `historyDbPath`: Path to the history database file (optional)
</Tab>
</Tabs>
### Config Values Precedence
Config values are applied in the following order of precedence (from highest to lowest):
1. Values explicitly set in the `config` dictionary
1. Values explicitly set in the `config` object/dictionary
2. Environment variables (e.g., `OPENAI_API_KEY`, `OPENAI_API_BASE`)
3. Default values defined in the LLM implementation
This means that values specified in the `config` dictionary will override corresponding environment variables, which in turn override default values.
This means that values specified in the `config` will override corresponding environment variables, which in turn override default values.
## How to Use Config
Here's a general example of how to use the config with mem0:
Here's a general example of how to use the config with Mem0:
```python
<CodeGroup>
```python Python
import os
from mem0 import Memory
@@ -42,38 +58,71 @@ m = Memory.from_config(config)
m.add("Your text here", user_id="user", metadata={"category": "example"})
```
```typescript TypeScript
import { Memory } from 'mem0ai/oss';
// Minimal configuration with just the LLM settings
const config = {
llm: {
provider: 'your_chosen_provider',
config: {
// Provider-specific settings go here
}
}
};
const memory = new Memory(config);
await memory.add("Your text here", { userId: "user123", metadata: { category: "example" } });
```
</CodeGroup>
## Why is Config Needed?
Config is essential for:
1. Specifying which llm to use.
1. Specifying which LLM to use.
2. Providing necessary connection details (e.g., model, api_key, temperature).
3. Ensuring proper initialization and connection to your chosen llm.
3. Ensuring proper initialization and connection to your chosen LLM.
## Master List of All Params in Config
Here's a comprehensive list of all parameters that can be used across different llms:
Here's the table based on the provided parameters:
| Parameter | Description | Provider |
|----------------------|-----------------------------------------------|-------------------|
| `model` | Embedding model to use | All |
| `temperature` | Temperature of the model | All |
| `api_key` | API key to use | All |
| `max_tokens` | Tokens to generate | All |
| `top_p` | Probability threshold for nucleus sampling | All |
| `top_k` | Number of highest probability tokens to keep | All |
| `http_client_proxies`| Allow proxy server settings | AzureOpenAI |
| `models` | List of models | Openrouter |
| `route` | Routing strategy | Openrouter |
| `openrouter_base_url`| Base URL for Openrouter API | Openrouter |
| `site_url` | Site URL | Openrouter |
| `app_name` | Application name | Openrouter |
| `ollama_base_url` | Base URL for Ollama API | Ollama |
| `openai_base_url` | Base URL for OpenAI API | OpenAI |
| `azure_kwargs` | Azure LLM args for initialization | AzureOpenAI |
Here's a comprehensive list of all parameters that can be used across different LLMs:
<Tabs>
<Tab title="Python">
| Parameter | Description | Provider |
|----------------------|-----------------------------------------------|-------------------|
| `model` | Embedding model to use | All |
| `temperature` | Temperature of the model | All |
| `api_key` | API key to use | All |
| `max_tokens` | Tokens to generate | All |
| `top_p` | Probability threshold for nucleus sampling | All |
| `top_k` | Number of highest probability tokens to keep | All |
| `http_client_proxies`| Allow proxy server settings | AzureOpenAI |
| `models` | List of models | Openrouter |
| `route` | Routing strategy | Openrouter |
| `openrouter_base_url`| Base URL for Openrouter API | Openrouter |
| `site_url` | Site URL | Openrouter |
| `app_name` | Application name | Openrouter |
| `ollama_base_url` | Base URL for Ollama API | Ollama |
| `openai_base_url` | Base URL for OpenAI API | OpenAI |
| `azure_kwargs` | Azure LLM args for initialization | AzureOpenAI |
| `deepseek_base_url` | Base URL for DeepSeek API | DeepSeek |
| `xai_base_url` | Base URL for XAI API | XAI |
| `lmstudio_base_url` | Base URL for LM Studio API | LM Studio |
</Tab>
<Tab title="TypeScript">
| Parameter | Description | Provider |
|----------------------|-----------------------------------------------|-------------------|
| `model` | Embedding model to use | All |
| `temperature` | Temperature of the model | All |
| `apiKey` | API key to use | All |
| `maxTokens` | Tokens to generate | All |
| `topP` | Probability threshold for nucleus sampling | All |
| `topK` | Number of highest probability tokens to keep | All |
| `openaiBaseUrl` | Base URL for OpenAI API | OpenAI |
</Tab>
</Tabs>
## Supported LLMs
For detailed information on configuring specific llms, please visit the [LLMs](./models) section. There you'll find information for each supported llm with provider-specific usage examples and configuration details.
For detailed information on configuring specific LLMs, please visit the [LLMs](./models) section. There you'll find information for each supported LLM with provider-specific usage examples and configuration details.
+40 -3
View File
@@ -1,8 +1,13 @@
---
title: Anthropic
---
To use anthropic's models, please set the `ANTHROPIC_API_KEY` which you find on their [Account Settings Page](https://console.anthropic.com/account/keys).
## Usage
```python
<CodeGroup>
```python Python
import os
from mem0 import Memory
@@ -13,7 +18,7 @@ config = {
"llm": {
"provider": "anthropic",
"config": {
"model": "claude-3-5-sonnet-latest",
"model": "claude-3-7-sonnet-latest",
"temperature": 0.1,
"max_tokens": 2000,
}
@@ -21,9 +26,41 @@ config = {
}
m = Memory.from_config(config)
m.add("Likes to play cricket on weekends", user_id="alice", metadata={"category": "hobbies"})
messages = [
{"role": "user", "content": "I'm planning to watch a movie tonight. Any recommendations?"},
{"role": "assistant", "content": "How about a thriller movies? They can be quite engaging."},
{"role": "user", "content": "I’m not a big fan of thriller movies but I love sci-fi movies."},
{"role": "assistant", "content": "Got it! I'll avoid thriller recommendations and suggest sci-fi movies in the future."}
]
m.add(messages, user_id="alice", metadata={"category": "movies"})
```
```typescript TypeScript
import { Memory } from 'mem0ai/oss';
const config = {
llm: {
provider: 'anthropic',
config: {
apiKey: process.env.ANTHROPIC_API_KEY || '',
model: 'claude-3-7-sonnet-latest',
temperature: 0.1,
maxTokens: 2000,
},
},
};
const memory = new Memory(config);
const messages = [
{"role": "user", "content": "I'm planning to watch a movie tonight. Any recommendations?"},
{"role": "assistant", "content": "How about a thriller movies? They can be quite engaging."},
{"role": "user", "content": "I’m not a big fan of thriller movies but I love sci-fi movies."},
{"role": "assistant", "content": "Got it! I'll avoid thriller recommendations and suggest sci-fi movies in the future."}
]
await memory.add(messages, { userId: "alice", metadata: { category: "movies" } });
```
</CodeGroup>
## Config
All available parameters for the `anthropic` config are present in [Master List of All Params in Config](../config).
+8 -2
View File
@@ -24,13 +24,19 @@ config = {
"config": {
"model": "arn:aws:bedrock:us-east-1:123456789012:model/your-model-name",
"temperature": 0.2,
"max_tokens": 1500,
"max_tokens": 2000,
}
}
}
m = Memory.from_config(config)
m.add("Likes to play cricket on weekends", user_id="alice", metadata={"category": "hobbies"})
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
+10 -1
View File
@@ -4,6 +4,9 @@ title: Azure OpenAI
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/).
> **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
```python
@@ -36,7 +39,13 @@ config = {
}
m = Memory.from_config(config)
m.add("Likes to play cricket on weekends", user_id="alice", metadata={"category": "hobbies"})
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"})
```
We also support the new [OpenAI structured-outputs](https://platform.openai.com/docs/guides/structured-outputs/introduction) model.
+55
View File
@@ -0,0 +1,55 @@
---
title: DeepSeek
---
To use DeepSeek LLM models, you have to set the `DEEPSEEK_API_KEY` environment variable. You can also optionally set `DEEPSEEK_API_BASE` if you need to use a different API endpoint (defaults to "https://api.deepseek.com").
## Usage
```python
import os
from mem0 import Memory
os.environ["DEEPSEEK_API_KEY"] = "your-api-key"
os.environ["OPENAI_API_KEY"] = "your-api-key" # for embedder model
config = {
"llm": {
"provider": "deepseek",
"config": {
"model": "deepseek-chat", # default model
"temperature": 0.2,
"max_tokens": 2000,
"top_p": 1.0
}
}
}
m = Memory.from_config(config)
messages = [
{"role": "user", "content": "I'm planning to watch a movie tonight. Any recommendations?"},
{"role": "assistant", "content": "How about a thriller movies? They can be quite engaging."},
{"role": "user", "content": "I’m not a big fan of thriller movies but I love sci-fi movies."},
{"role": "assistant", "content": "Got it! I'll avoid thriller recommendations and suggest sci-fi movies in the future."}
]
m.add(messages, user_id="alice", metadata={"category": "movies"})
```
You can also configure the API base URL in the config:
```python
config = {
"llm": {
"provider": "deepseek",
"config": {
"model": "deepseek-chat",
"deepseek_base_url": "https://your-custom-endpoint.com",
"api_key": "your-api-key" # alternatively to using environment variable
}
}
}
```
## Config
All available parameters for the `deepseek` config are present in [Master List of All Params in Config](../config).
+8 -2
View File
@@ -19,13 +19,19 @@ config = {
"config": {
"model": "gemini-1.5-flash-latest",
"temperature": 0.2,
"max_tokens": 1500,
"max_tokens": 2000,
}
}
}
m = Memory.from_config(config)
m.add("Likes to play cricket on weekends", user_id="alice", metadata={"category": "hobbies"})
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
+8 -2
View File
@@ -19,13 +19,19 @@ config = {
"config": {
"model": "gemini/gemini-pro",
"temperature": 0.2,
"max_tokens": 1500,
"max_tokens": 2000,
}
}
}
m = Memory.from_config(config)
m.add("Likes to play cricket on weekends", user_id="alice", metadata={"category": "hobbies"})
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
+40 -3
View File
@@ -1,10 +1,15 @@
---
title: Groq
---
[Groq](https://groq.com/) is the creator of the world's first Language Processing Unit (LPU), providing exceptional speed performance for AI workloads running on their LPU Inference Engine.
In order to use LLMs from Groq, go to their [platform](https://console.groq.com/keys) and get the API key. Set the API key as `GROQ_API_KEY` environment variable to use the model as given below in the example.
## Usage
```python
<CodeGroup>
```python Python
import os
from mem0 import Memory
@@ -17,15 +22,47 @@ config = {
"config": {
"model": "mixtral-8x7b-32768",
"temperature": 0.1,
"max_tokens": 1000,
"max_tokens": 2000,
}
}
}
m = Memory.from_config(config)
m.add("Likes to play cricket on weekends", user_id="alice", metadata={"category": "hobbies"})
messages = [
{"role": "user", "content": "I'm planning to watch a movie tonight. Any recommendations?"},
{"role": "assistant", "content": "How about a thriller movies? They can be quite engaging."},
{"role": "user", "content": "I’m not a big fan of thriller movies but I love sci-fi movies."},
{"role": "assistant", "content": "Got it! I'll avoid thriller recommendations and suggest sci-fi movies in the future."}
]
m.add(messages, user_id="alice", metadata={"category": "movies"})
```
```typescript TypeScript
import { Memory } from 'mem0ai/oss';
const config = {
llm: {
provider: 'groq',
config: {
apiKey: process.env.GROQ_API_KEY || '',
model: 'mixtral-8x7b-32768',
temperature: 0.1,
maxTokens: 1000,
},
},
};
const memory = new Memory(config);
const messages = [
{"role": "user", "content": "I'm planning to watch a movie tonight. Any recommendations?"},
{"role": "assistant", "content": "How about a thriller movies? They can be quite engaging."},
{"role": "user", "content": "I’m not a big fan of thriller movies but I love sci-fi movies."},
{"role": "assistant", "content": "Got it! I'll avoid thriller recommendations and suggest sci-fi movies in the future."}
]
await memory.add(messages, { userId: "alice", metadata: { category: "movies" } });
```
</CodeGroup>
## Config
All available parameters for the `groq` config are present in [Master List of All Params in Config](../config).
+8 -2
View File
@@ -14,13 +14,19 @@ config = {
"config": {
"model": "gpt-4o-mini",
"temperature": 0.2,
"max_tokens": 1500,
"max_tokens": 2000,
}
}
}
m = Memory.from_config(config)
m.add("Likes to play cricket on weekends", user_id="alice", metadata={"category": "hobbies"})
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
+82
View File
@@ -0,0 +1,82 @@
---
title: LM Studio
---
To use LM Studio with Mem0, you'll need to have LM Studio running locally with its server enabled. LM Studio provides a way to run local LLMs with an OpenAI-compatible API.
## Usage
<CodeGroup>
```python Python
import os
from mem0 import Memory
os.environ["OPENAI_API_KEY"] = "your-api-key" # used for embedding model
config = {
"llm": {
"provider": "lmstudio",
"config": {
"model": "lmstudio-community/Meta-Llama-3.1-70B-Instruct-GGUF/Meta-Llama-3.1-70B-Instruct-IQ2_M.gguf",
"temperature": 0.2,
"max_tokens": 2000,
"lmstudio_base_url": "http://localhost:1234/v1", # default LM Studio API URL
}
}
}
m = Memory.from_config(config)
messages = [
{"role": "user", "content": "I'm planning to watch a movie tonight. Any recommendations?"},
{"role": "assistant", "content": "How about a thriller movies? They can be quite engaging."},
{"role": "user", "content": "I'm not a big fan of thriller movies but I love sci-fi movies."},
{"role": "assistant", "content": "Got it! I'll avoid thriller recommendations and suggest sci-fi movies in the future."}
]
m.add(messages, user_id="alice", metadata={"category": "movies"})
```
</CodeGroup>
### Running Completely Locally
You can also use LM Studio for both LLM and embedding to run Mem0 entirely locally:
```python
from mem0 import Memory
# No external API keys needed!
config = {
"llm": {
"provider": "lmstudio"
},
"embedder": {
"provider": "lmstudio"
}
}
m = Memory.from_config(config)
messages = [
{"role": "user", "content": "I'm planning to watch a movie tonight. Any recommendations?"},
{"role": "assistant", "content": "How about a thriller movies? They can be quite engaging."},
{"role": "user", "content": "I'm not a big fan of thriller movies but I love sci-fi movies."},
{"role": "assistant", "content": "Got it! I'll avoid thriller recommendations and suggest sci-fi movies in the future."}
]
m.add(messages, user_id="alice123", metadata={"category": "movies"})
```
<Note>
When using LM Studio for both LLM and embedding, make sure you have:
1. An LLM model loaded for generating responses
2. An embedding model loaded for vector embeddings
3. The server enabled with the correct endpoints accessible
</Note>
<Note>
To use LM Studio, you need to:
1. Download and install [LM Studio](https://lmstudio.ai/)
2. Start a local server from the "Server" tab
3. Set the appropriate `lmstudio_base_url` in your configuration (default is usually http://localhost:1234/v1)
</Note>
## Config
All available parameters for the `lmstudio` config are present in [Master List of All Params in Config](../config).
+7 -1
View File
@@ -25,7 +25,13 @@ config = {
}
m = Memory.from_config(config)
m.add("Likes to play cricket on weekends", user_id="alice", metadata={"category": "hobbies"})
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
+7 -1
View File
@@ -20,7 +20,13 @@ config = {
}
m = Memory.from_config(config)
m.add("Likes to play cricket on weekends", user_id="alice", metadata={"category": "hobbies"})
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
+39 -4
View File
@@ -6,7 +6,8 @@ To use OpenAI LLM models, you have to set the `OPENAI_API_KEY` environment varia
## Usage
```python
<CodeGroup>
```python Python
import os
from mem0 import Memory
@@ -18,7 +19,7 @@ config = {
"config": {
"model": "gpt-4o",
"temperature": 0.2,
"max_tokens": 1500,
"max_tokens": 2000,
}
}
}
@@ -35,9 +36,41 @@ config = {
# }
m = Memory.from_config(config)
m.add("Likes to play cricket on weekends", user_id="alice", metadata={"category": "hobbies"})
messages = [
{"role": "user", "content": "I'm planning to watch a movie tonight. Any recommendations?"},
{"role": "assistant", "content": "How about a thriller movies? They can be quite engaging."},
{"role": "user", "content": "I’m not a big fan of thriller movies but I love sci-fi movies."},
{"role": "assistant", "content": "Got it! I'll avoid thriller recommendations and suggest sci-fi movies in the future."}
]
m.add(messages, user_id="alice", metadata={"category": "movies"})
```
```typescript TypeScript
import { Memory } from 'mem0ai/oss';
const config = {
llm: {
provider: 'openai',
config: {
apiKey: process.env.OPENAI_API_KEY || '',
model: 'gpt-4-turbo-preview',
temperature: 0.2,
maxTokens: 1500,
},
},
};
const memory = new Memory(config);
const messages = [
{"role": "user", "content": "I'm planning to watch a movie tonight. Any recommendations?"},
{"role": "assistant", "content": "How about a thriller movies? They can be quite engaging."},
{"role": "user", "content": "I’m not a big fan of thriller movies but I love sci-fi movies."},
{"role": "assistant", "content": "Got it! I'll avoid thriller recommendations and suggest sci-fi movies in the future."}
]
await memory.add(messages, { userId: "alice", metadata: { category: "movies" } });
```
</CodeGroup>
We also support the new [OpenAI structured-outputs](https://platform.openai.com/docs/guides/structured-outputs/introduction) model.
```python
@@ -59,7 +92,9 @@ config = {
m = Memory.from_config(config)
```
<Note>
OpenAI structured-outputs is currently only available in the Python implementation.
</Note>
## Config
+8 -2
View File
@@ -15,13 +15,19 @@ config = {
"config": {
"model": "mistralai/Mixtral-8x7B-Instruct-v0.1",
"temperature": 0.2,
"max_tokens": 1500,
"max_tokens": 2000,
}
}
}
m = Memory.from_config(config)
m.add("Likes to play cricket on weekends", user_id="alice", metadata={"category": "hobbies"})
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
+41
View File
@@ -0,0 +1,41 @@
---
title: xAI
---
[xAI](https://x.ai/) is a new AI company founded by Elon Musk that develops large language models, including Grok. Grok is trained on real-time data from X (formerly Twitter) and aims to provide accurate, up-to-date responses with a touch of wit and humor.
In order to use LLMs from xAI, go to their [platform](https://console.x.ai) and get the API key. Set the API key as `XAI_API_KEY` environment variable to use the model as given below in the example.
## Usage
```python
import os
from mem0 import Memory
os.environ["OPENAI_API_KEY"] = "your-api-key" # used for embedding model
os.environ["XAI_API_KEY"] = "your-api-key"
config = {
"llm": {
"provider": "xai",
"config": {
"model": "grok-2-latest",
"temperature": 0.1,
"max_tokens": 2000,
}
}
}
m = Memory.from_config(config)
messages = [
{"role": "user", "content": "I'm planning to watch a movie tonight. Any recommendations?"},
{"role": "assistant", "content": "How about a thriller movies? They can be quite engaging."},
{"role": "user", "content": "I’m not a big fan of thriller movies but I love sci-fi movies."},
{"role": "assistant", "content": "Got it! I'll avoid thriller recommendations and suggest sci-fi movies in the future."}
]
m.add(messages, user_id="alice", metadata={"category": "movies"})
```
## Config
All available parameters for the `xai` config are present in [Master List of All Params in Config](../config).
+20 -11
View File
@@ -1,5 +1,7 @@
---
title: Overview
icon: "info"
iconType: "solid"
---
Mem0 includes built-in support for various popular large language models. Memory can utilize the LLM provided by the user, ensuring efficient use for specific needs.
@@ -12,18 +14,25 @@ For a comprehensive list of available parameters for llm configuration, please r
To view all supported llms, visit the [Supported LLMs](./models).
<Note>
All LLMs are supported in Python. The following LLMs are also supported in TypeScript: **OpenAI**, **Anthropic**, and **Groq**.
</Note>
<CardGroup cols={4}>
<Card title="OpenAI" href="/components/llms/models/openai"></Card>
<Card title="Ollama" href="/components/llms/models/ollama"></Card>
<Card title="Azure OpenAI" href="/components/llms/models/azure_openai"></Card>
<Card title="Anthropic" href="/components/llms/models/anthropic"></Card>
<Card title="Together" href="/components/llms/models/together"></Card>
<Card title="Groq" href="/components/llms/models/groq"></Card>
<Card title="Litellm" href="/components/llms/models/litellm"></Card>
<Card title="Mistral AI" href="/components/llms/models/mistral_ai"></Card>
<Card title="Google AI" href="/components/llms/models/google_ai"></Card>
<Card title="AWS bedrock" href="/components/llms/models/aws_bedrock"></Card>
<Card title="Gemini" href="/components/llms/models/gemini"></Card>
<Card title="OpenAI" href="/components/llms/models/openai" />
<Card title="Ollama" href="/components/llms/models/ollama" />
<Card title="Azure OpenAI" href="/components/llms/models/azure_openai" />
<Card title="Anthropic" href="/components/llms/models/anthropic" />
<Card title="Together" href="/components/llms/models/together" />
<Card title="Groq" href="/components/llms/models/groq" />
<Card title="Litellm" href="/components/llms/models/litellm" />
<Card title="Mistral AI" href="/components/llms/models/mistral_ai" />
<Card title="Google AI" href="/components/llms/models/google_ai" />
<Card title="AWS bedrock" href="/components/llms/models/aws_bedrock" />
<Card title="Gemini" href="/components/llms/models/gemini" />
<Card title="DeepSeek" href="/components/llms/models/deepseek" />
<Card title="xAI" href="/components/llms/models/xAI" />
<Card title="LM Studio" href="/components/llms/models/lmstudio" />
</CardGroup>
## Structured vs Unstructured Outputs
+63 -7
View File
@@ -1,19 +1,23 @@
## What is Config?
---
title: Configurations
icon: "gear"
iconType: "solid"
---
Config in mem0 is a dictionary that specifies the settings for your vector database. It allows you to customize the behavior and connection details of your chosen vector store.
## How to define configurations?
## How to Define Config
The config is defined as a Python dictionary with two main keys:
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","azure_ai_search")
- `provider`: The name of the vector database (e.g., "chroma", "pgvector", "qdrant", "milvus","azure_ai_search", "vertex_ai_vector_search")
- `config`: A nested dictionary containing provider-specific settings
## How to Use Config
Here's a general example of how to use the config with mem0:
```python
<CodeGroup>
```python Python
import os
from mem0 import Memory
@@ -32,6 +36,29 @@ m = Memory.from_config(config)
m.add("Your text here", user_id="user", metadata={"category": "example"})
```
```typescript TypeScript
// Example for in-memory vector database (Only supported in TypeScript)
import { Memory } from 'mem0ai/oss';
const configMemory = {
vector_store: {
provider: 'memory',
config: {
collectionName: 'memories',
dimension: 1536,
},
},
};
const memory = new Memory(configMemory);
await memory.add("Your text here", { userId: "user", metadata: { category: "example" } });
```
</CodeGroup>
<Note>
The in-memory vector database is only supported in the TypeScript implementation.
</Note>
## Why is Config Needed?
Config is essential for:
@@ -44,6 +71,8 @@ Config is essential for:
Here's a comprehensive list of all parameters that can be used across different vector databases:
<Tabs>
<Tab title="Python">
| Parameter | Description |
|-----------|-------------|
| `collection_name` | Name of the collection |
@@ -58,6 +87,33 @@ Here's a comprehensive list of all parameters that can be used across different
| `url` | Full URL for the server |
| `api_key` | API key for the server |
| `on_disk` | Enable persistent storage |
| `endpoint_id` | Endpoint ID (vertex_ai_vector_search) |
| `index_id` | Index ID (vertex_ai_vector_search) |
| `deployment_index_id` | Deployment index ID (vertex_ai_vector_search) |
| `project_id` | Project ID (vertex_ai_vector_search) |
| `project_number` | Project number (vertex_ai_vector_search) |
| `vector_search_api_endpoint` | Vector search API endpoint (vertex_ai_vector_search) |
| `connection_string` | PostgreSQL connection string (for Supabase/PGVector) |
| `index_method` | Vector index method (for Supabase) |
| `index_measure` | Distance measure for similarity search (for Supabase) |
</Tab>
<Tab title="TypeScript">
| Parameter | Description |
|-----------|-------------|
| `collectionName` | Name of the collection |
| `embeddingModelDims` | Dimensions of the embedding model |
| `dimension` | Dimensions of the embedding model (for memory provider) |
| `host` | Host where the server is running |
| `port` | Port where the server is running |
| `url` | URL for the server |
| `apiKey` | API key for the server |
| `path` | Path for the database |
| `onDisk` | Enable persistent storage |
| `redisUrl` | URL for the Redis server |
| `username` | Username for database connection |
| `password` | Password for database connection |
</Tab>
</Tabs>
## Customizing Config
@@ -1,12 +1,12 @@
[Azure AI Search](https://learn.microsoft.com/en-us/azure/search/search-what-is-azure-search/) (formerly known as "Azure Cognitive Search") provides secure information retrieval at scale over user-owned content in traditional and generative AI search applications.
[Azure AI Search](https://learn.microsoft.com/azure/search/search-what-is-azure-search/) (formerly known as "Azure Cognitive Search") provides secure information retrieval at scale over user-owned content in traditional and generative AI search applications.
### Usage
## Usage
```python
import os
from mem0 import Memory
os.environ["OPENAI_API_KEY"] = "sk-xx" #this key is used for embedding purpose
os.environ["OPENAI_API_KEY"] = "sk-xx" # This key is used for embedding purpose
config = {
"vector_store": {
@@ -15,24 +15,81 @@ config = {
"service_name": "ai-search-test",
"api_key": "*****",
"collection_name": "mem0",
"embedding_model_dims": 1536 ,
"use_compression": False
"embedding_model_dims": 1536
}
}
}
m = Memory.from_config(config)
m.add("Likes to play cricket on weekends", user_id="alice", metadata={"category": "hobbies"})
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
## Using binary compression for large vector collections
Let's see the available parameters for the `qdrant` config:
service_name (str): Azure Cognitive Search service name.
| Parameter | Description | Default Value |
| --- | --- | --- |
| `service_name` | Azure AI Search service name | `None` |
| `api_key` | API key of the Azure AI Search service | `None` |
| `collection_name` | The name of the collection/index to store the vectors, it will be created automatically if not exist | `mem0` |
| `embedding_model_dims` | Dimensions of the embedding model | `1536` |
| `use_compression` | Use scalar quantization vector compression | False |
```python
config = {
"vector_store": {
"provider": "azure_ai_search",
"config": {
"service_name": "ai-search-test",
"api_key": "*****",
"collection_name": "mem0",
"embedding_model_dims": 1536,
"compression_type": "binary",
"use_float16": True # Use half precision for storage efficiency
}
}
}
```
## Using hybrid search
```python
config = {
"vector_store": {
"provider": "azure_ai_search",
"config": {
"service_name": "ai-search-test",
"api_key": "*****",
"collection_name": "mem0",
"embedding_model_dims": 1536,
"hybrid_search": True,
"vector_filter_mode": "postFilter"
}
}
}
```
## 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 | - |
| `collection_name` | The name of the collection/index to store vectors | `mem0` | Any valid index name |
| `embedding_model_dims` | Dimensions of the embedding model | `1536` | Any integer value |
| `compression_type` | Type of vector compression to use | `none` | `none`, `scalar`, `binary` |
| `use_float16` | Store vectors in half precision (Edm.Half) | `False` | `True`, `False` |
| `vector_filter_mode` | Vector filter mode to use | `preFilter` | `postFilter`, `preFilter` |
| `hybrid_search` | Use hybrid search | `False` | `True`, `False` |
## Notes on Configuration Options
- **compression_type**:
- `none`: No compression, uses full vector precision
- `scalar`: Scalar quantization with reasonable balance of speed and accuracy
- `binary`: Binary quantization for maximum compression with some accuracy trade-off
- **vector_filter_mode**:
- `preFilter`: Applies filters before vector search (faster)
- `postFilter`: Applies filters after vector search (may provide better relevance)
- **use_float16**: Using half precision (float16) reduces storage requirements but may slightly impact accuracy. Useful for very large vector collections.
- **Filterable Fields**: The implementation automatically extracts `user_id`, `run_id`, and `agent_id` fields from payloads for filtering.
+7 -1
View File
@@ -19,7 +19,13 @@ config = {
}
m = Memory.from_config(config)
m.add("Likes to play cricket on weekends", user_id="alice", metadata={"category": "hobbies"})
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
@@ -29,7 +29,13 @@ config = {
}
m = Memory.from_config(config)
m.add("Likes to play cricket on weekends", user_id="alice", metadata={"category": "hobbies"})
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
@@ -48,6 +54,7 @@ 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` |
### Features
@@ -56,3 +63,46 @@ Let's see the available parameters for the `elasticsearch` config:
- Multiple authentication methods (Basic Auth, API Key)
- Automatic index creation with optimized mappings for vector search
- Memory isolation through payload filtering
- Custom search query function to customize the search query
### Custom Search Query
The `custom_search_query` parameter allows you to customize the search query when `Memory.search` is called.
__Example__
```python
import os
from typing import List, Optional, Dict
from mem0 import Memory
def custom_search_query(query: List[float], limit: int, filters: Optional[Dict]) -> Dict:
return {
"knn": {
"field": "vector",
"query_vector": query,
"k": limit,
"num_candidates": limit * 2
}
}
os.environ["OPENAI_API_KEY"] = "sk-xx"
config = {
"vector_store": {
"provider": "elasticsearch",
"config": {
"collection_name": "mem0",
"host": "localhost",
"port": 9200,
"embedding_model_dims": 1536,
"custom_search_query": custom_search_query
}
}
}
```
It should be a function that takes the following parameters:
- `query`: a query vector used in `Memory.search`
- `limit`: a number of results used in `Memory.search`
- `filters`: a dictionary of key-value pairs used in `Memory.search`. You can add custom pairs for the custom search query.
The function should return a query body for the Elasticsearch search API.
+7 -1
View File
@@ -19,7 +19,13 @@ config = {
}
m = Memory.from_config(config)
m.add("Likes to play cricket on weekends", user_id="alice", metadata={"category": "hobbies"})
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
@@ -0,0 +1,65 @@
[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.
### Installation
OpenSearch support requires additional dependencies. Install them with:
```bash
pip install opensearch>=2.8.0
```
### Usage
```python
import os
from mem0 import Memory
os.environ["OPENAI_API_KEY"] = "sk-xx"
config = {
"vector_store": {
"provider": "opensearch",
"config": {
"collection_name": "mem0",
"host": "localhost",
"port": 9200,
"embedding_model_dims": 1536
}
}
}
m = Memory.from_config(config)
messages = [
{"role": "user", "content": "I'm planning to watch a movie tonight. Any recommendations?"},
{"role": "assistant", "content": "How about a thriller movies? They can be quite engaging."},
{"role": "user", "content": "I’m not a big fan of thriller movies but I love sci-fi movies."},
{"role": "assistant", "content": "Got it! I'll avoid thriller recommendations and suggest sci-fi movies in the future."}
]
m.add(messages, user_id="alice", metadata={"category": "movies"})
```
### Config
Let's see the available parameters for the `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` |
### Features
- Fast and Efficient Vector Search
- Can be deployed on-premises, in containers, or on cloud platforms like AWS OpenSearch Service.
- Multiple Authentication and Security Methods (Basic Authentication, API Keys, LDAP, SAML, and OpenID Connect)
- Automatic index creation with optimized mappings for vector search
- Memory Optimization through Disk-Based Vector Search and Quantization
- Real-Time Analytics and Observability
+7 -1
View File
@@ -21,7 +21,13 @@ config = {
}
m = Memory.from_config(config)
m.add("Likes to play cricket on weekends", user_id="alice", metadata={"category": "hobbies"})
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
@@ -0,0 +1,92 @@
[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.
> **Note**: Before configuring Pinecone, you need to select an embedding model (e.g., OpenAI, Cohere, or custom models) and ensure the `embedding_model_dims` in your config matches your chosen model's dimensions. For example, OpenAI's text-embedding-3-small uses 1536 dimensions.
### Usage
```python
import os
from mem0 import Memory
os.environ["OPENAI_API_KEY"] = "sk-xx"
os.environ["PINECONE_API_KEY"] = "your-api-key"
# Example using serverless configuration
config = {
"vector_store": {
"provider": "pinecone",
"config": {
"collection_name": "testing",
"embedding_model_dims": 1536, # Matches OpenAI's text-embedding-3-small
"serverless_config": {
"cloud": "aws", # Choose between 'aws' or 'gcp' or 'azure'
"region": "us-east-1"
},
"metric": "cosine"
}
}
}
m = Memory.from_config(config)
messages = [
{"role": "user", "content": "I'm planning to watch a movie tonight. Any recommendations?"},
{"role": "assistant", "content": "How about a thriller movies? They can be quite engaging."},
{"role": "user", "content": "I'm not a big fan of thriller movies but I love sci-fi movies."},
{"role": "assistant", "content": "Got it! I'll avoid thriller recommendations and suggest sci-fi movies in the future."}
]
m.add(messages, user_id="alice", metadata={"category": "movies"})
```
### Config
Here are the parameters available for configuring Pinecone:
| Parameter | Description | Default Value |
| --- | --- | --- |
| `collection_name` | Name of the index/collection | Required |
| `embedding_model_dims` | Dimensions of the embedding model (must match your chosen embedding model) | Required |
| `client` | Existing Pinecone client instance | `None` |
| `api_key` | API key for Pinecone | Environment variable: `PINECONE_API_KEY` |
| `environment` | Pinecone environment | `None` |
| `serverless_config` | Configuration for serverless deployment (AWS or GCP or Azure) | `None` |
| `pod_config` | Configuration for pod-based deployment | `None` |
| `hybrid_search` | Whether to enable hybrid search | `False` |
| `metric` | Distance metric for vector similarity | `"cosine"` |
| `batch_size` | Batch size for operations | `100` |
> **Important**: You must choose either `serverless_config` or `pod_config` for your deployment, but not both.
#### Serverless Config Example
```python
config = {
"vector_store": {
"provider": "pinecone",
"config": {
"collection_name": "memory_index",
"embedding_model_dims": 1536, # For OpenAI's text-embedding-3-small
"serverless_config": {
"cloud": "aws", # or "gcp" or "azure"
"region": "us-east-1" # Choose appropriate region
}
}
}
}
```
#### Pod Config Example
```python
config = {
"vector_store": {
"provider": "pinecone",
"config": {
"collection_name": "memory_index",
"embedding_model_dims": 1536, # For OpenAI's text-embedding-ada-002
"pod_config": {
"environment": "gcp-starter",
"replicas": 1,
"pod_type": "starter"
}
}
}
}
```
+52 -3
View File
@@ -2,7 +2,8 @@
### Usage
```python
<CodeGroup>
```python Python
import os
from mem0 import Memory
@@ -20,13 +21,47 @@ config = {
}
m = Memory.from_config(config)
m.add("Likes to play cricket on weekends", user_id="alice", metadata={"category": "hobbies"})
messages = [
{"role": "user", "content": "I'm planning to watch a movie tonight. Any recommendations?"},
{"role": "assistant", "content": "How about a thriller movies? They can be quite engaging."},
{"role": "user", "content": "I’m not a big fan of thriller movies but I love sci-fi movies."},
{"role": "assistant", "content": "Got it! I'll avoid thriller recommendations and suggest sci-fi movies in the future."}
]
m.add(messages, user_id="alice", metadata={"category": "movies"})
```
```typescript TypeScript
import { Memory } from 'mem0ai/oss';
const config = {
vectorStore: {
provider: 'qdrant',
config: {
collectionName: 'memories',
embeddingModelDims: 1536,
host: 'localhost',
port: 6333,
},
},
};
const memory = new Memory(config);
const messages = [
{"role": "user", "content": "I'm planning to watch a movie tonight. Any recommendations?"},
{"role": "assistant", "content": "How about a thriller movies? They can be quite engaging."},
{"role": "user", "content": "I’m not a big fan of thriller movies but I love sci-fi movies."},
{"role": "assistant", "content": "Got it! I'll avoid thriller recommendations and suggest sci-fi movies in the future."}
]
await memory.add(messages, { userId: "alice", metadata: { category: "movies" } });
```
</CodeGroup>
### Config
Let's see the available parameters for the `qdrant` config:
<Tabs>
<Tab title="Python">
| Parameter | Description | Default Value |
| --- | --- | --- |
| `collection_name` | The name of the collection to store the vectors | `mem0` |
@@ -37,4 +72,18 @@ Let's see the available parameters for the `qdrant` config:
| `path` | Path for the qdrant database | `/tmp/qdrant` |
| `url` | Full URL for the qdrant server | `None` |
| `api_key` | API key for the qdrant server | `None` |
| `on_disk` | For enabling persistent storage | `False` |
| `on_disk` | For enabling persistent storage | `False` |
</Tab>
<Tab title="TypeScript">
| Parameter | Description | Default Value |
| --- | --- | --- |
| `collectionName` | The name of the collection to store the vectors | `mem0` |
| `embeddingModelDims` | Dimensions of the embedding model | `1536` |
| `host` | The host where the Qdrant server is running | `None` |
| `port` | The port where the Qdrant server is running | `None` |
| `path` | Path for the Qdrant database | `/tmp/qdrant` |
| `url` | Full URL for the Qdrant server | `None` |
| `apiKey` | API key for the Qdrant server | `None` |
| `onDisk` | For enabling persistent storage | `False` |
</Tab>
</Tabs>
+52 -4
View File
@@ -12,7 +12,8 @@ docker run -d --name redis-stack -p 6379:6379 -p 8001:8001 redis/redis-stack:lat
### Usage
```python
<CodeGroup>
```python Python
import os
from mem0 import Memory
@@ -26,19 +27,66 @@ config = {
"embedding_model_dims": 1536,
"redis_url": "redis://localhost:6379"
}
}
},
"version": "v1.1"
}
m = Memory.from_config(config)
m.add("Likes to play cricket on weekends", user_id="alice", metadata={"category": "hobbies"})
messages = [
{"role": "user", "content": "I'm planning to watch a movie tonight. Any recommendations?"},
{"role": "assistant", "content": "How about a thriller movies? They can be quite engaging."},
{"role": "user", "content": "I’m not a big fan of thriller movies but I love sci-fi movies."},
{"role": "assistant", "content": "Got it! I'll avoid thriller recommendations and suggest sci-fi movies in the future."}
]
m.add(messages, user_id="alice", metadata={"category": "movies"})
```
```typescript TypeScript
import { Memory } from 'mem0ai/oss';
const config = {
vectorStore: {
provider: 'redis',
config: {
collectionName: 'memories',
embeddingModelDims: 1536,
redisUrl: 'redis://localhost:6379',
username: 'your-redis-username',
password: 'your-redis-password',
},
},
};
const memory = new Memory(config);
const messages = [
{"role": "user", "content": "I'm planning to watch a movie tonight. Any recommendations?"},
{"role": "assistant", "content": "How about a thriller movies? They can be quite engaging."},
{"role": "user", "content": "I’m not a big fan of thriller movies but I love sci-fi movies."},
{"role": "assistant", "content": "Got it! I'll avoid thriller recommendations and suggest sci-fi movies in the future."}
]
await memory.add(messages, { userId: "alice", metadata: { category: "movies" } });
```
</CodeGroup>
### Config
Let's see the available parameters for the `redis` config:
<Tabs>
<Tab title="Python">
| Parameter | Description | Default Value |
| --- | --- | --- |
| `collection_name` | The name of the collection to store the vectors | `mem0` |
| `embedding_model_dims` | Dimensions of the embedding model | `1536` |
| `redis_url` | The URL of the Redis server | `None` |
| `redis_url` | The URL of the Redis server | `None` |
</Tab>
<Tab title="TypeScript">
| Parameter | Description | Default Value |
| --- | --- | --- |
| `collectionName` | The name of the collection to store the vectors | `mem0` |
| `embeddingModelDims` | Dimensions of the embedding model | `1536` |
| `redisUrl` | The URL of the Redis server | `None` |
| `username` | Username for Redis connection | `None` |
| `password` | Password for Redis connection | `None` |
</Tab>
</Tabs>
+170
View File
@@ -0,0 +1,170 @@
[Supabase](https://supabase.com/) is an open-source Firebase alternative that provides a PostgreSQL database with pgvector extension for vector similarity search. It offers a powerful and scalable solution for storing and querying vector embeddings.
Create a [Supabase](https://supabase.com/dashboard/projects) account and project, then get your connection string from Project Settings > Database. See the [docs](https://supabase.github.io/vecs/hosting/) for details.
### Usage
<CodeGroup>
```python Python
import os
from mem0 import Memory
os.environ["OPENAI_API_KEY"] = "sk-xx"
config = {
"vector_store": {
"provider": "supabase",
"config": {
"connection_string": "postgresql://user:password@host:port/database",
"collection_name": "memories",
"index_method": "hnsw", # Optional: defaults to "auto"
"index_measure": "cosine_distance" # Optional: defaults to "cosine_distance"
}
}
}
m = Memory.from_config(config)
messages = [
{"role": "user", "content": "I'm planning to watch a movie tonight. Any recommendations?"},
{"role": "assistant", "content": "How about a thriller movies? They can be quite engaging."},
{"role": "user", "content": "I'm not a big fan of thriller movies but I love sci-fi movies."},
{"role": "assistant", "content": "Got it! I'll avoid thriller recommendations and suggest sci-fi movies in the future."}
]
m.add(messages, user_id="alice", metadata={"category": "movies"})
```
```typescript Typescript
import { Memory } from "mem0ai/oss";
const config = {
vectorStore: {
provider: "supabase",
config: {
collectionName: "memories",
embeddingModelDims: 1536,
supabaseUrl: process.env.SUPABASE_URL || "",
supabaseKey: process.env.SUPABASE_KEY || "",
tableName: "memories",
},
},
}
const memory = new Memory(config);
const messages = [
{"role": "user", "content": "I'm planning to watch a movie tonight. Any recommendations?"},
{"role": "assistant", "content": "How about a thriller movies? They can be quite engaging."},
{"role": "user", "content": "I'm not a big fan of thriller movies but I love sci-fi movies."},
{"role": "assistant", "content": "Got it! I'll avoid thriller recommendations and suggest sci-fi movies in the future."}
]
await memory.add(messages, { userId: "alice", metadata: { category: "movies" } });
```
</CodeGroup>
### SQL Migrations for TypeScript Implementation
The following SQL migrations are required to enable the vector extension and create the memories table:
```sql
-- Enable the vector extension
create extension if not exists vector;
-- Create the memories table
create table if not exists memories (
id text primary key,
embedding vector(1536),
metadata jsonb,
created_at timestamp with time zone default timezone('utc', now()),
updated_at timestamp with time zone default timezone('utc', now())
);
-- Create the vector similarity search function
create or replace function match_vectors(
query_embedding vector(1536),
match_count int,
filter jsonb default '{}'::jsonb
)
returns table (
id text,
similarity float,
metadata jsonb
)
language plpgsql
as $$
begin
return query
select
id,
similarity,
metadata
from memories
where case
when filter::text = '{}'::text then true
else metadata @> filter
end
order by embedding <=> query_embedding
limit match_count;
end;
$$;
```
Goto [Supabase](https://supabase.com/dashboard/projects) and run the above SQL migrations inside the SQL Editor.
### Config
Here are the parameters available for configuring Supabase:
<Tabs>
<Tab title="Python">
| Parameter | Description | Default Value |
| --- | --- | --- |
| `connection_string` | PostgreSQL connection string (required) | None |
| `collection_name` | Name for the vector collection | `mem0` |
| `embedding_model_dims` | Dimensions of the embedding model | `1536` |
| `index_method` | Vector index method to use | `auto` |
| `index_measure` | Distance measure for similarity search | `cosine_distance` |
</Tab>
<Tab title="TypeScript">
| Parameter | Description | Default Value |
| --- | --- | --- |
| `collectionName` | Name for the vector collection | `mem0` |
| `embeddingModelDims` | Dimensions of the embedding model | `1536` |
| `supabaseUrl` | Supabase URL | None |
| `supabaseKey` | Supabase key | None |
| `tableName` | Name for the vector table | `memories` |
</Tab>
</Tabs>
### Index Methods
The following index methods are supported:
- `auto`: Automatically selects the best available index method
- `hnsw`: Hierarchical Navigable Small World graph index (faster search, more memory usage)
- `ivfflat`: Inverted File Flat index (good balance of speed and memory)
### Distance Measures
Available distance measures for similarity search:
- `cosine_distance`: Cosine similarity (recommended for most embedding models)
- `l2_distance`: Euclidean distance
- `l1_distance`: Manhattan distance
- `max_inner_product`: Maximum inner product similarity
### Best Practices
1. **Index Method Selection**:
- Use `hnsw` for fastest search performance when memory is not a constraint
- Use `ivfflat` for a good balance of search speed and memory usage
- Use `auto` if unsure, it will select the best method based on your data
2. **Distance Measure Selection**:
- Use `cosine_distance` for most embedding models (OpenAI, Hugging Face, etc.)
- Use `max_inner_product` if your vectors are normalized
- Use `l2_distance` or `l1_distance` if working with raw feature vectors
3. **Connection String**:
- Always use environment variables for sensitive information in the connection string
- Format: `postgresql://user:password@host:port/database`
@@ -0,0 +1,46 @@
## Google Cloud Vertex AI Vector Search
### Usage
To use Google Cloud Vertex AI Vector Search with `mem0`, you need to configure the `vector_store` in your `mem0` config:
```python
import os
from mem0 import Memory
os.environ["GEMINI_API_KEY"] = = "sk-xx"
config = {
"vector_store": {
"provider": "vertex_ai_vector_search",
"config": {
"endpoint_id": "YOUR_ENDPOINT_ID", # Required: Vector Search endpoint ID
"index_id": "YOUR_INDEX_ID", # Required: Vector Search index ID
"deployment_index_id": "YOUR_DEPLOYMENT_INDEX_ID", # Required: Deployment-specific ID
"project_id": "YOUR_PROJECT_ID", # Required: Google Cloud project ID
"project_number": "YOUR_PROJECT_NUMBER", # Required: Google Cloud project number
"region": "YOUR_REGION", # Optional: Defaults to GOOGLE_CLOUD_REGION
"credentials_path": "path/to/credentials.json", # Optional: Defaults to GOOGLE_APPLICATION_CREDENTIALS
"vector_search_api_endpoint": "YOUR_API_ENDPOINT" # Required for get operations
}
}
}
m = Memory.from_config(config)
m.add("Your text here", user_id="user", metadata={"category": "example"})
```
### Required Parameters
| Parameter | Description | Required |
|-----------|-------------|----------|
| `endpoint_id` | Vector Search endpoint ID | Yes |
| `index_id` | Vector Search index ID | Yes |
| `deployment_index_id` | Deployment-specific index ID | Yes |
| `project_id` | Google Cloud project ID | Yes |
| `project_number` | Google Cloud project number | Yes |
| `vector_search_api_endpoint` | Vector search API endpoint | Yes (for get operations) |
| `region` | Google Cloud region | No (defaults to GOOGLE_CLOUD_REGION) |
| `credentials_path` | Path to service account credentials | No (defaults to GOOGLE_APPLICATION_CREDENTIALS) |
@@ -0,0 +1,47 @@
[Weaviate](https://weaviate.io/) is an open-source vector search engine. It allows efficient storage and retrieval of high-dimensional vector embeddings, enabling powerful search and retrieval capabilities.
### Installation
```bash
pip install weaviate weaviate-client
```
### Usage
```python Python
import os
from mem0 import Memory
os.environ["OPENAI_API_KEY"] = "sk-xx"
config = {
"vector_store": {
"provider": "weaviate",
"config": {
"collection_name": "test",
"cluster_url": "http://localhost:8080",
"auth_client_secret": None,
}
}
}
m = Memory.from_config(config)
messages = [
{"role": "user", "content": "I'm planning to watch a movie tonight. Any recommendations?"},
{"role": "assistant", "content": "How about a thriller movie? They can be quite engaging."},
{"role": "user", "content": "I’m not a big fan of thriller movies but I love sci-fi movies."},
{"role": "assistant", "content": "Got it! I'll avoid thriller recommendations and suggest sci-fi movies in the future."}
]
m.add(messages, user_id="alice", metadata={"category": "movies"})
```
### Config
Let's see the available parameters for the `weaviate` config:
| Parameter | Description | Default Value |
| --- | --- | --- |
| `collection_name` | The name of the collection to store the vectors | `mem0` |
| `embedding_model_dims` | Dimensions of the embedding model | `1536` |
| `cluster_url` | URL for the Weaviate server | `None` |
| `auth_client_secret` | API key for Weaviate authentication | `None` |
+11
View File
@@ -1,5 +1,7 @@
---
title: Overview
icon: "info"
iconType: "solid"
---
Mem0 includes built-in support for various popular databases. Memory can utilize the database provided by the user, ensuring efficient use for specific needs.
@@ -8,14 +10,23 @@ 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.
</Note>
<CardGroup cols={3}>
<Card title="Qdrant" href="/components/vectordbs/dbs/qdrant"></Card>
<Card title="Chroma" href="/components/vectordbs/dbs/chroma"></Card>
<Card title="Pgvector" href="/components/vectordbs/dbs/pgvector"></Card>
<Card title="Milvus" href="/components/vectordbs/dbs/milvus"></Card>
<Card title="Pinecone" href="/components/vectordbs/dbs/pinecone"></Card>
<Card title="Azure AI Search" href="/components/vectordbs/dbs/azure_ai_search"></Card>
<Card title="Redis" href="/components/vectordbs/dbs/redis"></Card>
<Card title="Elasticsearch" href="/components/vectordbs/dbs/elasticsearch"></Card>
<Card title="OpenSearch" href="/components/vectordbs/dbs/opensearch"></Card>
<Card title="Supabase" href="/components/vectordbs/dbs/supabase"></Card>
<Card title="Vertex AI Vector Search" href="/components/vectordbs/dbs/vertex_ai_vector_search"></Card>
<Card title="Weaviate" href="/components/vectordbs/dbs/weaviate"></Card>
</CardGroup>
## Usage
+87
View File
@@ -0,0 +1,87 @@
---
title: Development
icon: "code"
---
# Development Contributions
We strive to make contributions **easy, collaborative, and enjoyable**. Follow the steps below to ensure a smooth contribution process.
## Submitting Your Contribution through PR
To contribute, follow these steps:
1. **Fork & Clone** the repository: [Mem0 on GitHub](https://github.com/mem0ai/mem0)
2. **Create a Feature Branch**: Use a dedicated branch for your changes, e.g., `feature/my-new-feature`
3. **Implement Changes**: If adding a feature or fixing a bug, ensure to:
- Write necessary **tests**
- Add **documentation, docstrings, and runnable examples**
4. **Code Quality Checks**:
- Run **linting** to catch style issues
- Ensure **all tests pass**
5. **Submit a Pull Request** 🚀
For detailed guidance on pull requests, refer to [GitHub's documentation](https://docs.github.com/en/pull-requests/collaborating-with-pull-requests/proposing-changes-to-your-work-with-pull-requests/creating-a-pull-request).
---
## 📦 Dependency Management
We use `poetry` as our package manager. Install it by following the [official instructions](https://python-poetry.org/docs/#installation).
⚠️ **Do NOT use `pip` or `conda` for dependency management.** Instead, run:
```bash
make install_all
# Activate virtual environment
poetry shell
```
---
## 🛠️ Development Standards
### ✅ Pre-commit Hooks
Ensure `pre-commit` is installed before contributing:
```bash
pre-commit install
```
### 🔍 Linting with `ruff`
Run the linter and fix any reported issues before submitting your PR:
```bash
make lint
```
### 🎨 Code Formatting with `black`
To maintain a consistent code style, format your code using `black`:
```bash
make format
```
### 🧪 Testing with `pytest`
Run tests to verify functionality before submitting your PR:
```bash
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.
---
## 🚀 Release Process
Currently, releases are handled manually. We aim for frequent releases, typically when new features or bug fixes are introduced.
---
Thank you for contributing to Mem0! 🎉
+55
View File
@@ -0,0 +1,55 @@
---
title: Documentation
icon: "book"
---
# Documentation Contributions
## 📌 Prerequisites
Before getting started, ensure you have **Node.js (version 23.6.0 or higher)** installed on your system.
---
## 🚀 Setting Up Mintlify
### Step 1: Install Mintlify
Install Mintlify globally using your preferred package manager:
<CodeGroup>
```bash npm
npm i -g mintlify
```
```bash yarn
yarn global add mintlify
```
</CodeGroup>
### Step 2: Run the Documentation Server
Navigate to the `docs/` directory (where `docs.json` is located) and start the development server:
```bash
mintlify dev
```
The documentation website will be available at: [http://localhost:3000](http://localhost:3000).
---
## 🔧 Custom Ports
By default, Mintlify runs on **port 3000**. To use a different port, add the `--port` flag:
```bash
mintlify dev --port 3333
```
---
By following these steps, you can efficiently contribute to **Mem0's documentation**. Happy documenting! ✍️
+60
View File
@@ -0,0 +1,60 @@
---
title: Memory Operations
description: Understanding the core operations for managing memories in AI applications
icon: "gear"
iconType: "solid"
---
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.
+48
View File
@@ -0,0 +1,48 @@
---
title: Memory Types
description: Understanding different types of memory in AI Applications
icon: "memory"
iconType: "solid"
---
To build useful AI applications, we need to understand how different memory systems work together. This guide explores the fundamental types of memory in AI systems and shows how Mem0 implements these concepts.
## Why Memory Matters
AI systems need memory for three key purposes:
1. Maintaining context during conversations
2. Learning from past interactions
3. Building personalized experiences over time
Without proper memory systems, AI applications would treat each interaction as completely new, losing valuable context and personalization opportunities.
## Short-Term Memory
The most basic form of memory in AI systems holds immediate context - like a person remembering what was just said in a conversation. This includes:
- **Conversation History**: Recent messages and their order
- **Working Memory**: Temporary variables and state
- **Attention Context**: Current focus of the conversation
## Long-Term Memory
More sophisticated AI applications implement long-term memory to retain information across conversations. This includes:
- **Factual Memory**: Stored knowledge about users, preferences, and domain-specific information
- **Episodic Memory**: Past interactions and experiences
- **Semantic Memory**: Understanding of concepts and their relationships
## Memory Characteristics
Each memory type has distinct characteristics:
| Type | Persistence | Access Speed | Use Case |
|------|-------------|--------------|-----------|
| Short-Term | Temporary | Instant | Active conversations |
| Long-Term | Persistent | Fast | User preferences and history |
## How Mem0 Implements Long-Term Memory
Mem0's long-term memory system builds on these foundations by:
1. Using vector embeddings to store and retrieve semantic information
2. Maintaining user-specific context across sessions
3. Implementing efficient retrieval mechanisms for relevant past interactions
+351
View File
@@ -0,0 +1,351 @@
{
"$schema": "https://mintlify.com/docs.json",
"theme": "maple",
"name": "Mem0",
"description": "Mem0 is a self-improving memory layer for LLM applications, enabling personalized AI experiences that save costs and delight users.",
"colors": {
"primary": "#6c60f0",
"light": "#E6FFA2",
"dark": "#a3df02"
},
"favicon": "/logo/favicon.png",
"navigation": {
"anchors": [
{
"anchor": "Documentation",
"icon": "book-open",
"tabs": [
{
"tab": "Documentation",
"groups": [
{
"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",
{
"group": "Features",
"icon": "star",
"pages": [
"features/platform-overview",
"features/advanced-retrieval",
"features/contextual-add",
"features/multimodal-support",
"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"
]
}
]
},
{
"group": "Open Source",
"icon": "code-branch",
"pages": [
"open-source/quickstart",
"open-source/python-quickstart",
"open-source/node-quickstart",
{
"group": "Features",
"icon": "wrench",
"pages": [
"features/openai_compatibility",
"features/custom-fact-extraction-prompt",
"features/custom-update-memory-prompt",
"open-source/multimodal-support",
"open-source/features/rest-api"
]
},
{
"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/gemini",
"components/llms/models/deepseek",
"components/llms/models/xAI"
]
}
]
},
{
"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/azure_ai_search",
"components/vectordbs/dbs/redis",
"components/vectordbs/dbs/elasticsearch",
"components/vectordbs/dbs/opensearch",
"components/vectordbs/dbs/supabase",
"components/vectordbs/dbs/vertex_ai_vector_search",
"components/vectordbs/dbs/weaviate"
]
}
]
},
{
"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/gemini"
]
}
]
}
]
},
{
"group": "Contribution",
"icon": "handshake",
"pages": [
"contributing/development",
"contributing/documentation"
]
}
]
},
{
"tab": "Examples",
"groups": [
{
"group": "💡 Examples",
"icon": "lightbulb",
"pages": [
"examples/overview",
"examples/mem0-demo",
"examples/ai_companion_js",
"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"
]
}
]
},
{
"tab": "Integrations",
"groups": [
{
"group": "Integrations",
"icon": "plug",
"pages": [
"integrations/overview",
"integrations/vercel-ai-sdk",
"integrations/crewai",
"integrations/autogen",
"integrations/langchain",
"integrations/langgraph",
"integrations/llama-index",
"integrations/langchain-tools",
"integrations/dify",
"integrations/mcp-server"
]
}
]
},
{
"tab": "API Reference",
"icon": "square-terminal",
"groups": [
{
"group": "API Reference",
"icon": "terminal",
"pages": [
"api-reference/overview",
{
"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": "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"
]
}
]
}
]
}
]
},
{
"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"
}
]
},
"logo": {
"light": "/logo/light.svg",
"dark": "/logo/dark.svg",
"href": "https://github.com/mem0ai/mem0"
},
"background": {
"color": {
"light": "#fff",
"dark": "#0f1117"
}
},
"navbar": {
"primary": {
"type": "button",
"label": "Your Dashboard",
"href": "https://app.mem0.ai"
}
},
"footer": {
"socials": {
"discord": "https://mem0.dev/DiD",
"x": "https://x.com/mem0ai",
"github": "https://github.com/mem0ai",
"linkedin": "https://www.linkedin.com/company/mem0/"
}
},
"integrations": {
"posthog": {
"apiKey": "phc_hgJkUVJFYtmaJqrvf6CYN67TIQ8yhXAkWzUn9AMU4yX",
"apiHost": "https://mango.mem0.ai"
},
"intercom": {
"appId": "jjv2r0tt"
}
}
}
+126
View File
@@ -0,0 +1,126 @@
---
title: AI Companion in Node.js
---
You can create a personalised AI Companion using Mem0. This guide will walk you through the necessary steps and provide the complete code to get you started.
## Overview
The Personalized AI Companion leverages Mem0 to retain information across interactions, enabling a tailored learning experience. It creates memories for each user interaction and integrates with OpenAI's GPT models to provide detailed and context-aware responses to user queries.
## Setup
Before you begin, ensure you have Node.js installed and create a new project. Install the required dependencies using npm:
```bash
npm install openai mem0ai
```
## Full Code Example
Below is the complete code to create and interact with an AI Companion using Mem0:
```javascript
import { OpenAI } from 'openai';
import { Memory } from 'mem0ai/oss';
import * as readline from 'readline';
const openaiClient = new OpenAI();
const memory = new Memory();
async function chatWithMemories(message, userId = "default_user") {
const relevantMemories = await memory.search(message, { userId: userId });
const memoriesStr = relevantMemories.results
.map(entry => `- ${entry.memory}`)
.join('\n');
const systemPrompt = `You are a helpful AI. Answer the question based on query and memories.
User Memories:
${memoriesStr}`;
const messages = [
{ role: "system", content: systemPrompt },
{ role: "user", content: message }
];
const response = await openaiClient.chat.completions.create({
model: "gpt-4o-mini",
messages: messages
});
const assistantResponse = response.choices[0].message.content || "";
messages.push({ role: "assistant", content: assistantResponse });
await memory.add(messages, { userId: userId });
return assistantResponse;
}
async function main() {
const rl = readline.createInterface({
input: process.stdin,
output: process.stdout
});
console.log("Chat with AI (type 'exit' to quit)");
const askQuestion = () => {
return new Promise((resolve) => {
rl.question("You: ", (input) => {
resolve(input.trim());
});
});
};
try {
while (true) {
const userInput = await askQuestion();
if (userInput.toLowerCase() === 'exit') {
console.log("Goodbye!");
rl.close();
break;
}
const response = await chatWithMemories(userInput, "sample_user");
console.log(`AI: ${response}`);
}
} catch (error) {
console.error("An error occurred:", error);
rl.close();
}
}
main().catch(console.error);
```
### Key Components
1. **Initialization**
- The code initializes both OpenAI and Mem0 Memory clients
- Uses Node.js's built-in readline module for command-line interaction
2. **Memory Management (chatWithMemories function)**
- Retrieves relevant memories using Mem0's search functionality
- Constructs a system prompt that includes past memories
- Makes API calls to OpenAI for generating responses
- Stores new interactions in memory
3. **Interactive Chat Interface (main function)**
- Creates a command-line interface for user interaction
- Handles user input and displays AI responses
- Includes graceful exit functionality
### Environment Setup
Make sure to set up your environment variables:
```bash
export OPENAI_API_KEY=your_api_key
```
### Conclusion
This implementation demonstrates how to create an AI Companion that maintains context across conversations using Mem0's memory capabilities. The system automatically stores and retrieves relevant information, creating a more personalized and context-aware interaction experience.
As users interact with the system, Mem0's memory system continuously learns and adapts, making future responses more relevant and personalized. This setup is ideal for creating long-term learning AI assistants that can maintain context and provide increasingly personalized responses over time.
+55
View File
@@ -0,0 +1,55 @@
# Mem0 Chrome Extension
Enhance your AI interactions with **Mem0**, a Chrome extension that introduces a universal memory layer across platforms like `ChatGPT`, `Claude`, and `Perplexity`. Mem0 ensures seamless context sharing, making your AI experiences more personalized and efficient.
<Note>
🎉 We now support Grok! The Mem0 Chrome Extension has been updated to work with Grok, bringing the same powerful memory capabilities to your Grok conversations.
</Note>
## Features
- **Universal Memory Layer**: Share context seamlessly across ChatGPT, Claude, Perplexity, and Grok.
- **Smart Context Detection**: Automatically captures relevant information from your conversations.
- **Intelligent Memory Retrieval**: Surfaces pertinent memories at the right time.
- **One-Click Sync**: Easily synchronize with existing ChatGPT memories.
- **Memory Dashboard**: Manage all your memories in one centralized location.
## Installation
You can install the Mem0 Chrome Extension using one of the following methods:
### Method 1: Chrome Web Store Installation
1. **Download the Extension**: Open Google Chrome and navigate to the [Mem0 Chrome Extension page](https://chromewebstore.google.com/detail/mem0/onihkkbipkfeijkadecaafbgagkhglop?hl=en).
2. **Add to Chrome**: Click on the "Add to Chrome" button.
3. **Confirm Installation**: In the pop-up dialog, click "Add extension" to confirm. The Mem0 icon should now appear in your Chrome toolbar.
### Method 2: Manual Installation
1. **Download the Extension**: Clone or download the extension files from the [Mem0 Chrome Extension GitHub repository](https://github.com/mem0ai/mem0-chrome-extension).
2. **Access Chrome Extensions**: Open Google Chrome and navigate to `chrome://extensions`.
3. **Enable Developer Mode**: Toggle the "Developer mode" switch in the top right corner.
4. **Load Unpacked Extension**: Click "Load unpacked" and select the directory containing the extension files.
5. **Confirm Installation**: The Mem0 Chrome Extension should now appear in your Chrome toolbar.
## Usage
1. **Locate the Mem0 Icon**: After installation, find the Mem0 icon in your Chrome toolbar.
2. **Sign In**: Click the icon and sign in with your Google account.
3. **Interact with AI Assistants**:
- **ChatGPT and Perplexity**: Continue your conversations as usual; Mem0 operates seamlessly in the background.
- **Claude**: Click the Mem0 button or use the shortcut `Ctrl + M` to activate memory functions.
## Configuration
- **API Key**: Obtain your API key from the Mem0 Dashboard to connect the extension to the Mem0 API.
- **User ID**: This is your unique identifier in the Mem0 system. If not provided, it defaults to 'chrome-extension-user'.
## Demo Video
<iframe width="700" height="400" src="https://www.youtube.com/embed/dqenCMMlfwQ?si=zhGVrkq6IS_0Jwyj" title="YouTube video player" frameborder="0" allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture; web-share" referrerpolicy="strict-origin-when-cross-origin" allowfullscreen></iframe>
## Privacy and Data Security
Your messages are sent to the Mem0 API for extracting and retrieving memories. Mem0 is committed to ensuring your data's privacy and security.
+2 -2
View File
@@ -94,8 +94,8 @@ You can fetch all the memories at any point in time using the following code:
```python
memories = support_agent.get_memories(user_id=customer_id)
for m in memories:
print(m['text'])
for m in memories['results']:
print(m['memory'])
```
### Key Points
+184
View File
@@ -0,0 +1,184 @@
---
title: Document Editing with Mem0
---
This guide demonstrates how to leverage **Mem0** to edit documents efficiently, ensuring they align with your unique writing style and preferences.
## **Why Use Mem0?**
By integrating Mem0 into your workflow, you can streamline your document editing process with:
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.
---
## **Setup**
```python
import os
from mem0 import MemoryClient
# Set up Mem0 client
os.environ["MEM0_API_KEY"] = "your-mem0-api-key"
client = MemoryClient()
# 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).
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"},
{"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.")
return response
```
---
## **Editing Documents with Mem0**
```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.")
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
```
---
## **Complete Workflow: Document Editing**
```python
def document_editing_workflow(content):
"""Automated workflow for editing a document based on writing preferences."""
# Step 1: Store writing preferences (if not already stored)
store_writing_preferences()
# Step 2: Edit the document with Mem0 preferences
edited_content = edit_document_based_on_preferences(content)
if not edited_content:
return "Failed to edit document."
# Step 3: Display results
print("\n=== ORIGINAL DOCUMENT ===\n")
print(content)
print("\n=== EDITED DOCUMENT ===\n")
print(edited_content)
return edited_content
```
---
## **Example Usage**
```python
# Define your document
original_content = """Project Proposal
The following proposal outlines our strategy for the Q3 marketing campaign.
We believe this approach will significantly increase our market share.
Increase brand awareness
Boost sales by 15%
Expand our social media following
We plan to launch the campaign in July and continue through September.
"""
# Run the workflow
result = document_editing_workflow(original_content)
```
---
## **Expected Output**
Your document will be transformed into a structured, well-formatted version based on your preferences.
### **Original Document**
```
Project Proposal
The following proposal outlines our strategy for the Q3 marketing campaign.
We believe this approach will significantly increase our market share.
Increase brand awareness
Boost sales by 15%
Expand our social media following
We plan to launch the campaign in July and continue through September.
```
### **Edited Document**
```
# **Project Proposal**
## **Q3 Marketing Campaign Strategy**
This proposal outlines our strategy for the Q3 marketing campaign. We aim to significantly increase our market share with this approach.
### **Objectives**
- **Increase Brand Awareness**: Implement targeted advertising and community engagement to enhance visibility.
- **Boost Sales by 15%**: Increase sales by 15% compared to Q2 figures.
- **Expand Social Media Following**: Grow our social media audience by 20%.
### **Timeline**
- **Launch Date**: July
- **Duration**: July – September
### **Key Actions**
- **Targeted Advertising**: Utilize platforms like Google Ads and Facebook to reach specific demographics.
- **Community Engagement**: Host webinars and live Q&A sessions.
- **Content Creation**: Produce engaging videos and infographics.
### **Supporting Data**
- **Previous Campaign Success**: Our Q2 campaign increased sales by 12%. We will refine similar strategies for Q3.
- **Social Media Growth**: Last year, our Instagram followers grew by 25% during a similar campaign.
### **Conclusion**
We believe this strategy will effectively increase our market share. To achieve these goals, we need your support and collaboration. Let’s work together to make this campaign a success. Please review the proposal and provide your feedback by the end of the week.
```
Mem0 creates a seamless, intelligent document editing experience—perfect for content creators, technical writers, and businesses alike!
+226
View File
@@ -0,0 +1,226 @@
---
title: Mem0 as an Agentic Tool
---
Integrate Mem0's memory capabilities with OpenAI's Agents SDK to create AI agents with persistent memory.
You can create agents that remember past conversations and use that context to provide better responses.
## Installation
First, install the required packages:
```bash
pip install mem0ai pydantic openai-agents
```
You'll also need a custom agents framework for this implementation.
## Setting Up Environment Variables
Store your Mem0 API key as an environment variable:
```bash
export MEM0_API_KEY="your_mem0_api_key"
```
Or in your Python script:
```python
import os
os.environ["MEM0_API_KEY"] = "your_mem0_api_key"
```
## Code Structure
The integration consists of three main components:
1. **Context Manager**: Defines user context for memory operations
2. **Memory Tools**: Functions to add, search, and retrieve memories
3. **Memory Agent**: An agent configured to use these memory tools
## Step-by-Step Implementation
### 1. Import Dependencies
```python
from __future__ import annotations
import os
import asyncio
from pydantic import BaseModel
try:
from mem0 import AsyncMemoryClient
except ImportError:
raise ImportError("mem0 is not installed. Please install it using 'pip install mem0ai'.")
from agents import (
Agent,
ItemHelpers,
MessageOutputItem,
RunContextWrapper,
Runner,
ToolCallItem,
ToolCallOutputItem,
TResponseInputItem,
function_tool,
)
```
### 2. Define Memory Context
```python
class Mem0Context(BaseModel):
user_id: str | None = None
```
### 3. Initialize the Mem0 Client
```python
client = AsyncMemoryClient(api_key=os.getenv("MEM0_API_KEY"))
```
### 4. Create Memory Tools
#### Add to Memory
```python
@function_tool
async def add_to_memory(
context: RunContextWrapper[Mem0Context],
content: str,
) -> str:
"""
Add a message to Mem0
Args:
content: The content to store in memory.
"""
messages = [{"role": "user", "content": content}]
user_id = context.context.user_id or "default_user"
await client.add(messages, user_id=user_id)
return f"Stored message: {content}"
```
#### Search Memory
```python
@function_tool
async def search_memory(
context: RunContextWrapper[Mem0Context],
query: str,
) -> str:
"""
Search for memories in Mem0
Args:
query: The search query.
"""
user_id = context.context.user_id or "default_user"
memories = await client.search(query, user_id=user_id, output_format="v1.1")
results = '\n'.join([result["memory"] for result in memories["results"]])
return str(results)
```
#### Get All Memories
```python
@function_tool
async def get_all_memory(
context: RunContextWrapper[Mem0Context],
) -> str:
"""Retrieve all memories from Mem0"""
user_id = context.context.user_id or "default_user"
memories = await client.get_all(user_id=user_id, output_format="v1.1")
results = '\n'.join([result["memory"] for result in memories["results"]])
return str(results)
```
### 5. Configure the Memory Agent
```python
memory_agent = Agent[Mem0Context](
name="Memory Assistant",
instructions="""You are a helpful assistant with memory capabilities. You can:
1. Store new information using add_to_memory
2. Search existing information using search_memory
3. Retrieve all stored information using get_all_memory
When users ask questions:
- If they want to store information, use add_to_memory
- If they're searching for specific information, use search_memory
- If they want to see everything stored, use get_all_memory""",
tools=[add_to_memory, search_memory, get_all_memory],
)
```
### 6. Implement the Main Runtime Loop
```python
async def main():
current_agent: Agent[Mem0Context] = memory_agent
input_items: list[TResponseInputItem] = []
context = Mem0Context()
while True:
user_input = input("Enter your message (or 'quit' to exit): ")
if user_input.lower() == 'quit':
break
input_items.append({"content": user_input, "role": "user"})
result = await Runner.run(current_agent, input_items, context=context)
for new_item in result.new_items:
agent_name = new_item.agent.name
if isinstance(new_item, MessageOutputItem):
print(f"{agent_name}: {ItemHelpers.text_message_output(new_item)}")
elif isinstance(new_item, ToolCallItem):
print(f"{agent_name}: Calling a tool")
elif isinstance(new_item, ToolCallOutputItem):
print(f"{agent_name}: Tool call output: {new_item.output}")
else:
print(f"{agent_name}: Skipping item: {new_item.__class__.__name__}")
input_items = result.to_input_list()
if __name__ == "__main__":
asyncio.run(main())
```
## Usage Examples
### Storing Information
```
User: Remember that my favorite color is blue
Agent: Calling a tool
Agent: Tool call output: Stored message: my favorite color is blue
Agent: I've stored that your favorite color is blue in my memory. I'll remember that for future conversations.
```
### Searching Memory
```
User: What's my favorite color?
Agent: Calling a tool
Agent: Tool call output: my favorite color is blue
Agent: Your favorite color is blue, based on what you've told me earlier.
```
### Retrieving All Memories
```
User: What do you know about me?
Agent: Calling a tool
Agent: Tool call output: favorite color is blue
my birthday is on March 15
Agent: Based on our previous conversations, I know that:
1. Your favorite color is blue
2. Your birthday is on March 15
```
## Advanced Configuration
### Custom User IDs
You can specify different user IDs to maintain separate memory stores for multiple users:
```python
context = Mem0Context(user_id="user123")
```
## Resources
- [Mem0 Documentation](https://docs.mem0.ai)
- [Mem0 Dashboard](https://app.mem0.ai/dashboard)
- [API Reference](https://docs.mem0.ai/api-reference)
+68
View File
@@ -0,0 +1,68 @@
---
title: Mem0 Demo
---
You can create a personalized AI Companion using Mem0. This guide will walk you through the necessary steps and provide the complete setup instructions to get you started.
<video
autoPlay
muted
loop
playsInline
className="w-full aspect-video rounded-lg"
src="https://github.com/user-attachments/assets/cebc4f8e-bdb9-4837-868d-13c5ab7bb433"
></video>
You can try the [Mem0 Demo](https://mem0.dev/demo) live here.
## Overview
The Personalized AI Companion leverages Mem0 to retain information across interactions, enabling a tailored learning experience. It creates memories for each user interaction and integrates with OpenAI's GPT models to provide detailed and context-aware responses to user queries.
## Setup
Before you begin, follow these steps to set up the demo application:
1. Clone the Mem0 repository:
```bash
git clone https://github.com/mem0ai/mem0.git
```
2. Navigate to the demo application folder:
```bash
cd mem0/examples/mem0-demo
```
3. Install dependencies:
```bash
pnpm install
```
4. Set up environment variables by creating a `.env` file in the project root with the following content:
```bash
OPENAI_API_KEY=your_openai_api_key
MEM0_API_KEY=your_mem0_api_key
```
You can obtain your `MEM0_API_KEY` by signing up at [Mem0 API Dashboard](https://app.mem0.ai/dashboard/api-keys).
5. Start the development server:
```bash
pnpm run dev
```
## Enhancing the Next.js Application
Once the demo is running, you can customize and enhance the Next.js application by modifying the components in the `mem0-demo` folder. Consider:
- Adding new memory features to improve contextual retention.
- Customizing the UI to better suit your application needs.
- Integrating additional APIs or third-party services to extend functionality.
## Full Code
You can find the complete source code for this demo on GitHub:
[Mem0 Demo GitHub](https://github.com/mem0ai/mem0/tree/main/examples/mem0-demo)
## Conclusion
This setup demonstrates how to build an AI Companion that maintains memory across interactions using Mem0. The system continuously adapts to user interactions, making future responses more relevant and personalized. Experiment with the application and enhance it further to suit your use case!
+538
View File
@@ -0,0 +1,538 @@
---
title: 'Mem0 with OpenAI Agents SDK for Voice'
description: 'Integrate memory capabilities into your voice agents using Mem0 and OpenAI Agents SDK'
---
# Building Voice Agents with Memory using Mem0 and OpenAI Agents SDK
This guide demonstrates how to combine OpenAI's Agents SDK for voice applications with Mem0's memory capabilities to create a voice assistant that remembers user preferences and past interactions.
## Prerequisites
Before you begin, make sure you have:
1. Installed OpenAI Agents SDK with voice dependencies:
```bash
pip install 'openai-agents[voice]'
```
2. Installed Mem0 SDK:
```bash
pip install mem0ai
```
3. Installed other required dependencies:
```bash
pip install numpy sounddevice pydantic
```
4. Set up your API keys:
- OpenAI API key for the Agents SDK
- Mem0 API key from the Mem0 Platform
## Code Breakdown
Let's break down the key components of this implementation:
### 1. Setting Up Dependencies and Environment
```python
# OpenAI Agents SDK imports
from agents import (
Agent,
function_tool
)
from agents.voice import (
AudioInput,
SingleAgentVoiceWorkflow,
VoicePipeline
)
from agents.extensions.handoff_prompt import prompt_with_handoff_instructions
# Mem0 imports
from mem0 import AsyncMemoryClient
# Set up API keys (replace with your actual keys)
os.environ["OPENAI_API_KEY"] = "your-openai-api-key"
os.environ["MEM0_API_KEY"] = "your-mem0-api-key"
# Define a global user ID for simplicity
USER_ID = "voice_user"
# Initialize Mem0 client
mem0_client = AsyncMemoryClient()
```
This section handles:
- Importing required modules from OpenAI Agents SDK and Mem0
- Setting up environment variables for API keys
- Defining a simple user identification system (using a global variable)
- Initializing the Mem0 client that will handle memory operations
### 2. Memory Tools with Function Decorators
The `@function_tool` decorator transforms Python functions into callable tools for the OpenAI agent. Here are the key memory tools:
#### Storing User Memories
```python
import logging
# Set up logging at the top of your file
logging.basicConfig(
level=logging.DEBUG,
format='%(asctime)s - %(name)s - %(levelname)s - %(message)s',
force=True
)
logger = logging.getLogger("memory_voice_agent")
# Then use logger in your function tools
@function_tool
async def save_memories(
memory: str
) -> str:
"""Store a user memory in memory."""
# This will be visible in your console
logger.debug(f"Saving memory: {memory} for user {USER_ID}")
# Store the preference in Mem0
memory_content = f"User memory - {memory}"
await mem0_client.add(
memory_content,
user_id=USER_ID,
)
return f"I've saved your memory: {memory}"
```
This function:
- Takes a memory string
- Creates a formatted memory string
- Stores it in Mem0 using the `add()` method
- Includes metadata to categorize the memory for easier retrieval
- Returns a confirmation message that the agent will speak
#### Finding Relevant Memories
```python
@function_tool
async def search_memories(
query: str
) -> str:
"""
Find memories relevant to the current conversation.
Args:
query: The search query to find relevant memories
"""
print(f"Finding memories related to: {query}")
results = await mem0_client.search(
query,
user_id=USER_ID,
limit=5,
threshold=0.7, # Higher threshold for more relevant results
output_format="v1.1"
)
# Format and return the results
if not results.get('results', []):
return "I don't have any relevant memories about this topic."
memories = [f"• {result['memory']}" for result in results.get('results', [])]
return "Here's what I remember that might be relevant:\n" + "\n".join(memories)
```
This tool:
- Takes a search query string
- Passes it to Mem0's semantic search to find related memories
- Sets a threshold for relevance to ensure quality results
- Returns a formatted list of relevant memories or a default message
### 3. Creating the Voice Agent
```python
def create_memory_voice_agent():
# Create the agent with memory-enabled tools
agent = Agent(
name="Memory Assistant",
instructions=prompt_with_handoff_instructions(
"""You're speaking to a human, so be polite and concise.
Always respond in clear, natural English.
You have the ability to remember information about the user.
Use the save_memories tool when the user shares an important information worth remembering.
Use the search_memories tool when you need context from past conversations or user asks you to recall something.
""",
),
model="gpt-4o",
tools=[save_memories, search_memories],
)
return agent
```
This function:
- Creates an OpenAI Agent with specific instructions
- Configures it to use gpt-4o (you can use other models)
- Registers the memory-related tools with the agent
- Uses `prompt_with_handoff_instructions` to include standard voice agent behaviors
### 4. Microphone Recording Functionality
```python
async def record_from_microphone(duration=5, samplerate=24000):
"""Record audio from the microphone for a specified duration."""
print(f"Recording for {duration} seconds...")
# Create a buffer to store the recorded audio
frames = []
# Callback function to store audio data
def callback(indata, frames_count, time_info, status):
frames.append(indata.copy())
# Start recording
with sd.InputStream(samplerate=samplerate, channels=1, callback=callback, dtype=np.int16):
await asyncio.sleep(duration)
# Combine all frames into a single numpy array
audio_data = np.concatenate(frames)
return audio_data
```
This function:
- Creates a simple asynchronous microphone recording function
- Uses the sounddevice library to capture audio input
- Stores frames in a buffer during recording
- Combines frames into a single numpy array when complete
- Returns the audio data for processing
### 5. Main Loop and Voice Processing
```python
async def main():
# Create the agent
agent = create_memory_voice_agent()
# Set up the voice pipeline
pipeline = VoicePipeline(
workflow=SingleAgentVoiceWorkflow(agent)
)
# Configure TTS settings
pipeline.config.tts_settings.voice = "alloy"
pipeline.config.tts_settings.speed = 1.0
try:
while True:
# Get user input
print("\nPress Enter to start recording (or 'q' to quit)...")
user_input = input()
if user_input.lower() == 'q':
break
# Record and process audio
audio_data = await record_from_microphone(duration=5)
audio_input = AudioInput(buffer=audio_data)
result = await pipeline.run(audio_input)
# Play response and handle events
player = sd.OutputStream(samplerate=24000, channels=1, dtype=np.int16)
player.start()
agent_response = ""
print("\nAgent response:")
async for event in result.stream():
if event.type == "voice_stream_event_audio":
player.write(event.data)
elif event.type == "voice_stream_event_content":
content = event.data
agent_response += content
print(content, end="", flush=True)
# Save the agent's response to memory
if agent_response:
try:
await mem0_client.add(
f"Agent response: {agent_response}",
user_id=USER_ID,
metadata={"type": "agent_response"}
)
except Exception as e:
print(f"Failed to store memory: {e}")
except KeyboardInterrupt:
print("\nExiting...")
```
This main function orchestrates the entire process:
1. Creates the memory-enabled voice agent
2. Sets up the voice pipeline with TTS settings
3. Implements an interactive loop for recording and processing voice input
4. Handles streaming of response events (both audio and text)
5. Automatically saves the agent's responses to memory
6. Includes proper error handling and exit mechanisms
## Create a Memory-Enabled Voice Agent
Now that we've explained each component, here's the complete implementation that combines OpenAI Agents SDK for voice with Mem0's memory capabilities:
```python
import asyncio
import os
import logging
from typing import Optional, List, Dict, Any
import numpy as np
import sounddevice as sd
from pydantic import BaseModel
# OpenAI Agents SDK imports
from agents import (
Agent,
function_tool
)
from agents.voice import (
AudioInput,
SingleAgentVoiceWorkflow,
VoicePipeline
)
from agents.extensions.handoff_prompt import prompt_with_handoff_instructions
# Mem0 imports
from mem0 import AsyncMemoryClient
# Set up API keys (replace with your actual keys)
os.environ["OPENAI_API_KEY"] = "your-openai-api-key"
os.environ["MEM0_API_KEY"] = "your-mem0-api-key"
# Define a global user ID for simplicity
USER_ID = "voice_user"
# Initialize Mem0 client
mem0_client = AsyncMemoryClient()
# Create tools that utilize Mem0's memory
@function_tool
async def save_memories(
memory: str
) -> str:
"""
Store a user memory in memory.
Args:
memory: The memory to save
"""
print(f"Saving memory: {memory} for user {USER_ID}")
# Store the preference in Mem0
memory_content = f"User memory - {memory}"
await mem0_client.add(
memory_content,
user_id=USER_ID,
)
return f"I've saved your memory: {memory}"
@function_tool
async def search_memories(
query: str
) -> str:
"""
Find memories relevant to the current conversation.
Args:
query: The search query to find relevant memories
"""
print(f"Finding memories related to: {query}")
results = await mem0_client.search(
query,
user_id=USER_ID,
limit=5,
threshold=0.7, # Higher threshold for more relevant results
output_format="v1.1"
)
# Format and return the results
if not results.get('results', []):
return "I don't have any relevant memories about this topic."
memories = [f"• {result['memory']}" for result in results.get('results', [])]
return "Here's what I remember that might be relevant:\n" + "\n".join(memories)
# Create the agent with memory-enabled tools
def create_memory_voice_agent():
# Create the agent with memory-enabled tools
agent = Agent(
name="Memory Assistant",
instructions=prompt_with_handoff_instructions(
"""You're speaking to a human, so be polite and concise.
Always respond in clear, natural English.
You have the ability to remember information about the user.
Use the save_memories tool when the user shares an important information worth remembering.
Use the search_memories tool when you need context from past conversations or user asks you to recall something.
""",
),
model="gpt-4o",
tools=[save_memories, search_memories],
)
return agent
async def record_from_microphone(duration=5, samplerate=24000):
"""Record audio from the microphone for a specified duration."""
print(f"Recording for {duration} seconds...")
# Create a buffer to store the recorded audio
frames = []
# Callback function to store audio data
def callback(indata, frames_count, time_info, status):
frames.append(indata.copy())
# Start recording
with sd.InputStream(samplerate=samplerate, channels=1, callback=callback, dtype=np.int16):
await asyncio.sleep(duration)
# Combine all frames into a single numpy array
audio_data = np.concatenate(frames)
return audio_data
async def main():
print("Starting Memory Voice Agent")
# Create the agent and context
agent = create_memory_voice_agent()
# Set up the voice pipeline
pipeline = VoicePipeline(
workflow=SingleAgentVoiceWorkflow(agent)
)
# Configure TTS settings
pipeline.config.tts_settings.voice = "alloy"
pipeline.config.tts_settings.speed = 1.0
try:
while True:
# Get user input
print("\nPress Enter to start recording (or 'q' to quit)...")
user_input = input()
if user_input.lower() == 'q':
break
# Record and process audio
audio_data = await record_from_microphone(duration=5)
audio_input = AudioInput(buffer=audio_data)
print("Processing your request...")
# Process the audio input
result = await pipeline.run(audio_input)
# Create an audio player
player = sd.OutputStream(samplerate=24000, channels=1, dtype=np.int16)
player.start()
# Store the agent's response for adding to memory
agent_response = ""
print("\nAgent response:")
# Play the audio stream as it comes in
async for event in result.stream():
if event.type == "voice_stream_event_audio":
player.write(event.data)
elif event.type == "voice_stream_event_content":
# Accumulate and print the text response
content = event.data
agent_response += content
print(content, end="", flush=True)
print("\n")
# Example of saving the conversation to Mem0 after completion
if agent_response:
try:
await mem0_client.add(
f"Agent response: {agent_response}",
user_id=USER_ID,
metadata={"type": "agent_response"}
)
except Exception as e:
print(f"Failed to store memory: {e}")
except KeyboardInterrupt:
print("\nExiting...")
if __name__ == "__main__":
asyncio.run(main())
```
## Key Features of This Implementation
This implementation offers several key features:
1. **Simplified User Management**: Uses a global `USER_ID` variable for simplicity, but can be extended to manage multiple users.
2. **Real Microphone Input**: Includes a `record_from_microphone()` function that captures actual voice input from your microphone.
3. **Interactive Voice Loop**: Implements a continuous interaction loop, allowing for multiple back-and-forth exchanges.
4. **Memory Management Tools**:
- `save_memories`: Stores user memories in Mem0
- `search_memories`: Searches for relevant past information
5. **Voice Configuration**: Demonstrates how to configure TTS settings for the voice response.
## Running the Example
To run this example:
1. Replace the placeholder API keys with your actual keys
2. Make sure your microphone is properly connected
3. Run the script with Python 3.8 or newer
4. Press Enter to start recording, then speak your request
5. Press 'q' to quit the application
The agent will listen to your request, process it through the OpenAI model, utilize Mem0 for memory operations as needed, and respond both through text output and voice speech.
## Best Practices for Voice Agents with Memory
1. **Optimizing Memory for Voice**: Keep memories concise and relevant for voice responses.
2. **Forgetting Mechanism**: Implement a way to delete or expire memories that are no longer relevant.
3. **Context Preservation**: Store enough context with each memory to make retrieval effective.
4. **Error Handling**: Implement robust error handling for memory operations, as voice interactions should continue smoothly even if memory operations fail.
## Conclusion
By combining OpenAI's Agents SDK with Mem0's memory capabilities, you can create voice agents that maintain persistent memory of user preferences and past interactions. This significantly enhances the user experience by making conversations more natural and personalized.
As you build your voice application, experiment with different memory strategies and filtering approaches to find the optimal balance between comprehensive memory and efficient retrieval for your specific use case.
## Debugging Function Tools
When working with the OpenAI Agents SDK, you might notice that regular `print()` statements inside `@function_tool` decorated functions don't appear in your console output. This is because the Agents SDK captures and redirects standard output when executing these functions.
To effectively debug your function tools, use Python's `logging` module instead:
```python
import logging
# Set up logging at the top of your file
logging.basicConfig(
level=logging.DEBUG,
format='%(asctime)s - %(name)s - %(levelname)s - %(message)s',
force=True
)
logger = logging.getLogger("memory_voice_agent")
# Then use logger in your function tools
@function_tool
async def save_memories(
memory: str
) -> str:
"""Store a user memory in memory."""
# This will be visible in your console
logger.debug(f"Saving memory: {memory} for user {USER_ID}")
# Rest of your function...
```
+1 -1
View File
@@ -37,7 +37,7 @@ config = {
"config": {
"model": "llama3.1:latest",
"temperature": 0,
"max_tokens": 8000,
"max_tokens": 2000,
"ollama_base_url": "http://localhost:11434", # Ensure this URL is correct
},
},
+31
View File
@@ -0,0 +1,31 @@
---
title: Multimodal Demo with Mem0
---
Enhance your AI interactions with **Mem0**'s multimodal capabilities. Mem0 now supports image understanding, allowing for richer context and more natural interactions across supported AI platforms.
> 🎉 Experience the power of multimodal AI! Test out Mem0's image understanding capabilities at [multimodal-demo.mem0.ai](https://multimodal-demo.mem0.ai)
## 🚀 Features
- **🖼️ Image Understanding**: Share and discuss images with AI assistants while maintaining context.
- **🔍 Smart Visual Context**: Automatically capture and reference visual elements in conversations.
- **🔗 Cross-Modal Memory**: Link visual and textual information seamlessly in your memory layer.
- **📌 Cross-Session Recall**: Reference previously discussed visual content across different conversations.
- **⚡ Seamless Integration**: Works naturally with existing chat interfaces for a smooth experience.
## 📖 How It Works
1. **📂 Upload Visual Content**: Simply drag and drop or paste images into your conversations.
2. **💬 Natural Interaction**: Discuss the visual content naturally with AI assistants.
3. **📚 Memory Integration**: Visual context is automatically stored and linked with your conversation history.
4. **🔄 Persistent Recall**: Retrieve and reference past visual content effortlessly.
## Demo Video
<iframe width="700" height="400" src="https://www.youtube.com/embed/2Md5AEFVpmg?si=rXXupn6CiDUPJsi3" title="YouTube video player" frameborder="0" allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture; web-share" referrerpolicy="strict-origin-when-cross-origin" allowfullscreen></iframe>
## 🔥 Try It Out
Visit [multimodal-demo.mem0.ai](https://multimodal-demo.mem0.ai) to experience Mem0's multimodal capabilities firsthand. Upload images and see how Mem0 understands and remembers visual context across your conversations.
+312
View File
@@ -0,0 +1,312 @@
---
title: OpenAI Inbuilt Tools
---
Integrate Mem0’s memory capabilities with OpenAI’s Inbuilt Tools to create AI agents with persistent memory.
## Getting Started
### Installation
```bash
npm install mem0ai openai zod
```
## Environment Setup
Save your Mem0 and OpenAI API keys in a `.env` file:
```
MEM0_API_KEY=your_mem0_api_key
OPENAI_API_KEY=your_openai_api_key
```
Get your Mem0 API key from the [Mem0 Dashboard](https://app.mem0.ai/dashboard/api-keys).
### Configuration
```javascript
const mem0Config = {
apiKey: process.env.MEM0_API_KEY,
user_id: "sample-user",
};
const openAIClient = new OpenAI();
const mem0Client = new MemoryClient(mem0Config);
```
### Adding Memories
Store user preferences, past interactions, or any relevant information:
<CodeGroup>
```javascript JavaScript
async function addUserPreferences() {
const mem0Client = new MemoryClient(mem0Config);
const userPreferences = "I Love BMW, Audi and Porsche. I Hate Mercedes. I love Red cars and Maroon cars. I have a budget of 120K to 150K USD. I like Audi the most.";
await mem0Client.add([{
role: "user",
content: userPreferences,
}], mem0Config);
}
await addUserPreferences();
```
```json Output (Memories)
[
{
"id": "ff9f3367-9e83-415d-b9c5-dc8befd9a4b4",
"data": { "memory": "Loves BMW, Audi, and Porsche" },
"event": "ADD"
},
{
"id": "04172ce6-3d7b-45a3-b4a1-ee9798593cb4",
"data": { "memory": "Hates Mercedes" },
"event": "ADD"
},
{
"id": "db363a5d-d258-4953-9e4c-777c120de34d",
"data": { "memory": "Loves red cars and maroon cars" },
"event": "ADD"
},
{
"id": "5519aaad-a2ac-4c0d-81d7-0d55c6ecdba8",
"data": { "memory": "Has a budget of 120K to 150K USD" },
"event": "ADD"
},
{
"id": "523b7693-7344-4563-922f-5db08edc8634",
"data": { "memory": "Likes Audi the most" },
"event": "ADD"
}
]
```
</CodeGroup>
### Retrieving Memories
Search for relevant memories based on the current user input:
```javascript
const relevantMemories = await mem0Client.search(userInput, mem0Config);
```
### Structured Responses with Zod
Define structured response schemas to get consistent output formats:
```javascript
// Define the schema for a car recommendation
const CarSchema = z.object({
car_name: z.string(),
car_price: z.string(),
car_url: z.string(),
car_image: z.string(),
car_description: z.string(),
});
// Schema for a list of car recommendations
const Cars = z.object({
cars: z.array(CarSchema),
});
// Create a function tool based on the schema
const carRecommendationTool = zodResponsesFunction({
name: "carRecommendations",
parameters: Cars
});
// Use the tool in your OpenAI request
const response = await openAIClient.responses.create({
model: "gpt-4o",
tools: [{ type: "web_search_preview" }, carRecommendationTool],
input: `${getMemoryString(relevantMemories)}\n${userInput}`,
});
```
### Using Web Search
Combine memory with web search for up-to-date recommendations:
```javascript
const response = await openAIClient.responses.create({
model: "gpt-4o",
tools: [{ type: "web_search_preview" }, carRecommendationTool],
input: `${getMemoryString(relevantMemories)}\n${userInput}`,
});
```
## Examples
### Complete Car Recommendation System
```javascript
import MemoryClient from "mem0ai";
import { OpenAI } from "openai";
import { zodResponsesFunction } from "openai/helpers/zod";
import { z } from "zod";
import dotenv from 'dotenv';
dotenv.config();
const mem0Config = {
apiKey: process.env.MEM0_API_KEY,
user_id: "sample-user",
};
async function run() {
// Responses without memories
console.log("\n\nRESPONSES WITHOUT MEMORIES\n\n");
await main();
// Adding sample memories
await addSampleMemories();
// Responses with memories
console.log("\n\nRESPONSES WITH MEMORIES\n\n");
await main(true);
}
// OpenAI Response Schema
const CarSchema = z.object({
car_name: z.string(),
car_price: z.string(),
car_url: z.string(),
car_image: z.string(),
car_description: z.string(),
});
const Cars = z.object({
cars: z.array(CarSchema),
});
async function main(memory = false) {
const openAIClient = new OpenAI();
const mem0Client = new MemoryClient(mem0Config);
const input = "Suggest me some cars that I can buy today.";
const tool = zodResponsesFunction({ name: "carRecommendations", parameters: Cars });
// Store the user input as a memory
await mem0Client.add([{
role: "user",
content: input,
}], mem0Config);
// Search for relevant memories
let relevantMemories = []
if (memory) {
relevantMemories = await mem0Client.search(input, mem0Config);
}
const response = await openAIClient.responses.create({
model: "gpt-4o",
tools: [{ type: "web_search_preview" }, tool],
input: `${getMemoryString(relevantMemories)}\n${input}`,
});
console.log(response.output);
}
async function addSampleMemories() {
const mem0Client = new MemoryClient(mem0Config);
const myInterests = "I Love BMW, Audi and Porsche. I Hate Mercedes. I love Red cars and Maroon cars. I have a budget of 120K to 150K USD. I like Audi the most.";
await mem0Client.add([{
role: "user",
content: myInterests,
}], mem0Config);
}
const getMemoryString = (memories) => {
const MEMORY_STRING_PREFIX = "These are the memories I have stored. Give more weightage to the question by users and try to answer that first. You have to modify your answer based on the memories I have provided. If the memories are irrelevant you can ignore them. Also don't reply to this section of the prompt, or the memories, they are only for your reference. The MEMORIES of the USER are: \n\n";
const memoryString = memories.map((mem) => `${mem.memory}`).join("\n") ?? "";
return memoryString.length > 0 ? `${MEMORY_STRING_PREFIX}${memoryString}` : "";
};
run().catch(console.error);
```
### Responses
<CodeGroup>
```json Without Memories
{
"cars": [
{
"car_name": "Toyota Camry",
"car_price": "$25,000",
"car_url": "https://www.toyota.com/camry/",
"car_image": "https://link-to-toyota-camry-image.com",
"car_description": "Reliable mid-size sedan with great fuel efficiency."
},
{
"car_name": "Honda Accord",
"car_price": "$26,000",
"car_url": "https://www.honda.com/accord/",
"car_image": "https://link-to-honda-accord-image.com",
"car_description": "Comfortable and spacious with advanced safety features."
},
{
"car_name": "Ford Mustang",
"car_price": "$28,000",
"car_url": "https://www.ford.com/mustang/",
"car_image": "https://link-to-ford-mustang-image.com",
"car_description": "Iconic sports car with powerful engine options."
},
{
"car_name": "Tesla Model 3",
"car_price": "$38,000",
"car_url": "https://www.tesla.com/model3",
"car_image": "https://link-to-tesla-model3-image.com",
"car_description": "Electric vehicle with advanced technology and long range."
},
{
"car_name": "Chevrolet Equinox",
"car_price": "$24,000",
"car_url": "https://www.chevrolet.com/equinox/",
"car_image": "https://link-to-chevron-equinox-image.com",
"car_description": "Compact SUV with a spacious interior and user-friendly technology."
}
]
}
```
```json With Memories
{
"cars": [
{
"car_name": "Audi RS7",
"car_price": "$118,500",
"car_url": "https://www.audiusa.com/us/web/en/models/rs7/2023/overview.html",
"car_image": "https://www.audiusa.com/content/dam/nemo/us/models/rs7/my23/gallery/1920x1080_AOZ_A717_191004.jpg",
"car_description": "The Audi RS7 is a high-performance hatchback with a sleek design, powerful 591-hp twin-turbo V8, and luxurious interior. It's available in various colors including red."
},
{
"car_name": "Porsche Panamera GTS",
"car_price": "$129,300",
"car_url": "https://www.porsche.com/usa/models/panamera/panamera-models/panamera-gts/",
"car_image": "https://files.porsche.com/filestore/image/multimedia/noneporsche-panamera-gts-sample-m02-high/normal/8a6327c3-6c7f-4c6f-a9a8-fb9f58b21795;sP;twebp/porsche-normal.webp",
"car_description": "The Porsche Panamera GTS is a luxury sports sedan with a 473-hp V8 engine, exquisite handling, and available in stunning red. Balances sportiness and comfort."
},
{
"car_name": "BMW M5",
"car_price": "$105,500",
"car_url": "https://www.bmwusa.com/vehicles/m-models/m5/sedan/overview.html",
"car_image": "https://www.bmwusa.com/content/dam/bmwusa/M/m5/2023/bmw-my23-m5-sapphire-black-twilight-purple-exterior-02.jpg",
"car_description": "The BMW M5 is a powerhouse sedan with a 600-hp V8 engine, known for its great handling and luxury. It comes in several distinctive colors including maroon."
}
]
}
```
</CodeGroup>
## Resources
- [Mem0 Documentation](https://docs.mem0.ai)
- [Mem0 Dashboard](https://app.mem0.ai/dashboard)
- [API Reference](https://docs.mem0.ai/api-reference)
- [OpenAI Documentation](https://platform.openai.com/docs)
+54 -16
View File
@@ -16,20 +16,58 @@ Here are some examples of how Mem0 can be integrated into various applications:
## Examples
<CardGroup cols={2}>
<Card title="Mem0 with Ollama" icon="square-1" href="/examples/mem0-with-ollama">
Run Mem0 locally with Ollama.
</Card>
<Card title="Personal AI Tutor" icon="square-2" href="/examples/personal-ai-tutor">
Create a Personalized AI Tutor that adapts to student progress and learning preferences.
</Card>
<Card title="Personal Travel Assistant" icon="square-3" href="/examples/personal-travel-assistant">
Build a Personalized AI Travel Assistant that understands your travel preferences and past itineraries.
</Card>
<Card title="Customer Support Agent" icon="square-4" href="/examples/customer-support-agent">
Develop a Personal AI Assistant that remembers user preferences, past interactions, and context to provide personalized and efficient assistance.
</Card>
<Card title="LlamaIndex Mem0" icon="square-5" href="/examples/llama-index-mem0">
Create a ReAct Agent with LlamaIndex which uses Mem0 as the memory store.
</Card>
Explore how **Mem0** can power real-world applications and bring personalized, intelligent experiences to life:
<CardGroup cols={2}>
<Card title="AI Companion in Node.js" icon="node" href="/examples/ai_companion_js">
Build a personalized AI Companion in **Node.js** that remembers conversations and adapts over time using Mem0.
</Card>
<Card title="Mem0 with Ollama" icon="server" href="/examples/mem0-with-ollama">
Run **Mem0 locally** with **Ollama** to create private, stateful AI experiences without relying on cloud APIs.
</Card>
<Card title="Personal AI Tutor" icon="graduation-cap" href="/examples/personal-ai-tutor">
Create an **AI Tutor** that adapts to student progress, learning style, and history — for a truly customized learning experience.
</Card>
<Card title="Personal Travel Assistant" icon="plane" href="/examples/personal-travel-assistant">
Develop a **Personal Travel Assistant** that remembers your preferences, past trips, and helps plan future adventures.
</Card>
<Card title="Customer Support Agent" icon="headset" href="/examples/customer-support-agent">
Build a **Customer Support AI** that recalls user preferences, past chats, and provides context-aware, efficient help.
</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="Document Writing Assistant" icon="pen" href="/examples/document-writing">
Create a **Writing Assistant** that understands and adapts to your unique style, improving consistency and productivity.
</Card>
<Card title="Multimodal AI Demo" icon="image" href="/examples/multimodal-demo">
Supercharge AI with **Mem0's multimodal memory** — blend text, images, and more for richer, context-aware interactions.
</Card>
<Card title="Personalized Research Agent" icon="robot" 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="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="robot" href="/examples/mem0-openai-voice-demo">
Use Mem0's memory capabilities with OpenAI's Inbuilt Tools to create AI agents with persistent memory.
</Card>
</CardGroup>
+2 -2
View File
@@ -96,8 +96,8 @@ You can fetch all the memories at any point in time using the following code:
```python
memories = ai_tutor.get_memories(user_id=user_id)
for m in memories:
print(m['text'])
for m in memories['results']:
print(m['memory'])
```
### Key Points
+2 -2
View File
@@ -82,11 +82,11 @@ class PersonalTravelAssistant:
def get_memories(self, user_id):
memories = self.memory.get_all(user_id=user_id)
return [m['memory'] for m in memories['memories']]
return [m['memory'] for m in memories['results']]
def search_memories(self, query, user_id):
memories = self.memory.search(query, user_id=user_id)
return [m['memory'] for m in memories['memories']]
return [m['memory'] for m in memories['results']]
# Usage example
user_id = "traveler_123"
@@ -0,0 +1,70 @@
---
title: Personalized Deep Research
---
Deep Research is an intelligent agent that synthesizes large amounts of online data and completes complex research tasks, customized to your unique preferences and insights. Built on Mem0's technology, it enhances AI-driven online exploration with personalized memories.
## Overview
Deep Research leverages Mem0's memory capabilities to:
- Synthesize large amounts of online data
- Complete complex research tasks
- Customize results to your preferences
- Store and utilize personal insights
- Maintain context across research sessions
## Demo
Watch Deep Research in action:
<iframe
width="700"
height="400"
src="https://www.youtube.com/embed/8vQlCtXzF60?si=b8iTOgummAVzR7ia"
title="YouTube video player"
frameborder="0"
allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture; web-share"
referrerpolicy="strict-origin-when-cross-origin"
allowfullscreen
></iframe>
## Getting Started
1. Visit [deep-research.mem0.ai](https://deep-research.mem0.ai/)
2. Upload your resume (PDF or text) or manually enter information about yourself
3. Enter your research topic
4. Click "Start Research" to begin
## Features
### 1. Personalized Research
- Analyzes your background and expertise
- Tailors research depth and complexity to your level
- Incorporates your previous research context
### 2. Comprehensive Data Synthesis
- Processes multiple online sources
- Extracts relevant information
- Provides coherent summaries
### 3. Memory Integration
- Stores research findings for future reference
- Maintains context across sessions
- Links related research topics
### 4. Interactive Exploration
- Allows real-time query refinement
- Supports follow-up questions
- Enables deep-diving into specific areas
## Use Cases
- **Academic Research**: Literature reviews, thesis research, paper writing
- **Market Research**: Industry analysis, competitor research, trend identification
- **Technical Research**: Technology evaluation, solution comparison
- **Business Research**: Strategic planning, opportunity analysis
## Try It Out
Experience AI-powered research personalization at [deep-research.mem0.ai](https://deep-research.mem0.ai/)
+131
View File
@@ -0,0 +1,131 @@
---
title: FAQs
icon: "question"
iconType: "solid"
---
<AccordionGroup>
<Accordion title="How does Mem0 work?">
Mem0 utilizes a sophisticated hybrid database system to efficiently manage and retrieve memories for AI agents and assistants. Each memory is linked to a unique identifier, such as a user ID or agent ID, enabling Mem0 to organize and access memories tailored to specific individuals or contexts.
When a message is added to Mem0 via the `add` method, the system extracts pertinent facts and preferences, distributing them across various data stores: a vector database and a graph database. This hybrid strategy ensures that diverse types of information are stored optimally, facilitating swift and effective searches.
When an AI agent or LLM needs to access memories, it employs the `search` method. Mem0 conducts a comprehensive search across these data stores, retrieving relevant information from each.
The retrieved memories can be seamlessly integrated into the LLM's prompt as required, enhancing the personalization and relevance of responses.
</Accordion>
<Accordion title="What are the key features of Mem0?">
- **User, Session, and AI Agent Memory**: Retains information across sessions and interactions for users and AI agents, ensuring continuity and context.
- **Adaptive Personalization**: Continuously updates memories based on user interactions and feedback.
- **Developer-Friendly API**: Offers a straightforward API for seamless integration into various applications.
- **Platform Consistency**: Ensures consistent behavior and data across different platforms and devices.
- **Managed Service**: Provides a hosted solution for easy deployment and maintenance.
- **Save Costs**: Saves costs by adding relevent memories instead of complete transcripts to context window
</Accordion>
<Accordion title="How Mem0 is different from traditional RAG?">
Mem0's memory implementation for Large Language Models (LLMs) offers several advantages over Retrieval-Augmented Generation (RAG):
- **Entity Relationships**: Mem0 can understand and relate entities across different interactions, unlike RAG which retrieves information from static documents. This leads to a deeper understanding of context and relationships.
- **Contextual Continuity**: Mem0 retains information across sessions, maintaining continuity in conversations and interactions, which is essential for long-term engagement applications like virtual companions or personalized learning assistants.
- **Adaptive Learning**: Mem0 improves its personalization based on user interactions and feedback, making the memory more accurate and tailored to individual users over time.
- **Dynamic Updates**: Mem0 can dynamically update its memory with new information and interactions, unlike RAG which relies on static data. This allows for real-time adjustments and improvements, enhancing the user experience.
These advanced memory capabilities make Mem0 a powerful tool for developers aiming to create personalized and context-aware AI applications.
</Accordion>
<Accordion title="What are the common use-cases of Mem0?">
- **Personalized Learning Assistants**: Long-term memory allows learning assistants to remember user preferences, strengths and weaknesses, and progress, providing a more tailored and effective learning experience.
- **Customer Support AI Agents**: By retaining information from previous interactions, customer support bots can offer more accurate and context-aware assistance, improving customer satisfaction and reducing resolution times.
- **Healthcare Assistants**: Long-term memory enables healthcare assistants to keep track of patient history, medication schedules, and treatment plans, ensuring personalized and consistent care.
- **Virtual Companions**: Virtual companions can use long-term memory to build deeper relationships with users by remembering personal details, preferences, and past conversations, making interactions more delightful.
- **Productivity Tools**: Long-term memory helps productivity tools remember user habits, frequently used documents, and task history, streamlining workflows and enhancing efficiency.
- **Gaming AI**: In gaming, AI with long-term memory can create more immersive experiences by remembering player choices, strategies, and progress, adapting the game environment accordingly.
</Accordion>
<Accordion title="Why aren't my memories being created?">
Mem0 uses a sophisticated classification system to determine which parts of text should be extracted as memories. Not all text content will generate memories, as the system is designed to identify specific types of memorable information.
There are several scenarios where mem0 may return an empty list of memories:
- When users input definitional questions (e.g., "What is backpropagation?")
- For general concept explanations that don't contain personal or experiential information
- Technical definitions and theoretical explanations
- General knowledge statements without personal context
- Abstract or theoretical content
Example Scenarios
```
Input: "What is machine learning?"
No memories extracted - Content is definitional and does not meet memory classification criteria.
Input: "Yesterday I learned about machine learning in class"
Memory extracted - Contains personal experience and temporal context.
```
Best Practices
To ensure successful memory extraction:
- Include temporal markers (when events occurred)
- Add personal context or experiences
- Frame information in terms of real-world applications or experiences
- Include specific examples or cases rather than general definitions
</Accordion>
<Accordion title="How do I configure Mem0 for AWS Lambda?">
When deploying Mem0 on AWS Lambda, you'll need to modify the storage directory configuration due to Lambda's file system restrictions. By default, Lambda only allows writing to the `/tmp` directory.
To configure Mem0 for AWS Lambda, set the `MEM0_DIR` environment variable to point to a writable directory in `/tmp`:
```bash
MEM0_DIR=/tmp/.mem0
```
If you're not using environment variables, you'll need to modify the storage path in your code:
```python
# Change from
home_dir = os.path.expanduser("~")
mem0_dir = os.environ.get("MEM0_DIR") or os.path.join(home_dir, ".mem0")
# To
mem0_dir = os.environ.get("MEM0_DIR", "/tmp/.mem0")
```
Note that the `/tmp` directory in Lambda has a size limit of 512MB and its contents are not persistent between function invocations.
</Accordion>
<Accordion title="How can I use metadata with Mem0?">
Metadata is the recommended approach for incorporating additional information with Mem0. You can store any type of structured data as metadata during the `add` method, such as location, timestamp, weather conditions, user state, or application context. This enriches your memories with valuable contextual information that can be used for more precise retrieval and filtering.
During retrieval, you have two main approaches for using metadata:
1. **Pre-filtering**: Include metadata parameters in your initial search query to narrow down the memory pool
2. **Post-processing**: Retrieve a broader set of memories based on query, then apply metadata filters to refine the results
Examples of useful metadata you might store:
- **Contextual information**: Location, time, device type, application state
- **User attributes**: Preferences, skill levels, demographic information
- **Interaction details**: Conversation topics, sentiment, urgency levels
- **Custom tags**: Any domain-specific categorization relevant to your application
This flexibility allows you to create highly contextually aware AI applications that can adapt to specific user needs and situations. Metadata provides an additional dimension for memory retrieval, enabling more precise and relevant responses.
</Accordion>
</AccordionGroup>
+2 -38
View File
@@ -1,5 +1,7 @@
---
title: Features
icon: "wrench"
iconType: "solid"
---
## Core features
@@ -13,44 +15,6 @@ title: Features
## How does Mem0 work?
Mem0 leverages a hybrid database approach to manage and retrieve long-term memories for AI agents and assistants. Each memory is associated with a unique identifier, such as a user ID or agent ID, allowing Mem0 to organize and access memories specific to an individual or context.
When a message is added to the Mem0 using add() method, the system extracts relevant facts and preferences and stores it across data stores: a vector database, a key-value database, and a graph database. This hybrid approach ensures that different types of information are stored in the most efficient manner, making subsequent searches quick and effective.
When an AI agent or LLM needs to recall memories, it uses the search() method. Mem0 then performs search across these data stores, retrieving relevant information from each source. This information is then passed through a scoring layer, which evaluates their importance based on relevance, importance, and recency. This ensures that only the most personalized and useful context is surfaced.
The retrieved memories can then be appended to the LLM's prompt as needed, making responses personalized and relevant.
## Common Use Cases
- **Personalized Learning Assistants**: Long-term memory allows learning assistants to remember user preferences, strengths and weaknesses, and progress, providing a more tailored and effective learning experience.
- **Customer Support AI Agents**: By retaining information from previous interactions, customer support bots can offer more accurate and context-aware assistance, improving customer satisfaction and reducing resolution times.
- **Healthcare Assistants**: Long-term memory enables healthcare assistants to keep track of patient history, medication schedules, and treatment plans, ensuring personalized and consistent care.
- **Virtual Companions**: Virtual companions can use long-term memory to build deeper relationships with users by remembering personal details, preferences, and past conversations, making interactions more delightful.
- **Productivity Tools**: Long-term memory helps productivity tools remember user habits, frequently used documents, and task history, streamlining workflows and enhancing efficiency.
- **Gaming AI**: In gaming, AI with long-term memory can create more immersive experiences by remembering player choices, strategies, and progress, adapting the game environment accordingly.
## How is Mem0 different from RAG?
Mem0's memory implementation for Large Language Models (LLMs) offers several advantages over Retrieval-Augmented Generation (RAG):
- **Entity Relationships**: Mem0 can understand and relate entities across different interactions, unlike RAG which retrieves information from static documents. This leads to a deeper understanding of context and relationships.
- **Contextual Continuity**: Mem0 retains information across sessions, maintaining continuity in conversations and interactions, which is essential for long-term engagement applications like virtual companions or personalized learning assistants.
- **Adaptive Learning**: Mem0 improves its personalization based on user interactions and feedback, making the memory more accurate and tailored to individual users over time.
- **Dynamic Updates**: Mem0 can dynamically update its memory with new information and interactions, unlike RAG which relies on static data. This allows for real-time adjustments and improvements, enhancing the user experience.
These advanced memory capabilities make Mem0 a powerful tool for developers aiming to create personalized and context-aware AI applications.
If you have any questions, please feel free to reach out to us using one of the following methods:
+103
View File
@@ -0,0 +1,103 @@
---
title: Advanced Retrieval
icon: "magnifying-glass"
iconType: "solid"
---
Mem0's **Advanced Retrieval** feature delivers superior search results by leveraging state-of-the-art search algorithms. Beyond the default search functionality, Mem0 offers the following advanced retrieval modes:
1. **Keyword Search**
This mode emphasizes keywords within the query, returning memories that contain the most relevant keywords alongside those from the default search. By default, this parameter is set to `false`. Enabling it enhances search recall, though it may slightly impact precision.
```python
client.search(query, keyword_search=True, user_id='alex')
```
**Example:**
```python
# Search for memories about food preferences with keyword search enabled
query = "What are my food preferences?"
results = client.search(query, keyword_search=True, user_id='alex')
# Output might include:
# - "Vegetarian. Allergic to nuts." (highly relevant)
# - "Prefers spicy food and enjoys Thai cuisine" (relevant)
# - "Mentioned disliking sea food during restaurant discussion" (keyword match)
# Without keyword_search=True, only the most relevant memories would be returned:
# - "Vegetarian. Allergic to nuts." (highly relevant)
# - "Prefers spicy food and enjoys Thai cuisine" (relevant)
# The keyword-based match about "sea food" would be excluded
```
2. **Reranking**
Normal retrieval gives you memories sorted in order of their relevancy, but the order may not be perfect. Reranking uses a deep neural network to correct this order, ensuring the most relevant memories appear first. If you are concerned about the order of memories, or want that the best results always comes at top then use reranking. This parameter is set to `false` by default. When enabled, it reorders the memories based on a more accurate relevance score.
```python
client.search(query, rerank=True, user_id='alex')
```
**Example:**
```python
# Search for travel plans with reranking enabled
query = "What are my travel plans?"
results = client.search(query, rerank=True, user_id='alex')
# Without reranking, results might be ordered like:
# 1. "Traveled to France last year" (less relevant to current plans)
# 2. "Planning a trip to Japan next month" (more relevant to current plans)
# 3. "Interested in visiting Tokyo restaurants" (relevant to current plans)
# With reranking enabled, results would be reordered:
# 1. "Planning a trip to Japan next month" (most relevant to current plans)
# 2. "Interested in visiting Tokyo restaurants" (highly relevant to current plans)
# 3. "Traveled to France last year" (less relevant to current plans)
```
3. **Filtering**
Filtering allows you to narrow down search results by applying specific criterias. This parameter is set to `false` by default. When activated, it significantly enhances search precision by removing irrelevant memories, though it may slightly reduce recall. Filtering is particularly useful when you need highly specific information.
```python
client.search(query, filter_memories=True, user_id='alex')
```
**Example:**
```python
# Search for dietary restrictions with filtering enabled
query = "What are my dietary restrictions?"
results = client.search(query, filter_memories=True, user_id='alex')
# Without filtering, results might include:
# - "Vegetarian. Allergic to nuts." (directly relevant)
# - "I enjoy cooking Italian food on weekends" (somewhat related to food)
# - "Mentioned disliking seafood during restaurant discussion" (food-related)
# - "Prefers to eat dinner at 7pm" (tangentially food-related)
# With filtering enabled, results would be focused:
# - "Vegetarian. Allergic to nuts." (directly relevant)
# - "Mentioned disliking seafood during restaurant discussion" (relevant restriction)
#
# The filtering process removes memories that are about food preferences
# but not specifically about dietary restrictions
```
<Note> You can enable or disable these search modes by passing the respective parameters to the `search` method. There is no required sequence for these modes, and any combination can be used based on your needs. </Note>
### Latency Numbers
Here are the typical latency ranges for each search mode:
| **Mode** | **Latency** |
|---------------------|------------------|
| **Keyword Search** | **&lt;10ms** |
| **Reranking** | **150-200ms** |
| **Filtering** | **200-300ms** |
If you have any questions, please feel free to reach out to us using one of the following methods:
<Snippet file="get-help.mdx" />
+9 -3
View File
@@ -1,6 +1,8 @@
---
title: Async Client
description: 'Asynchronous client for Mem0'
icon: "bolt"
iconType: "solid"
---
The `AsyncMemoryClient` is an asynchronous client for interacting with the Mem0 API. It provides similar functionality to the synchronous `MemoryClient` but allows for non-blocking operations, which can be beneficial in applications that require high concurrency.
@@ -12,13 +14,17 @@ To use the async client, you first need to initialize it:
<CodeGroup>
```python Python
import os
from mem0 import AsyncMemoryClient
client = AsyncMemoryClient(api_key="your-api-key")
os.environ["MEM0_API_KEY"] = "your-api-key"
client = AsyncMemoryClient()
```
```javascript JavaScript
const { MemoryClient } = require('mem0ai');
const client = new MemoryClient('your-api-key');
const client = new MemoryClient({ apiKey: 'your-api-key'});
```
</CodeGroup>
@@ -58,7 +64,7 @@ Search for memories based on a query asynchronously.
<CodeGroup>
```python Python
await client.search(query="What is Alice's favorite sport?", user_id="alice")
await client.search("What is Alice's favorite sport?", user_id="alice")
```
```javascript JavaScript
+205
View File
@@ -0,0 +1,205 @@
---
title: Contextual Add (ADD v2)
icon: "square-plus"
iconType: "solid"
---
Mem0 now supports an contextual add version (v2). To use it, set `version="v2"` during the add call. The default version is v1, which is deprecated now. We recommend migrating to `v2` for new applications.
## Key Differences Between v1 and v2
### Version 1 (Legacy)
In v1 (default), users needed to pass either the entire conversation history or past k messages with each new message to generate properly contextualized memories. This approach required:
- Manually tracking and sending previous messages using a sliding window approach
- Increased payload sizes as conversations grew longer, requiring careful window size management
<CodeGroup>
```python Python
# First interaction
messages1 = [
{"role": "user", "content": "Hi, I'm Alex and I live in San Francisco."},
{"role": "assistant", "content": "Hello Alex! Nice to meet you. San Francisco is a beautiful city."}
]
client.add(messages1, user_id="alex")
# Second interaction - must include previous messages for context
messages2 = [
{"role": "user", "content": "Hi, I'm Alex and I live in San Francisco."},
{"role": "assistant", "content": "Hello Alex! Nice to meet you. San Francisco is a beautiful city."},
{"role": "user", "content": "I like to eat sushi, and yesterday I went to Sunnyvale to eat sushi with my friends."},
{"role": "assistant", "content": "Sushi is really a tasty choice. What did you do this weekend?"}
]
client.add(messages2, user_id="alex")
```
```javascript JavaScript
// First interaction
const messages1 = [
{"role": "user", "content": "Hi, I'm Alex and I live in San Francisco."},
{"role": "assistant", "content": "Hello Alex! Nice to meet you. San Francisco is a beautiful city."}
];
client.add(messages1, { user_id: "alex" })
.then(response => console.log(response))
.catch(error => console.error(error));
// Second interaction - must include previous messages for context
const messages2 = [
{"role": "user", "content": "Hi, I'm Alex and I live in San Francisco."},
{"role": "assistant", "content": "Hello Alex! Nice to meet you. San Francisco is a beautiful city."},
{"role": "user", "content": "I like to eat sushi, and yesterday I went to Sunnyvale to eat sushi with my friends."},
{"role": "assistant", "content": "Sushi is really a tasty choice. What did you do this weekend?"}
];
client.add(messages2, { user_id: "alex" })
.then(response => console.log(response))
.catch(error => console.error(error));
```
</CodeGroup>
### Version 2 (Recommended)
In v2, Mem0 automatically manages conversation context. Users only need to send new messages, and the system will:
- Automatically retrieve relevant conversation history
- Generate properly contextualized memories
- Reduce payload sizes and simplify integration
<CodeGroup>
```python Python
# First interaction
messages1 = [
{"role": "user", "content": "Hi, I'm Alex and I live in San Francisco."},
{"role": "assistant", "content": "Hello Alex! Nice to meet you. San Francisco is a beautiful city."}
]
client.add(messages1, user_id="alex", version="v2")
# Second interaction - only need to send new messages
messages2 = [
{"role": "user", "content": "I like to eat sushi, and yesterday I went to Sunnyvale to eat sushi with my friends."},
{"role": "assistant", "content": "Sushi is really a tasty choice. What did you do this weekend?"}
]
client.add(messages2, user_id="alex", version="v2")
```
```javascript JavaScript
// First interaction
const messages1 = [
{"role": "user", "content": "Hi, I'm Alex and I live in San Francisco."},
{"role": "assistant", "content": "Hello Alex! Nice to meet you. San Francisco is a beautiful city."}
];
client.add(messages1, { user_id: "alex", version: "v2" })
.then(response => console.log(response))
.catch(error => console.error(error));
// Second interaction - only need to send new messages
const messages2 = [
{"role": "user", "content": "I like to eat sushi, and yesterday I went to Sunnyvale to eat sushi with my friends."},
{"role": "assistant", "content": "Sushi is really a tasty choice. What did you do this weekend?"}
];
client.add(messages2, { user_id: "alex", version: "v2" })
.then(response => console.log(response))
.catch(error => console.error(error));
```
</CodeGroup>
## Benefits of Using v2
1. **Simplified Integration**: No need to track and manage conversation history
2. **Reduced Payload Size**: Only send new messages, not the entire conversation
3. **Improved Memory Quality**: Automatic context retrieval ensures better memory generation
## Understanding ID Parameters in v2
When using contextual add v2, you have different options for how to organize and retrieve memories:
### Using Only `user_id`
When you provide only a `user_id`:
- Memories are associated with this user's long-term memory store
- The system will automatically retrieve relevant context from all of the user's previous conversations
- These memories persist indefinitely across all of the user's sessions
- Ideal for maintaining persistent user information (preferences, personal details, etc.)
<CodeGroup>
```python Python
# Adding to long-term user memory
messages = [
{"role": "user", "content": "I'm allergic to peanuts and shellfish."},
{"role": "assistant", "content": "I've noted your allergies to peanuts and shellfish."}
]
client.add(messages, user_id="alex", version="v2")
```
```javascript JavaScript
// Adding to long-term user memory
const messages = [
{"role": "user", "content": "I'm allergic to peanuts and shellfish."},
{"role": "assistant", "content": "I've noted your allergies to peanuts and shellfish."}
];
client.add(messages, { user_id: "alex", version: "v2" })
.then(response => console.log(response))
.catch(error => console.error(error));
```
</CodeGroup>
### Using `user_id` with `run_id`
When you provide both `user_id` and `run_id`:
- Memories are associated with a specific conversation session or interaction
- The system will retrieve context primarily from this specific session
- These memories are still tied to the user but are organized by the specific session
- Ideal for maintaining context within a specific conversation flow or task
- Helps prevent context from different conversations from interfering with each other
<CodeGroup>
```python Python
# Adding to a specific conversation session
messages = [
{"role": "user", "content": "For this trip to Paris, I want to focus on art museums."},
{"role": "assistant", "content": "Great! I'll help you plan your Paris trip with a focus on art museums."}
]
client.add(messages, user_id="alex", run_id="paris-trip-2024", version="v2")
# Later in the same conversation session
messages2 = [
{"role": "user", "content": "I'd like to visit the Louvre on Monday."},
{"role": "assistant", "content": "The Louvre is a great choice for Monday. Would you like information about opening hours?"}
]
client.add(messages2, user_id="alex", run_id="paris-trip-2024", version="v2")
```
```javascript JavaScript
// Adding to a specific conversation session
const messages = [
{"role": "user", "content": "For this trip to Paris, I want to focus on art museums."},
{"role": "assistant", "content": "Great! I'll help you plan your Paris trip with a focus on art museums."}
];
client.add(messages, { user_id: "alex", run_id: "paris-trip-2024", version: "v2" })
.then(response => console.log(response))
.catch(error => console.error(error));
// Later in the same conversation session
const messages2 = [
{"role": "user", "content": "I'd like to visit the Louvre on Monday."},
{"role": "assistant", "content": "The Louvre is a great choice for Monday. Would you like information about opening hours?"}
];
client.add(messages2, { user_id: "alex", run_id: "paris-trip-2024", version: "v2" })
.then(response => console.log(response))
.catch(error => console.error(error));
```
</CodeGroup>
Using `run_id` helps you organize memories into logical sessions or tasks, making it easier to maintain context for specific interactions while still associating everything with the user's overall profile.
If you have any questions, please feel free to reach out to us using one of the following methods:
<Snippet file="get-help.mdx" />
+17 -6
View File
@@ -1,6 +1,8 @@
---
title: Custom Categories
description: 'Enhance your product experience by adding custom categories tailored to your needs'
icon: "tags"
iconType: "solid"
---
## How to set custom categories?
@@ -17,9 +19,12 @@ Here's how to set custom categories:
<CodeGroup>
```python Code
import os
from mem0 import MemoryClient
client = MemoryClient(api_key="<your_mem0_api_key>")
os.environ["MEM0_API_KEY"] = "your-api-key"
client = MemoryClient()
# Update custom categories
new_categories = [
@@ -28,7 +33,7 @@ new_categories = [
{"personal_information": "Basic information about the user including name, preferences, and personality traits"}
]
response = client.update_custom_instructions_and_categories({"custom_categories": new_categories})
response = client.update_project(custom_categories = new_categories)
print(response)
```
@@ -51,7 +56,7 @@ messages = [
]
# Add memories with custom categories
client.add(messages, user_id="alice"))
client.add(messages, user_id="alice")
```
```python Memories with categories
@@ -93,8 +98,11 @@ You can also set custom categories during the `add` API call. This will override
<CodeGroup>
```python Code
import os
from mem0 import MemoryClient
os.environ["MEM0_API_KEY"] = "your-api-key"
client = MemoryClient(api_key="<your_mem0_api_key>")
custom_categories = [
@@ -146,9 +154,12 @@ Here is the list of **default categories**. If you don't specify any custom cate
<CodeGroup>
```python Code
import os
from mem0 import MemoryClient
client = MemoryClient(api_key="<your_mem0_api_key>")
os.environ["MEM0_API_KEY"] = "your-api-key"
client = MemoryClient()
messages = [
{"role": "user", "content": "Hi, my name is Alice."},
@@ -172,11 +183,11 @@ Name is Alice (personal_details)
```
</CodeGroup>
You can check whether default categories are being used by calling `get_custom_instructions_and_categories()`. If `custom_categories` returns `None`, it means the default categories are being used.
You can check whether default categories are being used by calling `get_project()`. If `custom_categories` returns `None`, it means the default categories are being used.
<CodeGroup>
```python Code
client.get_custom_instructions_and_categories(["custom_categories"])
client.get_project(["custom_categories"])
```
```json Output
@@ -0,0 +1,169 @@
---
title: Custom Fact Extraction Prompt
description: 'Enhance your product experience by adding custom fact extraction prompt tailored to your needs'
icon: "pencil"
iconType: "solid"
---
## Introduction to Custom Fact Extraction Prompt
Custom fact extraction prompt allow you to tailor the behavior of your Mem0 instance to specific use cases or domains.
By defining it, you can control how information is extracted from the user's message.
To create an effective custom fact extraction prompt:
1. Be specific about the information to extract.
2. Provide few-shot examples to guide the LLM.
3. Ensure examples follow the format shown below.
Example of a custom fact extraction prompt:
<CodeGroup>
```python Python
custom_fact_extraction_prompt = """
Please only extract entities containing customer support information, order details, and user information.
Here are some few shot examples:
Input: Hi.
Output: {{"facts" : []}}
Input: The weather is nice today.
Output: {{"facts" : []}}
Input: My order #12345 hasn't arrived yet.
Output: {{"facts" : ["Order #12345 not received"]}}
Input: I'm John Doe, and I'd like to return the shoes I bought last week.
Output: {{"facts" : ["Customer name: John Doe", "Wants to return shoes", "Purchase made last week"]}}
Input: I ordered a red shirt, size medium, but received a blue one instead.
Output: {{"facts" : ["Ordered red shirt, size medium", "Received blue shirt instead"]}}
Return the facts and customer information in a json format as shown above.
"""
```
```typescript TypeScript
const customPrompt = `
Please only extract entities containing customer support information, order details, and user information.
Here are some few shot examples:
Input: Hi.
Output: {"facts" : []}
Input: The weather is nice today.
Output: {"facts" : []}
Input: My order #12345 hasn't arrived yet.
Output: {"facts" : ["Order #12345 not received"]}
Input: I am John Doe, and I would like to return the shoes I bought last week.
Output: {"facts" : ["Customer name: John Doe", "Wants to return shoes", "Purchase made last week"]}
Input: I ordered a red shirt, size medium, but received a blue one instead.
Output: {"facts" : ["Ordered red shirt, size medium", "Received blue shirt instead"]}
Return the facts and customer information in a json format as shown above.
`;
```
</CodeGroup>
Here we initialize the custom fact extraction prompt in the config:
<CodeGroup>
```python Python
from mem0 import Memory
config = {
"llm": {
"provider": "openai",
"config": {
"model": "gpt-4o",
"temperature": 0.2,
"max_tokens": 2000,
}
},
"custom_fact_extraction_prompt": custom_fact_extraction_prompt,
"version": "v1.1"
}
m = Memory.from_config(config_dict=config, user_id="alice")
```
```typescript TypeScript
import { Memory } from 'mem0ai/oss';
const config = {
version: 'v1.1',
llm: {
provider: 'openai',
config: {
apiKey: process.env.OPENAI_API_KEY || '',
model: 'gpt-4-turbo-preview',
temperature: 0.2,
maxTokens: 1500,
},
},
customPrompt: customPrompt
};
const memory = new Memory(config);
```
</CodeGroup>
### Example 1
In this example, we are adding a memory of a user ordering a laptop. As seen in the output, the custom prompt is used to extract the relevant information from the user's message.
<CodeGroup>
```python Python
m.add("Yesterday, I ordered a laptop, the order id is 12345", user_id="alice")
```
```typescript TypeScript
await memory.add('Yesterday, I ordered a laptop, the order id is 12345', { userId: "user123" });
```
```json Output
{
"results": [
{
"memory": "Ordered a laptop",
"event": "ADD"
},
{
"memory": "Order ID: 12345",
"event": "ADD"
},
{
"memory": "Order placed yesterday",
"event": "ADD"
}
],
"relations": []
}
```
</CodeGroup>
### Example 2
In this example, we are adding a memory of a user liking to go on hikes. This add message is not specific to the use-case mentioned in the custom prompt.
Hence, the memory is not added.
<CodeGroup>
```python Python
m.add("I like going to hikes", user_id="alice")
```
```typescript TypeScript
await memory.add('I like going to hikes', { userId: "user123" });
```
```json Output
{
"results": [],
"relations": []
}
```
</CodeGroup>
The custom fact extraction prompt will process both the user and assistant messages to extract relevant information according to the defined format.
+2
View File
@@ -1,6 +1,8 @@
---
title: Custom Instructions
description: 'Enhance your product experience by adding custom instructions tailored to your needs'
icon: "pencil"
iconType: "solid"
---
## Introduction to Custom Instructions
-109
View File
@@ -1,109 +0,0 @@
---
title: Custom Prompts
description: 'Enhance your product experience by adding custom prompts tailored to your needs'
---
## Introduction to Custom Prompts
Custom prompts allow you to tailor the behavior of your Mem0 instance to specific use cases or domains.
By defining a custom prompt, you can control how information is extracted, processed, and stored in your memory system.
To create an effective custom prompt:
1. Be specific about the information to extract.
2. Provide few-shot examples to guide the LLM.
3. Ensure examples follow the format shown below.
Example of a custom prompt:
```python
custom_prompt = """
Please only extract entities containing customer support information, order details, and user information.
Here are some few shot examples:
Input: Hi.
Output: {{"facts" : []}}
Input: The weather is nice today.
Output: {{"facts" : []}}
Input: My order #12345 hasn't arrived yet.
Output: {{"facts" : ["Order #12345 not received"]}}
Input: I'm John Doe, and I'd like to return the shoes I bought last week.
Output: {{"facts" : ["Customer name: John Doe", "Wants to return shoes", "Purchase made last week"]}}
Input: I ordered a red shirt, size medium, but received a blue one instead.
Output: {{"facts" : ["Ordered red shirt, size medium", "Received blue shirt instead"]}}
Return the facts and customer information in a json format as shown above.
"""
```
Here we initialize the custom prompt in the config.
```python
from mem0 import Memory
config = {
"llm": {
"provider": "openai",
"config": {
"model": "gpt-4o",
"temperature": 0.2,
"max_tokens": 1500,
}
},
"custom_prompt": custom_prompt,
"version": "v1.1"
}
m = Memory.from_config(config_dict=config, user_id="alice")
```
### Example 1
In this example, we are adding a memory of a user ordering a laptop. As seen in the output, the custom prompt is used to extract the relevant information from the user's message.
<CodeGroup>
```python Code
m.add("Yesterday, I ordered a laptop, the order id is 12345", user_id="alice")
```
```json Output
{
"results": [
{
"memory": "Ordered a laptop",
"event": "ADD"
},
{
"memory": "Order ID: 12345",
"event": "ADD"
},
{
"memory": "Order placed yesterday",
"event": "ADD"
}
],
"relations": []
}
```
</CodeGroup>
### Example 2
In this example, we are adding a memory of a user liking to go on hikes. This add message is not specific to the use-case mentioned in the custom prompt.
Hence, the memory is not added.
<CodeGroup>
```python Code
m.add("I like going to hikes", user_id="alice")
```
```json Output
{
"results": [],
"relations": []
}
```
</CodeGroup>
@@ -0,0 +1,239 @@
---
title: Custom Update Memory Prompt
icon: "pencil"
iconType: "solid"
---
Update memory prompt is a prompt used to determine the action to be performed on the memory.
By customizing this prompt, you can control how the memory is updated.
## Introduction
Mem0 memory system compares the newly retrieved facts with the existing memory and determines the action to be performed on the memory.
The kinds of actions are:
- Add
- Add the newly retrieved facts to the memory.
- Update
- Update the existing memory with the newly retrieved facts.
- Delete
- Delete the existing memory.
- No Change
- Do not make any changes to the memory.
### Example
Example of a custom update memory prompt:
<CodeGroup>
```python Python
UPDATE_MEMORY_PROMPT = """You are a smart memory manager which controls the memory of a system.
You can perform four operations: (1) add into the memory, (2) update the memory, (3) delete from the memory, and (4) no change.
Based on the above four operations, the memory will change.
Compare newly retrieved facts with the existing memory. For each new fact, decide whether to:
- ADD: Add it to the memory as a new element
- UPDATE: Update an existing memory element
- DELETE: Delete an existing memory element
- NONE: Make no change (if the fact is already present or irrelevant)
There are specific guidelines to select which operation to perform:
1. **Add**: If the retrieved facts contain new information not present in the memory, then you have to add it by generating a new ID in the id field.
- **Example**:
- Old Memory:
[
{
"id" : "0",
"text" : "User is a software engineer"
}
]
- Retrieved facts: ["Name is John"]
- New Memory:
{
"memory" : [
{
"id" : "0",
"text" : "User is a software engineer",
"event" : "NONE"
},
{
"id" : "1",
"text" : "Name is John",
"event" : "ADD"
}
]
}
2. **Update**: If the retrieved facts contain information that is already present in the memory but the information is totally different, then you have to update it.
If the retrieved fact contains information that conveys the same thing as the elements present in the memory, then you have to keep the fact which has the most information.
Example (a) -- if the memory contains "User likes to play cricket" and the retrieved fact is "Loves to play cricket with friends", then update the memory with the retrieved facts.
Example (b) -- if the memory contains "Likes cheese pizza" and the retrieved fact is "Loves cheese pizza", then you do not need to update it because they convey the same information.
If the direction is to update the memory, then you have to update it.
Please keep in mind while updating you have to keep the same ID.
Please note to return the IDs in the output from the input IDs only and do not generate any new ID.
- **Example**:
- Old Memory:
[
{
"id" : "0",
"text" : "I really like cheese pizza"
},
{
"id" : "1",
"text" : "User is a software engineer"
},
{
"id" : "2",
"text" : "User likes to play cricket"
}
]
- Retrieved facts: ["Loves chicken pizza", "Loves to play cricket with friends"]
- New Memory:
{
"memory" : [
{
"id" : "0",
"text" : "Loves cheese and chicken pizza",
"event" : "UPDATE",
"old_memory" : "I really like cheese pizza"
},
{
"id" : "1",
"text" : "User is a software engineer",
"event" : "NONE"
},
{
"id" : "2",
"text" : "Loves to play cricket with friends",
"event" : "UPDATE",
"old_memory" : "User likes to play cricket"
}
]
}
3. **Delete**: If the retrieved facts contain information that contradicts the information present in the memory, then you have to delete it. Or if the direction is to delete the memory, then you have to delete it.
Please note to return the IDs in the output from the input IDs only and do not generate any new ID.
- **Example**:
- Old Memory:
[
{
"id" : "0",
"text" : "Name is John"
},
{
"id" : "1",
"text" : "Loves cheese pizza"
}
]
- Retrieved facts: ["Dislikes cheese pizza"]
- New Memory:
{
"memory" : [
{
"id" : "0",
"text" : "Name is John",
"event" : "NONE"
},
{
"id" : "1",
"text" : "Loves cheese pizza",
"event" : "DELETE"
}
]
}
4. **No Change**: If the retrieved facts contain information that is already present in the memory, then you do not need to make any changes.
- **Example**:
- Old Memory:
[
{
"id" : "0",
"text" : "Name is John"
},
{
"id" : "1",
"text" : "Loves cheese pizza"
}
]
- Retrieved facts: ["Name is John"]
- New Memory:
{
"memory" : [
{
"id" : "0",
"text" : "Name is John",
"event" : "NONE"
},
{
"id" : "1",
"text" : "Loves cheese pizza",
"event" : "NONE"
}
]
}
"""
```
</CodeGroup>
## Output format
The prompt needs to guide the output to follow the structure as shown below:
<CodeGroup>
```json Add
{
"memory": [
{
"id" : "0",
"text" : "This information is new",
"event" : "ADD"
}
]
}
```
```json Update
{
"memory": [
{
"id" : "0",
"text" : "This information replaces the old information",
"event" : "UPDATE",
"old_memory" : "Old information"
}
]
}
```
```json Delete
{
"memory": [
{
"id" : "0",
"text" : "This information will be deleted",
"event" : "DELETE"
}
]
}
```
```json No Change
{
"memory": [
{
"id" : "0",
"text" : "No changes for this information",
"event" : "NONE"
}
]
}
```
</CodeGroup>
## custom update memory prompt vs custom prompt
| Feature | `custom_update_memory_prompt` | `custom_prompt` |
|---------|-------------------------------|-----------------|
| Use case | Determine the action to be performed on the memory | Extract the facts from messages |
| Reference | Retrieved facts from messages and old memory | Messages |
| Output | Action to be performed on the memory | Extracted facts |
+3 -1
View File
@@ -1,6 +1,8 @@
---
title: Direct Import
description: 'Bypass the memory deduction phase and directly store pre-defined memories for efficient retrieval'
icon: "arrow-right"
iconType: "solid"
---
## How to use Direct Import?
@@ -39,7 +41,7 @@ You can retrieve memories using the `search` method.
<CodeGroup>
```python Python
client.search(query="What is Alice's favorite sport?", user_id="alice", output_format="v1.1")
client.search("What is Alice's favorite sport?", user_id="alice", output_format="v1.1")
```
```json Output
+62
View File
@@ -0,0 +1,62 @@
---
title: Feedback Mechanism
icon: "thumbs-up"
iconType: "solid"
---
Mem0's **Feedback Mechanism** allows you to provide feedback on the memories generated by your application. This feedback is used to improve the accuracy of the memories and the search results.
## How it works
The feedback mechanism is a simple API that allows you to provide feedback on the memories generated by your application. The feedback is stored in the database and is used to improve the accuracy of the memories and the search results. Over time, Mem0 continuously learns from this feedback, refining its memory generation and search capabilities for better performance.
## Give Feedback
You can give feedback on a memory by calling the `feedback` method on the Mem0 client.
<CodeGroup>
```python Python
from mem0 import MemoryClient
client = MemoryClient(api_key="your_api_key")
client.feedback(memory_id="your-memory-id", feedback="NEGATIVE", feedback_reason="I don't like this memory because it is not relevant.")
```
```javascript JavaScript
import MemoryClient from 'mem0ai';
const client = new MemoryClient({ apiKey: 'your-api-key'});
client.feedback({
memory_id: "your-memory-id",
feedback: "NEGATIVE",
feedback_reason: "I don't like this memory because it is not relevant."
})
```
</CodeGroup>
## Feedback Types
The `feedback` parameter can be one of the following values:
- `POSITIVE`: The memory is useful.
- `NEGATIVE`: The memory is not useful.
- `VERY_NEGATIVE`: The memory is not useful at all.
## Parameters
The `feedback` method takes the following parameters:
- `memory_id`: The ID of the memory to give feedback on.
- `feedback`: The feedback to give on the memory. (Optional)
- `feedback_reason`: The reason for the feedback. (Optional)
The `feedback_reason` parameter is optional and can be used to provide a reason for the feedback.
<Note>
You can pass `None` or `null` to the `feedback` and `feedback_reason` parameters to remove the feedback for a memory.
</Note>
+295
View File
@@ -0,0 +1,295 @@
---
title: Graph Memory
icon: "circle-nodes"
iconType: "solid"
description: "Enable graph-based memory retrieval for more contextually relevant results"
---
## Overview
Graph Memory enhances memory pipeline by creating relationships between entities in your data. It builds a network of interconnected information for more contextually relevant search results.
This feature allows your AI applications to understand connections between entities, providing richer context for responses. It's ideal for applications needing relationship tracking and nuanced information retrieval across related memories.
## How Graph Memory Works
The Graph Memory feature analyzes how each entity connects and relates to each other. When enabled:
1. Mem0 automatically builds a graph representation of entities
2. Retrieval considers graph relationships between entities
3. Results include entities that may be contextually important even if they're not direct semantic matches
## Using Graph Memory
To use Graph Memory, you need to enable it in your API calls by setting the `enable_graph=True` parameter. You'll also need to specify `output_format="v1.1"` to receive the enriched response format.
### Adding Memories with Graph Memory
When adding new memories, enable Graph Memory to automatically build relationships with existing memories:
<CodeGroup>
```python Python
from mem0 import MemoryClient
client = MemoryClient(
api_key="your-api-key",
org_id="your-org-id",
project_id="your-project-id"
)
messages = [
{"role": "user", "content": "My name is Joseph"},
{"role": "assistant", "content": "Hello Joseph, it's nice to meet you!"},
{"role": "user", "content": "I'm from Seattle and I work as a software engineer"}
]
# Enable graph memory when adding
client.add(
messages,
user_id="joseph",
version="v1",
enable_graph=True,
output_format="v1.1"
)
```
```javascript JavaScript
import { MemoryClient } from "mem0";
const client = new MemoryClient({
apiKey: "your-api-key",
orgId: "your-org-id",
projectId: "your-project-id"
});
const messages = [
{ role: "user", content: "My name is Joseph" },
{ role: "assistant", content: "Hello Joseph, it's nice to meet you!" },
{ role: "user", content: "I'm from Seattle and I work as a software engineer" }
];
// Enable graph memory when adding
await client.add({
messages,
userId: "joseph",
version: "v1",
enableGraph: true,
outputFormat: "v1.1"
});
```
```json Output
{
"results": [
{
"memory": "Name is Joseph",
"event": "ADD",
"id": "4a5a417a-fa10-43b5-8c53-a77c45e80438"
},
{
"memory": "Is from Seattle",
"event": "ADD",
"id": "8d268d0f-5452-4714-b27d-ae46f676a49d"
},
{
"memory": "Is a software engineer",
"event": "ADD",
"id": "5f0a184e-ddea-4fe6-9b92-692d6a901df8"
}
]
}
```
</CodeGroup>
The graph memory would look like this:
<Frame>
<img src="/images/graph-platform.png" alt="Graph Memory Visualization showing relationships between entities" />
</Frame>
<Caption>Graph Memory creates a network of relationships between entities, enabling more contextual retrieval</Caption>
<Note>
Response for the graph memory's `add` operation will not be available directly in the response.
As adding graph memories is an asynchronous operation due to heavy processing,
you can use the `get_all()` endpoint to retrieve the memory with the graph metadata.
</Note>
### Searching with Graph Memory
When searching memories, Graph Memory helps retrieve entities that are contextually important even if they're not direct semantic matches.
<CodeGroup>
```python Python
# Search with graph memory enabled
results = client.search(
"what is my name?",
user_id="joseph",
enable_graph=True,
output_format="v1.1"
)
print(results)
```
```javascript JavaScript
// Search with graph memory enabled
const results = await client.search({
query: "what is my name?",
userId: "joseph",
enableGraph: true,
outputFormat: "v1.1"
});
console.log(results);
```
```json Output
{
"results": [
{
"id": "4a5a417a-fa10-43b5-8c53-a77c45e80438",
"memory": "Name is Joseph",
"user_id": "joseph",
"metadata": null,
"categories": ["personal_details"],
"immutable": false,
"created_at": "2025-03-19T09:09:00.146390-07:00",
"updated_at": "2025-03-19T09:09:00.146404-07:00",
"score": 0.3621795393335552
},
{
"id": "8d268d0f-5452-4714-b27d-ae46f676a49d",
"memory": "Is from Seattle",
"user_id": "joseph",
"metadata": null,
"categories": ["personal_details"],
"immutable": false,
"created_at": "2025-03-19T09:09:00.170680-07:00",
"updated_at": "2025-03-19T09:09:00.170692-07:00",
"score": 0.31212713194651254
}
],
"relations": [
{
"source": "joseph",
"source_type": "person",
"relationship": "name",
"target": "joseph",
"target_type": "person",
"score": 0.39
}
]
}
```
</CodeGroup>
### Retrieving All Memories with Graph Memory
When retrieving all memories, Graph Memory provides additional relationship context:
<CodeGroup>
```python Python
# Get all memories with graph context
memories = client.get_all(
user_id="joseph",
enable_graph=True,
output_format="v1.1"
)
print(memories)
```
```javascript JavaScript
// Get all memories with graph context
const memories = await client.getAll({
userId: "joseph",
enableGraph: true,
outputFormat: "v1.1"
});
console.log(memories);
```
```json Output
{
"results": [
{
"id": "5f0a184e-ddea-4fe6-9b92-692d6a901df8",
"memory": "Is a software engineer",
"user_id": "joseph",
"metadata": null,
"categories": ["professional_details"],
"immutable": false,
"created_at": "2025-03-19T09:09:00.194116-07:00",
"updated_at": "2025-03-19T09:09:00.194128-07:00",
},
{
"id": "8d268d0f-5452-4714-b27d-ae46f676a49d",
"memory": "Is from Seattle",
"user_id": "joseph",
"metadata": null,
"categories": ["personal_details"],
"immutable": false,
"created_at": "2025-03-19T09:09:00.170680-07:00",
"updated_at": "2025-03-19T09:09:00.170692-07:00",
},
{
"id": "4a5a417a-fa10-43b5-8c53-a77c45e80438",
"memory": "Name is Joseph",
"user_id": "joseph",
"metadata": null,
"categories": ["personal_details"],
"immutable": false,
"created_at": "2025-03-19T09:09:00.146390-07:00",
"updated_at": "2025-03-19T09:09:00.146404-07:00",
}
],
"relations": [
{
"source": "joseph",
"source_type": "person",
"relationship": "name",
"target": "joseph",
"target_type": "person"
},
{
"source": "joseph",
"source_type": "person",
"relationship": "city",
"target": "seattle",
"target_type": "city"
},
{
"source": "joseph",
"source_type": "person",
"relationship": "job",
"target": "software engineer",
"target_type": "job"
}
]
}
```
</CodeGroup>
## Best Practices
- Enable Graph Memory for applications where understanding context and relationships between memories is important
- Graph Memory works best with a rich history of related conversations
- Consider Graph Memory for long-running assistants that need to track evolving information
## Performance Considerations
Graph Memory requires additional processing and may increase response times slightly for very large memory stores. However, for most use cases, the improved retrieval quality outweighs the minimal performance impact.
If you have any questions, please feel free to reach out to us using one of the following methods:
<Snippet file="get-help.mdx" />
+26 -4
View File
@@ -1,6 +1,8 @@
---
title: Memory Export
description: 'Export memories in a structured format using customizable Pydantic schemas'
icon: "file-export"
iconType: "solid"
---
## Overview
@@ -69,13 +71,32 @@ Here's an example schema for extracting professional profile information:
### Submit Export Job
You can optionally provide additional instructions to guide how memories are processed and structured during export using the `export_instructions` parameter.
<CodeGroup>
```python Python
# Basic export request
response = client.create_memory_export(
schema=json_schema,
user_id="user123"
user_id="alice"
)
# Export with custom instructions
export_instructions = """
1. Create a comprehensive profile with detailed information in each category
2. Only mark fields as "None" when absolutely no relevant information exists
3. Base all information directly on the user's memories
4. When contradictions exist, prioritize the most recent information
5. Clearly distinguish between factual statements and inferences
"""
response = client.create_memory_export(
schema=json_schema,
user_id="alice",
export_instructions=export_instructions
)
print(response)
```
@@ -85,7 +106,8 @@ curl -X POST "https://api.mem0.ai/v1/memories/export/" \
-H "Content-Type: application/json" \
-d '{
"schema": {json_schema},
"user_id": "user123"
"user_id": "alice",
"export_instructions": "1. Create a comprehensive profile with detailed information\n2. Only mark fields as \"None\" when absolutely no relevant information exists"
}'
```
@@ -105,12 +127,12 @@ Once the export job is complete, you can retrieve the structured data:
<CodeGroup>
```python Python
response = client.get_memory_export(user_id="user123")
response = client.get_memory_export(user_id="alice")
print(response)
```
```bash cURL
curl -X GET "https://api.mem0.ai/v1/memories/export/?user_id=user123" \
curl -X GET "https://api.mem0.ai/v1/memories/export/?user_id=alice" \
-H "Authorization: Token your-api-key"
```
+171
View File
@@ -0,0 +1,171 @@
---
title: Multimodal Support
description: Integrate images into your interactions with Mem0
icon: "image"
iconType: "solid"
---
Mem0 extends its capabilities beyond text by supporting multimodal data, including images. With this feature, users can seamlessly integrate images into their interactions—allowing Mem0 to extract relevant information from visual content and enrich the memory system.
## How It Works
When a user submits an image, Mem0 processes it to extract textual information and other pertinent details. These details are then added to the user's memory, enhancing the system's ability to understand and recall visual inputs.
<CodeGroup>
```python Python
import os
from mem0 import MemoryClient
os.environ["MEM0_API_KEY"] = "your-api-key"
client = MemoryClient()
messages = [
{
"role": "user",
"content": "Hi, my name is Alice."
},
{
"role": "assistant",
"content": "Nice to meet you, Alice! What do you like to eat?"
},
{
"role": "user",
"content": {
"type": "image_url",
"image_url": {
"url": "https://www.superhealthykids.com/wp-content/uploads/2021/10/best-veggie-pizza-featured-image-square-2.jpg"
}
}
},
]
# Calling the add method to ingest messages into the memory system
client.add(messages, user_id="alice")
```
```typescript TypeScript
import MemoryClient from "mem0ai";
const client = new MemoryClient();
const messages = [
{
role: "user",
content: "Hi, my name is Alice."
},
{
role: "assistant",
content: "Nice to meet you, Alice! What do you like to eat?"
},
{
role: "user",
content: {
type: "image_url",
image_url: {
url: "https://www.superhealthykids.com/wp-content/uploads/2021/10/best-veggie-pizza-featured-image-square-2.jpg"
}
}
},
]
await client.add(messages, { user_id: "alice" })
```
```json Output
{
"results": [
{
"memory": "Name is Alice",
"event": "ADD",
"id": "7ae113a3-3cb5-46e9-b6f7-486c36391847"
},
{
"memory": "Likes large pizza with toppings including cherry tomatoes, black olives, green spinach, yellow bell peppers, diced ham, and sliced mushrooms",
"event": "ADD",
"id": "56545065-7dee-4acf-8bf2-a5b2535aabb3"
}
]
}
```
</CodeGroup>
## Image Integration Methods
Mem0 supports incorporating images into user interactions using two primary methods: by providing an image URL or by using a Base64-encoded image. The examples below demonstrate both approaches.
## 1. Using an Image URL (Recommended)
You can include an image by providing its direct URL. This method is simple and efficient for online images.
```python {2, 5-13}
# Define the image URL
image_url = "https://www.superhealthykids.com/wp-content/uploads/2021/10/best-veggie-pizza-featured-image-square-2.jpg"
# Create the message dictionary with the image URL
image_message = {
"role": "user",
"content": {
"type": "image_url",
"image_url": {
"url": image_url
}
}
}
client.add([image_message], user_id="alice")
```
## 2. Using Base64 Image Encoding for Local Files
For local images—or when embedding the image directly is preferable—you can use a Base64-encoded string.
<CodeGroup>
```python Python
import base64
# Path to the image file
image_path = "path/to/your/image.jpg"
# Encode the image in Base64
with open(image_path, "rb") as image_file:
base64_image = base64.b64encode(image_file.read()).decode("utf-8")
# Create the message dictionary with the Base64-encoded image
image_message = {
"role": "user",
"content": {
"type": "image_url",
"image_url": {
"url": f"data:image/jpeg;base64,{base64_image}"
}
}
}
client.add([image_message], user_id="alice")
```
```typescript TypeScript
import MemoryClient from "mem0ai";
import fs from 'fs';
const imagePath = 'path/to/your/image.jpg';
const base64Image = fs.readFileSync(imagePath, { encoding: 'base64' });
const imageMessage = {
role: "user",
content: {
type: "image_url",
image_url: {
url: `data:image/jpeg;base64,${base64Image}`
}
}
};
await client.add([imageMessage], { user_id: "alice" })
```
</CodeGroup>
Using these methods, you can seamlessly incorporate images into your interactions, further enhancing Mem0's multimodal capabilities.
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
@@ -1,5 +1,7 @@
---
title: OpenAI Compatibility
icon: "code"
iconType: "solid"
---
Mem0 can be easily integrated into chat applications to enhance conversational agents with structured memory. Mem0's APIs are designed to be compatible with OpenAI's, with the goal of making it easy to leverage Mem0 in applications you may have already built.
+48
View File
@@ -0,0 +1,48 @@
---
title: Overview
icon: "info"
iconType: "solid"
---
Learn about the key features and capabilities that make Mem0 a powerful platform for memory management and retrieval.
## Core Features
<CardGroup>
<Card title="Advanced Retrieval" icon="magnifying-glass" href="/features/advanced-retrieval">
Superior search results using state-of-the-art algorithms, including keyword search, reranking, and filtering capabilities.
</Card>
<Card title="Contextual Add" icon="square-plus" href="/features/contextual-add">
Only send your latest conversation history - we automatically retrieve the rest and generate properly contextualized memories.
</Card>
<Card title="Multimodal Support" icon="photo-film" href="/features/multimodal-support">
Process and analyze various types of content including images.
</Card>
<Card title="Memory Customization" icon="filter" href="/features/selective-memory">
Customize and curate stored memories to focus on relevant information while excluding unnecessary data, enabling improved accuracy, privacy control, and resource efficiency.
</Card>
<Card title="Custom Categories" icon="tags" href="/features/custom-categories">
Create and manage custom categories to organize memories based on your specific needs and requirements.
</Card>
<Card title="Custom Instructions" icon="list-check" href="/features/custom-instructions">
Define specific guidelines for your project to ensure consistent handling of information and requirements.
</Card>
<Card title="Direct Import" icon="message-bot" href="/features/direct-import">
Tailor the behavior of your Mem0 instance with custom prompts for specific use cases or domains.
</Card>
<Card title="Async Client" icon="bolt" href="/features/async-client">
Asynchronous client for non-blocking operations and high concurrency applications.
</Card>
<Card title="Memory Export" icon="file-export" href="/features/memory-export">
Export memories in structured formats using customizable Pydantic schemas.
</Card>
<Card title="Graph Memory" icon="graph" href="/features/graph-memory">
Add memories in the form of nodes and edges in a graph database and search for related memories.
</Card>
</CardGroup>
## Getting Help
If you have any questions about these features or need assistance, our team is here to help:
<Snippet file="get-help.mdx" />
+6 -1
View File
@@ -1,6 +1,8 @@
---
title: Memory Customization
description: 'Mem0 supports customizing the memories you store, allowing you to focus on pertinent information while omitting irrelevant data.'
icon: "filter"
iconType: "solid"
---
## Benefits of Memory Customization
@@ -27,9 +29,12 @@ Users can define specific kinds of memories to store. This feature enhances memo
Here’s how you can do it:
```python
import os
from mem0 import MemoryClient
m = MemoryClient(api_key="xxx")
os.environ["MEM0_API_KEY"] = "your-api-key"
m = MemoryClient()
# Define what to include
includes = "sports related things"
+201
View File
@@ -0,0 +1,201 @@
---
title: Webhooks
description: 'Configure and manage webhooks to receive real-time notifications about memory events'
icon: "webhook"
iconType: "solid"
---
## Overview
Webhooks enable real-time notifications for memory events in your Mem0 project. Webhooks are configured at the project level, meaning each webhook is tied to a specific project and receives events solely from that project. You can configure webhooks to send HTTP POST requests to your specified URLs whenever memories are created, updated, or deleted.
## Managing Webhooks
### Create Webhook
Create a webhook for your project; it will receive events only from that project:
<CodeGroup>
```python Python
import os
from mem0 import MemoryClient
os.environ["MEM0_API_KEY"] = "your-api-key"
client = MemoryClient()
# Create webhook in a specific project
webhook = client.create_webhook(
url="https://your-app.com/webhook",
name="Memory Logger",
project_id="proj_123",
event_types=["memory_add"]
)
print(webhook)
```
```javascript JavaScript
const { MemoryClient } = require('mem0ai');
const client = new MemoryClient({ apiKey: 'your-api-key'});
// Create webhook in a specific project
const webhook = await client.createWebhook({
url: "https://your-app.com/webhook",
name: "Memory Logger",
projectId: "proj_123",
eventTypes: ["memory_add"]
});
console.log(webhook);
```
```json Output
{
"webhook_id": "wh_123",
"name": "Memory Logger",
"url": "https://your-app.com/webhook",
"event_types": ["memory_add"],
"project": "default-project",
"is_active": true,
"created_at": "2025-02-18T22:59:56.804993-08:00",
"updated_at": "2025-02-18T23:06:41.479361-08:00"
}
```
</CodeGroup>
### Get Webhooks
Retrieve all webhooks for your project:
<CodeGroup>
```python Python
# Get webhooks for a specific project
webhooks = client.get_webhooks(project_id="proj_123")
print(webhooks)
```
```javascript JavaScript
// Get webhooks for a specific project
const webhooks = await client.getWebhooks({projectId: "proj_123"});
console.log(webhooks);
```
```json Output
[
{
"webhook_id": "wh_123",
"url": "https://mem0.ai",
"name": "mem0",
"owner": "john",
"event_types": ["memory_add"],
"project": "default-project",
"is_active": true,
"created_at": "2025-02-18T22:59:56.804993-08:00",
"updated_at": "2025-02-18T23:06:41.479361-08:00"
}
]
```
</CodeGroup>
### Update Webhook
Update an existing webhook’s configuration by specifying its `webhook_id`:
<CodeGroup>
```python Python
# Update webhook for a specific project
updated_webhook = client.update_webhook(
name="Updated Logger",
url="https://your-app.com/new-webhook",
event_types=["memory_update", "memory_add"],
webhook_id="wh_123"
)
print(updated_webhook)
```
```javascript JavaScript
// Update webhook for a specific project
const updatedWebhook = await client.updateWebhook({
name: "Updated Logger",
url: "https://your-app.com/new-webhook",
eventTypes: ["memory_update", "memory_add"],
webhookId: "wh_123"
});
console.log(updatedWebhook);
```
```json Output
{
"message": "Webhook updated successfully"
}
```
</CodeGroup>
### Delete Webhook
Delete a webhook by providing its `webhook_id`:
<CodeGroup>
```python Python
# Delete webhook from a specific project
response = client.delete_webhook(webhook_id="wh_123")
print(response)
```
```javascript JavaScript
// Delete webhook from a specific project
const response = await client.deleteWebhook({webhookId: "wh_123"});
console.log(response);
```
```json Output
{
"message": "Webhook deleted successfully"
}
```
</CodeGroup>
## Event Types
Mem0 supports the following event types for webhooks:
- `memory_add`: Triggered when a memory is added.
- `memory_update`: Triggered when an existing memory is updated.
- `memory_delete`: Triggered when a memory is deleted.
## Webhook Payload
When a memory event occurs, Mem0 sends an HTTP POST request to your webhook URL with the following payload:
```json
{
"event_details": {
"id": "a1b2c3d4-e5f6-4g7h-8i9j-k0l1m2n3o4p5",
"data": {
"memory": "Name is Alex"
},
"event": "ADD"
}
}
```
## Best Practices
1. **Implement Retry Logic**: Ensure your webhook endpoint can handle temporary failures by implementing retry logic.
2. **Verify Webhook Source**: Implement security measures to verify that webhook requests originate from Mem0.
3. **Process Events Asynchronously**: Process webhook events asynchronously to avoid timeouts and ensure reliable handling.
4. **Monitor Webhook Health**: Regularly review your webhook logs to ensure functionality and promptly address any delivery failures.
If you have any questions, please feel free to reach out to us using one of the following methods:
<Snippet file="get-help.mdx" />
Binary file not shown.

After

Width:  |  Height:  |  Size: 276 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 2.8 MiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 843 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 4.6 MiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 290 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 72 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 3.9 MiB

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