Compare commits

..
58 Commits
Author SHA1 Message Date
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 AryanandGitHub 5606c3ffb8 Update Docs (#2277) 2025-02-28 16:37:05 -08:00
Saket AryanandGitHub c1aba35884 Mem0 TS Spec/Docs Update (#2275) 2025-02-28 21:43:51 +05:30
Dev KhantandGitHub d9b48191de Doc: Update embeddings config page (#2276) 2025-02-28 21:43:00 +05:30
Dev KhantandGitHub e06f95cea4 fix deprecation warning: qdrant and version bump -> 0.1.58 (#2274) 2025-02-28 16:41:45 +05:30
Dev KhantandGitHub b131c4bfc4 Update max_token and formatting (#2273) 2025-02-28 15:59:34 +05:30
Wonbin KimandGitHub 6acb00731d Add config option for vertex embedding tasks (#2266) 2025-02-28 15:20:05 +05:30
Dev KhantandGitHub 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 AryanandGitHub 434b555a29 Updated docs for typescript package (#2269) 2025-02-27 18:22:28 -08:00
Saket AryanandGitHub f8071a753b Update AI SDK Example (#2271) 2025-02-27 18:11:59 -08:00
Saket AryanandGitHub d200691e9b Added Mem0 TS Library (#2270) 2025-02-27 15:19:17 -08:00
Dev KhantandGitHub ecff6315e7 User_id creation for client and formatting (#2264) 2025-02-28 00:00:11 +05:30
Dev KhantandGitHub ff4510f83d Doc: add param fields in v2 get_all (#2268) 2025-02-27 15:49:57 +05:30
Dev KhantandGitHub 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 KhantandGitHub 5cebe9ab52 Rename xai.mdx to xAI.mdx 2025-02-26 13:45:32 +05:30
Dev KhantandGitHub 371848cfbc Doc: fix xai (#2263) 2025-02-26 13:43:38 +05:30
Dev KhantandGitHub 8e3ed634d1 version bump -> 0.1.56 (#2262) 2025-02-26 13:35:25 +05:30
Dev KhantandGitHub e9bc4cdc95 Add Grok Support (#2260) 2025-02-26 13:34:01 +05:30
Dev KhantandGitHub a236aa2315 Doc: fix integrations page (#2261) 2025-02-26 13:18:52 +05:30
Dev KhantandGitHub 5660fffa96 Doc: update example on quickstart (#2255) 2025-02-26 00:04:38 +05:30
Dev KhantandGitHub eba6f77330 Doc: update anthropic model (#2254) 2025-02-25 00:59:14 +05:30
Dev KhantandGitHub b5d00e9b6c Docs: set api_key to env (#2252) 2025-02-24 13:42:39 +05:30
Dev KhantandGitHub 1be0d70d02 Doc: api_key changes (#2251) 2025-02-24 10:23:28 +05:30
Taranjeet SinghandGitHub edb53209ef improvement: Update multimodal docs. (#2250) 2025-02-23 16:43:23 -08:00
Taranjeet SinghandGitHub 7443e58a9d improvement: Update webhook docs. (#2249) 2025-02-23 16:10:21 -08:00
Dev KhantandGitHub 7f25caba47 version bump -> 0.1.55 (#2248) 2025-02-23 18:07:11 +05:30
Dev KhantandGitHub c42934b7fb Formatting and Client changes (#2247) 2025-02-23 00:39:26 +05:30
Dev KhantandGitHub 17887b5959 Docs: Add immutable param to ADD (#2246) 2025-02-22 23:37:30 +05:30
Dev KhantandGitHub 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 KhantandGitHub 2d0c8fe94e embedchain: version bump -> 0.1.127 (#2244) 2025-02-21 17:51:47 +05:30
Dev KhantandGitHub 369d5325f9 version bump -> 0.1.54 (#2243) 2025-02-21 16:03:18 +05:30
Dev KhantandGitHub 29d63306a4 Webhook API reference and update/delete function change (#2242) 2025-02-21 16:01:53 +05:30
Deshraj YadavandGitHub 96628d7791 Update docs for running REST API Server (#2241) 2025-02-21 01:26:57 -08:00
Deshraj YadavandGitHub 244fd2231d Add support for Mem0 REST API Server in OSS package (#2240) 2025-02-21 01:05:55 -08:00
Dev KhantandGitHub 3db028c719 Docs: update webhook (#2238) 2025-02-21 00:48:59 +05:30
Dev KhantandGitHub c86b1e4d4c Docs: update webhooks (#2237) 2025-02-21 00:42:02 +05:30
Dev KhantandGitHub 5f5b738745 version bump -> 0.1.53 (#2236) 2025-02-20 23:58:54 +05:30
acaf47ed54 Project_id mandatory for Webhooks (#2232)
Co-authored-by: Deshraj Yadav <deshrajdry@gmail.com>
2025-02-20 23:57:29 +05:30
colaandGitHub 9734b2db7e delete same vector in retrieved_old_memory (#2201) 2025-02-20 10:10:09 -08:00
Saket AryanandGitHub 3fe31e1c31 Fix Build Errors (#2235) 2025-02-20 22:47:15 +05:30
Seetha Rama GupthaandGitHub f4c0f98fde Adding Native OpenSearch support for Mem0 (#2211) 2025-02-20 11:42:12 +05:30
Dev KhantandGitHub 6e781f616c Doc: Update Redis config (#2233) 2025-02-20 11:24:00 +05:30
Prateek ChhikaraandGitHub dcba83186a Updated docs (#2231) 2025-02-19 18:37:01 -08:00
Saket AryanandGitHub a6d305f8d0 Update Docs for Mem0 AI SDK (#2230) 2025-02-19 14:39:49 -08:00
Lennex ZinyandoandGitHub 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 KhantandGitHub 0e6b20982a Docs: webhook announcement (#2228) 2025-02-19 15:52:13 +05:30
Dev KhantandGitHub 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 KhantandGitHub 760cd54ddf Webhook Support (#2225) 2025-02-19 00:04:01 -08:00
Deshraj YadavandGitHub 1436da18b1 Update docs (#2222) 2025-02-18 17:52:32 -08:00
Prateek ChhikaraandGitHub cc9acb7493 Added support of vision input 2025-02-18 11:47:13 -08:00
Dev KhantandGitHub cbee71a63e Proper error msg for API Key validation (#2220) 2025-02-18 23:59:59 +05:30
Dev KhantandGitHub b052a86424 Update API reference to remove Org/Proj (#2221) 2025-02-18 22:34:58 +05:30
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
175 changed files with 11008 additions and 2104 deletions
+1
View File
@@ -2,6 +2,7 @@
__pycache__/
*.py[cod]
*$py.class
**/node_modules/
# C extensions
*.so
+1 -1
View File
@@ -13,7 +13,7 @@ install:
install_all:
poetry install
poetry run pip install groq together boto3 litellm ollama chromadb sentence_transformers vertexai \
google-generativeai elasticsearch
google-generativeai elasticsearch opensearch-py
# Format code with ruff
format:
+8
View File
@@ -71,6 +71,12 @@ Install the Mem0 package via pip:
pip install mem0ai
```
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).
@@ -114,6 +120,8 @@ if __name__ == "__main__":
main()
```
See the example for [Node.js](https://docs.mem0.ai/examples/ai_companion_js).
For more advanced usage and API documentation, visit our [documentation](https://docs.mem0.ai).
> [!TIP]
@@ -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,83 +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.",
"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.",
"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.
+55 -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,31 @@ 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 |
</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
+31 -1
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
@@ -25,12 +26,41 @@ m = Memory.from_config(config)
m.add("I'm visiting Paris", 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>
+15 -2
View File
@@ -16,7 +16,10 @@ 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"
}
}
}
@@ -24,7 +27,14 @@ config = {
m = Memory.from_config(config)
m.add("I'm visiting Paris", 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 +44,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` |
+6
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>
+84 -37
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,39 +58,70 @@ 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 |
| `deepseek_base_url` | Base URL for DeepSeek API | DeepSeek |
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 |
</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.
+27 -2
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,
}
@@ -24,6 +29,26 @@ m = Memory.from_config(config)
m.add("Likes to play cricket on weekends", user_id="alice", metadata={"category": "hobbies"})
```
```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);
await memory.add("Likes to play cricket on weekends", { userId: "alice", metadata: { category: "hobbies" } });
```
</CodeGroup>
## Config
All available parameters for the `anthropic` config are present in [Master List of All Params in Config](../config).
+1 -1
View File
@@ -24,7 +24,7 @@ config = {
"config": {
"model": "arn:aws:bedrock:us-east-1:123456789012:model/your-model-name",
"temperature": 0.2,
"max_tokens": 1500,
"max_tokens": 2000,
}
}
}
+1 -1
View File
@@ -19,7 +19,7 @@ config = {
"config": {
"model": "deepseek-chat", # default model
"temperature": 0.2,
"max_tokens": 1500,
"max_tokens": 2000,
"top_p": 1.0
}
}
+1 -1
View File
@@ -19,7 +19,7 @@ config = {
"config": {
"model": "gemini-1.5-flash-latest",
"temperature": 0.2,
"max_tokens": 1500,
"max_tokens": 2000,
}
}
}
+1 -1
View File
@@ -19,7 +19,7 @@ config = {
"config": {
"model": "gemini/gemini-pro",
"temperature": 0.2,
"max_tokens": 1500,
"max_tokens": 2000,
}
}
}
+27 -2
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,7 +22,7 @@ config = {
"config": {
"model": "mixtral-8x7b-32768",
"temperature": 0.1,
"max_tokens": 1000,
"max_tokens": 2000,
}
}
}
@@ -26,6 +31,26 @@ m = Memory.from_config(config)
m.add("Likes to play cricket on weekends", user_id="alice", metadata={"category": "hobbies"})
```
```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);
await memory.add("Likes to play cricket on weekends", { userId: "alice", metadata: { category: "hobbies" } });
```
</CodeGroup>
## Config
All available parameters for the `groq` config are present in [Master List of All Params in Config](../config).
+1 -1
View File
@@ -14,7 +14,7 @@ config = {
"config": {
"model": "gpt-4o-mini",
"temperature": 0.2,
"max_tokens": 1500,
"max_tokens": 2000,
}
}
}
+26 -3
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,
}
}
}
@@ -38,6 +39,26 @@ m = Memory.from_config(config)
m.add("Likes to play cricket on weekends", user_id="alice", metadata={"category": "hobbies"})
```
```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);
await memory.add("Likes to play cricket on weekends", { userId: "alice", metadata: { category: "hobbies" } });
```
</CodeGroup>
We also support the new [OpenAI structured-outputs](https://platform.openai.com/docs/guides/structured-outputs/introduction) model.
```python
@@ -59,7 +80,9 @@ config = {
m = Memory.from_config(config)
```
<Note>
OpenAI structured-outputs is currently only available in the Python implementation.
</Note>
## Config
+1 -1
View File
@@ -15,7 +15,7 @@ config = {
"config": {
"model": "mistralai/Mixtral-8x7B-Instruct-v0.1",
"temperature": 0.2,
"max_tokens": 1500,
"max_tokens": 2000,
}
}
}
+35
View File
@@ -0,0 +1,35 @@
---
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)
m.add("Likes to play cricket on weekends", user_id="alice", metadata={"category": "hobbies"})
```
## Config
All available parameters for the `xai` config are present in [Master List of All Params in Config](../config).
+19 -12
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,19 +14,24 @@ 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="DeepSeek" href="/components/llms/models/deepseek"></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" />
</CardGroup>
## Structured vs Unstructured Outputs
+54 -8
View File
@@ -1,19 +1,22 @@
## 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")
- `config`: A nested dictionary containing provider-specific settings
- `provider`: The name of the vector database (e.g., "chroma", "pgvector", "qdrant", "milvus", "azure_ai_search")
- `config`: A nested object 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 +35,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 +70,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 +86,24 @@ 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 |
</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
@@ -0,0 +1,59 @@
[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)
m.add("Likes to play cricket on weekends", user_id="alice", metadata={"category": "hobbies"})
```
### 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
+39 -2
View File
@@ -2,7 +2,8 @@
### Usage
```python
<CodeGroup>
```python Python
import os
from mem0 import Memory
@@ -23,10 +24,32 @@ m = Memory.from_config(config)
m.add("Likes to play cricket on weekends", user_id="alice", metadata={"category": "hobbies"})
```
```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);
await memory.add("Likes to play cricket on weekends", { userId: "alice", metadata: { category: "hobbies" } });
```
</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 +60,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>
+39 -3
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,54 @@ 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"})
```
```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);
await memory.add("Likes to play cricket on weekends", { userId: "alice", metadata: { category: "hobbies" } });
```
</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>
+7
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,6 +10,10 @@ 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>
@@ -16,6 +22,7 @@ See the list of supported vector databases below.
<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>
</CardGroup>
## Usage
+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
+316
View File
@@ -0,0 +1,316 @@
{
"$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/multimodal-support",
"features/selective-memory",
"features/custom-categories",
"features/custom-instructions",
"features/direct-import",
"features/async-client",
"features/memory-export",
"features/webhooks"
]
}
]
},
{
"group": "Open Source",
"icon": "code-branch",
"pages": [
"open-source/quickstart",
"open-source/python-quickstart",
"open-source-typescript/quickstart",
{
"group": "Features",
"icon": "wrench",
"pages": [
"features/openai_compatibility",
"features/custom-prompts",
"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/azure_ai_search",
"components/vectordbs/dbs/redis",
"components/vectordbs/dbs/elasticsearch",
"components/vectordbs/dbs/opensearch"
]
}
]
},
{
"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"
]
}
]
}
]
}
]
},
{
"tab": "Examples",
"groups": [
{
"group": "💡 Examples",
"icon": "lightbulb",
"pages": [
"examples/overview",
"examples/ai_companion_js",
"examples/mem0-with-ollama",
"examples/personal-ai-tutor",
"examples/customer-support-agent",
"examples/personal-travel-assistant",
"examples/llama-index-mem0"
]
}
]
},
{
"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"
]
}
]
},
{
"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"
]
},
{
"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": "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"
}
}
}
+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.
+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
},
},
+3
View File
@@ -17,6 +17,9 @@ Here are some examples of how Mem0 can be integrated into various applications:
## Examples
<CardGroup cols={2}>
<Card title="AI Companion in Node.js" icon="square-6" href="/examples/ai_companion_js">
Create a Personalized AI Companion using Mem0 in Node.js.
</Card>
<Card title="Mem0 with Ollama" icon="square-1" href="/examples/mem0-with-ollama">
Run Mem0 locally with Ollama.
</Card>
+2
View File
@@ -1,5 +1,7 @@
---
title: FAQs
icon: "question"
iconType: "solid"
---
+2
View File
@@ -1,5 +1,7 @@
---
title: Features
icon: "wrench"
iconType: "solid"
---
## Core features
+2
View File
@@ -1,5 +1,7 @@
---
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:
+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
+13 -2
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 = [
@@ -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."},
+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
+67 -7
View File
@@ -1,6 +1,8 @@
---
title: Custom Prompts
description: 'Enhance your product experience by adding custom prompts tailored to your needs'
icon: "pencil"
iconType: "solid"
---
## Introduction to Custom Prompts
@@ -15,7 +17,8 @@ To create an effective custom prompt:
Example of a custom prompt:
```python
<CodeGroup>
```python Python
custom_prompt = """
Please only extract entities containing customer support information, order details, and user information.
Here are some few shot examples:
@@ -37,12 +40,37 @@ Output: {{"facts" : ["Ordered red shirt, size medium", "Received blue shirt inst
Return the facts and customer information in a json format as shown above.
"""
```
Here we initialize the custom prompt in the config.
```typescript TypeScript
const customPrompt = `
Please only extract entities containing customer support information, order details, and user information.
Here are some few shot examples:
```python
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 prompt in the config:
<CodeGroup>
```python Python
from mem0 import Memory
config = {
@@ -51,7 +79,7 @@ config = {
"config": {
"model": "gpt-4o",
"temperature": 0.2,
"max_tokens": 1500,
"max_tokens": 2000,
}
},
"custom_prompt": custom_prompt,
@@ -61,15 +89,40 @@ config = {
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 Code
```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": [
@@ -95,11 +148,16 @@ m.add("Yesterday, I ordered a laptop, the order id is 12345", user_id="alice")
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
```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": [],
@@ -107,3 +165,5 @@ m.add("I like going to hikes", user_id="alice")
}
```
</CodeGroup>
The custom prompt will process both the user and assistant messages to extract relevant information according to the defined format.
+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
+2
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
+120
View File
@@ -0,0 +1,120 @@
---
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 Code
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")
```
```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.
```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")
```
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.
+42
View File
@@ -0,0 +1,42 @@
---
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="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>
</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.

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.

Before

Width:  |  Height:  |  Size: 3.9 MiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 180 KiB

After

Width:  |  Height:  |  Size: 601 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 169 KiB

After

Width:  |  Height:  |  Size: 224 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 110 KiB

+2 -1
View File
@@ -30,9 +30,10 @@ USER_ID = "customer_service_bot"
# Set up OpenAI API key
os.environ['OPENAI_API_KEY'] = OPENAI_API_KEY
os.environ['MEM0_API_KEY'] = MEM0_API_KEY
# Initialize Mem0 and AutoGen agents
memory_client = MemoryClient(api_key=MEM0_API_KEY)
memory_client = MemoryClient()
agent = ConversableAgent(
"chatbot",
llm_config={"config_list": [{"model": "gpt-4", "api_key": OPENAI_API_KEY}]},
+2
View File
@@ -164,3 +164,5 @@ By combining CrewAI with Mem0, you can create sophisticated AI systems that main
- For CrewAI documentation, visit [CrewAI Documentation](https://docs.crewai.com/)
- For Mem0 documentation, refer to the [Mem0 Platform](https://app.mem0.ai/)
<Snippet file="get-help.mdx" />
+10 -2
View File
@@ -25,9 +25,11 @@ from langchain_core.tools import StructuredTool
from mem0 import MemoryClient
from pydantic import BaseModel, Field
from typing import List, Dict, Any, Optional
import os
os.environ["MEM0_API_KEY"] = "your-api-key"
client = MemoryClient(
api_key=your_api_key,
org_id=your_org_id,
project_id=your_project_id
)
@@ -325,4 +327,10 @@ All tools are implemented as Langchain `StructuredTool` instances, making them c
2. Add the tools to your agent's toolset
3. The agent can now use these tools to manage memories through natural language interactions
Each tool provides structured input validation through Pydantic models and returns consistent responses that can be processed by your agent.
Each tool provides structured input validation through Pydantic models and returns consistent responses that can be processed by your agent.
## Help
In case of any questions, please feel free to reach out to us using one of the following methods:
<Snippet file="get-help.mdx" />
+1 -1
View File
@@ -37,7 +37,7 @@ os.environ["MEM0_API_KEY"] = "your-mem0-api-key"
# Initialize LangChain and Mem0
llm = ChatOpenAI(model="gpt-4o-mini")
mem0 = MemoryClient(api_key=os.environ["MEM0_API_KEY"])
mem0 = MemoryClient()
```
## Create Prompt Template
+1 -1
View File
@@ -80,7 +80,7 @@ config = {
"config": {
"model": "gpt-4o",
"temperature": 0.2,
"max_tokens": 1500,
"max_tokens": 2000,
},
},
"embedder": {
+4 -1
View File
@@ -34,10 +34,11 @@ USER_ID = "your-user-id"
# Set up OpenAI API key
os.environ['OPENAI_API_KEY'] = OPENAI_API_KEY
os.environ['MEM0_API_KEY'] = MEM0_API_KEY
# Initialize Mem0 and MultiOn
memory = Memory() # For local usage
memory_client = MemoryClient(api_key=MEM0_API_KEY) # For API usage
memory_client = MemoryClient() # For API usage
multion = MultiOn(api_key=MULTION_API_KEY)
```
@@ -209,3 +210,5 @@ These examples illustrate how combining memory management with web browsing capa
- For more details and advanced usage, refer to the full [cookbooks here](https://github.com/mem0ai/mem0/blob/main/cookbooks).
- Feel free to visit our [Github](https://github.com/mem0ai/mem0) or [Mem0 Platform](https://app.mem0.ai/).
- For any questions or assistance, please reach out to `taranjeetio` on [Discord](https://mem0.dev/DiD).
<Snippet file="get-help.mdx" />
+1 -1
View File
@@ -72,7 +72,7 @@ Here are the available integrations for Mem0:
</defs>
</svg>
}
href="/integrations/llamaindex"
href="/integrations/llama-index"
>
Build RAG applications with LlamaIndex and Mem0.
</Card>
+47 -1
View File
@@ -5,7 +5,7 @@ title: Vercel AI SDK
The [**Mem0 AI SDK Provider**](https://www.npmjs.com/package/@mem0/vercel-ai-provider) is a library developed by **Mem0** to integrate with the Vercel AI SDK. This library brings enhanced AI interaction capabilities to your applications by introducing persistent memory functionality.
<Note type="info">
🎉 Exciting news! Mem0 AI SDK now supports **OpenAI**, **Anthropic**, **Cohere**, and **Groq** providers.
🎉 Exciting news! Mem0 AI SDK now supports <strong>Tools Call</strong>.
</Note>
## Overview
@@ -43,11 +43,19 @@ npm install @mem0/vercel-ai-provider
config: {
compatibility: "strict",
},
// Optional Mem0 Global Config
mem0Config: {
user_id: "mem0-user-id",
org_id: "mem0-org-id",
project_id: "mem0-project-id",
},
});
```
> **Note**: The `openai` provider is set as default. Consider using `MEM0_API_KEY` and `OPENAI_API_KEY` as environment variables for security.
> **Note**: The `mem0Config` is optional. It is used to set the global config for the Mem0 Client (eg. `user_id`, `agent_id`, `app_id`, `run_id`, `org_id`, `project_id` etc).
3. Add Memories to Enhance Context:
```typescript
@@ -145,6 +153,44 @@ npm install @mem0/vercel-ai-provider
}
```
### 4. Generate Responses with Tools Call
```typescript
import { generateText } from "ai";
import { createMem0 } from "@mem0/vercel-ai-provider";
import { z } from "zod";
const mem0 = createMem0({
provider: "anthropic",
apiKey: "anthropic-api-key",
mem0Config: {
// Global User ID
user_id: "borat"
}
});
const prompt = "What the temperature in the city that I live in?"
const result = await generateText({
model: mem0('claude-3-5-sonnet-20240620'),
tools: {
weather: tool({
description: 'Get the weather in a location',
parameters: z.object({
location: z.string().describe('The location to get the weather for'),
}),
execute: async ({ location }) => ({
location,
temperature: 72 + Math.floor(Math.random() * 21) - 10,
}),
}),
},
prompt: prompt,
});
console.log(result);
```
## Key Features
- `createMem0()`: Initializes a new Mem0 provider instance.
-262
View File
@@ -1,262 +0,0 @@
{
"$schema": "https://mintlify.com/schema.json",
"name": "Mem0.ai",
"favicon": "/logo/favicon.png",
"colors": {
"primary": "#6c60f0",
"light": "#E6FFA2",
"dark": "#a3df02",
"background": {
"dark": "#0f1117",
"light": "#fff"
}
},
"logo": {
"dark": "/logo/dark.svg",
"light": "/logo/light.svg",
"href": "https://github.com/mem0ai/mem0"
},
"topbarCtaButton": {
"name": "Your Dashboard",
"url": "https://app.mem0.ai"
},
"anchors": [
{
"name": "Your Dashboard",
"icon": "chart-simple",
"url": "https://app.mem0.ai"
},
{
"name": "API Reference",
"url": "api-reference",
"icon": "square-terminal"
},
{
"name": "Discord",
"icon": "discord",
"url": "https://mem0.dev/DiD"
},
{
"name": "GitHub",
"icon": "github",
"url": "https://github.com/mem0ai/mem0"
},
{
"name": "Support",
"icon": "envelope",
"url": "mailto:taranjeet@mem0.ai"
}
],
"tabs": [{
"name": "Documentation",
"url": "content"
},
{
"name": "Examples",
"url": "examples"
},
{
"name": "Integrations",
"url": "integrations"
}],
"navigation": [
{
"group": "Get Started",
"pages": [
"overview",
"quickstart",
"faqs"
]
},
{
"group": "Platform",
"pages": [
"platform/overview",
"platform/quickstart",
{
"group": "Features",
"pages": ["features/advanced-retrieval", "features/selective-memory", "features/custom-categories", "features/custom-instructions", "features/direct-import", "features/async-client", "features/memory-export"]
}
]
},
{
"group": "Open Source",
"pages": [
"open-source/quickstart",
{
"group": "Graph Memory",
"pages": ["open-source/graph_memory/overview", "open-source/graph_memory/features"]
},
{
"group": "LLMs",
"pages": [
"components/llms/overview",
"components/llms/config",
{
"group": "Supported LLMs",
"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"
]
}
]
},
{
"group": "Vector Databases",
"pages": [
"components/vectordbs/overview",
"components/vectordbs/config",
{
"group": "Supported Vector Databases",
"pages": [
"components/vectordbs/dbs/qdrant",
"components/vectordbs/dbs/chroma",
"components/vectordbs/dbs/pgvector",
"components/vectordbs/dbs/milvus",
"components/vectordbs/dbs/azure_ai_search",
"components/vectordbs/dbs/redis",
"components/vectordbs/dbs/elasticsearch"
]
}
]
},
{
"group": "Embedding Models",
"pages": [
"components/embedders/overview",
"components/embedders/config",
{
"group": "Supported Embedding Models",
"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": "Features",
"pages": ["features/openai_compatibility", "features/custom-prompts"]
}
]
},
{
"group": "API Reference",
"pages": [
"api-reference/overview",
{
"group": "Memory APIs",
"pages": [
"api-reference/memory/v1-get-memories",
"api-reference/memory/v2-get-memories",
"api-reference/memory/add-memories",
"api-reference/memory/delete-memories",
"api-reference/memory/get-memory",
"api-reference/memory/update-memory",
"api-reference/memory/delete-memory",
"api-reference/memory/v1-search-memories",
"api-reference/memory/v2-search-memories",
"api-reference/memory/history-memory",
"api-reference/memory/batch-update",
"api-reference/memory/batch-delete",
"api-reference/memory/create-memory-export",
"api-reference/memory/get-memory-export"
]
},
{
"group": "Entities APIs",
"pages": [
"api-reference/entities/get-users",
"api-reference/entities/delete-user"
]
},
{
"group": "Organizations APIs",
"pages": [
"api-reference/organization/get-orgs",
"api-reference/organization/get-org",
"api-reference/organization/create-org",
"api-reference/organization/delete-org",
{
"group": "Members APIs",
"pages": [
"api-reference/organization/get-org-members",
"api-reference/organization/add-org-member",
"api-reference/organization/update-org-member",
"api-reference/organization/delete-org-member"
]
}
]
},
{
"group": "Projects APIs",
"pages": [
"api-reference/project/get-projects",
"api-reference/project/get-project",
"api-reference/project/update-project",
"api-reference/project/create-project",
"api-reference/project/delete-project",
{
"group": "Members APIs",
"pages":[
"api-reference/project/get-project-members",
"api-reference/project/add-project-member",
"api-reference/project/update-project-member",
"api-reference/project/delete-project-member"
]
}
]
}
]
},
{
"group": "Integrations",
"pages": [
"integrations/overview",
"integrations/vercel-ai-sdk",
"integrations/crewai",
"integrations/autogen",
"integrations/langchain",
"integrations/langgraph",
"integrations/llama-index",
"integrations/langchain-tools"
]
},
{
"group": "💡 Examples",
"pages": [
"examples/overview",
"examples/mem0-with-ollama",
"examples/personal-ai-tutor",
"examples/customer-support-agent",
"examples/personal-travel-assistant",
"examples/llama-index-mem0"
]
}
],
"footerSocials": {
"discord": "https://mem0.dev/DiD",
"x": "https://x.com/mem0ai",
"github": "https://github.com/mem0ai",
"linkedin": "https://www.linkedin.com/company/mem0/"
},
"analytics": {
"posthog": {
"apiKey": "phc_hgJkUVJFYtmaJqrvf6CYN67TIQ8yhXAkWzUn9AMU4yX",
"apiHost": "https://mango.mem0.ai"
}
}
}
+380
View File
@@ -0,0 +1,380 @@
---
title: Node SDK
description: 'Get started with Mem0 quickly!'
icon: "node"
iconType: "solid"
---
> Welcome to the Mem0 quickstart guide. This guide will help you get up and running with Mem0 in no time.
## Installation
To install Mem0, you can use npm. Run the following command in your terminal:
```bash
npm install mem0ai
```
## Basic Usage
### Initialize Mem0
<Tabs>
<Tab title="Basic">
```typescript
import { Memory } from 'mem0ai/oss';
const memory = new Memory();
```
</Tab>
<Tab title="Advanced">
If you want to run Mem0 in production, initialize using the following method:
```typescript
import { Memory } from 'mem0ai/oss';
const memory = new Memory({
version: 'v1.1',
embedder: {
provider: 'openai',
config: {
apiKey: process.env.OPENAI_API_KEY || '',
model: 'text-embedding-3-small',
},
},
vectorStore: {
provider: 'memory',
config: {
collectionName: 'memories',
dimension: 1536,
},
},
llm: {
provider: 'openai',
config: {
apiKey: process.env.OPENAI_API_KEY || '',
model: 'gpt-4-turbo-preview',
},
},
historyDbPath: 'memory.db',
});
```
</Tab>
</Tabs>
### Store a Memory
<CodeGroup>
```typescript Code
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: "user123", metadata: { category: "movie_recommendations" } });
```
```json Output
{
"results": [
{
"id": "c03c9045-df76-4949-bbc5-d5dc1932aa5c",
"memory": "User is planning to watch a movie tonight.",
"metadata": {
"category": "movie_recommendations"
}
},
{
"id": "cbb1fe73-0bf1-4067-8c1f-63aa53e7b1a4",
"memory": "User is not a big fan of thriller movies.",
"metadata": {
"category": "movie_recommendations"
}
},
{
"id": "475bde34-21e6-42ab-8bef-0ab84474f156",
"memory": "User loves sci-fi movies.",
"metadata": {
"category": "movie_recommendations"
}
}
]
}
```
</CodeGroup>
### Retrieve Memories
<CodeGroup>
```typescript Code
// Get all memories
const allMemories = await memory.getAll({ userId: "user123" });
console.log(allMemories)
```
```json Output
{
"results": [
{
"id": "892db2ae-06d9-49e5-8b3e-585ef9b85b8e",
"memory": "User is planning to watch a movie tonight.",
"hash": "1a271c007316c94377175ee80e746a19",
"createdAt": "2025-02-27T16:33:20.557Z",
"updatedAt": "2025-02-27T16:33:27.051Z",
"metadata": {
"category": "movie_recommendations"
},
"userId": "user123"
},
{
"id": "475bde34-21e6-42ab-8bef-0ab84474f156",
"memory": "User loves sci-fi movies.",
"hash": "285d07801ae42054732314853e9eadd7",
"createdAt": "2025-02-27T16:33:20.560Z",
"updatedAt": undefined,
"metadata": {
"category": "movie_recommendations"
},
"userId": "user123"
},
{
"id": "cbb1fe73-0bf1-4067-8c1f-63aa53e7b1a4",
"memory": "User is not a big fan of thriller movies.",
"hash": "285d07801ae42054732314853e9eadd7",
"createdAt": "2025-02-27T16:33:20.560Z",
"updatedAt": undefined,
"metadata": {
"category": "movie_recommendations"
},
"userId": "user123"
}
]
}
```
</CodeGroup>
<br />
<CodeGroup>
```typescript Code
// Get a single memory by ID
const singleMemory = await memory.get('892db2ae-06d9-49e5-8b3e-585ef9b85b8e');
console.log(singleMemory);
```
```json Output
{
"id": "892db2ae-06d9-49e5-8b3e-585ef9b85b8e",
"memory": "User is planning to watch a movie tonight.",
"hash": "1a271c007316c94377175ee80e746a19",
"createdAt": "2025-02-27T16:33:20.557Z",
"updatedAt": undefined,
"metadata": {
"category": "movie_recommendations"
},
"userId": "user123"
}
```
</CodeGroup>
### Search Memories
<CodeGroup>
```typescript Code
const result = await memory.search('What do you know about me?', { userId: "user123" });
console.log(result);
```
```json Output
{
"results": [
{
"id": "892db2ae-06d9-49e5-8b3e-585ef9b85b8e",
"memory": "User is planning to watch a movie tonight.",
"hash": "1a271c007316c94377175ee80e746a19",
"createdAt": "2025-02-27T16:33:20.557Z",
"updatedAt": undefined,
"score": 0.38920719231944799,
"metadata": {
"category": "movie_recommendations"
},
"userId": "user123"
},
{
"id": "475bde34-21e6-42ab-8bef-0ab84474f156",
"memory": "User loves sci-fi movies.",
"hash": "285d07801ae42054732314853e9eadd7",
"createdAt": "2025-02-27T16:33:20.560Z",
"updatedAt": undefined,
"score": 0.36869761478135689,
"metadata": {
"category": "movie_recommendations"
},
"userId": "user123"
},
{
"id": "cbb1fe73-0bf1-4067-8c1f-63aa53e7b1a4",
"memory": "User is not a big fan of thriller movies.",
"hash": "285d07801ae42054732314853e9eadd7",
"createdAt": "2025-02-27T16:33:20.560Z",
"updatedAt": undefined,
"score": 0.33855272141248272,
"metadata": {
"category": "movie_recommendations"
},
"userId": "user123"
}
]
}
```
</CodeGroup>
### Update a Memory
<CodeGroup>
```typescript Code
const result = await memory.update(
'892db2ae-06d9-49e5-8b3e-585ef9b85b8e',
'I love India, it is my favorite country.'
);
console.log(result);
```
```json Output
{
"message": "Memory updated successfully!"
}
```
</CodeGroup>
### Memory History
<CodeGroup>
```typescript Code
const history = await memory.history('892db2ae-06d9-49e5-8b3e-585ef9b85b8e');
console.log(history);
```
```json Output
[
{
"id": 39,
"memory_id": "892db2ae-06d9-49e5-8b3e-585ef9b85b8e",
"previous_value": "User is planning to watch a movie tonight.",
"new_value": "I love India, it is my favorite country.",
"action": "UPDATE",
"created_at": "2025-02-27T16:33:20.557Z",
"updated_at": "2025-02-27T16:33:27.051Z",
"is_deleted": 0
},
{
"id": 37,
"memory_id": "892db2ae-06d9-49e5-8b3e-585ef9b85b8e",
"previous_value": null,
"new_value": "User is planning to watch a movie tonight.",
"action": "ADD",
"created_at": "2025-02-27T16:33:20.557Z",
"updated_at": null,
"is_deleted": 0
}
]
```
</CodeGroup>
### Delete Memory
```typescript
// Delete a memory by id
await memory.delete('892db2ae-06d9-49e5-8b3e-585ef9b85b8e');
// Delete all memories for a user
await memory.deleteAll({ userId: "user123" });
```
### Reset Memory
```typescript
await memory.reset(); // Reset all memories
```
## Configuration Parameters
Mem0 offers extensive configuration options to customize its behavior according to your needs. These configurations span across different components like vector stores, language models, embedders, and graph stores.
<AccordionGroup>
<Accordion title="Vector Store Configuration">
| Parameter | Description | Default |
|-------------|---------------------------------|-------------|
| `provider` | Vector store provider (e.g., "memory") | "memory" |
| `host` | Host address | "localhost" |
| `port` | Port number | undefined |
</Accordion>
<Accordion title="LLM Configuration">
| Parameter | Description | Provider |
|-----------------------|-----------------------------------------------|-------------------|
| `provider` | LLM provider (e.g., "openai", "anthropic") | All |
| `model` | 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 |
</Accordion>
<Accordion title="Embedder Configuration">
| Parameter | Description | Default |
|-------------|---------------------------------|------------------------------|
| `provider` | Embedding provider | "openai" |
| `model` | Embedding model to use | "text-embedding-3-small" |
| `apiKey` | API key for embedding service | None |
</Accordion>
<Accordion title="General Configuration">
| Parameter | Description | Default |
|------------------|--------------------------------------|----------------------------|
| `historyDbPath` | Path to the history database | "{mem0_dir}/history.db" |
| `version` | API version | "v1.0" |
| `customPrompt` | Custom prompt for memory processing | None |
</Accordion>
<Accordion title="Complete Configuration Example">
```typescript
const config = {
version: 'v1.1',
embedder: {
provider: 'openai',
config: {
apiKey: process.env.OPENAI_API_KEY || '',
model: 'text-embedding-3-small',
},
},
vectorStore: {
provider: 'memory',
config: {
collectionName: 'memories',
dimension: 1536,
},
},
llm: {
provider: 'openai',
config: {
apiKey: process.env.OPENAI_API_KEY || '',
model: 'gpt-4-turbo-preview',
},
},
historyDbPath: 'memory.db',
customPrompt: "I'm a virtual assistant. I'm here to help you with your queries.",
}
```
</Accordion>
</AccordionGroup>
If you have any questions, please feel free to reach out to us using one of the following methods:
<Snippet file="get-help.mdx" />
+91
View File
@@ -0,0 +1,91 @@
---
title: REST API Server
icon: "server"
iconType: "solid"
---
Mem0 provides a REST API server (written using FastAPI). Users can perform all operations through REST endpoints. The API also includes OpenAPI documentation, accessible at `/docs` when the server is running.
<Frame caption="APIs supported by Mem0 REST API Server">
<img src="/images/rest-api-server.png" />
</Frame>
## Features
- **Create memories:** Create memories based on messages for a user, agent, or run.
- **Retrieve memories:** Get all memories for a given user, agent, or run.
- **Search memories:** Search stored memories based on a query.
- **Update memories:** Update an existing memory.
- **Delete memories:** Delete a specific memory or all memories for a user, agent, or run.
- **Reset memories:** Reset all memories for a user, agent, or run.
- **OpenAPI Documentation:** Accessible via `/docs` endpoint.
## Running Locally
<Tabs>
<Tab title="With Docker">
1. Create a `.env` file in the current directory and set your environment variables. For example:
```txt
OPENAI_API_KEY=your-openai-api-key
```
2. Either pull the docker image from docker hub or build the docker image locally.
<Tabs>
<Tab title="Pull from Docker Hub">
```bash
docker pull mem0/mem0-api-server
```
</Tab>
<Tab title="Build Locally">
```bash
docker build -t mem0-api-server .
```
</Tab>
</Tabs>
3. Run the Docker container:
``` bash
docker run -p 8000:8000 mem0-api-server --env-file .env
```
4. Access the API at http://localhost:8000.
</Tab>
<Tab title="Without Docker">
1. Create a `.env` file in the current directory and set your environment variables. For example:
```txt
OPENAI_API_KEY=your-openai-api-key
```
2. Install dependencies:
```bash
pip install -r requirements.txt
```
3. Start the FastAPI server:
```bash
uvicorn main:app --reload
```
4. Access the API at http://localhost:8000.
</Tab>
</Tabs>
## Usage
Once the server is running (locally or via Docker), you can interact with it using any REST client or through your preferred programming language (e.g., Go, Java, etc.). You can test out the APIs using the OpenAPI documentation at [http://localhost:8000/docs](http://localhost:8000/docs) endpoint.
+3 -2
View File
@@ -1,6 +1,8 @@
---
title: Features
description: 'Graph Memory features'
icon: "list-check"
iconType: "solid"
---
Graph Memory is a powerful feature that allows users to create and utilize complex relationships between pieces of information.
@@ -26,8 +28,7 @@ config = {
"password": "xxx"
},
"custom_prompt": "Please only extract entities containing sports related relationships and nothing else.",
},
"version": "v1.1"
}
}
m = Memory.from_config(config_dict=config)
+6 -7
View File
@@ -1,6 +1,8 @@
---
title: Overview
description: 'Enhance your memory system with graph-based knowledge representation and retrieval'
icon: "database"
iconType: "solid"
---
Mem0 now supports **Graph Memory**.
@@ -36,8 +38,7 @@ allowfullscreen
## Initialize 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*).
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/).
<Note>If you are using Neo4j locally, then you need to install [APOC plugins](https://neo4j.com/labs/apoc/4.1/installation/).</Note>
@@ -63,8 +64,7 @@ config = {
"username": "neo4j",
"password": "xxx"
}
},
"version": "v1.1"
}
}
m = Memory.from_config(config_dict=config)
@@ -79,7 +79,7 @@ config = {
"config": {
"model": "gpt-4o",
"temperature": 0.2,
"max_tokens": 1500,
"max_tokens": 2000,
}
},
"graph_store": {
@@ -96,8 +96,7 @@ config = {
"temperature": 0.0,
}
}
},
"version": "v1.1"
}
}
m = Memory.from_config(config_dict=config)
+119
View File
@@ -0,0 +1,119 @@
---
title: Multimodal Support
icon: "image"
iconType: "solid"
---
Mem0 extends its capabilities beyond text by supporting multimodal data, including images. Users can seamlessly integrate images into their interactions, allowing Mem0 to extract pertinent information from visual content and enrich the memory system.
## How It Works
When a user provides an image, Mem0 processes the image to extract textual information and relevant details, which are then added to the user's memory. This feature enhances the system's ability to understand and remember details based on visual inputs.
<CodeGroup>
```python Code
from mem0 import Memory
client = Memory()
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")
```
```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 allows you to add images to user interactions through two primary methods: by providing an image URL or by using a Base64-encoded image. Below are examples demonstrating each approach.
## 1. Using an Image URL (Recommended)
You can include an image by passing its direct URL. This method is simple and efficient for online images.
```python
# 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
}
}
}
```
## 2. Using Base64 Image Encoding for Local Files
For local images or scenarios where embedding the image directly is preferable, you can use a Base64-encoded string.
```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}"
}
}
}
```
By utilizing these methods, you can effectively incorporate images into user interactions, enhancing the multimodal capabilities of your Mem0 instance.
<Note>
Currently, we support only OpenAI models for image description.
</Note>
If you have any questions, please feel free to reach out to us using one of the following methods:
<Snippet file="get-help.mdx" />
+480
View File
@@ -0,0 +1,480 @@
---
title: Python SDK
description: 'Get started with Mem0 quickly!'
icon: "python"
iconType: "solid"
---
> Welcome to the Mem0 quickstart guide. This guide will help you get up and running with Mem0 in no time.
## Installation
To install Mem0, you can use pip. Run the following command in your terminal:
```bash
pip install mem0ai
```
## Basic Usage
### Initialize Mem0
<Tabs>
<Tab title="Basic">
```python
from mem0 import Memory
m = Memory()
```
</Tab>
<Tab title="Advanced">
If you want to run Mem0 in production, initialize using the following method:
Run Qdrant first:
```bash
docker pull qdrant/qdrant
docker run -p 6333:6333 -p 6334:6334 \
-v $(pwd)/qdrant_storage:/qdrant/storage:z \
qdrant/qdrant
```
Then, instantiate memory with qdrant server:
```python
from mem0 import Memory
config = {
"vector_store": {
"provider": "qdrant",
"config": {
"host": "localhost",
"port": 6333,
}
},
}
m = Memory.from_config(config)
```
</Tab>
<Tab title="Advanced (Graph Memory)">
```python
from mem0 import Memory
config = {
"graph_store": {
"provider": "neo4j",
"config": {
"url": "neo4j+s://---",
"username": "neo4j",
"password": "---"
}
}
}
m = Memory.from_config(config_dict=config)
```
</Tab>
</Tabs>
### Store a Memory
<CodeGroup>
```python Code
# For a user
result = m.add("Likes to play cricket on weekends", user_id="alice", metadata={"category": "hobbies"})
# messages = [
# {"role": "user", "content": "Hi, I'm Alex. I like to play cricket on weekends."},
# {"role": "assistant", "content": "Hello Alex! It's great to know that you enjoy playing cricket on weekends. I'll remember that for future reference."}
# ]
# client.add(messages, user_id="alice")
```
```json Output
{
"results": [
{"id": "bf4d4092-cf91-4181-bfeb-b6fa2ed3061b", "memory": "Likes to play cricket on weekends", "event": "ADD"}
]
}
```
</CodeGroup>
### Retrieve Memories
<CodeGroup>
```python Code
# Get all memories
all_memories = m.get_all(user_id="alice")
```
```json Output
{
"results": [
{
"id": "bf4d4092-cf91-4181-bfeb-b6fa2ed3061b",
"memory": "Likes to play cricket on weekends",
"hash": "285d07801ae42054732314853e9eadd7",
"metadata": {"category": "hobbies"},
"created_at": "2024-10-28T12:32:07.744891-07:00",
"updated_at": None,
"user_id": "alice"
}
]
}
```
</CodeGroup>
<br />
<CodeGroup>
```python Code
# Get a single memory by ID
specific_memory = m.get("bf4d4092-cf91-4181-bfeb-b6fa2ed3061b")
```
```json Output
{
"id": "bf4d4092-cf91-4181-bfeb-b6fa2ed3061b",
"memory": "Likes to play cricket on weekends",
"hash": "285d07801ae42054732314853e9eadd7",
"metadata": {"category": "hobbies"},
"created_at": "2024-10-28T12:32:07.744891-07:00",
"updated_at": None,
"user_id": "alice"
}
```
</CodeGroup>
### Search Memories
<CodeGroup>
```python Code
related_memories = m.search(query="What are Alice's hobbies?", user_id="alice")
```
```json Output
{
"results": [
{
"id": "bf4d4092-cf91-4181-bfeb-b6fa2ed3061b",
"memory": "Likes to play cricket on weekends",
"hash": "285d07801ae42054732314853e9eadd7",
"metadata": {"category": "hobbies"},
"score": 0.30808347,
"created_at": "2024-10-28T12:32:07.744891-07:00",
"updated_at": None,
"user_id": "alice"
}
]
}
```
</CodeGroup>
### Update a Memory
<CodeGroup>
```python Code
result = m.update(memory_id="bf4d4092-cf91-4181-bfeb-b6fa2ed3061b", data="Likes to play tennis on weekends")
```
```json Output
{'message': 'Memory updated successfully!'}
```
</CodeGroup>
### Memory History
<CodeGroup>
```python Code
history = m.history(memory_id="bf4d4092-cf91-4181-bfeb-b6fa2ed3061b")
```
```json Output
[
{
"id": "96d2821d-e551-4089-aa57-9398c421d450",
"memory_id": "bf4d4092-cf91-4181-bfeb-b6fa2ed3061b",
"old_memory": None,
"new_memory": "Likes to play cricket on weekends",
"event": "ADD",
"created_at": "2024-10-28T12:32:07.744891-07:00",
"updated_at": None
},
{
"id": "3db4cb58-c0f1-4dd0-b62a-8123068ebfe7",
"memory_id": "bf4d4092-cf91-4181-bfeb-b6fa2ed3061b",
"old_memory": "Likes to play cricket on weekends",
"new_memory": "Likes to play tennis on weekends",
"event": "UPDATE",
"created_at": "2024-10-28T12:32:07.744891-07:00",
"updated_at": "2024-10-28T13:05:46.987978-07:00"
}
]
```
</CodeGroup>
### Delete Memory
```python
# Delete a memory by id
m.delete(memory_id="bf4d4092-cf91-4181-bfeb-b6fa2ed3061b")
# Delete all memories for a user
m.delete_all(user_id="alice")
```
### Reset Memory
```python
m.reset() # Reset all memories
```
## Configuration Parameters
Mem0 offers extensive configuration options to customize its behavior according to your needs. These configurations span across different components like vector stores, language models, embedders, and graph stores.
<AccordionGroup>
<Accordion title="Vector Store Configuration">
| Parameter | Description | Default |
|-------------|---------------------------------|-------------|
| `provider` | Vector store provider (e.g., "qdrant") | "qdrant" |
| `host` | Host address | "localhost" |
| `port` | Port number | 6333 |
</Accordion>
<Accordion title="LLM Configuration">
| Parameter | Description | Provider |
|-----------------------|-----------------------------------------------|-------------------|
| `provider` | LLM provider (e.g., "openai", "anthropic") | All |
| `model` | 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 |
</Accordion>
<Accordion title="Embedder Configuration">
| Parameter | Description | Default |
|-------------|---------------------------------|------------------------------|
| `provider` | Embedding provider | "openai" |
| `model` | Embedding model to use | "text-embedding-3-small" |
| `api_key` | API key for embedding service | None |
</Accordion>
<Accordion title="Graph Store Configuration">
| Parameter | Description | Default |
|-------------|---------------------------------|-------------|
| `provider` | Graph store provider (e.g., "neo4j") | "neo4j" |
| `url` | Connection URL | None |
| `username` | Authentication username | None |
| `password` | Authentication password | None |
</Accordion>
<Accordion title="General Configuration">
| Parameter | Description | Default |
|------------------|--------------------------------------|----------------------------|
| `history_db_path` | Path to the history database | "{mem0_dir}/history.db" |
| `version` | API version | "v1.1" |
| `custom_prompt` | Custom prompt for memory processing | None |
</Accordion>
<Accordion title="Complete Configuration Example">
```python
config = {
"vector_store": {
"provider": "qdrant",
"config": {
"host": "localhost",
"port": 6333
}
},
"llm": {
"provider": "openai",
"config": {
"api_key": "your-api-key",
"model": "gpt-4"
}
},
"embedder": {
"provider": "openai",
"config": {
"api_key": "your-api-key",
"model": "text-embedding-3-small"
}
},
"graph_store": {
"provider": "neo4j",
"config": {
"url": "neo4j+s://your-instance",
"username": "neo4j",
"password": "password"
}
},
"history_db_path": "/path/to/history.db",
"version": "v1.1",
"custom_prompt": "Optional custom prompt for memory processing"
}
```
</Accordion>
</AccordionGroup>
## Run Mem0 Locally
Please refer to the example [Mem0 with Ollama](../examples/mem0-with-ollama) to run Mem0 locally.
## Chat Completion
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.
If you have a `Mem0 API key`, you can use it to initialize the client. Alternatively, you can initialize Mem0 without an API key if you're using it locally.
Mem0 supports several language models (LLMs) through integration with various [providers](https://litellm.vercel.app/docs/providers).
## Use Mem0 Platform
```python
from mem0.proxy.main import Mem0
client = Mem0(api_key="m0-xxx")
# First interaction: Storing user preferences
messages = [
{
"role": "user",
"content": "I love indian food but I cannot eat pizza since allergic to cheese."
},
]
user_id = "alice"
chat_completion = client.chat.completions.create(messages=messages, model="gpt-4o-mini", user_id=user_id)
# Memory saved after this will look like: "Loves Indian food. Allergic to cheese and cannot eat pizza."
# Second interaction: Leveraging stored memory
messages = [
{
"role": "user",
"content": "Suggest restaurants in San Francisco to eat.",
}
]
chat_completion = client.chat.completions.create(messages=messages, model="gpt-4o-mini", user_id=user_id)
print(chat_completion.choices[0].message.content)
# Answer: You might enjoy Indian restaurants in San Francisco, such as Amber India, Dosa, or Curry Up Now, which offer delicious options without cheese.
```
In this example, you can see how the second response is tailored based on the information provided in the first interaction. Mem0 remembers the user's preference for Indian food and their cheese allergy, using this information to provide more relevant and personalized restaurant suggestions in San Francisco.
### Use Mem0 OSS
```python
config = {
"vector_store": {
"provider": "qdrant",
"config": {
"host": "localhost",
"port": 6333,
}
},
}
client = Mem0(config=config)
chat_completion = client.chat.completions.create(
messages=[
{
"role": "user",
"content": "What's the capital of France?",
}
],
model="gpt-4o",
)
```
## APIs
Get started with using Mem0 APIs in your applications. For more details, refer to the [Platform](/platform/quickstart.mdx).
Here is an example of how to use Mem0 APIs:
```python
import os
from mem0 import MemoryClient
os.environ["MEM0_API_KEY"] = "your-api-key"
client = MemoryClient() # get api_key from https://app.mem0.ai/
# Store messages
messages = [
{"role": "user", "content": "Hi, I'm Alex. I'm a vegetarian and I'm allergic to nuts."},
{"role": "assistant", "content": "Hello Alex! I've noted that you're a vegetarian and have a nut allergy. I'll keep this in mind for any food-related recommendations or discussions."}
]
result = client.add(messages, user_id="alex")
print(result)
# Retrieve memories
all_memories = client.get_all(user_id="alex")
print(all_memories)
# Search memories
query = "What do you know about me?"
related_memories = client.search(query, user_id="alex")
# Get memory history
history = client.history(memory_id="m1")
print(history)
```
## Contributing
We welcome contributions to Mem0! Here's how you can contribute:
1. Fork the repository and create your branch from `main`.
2. Clone the forked repository to your local machine.
3. Install the project dependencies:
```bash
poetry install
```
4. Install pre-commit hooks:
```bash
pip install pre-commit # If pre-commit is not already installed
pre-commit install
```
5. Make your changes and ensure they adhere to the project's coding standards.
6. Run the tests locally:
```bash
poetry run pytest
```
7. If all tests pass, commit your changes and push to your fork.
8. Open a pull request with a clear title and description.
Please make sure your code follows our coding conventions and is well-documented. We appreciate your contributions to make Mem0 better!
If you have any questions, please feel free to reach out to us using one of the following methods:
<Snippet file="get-help.mdx" />
+20 -478
View File
@@ -1,487 +1,29 @@
---
title: Guide
description: 'Get started with Mem0 quickly!'
title: Overview
icon: "info"
iconType: "solid"
---
> Welcome to the Mem0 quickstart guide. This guide will help you get up and running with Mem0 in no time.
Welcome to Mem0 Open Source - a powerful, self-hosted memory management solution for AI agents and assistants. With Mem0 OSS, you get full control over your infrastructure while maintaining complete customization flexibility.
## Installation
We offer two SDKs for Python and Node.js.
To install Mem0, you can use pip. Run the following command in your terminal:
Check out our [GitHub repository](https://mem0.dev/gd) to explore the source code.
```bash
pip install mem0ai
```
<CardGroup cols={2}>
<Card title="Python SDK Guide" icon="python" href="/open-source/python-quickstart">
Learn more about Mem0 OSS Python SDK
</Card>
<Card title="Node.js SDK Guide" icon="node" href="/open-source-typescript/quickstart">
Learn more about Mem0 OSS Node.js SDK
</Card>
</CardGroup>
## Basic Usage
## Key Features
### Initialize Mem0
- **Full Infrastructure Control**: Host Mem0 on your own servers
- **Customizable Implementation**: Modify and extend functionality as needed
- **Local Development**: Perfect for development and testing
- **No Vendor Lock-in**: Own your data and infrastructure
- **Community Driven**: Benefit from and contribute to community improvements
<Tabs>
<Tab title="Basic">
```python
from mem0 import Memory
m = Memory()
```
</Tab>
<Tab title="Advanced">
If you want to run Mem0 in production, initialize using the following method:
Run Qdrant first:
```bash
docker pull qdrant/qdrant
docker run -p 6333:6333 -p 6334:6334 \
-v $(pwd)/qdrant_storage:/qdrant/storage:z \
qdrant/qdrant
```
Then, instantiate memory with qdrant server:
```python
from mem0 import Memory
config = {
"vector_store": {
"provider": "qdrant",
"config": {
"host": "localhost",
"port": 6333,
}
},
}
m = Memory.from_config(config)
```
</Tab>
<Tab title="Advanced (Graph Memory)">
```python
from mem0 import Memory
config = {
"graph_store": {
"provider": "neo4j",
"config": {
"url": "neo4j+s://---",
"username": "neo4j",
"password": "---"
}
},
"version": "v1.1"
}
m = Memory.from_config(config_dict=config)
```
</Tab>
</Tabs>
### Store a Memory
<CodeGroup>
```python Code
# For a user
result = m.add("Likes to play cricket on weekends", user_id="alice", metadata={"category": "hobbies"})
# messages = [
# {"role": "user", "content": "Hi, I'm Alex. I like to play cricket on weekends."},
# {"role": "assistant", "content": "Hello Alex! It's great to know that you enjoy playing cricket on weekends. I'll remember that for future reference."}
# ]
# client.add(messages, user_id="alice")
```
```json Output
{
"results": [
{"id": "bf4d4092-cf91-4181-bfeb-b6fa2ed3061b", "memory": "Likes to play cricket on weekends", "event": "ADD"}
],
"relations": [
{"source": "alice", "relationship": "likes_to_play", "target": "cricket"},
{"source": "alice", "relationship": "plays_on", "target": "weekends"}
]
}
```
</CodeGroup>
### Retrieve Memories
<CodeGroup>
```python Code
# Get all memories
all_memories = m.get_all(user_id="alice")
```
```json Output
{
"results": [
{
"id": "bf4d4092-cf91-4181-bfeb-b6fa2ed3061b",
"memory": "Likes to play cricket on weekends",
"hash": "285d07801ae42054732314853e9eadd7",
"metadata": {"category": "hobbies"},
"created_at": "2024-10-28T12:32:07.744891-07:00",
"updated_at": None,
"user_id": "alice"
}
],
"relations": [
{"source": "alice", "relationship": "likes_to_play", "target": "cricket"},
{"source": "alice", "relationship": "plays_on", "target": "weekends"}
]
}
```
</CodeGroup>
<br />
<CodeGroup>
```python Code
# Get a single memory by ID
specific_memory = m.get("bf4d4092-cf91-4181-bfeb-b6fa2ed3061b")
```
```json Output
{
"id": "bf4d4092-cf91-4181-bfeb-b6fa2ed3061b",
"memory": "Likes to play cricket on weekends",
"hash": "285d07801ae42054732314853e9eadd7",
"metadata": {"category": "hobbies"},
"created_at": "2024-10-28T12:32:07.744891-07:00",
"updated_at": None,
"user_id": "alice"
}
```
</CodeGroup>
### Search Memories
<CodeGroup>
```python Code
related_memories = m.search(query="What are Alice's hobbies?", user_id="alice")
```
```json Output
{
"results": [
{
"id": "bf4d4092-cf91-4181-bfeb-b6fa2ed3061b",
"memory": "Likes to play cricket on weekends",
"hash": "285d07801ae42054732314853e9eadd7",
"metadata": {"category": "hobbies"},
"score": 0.30808347,
"created_at": "2024-10-28T12:32:07.744891-07:00",
"updated_at": None,
"user_id": "alice"
}
],
"relations": [
{"source": "alice", "relationship": "plays_on", "target": "weekends"},
{"source": "alice", "relationship": "likes_to_play", "target": "cricket"}
]
}
```
</CodeGroup>
### Update a Memory
<CodeGroup>
```python Code
result = m.update(memory_id="bf4d4092-cf91-4181-bfeb-b6fa2ed3061b", data="Likes to play tennis on weekends")
```
```json Output
{'message': 'Memory updated successfully!'}
```
</CodeGroup>
### Memory History
<CodeGroup>
```python Code
history = m.history(memory_id="bf4d4092-cf91-4181-bfeb-b6fa2ed3061b")
```
```json Output
[
{
"id": "96d2821d-e551-4089-aa57-9398c421d450",
"memory_id": "bf4d4092-cf91-4181-bfeb-b6fa2ed3061b",
"old_memory": None,
"new_memory": "Likes to play cricket on weekends",
"event": "ADD",
"created_at": "2024-10-28T12:32:07.744891-07:00",
"updated_at": None
},
{
"id": "3db4cb58-c0f1-4dd0-b62a-8123068ebfe7",
"memory_id": "bf4d4092-cf91-4181-bfeb-b6fa2ed3061b",
"old_memory": "Likes to play cricket on weekends",
"new_memory": "Likes to play tennis on weekends",
"event": "UPDATE",
"created_at": "2024-10-28T12:32:07.744891-07:00",
"updated_at": "2024-10-28T13:05:46.987978-07:00"
}
]
```
</CodeGroup>
### Delete Memory
```python
# Delete a memory by id
m.delete(memory_id="bf4d4092-cf91-4181-bfeb-b6fa2ed3061b")
# Delete all memories for a user
m.delete_all(user_id="alice")
```
### Reset Memory
```python
m.reset() # Reset all memories
```
## Configuration Parameters
Mem0 offers extensive configuration options to customize its behavior according to your needs. These configurations span across different components like vector stores, language models, embedders, and graph stores.
<AccordionGroup>
<Accordion title="Vector Store Configuration">
| Parameter | Description | Default |
|-------------|---------------------------------|-------------|
| `provider` | Vector store provider (e.g., "qdrant") | "qdrant" |
| `host` | Host address | "localhost" |
| `port` | Port number | 6333 |
</Accordion>
<Accordion title="LLM Configuration">
| Parameter | Description | Provider |
|-----------------------|-----------------------------------------------|-------------------|
| `provider` | LLM provider (e.g., "openai", "anthropic") | All |
| `model` | 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 |
</Accordion>
<Accordion title="Embedder Configuration">
| Parameter | Description | Default |
|-------------|---------------------------------|------------------------------|
| `provider` | Embedding provider | "openai" |
| `model` | Embedding model to use | "text-embedding-3-small" |
| `api_key` | API key for embedding service | None |
</Accordion>
<Accordion title="Graph Store Configuration">
| Parameter | Description | Default |
|-------------|---------------------------------|-------------|
| `provider` | Graph store provider (e.g., "neo4j") | "neo4j" |
| `url` | Connection URL | None |
| `username` | Authentication username | None |
| `password` | Authentication password | None |
</Accordion>
<Accordion title="General Configuration">
| Parameter | Description | Default |
|------------------|--------------------------------------|----------------------------|
| `history_db_path` | Path to the history database | "{mem0_dir}/history.db" |
| `version` | API version | "v1.0" |
| `custom_prompt` | Custom prompt for memory processing | None |
</Accordion>
<Accordion title="Complete Configuration Example">
```python
config = {
"vector_store": {
"provider": "qdrant",
"config": {
"host": "localhost",
"port": 6333
}
},
"llm": {
"provider": "openai",
"config": {
"api_key": "your-api-key",
"model": "gpt-4"
}
},
"embedder": {
"provider": "openai",
"config": {
"api_key": "your-api-key",
"model": "text-embedding-3-small"
}
},
"graph_store": {
"provider": "neo4j",
"config": {
"url": "neo4j+s://your-instance",
"username": "neo4j",
"password": "password"
}
},
"history_db_path": "/path/to/history.db",
"version": "v1.1",
"custom_prompt": "Optional custom prompt for memory processing"
}
```
</Accordion>
</AccordionGroup>
## Run Mem0 Locally
Please refer to the example [Mem0 with Ollama](../examples/mem0-with-ollama) to run Mem0 locally.
## Chat Completion
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.
If you have a `Mem0 API key`, you can use it to initialize the client. Alternatively, you can initialize Mem0 without an API key if you're using it locally.
Mem0 supports several language models (LLMs) through integration with various [providers](https://litellm.vercel.app/docs/providers).
## Use Mem0 Platform
```python
from mem0.proxy.main import Mem0
client = Mem0(api_key="m0-xxx")
# First interaction: Storing user preferences
messages = [
{
"role": "user",
"content": "I love indian food but I cannot eat pizza since allergic to cheese."
},
]
user_id = "alice"
chat_completion = client.chat.completions.create(messages=messages, model="gpt-4o-mini", user_id=user_id)
# Memory saved after this will look like: "Loves Indian food. Allergic to cheese and cannot eat pizza."
# Second interaction: Leveraging stored memory
messages = [
{
"role": "user",
"content": "Suggest restaurants in San Francisco to eat.",
}
]
chat_completion = client.chat.completions.create(messages=messages, model="gpt-4o-mini", user_id=user_id)
print(chat_completion.choices[0].message.content)
# Answer: You might enjoy Indian restaurants in San Francisco, such as Amber India, Dosa, or Curry Up Now, which offer delicious options without cheese.
```
In this example, you can see how the second response is tailored based on the information provided in the first interaction. Mem0 remembers the user's preference for Indian food and their cheese allergy, using this information to provide more relevant and personalized restaurant suggestions in San Francisco.
### Use Mem0 OSS
```python
config = {
"vector_store": {
"provider": "qdrant",
"config": {
"host": "localhost",
"port": 6333,
}
},
}
client = Mem0(config=config)
chat_completion = client.chat.completions.create(
messages=[
{
"role": "user",
"content": "What's the capital of France?",
}
],
model="gpt-4o",
)
```
## APIs
Get started with using Mem0 APIs in your applications. For more details, refer to the [Platform](/platform/quickstart.mdx).
Here is an example of how to use Mem0 APIs:
```python
from mem0 import MemoryClient
client = MemoryClient(api_key="your-api-key") # get api_key from https://app.mem0.ai/
# Store messages
messages = [
{"role": "user", "content": "Hi, I'm Alex. I'm a vegetarian and I'm allergic to nuts."},
{"role": "assistant", "content": "Hello Alex! I've noted that you're a vegetarian and have a nut allergy. I'll keep this in mind for any food-related recommendations or discussions."}
]
result = client.add(messages, user_id="alex")
print(result)
# Retrieve memories
all_memories = client.get_all(user_id="alex")
print(all_memories)
# Search memories
query = "What do you know about me?"
related_memories = client.search(query, user_id="alex")
# Get memory history
history = client.history(memory_id="m1")
print(history)
```
## Contributing
We welcome contributions to Mem0! Here's how you can contribute:
1. Fork the repository and create your branch from `main`.
2. Clone the forked repository to your local machine.
3. Install the project dependencies:
```bash
poetry install
```
4. Install pre-commit hooks:
```bash
pip install pre-commit # If pre-commit is not already installed
pre-commit install
```
5. Make your changes and ensure they adhere to the project's coding standards.
6. Run the tests locally:
```bash
poetry run pytest
```
7. If all tests pass, commit your changes and push to your fork.
8. Open a pull request with a clear title and description.
Please make sure your code follows our coding conventions and is well-documented. We appreciate your contributions to make Mem0 better!
If you have any questions, please feel free to reach out to us using one of the following methods:
<Snippet file="get-help.mdx" />
+558 -36
View File
@@ -774,26 +774,20 @@
"type": "string",
"format": "date-time"
},
"total_memories": {
"type": "integer"
},
"owner": {
"type": "string"
},
"immutable": {
"type": "boolean",
"description": "Whether the memory is immutable.",
"title": "Immutable",
"default": false
},
"organization": {
"type": "string"
},
"metadata": {
"type": "object"
},
"type": {
"type": "string",
"enum": [
"user",
"agent",
"app",
"run"
]
}
},
"required": [
@@ -1097,6 +1091,7 @@
"created_at": {"type": "string", "format": "date-time"},
"updated_at": {"type": "string", "format": "date-time"},
"categories": {"type": "array", "items": {"type": "string"}},
"metadata": {"type": "object"},
"keywords": {"type": "string"}
},
"additionalProperties": {
@@ -1117,6 +1112,15 @@
"style": "deepObject",
"explode": true
},
{
"name": "fields",
"in": "query",
"schema": {
"type": "array",
"items": {"type": "string"}
},
"description": "A list of field names to include in the response. If not provided, all fields will be returned."
},
{
"name": "org_id",
"in": "query",
@@ -1170,26 +1174,20 @@
"type": "string",
"format": "date-time"
},
"total_memories": {
"type": "integer"
},
"owner": {
"type": "string"
},
"immutable": {
"type": "boolean",
"description": "Whether the memory is immutable.",
"title": "Immutable",
"default": false
},
"organization": {
"type": "string"
},
"metadata": {
"type": "object"
},
"type": {
"type": "string",
"enum": [
"user",
"agent",
"app",
"run"
]
}
},
"required": [
@@ -1320,6 +1318,12 @@
},
"description": "Categories associated with the memory"
},
"immutable": {
"type": "boolean",
"description": "Whether the memory is immutable.",
"title": "Immutable",
"default": false
},
"created_at": {
"type": "string",
"format": "date-time",
@@ -1441,6 +1445,12 @@
},
"description": "Categories associated with the memory"
},
"immutable": {
"type": "boolean",
"description": "Whether the memory is immutable.",
"title": "Immutable",
"default": false
},
"created_at": {
"type": "string",
"format": "date-time",
@@ -4140,6 +4150,506 @@
}
]
}
},
"/api/v1/webhooks/projects/{project_id}/": {
"get": {
"tags": ["webhooks"],
"summary": "Get Project Webhooks",
"description": "Retrieve all webhooks for a specific project",
"operationId": "get_project_webhooks",
"parameters": [
{
"name": "project_id",
"in": "path",
"required": true,
"description": "Unique identifier of the project",
"schema": {
"type": "string"
}
}
],
"responses": {
"200": {
"description": "List of webhooks for the project",
"content": {
"application/json": {
"schema": {
"type": "array",
"items": {
"type": "object",
"properties": {
"webhook_id": {
"type": "string",
"description": "Unique identifier of the webhook"
},
"name": {
"type": "string",
"description": "Name of the webhook"
},
"url": {
"type": "string",
"description": "URL endpoint for the webhook"
},
"event_types": {
"type": "array",
"items": {
"type": "string"
},
"description": "List of event types the webhook subscribes to"
},
"is_active": {
"type": "boolean",
"description": "Whether the webhook is active"
},
"project": {
"type": "string",
"description": "Name of the project the webhook is associated with"
},
"created_at": {
"type": "string",
"format": "date-time",
"description": "Timestamp when the webhook was created"
},
"updated_at": {
"type": "string",
"format": "date-time",
"description": "Timestamp when the webhook was last updated"
}
}
}
}
}
}
},
"403": {
"description": "Unauthorized access",
"content": {
"application/json": {
"schema": {
"type": "object",
"properties": {
"error": {
"type": "string",
"example": "You don't have access to this project"
}
}
}
}
}
}
},
"x-code-samples": [
{
"lang": "Python",
"source": "# To use the Python SDK, install the package:\n# pip install mem0ai\n\nfrom mem0 import MemoryClient\nclient = MemoryClient(api_key=\"your_api_key\")\n\n# Get all webhooks\nwebhooks = client.get_webhooks(project_id=\"your_project_id\")\nprint(webhooks)\n\n# Create a webhook\nwebhook = client.create_webhook(\n url=\"https://your-webhook-url.com\",\n name=\"My Webhook\",\n project_id=\"your_project_id\",\n event_types=[\"memory:add\"]\n)\nprint(webhook)"
},
{
"lang": "JavaScript",
"source": "// To use the JavaScript SDK, install the package:\n// npm i mem0ai\n\nimport MemoryClient from 'mem0ai';\nconst client = new MemoryClient({ apiKey: 'your-api-key' });\n\n// Get all webhooks\nclient.getWebhooks('your_project_id')\n .then(webhooks => console.log(webhooks))\n .catch(err => console.error(err));\n\n// Create a webhook\nclient.createWebhook({\n url: 'https://your-webhook-url.com',\n name: 'My Webhook',\n project_id: 'your_project_id',\n event_types: ['memory:add']\n})\n .then(webhook => console.log(webhook))\n .catch(err => console.error(err));"
},
{
"lang": "cURL",
"source": "# Get all webhooks\ncurl --request GET \\\n --url 'https://api.mem0.ai/api/v1/webhooks/your_project_id/webhook/' \\\n --header 'Authorization: Token your-api-key'\n\n# Create a webhook\ncurl --request POST \\\n --url 'https://api.mem0.ai/api/v1/webhooks/your_project_id/webhook/' \\\n --header 'Authorization: Token your-api-key' \\\n --header 'Content-Type: application/json' \\\n --data '{\n \"url\": \"https://your-webhook-url.com\",\n \"name\": \"My Webhook\",\n \"event_types\": [\"memory:add\"]\n }'"
},
{
"lang": "PHP",
"source": "<?php\n\n$curl = curl_init();\n\n// Get all webhooks\ncurl_setopt_array($curl, [\n CURLOPT_URL => \"https://api.mem0.ai/api/v1/webhooks/your_project_id/webhook/\",\n CURLOPT_RETURNTRANSFER => true,\n CURLOPT_HTTPHEADER => [\"Authorization: Token your-api-key\"],\n]);\n\n$response = curl_exec($curl);\n\n// Create a webhook\ncurl_setopt_array($curl, [\n CURLOPT_URL => \"https://api.mem0.ai/api/v1/webhooks/your_project_id/webhook/\",\n CURLOPT_RETURNTRANSFER => true,\n CURLOPT_POST => true,\n CURLOPT_POSTFIELDS => json_encode([\n \"url\" => \"https://your-webhook-url.com\",\n \"name\" => \"My Webhook\",\n \"event_types\" => [\"memory:add\"]\n ]),\n CURLOPT_HTTPHEADER => [\n \"Authorization: Token your-api-key\",\n \"Content-Type: application/json\"\n ],\n]);\n\n$response = curl_exec($curl);\ncurl_close($curl);"
},
{
"lang": "Go",
"source": "package main\n\nimport (\n\t\"fmt\"\n\t\"strings\"\n\t\"net/http\"\n\t\"io/ioutil\"\n)\n\nfunc main() {\n\t// Get all webhooks\n\treq, _ := http.NewRequest(\"GET\", \"https://api.mem0.ai/api/v1/webhooks/your_project_id/webhook/\", nil)\n\treq.Header.Add(\"Authorization\", \"Token your-api-key\")\n\n\tres, _ := http.DefaultClient.Do(req)\n\tdefer res.Body.Close()\n\tbody, _ := ioutil.ReadAll(res.Body)\n\tfmt.Println(string(body))\n\n\t// Create a webhook\n\tpayload := strings.NewReader(`{\n\t\t\"url\": \"https://your-webhook-url.com\",\n\t\t\"name\": \"My Webhook\",\n\t\t\"event_types\": [\"memory:add\"]\n\t}`)\n\n\treq, _ = http.NewRequest(\"POST\", \"https://api.mem0.ai/api/v1/webhooks/your_project_id/webhook/\", payload)\n\treq.Header.Add(\"Authorization\", \"Token your-api-key\")\n\treq.Header.Add(\"Content-Type\", \"application/json\")\n\n\tres, _ = http.DefaultClient.Do(req)\n\tdefer res.Body.Close()\n\tbody, _ = ioutil.ReadAll(res.Body)\n\tfmt.Println(string(body))\n}"
},
{
"lang": "Java",
"source": "// Get all webhooks\nHttpResponse<String> response = Unirest.get(\"https://api.mem0.ai/api/v1/webhooks/your_project_id/webhook/\")\n .header(\"Authorization\", \"Token your-api-key\")\n .asString();\n\n// Create a webhook\nHttpResponse<String> response = Unirest.post(\"https://api.mem0.ai/api/v1/webhooks/your_project_id/webhook/\")\n .header(\"Authorization\", \"Token your-api-key\")\n .header(\"Content-Type\", \"application/json\")\n .body(\"{\n \\\"url\\\": \\\"https://your-webhook-url.com\\\",\n \\\"name\\\": \\\"My Webhook\\\",\n \\\"event_types\\\": [\\\"memory:add\\\"]\n }\")\n .asString();"
}
]
},
"post": {
"tags": ["webhooks"],
"summary": "Create Webhook",
"description": "Create a new webhook for a specific project",
"operationId": "create_webhook",
"parameters": [
{
"name": "project_id",
"in": "path",
"required": true,
"description": "Unique identifier of the project",
"schema": {
"type": "string"
}
}
],
"requestBody": {
"required": true,
"content": {
"application/json": {
"schema": {
"type": "object",
"required": ["url"],
"properties": {
"name": {
"type": "string",
"description": "Name of the webhook"
},
"url": {
"type": "string",
"description": "URL endpoint for the webhook"
},
"event_types": {
"type": "array",
"items": {
"type": "string",
"enum": ["memory:add", "memory:update", "memory:delete"]
},
"description": "List of event types to subscribe to"
},
"is_active": {
"type": "boolean",
"description": "Whether the webhook is active"
},
"project_id": {
"type": "string",
"description": "Unique identifier of the project"
}
}
}
}
}
},
"responses": {
"201": {
"description": "Webhook created successfully",
"content": {
"application/json": {
"schema": {
"type": "object",
"properties": {
"webhook_id": {
"type": "string"
},
"name": {
"type": "string"
},
"url": {
"type": "string"
},
"event_types": {
"type": "array",
"items": {
"type": "string"
}
},
"is_active": {
"type": "boolean"
},
"project": {
"type": "string"
},
"created_at": {
"type": "string",
"format": "date-time"
},
"updated_at": {
"type": "string",
"format": "date-time"
}
}
}
}
}
},
"400": {
"description": "Invalid request",
"content": {
"application/json": {
"schema": {
"type": "object",
"properties": {
"error": {
"type": "string"
}
}
}
}
}
},
"403": {
"description": "Unauthorized access",
"content": {
"application/json": {
"schema": {
"type": "object",
"properties": {
"error": {
"type": "string",
"example": "You don't have access to this project"
}
}
}
}
}
}
},
"x-code-samples": [
{
"lang": "Python",
"source": "# To use the Python SDK, install the package:\n# pip install mem0ai\n\nfrom mem0 import MemoryClient\nclient = MemoryClient(api_key=\"your_api_key\", org_id=\"your_org_id\", project_id=\"your_project_id\")\n\n# Create a webhook\nwebhook = client.create_webhook(\n url=\"https://your-webhook-url.com\",\n name=\"My Webhook\",\n project_id=\"your_project_id\",\n event_types=[\"memory:add\"]\n)\nprint(webhook)"
},
{
"lang": "JavaScript",
"source": "// To use the JavaScript SDK, install the package:\n// npm i mem0ai\n\nimport MemoryClient from 'mem0ai';\nconst client = new MemoryClient({ apiKey: \"your-api-key\" });\n\n// Create a webhook\nclient.createWebhook({\n url: \"https://your-webhook-url.com\",\n name: \"My Webhook\",\n project_id: \"your_project_id\",\n event_types: [\"memory:add\"]\n})\n .then(response => console.log('Create webhook response:', response))\n .catch(error => console.error(error));"
},
{
"lang": "cURL",
"source": "curl -X POST \"https://api.mem0.ai/api/v1/webhooks/your_project_id/webhook/\" \\\n -H \"Authorization: Token your-api-key\" \\\n -H \"Content-Type: application/json\" \\\n -d '{\n \"url\": \"https://your-webhook-url.com\",\n \"name\": \"My Webhook\",\n \"event_types\": [\"memory:add\"]\n }'"
},
{
"lang": "PHP",
"source": "<?php\n\n$curl = curl_init();\n\ncurl_setopt_array($curl, [\n CURLOPT_URL => \"https://api.mem0.ai/api/v1/webhooks/your_project_id/webhook/\",\n CURLOPT_RETURNTRANSFER => true,\n CURLOPT_POST => true,\n CURLOPT_POSTFIELDS => json_encode([\n \"url\" => \"https://your-webhook-url.com\",\n \"name\" => \"My Webhook\",\n \"event_types\" => [\"memory:add\"]\n ]),\n CURLOPT_HTTPHEADER => [\n \"Authorization: Token your-api-key\",\n \"Content-Type: application/json\"\n ],\n]);\n\n$response = curl_exec($curl);\ncurl_close($curl);\n\necho $response;"
},
{
"lang": "Go",
"source": "package main\n\nimport (\n \"fmt\"\n \"strings\"\n \"net/http\"\n \"io/ioutil\"\n)\n\nfunc main() {\n payload := strings.NewReader(`{\n \"url\": \"https://your-webhook-url.com\",\n \"name\": \"My Webhook\",\n \"event_types\": [\"memory:add\"]\n }`)\n\n req, _ := http.NewRequest(\"POST\", \"https://api.mem0.ai/api/v1/webhooks/your_project_id/webhook/\", payload)\n req.Header.Add(\"Authorization\", \"Token your-api-key\")\n req.Header.Add(\"Content-Type\", \"application/json\")\n\n res, _ := http.DefaultClient.Do(req)\n defer res.Body.Close()\n body, _ := ioutil.ReadAll(res.Body)\n\n fmt.Println(string(body))\n}"
},
{
"lang": "Java",
"source": "import com.konghq.unirest.http.HttpResponse;\nimport com.konghq.unirest.http.Unirest;\n\n// Create a webhook\nHttpResponse<String> response = Unirest.post(\"https://api.mem0.ai/api/v1/webhooks/your_project_id/webhook/\")\n .header(\"Authorization\", \"Token your-api-key\")\n .header(\"Content-Type\", \"application/json\")\n .body(\"{\n \\\"url\\\": \\\"https://your-webhook-url.com\\\",\n \\\"name\\\": \\\"My Webhook\\\",\n \\\"event_types\\\": [\\\"memory:add\\\"]\n }\")\n .asString();\n\nSystem.out.println(response.getBody());"
}
]
}
},
"/api/v1/webhooks/{webhook_id}/": {
"put": {
"tags": ["webhooks"],
"summary": "Update Webhook",
"description": "Update an existing webhook",
"operationId": "update_webhook",
"parameters": [
{
"name": "webhook_id",
"in": "path",
"required": true,
"description": "Unique identifier of the webhook",
"schema": {
"type": "string"
}
}
],
"requestBody": {
"required": true,
"content": {
"application/json": {
"schema": {
"type": "object",
"properties": {
"name": {
"type": "string",
"description": "New name for the webhook"
},
"url": {
"type": "string",
"description": "New URL endpoint for the webhook"
},
"event_types": {
"type": "array",
"items": {
"type": "string",
"enum": ["memory:add", "memory:update", "memory:delete"]
},
"description": "New list of event types to subscribe to"
}
}
}
}
}
},
"responses": {
"200": {
"description": "Webhook updated successfully",
"content": {
"application/json": {
"schema": {
"type": "object",
"properties": {
"message": {
"type": "string",
"example": "Webhook updated successfully"
}
}
}
}
}
},
"400": {
"description": "Invalid request",
"content": {
"application/json": {
"schema": {
"type": "object",
"properties": {
"error": {
"type": "string"
}
}
}
}
}
},
"403": {
"description": "Unauthorized access",
"content": {
"application/json": {
"schema": {
"type": "object",
"properties": {
"error": {
"type": "string",
"example": "You don't have access to this webhook"
}
}
}
}
}
},
"404": {
"description": "Webhook not found",
"content": {
"application/json": {
"schema": {
"type": "object",
"properties": {
"error": {
"type": "string",
"example": "Webhook not found"
}
}
}
}
}
}
},
"x-code-samples": [
{
"lang": "Python",
"source": "# To use the Python SDK, install the package:\n# pip install mem0ai\n\nfrom mem0 import MemoryClient\nclient = MemoryClient(api_key=\"your_api_key\")\n\n# Update a webhook\nwebhook = client.update_webhook(\n webhook_id=\"your_webhook_id\",\n name=\"Updated Webhook\",\n url=\"https://new-webhook-url.com\",\n event_types=[\"memory:add\"]\n)\nprint(webhook)\n\n# Delete a webhook\nresponse = client.delete_webhook(webhook_id=\"your_webhook_id\")\nprint(response)"
},
{
"lang": "JavaScript",
"source": "// To use the JavaScript SDK, install the package:\n// npm i mem0ai\n\nimport MemoryClient from 'mem0ai';\nconst client = new MemoryClient({ apiKey: 'your-api-key' });\n\n// Update a webhook\nclient.updateWebhook('your_webhook_id', {\n name: 'Updated Webhook',\n url: 'https://new-webhook-url.com',\n event_types: ['memory:add']\n})\n .then(webhook => console.log(webhook))\n .catch(err => console.error(err));\n\n// Delete a webhook\nclient.deleteWebhook('your_webhook_id')\n .then(response => console.log(response))\n .catch(err => console.error(err));"
},
{
"lang": "cURL",
"source": "# Update a webhook\ncurl --request PUT \\\n --url 'https://api.mem0.ai/api/v1/webhooks/your_webhook_id/webhook/' \\\n --header 'Authorization: Token your-api-key' \\\n --header 'Content-Type: application/json' \\\n --data '{\n \"name\": \"Updated Webhook\",\n \"url\": \"https://new-webhook-url.com\",\n \"event_types\": [\"memory:add\"]\n }'\n\n# Delete a webhook\ncurl --request DELETE \\\n --url 'https://api.mem0.ai/api/v1/webhooks/your_webhook_id/webhook/' \\\n --header 'Authorization: Token your-api-key'"
},
{
"lang": "PHP",
"source": "<?php\n\n$curl = curl_init();\n\n// Update a webhook\ncurl_setopt_array($curl, [\n CURLOPT_URL => \"https://api.mem0.ai/api/v1/webhooks/your_webhook_id/webhook/\",\n CURLOPT_RETURNTRANSFER => true,\n CURLOPT_CUSTOMREQUEST => \"PUT\",\n CURLOPT_POSTFIELDS => json_encode([\n \"name\" => \"Updated Webhook\",\n \"url\" => \"https://new-webhook-url.com\",\n \"event_types\" => [\"memory:add\"]\n ]),\n CURLOPT_HTTPHEADER => [\n \"Authorization: Token your-api-key\",\n \"Content-Type: application/json\"\n ],\n]);\n\n$response = curl_exec($curl);\n\n// Delete a webhook\ncurl_setopt_array($curl, [\n CURLOPT_URL => \"https://api.mem0.ai/api/v1/webhooks/your_webhook_id/webhook/\",\n CURLOPT_RETURNTRANSFER => true,\n CURLOPT_CUSTOMREQUEST => \"DELETE\",\n CURLOPT_HTTPHEADER => [\"Authorization: Token your-api-key\"],\n]);\n\n$response = curl_exec($curl);\ncurl_close($curl);"
},
{
"lang": "Go",
"source": "package main\n\nimport (\n\t\"fmt\"\n\t\"strings\"\n\t\"net/http\"\n\t\"io/ioutil\"\n)\n\nfunc main() {\n\t// Update a webhook\n\tpayload := strings.NewReader(`{\n\t\t\"name\": \"Updated Webhook\",\n\t\t\"url\": \"https://new-webhook-url.com\",\n\t\t\"event_types\": [\"memory:add\"]\n\t}`)\n\n\treq, _ := http.NewRequest(\"PUT\", \"https://api.mem0.ai/api/v1/webhooks/your_webhook_id/webhook/\", payload)\n\treq.Header.Add(\"Authorization\", \"Token your-api-key\")\n\treq.Header.Add(\"Content-Type\", \"application/json\")\n\n\tres, _ := http.DefaultClient.Do(req)\n\tdefer res.Body.Close()\n\tbody, _ := ioutil.ReadAll(res.Body)\n\tfmt.Println(string(body))\n\n\t// Delete a webhook\n\treq, _ = http.NewRequest(\"DELETE\", \"https://api.mem0.ai/api/v1/webhooks/your_webhook_id/webhook/\", nil)\n\treq.Header.Add(\"Authorization\", \"Token your-api-key\")\n\n\tres, _ = http.DefaultClient.Do(req)\n\tdefer res.Body.Close()\n\tbody, _ = ioutil.ReadAll(res.Body)\n\tfmt.Println(string(body))\n}"
},
{
"lang": "Java",
"source": "// Update a webhook\nHttpResponse<String> response = Unirest.put(\"https://api.mem0.ai/api/v1/webhooks/your_webhook_id/webhook/\")\n .header(\"Authorization\", \"Token your-api-key\")\n .header(\"Content-Type\", \"application/json\")\n .body(\"{\n \\\"name\\\": \\\"Updated Webhook\\\",\n \\\"url\\\": \\\"https://new-webhook-url.com\\\",\n \\\"event_types\\\": [\\\"memory:add\\\"]\n }\")\n .asString();\n\n// Delete a webhook\nHttpResponse<String> response = Unirest.delete(\"https://api.mem0.ai/api/v1/webhooks/your_webhook_id/webhook/\")\n .header(\"Authorization\", \"Token your-api-key\")\n .asString();"
}
]
},
"delete": {
"tags": ["webhooks"],
"summary": "Delete Webhook",
"description": "Delete an existing webhook",
"operationId": "delete_webhook",
"parameters": [
{
"name": "webhook_id",
"in": "path",
"required": true,
"description": "Unique identifier of the webhook",
"schema": {
"type": "string"
}
}
],
"responses": {
"200": {
"description": "Webhook deleted successfully",
"content": {
"application/json": {
"schema": {
"type": "object",
"properties": {
"message": {
"type": "string",
"example": "Webhook deleted successfully"
}
}
}
}
}
},
"403": {
"description": "Unauthorized access",
"content": {
"application/json": {
"schema": {
"type": "object",
"properties": {
"error": {
"type": "string",
"example": "You don't have access to this webhook"
}
}
}
}
}
},
"404": {
"description": "Webhook not found",
"content": {
"application/json": {
"schema": {
"type": "object",
"properties": {
"error": {
"type": "string",
"example": "Webhook not found"
}
}
}
}
}
}
},
"x-code-samples": [
{
"lang": "Python",
"source": "# To use the Python SDK, install the package:\n# pip install mem0ai\n\nfrom mem0 import MemoryClient\nclient = MemoryClient(api_key=\"your_api_key\", org_id=\"your_org_id\", project_id=\"your_project_id\")\n\n# Delete a webhook\nresponse = client.delete_webhook(webhook_id=\"your_webhook_id\")\nprint(response)"
},
{
"lang": "JavaScript",
"source": "// To use the JavaScript SDK, install the package:\n// npm i mem0ai\n\nimport MemoryClient from 'mem0ai';\nconst client = new MemoryClient({ apiKey: \"your-api-key\" });\n\n// Delete a webhook\nclient.deleteWebhook(\"your_webhook_id\")\n .then(response => console.log('Delete webhook response:', response))\n .catch(error => console.error(error));"
},
{
"lang": "cURL",
"source": "curl -X DELETE \"https://api.mem0.ai/api/v1/webhooks/your_webhook_id/webhook/\" \\\n -H \"Authorization: Token your-api-key\""
},
{
"lang": "PHP",
"source": "<?php\n\n$curl = curl_init();\n\ncurl_setopt_array($curl, [\n CURLOPT_URL => \"https://api.mem0.ai/api/v1/webhooks/your_webhook_id/webhook/\",\n CURLOPT_RETURNTRANSFER => true,\n CURLOPT_CUSTOMREQUEST => \"DELETE\",\n CURLOPT_HTTPHEADER => [\"Authorization: Token your-api-key\"],\n]);\n\n$response = curl_exec($curl);\ncurl_close($curl);\n\necho $response;"
},
{
"lang": "Go",
"source": "package main\n\nimport (\n \"fmt\"\n \"net/http\"\n \"io/ioutil\"\n)\n\nfunc main() {\n req, _ := http.NewRequest(\"DELETE\", \"https://api.mem0.ai/api/v1/webhooks/your_webhook_id/webhook/\", nil)\n req.Header.Add(\"Authorization\", \"Token your-api-key\")\n\n res, _ := http.DefaultClient.Do(req)\n defer res.Body.Close()\n body, _ := ioutil.ReadAll(res.Body)\n\n fmt.Println(string(body))\n}"
},
{
"lang": "Java",
"source": "import com.konghq.unirest.http.HttpResponse;\nimport com.konghq.unirest.http.Unirest;\n\n// Delete a webhook\nHttpResponse<String> response = Unirest.delete(\"https://api.mem0.ai/api/v1/webhooks/your_webhook_id/webhook/\")\n .header(\"Authorization\", \"Token your-api-key\")\n .asString();\n\nSystem.out.println(response.getBody());"
}
]
}
}
},
"components": {
@@ -4276,18 +4786,30 @@
},
"nullable": true
},
"org_id": {
"description": "The unique identifier of the organization associated with this memory.",
"title": "Organization id",
"type": "string",
"nullable": true
},
"project_id": {
"description": "The unique identifier of the project associated with this memory.",
"title": "Project id",
"type": "string",
"nullable": true
}
"custom_instructions": {
"description": "Defines project-specific guidelines for handling and organizing memories. When set at the project level, they apply to all new memories in that project.",
"title": "Custom instructions",
"type": "string",
"nullable": true
},
"immutable": {
"description": "Whether the memory is immutable.",
"title": "Immutable",
"type": "boolean",
"default": false
},
"org_id": {
"description": "The unique identifier of the organization associated with this memory.",
"title": "Organization id",
"type": "string",
"nullable": true
},
"project_id": {
"description": "The unique identifier of the project associated with this memory.",
"title": "Project id",
"type": "string",
"nullable": true
}
}
},
"MemorySearchInput": {
+18 -45
View File
@@ -1,60 +1,34 @@
---
title: Overview
icon: "info"
iconType: "solid"
---
<Note type="info">
🎉 Exciting news! We have added support for [DeepSeek](/components/llms/models/deepseek).
🎉 We now support [Claude 3.7 Sonnet](components/llms/models/anthropic)! Enhance your AI assistants with the latest and most capable language model from Anthropic.
</Note>
[Mem0](https://mem0.dev/wd) (pronounced "mem-zero") enhances AI assistants and agents with an intelligent memory layer, enabling personalized AI interactions. Mem0 remembers user preferences and traits and continuously updates over time, making it ideal for applications like customer support chatbots and AI assistants.
# Introduction
## Understanding Mem0
[Mem0](https://mem0.dev/wd) (pronounced "mem-zero") enhances AI assistants by giving them persistent, contextual memory. AI systems using Mem0 actively learn from and adapt to user interactions over time.
Mem0, described as "_The Memory Layer for your AI Agents_," leverages advanced LLMs and algorithms to detect, store, and retrieve memories from conversations and interactions. It identifies key information such as facts, user preferences, and other contextual information, smartly updates memories over time by resolving contradictions, and supports the development of an AI Agent that evolves with the user interactions. When needed, Mem0 employs a smart search system to find memories, ranking them based on relevance, importance, and recency to ensure only the most useful information is presented.
Mem0's memory layer combines LLMs with vector based storage. LLMs extract and process key information from conversations, while the vector storage enables efficient semantic search and retrieval of memories. This architecture helps AI agents connect past interactions with current context for more relevant responses.
Mem0 provides multiple endpoints through which users can interact with their memories. The two main endpoints are `add` and `search`. The `add` endpoint lets users ingest their conversations into Mem0, storing them as memories. The `search` endpoint handles retrieval, allowing users to query their set of stored memories.
## Key Features
### ADD Memories
- **Memory Processing**: Uses LLMs to automatically extract and store important information from conversations while maintaining full context
- **Memory Management**: Continuously updates and resolves contradictions in stored information to maintain accuracy
- **Dual Storage Architecture**: Combines vector database for memory storage and graph database for relationship tracking
- **Smart Retrieval System**: Employs semantic search and graph queries to find relevant memories based on importance and recency
- **Simple API Integration**: Provides easy-to-use endpoints for adding (`add`) and retrieving (`search`) memories
<Frame caption="Architecture diagram illustrating the process of adding memories.">
<img src="images/add_architecture.png" />
</Frame>
## Use Cases
When a user has a conversation, Mem0 uses an LLM to understand and extract important information. This model is designed to capture detailed information while maintaining the full context of the conversation.
Here's how the process works:
1. First, the LLM extracts two key elements:
* Relevant memories
* Important entities and their relationships
2. The system then compares this new information with existing data to identify contradictions, if present.
3. A second LLM evaluates the new information and decides whether to:
* Add it as new data
* Update existing information
* Delete outdated information
4. These changes are automatically made to two databases:
* A vector database (for storing memories)
* A graph database (for storing relationships)
This entire process happens continuously with each user interaction, ensuring that the system always maintains an up-to-date understanding of the user's information.
### SEARCH Memories
<Frame caption="Architecture diagram illustrating the memory search process.">
<img src="images/search_architecture.png" />
</Frame>
When a user asks Mem0 a question, the system uses smart memory lookup to find relevant information. Here's how it works:
1. The user submits a question to Mem0
2. The LLM processes this question in two ways:
* It rewrites the question to search the vector database better
* It identifies important entities and their relationships from the question
3. The system then performs two parallel searches:
* It searches the vector database using the rewritten question and semantic search
* It searches the graph database using the identified entities and relationships using graph queries
4. Finally, Mem0 combines the results from both databases to provide a complete answer to the user's question
This approach ensures that Mem0 can find and return all relevant information, whether it's stored as memories in the vector database or as relationships in the graph database.
- **Customer Support Chatbots**: Create support agents that remember customer history, preferences, and past interactions to provide personalized assistance
- **Personal AI Tutors**: Build educational assistants that track student progress, adapt to learning patterns, and provide contextual help
- **Healthcare Applications**: Develop healthcare assistants that maintain patient history and provide personalized care recommendations
- **Enterprise Knowledge Management**: Power systems that learn from organizational interactions and maintain institutional knowledge
- **Personalized AI Assistants**: Create assistants that learn user preferences and adapt their responses over time
## Getting Started
Mem0 offers two powerful ways to leverage our technology: our [managed platform](/platform/overview) and our [open source solution](/open-source/quickstart).
@@ -72,7 +46,6 @@ Mem0 offers two powerful ways to leverage our technology: our [managed platform]
</Card>
</CardGroup>
## Need help?
If you have any questions, please feel free to reach out to us using one of the following methods:
+2
View File
@@ -1,6 +1,8 @@
---
title: Introduction
description: 'Empower your AI applications with long-term memory and personalization'
icon: "eye"
iconType: "solid"
---
## Welcome to Mem0 Platform
+147 -2
View File
@@ -1,6 +1,8 @@
---
title: Guide
description: 'Get started with Mem0 Platform in minutes'
icon: "book"
iconType: "solid"
---
<Note type="info">
@@ -403,6 +405,7 @@ curl -X POST "https://api.mem0.ai/v1/memories/search/" \
"user_id": "alex",
"metadata": {"food": "vegan"},
"categories": ["food_preferences"],
"immutable": false,
"created_at": "2024-07-20T01:30:36.275141-07:00",
"updated_at": "2024-07-20T01:30:36.275172-07:00"
}
@@ -418,6 +421,7 @@ curl -X POST "https://api.mem0.ai/v1/memories/search/" \
"user_id": "alex",
"metadata": {"food": "vegan"},
"categories": ["food_preferences"],
"immutable": false,
"created_at": "2024-07-20T01:30:36.275141-07:00",
"updated_at": "2024-07-20T01:30:36.275172-07:00"
}
@@ -461,6 +465,7 @@ curl -X POST "https://api.mem0.ai/v1/memories/search/?version=v2" \
"user_id": "alex",
"metadata": {"food": "vegan"},
"categories": ["food_preferences"],
"immutable": false,
"created_at": "2024-07-20T01:30:36.275141-07:00",
"updated_at": "2024-07-20T01:30:36.275172-07:00"
}
@@ -550,6 +555,7 @@ curl -X POST "https://api.mem0.ai/v1/memories/search/?version=v2" \
"user_id": "alex",
"metadata": null,
"categories": ["food_preferences"],
"immutable": false,
"created_at": "2024-07-20T01:30:36.275141-07:00",
"updated_at": "2024-07-20T01:30:36.275172-07:00"
}
@@ -614,6 +620,7 @@ curl -X POST "https://api.mem0.ai/v1/memories/search/?version=v2" \
"user_id": "alex",
"metadata": null,
"categories": ["food_preferences"],
"immutable": false,
"created_at": "2024-07-20T01:30:36.275141-07:00",
"updated_at": "2024-07-20T01:30:36.275172-07:00"
}
@@ -687,6 +694,7 @@ curl -X POST "https://api.mem0.ai/v1/memories/search/?version=v2" \
"user_id": "alex",
"metadata": {"food": "vegan"},
"categories": ["food_preferences"],
"immutable": false,
"created_at": "2024-07-20T01:30:36.275141-07:00",
"updated_at": "2024-07-20T01:30:36.275172-07:00"
}
@@ -786,6 +794,7 @@ curl -X GET "https://api.mem0.ai/v1/memories/?user_id=alex&page=1&page_size=50"
"agent_id":"travel-assistant",
"hash":"62bc074f56d1f909f1b4c2b639f56f6a",
"metadata":None,
"immutable": false,
"created_at":"2024-07-25T23:57:00.108347-07:00",
"updated_at":"2024-07-25T23:57:00.108367-07:00",
"categories":None
@@ -796,6 +805,7 @@ curl -X GET "https://api.mem0.ai/v1/memories/?user_id=alex&page=1&page_size=50"
"agent_id":"travel-assistant",
"hash":"35a305373d639b0bffc6c2a3e2eb4244",
"metadata":"None",
"immutable": false,
"created_at":"2024-07-26T00:31:03.543759-07:00",
"updated_at":"2024-07-26T00:31:03.543778-07:00",
"categories":None
@@ -818,6 +828,7 @@ curl -X GET "https://api.mem0.ai/v1/memories/?user_id=alex&page=1&page_size=50"
"agent_id":"travel-assistant",
"hash":"62bc074f56d1f909f1b4c2b639f56f6a",
"metadata":None,
"immutable": false,
"created_at":"2024-07-25T23:57:00.108347-07:00",
"updated_at":"2024-07-25T23:57:00.108367-07:00",
"categories":None
@@ -828,6 +839,7 @@ curl -X GET "https://api.mem0.ai/v1/memories/?user_id=alex&page=1&page_size=50"
"agent_id":"travel-assistant",
"hash":"35a305373d639b0bffc6c2a3e2eb4244",
"metadata":"None",
"immutable": false,
"created_at":"2024-07-26T00:31:03.543759-07:00",
"updated_at":"2024-07-26T00:31:03.543778-07:00",
"categories":None
@@ -871,6 +883,7 @@ curl -X GET "https://api.mem0.ai/v1/memories/?agent_id=ai-tutor&page=1&page_size
"agent_id":"ai-tutor",
"hash":"62bc074f56d1f909f1b4c2b639f56f6a",
"metadata":None,
"immutable": false,
"created_at":"2024-07-25T23:57:00.108347-07:00",
"updated_at":"2024-07-25T23:57:00.108367-07:00",
"categories":None
@@ -881,6 +894,7 @@ curl -X GET "https://api.mem0.ai/v1/memories/?agent_id=ai-tutor&page=1&page_size
"agent_id":"ai-tutor",
"hash":"35a305373d639b0bffc6c2a3e2eb4244",
"metadata":None,
"immutable": false,
"created_at":"2024-07-26T00:31:03.543759-07:00",
"updated_at":"2024-07-26T00:31:03.543778-07:00",
"categories":None
@@ -903,6 +917,7 @@ curl -X GET "https://api.mem0.ai/v1/memories/?agent_id=ai-tutor&page=1&page_size
"agent_id": "ai-tutor",
"hash": "62bc074f56d1f909f1b4c2b639f56f6a",
"metadata":None,
"immutable": false,
"created_at": "2024-07-25T23:57:00.108347-07:00",
"updated_at": "2024-07-25T23:57:00.108367-07:00"
},
@@ -912,6 +927,7 @@ curl -X GET "https://api.mem0.ai/v1/memories/?agent_id=ai-tutor&page=1&page_size
"agent_id": "ai-tutor",
"hash": "35a305373d639b0bffc6c2a3e2eb4244",
"metadata":None,
"immutable": false,
"created_at": "2024-07-26T00:31:03.543759-07:00",
"updated_at": "2024-07-26T00:31:03.543778-07:00"
}
@@ -953,6 +969,7 @@ curl -X GET "https://api.mem0.ai/v1/memories/?user_id=alex123&run_id=trip-planni
"user_id":"alex123",
"hash":"d2088c936e259f2f5d2d75543d31401c",
"metadata":None,
"immutable": false,
"created_at":"2024-07-26T00:25:16.566471-07:00",
"updated_at":"2024-07-26T00:25:16.566492-07:00",
"categories":None
@@ -963,6 +980,7 @@ curl -X GET "https://api.mem0.ai/v1/memories/?user_id=alex123&run_id=trip-planni
"user_id":"alex123",
"hash":"d2088c936e259f2f5d2d75543d31401c",
"metadata":None,
"immutable": false,
"created_at":"2024-07-26T00:33:20.350542-07:00",
"updated_at":"2024-07-26T00:33:20.350560-07:00",
"categories":None
@@ -973,6 +991,7 @@ curl -X GET "https://api.mem0.ai/v1/memories/?user_id=alex123&run_id=trip-planni
"user_id":"alex123",
"hash":"d2088c936e259f2f5d2d75543d31401c",
"metadata":None,
"immutable": false,
"created_at":"2024-07-26T00:51:09.642275-07:00",
"updated_at":"2024-07-26T00:51:09.642295-07:00",
"categories":None
@@ -995,6 +1014,7 @@ curl -X GET "https://api.mem0.ai/v1/memories/?user_id=alex123&run_id=trip-planni
"user_id": "alex123",
"hash": "d2088c936e259f2f5d2d75543d31401c",
"metadata":None,
"immutable": false,
"created_at": "2024-07-26T00:25:16.566471-07:00",
"updated_at": "2024-07-26T00:25:16.566492-07:00",
"categories": ["food_preferences"]
@@ -1005,6 +1025,7 @@ curl -X GET "https://api.mem0.ai/v1/memories/?user_id=alex123&run_id=trip-planni
"user_id": "alex123",
"hash": "d2088c936e259f2f5d2d75543d31401c",
"metadata":None,
"immutable": false,
"created_at": "2024-07-26T00:33:20.350542-07:00",
"updated_at": "2024-07-26T00:33:20.350560-07:00",
"categories": ["food_preferences"]
@@ -1015,6 +1036,7 @@ curl -X GET "https://api.mem0.ai/v1/memories/?user_id=alex123&run_id=trip-planni
"user_id": "alex123",
"hash": "d2088c936e259f2f5d2d75543d31401c",
"metadata":None,
"immutable": false,
"created_at": "2024-07-26T00:51:09.642275-07:00",
"updated_at": "2024-07-26T00:51:09.642295-07:00",
"categories": None
@@ -1053,6 +1075,7 @@ curl -X GET "https://api.mem0.ai/v1/memories/582bbe6d-506b-48c6-a4c6-5df3b1e6342
"user_id":"alex123",
"hash":"d2088c936e259f2f5d2d75543d31401c",
"metadata":"None",
"immutable": false,
"created_at":"2024-07-26T00:25:16.566471-07:00",
"updated_at":"2024-07-26T00:25:16.566492-07:00",
"categories": ["travel"]
@@ -1132,6 +1155,7 @@ curl -X GET "https://api.mem0.ai/v1/memories/?user_id=alex123&keywords=to play&p
"user_id": "alex123",
"hash": "d2088c936e259f2f5d2d75543d31401c",
"metadata": null,
"immutable": false,
"created_at": "2024-07-26T00:25:16.566471-07:00",
"updated_at": "2024-07-26T00:25:16.566492-07:00",
"categories": ["likes", "food_preferences"]
@@ -1142,6 +1166,7 @@ curl -X GET "https://api.mem0.ai/v1/memories/?user_id=alex123&keywords=to play&p
"user_id": "alex123",
"hash": "d2088c936e259f2f5d2d75543d31401c",
"metadata": null,
"immutable": false,
"created_at": "2024-07-26T00:33:20.350542-07:00",
"updated_at": "2024-07-26T00:33:20.350560-07:00",
"categories": ["likes"]
@@ -1154,11 +1179,11 @@ curl -X GET "https://api.mem0.ai/v1/memories/?user_id=alex123&keywords=to play&p
#### Get all memories using custom filters
Our advanced retrieval allows you to set custom filters when fetching memories. You can filter by user_id, agent_id, app_id, run_id, created_at, updated_at, categories, and keywords. The filters support logical operators (AND, OR) and comparison operators (in, gte, lte, gt, lt, ne, contains, icontains). For more details, see [V2 Get Memories](/api-reference/memory/v2-get-memories).
Our advanced retrieval allows you to set custom filters when fetching memories. You can filter by user_id, agent_id, app_id, run_id, created_at, updated_at, categories, and keywords. The filters support logical operators (AND, OR) and comparison operators (in, gte, lte, gt, lt, ne, contains, icontains). For more details, see [v2 Get Memories](/api-reference/memory/v2-get-memories).
Here you need to define `version` as `v2` in the get_all method.
Example: Get all memories using user_id and date filters
Example 1. Get all memories using user_id and date filters
<CodeGroup>
@@ -1280,6 +1305,7 @@ curl -X GET "https://api.mem0.ai/v1/memories/?version=v2&page=1&page_size=50" \
"user_id":"alex",
"hash":"62bc074f56d1f909f1b4c2b639f56f6a",
"metadata":null,
"immutable": false,
"created_at":"2024-07-25T23:57:00.108347-07:00",
"updated_at":"2024-07-25T23:57:00.108367-07:00",
"categories": ["food_preferences"]
@@ -1299,6 +1325,125 @@ curl -X GET "https://api.mem0.ai/v1/memories/?version=v2&page=1&page_size=50" \
"user_id":"alex",
"hash":"62bc074f56d1f909f1b4c2b639f56f6a",
"metadata":null,
"immutable": false,
"created_at":"2024-07-25T23:57:00.108347-07:00",
"updated_at":"2024-07-25T23:57:00.108367-07:00",
"categories": ["food_preferences"]
}
]
}
```
</CodeGroup>
Example 2: Search using metadata and categories Filters
<CodeGroup>
```python Python
filters = {
"AND": [
{"metadata": {"food": "vegan"}},
{
"categories":{
"contains": "food_preferences"
}
}
]
}
# Default (No Pagination)
client.get_all(version="v2", filters=filters)
# Pagination (You can also use the page and page_size parameters)
client.get_all(version="v2", filters=filters, page=1, page_size=50)
```
```javascript JavaScript
const filters = {
"AND": [
{"metadata": {"food": "vegan"}},
{
"categories": {
"contains": "food_preferences"
}
}
]
};
// Default (No Pagination)
client.getAll({ version: "v2", filters })
.then(memories => console.log(memories))
.catch(error => console.error(error));
// Pagination (You can also use the page and page_size parameters)
client.getAll({ version: "v2", filters, page: 1, page_size: 50 })
.then(memories => console.log(memories))
.catch(error => console.error(error));
```
```bash cURL
# Default (No Pagination)
curl -X GET "https://api.mem0.ai/v1/memories/?version=v2" \
-H "Authorization: Token your-api-key" \
-H "Content-Type: application/json" \
-d '{
"filters": {
"AND": [
{"metadata": {"food": "vegan"}},
{
"categories": {
"contains": "food_preferences"
}
}
]
}
}'
# Pagination (You can also use the page and page_size parameters)
curl -X GET "https://api.mem0.ai/v1/memories/?version=v2&page=1&page_size=50" \
-H "Authorization: Token your-api-key" \
-H "Content-Type: application/json" \
-d '{
"filters": {
"AND": [
{"metadata": {"food": "vegan"}},
{
"categories": {
"contains": "food_preferences"
}
}
]
}
}'
```
```json Output (Default)
[
{
"id":"f38b689d-6b24-45b7-bced-17fbb4d8bac7",
"memory":"Name: Alex. Vegetarian. Allergic to nuts.",
"user_id":"alex",
"hash":"62bc074f56d1f909f1b4c2b639f56f6a",
"metadata":{"food":"vegan"},
"immutable": false,
"created_at":"2024-07-25T23:57:00.108347-07:00",
"updated_at":"2024-07-25T23:57:00.108367-07:00",
"categories": ["food_preferences"]
}
]
```
```json Output (Paginated)
{
"count": 1,
"next": null,
"previous": null,
"results": [
{
"id":"f38b689d-6b24-45b7-bced-17fbb4d8bac7",
"memory":"Name: Alex. Vegetarian. Allergic to nuts.",
"user_id":"alex",
"hash":"62bc074f56d1f909f1b4c2b639f56f6a",
"metadata":{"food":"vegan"},
"immutable": false,
"created_at":"2024-07-25T23:57:00.108347-07:00",
"updated_at":"2024-07-25T23:57:00.108367-07:00",
"categories": ["food_preferences"]
+128 -82
View File
@@ -1,5 +1,7 @@
---
title: Quickstart
icon: "bolt"
iconType: "solid"
---
Mem0 offers two powerful ways to leverage our technology: [our managed platform](#mem0-platform-managed-solution) and [our open source solution](#mem0-open-source).
@@ -76,16 +78,20 @@ const client = new MemoryClient({ apiKey: 'your-api-key' });
```python Python
messages = [
{"role": "user", "content": "Hi, I'm Alex. I'm a vegetarian and I'm allergic to nuts."},
{"role": "assistant", "content": "Hello Alex! I've noted that you're a vegetarian and have a nut allergy. I'll keep this in mind for any food-related recommendations or discussions."}
{"role": "user", "content": "Thinking of making a sandwich. What do you recommend?"},
{"role": "assistant", "content": "How about adding some cheese for extra flavor?"},
{"role": "user", "content": "Actually, I don't like cheese."},
{"role": "assistant", "content": "I'll remember that you don't like cheese for future recommendations."}
]
client.add(messages, user_id="alex")
```
```javascript JavaScript
const messages = [
{"role": "user", "content": "Hi, I'm Alex. I'm a vegetarian and I'm allergic to nuts."},
{"role": "assistant", "content": "Hello Alex! I've noted that you're a vegetarian and have a nut allergy. I'll keep this in mind for any food-related recommendations or discussions."}
{"role": "user", "content": "Thinking of making a sandwich. What do you recommend?"},
{"role": "assistant", "content": "How about adding some cheese for extra flavor?"},
{"role": "user", "content": "Actually, I don't like cheese."},
{"role": "assistant", "content": "I'll remember that you don't like cheese for future recommendations."}
];
client.add(messages, { user_id: "alex" })
.then(response => console.log(response))
@@ -98,23 +104,28 @@ curl -X POST "https://api.mem0.ai/v1/memories/" \
-H "Content-Type: application/json" \
-d '{
"messages": [
{"role": "user", "content": "Hi, I'm Alex. I'm a vegetarian and I'm allergic to nuts."},
{"role": "assistant", "content": "Hello Alex! I've noted that you're a vegetarian and have a nut allergy. I'll keep this in mind for any food-related recommendations or discussions."}
{"role": "user", "content": "I live in San Francisco. Thinking of making a sandwich. What do you recommend?"},
{"role": "assistant", "content": "How about adding some cheese for extra flavor?"},
{"role": "user", "content": "Actually, I don't like cheese."},
{"role": "assistant", "content": "I'll remember that you don't like cheese for future recommendations."}
],
"user_id": "alex"
}'
```
```json Output
[{'id': '24e466b5-e1c6-4bde-8a92-f09a327ffa60',
'memory': 'Name is Alex',
'event': 'ADD'},
{'id': 'f2d874ac-09c7-49db-b34a-22cf666bd4ad',
'memory': 'Is a vegetarian',
'event': 'ADD'},
{'id': 'bce04006-01e8-4dbc-8a22-67fa46f1822c',
'memory': 'Is allergic to nuts',
'event': 'ADD'}]
[
{
"id": "24e466b5-e1c6-4bde-8a92-f09a327ffa60",
"memory": "Does not like cheese",
"event": "ADD"
},
{
"id": "e8d78459-fadd-4c5a-bece-abb8c3dc7ed7",
"memory": "Lives in San Francisco",
"event": "ADD"
}
]
```
</CodeGroup>
</Accordion>
@@ -127,7 +138,8 @@ curl -X POST "https://api.mem0.ai/v1/memories/" \
<CodeGroup>
```python Python
query = "What can I cook for dinner tonight?"
# Example showing location and preference-aware recommendations
query = "I'm craving some pizza. Any recommendations?"
filters = {
"AND": [
{
@@ -139,7 +151,7 @@ client.search(query, version="v2", filters=filters)
```
```javascript JavaScript
const query = "What can I cook for dinner tonight?";
const query = "I'm craving some pizza. Any recommendations?";
const filters = {
"AND": [
{
@@ -157,7 +169,7 @@ curl -X POST "https://api.mem0.ai/v1/memories/search/?version=v2" \
-H "Authorization: Token your-api-key" \
-H "Content-Type: application/json" \
-d '{
"query": "What can I cook for dinner tonight?",
"query": "I'm craving some pizza. Any recommendations?",
"filters": {
"AND": [
{
@@ -172,11 +184,21 @@ curl -X POST "https://api.mem0.ai/v1/memories/search/?version=v2" \
[
{
"id": "7f165f7e-b411-4afe-b7e5-35789b72c4a5",
"memory": "Name: Alex. Vegetarian. Allergic to nuts.",
"memory": "Does not like cheese",
"user_id": "alex",
"metadata": null,
"created_at": "2024-07-20T01:30:36.275141-07:00",
"updated_at": "2024-07-20T01:30:36.275172-07:00"
"updated_at": "2024-07-20T01:30:36.275172-07:00",
"score": 0.92
},
{
"id": "8f165f7e-b411-4afe-b7e5-35789b72c4b6",
"memory": "Lives in San Francisco",
"user_id": "alex",
"metadata": null,
"created_at": "2024-07-20T01:30:36.275141-07:00",
"updated_at": "2024-07-20T01:30:36.275172-07:00",
"score": 0.85
}
]
```
@@ -191,7 +213,7 @@ curl -X POST "https://api.mem0.ai/v1/memories/search/?version=v2" \
filters = {
"AND": [
{
"user_id": "alice"
"user_id": "alex"
}
]
}
@@ -203,7 +225,7 @@ all_memories = client.get_all(version="v2", filters=filters, page=1, page_size=5
const filters = {
"AND": [
{
"user_id": "alice"
"user_id": "alex"
}
]
};
@@ -230,24 +252,24 @@ curl -X GET "https://api.mem0.ai/v1/memories/?version=v2&page=1&page_size=50" \
```json Output
[
{
"id":"f38b689d-6b24-45b7-bced-17fbb4d8bac7",
"memory":"是素食主义者,对坚果过敏。",
"agent_id":"travel-assistant",
"hash":"62bc074f56d1f909f1b4c2b639f56f6a",
"metadata":"None",
"created_at":"2024-07-25T23:57:00.108347-07:00",
"updated_at":"2024-07-25T23:57:00.108367-07:00"
},
{
"id":"0a14d8f0-e364-4f5c-b305-10da1f0d0878",
"memory":"Will maintain personalized travel preferences for each user. Provide customized recommendations based on dietary restrictions, interests, and past interactions.",
"agent_id":"travel-assistant",
"hash":"35a305373d639b0bffc6c2a3e2eb4244",
"metadata":"None",
"created_at":"2024-07-26T00:31:03.543759-07:00",
"updated_at":"2024-07-26T00:31:03.543778-07:00"
}
{
"id": "7f165f7e-b411-4afe-b7e5-35789b72c4a5",
"memory": "Does not like cheese",
"user_id": "alex",
"metadata": null,
"created_at": "2024-07-20T01:30:36.275141-07:00",
"updated_at": "2024-07-20T01:30:36.275172-07:00",
"score": 0.92
},
{
"id": "8f165f7e-b411-4afe-b7e5-35789b72c4b6",
"memory": "Lives in San Francisco",
"user_id": "alex",
"metadata": null,
"created_at": "2024-07-20T01:30:36.275141-07:00",
"updated_at": "2024-07-20T01:30:36.275172-07:00",
"score": 0.85
}
]
```
</CodeGroup>
@@ -272,9 +294,15 @@ Follow the steps below to get started with Mem0 Open Source:
<AccordionGroup>
<Accordion title="Install package">
```bash
<CodeGroup>
```bash pip
pip install mem0ai
```
```bash npm
npm install mem0ai
```
</CodeGroup>
</Accordion>
</AccordionGroup>
@@ -282,22 +310,42 @@ pip install mem0ai
<AccordionGroup>
<Accordion title="Instantiate client">
<CodeGroup>
```python Python
from mem0 import Memory
m = Memory()
```
```typescript TypeScript
import { Memory } from 'mem0ai/oss';
const memory = new Memory();
```
</CodeGroup>
</Accordion>
<Accordion title="Add memories">
<CodeGroup>
```python Code
# For a user
result = m.add("I like to take long walks on weekends.", user_id="alice", metadata={"category": "hobbies"})
result = m.add("I like to drink coffee in the morning and go for a walk.", user_id="alice", metadata={"category": "preferences"})
```
```typescript TypeScript
const result = memory.add("I like to drink coffee in the morning and go for a walk.", { userId: "alice", metadata: { category: "preferences" } });
```
```json Output
[{'id': 'ea9b08ee-09d7-4e8b-9912-687ad65548b4',
'memory': 'Likes to take long walks on weekends',
'event': 'ADD'}]
[
{
"id": "3dc6f65f-fb3f-4e91-89a8-ed1a22f8898a",
"data": {"memory": "Likes to drink coffee in the morning"},
"event": "ADD"
},
{
"id": "f1673706-e3d6-4f12-a767-0384c7697d53",
"data": {"memory": "Likes to go for a walk"},
"event": "ADD"
}
]
```
</CodeGroup>
</Accordion>
@@ -308,52 +356,50 @@ result = m.add("I like to take long walks on weekends.", user_id="alice", metada
<AccordionGroup>
<Accordion title="Search for relevant memories">
<CodeGroup>
```python Code
related_memories = m.search(query="Help me plan my weekend.", user_id="alice")
```python Python
related_memories = m.search("Should I drink coffee or tea?", user_id="alice")
```
```typescript TypeScript
const relatedMemories = memory.search("Should I drink coffee or tea?", { userId: "alice" });
```
```json Output
[
{
"id":"ea925981-272f-40dd-b576-be64e4871429",
"memory":"Likes to take long walks 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"
}
{
"id": "3dc6f65f-fb3f-4e91-89a8-ed1a22f8898a",
"memory": "Likes to drink coffee in the morning",
"user_id": "alice",
"metadata": {"category": "preferences"},
"categories": ["user_preferences", "food"],
"immutable": false,
"created_at": "2025-02-24T20:11:39.010261-08:00",
"updated_at": "2025-02-24T20:11:39.010274-08:00",
"score": 0.5915589089130715
},
{
"id": "e8d78459-fadd-4c5a-bece-abb8c3dc7ed7",
"memory": "Likes to go for a walk",
"user_id": "alice",
"metadata": {"category": "preferences"},
"categories": ["hobby", "food"],
"immutable": false,
"created_at": "2025-02-24T11:47:52.893038-08:00",
"updated_at": "2025-02-24T11:47:52.893048-08:00",
"score": 0.43263634637810866
}
]
```
</CodeGroup>
</Accordion>
<Accordion title="Get all memories of a user">
<CodeGroup>
```python Code
# Get all memories
all_memories = m.get_all(user_id="alice")
```
```json Output
[
{
"id":"13efe83b-a8df-4ec0-814e-428d6e8451eb",
"memory":"Likes to take long walks on weekends",
"hash":"87bcddeb-fe45-4353-bc22-15a841c50308",
"metadata":"None",
"created_at":"2024-07-26T08:44:41.039788-07:00",
"updated_at":"None",
"user_id":"alice"
}
]
```
</CodeGroup>
</Accordion>
</AccordionGroup>
<Card title="Mem0 Open source" icon="code-branch" href="/open-source/overview">
Learn more about Mem0 open source
<CardGroup cols={2}>
<Card title="Mem0 OSS Python SDK" icon="python" href="/open-source/python-quickstart">
Learn more about Mem0 OSS Python SDK
</Card>
<Card title="Mem0 OSS Node.js SDK" icon="node" href="/open-source-typescript/quickstart">
Learn more about Mem0 OSS Node.js SDK
</Card>
</CardGroup>
+8 -5
View File
@@ -1,4 +1,4 @@
# This file is automatically @generated by Poetry 1.8.3 and should not be changed by hand.
# This file is automatically @generated by Poetry 1.8.4 and should not be changed by hand.
[[package]]
name = "aiohttp"
@@ -2805,13 +2805,13 @@ files = [
[[package]]
name = "mem0ai"
version = "0.1.29"
version = "0.1.54"
description = "Long-term memory for AI Agents"
optional = false
python-versions = "<4.0,>=3.9"
files = [
{file = "mem0ai-0.1.29-py3-none-any.whl", hash = "sha256:07bbfd4238d0d7da65d5e4cf75a217eeb5b2829834e399074b05bb046730a57f"},
{file = "mem0ai-0.1.29.tar.gz", hash = "sha256:42adefb7a9b241be03fbcabadf5328abf91b4ac390bc97e5966e55e3cac192c5"},
{file = "mem0ai-0.1.54-py3-none-any.whl", hash = "sha256:026c3262d714ebe536fb796c53e553051dbe6da66a8a313587efebfd420a0f7a"},
{file = "mem0ai-0.1.54.tar.gz", hash = "sha256:f7a0dd2303e59a0131c1dea72058ba165d91e2b3e36d159cc7bbbb062610cc87"},
]
[package.dependencies]
@@ -2822,6 +2822,9 @@ pytz = ">=2024.1,<2025.0"
qdrant-client = ">=1.9.1,<2.0.0"
sqlalchemy = ">=2.0.31,<3.0.0"
[package.extras]
graph = ["langchain-community (>=0.3.1,<0.4.0)", "neo4j (>=5.23.1,<6.0.0)", "rank-bm25 (>=0.2.2,<0.3.0)"]
[[package]]
name = "milvus-lite"
version = "2.4.8"
@@ -6667,4 +6670,4 @@ weaviate = ["weaviate-client"]
[metadata]
lock-version = "2.0"
python-versions = ">=3.9,<=3.13"
content-hash = "98ab80c76f001e35dd37dd705b4d8e88ecd4377383457aab38c0c94d3b872f33"
content-hash = "d7b43f88a863fa5f6835deebeaa1f454a423439e8c9b4b3e923c4d0a2a96e4c6"
+2 -2
View File
@@ -1,6 +1,6 @@
[tool.poetry]
name = "embedchain"
version = "0.1.126"
version = "0.1.127"
description = "Simplest open source retrieval (RAG) framework"
authors = [
"Taranjeet Singh <taranjeet@embedchain.ai>",
@@ -103,7 +103,7 @@ beautifulsoup4 = "^4.12.2"
pypdf = "^5.0.0"
gptcache = "^0.1.43"
pysbd = "^0.3.4"
mem0ai = "^0.1.37"
mem0ai = "^0.1.54"
tiktoken = { version = "^0.7.0", optional = true }
sentence-transformers = { version = "^2.2.2", optional = true }
torch = { version = "2.3.0", optional = true }
+2 -2
View File
@@ -10,7 +10,7 @@
"preview": "vite preview"
},
"dependencies": {
"@mem0/vercel-ai-provider": "^0.0.7",
"@mem0/vercel-ai-provider": "0.0.12",
"@radix-ui/react-avatar": "^1.1.1",
"@radix-ui/react-dialog": "^1.1.2",
"@radix-ui/react-icons": "^1.3.1",
@@ -18,7 +18,7 @@
"@radix-ui/react-scroll-area": "^1.2.0",
"@radix-ui/react-select": "^2.1.2",
"@radix-ui/react-slot": "^1.1.0",
"ai": "^3.4.31",
"ai": "4.1.42",
"buffer": "^6.0.3",
"class-variance-authority": "^0.7.0",
"clsx": "^2.1.1",
@@ -5,7 +5,7 @@ import { Label } from "@/components/ui/label"
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select"
import { Dialog, DialogContent, DialogHeader, DialogTitle, DialogFooter } from "@/components/ui/dialog"
import GlobalContext from '@/contexts/GlobalContext'
import { Provider } from '@/constants/messages'
export default function ApiSettingsPopup(props: { isOpen: boolean, setIsOpen: Dispatch<SetStateAction<boolean>> }) {
const {isOpen, setIsOpen} = props
const [mem0ApiKey, setMem0ApiKey] = useState('')
@@ -15,7 +15,7 @@ export default function ApiSettingsPopup(props: { isOpen: boolean, setIsOpen: Di
const handleSave = () => {
// Here you would typically save the settings to your backend or local storage
selectorHandler(mem0ApiKey, providerApiKey, provider);
selectorHandler(mem0ApiKey, providerApiKey, provider as Provider);
setIsOpen(false)
}
@@ -3,12 +3,12 @@ import { Card } from "@/components/ui/card";
import { ScrollArea } from "@radix-ui/react-scroll-area";
import { Memory } from "../types";
import GlobalContext from "@/contexts/GlobalContext";
import { useContext, useEffect, useState } from "react";
import { useContext } from "react";
import { motion } from "framer-motion";
// eslint-disable-next-line @typescript-eslint/no-unused-vars
const MemoryItem = ({ memory, index }: { memory: Memory; index: number }) => {
const MemoryItem = ({ memory }: { memory: Memory; index: number }) => {
return (
<motion.div
layout
@@ -39,14 +39,6 @@ const MemoryItem = ({ memory, index }: { memory: Memory; index: number }) => {
const Memories = (props: { isMemoriesExpanded: boolean }) => {
const { isMemoriesExpanded } = props;
const { memories } = useContext(GlobalContext);
// eslint-disable-next-line @typescript-eslint/no-unused-vars
const [prevMemories, setPrevMemories] = useState<Memory[]>([]);
// Track memory positions for animation
useEffect(() => {
setPrevMemories(memories);
}, [memories]);
return (
<Card
@@ -0,0 +1,31 @@
import { Message } from "@/types";
export const WELCOME_MESSAGE: Message = {
id: "1",
content: "👋 Hi there! I'm your personal assistant. How can I help you today? 😊",
sender: "assistant",
timestamp: new Date().toLocaleTimeString(),
};
export const INVALID_CONFIG_MESSAGE: Message = {
id: "2",
content: "Invalid configuration. Please check your API keys, and add a user and try again.",
sender: "assistant",
timestamp: new Date().toLocaleTimeString(),
};
export const ERROR_MESSAGE: Message = {
id: "3",
content: "Something went wrong. Please try again.",
sender: "assistant",
timestamp: new Date().toLocaleTimeString(),
};
export const AI_MODELS = {
openai: "gpt-4o",
anthropic: "claude-3-haiku-20240307",
cohere: "command-r-plus",
groq: "gemma2-9b-it",
} as const;
export type Provider = keyof typeof AI_MODELS;
@@ -1,281 +1,84 @@
/* eslint-disable @typescript-eslint/no-explicit-any */
import { createContext, useEffect, useState } from "react";
import { createMem0, searchMemories } from "@mem0/vercel-ai-provider";
import { LanguageModelV1Prompt, streamText } from "ai";
import { Message, Memory, FileInfo } from "@/types";
import { Buffer } from 'buffer';
import { createContext } from 'react';
import { Message, Memory, FileInfo } from '@/types';
import { useAuth } from '@/hooks/useAuth';
import { useChat } from '@/hooks/useChat';
import { useFileHandler } from '@/hooks/useFileHandler';
import { Provider } from '@/constants/messages';
const GlobalContext = createContext<any>({});
const WelcomeMessage: Message = {
id: "1",
content:
"👋 Hi there! I'm your personal assistant. How can I help you today? 😊",
sender: "assistant",
timestamp: new Date().toLocaleTimeString(),
};
const InvalidConfigMessage: Message = {
id: "2",
content:
"Invalid configuration. Please check your API keys, and add a user and try again.",
sender: "assistant",
timestamp: new Date().toLocaleTimeString(),
};
const SomethingWentWrongMessage: Message = {
id: "3",
content: "Something went wrong. Please try again.",
sender: "assistant",
timestamp: new Date().toLocaleTimeString(),
};
const models = {
"openai": "gpt-4o",
"anthropic": "claude-3-haiku-20240307",
"cohere": "command-r-plus",
"groq": "gemma2-9b-it"
interface GlobalContextType {
selectedUser: string;
selectUserHandler: (user: string) => void;
clearUserHandler: () => void;
messages: Message[];
memories: Memory[];
handleSend: (content: string) => Promise<void>;
thinking: boolean;
selectedMem0Key: string;
selectedOpenAIKey: string;
selectedProvider: Provider;
selectorHandler: (mem0: string, openai: string, provider: Provider) => void;
clearConfiguration: () => void;
selectedFile: FileInfo | null;
setSelectedFile: (file: FileInfo | null) => void;
file: File | null;
setFile: (file: File | null) => void;
}
const getModel = (provider: string) => {
switch (provider) {
case "openai":
return models.openai;
case "anthropic":
return models.anthropic;
case "cohere":
return models.cohere;
case "groq":
return models.groq;
default:
return models.openai;
}
}
const GlobalContext = createContext<GlobalContextType>({} as GlobalContextType);
const GlobalState = (props: any) => {
const [memories, setMemories] = useState<Memory[]>([]);
const [messages, setMessages] = useState<Message[]>([]);
const [selectedUser, setSelectedUser] = useState<string>("");
const [thinking, setThinking] = useState<boolean>(false);
const [selectedOpenAIKey, setSelectedOpenAIKey] = useState<string>("");
const [selectedMem0Key, setSelectedMem0Key] = useState<string>("");
const [selectedProvider, setSelectedProvider] = useState<string>("openai");
const [selectedFile, setSelectedFile] = useState<FileInfo | null>(null)
const [file, setFile] = useState<any>(null)
const mem0 = createMem0({
provider: selectedProvider,
const GlobalState = (props: { children: React.ReactNode }) => {
const {
mem0ApiKey: selectedMem0Key,
apiKey: selectedOpenAIKey,
openaiApiKey: selectedOpenAIKey,
provider: selectedProvider,
user: selectedUser,
setAuth: selectorHandler,
setUser: selectUserHandler,
clearAuth: clearConfiguration,
clearUser: clearUserHandler,
} = useAuth();
const {
selectedFile,
file,
fileData,
setSelectedFile,
handleFile,
clearFile,
} = useFileHandler();
const {
messages,
memories,
thinking,
sendMessage,
} = useChat({
user: selectedUser,
mem0ApiKey: selectedMem0Key,
openaiApiKey: selectedOpenAIKey,
provider: selectedProvider,
});
const clearConfiguration = () => {
localStorage.removeItem("mem0ApiKey");
localStorage.removeItem("openaiApiKey");
localStorage.removeItem("provider");
setSelectedMem0Key("");
setSelectedOpenAIKey("");
setSelectedProvider("openai");
setSelectedUser("");
setMessages([WelcomeMessage]);
setMemories([]);
setFile(null);
};
const selectorHandler = (mem0: string, openai: string, provider: string) => {
setSelectedMem0Key(mem0);
setSelectedOpenAIKey(openai);
setSelectedProvider(provider);
localStorage.setItem("mem0ApiKey", mem0);
localStorage.setItem("openaiApiKey", openai);
localStorage.setItem("provider", provider);
};
useEffect(() => {
const mem0 = localStorage.getItem("mem0ApiKey");
const openai = localStorage.getItem("openaiApiKey");
const provider = localStorage.getItem("provider");
const user = localStorage.getItem("user");
if (mem0 && openai && provider) {
selectorHandler(mem0, openai, provider);
}
if (user) {
setSelectedUser(user);
}
}, []);
const selectUserHandler = (user: string) => {
setSelectedUser(user);
localStorage.setItem("user", user);
};
const clearUserHandler = () => {
setSelectedUser("");
setMemories([]);
};
const getMemories = async (messages: LanguageModelV1Prompt) => {
try {
const smemories = await searchMemories(messages, {
user_id: selectedUser || "",
mem0ApiKey: selectedMem0Key,
});
const newMemories = smemories.map((memory: any) => ({
id: memory.id,
content: memory.memory,
timestamp: memory.updated_at,
tags: memory.categories,
}));
setMemories(newMemories);
} catch (error) {
console.error("Error in getMemories:", error);
}
};
const handleSend = async (inputValue: string) => {
if (!inputValue.trim() && !file) return;
if (!selectedUser) {
const newMessage: Message = {
id: Date.now().toString(),
content: inputValue,
sender: "user",
timestamp: new Date().toLocaleTimeString(),
};
setMessages((prev) => [...prev, newMessage, InvalidConfigMessage]);
return;
}
const userMessage: Message = {
id: Date.now().toString(),
content: inputValue,
sender: "user",
timestamp: new Date().toLocaleTimeString(),
};
let fileData;
const handleSend = async (content: string) => {
if (file) {
if (file.type.startsWith("image/")) {
// Convert image to Base64
fileData = await convertToBase64(file);
userMessage.image = fileData;
} else if (file.type.startsWith("audio/")) {
// Convert audio to ArrayBuffer
fileData = await getFileBuffer(file);
userMessage.audio = fileData;
}
}
// Update the state with the new user message
setMessages((prev) => [...prev, userMessage]);
setThinking(true);
// Transform messages into the required format
const messagesForPrompt: LanguageModelV1Prompt = [];
messages.map((message) => {
const messageContent: any = {
role: message.sender,
content: [
{
type: "text",
text: message.content,
},
],
};
if (message.image) {
messageContent.content.push({
type: "image",
image: message.image,
});
}
if (message.audio) {
messageContent.content.push({
type: 'file',
mimeType: 'audio/mpeg',
data: message.audio,
});
}
if(!message.audio) messagesForPrompt.push(messageContent);
});
const newMessage: any = {
role: "user",
content: [
{
type: "text",
text: inputValue,
},
],
};
if (file) {
if (file.type.startsWith("image/")) {
newMessage.content.push({
type: "image",
image: userMessage.image,
});
} else if (file.type.startsWith("audio/")) {
newMessage.content.push({
type: 'file',
mimeType: 'audio/mpeg',
data: userMessage.audio,
});
}
}
messagesForPrompt.push(newMessage);
getMemories(messagesForPrompt);
setFile(null);
setSelectedFile(null);
try {
const { textStream } = await streamText({
model: mem0(getModel(selectedProvider), {
user_id: selectedUser || "",
}),
messages: messagesForPrompt,
await sendMessage(content, {
type: file.type,
data: fileData!,
});
const assistantMessageId = Date.now() + 1;
const assistantMessage: Message = {
id: assistantMessageId.toString(),
content: "",
sender: "assistant",
timestamp: new Date().toLocaleTimeString(),
};
setMessages((prev) => [...prev, assistantMessage]);
// Stream the text part by part
for await (const textPart of textStream) {
assistantMessage.content += textPart;
setThinking(false);
setFile(null);
setSelectedFile(null);
setMessages((prev) =>
prev.map((msg) =>
msg.id === assistantMessageId.toString()
? { ...msg, content: assistantMessage.content }
: msg
)
);
}
setThinking(false);
} catch (error) {
console.error("Error in handleSend:", error);
setMessages((prev) => [...prev, SomethingWentWrongMessage]);
setThinking(false);
setFile(null);
setSelectedFile(null);
clearFile();
} else {
await sendMessage(content);
}
};
useEffect(() => {
setMessages([WelcomeMessage]);
}, []);
const setFile = async (newFile: File | null) => {
if (newFile) {
await handleFile(newFile);
} else {
clearFile();
}
};
return (
<GlobalContext.Provider
@@ -295,7 +98,7 @@ const GlobalState = (props: any) => {
selectedFile,
setSelectedFile,
file,
setFile
setFile,
}}
>
{props.children}
@@ -304,21 +107,4 @@ const GlobalState = (props: any) => {
};
export default GlobalContext;
export { GlobalState };
const convertToBase64 = (file: File): Promise<string> => {
return new Promise((resolve, reject) => {
const reader = new FileReader();
reader.readAsDataURL(file);
reader.onload = () => resolve(reader.result as string); // Resolve with Base64 string
reader.onerror = error => reject(error); // Reject on error
});
};
async function getFileBuffer(file: any) {
const response = await fetch(file);
const arrayBuffer = await response.arrayBuffer();
const buffer = Buffer.from(arrayBuffer);
return buffer;
}
export { GlobalState };
@@ -0,0 +1,73 @@
import { useState, useEffect } from 'react';
import { Provider } from '@/constants/messages';
interface UseAuthReturn {
mem0ApiKey: string;
openaiApiKey: string;
provider: Provider;
user: string;
setAuth: (mem0: string, openai: string, provider: Provider) => void;
setUser: (user: string) => void;
clearAuth: () => void;
clearUser: () => void;
}
export const useAuth = (): UseAuthReturn => {
const [mem0ApiKey, setMem0ApiKey] = useState<string>('');
const [openaiApiKey, setOpenaiApiKey] = useState<string>('');
const [provider, setProvider] = useState<Provider>('openai');
const [user, setUser] = useState<string>('');
useEffect(() => {
const mem0 = localStorage.getItem('mem0ApiKey');
const openai = localStorage.getItem('openaiApiKey');
const savedProvider = localStorage.getItem('provider') as Provider;
const savedUser = localStorage.getItem('user');
if (mem0 && openai && savedProvider) {
setAuth(mem0, openai, savedProvider);
}
if (savedUser) {
setUser(savedUser);
}
}, []);
const setAuth = (mem0: string, openai: string, provider: Provider) => {
setMem0ApiKey(mem0);
setOpenaiApiKey(openai);
setProvider(provider);
localStorage.setItem('mem0ApiKey', mem0);
localStorage.setItem('openaiApiKey', openai);
localStorage.setItem('provider', provider);
};
const clearAuth = () => {
localStorage.removeItem('mem0ApiKey');
localStorage.removeItem('openaiApiKey');
localStorage.removeItem('provider');
setMem0ApiKey('');
setOpenaiApiKey('');
setProvider('openai');
};
const updateUser = (user: string) => {
setUser(user);
localStorage.setItem('user', user);
};
const clearUser = () => {
localStorage.removeItem('user');
setUser('');
};
return {
mem0ApiKey,
openaiApiKey,
provider,
user,
setAuth,
setUser: updateUser,
clearAuth,
clearUser,
};
};
@@ -0,0 +1,169 @@
import { useState } from 'react';
import { createMem0, getMemories } from '@mem0/vercel-ai-provider';
import { LanguageModelV1Prompt, streamText } from 'ai';
import { Message, Memory } from '@/types';
import { WELCOME_MESSAGE, INVALID_CONFIG_MESSAGE, ERROR_MESSAGE, AI_MODELS, Provider } from '@/constants/messages';
interface UseChatProps {
user: string;
mem0ApiKey: string;
openaiApiKey: string;
provider: Provider;
}
interface UseChatReturn {
messages: Message[];
memories: Memory[];
thinking: boolean;
sendMessage: (content: string, fileData?: { type: string; data: string | Buffer }) => Promise<void>;
}
interface MemoryResponse {
id: string;
memory: string;
updated_at: string;
categories: string[];
}
type MessageContent =
| { type: 'text'; text: string }
| { type: 'image'; image: string }
| { type: 'file'; mimeType: string; data: Buffer };
interface PromptMessage {
role: string;
content: MessageContent[];
}
export const useChat = ({ user, mem0ApiKey, openaiApiKey, provider }: UseChatProps): UseChatReturn => {
const [messages, setMessages] = useState<Message[]>([WELCOME_MESSAGE]);
const [memories, setMemories] = useState<Memory[]>([]);
const [thinking, setThinking] = useState(false);
const mem0 = createMem0({
provider,
mem0ApiKey,
apiKey: openaiApiKey,
});
const updateMemories = async (messages: LanguageModelV1Prompt) => {
try {
const fetchedMemories = await getMemories(messages, {
user_id: user,
mem0ApiKey,
});
const newMemories = fetchedMemories.map((memory: MemoryResponse) => ({
id: memory.id,
content: memory.memory,
timestamp: memory.updated_at,
tags: memory.categories,
}));
setMemories(newMemories);
} catch (error) {
console.error('Error in getMemories:', error);
}
};
const formatMessagesForPrompt = (messages: Message[]): PromptMessage[] => {
return messages.map((message) => {
const messageContent: MessageContent[] = [
{ type: 'text', text: message.content }
];
if (message.image) {
messageContent.push({
type: 'image',
image: message.image,
});
}
if (message.audio) {
messageContent.push({
type: 'file',
mimeType: 'audio/mpeg',
data: message.audio as Buffer,
});
}
return {
role: message.sender,
content: messageContent,
};
});
};
const sendMessage = async (content: string, fileData?: { type: string; data: string | Buffer }) => {
if (!content.trim() && !fileData) return;
if (!user) {
const newMessage: Message = {
id: Date.now().toString(),
content,
sender: 'user',
timestamp: new Date().toLocaleTimeString(),
};
setMessages((prev) => [...prev, newMessage, INVALID_CONFIG_MESSAGE]);
return;
}
const userMessage: Message = {
id: Date.now().toString(),
content,
sender: 'user',
timestamp: new Date().toLocaleTimeString(),
...(fileData?.type.startsWith('image/') && { image: fileData.data.toString() }),
...(fileData?.type.startsWith('audio/') && { audio: fileData.data as Buffer }),
};
setMessages((prev) => [...prev, userMessage]);
setThinking(true);
const messagesForPrompt = formatMessagesForPrompt([...messages, userMessage]);
await updateMemories(messagesForPrompt as LanguageModelV1Prompt);
try {
const { textStream } = await streamText({
model: mem0(AI_MODELS[provider], {
user_id: user,
}),
messages: messagesForPrompt as LanguageModelV1Prompt,
});
const assistantMessageId = Date.now() + 1;
const assistantMessage: Message = {
id: assistantMessageId.toString(),
content: '',
sender: 'assistant',
timestamp: new Date().toLocaleTimeString(),
};
setMessages((prev) => [...prev, assistantMessage]);
for await (const textPart of textStream) {
assistantMessage.content += textPart;
setThinking(false);
setMessages((prev) =>
prev.map((msg) =>
msg.id === assistantMessageId.toString()
? { ...msg, content: assistantMessage.content }
: msg
)
);
}
} catch (error) {
console.error('Error in sendMessage:', error);
setMessages((prev) => [...prev, ERROR_MESSAGE]);
} finally {
setThinking(false);
}
};
return {
messages,
memories,
thinking,
sendMessage,
};
};
@@ -0,0 +1,45 @@
import { useState } from 'react';
import { FileInfo } from '@/types';
import { convertToBase64, getFileBuffer } from '@/utils/fileUtils';
interface UseFileHandlerReturn {
selectedFile: FileInfo | null;
file: File | null;
fileData: string | Buffer | null;
setSelectedFile: (file: FileInfo | null) => void;
handleFile: (file: File) => Promise<void>;
clearFile: () => void;
}
export const useFileHandler = (): UseFileHandlerReturn => {
const [selectedFile, setSelectedFile] = useState<FileInfo | null>(null);
const [file, setFile] = useState<File | null>(null);
const [fileData, setFileData] = useState<string | Buffer | null>(null);
const handleFile = async (file: File) => {
setFile(file);
if (file.type.startsWith('image/')) {
const base64Data = await convertToBase64(file);
setFileData(base64Data);
} else if (file.type.startsWith('audio/')) {
const bufferData = await getFileBuffer(file);
setFileData(bufferData);
}
};
const clearFile = () => {
setSelectedFile(null);
setFile(null);
setFileData(null);
};
return {
selectedFile,
file,
fileData,
setSelectedFile,
handleFile,
clearFile,
};
};
@@ -0,0 +1,16 @@
import { Buffer } from 'buffer';
export const convertToBase64 = (file: File): Promise<string> => {
return new Promise((resolve, reject) => {
const reader = new FileReader();
reader.readAsDataURL(file);
reader.onload = () => resolve(reader.result as string);
reader.onerror = error => reject(error);
});
};
export const getFileBuffer = async (file: File): Promise<Buffer> => {
const response = await fetch(URL.createObjectURL(file));
const arrayBuffer = await response.arrayBuffer();
return Buffer.from(arrayBuffer);
};
+65
View File
@@ -0,0 +1,65 @@
# Mem0 - The Memory Layer for Your AI Apps
Mem0 is a self-improving memory layer for LLM applications, enabling personalized AI experiences that save costs and delight users. We offer both cloud and open-source solutions to cater to different needs.
See the complete [OSS Docs](https://docs.mem0.ai/open-source-typescript/quickstart).
See the complete [Platform API Reference](https://docs.mem0.ai/api-reference/overview).
## 1. Installation
For the open-source version, you can install the Mem0 package using npm:
```bash
npm i mem0ai
```
## 2. API Key Setup
For the cloud offering, sign in to [Mem0 Platform](https://app.mem0.ai/dashboard/api-keys) to obtain your API Key.
## 3. Client Features
### Cloud Offering
The cloud version provides a comprehensive set of features, including:
- **Memory Operations**: Perform CRUD operations on memories.
- **Search Capabilities**: Search for relevant memories using advanced filters.
- **Memory History**: Track changes to memories over time.
- **Error Handling**: Robust error handling for API-related issues.
- **Async/Await Support**: All methods return promises for easy integration.
### Open-Source Offering
The open-source version includes the following top features:
- **Memory Management**: Add, update, delete, and retrieve memories.
- **Vector Store Integration**: Supports various vector store providers for efficient memory retrieval.
- **LLM Support**: Integrates with multiple LLM providers for generating responses.
- **Customizable Configuration**: Easily configure memory settings and providers.
- **SQLite Storage**: Use SQLite for memory history management.
## 4. Memory Operations
Mem0 provides a simple and customizable interface for performing memory operations. You can create long-term and short-term memories, search for relevant memories, and manage memory history.
## 5. Error Handling
The MemoryClient throws errors for any API-related issues. You can catch and handle these errors effectively.
## 6. Using with async/await
All methods of the MemoryClient return promises, allowing for seamless integration with async/await syntax.
## 7. Testing the Client
To test the MemoryClient in a Node.js environment, you can create a simple script to verify the functionality of memory operations.
## Getting Help
If you have any questions or need assistance, please reach out to us:
- Email: founders@mem0.ai
- [Join our discord community](https://mem0.ai/discord)
- [Join our slack community](https://mem0.ai/slack)
- GitHub Issues: [Report bugs or request features](https://github.com/mem0ai/mem0ai-node/issues)
+29
View File
@@ -0,0 +1,29 @@
/** @type {import('ts-jest').JestConfigWithTsJest} */
module.exports = {
preset: "ts-jest",
testEnvironment: "node",
roots: ["<rootDir>/src", "<rootDir>/tests"],
testMatch: [
"**/__tests__/**/*.+(ts|tsx|js)",
"**/?(*.)+(spec|test).+(ts|tsx|js)",
],
transform: {
"^.+\\.(ts|tsx)$": [
"ts-jest",
{
tsconfig: "tsconfig.test.json",
},
],
},
moduleNameMapper: {
"^@/(.*)$": "<rootDir>/src/$1",
},
setupFiles: ["dotenv/config"],
testPathIgnorePatterns: ["/node_modules/", "/dist/"],
moduleFileExtensions: ["ts", "tsx", "js", "jsx", "json", "node"],
globals: {
"ts-jest": {
tsconfig: "tsconfig.test.json",
},
},
};
+117
View File
@@ -0,0 +1,117 @@
{
"name": "mem0ai",
"version": "2.0.1",
"description": "The Memory Layer For Your AI Apps",
"main": "./dist/index.js",
"module": "./dist/index.mjs",
"types": "./dist/index.d.ts",
"typesVersions": {
"*": {
"*": [
"./dist/index.d.ts"
],
"oss": [
"./dist/oss/index.d.ts"
]
}
},
"exports": {
".": {
"types": "./dist/index.d.ts",
"require": "./dist/index.js",
"import": "./dist/index.mjs"
},
"./oss": {
"types": "./dist/oss/index.d.ts",
"require": "./dist/oss/index.js",
"import": "./dist/oss/index.mjs"
}
},
"files": [
"dist"
],
"scripts": {
"clean": "rm -rf dist",
"build": "npm run clean && prettier --check . && tsup",
"dev": "nodemon",
"test": "jest",
"test:ts": "jest --config jest.config.js",
"test:watch": "jest --config jest.config.js --watch",
"format": "npm run clean && prettier --write .",
"format:check": "npm run clean && prettier --check ."
},
"tsup": {
"entry": [
"src/index.ts"
],
"format": [
"cjs",
"esm"
],
"dts": {
"resolve": true
},
"splitting": false,
"sourcemap": true,
"clean": true,
"treeshake": true,
"minify": false
},
"keywords": [
"mem0",
"api",
"client",
"memory",
"llm",
"long-term-memory",
"ai"
],
"author": "Deshraj Yadav",
"license": "Apache-2.0",
"devDependencies": {
"@types/node": "^22.7.6",
"@types/uuid": "^9.0.8",
"dotenv": "^16.4.5",
"fix-tsup-cjs": "^1.2.0",
"jest": "^29.7.0",
"prettier": "^3.5.2",
"ts-jest": "^29.2.6",
"ts-node": "^10.9.2",
"tsup": "^8.3.0",
"typescript": "5.5.4"
},
"dependencies": {
"axios": "1.7.7",
"openai": "4.28.0",
"uuid": "9.0.1",
"zod": "3.22.4"
},
"peerDependencies": {
"@anthropic-ai/sdk": "0.18.0",
"groq-sdk": "0.3.0",
"@qdrant/js-client-rest": "1.13.0",
"@types/jest": "29.5.14",
"@types/pg": "8.11.0",
"@types/sqlite3": "3.1.11",
"pg": "8.11.3",
"redis": "4.7.0",
"sqlite3": "5.1.7"
},
"peerDependenciesMeta": {
"posthog-node": {
"optional": true
},
"posthog-js": {
"optional": true
}
},
"optionalDependencies": {
"posthog-js": "^1.116.6"
},
"engines": {
"node": ">=18"
},
"publishConfig": {
"access": "public"
}
}
+36
View File
@@ -0,0 +1,36 @@
import { MemoryClient } from "./mem0";
import type { TelemetryClient, TelemetryInstance } from "./telemetry.types";
import {
telemetry,
captureClientEvent,
generateHash,
} from "./telemetry.browser";
import type * as MemoryTypes from "./mem0.types";
// Re-export all types from mem0.types
export type {
MemoryOptions,
ProjectOptions,
Memory,
MemoryHistory,
MemoryUpdateBody,
ProjectResponse,
PromptUpdatePayload,
SearchOptions,
Webhook,
WebhookPayload,
Messages,
Message,
AllUsers,
User,
} from "./mem0.types";
// Export telemetry types
export type { TelemetryClient, TelemetryInstance };
// Export telemetry implementation
export { telemetry, captureClientEvent, generateHash };
// Export the main client
export { MemoryClient };
export default MemoryClient;
+560
View File
@@ -0,0 +1,560 @@
import axios from "axios";
import {
AllUsers,
ProjectOptions,
Memory,
MemoryHistory,
MemoryOptions,
MemoryUpdateBody,
ProjectResponse,
PromptUpdatePayload,
SearchOptions,
Webhook,
WebhookPayload,
} from "./mem0.types";
import { captureClientEvent, generateHash } from "./telemetry";
class APIError extends Error {
constructor(message: string) {
super(message);
this.name = "APIError";
}
}
interface ClientOptions {
apiKey: string;
host?: string;
organizationName?: string;
projectName?: string;
organizationId?: string;
projectId?: string;
}
export default class MemoryClient {
apiKey: string;
host: string;
organizationName: string | null;
projectName: string | null;
organizationId: string | number | null;
projectId: string | number | null;
headers: Record<string, string>;
client: any;
telemetryId: string;
_validateApiKey(): any {
if (!this.apiKey) {
throw new Error("Mem0 API key is required");
}
if (typeof this.apiKey !== "string") {
throw new Error("Mem0 API key must be a string");
}
if (this.apiKey.trim() === "") {
throw new Error("Mem0 API key cannot be empty");
}
}
_validateOrgProject(): void {
// Check for organizationName/projectName pair
if (
(this.organizationName === null && this.projectName !== null) ||
(this.organizationName !== null && this.projectName === null)
) {
console.warn(
"Warning: Both organizationName and projectName must be provided together when using either. This will be removedfrom the version 1.0.40. Note that organizationName/projectName are being deprecated in favor of organizationId/projectId.",
);
}
// Check for organizationId/projectId pair
if (
(this.organizationId === null && this.projectId !== null) ||
(this.organizationId !== null && this.projectId === null)
) {
console.warn(
"Warning: Both organizationId and projectId must be provided together when using either. This will be removedfrom the version 1.0.40.",
);
}
}
constructor(options: ClientOptions) {
this.apiKey = options.apiKey;
this.host = options.host || "https://api.mem0.ai";
this.organizationName = options.organizationName || null;
this.projectName = options.projectName || null;
this.organizationId = options.organizationId || null;
this.projectId = options.projectId || null;
this.headers = {
Authorization: `Token ${this.apiKey}`,
"Content-Type": "application/json",
};
this.client = axios.create({
baseURL: this.host,
headers: { Authorization: `Token ${this.apiKey}` },
timeout: 60000,
});
this._validateApiKey();
this._validateOrgProject();
// Initialize with a temporary ID that will be updated
this.telemetryId = "";
// Initialize the client
this._initializeClient();
}
private async _initializeClient() {
try {
// do this only in browser
if (typeof window !== "undefined") {
this.telemetryId = await generateHash(this.apiKey);
await captureClientEvent("init", this);
}
// Wrap methods after initialization
this.add = this.wrapMethod("add", this.add);
this.get = this.wrapMethod("get", this.get);
this.getAll = this.wrapMethod("get_all", this.getAll);
this.search = this.wrapMethod("search", this.search);
this.delete = this.wrapMethod("delete", this.delete);
this.deleteAll = this.wrapMethod("delete_all", this.deleteAll);
this.history = this.wrapMethod("history", this.history);
this.users = this.wrapMethod("users", this.users);
this.deleteUser = this.wrapMethod("delete_user", this.deleteUser);
this.deleteUsers = this.wrapMethod("delete_users", this.deleteUsers);
this.batchUpdate = this.wrapMethod("batch_update", this.batchUpdate);
this.batchDelete = this.wrapMethod("batch_delete", this.batchDelete);
this.getProject = this.wrapMethod("get_project", this.getProject);
this.updateProject = this.wrapMethod(
"update_project",
this.updateProject,
);
this.getWebhooks = this.wrapMethod("get_webhook", this.getWebhooks);
this.createWebhook = this.wrapMethod(
"create_webhook",
this.createWebhook,
);
this.updateWebhook = this.wrapMethod(
"update_webhook",
this.updateWebhook,
);
this.deleteWebhook = this.wrapMethod(
"delete_webhook",
this.deleteWebhook,
);
} catch (error) {
console.error("Failed to initialize client:", error);
}
}
wrapMethod(methodName: any, method: any) {
return async function (...args: any) {
// @ts-ignore
await captureClientEvent(methodName, this);
// @ts-ignore
return method.apply(this, args);
}.bind(this);
}
async _fetchWithErrorHandling(url: string, options: any): Promise<any> {
const response = await fetch(url, options);
if (!response.ok) {
const errorData = await response.text();
throw new APIError(`API request failed: ${errorData}`);
}
const jsonResponse = await response.json();
return jsonResponse;
}
_preparePayload(
messages: string | Array<{ role: string; content: string }>,
options: MemoryOptions,
): object {
const payload: any = {};
if (typeof messages === "string") {
payload.messages = [{ role: "user", content: messages }];
} else if (Array.isArray(messages)) {
payload.messages = messages;
}
return { ...payload, ...options };
}
_prepareParams(options: MemoryOptions): object {
return Object.fromEntries(
Object.entries(options).filter(([_, v]) => v != null),
);
}
async add(
messages: string | Array<{ role: string; content: string }>,
options: MemoryOptions = {},
): Promise<Array<Memory>> {
this._validateOrgProject();
if (this.organizationName != null && this.projectName != null) {
options.org_name = this.organizationName;
options.project_name = this.projectName;
}
if (this.organizationId != null && this.projectId != null) {
options.org_id = this.organizationId;
options.project_id = this.projectId;
if (options.org_name) delete options.org_name;
if (options.project_name) delete options.project_name;
}
const payload = this._preparePayload(messages, options);
const response = await this._fetchWithErrorHandling(
`${this.host}/v1/memories/`,
{
method: "POST",
headers: this.headers,
body: JSON.stringify(payload),
},
);
return response;
}
async update(memoryId: string, message: string): Promise<Array<Memory>> {
this._validateOrgProject();
const payload = {
text: message,
};
const response = await this._fetchWithErrorHandling(
`${this.host}/v1/memories/${memoryId}/`,
{
method: "PUT",
headers: this.headers,
body: JSON.stringify(payload),
},
);
return response;
}
async get(memoryId: string): Promise<Memory> {
return this._fetchWithErrorHandling(
`${this.host}/v1/memories/${memoryId}/`,
{
headers: this.headers,
},
);
}
async getAll(options?: SearchOptions): Promise<Array<Memory>> {
this._validateOrgProject();
const { api_version, page, page_size, ...otherOptions } = options!;
if (this.organizationName != null && this.projectName != null) {
otherOptions.org_name = this.organizationName;
otherOptions.project_name = this.projectName;
}
let appendedParams = "";
let paginated_response = false;
if (page && page_size) {
appendedParams += `page=${page}&page_size=${page_size}`;
paginated_response = true;
}
if (this.organizationId != null && this.projectId != null) {
otherOptions.org_id = this.organizationId;
otherOptions.project_id = this.projectId;
if (otherOptions.org_name) delete otherOptions.org_name;
if (otherOptions.project_name) delete otherOptions.project_name;
}
if (api_version === "v2") {
let url = paginated_response
? `${this.host}/v2/memories/?${appendedParams}`
: `${this.host}/v2/memories/`;
return this._fetchWithErrorHandling(url, {
method: "POST",
headers: this.headers,
body: JSON.stringify(otherOptions),
});
} else {
// @ts-ignore
const params = new URLSearchParams(this._prepareParams(otherOptions));
const url = paginated_response
? `${this.host}/v1/memories/?${params}&${appendedParams}`
: `${this.host}/v1/memories/?${params}`;
return this._fetchWithErrorHandling(url, {
headers: this.headers,
});
}
}
async search(query: string, options?: SearchOptions): Promise<Array<Memory>> {
this._validateOrgProject();
const { api_version, ...otherOptions } = options!;
const payload = { query, ...otherOptions };
if (this.organizationName != null && this.projectName != null) {
payload.org_name = this.organizationName;
payload.project_name = this.projectName;
}
if (this.organizationId != null && this.projectId != null) {
payload.org_id = this.organizationId;
payload.project_id = this.projectId;
if (payload.org_name) delete payload.org_name;
if (payload.project_name) delete payload.project_name;
}
const endpoint =
api_version === "v2" ? "/v2/memories/search/" : "/v1/memories/search/";
const response = await this._fetchWithErrorHandling(
`${this.host}${endpoint}`,
{
method: "POST",
headers: this.headers,
body: JSON.stringify(payload),
},
);
return response;
}
async delete(memoryId: string): Promise<{ message: string }> {
return this._fetchWithErrorHandling(
`${this.host}/v1/memories/${memoryId}/`,
{
method: "DELETE",
headers: this.headers,
},
);
}
async deleteAll(options: MemoryOptions = {}): Promise<{ message: string }> {
this._validateOrgProject();
if (this.organizationName != null && this.projectName != null) {
options.org_name = this.organizationName;
options.project_name = this.projectName;
}
if (this.organizationId != null && this.projectId != null) {
options.org_id = this.organizationId;
options.project_id = this.projectId;
if (options.org_name) delete options.org_name;
if (options.project_name) delete options.project_name;
}
// @ts-ignore
const params = new URLSearchParams(this._prepareParams(options));
const response = await this._fetchWithErrorHandling(
`${this.host}/v1/memories/?${params}`,
{
method: "DELETE",
headers: this.headers,
},
);
return response;
}
async history(memoryId: string): Promise<Array<MemoryHistory>> {
const response = await this._fetchWithErrorHandling(
`${this.host}/v1/memories/${memoryId}/history/`,
{
headers: this.headers,
},
);
return response;
}
async users(): Promise<AllUsers> {
this._validateOrgProject();
const options: MemoryOptions = {};
if (this.organizationName != null && this.projectName != null) {
options.org_name = this.organizationName;
options.project_name = this.projectName;
}
if (this.organizationId != null && this.projectId != null) {
options.org_id = this.organizationId;
options.project_id = this.projectId;
if (options.org_name) delete options.org_name;
if (options.project_name) delete options.project_name;
}
// @ts-ignore
const params = new URLSearchParams(options);
const response = await this._fetchWithErrorHandling(
`${this.host}/v1/entities/?${params}`,
{
headers: this.headers,
},
);
return response;
}
async deleteUser(
entityId: string,
entity: { type: string } = { type: "user" },
): Promise<{ message: string }> {
const response = await this._fetchWithErrorHandling(
`${this.host}/v1/entities/${entity.type}/${entityId}/`,
{
method: "DELETE",
headers: this.headers,
},
);
return response;
}
async deleteUsers(): Promise<{ message: string }> {
this._validateOrgProject();
const entities = await this.users();
for (const entity of entities.results) {
let options: MemoryOptions = {};
if (this.organizationName != null && this.projectName != null) {
options.org_name = this.organizationName;
options.project_name = this.projectName;
}
if (this.organizationId != null && this.projectId != null) {
options.org_id = this.organizationId;
options.project_id = this.projectId;
if (options.org_name) delete options.org_name;
if (options.project_name) delete options.project_name;
}
await this.client.delete(`/v1/entities/${entity.type}/${entity.id}/`, {
params: options,
});
}
return { message: "All users, agents, and sessions deleted." };
}
async batchUpdate(memories: Array<MemoryUpdateBody>): Promise<string> {
const memoriesBody = memories.map((memory) => ({
memory_id: memory.memoryId,
text: memory.text,
}));
const response = await this._fetchWithErrorHandling(
`${this.host}/v1/batch/`,
{
method: "PUT",
headers: this.headers,
body: JSON.stringify({ memories: memoriesBody }),
},
);
return response;
}
async batchDelete(memories: Array<string>): Promise<string> {
const memoriesBody = memories.map((memory) => ({
memory_id: memory,
}));
const response = await this._fetchWithErrorHandling(
`${this.host}/v1/batch/`,
{
method: "DELETE",
headers: this.headers,
body: JSON.stringify({ memories: memoriesBody }),
},
);
return response;
}
async getProject(options: ProjectOptions): Promise<ProjectResponse> {
this._validateOrgProject();
const { fields } = options;
if (!(this.organizationId && this.projectId)) {
throw new Error(
"organizationId and projectId must be set to access instructions or categories",
);
}
const params = new URLSearchParams();
fields?.forEach((field) => params.append("fields", field));
const response = await this._fetchWithErrorHandling(
`${this.host}/api/v1/orgs/organizations/${this.organizationId}/projects/${this.projectId}/?${params.toString()}`,
{
headers: this.headers,
},
);
return response;
}
async updateProject(
prompts: PromptUpdatePayload,
): Promise<Record<string, any>> {
this._validateOrgProject();
if (!(this.organizationId && this.projectId)) {
throw new Error(
"organizationId and projectId must be set to update instructions or categories",
);
}
const response = await this._fetchWithErrorHandling(
`${this.host}/api/v1/orgs/organizations/${this.organizationId}/projects/${this.projectId}/`,
{
method: "PATCH",
headers: this.headers,
body: JSON.stringify(prompts),
},
);
return response;
}
// WebHooks
async getWebhooks(data?: { projectId?: string }): Promise<Array<Webhook>> {
const project_id = data?.projectId || this.projectId;
const response = await this._fetchWithErrorHandling(
`${this.host}/api/v1/webhooks/projects/${project_id}/`,
{
headers: this.headers,
},
);
return response;
}
async createWebhook(webhook: WebhookPayload): Promise<Webhook> {
const response = await this._fetchWithErrorHandling(
`${this.host}/api/v1/webhooks/projects/${this.projectId}/`,
{
method: "POST",
headers: this.headers,
body: JSON.stringify(webhook),
},
);
return response;
}
async updateWebhook(webhook: WebhookPayload): Promise<{ message: string }> {
const project_id = webhook.projectId || this.projectId;
const response = await this._fetchWithErrorHandling(
`${this.host}/api/v1/webhooks/${webhook.webhookId}/`,
{
method: "PUT",
headers: this.headers,
body: JSON.stringify({
...webhook,
projectId: project_id,
}),
},
);
return response;
}
async deleteWebhook(data: {
webhookId: string;
}): Promise<{ message: string }> {
const webhook_id = data.webhookId || data;
const response = await this._fetchWithErrorHandling(
`${this.host}/api/v1/webhooks/${webhook_id}/`,
{
method: "DELETE",
headers: this.headers,
},
);
return response;
}
}
export { MemoryClient };
+156
View File
@@ -0,0 +1,156 @@
export interface MemoryOptions {
user_id?: string;
agent_id?: string;
app_id?: string;
run_id?: string;
metadata?: Record<string, any>;
filters?: Record<string, any>;
org_name?: string | null; // Deprecated
project_name?: string | null; // Deprecated
org_id?: string | number | null;
project_id?: string | number | null;
infer?: boolean;
page?: number;
page_size?: number;
includes?: string;
excludes?: string;
enable_graph?: boolean;
start_date?: string;
end_date?: string;
}
export interface ProjectOptions {
fields?: string[];
}
export enum API_VERSION {
V1 = "v1",
V2 = "v2",
}
export interface Messages {
role: string;
content: string;
}
export interface Message extends Messages {}
export interface MemoryHistory {
id: string;
memory_id: string;
input: Array<Messages>;
old_memory: string | null;
new_memory: string | null;
user_id: string;
categories: Array<string>;
event: Event | string;
created_at: Date;
updated_at: Date;
}
export interface SearchOptions extends MemoryOptions {
api_version?: API_VERSION | string;
limit?: number;
enable_graph?: boolean;
threshold?: number;
top_k?: number;
only_metadata_based_search?: boolean;
keyword_search?: boolean;
fields?: string[];
categories?: string[];
rerank?: boolean;
}
enum Event {
ADD = "ADD",
UPDATE = "UPDATE",
DELETE = "DELETE",
NOOP = "NOOP",
}
export interface MemoryData {
memory: string;
}
export interface Memory {
id: string;
messages?: Array<Messages>;
event?: Event | string;
data?: MemoryData | null;
memory?: string;
user_id?: string;
hash?: string;
categories?: Array<string>;
created_at?: Date;
updated_at?: Date;
memory_type?: string;
score?: number;
metadata?: any | null;
owner?: string | null;
agent_id?: string | null;
app_id?: string | null;
run_id?: string | null;
}
export interface MemoryUpdateBody {
memoryId: string;
text: string;
}
export interface User {
id: string;
name: string;
created_at: Date;
updated_at: Date;
total_memories: number;
owner: string;
type: string;
}
export interface AllUsers {
count: number;
results: Array<User>;
next: any;
previous: any;
}
export interface ProjectResponse {
custom_instructions?: string;
custom_categories?: string[];
[key: string]: any;
}
interface custom_categories {
[key: string]: any;
}
export interface PromptUpdatePayload {
custom_instructions?: string;
custom_categories?: custom_categories[];
[key: string]: any;
}
enum WebhookEvent {
MEMORY_ADDED = "memory_add",
MEMORY_UPDATED = "memory_update",
MEMORY_DELETED = "memory_delete",
}
export interface Webhook {
webhook_id?: string;
name: string;
url: string;
project?: string;
created_at?: Date;
updated_at?: Date;
is_active?: boolean;
event_types?: WebhookEvent[];
}
export interface WebhookPayload {
eventTypes: WebhookEvent[];
projectId: string;
webhookId: string;
name: string;
url: string;
}
+85
View File
@@ -0,0 +1,85 @@
// @ts-nocheck
import type { PostHog } from "posthog-js";
import type { TelemetryClient } from "./telemetry.types";
let version = "1.0.20";
const MEM0_TELEMETRY = process.env.MEM0_TELEMETRY !== "false";
const POSTHOG_API_KEY = "phc_hgJkUVJFYtmaJqrvf6CYN67TIQ8yhXAkWzUn9AMU4yX";
const POSTHOG_HOST = "https://us.i.posthog.com";
// Browser-specific hash function using Web Crypto API
async function generateHash(input: string): Promise<string> {
const msgBuffer = new TextEncoder().encode(input);
const hashBuffer = await window.crypto.subtle.digest("SHA-256", msgBuffer);
const hashArray = Array.from(new Uint8Array(hashBuffer));
return hashArray.map((b) => b.toString(16).padStart(2, "0")).join("");
}
class BrowserTelemetry implements TelemetryClient {
client: PostHog | null = null;
constructor(projectApiKey: string, host: string) {
if (MEM0_TELEMETRY) {
this.initializeClient(projectApiKey, host);
}
}
private async initializeClient(projectApiKey: string, host: string) {
try {
const posthog = await import("posthog-js").catch(() => null);
if (posthog) {
posthog.init(projectApiKey, { api_host: host });
this.client = posthog;
}
} catch (error) {
// Silently fail if posthog-js is not available
this.client = null;
}
}
async captureEvent(distinctId: string, eventName: string, properties = {}) {
if (!this.client || !MEM0_TELEMETRY) return;
const eventProperties = {
client_source: "browser",
client_version: getVersion(),
browser: window.navigator.userAgent,
...properties,
};
try {
this.client.capture(eventName, eventProperties);
} catch (error) {
// Silently fail if telemetry fails
}
}
async shutdown() {
// No shutdown needed for browser client
}
}
function getVersion() {
return version;
}
const telemetry = new BrowserTelemetry(POSTHOG_API_KEY, POSTHOG_HOST);
async function captureClientEvent(
eventName: string,
instance: any,
additionalData = {},
) {
const eventData = {
function: `${instance.constructor.name}`,
...additionalData,
};
await telemetry.captureEvent(
instance.telemetryId,
`client.${eventName}`,
eventData,
);
}
export { telemetry, captureClientEvent, generateHash };
+107
View File
@@ -0,0 +1,107 @@
// @ts-nocheck
import type { TelemetryClient } from "./telemetry.types";
let version = "1.0.20";
const MEM0_TELEMETRY = process.env.MEM0_TELEMETRY !== "false";
const POSTHOG_API_KEY = "phc_hgJkUVJFYtmaJqrvf6CYN67TIQ8yhXAkWzUn9AMU4yX";
const POSTHOG_HOST = "https://us.i.posthog.com";
// Node-specific hash function using crypto module
function generateHash(input: string): string {
const crypto = require("crypto");
return crypto.createHash("sha256").update(input).digest("hex");
}
class NodeTelemetry implements TelemetryClient {
client: any = null;
constructor(projectApiKey: string, host: string) {
if (MEM0_TELEMETRY) {
this.initializeClient(projectApiKey, host);
}
}
private async initializeClient(projectApiKey: string, host: string) {
try {
const { PostHog } = await import("posthog-node").catch(() => ({
PostHog: null,
}));
if (PostHog) {
this.client = new PostHog(projectApiKey, { host, flushAt: 1 });
}
} catch (error) {
// Silently fail if posthog-node is not available
this.client = null;
}
}
async captureEvent(distinctId: string, eventName: string, properties = {}) {
if (!this.client || !MEM0_TELEMETRY) return;
const eventProperties = {
client_source: "nodejs",
client_version: getVersion(),
...this.getEnvironmentInfo(),
...properties,
};
try {
this.client.capture({
distinctId,
event: eventName,
properties: eventProperties,
});
} catch (error) {
// Silently fail if telemetry fails
}
}
private getEnvironmentInfo() {
try {
const os = require("os");
return {
node_version: process.version,
os: process.platform,
os_version: os.release(),
os_arch: os.arch(),
};
} catch (error) {
return {};
}
}
async shutdown() {
if (this.client) {
try {
return this.client.shutdown();
} catch (error) {
// Silently fail shutdown
}
}
}
}
function getVersion() {
return version;
}
const telemetry = new NodeTelemetry(POSTHOG_API_KEY, POSTHOG_HOST);
async function captureClientEvent(
eventName: string,
instance: any,
additionalData = {},
) {
const eventData = {
function: `${instance.constructor.name}`,
...additionalData,
};
await telemetry.captureEvent(
instance.telemetryId,
`client.${eventName}`,
eventData,
);
}
export { telemetry, captureClientEvent, generateHash };

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