Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
3db028c719 | ||
|
|
c86b1e4d4c | ||
|
|
5f5b738745 | ||
|
|
acaf47ed54 | ||
|
|
9734b2db7e | ||
|
|
3fe31e1c31 | ||
|
|
f4c0f98fde | ||
|
|
6e781f616c | ||
|
|
dcba83186a | ||
|
|
a6d305f8d0 | ||
|
|
db512950b9 | ||
|
|
d4df9f6dfe | ||
|
|
0e6b20982a | ||
|
|
92e1a9b433 | ||
|
|
3be356a0e9 | ||
|
|
760cd54ddf | ||
|
|
1436da18b1 | ||
|
|
cc9acb7493 | ||
|
|
cbee71a63e | ||
|
|
b052a86424 | ||
|
|
95f5fb3ab4 | ||
|
|
04d7f2e48c | ||
|
|
be46f4eb40 | ||
|
|
f16a580ef6 | ||
|
|
095189d39a | ||
|
|
064d28626b | ||
|
|
cd31c5897a | ||
|
|
0bb6137877 | ||
|
|
2c63f4d866 | ||
|
|
3984b90f62 | ||
|
|
b08b50cbc6 | ||
|
|
90096d6954 | ||
|
|
7581974805 | ||
|
|
a8fafb9368 | ||
|
|
75a4a253f7 | ||
|
|
f9995d144f | ||
|
|
8d3c8c695d | ||
|
|
9f27b88843 | ||
|
|
d2f0e23dc8 | ||
|
|
6e23a6f00e | ||
|
|
a06c9a99ae | ||
|
|
63fbd2dc2c |
@@ -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:
|
||||
|
||||
@@ -45,50 +45,25 @@
|
||||
|
||||
[Mem0](https://mem0.ai) (pronounced as "mem-zero") enhances AI assistants and agents with an intelligent memory layer, enabling personalized AI interactions. Mem0 remembers user preferences, adapts to individual needs, and continuously improves over time, making it ideal for customer support chatbots, AI assistants, and autonomous systems.
|
||||
|
||||
<!-- Start of Selection -->
|
||||
<p style="display: flex;">
|
||||
<span style="font-size: 1.2em;">New Feature: Introducing Graph Memory. Check out our <a href="https://docs.mem0.ai/open-source/graph-memory" target="_blank">documentation</a>.</span>
|
||||
</p>
|
||||
<!-- End of Selection -->
|
||||
### Features & Use Cases
|
||||
|
||||
Core Capabilities:
|
||||
- **Multi-Level Memory**: User, Session, and AI Agent memory retention with adaptive personalization
|
||||
- **Developer-Friendly**: Simple API integration, cross-platform consistency, and hassle-free managed service
|
||||
|
||||
### Core Features
|
||||
|
||||
- **Multi-Level Memory**: User, Session, and AI Agent memory retention
|
||||
- **Adaptive Personalization**: Continuous improvement based on interactions
|
||||
- **Developer-Friendly API**: Simple integration into various applications
|
||||
- **Cross-Platform Consistency**: Uniform behavior across devices
|
||||
- **Managed Service**: Hassle-free hosted solution
|
||||
|
||||
### How Mem0 works?
|
||||
|
||||
Mem0 leverages a hybrid database approach to manage and retrieve long-term memories for AI agents and assistants. Each memory is associated with a unique identifier, such as a user ID or agent ID, allowing Mem0 to organize and access memories specific to an individual or context.
|
||||
|
||||
When a message is added to the Mem0 using add() method, the system extracts relevant facts and preferences and stores it across data stores: a vector database, a key-value database, and a graph database. This hybrid approach ensures that different types of information are stored in the most efficient manner, making subsequent searches quick and effective.
|
||||
|
||||
When an AI agent or LLM needs to recall memories, it uses the search() method. Mem0 then performs search across these data stores, retrieving relevant information from each source. This information is then passed through a scoring layer, which evaluates their importance based on relevance, importance, and recency. This ensures that only the most personalized and useful context is surfaced.
|
||||
|
||||
The retrieved memories can then be appended to the LLM's prompt as needed, enhancing the personalization and relevance of its responses.
|
||||
|
||||
### Use Cases
|
||||
|
||||
Mem0 empowers organizations and individuals to enhance:
|
||||
|
||||
- **AI Assistants and agents**: Seamless conversations with a touch of déjà vu
|
||||
- **Personalized Learning**: Tailored content recommendations and progress tracking
|
||||
- **Customer Support**: Context-aware assistance with user preference memory
|
||||
- **Healthcare**: Patient history and treatment plan management
|
||||
- **Virtual Companions**: Deeper user relationships through conversation memory
|
||||
- **Productivity**: Streamlined workflows based on user habits and task history
|
||||
- **Gaming**: Adaptive environments reflecting player choices and progress
|
||||
Applications:
|
||||
- **AI Assistants**: Seamless conversations with context and personalization
|
||||
- **Learning & Support**: Tailored content recommendations and context-aware customer assistance
|
||||
- **Healthcare & Companions**: Patient history tracking and deeper relationship building
|
||||
- **Productivity & Gaming**: Streamlined workflows and adaptive environments based on user behavior
|
||||
|
||||
## Get Started
|
||||
|
||||
The easiest way to set up Mem0 is through the managed [Mem0 Platform](https://app.mem0.ai). This hosted solution offers automatic updates, advanced analytics, and dedicated support. [Sign up](https://app.mem0.ai) to get started.
|
||||
Get started quickly with [Mem0 Platform](https://app.mem0.ai) - our fully managed solution that provides automatic updates, advanced analytics, enterprise security, and dedicated support. [Create a free account](https://app.mem0.ai) to begin.
|
||||
|
||||
If you prefer to self-host, use the open-source Mem0 package. Follow the [installation instructions](#install) to get started.
|
||||
For complete control, you can self-host Mem0 using our open-source package. See the [Quickstart guide](#quickstart) below to set up your own instance.
|
||||
|
||||
## Installation Instructions <a name="install"></a>
|
||||
## Quickstart Guide <a name="quickstart"></a>
|
||||
|
||||
Install the Mem0 package via pip:
|
||||
|
||||
@@ -96,8 +71,6 @@ Install the Mem0 package via pip:
|
||||
pip install mem0ai
|
||||
```
|
||||
|
||||
Alternatively, you can use Mem0 with one click on the hosted platform [here](https://app.mem0.ai/).
|
||||
|
||||
### 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).
|
||||
@@ -105,101 +78,85 @@ Mem0 requires an LLM to function, with `gpt-4o` from OpenAI as the default. Howe
|
||||
First step is to instantiate the memory:
|
||||
|
||||
```python
|
||||
from openai import OpenAI
|
||||
from mem0 import Memory
|
||||
|
||||
m = Memory()
|
||||
openai_client = OpenAI()
|
||||
memory = Memory()
|
||||
|
||||
def chat_with_memories(message: str, user_id: str = "default_user") -> str:
|
||||
# Retrieve relevant memories
|
||||
relevant_memories = memory.search(query=message, user_id=user_id, limit=3)
|
||||
memories_str = "\n".join(f"- {entry['memory']}" for entry in relevant_memories)
|
||||
|
||||
# Generate Assistant response
|
||||
system_prompt = f"You are a helpful AI. Answer the question based on query and memories.\nUser Memories:\n{memories_str}"
|
||||
messages = [{"role": "system", "content": system_prompt}, {"role": "user", "content": message}]
|
||||
response = openai_client.chat.completions.create(model="gpt-4o-mini", messages=messages)
|
||||
assistant_response = response.choices[0].message.content
|
||||
|
||||
# Create new memories from the conversation
|
||||
messages.append({"role": "assistant", "content": assistant_response})
|
||||
memory.add(messages, user_id=user_id)
|
||||
|
||||
return assistant_response
|
||||
|
||||
def main():
|
||||
print("Chat with AI (type 'exit' to quit)")
|
||||
while True:
|
||||
user_input = input("You: ").strip()
|
||||
if user_input.lower() == 'exit':
|
||||
print("Goodbye!")
|
||||
break
|
||||
print(f"AI: {chat_with_memories(user_input)}")
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
```
|
||||
|
||||
<details>
|
||||
<summary>How to set OPENAI_API_KEY</summary>
|
||||
|
||||
```python
|
||||
import os
|
||||
os.environ["OPENAI_API_KEY"] = "sk-xxx"
|
||||
```
|
||||
</details>
|
||||
|
||||
|
||||
You can perform the following task on the memory:
|
||||
|
||||
1. Add: Store a memory from any unstructured text
|
||||
2. Update: Update memory of a given memory_id
|
||||
3. Search: Fetch memories based on a query
|
||||
4. Get: Return memories for a certain user/agent/session
|
||||
5. History: Describe how a memory has changed over time for a specific memory ID
|
||||
|
||||
```python
|
||||
# 1. Add: Store a memory from any unstructured text
|
||||
result = m.add("I am working on improving my tennis skills. Suggest some online courses.", user_id="alice", metadata={"category": "hobbies"})
|
||||
|
||||
# Created memory --> 'Improving her tennis skills.' and 'Looking for online suggestions.'
|
||||
```
|
||||
|
||||
```python
|
||||
# 2. Update: update the memory
|
||||
result = m.update(memory_id=<memory_id_1>, data="Likes to play tennis on weekends")
|
||||
|
||||
# Updated memory --> 'Likes to play tennis on weekends.' and 'Looking for online suggestions.'
|
||||
```
|
||||
|
||||
```python
|
||||
# 3. Search: search related memories
|
||||
related_memories = m.search(query="What are Alice's hobbies?", user_id="alice")
|
||||
|
||||
# Retrieved memory --> 'Likes to play tennis on weekends'
|
||||
```
|
||||
|
||||
```python
|
||||
# 4. Get all memories
|
||||
all_memories = m.get_all()
|
||||
memory_id = all_memories["memories"][0] ["id"] # get a memory_id
|
||||
|
||||
# All memory items --> 'Likes to play tennis on weekends.' and 'Looking for online suggestions.'
|
||||
```
|
||||
|
||||
```python
|
||||
# 5. Get memory history for a particular memory_id
|
||||
history = m.history(memory_id=<memory_id_1>)
|
||||
|
||||
# Logs corresponding to memory_id_1 --> {'prev_value': 'Working on improving tennis skills and interested in online courses for tennis.', 'new_value': 'Likes to play tennis on weekends' }
|
||||
```
|
||||
For more advanced usage and API documentation, visit our [documentation](https://docs.mem0.ai).
|
||||
|
||||
> [!TIP]
|
||||
> If you prefer a hosted version without the need to set up infrastructure yourself, check out the [Mem0 Platform](https://app.mem0.ai/) to get started in minutes.
|
||||
> For a hassle-free experience, try our [hosted platform](https://app.mem0.ai) with automatic updates and enterprise features.
|
||||
|
||||
## Demos
|
||||
|
||||
- AI Companion: Experience personalized conversations with an AI that remembers your preferences and past interactions
|
||||
|
||||
[AI Companion Demo](https://github.com/user-attachments/assets/3fc72023-a72c-4593-8be0-3cee3ba744da)
|
||||
|
||||
<br/><br/>
|
||||
|
||||
- Enhance your AI interactions by storing memories across ChatGPT, Perplexity, and Claude using our browser extension. Get [chrome extension](https://chromewebstore.google.com/detail/mem0/onihkkbipkfeijkadecaafbgagkhglop?hl=en).
|
||||
|
||||
|
||||
### Graph Memory
|
||||
To initialize Graph Memory you'll need to set up your configuration with graph store providers.
|
||||
Currently, we support Neo4j as a graph store provider. You can setup [Neo4j](https://neo4j.com/) locally or use the hosted [Neo4j AuraDB](https://neo4j.com/product/auradb/).
|
||||
Moreover, you also need to set the version to `v1.1` (*prior versions are not supported*).
|
||||
Here's how you can do it:
|
||||
[Chrome Extension Demo](https://github.com/user-attachments/assets/ca92e40b-c453-4ff6-b25e-739fb18a8650)
|
||||
|
||||
```python
|
||||
from mem0 import Memory
|
||||
<br/><br/>
|
||||
|
||||
config = {
|
||||
"graph_store": {
|
||||
"provider": "neo4j",
|
||||
"config": {
|
||||
"url": "neo4j+s://xxx",
|
||||
"username": "neo4j",
|
||||
"password": "xxx"
|
||||
}
|
||||
},
|
||||
"version": "v1.1"
|
||||
}
|
||||
- Customer support bot using <strong>Langgraph and Mem0</strong>. Get the complete code from [here](https://docs.mem0.ai/integrations/langgraph)
|
||||
|
||||
|
||||
[Langgraph: Customer Bot](https://github.com/user-attachments/assets/ca6b482e-7f46-42c8-aa08-f88d1d93a5f4)
|
||||
|
||||
<br/><br/>
|
||||
|
||||
- Use Mem0 with CrewAI to get personalized results. Full example [here](https://docs.mem0.ai/integrations/crewai)
|
||||
|
||||
[CrewAI Demo](https://github.com/user-attachments/assets/69172a79-ccb9-4340-91f1-caa7d2dd4213)
|
||||
|
||||
m = Memory.from_config(config_dict=config)
|
||||
|
||||
```
|
||||
|
||||
## Documentation
|
||||
|
||||
For detailed usage instructions and API reference, visit our documentation at [docs.mem0.ai](https://docs.mem0.ai). Here, you can find more information on both the open-source version and the hosted [Mem0 Platform](https://app.mem0.ai).
|
||||
|
||||
## Star History
|
||||
|
||||
[](https://star-history.com/#mem0ai/mem0&Date)
|
||||
For detailed usage instructions and API reference, visit our [documentation](https://docs.mem0.ai). You'll find:
|
||||
- Complete API reference
|
||||
- Integration guides
|
||||
- Advanced configuration options
|
||||
- Best practices and examples
|
||||
- More details about:
|
||||
- Open-source version
|
||||
- [Hosted Mem0 Platform](https://app.mem0.ai)
|
||||
|
||||
## Support
|
||||
|
||||
@@ -209,20 +166,6 @@ Join our community for support and discussions. If you have any questions, feel
|
||||
- [Follow us on Twitter](https://x.com/mem0ai)
|
||||
- [Email founders](mailto:founders@mem0.ai)
|
||||
|
||||
## Contributors
|
||||
|
||||
Join our [Discord community](https://mem0.dev/DiG) to learn about memory management for AI agents and LLMs, and connect with Mem0 users and contributors. Share your ideas, questions, or feedback in our [GitHub Issues](https://github.com/mem0ai/mem0/issues).
|
||||
|
||||
We value and appreciate the contributions of our community. Special thanks to our contributors for helping us improve Mem0.
|
||||
|
||||
<a href="https://github.com/mem0ai/mem0/graphs/contributors">
|
||||
<img src="https://contrib.rocks/image?repo=mem0ai/mem0" />
|
||||
</a>
|
||||
|
||||
## Anonymous Telemetry
|
||||
|
||||
We collect anonymous usage metrics to enhance our package's quality and user experience. This includes data like feature usage frequency and system info, but never personal details. The data helps us prioritize improvements and ensure compatibility. If you wish to opt-out, set the environment variable MEM0_TELEMETRY=false. We prioritize data security and don't share this data externally.
|
||||
|
||||
## License
|
||||
|
||||
This project is licensed under the Apache 2.0 License - see the [LICENSE](LICENSE) file for details.
|
||||
|
||||
@@ -17,7 +17,6 @@ Mem0 offers two versions of the search API: v1 and v2. Here's how they differ:
|
||||
{
|
||||
"id":"ea925981-272f-40dd-b576-be64e4871429",
|
||||
"memory":"Likes to play cricket and plays cricket on weekends.",
|
||||
"hash":"c8809002-25c1-4c97-a3a2-227ce9c20c53",
|
||||
"metadata":{
|
||||
"category":"hobbies"
|
||||
},
|
||||
@@ -61,7 +60,6 @@ Mem0 offers two versions of the search API: v1 and v2. Here's how they differ:
|
||||
{
|
||||
"id": "ea925981-272f-40dd-b576-be64e4871429",
|
||||
"memory": "Likes to play cricket and plays cricket on weekends.",
|
||||
"hash": "c8809002-25c1-4c97-a3a2-227ce9c20c53",
|
||||
"metadata": {
|
||||
"category": "hobbies"
|
||||
},
|
||||
|
||||
@@ -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.
|
||||
|
||||
@@ -43,8 +47,6 @@ client = MemoryClient(
|
||||
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.
|
||||
|
||||
|
||||
Example with the mem0 Node.js package:
|
||||
|
||||
|
||||
@@ -1,15 +1,19 @@
|
||||
## 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:
|
||||
- `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
|
||||
|
||||
## How to Use Config
|
||||
## How to use configurations?
|
||||
|
||||
Here's a general example of how to use the config with mem0:
|
||||
|
||||
|
||||
@@ -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.
|
||||
|
||||
@@ -1,10 +1,12 @@
|
||||
## 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:
|
||||
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
|
||||
|
||||
@@ -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.
|
||||
|
||||
@@ -1,10 +1,12 @@
|
||||
## 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 a Python dictionary 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
|
||||
|
||||
@@ -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
|
||||
@@ -26,7 +26,8 @@ config = {
|
||||
"embedding_model_dims": 1536,
|
||||
"redis_url": "redis://localhost:6379"
|
||||
}
|
||||
}
|
||||
},
|
||||
"version": "v1.1"
|
||||
}
|
||||
|
||||
m = Memory.from_config(config)
|
||||
|
||||
@@ -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.
|
||||
@@ -16,6 +18,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
|
||||
|
||||
@@ -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.
|
||||
@@ -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
|
||||
+305
@@ -0,0 +1,305 @@
|
||||
{
|
||||
"$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/webhook"
|
||||
]
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
"group": "Open Source",
|
||||
"icon": "code-branch",
|
||||
"pages": [
|
||||
"open-source/quickstart",
|
||||
{
|
||||
"group": "Features",
|
||||
"icon": "wrench",
|
||||
"pages": [
|
||||
"features/openai_compatibility",
|
||||
"features/custom-prompts",
|
||||
"open-source/multimodal-support"
|
||||
]
|
||||
},
|
||||
{
|
||||
"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"
|
||||
]
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
"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/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/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",
|
||||
"icon": "users",
|
||||
"pages": [
|
||||
"api-reference/entities/get-users",
|
||||
"api-reference/entities/delete-user"
|
||||
]
|
||||
},
|
||||
{
|
||||
"group": "Organizations APIs",
|
||||
"icon": "building",
|
||||
"pages": [
|
||||
"api-reference/organization/get-orgs",
|
||||
"api-reference/organization/get-org",
|
||||
"api-reference/organization/create-org",
|
||||
"api-reference/organization/update-org",
|
||||
"api-reference/organization/delete-org",
|
||||
"api-reference/organization/get-org-members",
|
||||
"api-reference/organization/add-org-member",
|
||||
"api-reference/organization/remove-org-member",
|
||||
"api-reference/organization/get-org-projects",
|
||||
"api-reference/organization/add-org-project",
|
||||
"api-reference/organization/remove-org-project"
|
||||
]
|
||||
}
|
||||
]
|
||||
}
|
||||
]
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
"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"
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,92 @@
|
||||
---
|
||||
title: FAQs
|
||||
icon: "question"
|
||||
iconType: "solid"
|
||||
---
|
||||
|
||||
|
||||
<AccordionGroup>
|
||||
<Accordion title="How does Mem0 work?">
|
||||
Mem0 utilizes a sophisticated hybrid database system to efficiently manage and retrieve memories for AI agents and assistants. Each memory is linked to a unique identifier, such as a user ID or agent ID, enabling Mem0 to organize and access memories tailored to specific individuals or contexts.
|
||||
|
||||
When a message is added to Mem0 via the `add` method, the system extracts pertinent facts and preferences, distributing them across various data stores: a vector database and a graph database. This hybrid strategy ensures that diverse types of information are stored optimally, facilitating swift and effective searches.
|
||||
|
||||
When an AI agent or LLM needs to access memories, it employs the `search` method. Mem0 conducts a comprehensive search across these data stores, retrieving relevant information from each.
|
||||
|
||||
The retrieved memories can be seamlessly integrated into the LLM's prompt as required, enhancing the personalization and relevance of responses.
|
||||
</Accordion>
|
||||
|
||||
<Accordion title="What are the key features of Mem0?">
|
||||
- **User, Session, and AI Agent Memory**: Retains information across sessions and interactions for users and AI agents, ensuring continuity and context.
|
||||
- **Adaptive Personalization**: Continuously updates memories based on user interactions and feedback.
|
||||
- **Developer-Friendly API**: Offers a straightforward API for seamless integration into various applications.
|
||||
- **Platform Consistency**: Ensures consistent behavior and data across different platforms and devices.
|
||||
- **Managed Service**: Provides a hosted solution for easy deployment and maintenance.
|
||||
- **Save Costs**: Saves costs by adding relevent memories instead of complete transcripts to context window
|
||||
</Accordion>
|
||||
|
||||
<Accordion title="How Mem0 is different from traditional RAG?">
|
||||
Mem0's memory implementation for Large Language Models (LLMs) offers several advantages over Retrieval-Augmented Generation (RAG):
|
||||
|
||||
- **Entity Relationships**: Mem0 can understand and relate entities across different interactions, unlike RAG which retrieves information from static documents. This leads to a deeper understanding of context and relationships.
|
||||
|
||||
- **Contextual Continuity**: Mem0 retains information across sessions, maintaining continuity in conversations and interactions, which is essential for long-term engagement applications like virtual companions or personalized learning assistants.
|
||||
|
||||
- **Adaptive Learning**: Mem0 improves its personalization based on user interactions and feedback, making the memory more accurate and tailored to individual users over time.
|
||||
|
||||
- **Dynamic Updates**: Mem0 can dynamically update its memory with new information and interactions, unlike RAG which relies on static data. This allows for real-time adjustments and improvements, enhancing the user experience.
|
||||
|
||||
These advanced memory capabilities make Mem0 a powerful tool for developers aiming to create personalized and context-aware AI applications.
|
||||
</Accordion>
|
||||
|
||||
|
||||
<Accordion title="What are the common use-cases of Mem0?">
|
||||
- **Personalized Learning Assistants**: Long-term memory allows learning assistants to remember user preferences, strengths and weaknesses, and progress, providing a more tailored and effective learning experience.
|
||||
|
||||
- **Customer Support AI Agents**: By retaining information from previous interactions, customer support bots can offer more accurate and context-aware assistance, improving customer satisfaction and reducing resolution times.
|
||||
|
||||
- **Healthcare Assistants**: Long-term memory enables healthcare assistants to keep track of patient history, medication schedules, and treatment plans, ensuring personalized and consistent care.
|
||||
|
||||
- **Virtual Companions**: Virtual companions can use long-term memory to build deeper relationships with users by remembering personal details, preferences, and past conversations, making interactions more delightful.
|
||||
|
||||
- **Productivity Tools**: Long-term memory helps productivity tools remember user habits, frequently used documents, and task history, streamlining workflows and enhancing efficiency.
|
||||
|
||||
- **Gaming AI**: In gaming, AI with long-term memory can create more immersive experiences by remembering player choices, strategies, and progress, adapting the game environment accordingly.
|
||||
|
||||
</Accordion>
|
||||
|
||||
<Accordion title="Why aren't my memories being created?">
|
||||
Mem0 uses a sophisticated classification system to determine which parts of text should be extracted as memories. Not all text content will generate memories, as the system is designed to identify specific types of memorable information.
|
||||
There are several scenarios where mem0 may return an empty list of memories:
|
||||
|
||||
- When users input definitional questions (e.g., "What is backpropagation?")
|
||||
- For general concept explanations that don't contain personal or experiential information
|
||||
- Technical definitions and theoretical explanations
|
||||
- General knowledge statements without personal context
|
||||
- Abstract or theoretical content
|
||||
|
||||
Example Scenarios
|
||||
|
||||
```
|
||||
Input: "What is machine learning?"
|
||||
No memories extracted - Content is definitional and does not meet memory classification criteria.
|
||||
|
||||
Input: "Yesterday I learned about machine learning in class"
|
||||
Memory extracted - Contains personal experience and temporal context.
|
||||
```
|
||||
|
||||
Best Practices
|
||||
|
||||
To ensure successful memory extraction:
|
||||
- Include temporal markers (when events occurred)
|
||||
- Add personal context or experiences
|
||||
- Frame information in terms of real-world applications or experiences
|
||||
- Include specific examples or cases rather than general definitions
|
||||
</Accordion>
|
||||
|
||||
</AccordionGroup>
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
+2
-38
@@ -1,5 +1,7 @@
|
||||
---
|
||||
title: Features
|
||||
icon: "wrench"
|
||||
iconType: "solid"
|
||||
---
|
||||
|
||||
## Core features
|
||||
@@ -13,44 +15,6 @@ title: Features
|
||||
|
||||
|
||||
|
||||
## How does Mem0 work?
|
||||
|
||||
Mem0 leverages a hybrid database approach to manage and retrieve long-term memories for AI agents and assistants. Each memory is associated with a unique identifier, such as a user ID or agent ID, allowing Mem0 to organize and access memories specific to an individual or context.
|
||||
|
||||
When a message is added to the Mem0 using add() method, the system extracts relevant facts and preferences and stores it across data stores: a vector database, a key-value database, and a graph database. This hybrid approach ensures that different types of information are stored in the most efficient manner, making subsequent searches quick and effective.
|
||||
|
||||
When an AI agent or LLM needs to recall memories, it uses the search() method. Mem0 then performs search across these data stores, retrieving relevant information from each source. This information is then passed through a scoring layer, which evaluates their importance based on relevance, importance, and recency. This ensures that only the most personalized and useful context is surfaced.
|
||||
|
||||
The retrieved memories can then be appended to the LLM's prompt as needed, making responses personalized and relevant.
|
||||
|
||||
|
||||
## Common Use Cases
|
||||
|
||||
- **Personalized Learning Assistants**: Long-term memory allows learning assistants to remember user preferences, strengths and weaknesses, and progress, providing a more tailored and effective learning experience.
|
||||
|
||||
- **Customer Support AI Agents**: By retaining information from previous interactions, customer support bots can offer more accurate and context-aware assistance, improving customer satisfaction and reducing resolution times.
|
||||
|
||||
- **Healthcare Assistants**: Long-term memory enables healthcare assistants to keep track of patient history, medication schedules, and treatment plans, ensuring personalized and consistent care.
|
||||
|
||||
- **Virtual Companions**: Virtual companions can use long-term memory to build deeper relationships with users by remembering personal details, preferences, and past conversations, making interactions more delightful.
|
||||
|
||||
- **Productivity Tools**: Long-term memory helps productivity tools remember user habits, frequently used documents, and task history, streamlining workflows and enhancing efficiency.
|
||||
|
||||
- **Gaming AI**: In gaming, AI with long-term memory can create more immersive experiences by remembering player choices, strategies, and progress, adapting the game environment accordingly.
|
||||
|
||||
## How is Mem0 different from RAG?
|
||||
|
||||
Mem0's memory implementation for Large Language Models (LLMs) offers several advantages over Retrieval-Augmented Generation (RAG):
|
||||
|
||||
- **Entity Relationships**: Mem0 can understand and relate entities across different interactions, unlike RAG which retrieves information from static documents. This leads to a deeper understanding of context and relationships.
|
||||
|
||||
- **Contextual Continuity**: Mem0 retains information across sessions, maintaining continuity in conversations and interactions, which is essential for long-term engagement applications like virtual companions or personalized learning assistants.
|
||||
|
||||
- **Adaptive Learning**: Mem0 improves its personalization based on user interactions and feedback, making the memory more accurate and tailored to individual users over time.
|
||||
|
||||
- **Dynamic Updates**: Mem0 can dynamically update its memory with new information and interactions, unlike RAG which relies on static data. This allows for real-time adjustments and improvements, enhancing the user experience.
|
||||
|
||||
These advanced memory capabilities make Mem0 a powerful tool for developers aiming to create personalized and context-aware AI applications.
|
||||
|
||||
If you have any questions, please feel free to reach out to us using one of the following methods:
|
||||
|
||||
|
||||
@@ -0,0 +1,49 @@
|
||||
---
|
||||
title: Advanced Retrieval
|
||||
icon: "magnifying-glass"
|
||||
iconType: "solid"
|
||||
---
|
||||
|
||||
Mem0's **Advanced Retrieval** feature delivers superior search results by leveraging state-of-the-art search algorithms. Beyond the default search functionality, Mem0 offers the following advanced retrieval modes:
|
||||
|
||||
1. **Keyword Search**
|
||||
|
||||
This mode emphasizes keywords within the query, returning memories that contain the most relevant keywords alongside those from the default search. By default, this parameter is set to `false`. Enabling it enhances search recall, though it may slightly impact precision.
|
||||
|
||||
```python
|
||||
client.search(query, keyword_search=True, user_id='alex')
|
||||
```
|
||||
|
||||
2. **Reranking**
|
||||
|
||||
Reranking allows you to reorder the memories returned by the default search based on relevance. This parameter is set to `false` by default. When enabled, it reorders the memories based on the relevance score.
|
||||
|
||||
```python
|
||||
client.search(query, rerank=True, user_id='alex')
|
||||
```
|
||||
|
||||
3. **Filtering**
|
||||
|
||||
Filtering enables you to narrow down the search results by applying specific criteria. This parameter is set to `false` by default. Activating it enhances search precision, potentially reducing recall by a small margin.
|
||||
|
||||
```python
|
||||
client.search(query, filter_memories=True, user_id='alex')
|
||||
```
|
||||
|
||||
**Note:** You can enable or disable these search modes by passing the respective parameters to the `search` method. There is no required sequence for these modes, and any combination can be used based on your needs.
|
||||
|
||||
|
||||
### Latency Numbers
|
||||
|
||||
Here are the typical latency ranges for each search mode:
|
||||
|
||||
| **Mode** | **Latency** |
|
||||
|---------------------|------------------|
|
||||
| **Keyword Search** | **<10ms** |
|
||||
| **Reranking** | **150-200ms** |
|
||||
| **Filtering** | **200-300ms** |
|
||||
|
||||
|
||||
If you have any questions, please feel free to reach out to us using one of the following methods:
|
||||
|
||||
<Snippet file="get-help.mdx" />
|
||||
@@ -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.
|
||||
|
||||
@@ -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?
|
||||
@@ -28,7 +30,7 @@ new_categories = [
|
||||
{"personal_information": "Basic information about the user including name, preferences, and personality traits"}
|
||||
]
|
||||
|
||||
response = client.update_custom_instructions_and_categories({"custom_categories": new_categories})
|
||||
response = client.update_project(custom_categories = new_categories)
|
||||
print(response)
|
||||
```
|
||||
|
||||
@@ -51,7 +53,7 @@ messages = [
|
||||
]
|
||||
|
||||
# Add memories with custom categories
|
||||
client.add(messages, user_id="alice"))
|
||||
client.add(messages, user_id="alice")
|
||||
```
|
||||
|
||||
```python Memories with categories
|
||||
@@ -172,11 +174,11 @@ Name is Alice (personal_details)
|
||||
```
|
||||
</CodeGroup>
|
||||
|
||||
You can check whether default categories are being used by calling `get_custom_instructions_and_categories()`. If `custom_categories` returns `None`, it means the default categories are being used.
|
||||
You can check whether default categories are being used by calling `get_project()`. If `custom_categories` returns `None`, it means the default categories are being used.
|
||||
|
||||
<CodeGroup>
|
||||
```python Code
|
||||
client.get_custom_instructions_and_categories(["custom_categories"])
|
||||
client.get_project(["custom_categories"])
|
||||
```
|
||||
|
||||
```json Output
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -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?
|
||||
|
||||
@@ -1,6 +1,8 @@
|
||||
---
|
||||
title: Memory Export
|
||||
description: 'Export memories in a structured format using customizable Pydantic schemas'
|
||||
icon: "file-export"
|
||||
iconType: "solid"
|
||||
---
|
||||
|
||||
## Overview
|
||||
|
||||
@@ -0,0 +1,116 @@
|
||||
---
|
||||
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 MemoryClient
|
||||
|
||||
# Initialize the MemoryClient with your API key
|
||||
client = MemoryClient(api_key="your_api_key_here")
|
||||
|
||||
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.
|
||||
|
||||
If you have any questions, please feel free to reach out to us using one of the following methods:
|
||||
|
||||
<Snippet file="get-help.mdx" />
|
||||
@@ -1,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.
|
||||
|
||||
@@ -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" />
|
||||
@@ -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
|
||||
|
||||
@@ -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 allow you to receive real-time notifications when memory events occur in your Mem0 project. Webhooks are configured at the project level, meaning each webhook is associated with a specific project and will only receive events 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 new webhook for your project. The webhook will only receive events from the specified project:
|
||||
|
||||
<CodeGroup>
|
||||
|
||||
```python Python
|
||||
from mem0 import MemoryClient
|
||||
|
||||
client = MemoryClient(api_key="your-api-key")
|
||||
|
||||
# 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('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 configured 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
|
||||
|
||||
Modify an existing webhook's configuration. Remember that webhooks can only be updated within their associated project:
|
||||
|
||||
<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"],
|
||||
project_id="proj_123",
|
||||
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"],
|
||||
projectId: "proj_123",
|
||||
webhookId: "wh_123"
|
||||
});
|
||||
console.log(updatedWebhook);
|
||||
```
|
||||
|
||||
```json Output
|
||||
{
|
||||
"message": "Webhook updated successfully"
|
||||
}
|
||||
```
|
||||
|
||||
</CodeGroup>
|
||||
|
||||
### Delete Webhook
|
||||
|
||||
Remove a webhook configuration from a project:
|
||||
|
||||
<CodeGroup>
|
||||
|
||||
```python Python
|
||||
# Delete webhook from a specific project
|
||||
response = client.delete_webhook(webhook_id="wh_123", project_id="proj_123")
|
||||
print(response)
|
||||
```
|
||||
|
||||
```javascript JavaScript
|
||||
// Delete webhook from a specific project
|
||||
const response = await client.deleteWebhook("wh_123", "proj_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 new 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 in your project, Mem0 sends a POST request to your webhook URL with the following example payload structure:
|
||||
|
||||
```json
|
||||
{
|
||||
"event_details": {
|
||||
"id": "a1b2c3d4-e5f6-4g7h-8i9j-k0l1m2n3o4p5",
|
||||
"data": {
|
||||
"memory": "Name is Alex"
|
||||
},
|
||||
"event": "ADD"
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
## Best Practices
|
||||
|
||||
1. **Implement Retry Logic**: Your webhook endpoint should be able to handle temporary failures and implement appropriate retry mechanisms.
|
||||
|
||||
2. **Verify Webhook Source**: Implement security measures to verify that webhook requests are coming from Mem0.
|
||||
|
||||
3. **Process Events Asynchronously**: Handle webhook events asynchronously to prevent timeouts and ensure reliable processing.
|
||||
|
||||
4. **Monitor Webhook Health**: Regularly check your webhook logs to ensure proper functionality and handle any delivery failures.
|
||||
|
||||
If you have any questions, please feel free to reach out to us using one of the following methods:
|
||||
|
||||
<Snippet file="get-help.mdx" />
|
||||
Binary file not shown.
|
After Width: | Height: | Size: 276 KiB |
Binary file not shown.
|
After Width: | Height: | Size: 227 KiB |
File diff suppressed because one or more lines are too long
@@ -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.
|
||||
|
||||
-251
@@ -1,251 +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"
|
||||
}
|
||||
],
|
||||
"navigation": [
|
||||
{
|
||||
"group": "Get Started",
|
||||
"pages": [
|
||||
"overview",
|
||||
"quickstart",
|
||||
"playground",
|
||||
"features"
|
||||
]
|
||||
},
|
||||
{
|
||||
"group": "Platform",
|
||||
"pages": [
|
||||
"platform/overview",
|
||||
"platform/quickstart",
|
||||
{
|
||||
"group": "Features",
|
||||
"pages": ["features/selective-memory", "features/custom-categories", "features/custom-instructions", "features/direct-import", "features/async-client", "features/memory-export"]
|
||||
},
|
||||
"features/langchain-tools"
|
||||
]
|
||||
},
|
||||
{
|
||||
"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/vercel-ai-sdk",
|
||||
"integrations/crewai",
|
||||
"integrations/multion",
|
||||
"integrations/autogen",
|
||||
"integrations/langchain",
|
||||
"integrations/langgraph",
|
||||
"integrations/llama-index"
|
||||
]
|
||||
},
|
||||
{
|
||||
"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"
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -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.
|
||||
|
||||
@@ -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**.
|
||||
|
||||
@@ -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" />
|
||||
@@ -1,6 +1,8 @@
|
||||
---
|
||||
title: Guide
|
||||
description: 'Get started with Mem0 quickly!'
|
||||
icon: "book"
|
||||
iconType: "solid"
|
||||
---
|
||||
|
||||
> Welcome to the Mem0 quickstart guide. This guide will help you get up and running with Mem0 in no time.
|
||||
@@ -245,6 +247,106 @@ m.delete_all(user_id="alice")
|
||||
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.
|
||||
@@ -384,4 +486,4 @@ Please make sure your code follows our coding conventions and is well-documented
|
||||
|
||||
If you have any questions, please feel free to reach out to us using one of the following methods:
|
||||
|
||||
<Snippet file="get-help.mdx" />
|
||||
<Snippet file="get-help.mdx" />
|
||||
+60
-190
@@ -95,22 +95,6 @@
|
||||
],
|
||||
"operationId": "entities_list",
|
||||
"parameters": [
|
||||
{
|
||||
"name": "org_name",
|
||||
"in": "query",
|
||||
"schema": {
|
||||
"type": "string"
|
||||
},
|
||||
"description": "Filter entities by organization name. Will be deprecated soon, use `org_id` instead."
|
||||
},
|
||||
{
|
||||
"name": "project_name",
|
||||
"in": "query",
|
||||
"schema": {
|
||||
"type": "string"
|
||||
},
|
||||
"description": "Filter entities by project name. Will be deprecated soon, use `project_id` instead."
|
||||
},
|
||||
{
|
||||
"name": "org_id",
|
||||
"in": "query",
|
||||
@@ -699,22 +683,6 @@
|
||||
},
|
||||
"description": "Filter memories by categories"
|
||||
},
|
||||
{
|
||||
"name": "org_name",
|
||||
"in": "query",
|
||||
"schema": {
|
||||
"type": "string"
|
||||
},
|
||||
"description": "Filter memories by organization name. Will be deprecated soon, use `org_id` instead."
|
||||
},
|
||||
{
|
||||
"name": "project_name",
|
||||
"in": "query",
|
||||
"schema": {
|
||||
"type": "string"
|
||||
},
|
||||
"description": "Filter memories by project name. Will be deprecated soon, use `project_id` instead."
|
||||
},
|
||||
{
|
||||
"name": "org_id",
|
||||
"in": "query",
|
||||
@@ -868,7 +836,7 @@
|
||||
{
|
||||
"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// Retrieve memories for a specific user\nclient.getAll({ user_id: \"<user_id>\" })\n .then(result => console.log(result))\n .catch(error => console.error(error));"
|
||||
},
|
||||
},
|
||||
{
|
||||
"lang": "cURL",
|
||||
"source": "curl --location --request GET 'https://api.mem0.ai/v1/memories/' \\\n--header 'Authorization: Token <api-key>'"
|
||||
@@ -978,19 +946,19 @@
|
||||
},
|
||||
{
|
||||
"lang": "cURL",
|
||||
"source": "curl --request POST \\\n --url https://api.mem0.ai/v1/memories/ \\\n --header 'Authorization: Token <api-key>' \\\n --header 'Content-Type: application/json' \\\n --data '{\n \"messages\": [\n {}\n ],\n \"agent_id\": \"<string>\",\n \"user_id\": \"<string>\",\n \"app_id\": \"<string>\",\n \"run_id\": \"<string>\",\n \"metadata\": {},\n \"includes\": \"<string>\",\n \"excludes\": \"<string>\",\n \"infer\": true,\n \"custom_categories\": {},\n \"org_name\": \"<string>\",\n \"project_name\": \"<string>\", \n \"org_id\": \"<string>\",\n \"project_id\": \"<string>\"\n}'"
|
||||
"source": "curl --request POST \\\n --url https://api.mem0.ai/v1/memories/ \\\n --header 'Authorization: Token <api-key>' \\\n --header 'Content-Type: application/json' \\\n --data '{\n \"messages\": [\n {}\n ],\n \"agent_id\": \"<string>\",\n \"user_id\": \"<string>\",\n \"app_id\": \"<string>\",\n \"run_id\": \"<string>\",\n \"metadata\": {},\n \"includes\": \"<string>\",\n \"excludes\": \"<string>\",\n \"infer\": true,\n \"custom_categories\": {}, \n \"org_id\": \"<string>\",\n \"project_id\": \"<string>\"\n}'"
|
||||
},
|
||||
{
|
||||
"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\n\turl := \"https://api.mem0.ai/v1/memories/\"\n\n\tpayload := strings.NewReader(\"{\n \\\"messages\\\": [\n {}\n ],\n \\\"agent_id\\\": \\\"<string>\\\",\n \\\"user_id\\\": \\\"<string>\\\",\n \\\"app_id\\\": \\\"<string>\\\",\n \\\"run_id\\\": \\\"<string>\\\",\n \\\"metadata\\\": {},\n \\\"includes\\\": \\\"<string>\\\",\n \\\"excludes\\\": \\\"<string>\\\",\n \\\"infer\\\": true,\n \\\"custom_categories\\\": {},\n \\\"org_name\\\": \\\"<string>\\\",\n \\\"project_name\\\": \\\"<string>\\\", \n \\\"org_id\\\": \\\"<string>\\\",\n \\\"project_id\\\": \\\"<string>\"\n}\")\n\n\treq, _ := http.NewRequest(\"POST\", url, payload)\n\n\treq.Header.Add(\"Authorization\", \"Token <api-key>\")\n\treq.Header.Add(\"Content-Type\", \"application/json\")\n\n\tres, _ := http.DefaultClient.Do(req)\n\n\tdefer res.Body.Close()\n\tbody, _ := ioutil.ReadAll(res.Body)\n\n\tfmt.Println(res)\n\tfmt.Println(string(body))\n\n}"
|
||||
"source": "package main\n\nimport (\n\t\"fmt\"\n\t\"strings\"\n\t\"net/http\"\n\t\"io/ioutil\"\n)\n\nfunc main() {\n\n\turl := \"https://api.mem0.ai/v1/memories/\"\n\n\tpayload := strings.NewReader(\"{\n \\\"messages\\\": [\n {}\n ],\n \\\"agent_id\\\": \\\"<string>\\\",\n \\\"user_id\\\": \\\"<string>\\\",\n \\\"app_id\\\": \\\"<string>\\\",\n \\\"run_id\\\": \\\"<string>\\\",\n \\\"metadata\\\": {},\n \\\"includes\\\": \\\"<string>\\\",\n \\\"excludes\\\": \\\"<string>\\\",\n \\\"infer\\\": true,\n \\\"custom_categories\\\": {},\n \\\"org_id\\\": \\\"<string>\\\",\n \\\"project_id\\\": \\\"<string>\"\n}\")\n\n\treq, _ := http.NewRequest(\"POST\", url, payload)\n\n\treq.Header.Add(\"Authorization\", \"Token <api-key>\")\n\treq.Header.Add(\"Content-Type\", \"application/json\")\n\n\tres, _ := http.DefaultClient.Do(req)\n\n\tdefer res.Body.Close()\n\tbody, _ := ioutil.ReadAll(res.Body)\n\n\tfmt.Println(res)\n\tfmt.Println(string(body))\n\n}"
|
||||
},
|
||||
{
|
||||
"lang": "PHP",
|
||||
"source": "<?php\n\n$curl = curl_init();\n\ncurl_setopt_array($curl, [\n CURLOPT_URL => \"https://api.mem0.ai/v1/memories/\",\n CURLOPT_RETURNTRANSFER => true,\n CURLOPT_ENCODING => \"\",\n CURLOPT_MAXREDIRS => 10,\n CURLOPT_TIMEOUT => 30,\n CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,\n CURLOPT_CUSTOMREQUEST => \"POST\",\n CURLOPT_POSTFIELDS => \"{\n \\\"messages\\\": [\n {}\n ],\n \\\"agent_id\\\": \\\"<string>\\\",\n \\\"user_id\\\": \\\"<string>\\\",\n \\\"app_id\\\": \\\"<string>\\\",\n \\\"run_id\\\": \\\"<string>\\\",\n \\\"metadata\\\": {},\n \\\"includes\\\": \\\"<string>\\\",\n \\\"excludes\\\": \\\"<string>\\\",\n \\\"infer\\\": true,\n \\\"custom_categories\\\": {},\n \\\"org_name\\\": \\\"<string>\\\",\n \\\"project_name\\\": \\\"<string>\\\", \n \\\"org_id\\\": \\\"<string>\\\",\n \\\"project_id\\\": \\\"<string>\"\n}\",\n CURLOPT_HTTPHEADER => [\n \"Authorization: Token <api-key>\",\n \"Content-Type: application/json\"\n ],\n]);\n\n$response = curl_exec($curl);\n$err = curl_error($curl);\n\ncurl_close($curl);\n\nif ($err) {\n echo \"cURL Error #:\" . $err;\n} else {\n echo $response;\n}"
|
||||
"source": "<?php\n\n$curl = curl_init();\n\ncurl_setopt_array($curl, [\n CURLOPT_URL => \"https://api.mem0.ai/v1/memories/\",\n CURLOPT_RETURNTRANSFER => true,\n CURLOPT_ENCODING => \"\",\n CURLOPT_MAXREDIRS => 10,\n CURLOPT_TIMEOUT => 30,\n CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,\n CURLOPT_CUSTOMREQUEST => \"POST\",\n CURLOPT_POSTFIELDS => \"{\n \\\"messages\\\": [\n {}\n ],\n \\\"agent_id\\\": \\\"<string>\\\",\n \\\"user_id\\\": \\\"<string>\\\",\n \\\"app_id\\\": \\\"<string>\\\",\n \\\"run_id\\\": \\\"<string>\\\",\n \\\"metadata\\\": {},\n \\\"includes\\\": \\\"<string>\\\",\n \\\"excludes\\\": \\\"<string>\\\",\n \\\"infer\\\": true,\n \\\"custom_categories\\\": {}, \n \\\"org_id\\\": \\\"<string>\\\",\n \\\"project_id\\\": \\\"<string>\"\n}\",\n CURLOPT_HTTPHEADER => [\n \"Authorization: Token <api-key>\",\n \"Content-Type: application/json\"\n ],\n]);\n\n$response = curl_exec($curl);\n$err = curl_error($curl);\n\ncurl_close($curl);\n\nif ($err) {\n echo \"cURL Error #:\" . $err;\n} else {\n echo $response;\n}"
|
||||
},
|
||||
{
|
||||
"lang": "Java",
|
||||
"source": "HttpResponse<String> response = Unirest.post(\"https://api.mem0.ai/v1/memories/\")\n .header(\"Authorization\", \"Token <api-key>\")\n .header(\"Content-Type\", \"application/json\")\n .body(\"{\n \\\"messages\\\": [\n {}\n ],\n \\\"agent_id\\\": \\\"<string>\\\",\n \\\"user_id\\\": \\\"<string>\\\",\n \\\"app_id\\\": \\\"<string>\\\",\n \\\"run_id\\\": \\\"<string>\\\",\n \\\"metadata\\\": {},\n \\\"includes\\\": \\\"<string>\\\",\n \\\"excludes\\\": \\\"<string>\\\",\n \\\"infer\\\": true,\n \\\"custom_categories\\\": {},\n \\\"org_name\\\": \\\"<string>\\\",\n \\\"project_name\\\": \\\"<string>\\\", \n \\\"org_id\\\": \\\"<string>\\\",\n \\\"project_id\\\": \\\"<string>\"\n}\")\n .asString();"
|
||||
"source": "HttpResponse<String> response = Unirest.post(\"https://api.mem0.ai/v1/memories/\")\n .header(\"Authorization\", \"Token <api-key>\")\n .header(\"Content-Type\", \"application/json\")\n .body(\"{\n \\\"messages\\\": [\n {}\n ],\n \\\"agent_id\\\": \\\"<string>\\\",\n \\\"user_id\\\": \\\"<string>\\\",\n \\\"app_id\\\": \\\"<string>\\\",\n \\\"run_id\\\": \\\"<string>\\\",\n \\\"metadata\\\": {},\n \\\"includes\\\": \\\"<string>\\\",\n \\\"excludes\\\": \\\"<string>\\\",\n \\\"infer\\\": true,\n \\\"custom_categories\\\": {}, \n \\\"org_id\\\": \\\"<string>\\\",\n \\\"project_id\\\": \\\"<string>\"\n}\")\n .asString();"
|
||||
}
|
||||
],
|
||||
"x-codegen-request-body-name": "data"
|
||||
@@ -1044,22 +1012,6 @@
|
||||
"style": "deepObject",
|
||||
"explode": true
|
||||
},
|
||||
{
|
||||
"name": "org_name",
|
||||
"in": "query",
|
||||
"schema": {
|
||||
"type": "string"
|
||||
},
|
||||
"description": "Filter memories by organization name. Will be deprecated soon, use `org_id` instead."
|
||||
},
|
||||
{
|
||||
"name": "project_name",
|
||||
"in": "query",
|
||||
"schema": {
|
||||
"type": "string"
|
||||
},
|
||||
"description": "Filter memories by project name. Will be deprecated soon, use `project_id` instead."
|
||||
},
|
||||
{
|
||||
"name": "org_id",
|
||||
"in": "query",
|
||||
@@ -1165,22 +1117,6 @@
|
||||
"style": "deepObject",
|
||||
"explode": true
|
||||
},
|
||||
{
|
||||
"name": "org_name",
|
||||
"in": "query",
|
||||
"schema": {
|
||||
"type": "string"
|
||||
},
|
||||
"description": "Filter memories by organization name. Will be deprecated soon, use `org_id` instead."
|
||||
},
|
||||
{
|
||||
"name": "project_name",
|
||||
"in": "query",
|
||||
"schema": {
|
||||
"type": "string"
|
||||
},
|
||||
"description": "Filter memories by project name. Will be deprecated soon, use `project_id` instead."
|
||||
},
|
||||
{
|
||||
"name": "org_id",
|
||||
"in": "query",
|
||||
@@ -1368,44 +1304,22 @@
|
||||
"type": "string",
|
||||
"description": "The content of the memory"
|
||||
},
|
||||
"input": {
|
||||
"type": "array",
|
||||
"items": {
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"role": {
|
||||
"type": "string",
|
||||
"enum": [
|
||||
"user",
|
||||
"assistant"
|
||||
],
|
||||
"description": "The role of the speaker in the conversation"
|
||||
},
|
||||
"content": {
|
||||
"type": "string",
|
||||
"description": "The content of the message"
|
||||
}
|
||||
},
|
||||
"required": [
|
||||
"role",
|
||||
"content"
|
||||
]
|
||||
},
|
||||
"description": "The conversation input that was used to generate this memory"
|
||||
},
|
||||
"user_id": {
|
||||
"type": "string",
|
||||
"description": "The identifier of the user associated with this memory"
|
||||
},
|
||||
"hash": {
|
||||
"type": "string",
|
||||
"description": "A hash of the memory content"
|
||||
},
|
||||
"metadata": {
|
||||
"type": "object",
|
||||
"nullable": true,
|
||||
"description": "Additional metadata associated with the memory"
|
||||
},
|
||||
"categories": {
|
||||
"type": "array",
|
||||
"items": {
|
||||
"type": "string"
|
||||
},
|
||||
"description": "Categories associated with the memory"
|
||||
},
|
||||
"created_at": {
|
||||
"type": "string",
|
||||
"format": "date-time",
|
||||
@@ -1420,9 +1334,7 @@
|
||||
"required": [
|
||||
"id",
|
||||
"memory",
|
||||
"input",
|
||||
"user_id",
|
||||
"hash",
|
||||
"created_at",
|
||||
"updated_at"
|
||||
]
|
||||
@@ -1459,7 +1371,7 @@
|
||||
},
|
||||
{
|
||||
"lang": "cURL",
|
||||
"source": "curl --request POST \\\n --url https://api.mem0.ai/v1/memories/search/ \\\n --header 'Authorization: Token <api-key>' \\\n --header 'Content-Type: application/json' \\\n --data '{\n \"query\": \"<string>\",\n \"agent_id\": \"<string>\",\n \"user_id\": \"<string>\",\n \"app_id\": \"<string>\",\n \"run_id\": \"<string>\",\n \"metadata\": {},\n \"top_k\": 123,\n \"fields\": [\n \"<string>\"\n ],\n \"rerank\": true,\n \"org_name\": \"<string>\",\n \"project_name\": \"<string>\", \n \"org_id\": \"<string>\",\n \"project_id\": \"<string>\"\n}'"
|
||||
"source": "curl --request POST \\\n --url https://api.mem0.ai/v1/memories/search/ \\\n --header 'Authorization: Token <api-key>' \\\n --header 'Content-Type: application/json' \\\n --data '{\n \"query\": \"<string>\",\n \"agent_id\": \"<string>\",\n \"user_id\": \"<string>\",\n \"app_id\": \"<string>\",\n \"run_id\": \"<string>\",\n \"metadata\": {},\n \"top_k\": 123,\n \"fields\": [\n \"<string>\"\n ],\n \"rerank\": true,\n \"org_id\": \"<string>\",\n \"project_id\": \"<string>\"\n}'"
|
||||
},
|
||||
{
|
||||
"lang": "Go",
|
||||
@@ -1513,44 +1425,22 @@
|
||||
"type": "string",
|
||||
"description": "The content of the memory"
|
||||
},
|
||||
"input": {
|
||||
"type": "array",
|
||||
"items": {
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"role": {
|
||||
"type": "string",
|
||||
"enum": [
|
||||
"user",
|
||||
"assistant"
|
||||
],
|
||||
"description": "The role of the speaker in the conversation"
|
||||
},
|
||||
"content": {
|
||||
"type": "string",
|
||||
"description": "The content of the message"
|
||||
}
|
||||
},
|
||||
"required": [
|
||||
"role",
|
||||
"content"
|
||||
]
|
||||
},
|
||||
"description": "The conversation input that was used to generate this memory"
|
||||
},
|
||||
"user_id": {
|
||||
"type": "string",
|
||||
"description": "The identifier of the user associated with this memory"
|
||||
},
|
||||
"hash": {
|
||||
"type": "string",
|
||||
"description": "A hash of the memory content"
|
||||
},
|
||||
"metadata": {
|
||||
"type": "object",
|
||||
"nullable": true,
|
||||
"description": "Additional metadata associated with the memory"
|
||||
},
|
||||
"categories": {
|
||||
"type": "array",
|
||||
"items": {
|
||||
"type": "string"
|
||||
},
|
||||
"description": "Categories associated with the memory"
|
||||
},
|
||||
"created_at": {
|
||||
"type": "string",
|
||||
"format": "date-time",
|
||||
@@ -1565,9 +1455,7 @@
|
||||
"required": [
|
||||
"id",
|
||||
"memory",
|
||||
"input",
|
||||
"user_id",
|
||||
"hash",
|
||||
"created_at",
|
||||
"updated_at"
|
||||
]
|
||||
@@ -1588,19 +1476,19 @@
|
||||
},
|
||||
{
|
||||
"lang": "cURL",
|
||||
"source": "curl --request POST \\\n --url https://api.mem0.ai/v2/memories/search/ \\\n --header 'Authorization: Token <api-key>' \\\n --header 'Content-Type: application/json' \\\n --data '{\n \"query\": \"<string>\",\n \"filters\": {},\n \"top_k\": 123,\n \"fields\": [\n \"<string>\"\n ],\n \"rerank\": true,\n \"org_name\": \"<string>\",\n \"project_name\": \"<string>\",\n \"org_id\": \"<string>\",\n \"project_id\": \"<string>\"\n}'"
|
||||
"source": "curl --request POST \\\n --url https://api.mem0.ai/v2/memories/search/ \\\n --header 'Authorization: Token <api-key>' \\\n --header 'Content-Type: application/json' \\\n --data '{\n \"query\": \"<string>\",\n \"filters\": {},\n \"top_k\": 123,\n \"fields\": [\n \"<string>\"\n ],\n \"rerank\": true,\n \"org_id\": \"<string>\",\n \"project_id\": \"<string>\"\n}'"
|
||||
},
|
||||
{
|
||||
"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\n\turl := \"https://api.mem0.ai/v2/memories/search/\"\n\n\tpayload := strings.NewReader(\"{\n \\\"query\\\": \\\"<string>\\\",\n \\\"filters\\\": {},\n \\\"top_k\\\": 123,\n \\\"fields\\\": [\n \\\"<string>\\\"\n ],\n \\\"rerank\\\": true,\n \\\"org_name\\\": \\\"<string>\\\",\n \\\"project_name\\\": \\\"<string>\\\",\n \\\"org_id\\\": \\\"<string>\\\",\n \\\"project_id\\\": \\\"<string>\\\"\n}\")\n\n\treq, _ := http.NewRequest(\"POST\", url, payload)\n\n\treq.Header.Add(\"Authorization\", \"Token <api-key>\")\n\treq.Header.Add(\"Content-Type\", \"application/json\")\n\n\tres, _ := http.DefaultClient.Do(req)\n\n\tdefer res.Body.Close()\n\tbody, _ := ioutil.ReadAll(res.Body)\n\n\tfmt.Println(res)\n\tfmt.Println(string(body))\n\n}"
|
||||
"source": "package main\n\nimport (\n\t\"fmt\"\n\t\"strings\"\n\t\"net/http\"\n\t\"io/ioutil\"\n)\n\nfunc main() {\n\n\turl := \"https://api.mem0.ai/v2/memories/search/\"\n\n\tpayload := strings.NewReader(\"{\n \\\"query\\\": \\\"<string>\\\",\n \\\"filters\\\": {},\n \\\"top_k\\\": 123,\n \\\"fields\\\": [\n \\\"<string>\\\"\n ],\n \\\"rerank\\\": true,\n \\\"org_id\\\": \\\"<string>\\\",\n \\\"project_id\\\": \\\"<string>\\\"\n}\")\n\n\treq, _ := http.NewRequest(\"POST\", url, payload)\n\n\treq.Header.Add(\"Authorization\", \"Token <api-key>\")\n\treq.Header.Add(\"Content-Type\", \"application/json\")\n\n\tres, _ := http.DefaultClient.Do(req)\n\n\tdefer res.Body.Close()\n\tbody, _ := ioutil.ReadAll(res.Body)\n\n\tfmt.Println(res)\n\tfmt.Println(string(body))\n\n}"
|
||||
},
|
||||
{
|
||||
"lang": "PHP",
|
||||
"source": "<?php\n\n$curl = curl_init();\n\ncurl_setopt_array($curl, [\n CURLOPT_URL => \"https://api.mem0.ai/v2/memories/search/\",\n CURLOPT_RETURNTRANSFER => true,\n CURLOPT_ENCODING => \"\",\n CURLOPT_MAXREDIRS => 10,\n CURLOPT_TIMEOUT => 30,\n CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,\n CURLOPT_CUSTOMREQUEST => \"POST\",\n CURLOPT_POSTFIELDS => \"{\n \\\"query\\\": \\\"<string>\\\",\n \\\"filters\\\": {},\n \\\"top_k\\\": 123,\n \\\"fields\\\": [\n \\\"<string>\\\"\n ],\n \\\"rerank\\\": true,\n \\\"org_name\\\": \\\"<string>\\\",\n \\\"project_name\\\": \\\"<string>\\\",\n \\\"org_id\\\": \\\"<string>\\\",\n \\\"project_id\\\": \\\"<string>\\\"\n}\",\n CURLOPT_HTTPHEADER => [\n \"Authorization: Token <api-key>\",\n \"Content-Type: application/json\"\n ],\n]);\n\n$response = curl_exec($curl);\n$err = curl_error($curl);\n\ncurl_close($curl);\n\nif ($err) {\n echo \"cURL Error #:\" . $err;\n} else {\n echo $response;\n}"
|
||||
"source": "<?php\n\n$curl = curl_init();\n\ncurl_setopt_array($curl, [\n CURLOPT_URL => \"https://api.mem0.ai/v2/memories/search/\",\n CURLOPT_RETURNTRANSFER => true,\n CURLOPT_ENCODING => \"\",\n CURLOPT_MAXREDIRS => 10,\n CURLOPT_TIMEOUT => 30,\n CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,\n CURLOPT_CUSTOMREQUEST => \"POST\",\n CURLOPT_POSTFIELDS => \"{\n \\\"query\\\": \\\"<string>\\\",\n \\\"filters\\\": {},\n \\\"top_k\\\": 123,\n \\\"fields\\\": [\n \\\"<string>\\\"\n ],\n \\\"rerank\\\": true,\n \\\"org_id\\\": \\\"<string>\\\",\n \\\"project_id\\\": \\\"<string>\\\"\n}\",\n CURLOPT_HTTPHEADER => [\n \"Authorization: Token <api-key>\",\n \"Content-Type: application/json\"\n ],\n]);\n\n$response = curl_exec($curl);\n$err = curl_error($curl);\n\ncurl_close($curl);\n\nif ($err) {\n echo \"cURL Error #:\" . $err;\n} else {\n echo $response;\n}"
|
||||
},
|
||||
{
|
||||
"lang": "Java",
|
||||
"source": "HttpResponse<String> response = Unirest.post(\"https://api.mem0.ai/v2/memories/search/\")\n .header(\"Authorization\", \"Token <api-key>\")\n .header(\"Content-Type\", \"application/json\")\n .body(\"{\n \\\"query\\\": \\\"<string>\\\",\n \\\"filters\\\": {},\n \\\"top_k\\\": 123,\n \\\"fields\\\": [\n \\\"<string>\\\"\n ],\n \\\"rerank\\\": true,\n \\\"org_name\\\": \\\"<string>\\\",\n \\\"project_name\\\": \\\"<string>\\\",\n \\\"org_id\\\": \\\"<string>\\\",\n \\\"project_id\\\": \\\"<string>\\\"\n}\")\n .asString();"
|
||||
"source": "HttpResponse<String> response = Unirest.post(\"https://api.mem0.ai/v2/memories/search/\")\n .header(\"Authorization\", \"Token <api-key>\")\n .header(\"Content-Type\", \"application/json\")\n .body(\"{\n \\\"query\\\": \\\"<string>\\\",\n \\\"filters\\\": {},\n \\\"top_k\\\": 123,\n \\\"fields\\\": [\n \\\"<string>\\\"\n ],\n \\\"rerank\\\": true,\n \\\"org_id\\\": \\\"<string>\\\",\n \\\"project_id\\\": \\\"<string>\\\"\n}\")\n .asString();"
|
||||
}
|
||||
],
|
||||
"x-codegen-request-body-name": "data"
|
||||
@@ -4388,30 +4276,24 @@
|
||||
},
|
||||
"nullable": true
|
||||
},
|
||||
"org_name": {
|
||||
"description": "The name of the organization associated with this memory. Will be deprecated soon use `org_id` instead.",
|
||||
"title": "Organization name",
|
||||
"type": "string",
|
||||
"nullable": true
|
||||
},
|
||||
"project_name": {
|
||||
"description": "The name of the project associated with this memory. Will be deprecated soon use project_id instead.",
|
||||
"title": "Project name",
|
||||
"type": "string",
|
||||
"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
|
||||
},
|
||||
"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": {
|
||||
@@ -4479,24 +4361,18 @@
|
||||
"default": false,
|
||||
"description": "Whether to rerank the memories."
|
||||
},
|
||||
"keyword_search": {
|
||||
"title": "Keyword search",
|
||||
"type": "boolean",
|
||||
"default": false,
|
||||
"description": "Whether to search for memories based on keywords."
|
||||
},
|
||||
"output_format": {
|
||||
"title": "Output format",
|
||||
"type": "string",
|
||||
"nullable": true,
|
||||
"description": "The search method supports two output formats: `v1.0` (default) and `v1.1`."
|
||||
},
|
||||
"org_name": {
|
||||
"title": "Organization Name",
|
||||
"type": "string",
|
||||
"nullable": true,
|
||||
"description": "The name of the organization associated with the memory. Will be deprecated soon use `org_id` instead."
|
||||
},
|
||||
"project_name": {
|
||||
"title": "Project Name",
|
||||
"type": "string",
|
||||
"nullable": true,
|
||||
"description": "The name of the project associated with the memory. Will be deprecated soon use project_id instead."
|
||||
},
|
||||
"org_id": {
|
||||
"title": "Organization id",
|
||||
"type": "string",
|
||||
@@ -4592,30 +4468,24 @@
|
||||
"default": false,
|
||||
"description": "Whether to rerank the memories."
|
||||
},
|
||||
"keyword_search": {
|
||||
"title": "Keyword search",
|
||||
"type": "boolean",
|
||||
"default": false,
|
||||
"description": "Whether to search for memories based on keywords."
|
||||
},
|
||||
"filter_memories": {
|
||||
"title": "Filter memories",
|
||||
"type": "boolean",
|
||||
"default": false,
|
||||
"description": "Whether to filter the memories."
|
||||
},
|
||||
"threshold": {
|
||||
"title": "Threshold",
|
||||
"type": "number",
|
||||
"default": 0.3,
|
||||
"description": "The minimum similarity threshold for returned results."
|
||||
},
|
||||
"smart_search": {
|
||||
"title": "Smart Search",
|
||||
"type": "boolean",
|
||||
"default": false,
|
||||
"description": "Whether to enable smart search functionality."
|
||||
},
|
||||
"org_name": {
|
||||
"title": "Organization Name",
|
||||
"type": "string",
|
||||
"nullable": true,
|
||||
"description": "The name of the organization associated with the memory. Will be deprecated soon use `org_id` instead."
|
||||
},
|
||||
"project_name": {
|
||||
"title": "Project Name",
|
||||
"type": "string",
|
||||
"nullable": true,
|
||||
"description": "The name of the project associated with the memory. Will be deprecated soon use `project_id` instead."
|
||||
},
|
||||
"org_id": {
|
||||
"title": "Organization id",
|
||||
"type": "string",
|
||||
|
||||
+29
-45
@@ -1,68 +1,52 @@
|
||||
---
|
||||
title: Overview
|
||||
icon: "info"
|
||||
iconType: "solid"
|
||||
---
|
||||
|
||||
<Note type="info">
|
||||
🎉 Exciting news! We have added support for [DeepSeek](https://deepseek.com).
|
||||
🔔 New Feature: [Webhooks](/features/webhook) are now available! Configure real-time notifications for memory events in your Mem0 project.
|
||||
</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
|
||||
|
||||
[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'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.
|
||||
|
||||
## Key Features
|
||||
|
||||
- **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
|
||||
|
||||
## Use Cases
|
||||
|
||||
- **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).
|
||||
## Getting Started
|
||||
|
||||
|
||||
<CardGroup cols={3}>
|
||||
<Card title="Quickstart" icon="rocket" href="/quickstart">
|
||||
Integrate Mem0 in a few lines of code
|
||||
</Card>
|
||||
<Card title="Playground" icon="play" href="playground">
|
||||
<Card title="Playground" icon="play" href="https://app.mem0.ai/playground">
|
||||
Mem0 in action
|
||||
</Card>
|
||||
<Card title="Examples" icon="lightbulb" href="/open-source/quickstart">
|
||||
<Card title="Examples" icon="lightbulb" href="/examples">
|
||||
See what you can build with Mem0
|
||||
</Card>
|
||||
</CardGroup>
|
||||
## Key Features
|
||||
|
||||
- OpenAI-compatible API: Easily switch between OpenAI and Mem0
|
||||
- Advanced memory management: Save costs by efficiently handling long-term context
|
||||
- Flexible deployment: Choose between managed platform or self-hosted solution
|
||||
<Card title="All Mem0 Features" icon="list" href="/features" horizontal="false">
|
||||
</Card>
|
||||
|
||||
# Memory Classification in mem0
|
||||
|
||||
Mem0 uses a sophisticated classification system to determine which parts of text should be extracted as memories. Not all text content will generate memories, as the system is designed to identify specific types of memorable information.
|
||||
|
||||
### When Memories Are Not Generated
|
||||
|
||||
There are several scenarios where mem0 may return an empty list of memories:
|
||||
|
||||
- When users input definitional questions (e.g., "What is backpropagation?")
|
||||
- For general concept explanations that don't contain personal or experiential information
|
||||
- Technical definitions and theoretical explanations
|
||||
- General knowledge statements without personal context
|
||||
- Abstract or theoretical content
|
||||
|
||||
### Example Scenarios
|
||||
|
||||
```
|
||||
Input: "What is machine learning?"
|
||||
No memories extracted - Content is definitional and does not meet memory classification criteria.
|
||||
|
||||
Input: "Yesterday I learned about machine learning in class"
|
||||
Memory extracted - Contains personal experience and temporal context.
|
||||
```
|
||||
|
||||
### Best Practices
|
||||
|
||||
To ensure successful memory extraction:
|
||||
- Include temporal markers (when events occurred)
|
||||
- Add personal context or experiences
|
||||
- Frame information in terms of real-world applications or experiences
|
||||
- Include specific examples or cases rather than general definitions
|
||||
|
||||
|
||||
## Need help?
|
||||
If you have any questions, please feel free to reach out to us using one of the following methods:
|
||||
|
||||
<Snippet file="get-help.mdx"/>
|
||||
@@ -1,6 +1,8 @@
|
||||
---
|
||||
title: Introduction
|
||||
description: 'Empower your AI applications with long-term memory and personalization'
|
||||
icon: "eye"
|
||||
iconType: "solid"
|
||||
---
|
||||
|
||||
## Welcome to Mem0 Platform
|
||||
@@ -27,6 +29,6 @@ Check out our [Platform Guide](/platform/guide) to start using Mem0 platform qui
|
||||
## Next Steps
|
||||
|
||||
- Sign up to the [Mem0 Platform](https://mem0.dev/pd)
|
||||
- Join our [Discord](https://mem0.dev/Did) or [Slack](https://mem0.ai/slack) with other developers and get support.
|
||||
- Join our [Discord](https://mem0.dev/Did) or [Slack](https://mem0.dev/slack) with other developers and get support.
|
||||
|
||||
We're excited to see what you'll build with Mem0 Platform. Let's create smarter, more personalized AI experiences together!
|
||||
|
||||
@@ -1,8 +1,14 @@
|
||||
---
|
||||
title: Guide
|
||||
description: 'Get started with Mem0 Platform in minutes'
|
||||
icon: "book"
|
||||
iconType: "solid"
|
||||
---
|
||||
|
||||
<Note type="info">
|
||||
🎉 Looking for TypeScript support? Mem0 has you covered! Check out an example [here](/platform/quickstart/#4-11-working-with-mem0-in-typescript).
|
||||
</Note>
|
||||
|
||||
## 1. Installation
|
||||
|
||||
<CodeGroup>
|
||||
@@ -27,8 +33,12 @@ npm install mem0ai
|
||||
|
||||
<CodeGroup>
|
||||
```python Python
|
||||
import os
|
||||
from mem0 import MemoryClient
|
||||
client = MemoryClient(api_key="your-api-key")
|
||||
|
||||
os.environ["MEM0_API_KEY"] = "your-api-key"
|
||||
|
||||
client = MemoryClient()
|
||||
```
|
||||
|
||||
```javascript JavaScript
|
||||
@@ -43,9 +53,12 @@ const client = new MemoryClient({ apiKey: 'your-api-key' });
|
||||
For asynchronous operations in Python, you can use the AsyncMemoryClient:
|
||||
|
||||
```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()
|
||||
|
||||
|
||||
async def main():
|
||||
@@ -154,7 +167,7 @@ curl -X POST "https://api.mem0.ai/v1/memories/" \
|
||||
</CodeGroup>
|
||||
|
||||
|
||||
<Note> The `add` method offers support for two output formats: `v1.0` (default) and `v1.1`. To enable the latest format, which provides enhanced detail for each memory operation, set the `output_format` parameter to `v1.1`. Note that `v1.0` will be deprecated in version `0.1.30`. </Note>
|
||||
<Note> The `add` method offers support for two output formats: `v1.0` (default) and `v1.1`. To enable the latest format, which provides enhanced detail for each memory operation, set the `output_format` parameter to `v1.1`. </Note>
|
||||
|
||||
<Note>
|
||||
Messages passed along with `user_id`, `run_id`, or `app_id` are stored as user memories, while messages from the assistant are excluded from memory. To store messages for the assistant, use `agent_id` exclusively and avoid including other IDs, such as user_id, alongside it. This ensures the memory is properly attributed to the assistant.
|
||||
@@ -389,18 +402,7 @@ curl -X POST "https://api.mem0.ai/v1/memories/search/" \
|
||||
{
|
||||
"id": "7f165f7e-b411-4afe-b7e5-35789b72c4a5",
|
||||
"memory": "Vegetarian. Allergic to nuts.",
|
||||
"input": [
|
||||
{
|
||||
"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."
|
||||
}
|
||||
],
|
||||
"user_id": "alex",
|
||||
"hash": "9ee7e1455e84d1dab700ed8749aed75a",
|
||||
"metadata": {"food": "vegan"},
|
||||
"categories": ["food_preferences"],
|
||||
"created_at": "2024-07-20T01:30:36.275141-07:00",
|
||||
@@ -415,18 +417,7 @@ curl -X POST "https://api.mem0.ai/v1/memories/search/" \
|
||||
{
|
||||
"id": "7f165f7e-b411-4afe-b7e5-35789b72c4a5",
|
||||
"memory": "Vegetarian. Allergic to nuts.",
|
||||
"input": [
|
||||
{
|
||||
"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."
|
||||
}
|
||||
],
|
||||
"user_id": "alex",
|
||||
"hash": "9ee7e1455e84d1dab700ed8749aed75a",
|
||||
"metadata": {"food": "vegan"},
|
||||
"categories": ["food_preferences"],
|
||||
"created_at": "2024-07-20T01:30:36.275141-07:00",
|
||||
@@ -469,18 +460,7 @@ 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.",
|
||||
"input": [
|
||||
{
|
||||
"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."
|
||||
}
|
||||
],
|
||||
"user_id": "alex",
|
||||
"hash": "9ee7e1455e84d1dab700ed8749aed75a",
|
||||
"metadata": {"food": "vegan"},
|
||||
"categories": ["food_preferences"],
|
||||
"created_at": "2024-07-20T01:30:36.275141-07:00",
|
||||
@@ -569,18 +549,7 @@ 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.",
|
||||
"input": [
|
||||
{
|
||||
"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."
|
||||
}
|
||||
],
|
||||
"user_id": "alex",
|
||||
"hash": "9ee7e1455e84d1dab700ed8749aed75a",
|
||||
"metadata": null,
|
||||
"categories": ["food_preferences"],
|
||||
"created_at": "2024-07-20T01:30:36.275141-07:00",
|
||||
@@ -644,18 +613,7 @@ 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.",
|
||||
"input": [
|
||||
{
|
||||
"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."
|
||||
}
|
||||
],
|
||||
"user_id": "alex",
|
||||
"hash": "9ee7e1455e84d1dab700ed8749aed75a",
|
||||
"metadata": null,
|
||||
"categories": ["food_preferences"],
|
||||
"created_at": "2024-07-20T01:30:36.275141-07:00",
|
||||
@@ -728,18 +686,7 @@ curl -X POST "https://api.mem0.ai/v1/memories/search/?version=v2" \
|
||||
{
|
||||
"id": "654fee-b411-4afe-b7e5-35789b72c4a5",
|
||||
"memory": "Name: Alex. Vegetarian. Allergic to nuts.",
|
||||
"input": [
|
||||
{
|
||||
"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."
|
||||
}
|
||||
],
|
||||
"user_id": "alex",
|
||||
"hash": "9ee7e1455e84d1dab700eiy8749aed75a",
|
||||
"metadata": {"food": "vegan"},
|
||||
"categories": ["food_preferences"],
|
||||
"created_at": "2024-07-20T01:30:36.275141-07:00",
|
||||
@@ -1641,7 +1588,18 @@ curl -X POST "https://api.mem0.ai/v1/memories/" \
|
||||
```
|
||||
|
||||
```json Output
|
||||
{'message': 'ok'}
|
||||
[{'id': '3f4eccba-3b09-497a-81ab-cca1ababb36b',
|
||||
'memory': 'Is allergic to nuts',
|
||||
'event': 'DELETE'},
|
||||
{'id': 'f5dcfbf4-5f0b-422a-8ad4-cadb9e941e25',
|
||||
'memory': 'Is a vegetarian',
|
||||
'event': 'DELETE'},
|
||||
{'id': 'dd32f70c-fa69-4fc7-997b-fb4a66d1a0fa',
|
||||
'memory': 'Name is Alex',
|
||||
'event': 'DELETE'}]{'message': 'ok'}
|
||||
{'id': '3f4eccba-3b09-497a-81ab-cca1ababb36b',
|
||||
'memory': 'Likes Chicken',
|
||||
'event': 'DELETE'}
|
||||
```
|
||||
|
||||
</CodeGroup>
|
||||
@@ -1743,6 +1701,52 @@ curl -X DELETE "https://api.mem0.ai/v1/memories/batch/" \
|
||||
```
|
||||
</CodeGroup>
|
||||
|
||||
### 4.11 Working with Mem0 in TypeScript
|
||||
Manage memories using TypeScript with Mem0. Mem0 has completet TypeScript support Below is an example demonstrating how to add and search memories.
|
||||
|
||||
<CodeGroup>
|
||||
```typescript TypeScript
|
||||
import MemoryClient, { Message, SearchOptions, MemoryOptions } from 'mem0ai';
|
||||
|
||||
const apiKey = 'your-api-key-here';
|
||||
const client = new MemoryClient(apiKey);
|
||||
|
||||
// Messages
|
||||
const messages: Message[] = [
|
||||
{ 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." }
|
||||
];
|
||||
|
||||
// ADD
|
||||
const memoryOptions: MemoryOptions = {
|
||||
user_id: "alex",
|
||||
agent_id: "travel-assistant"
|
||||
}
|
||||
|
||||
client.add(messages, memoryOptions)
|
||||
.then(result => console.log(result))
|
||||
.catch(error => console.error(error));
|
||||
|
||||
// SEARCH
|
||||
const query: string = "What do you know about me?";
|
||||
const searchOptions: SearchOptions = {
|
||||
user_id: "alex",
|
||||
filters: {
|
||||
OR: [
|
||||
{ agent_id: "travel-assistant" },
|
||||
{ user_id: "alex" }
|
||||
]
|
||||
},
|
||||
threshold: 0.1,
|
||||
api_version: 'v2'
|
||||
}
|
||||
|
||||
client.search(query, searchOptions)
|
||||
.then(results => console.log(results))
|
||||
.catch(error => console.error(error));
|
||||
```
|
||||
</CodeGroup>
|
||||
|
||||
If you have any questions, please feel free to reach out to us using one of the following methods:
|
||||
|
||||
<Snippet file="get-help.mdx" />
|
||||
@@ -1,25 +0,0 @@
|
||||
---
|
||||
title: Interactive Playground
|
||||
---
|
||||
Watch Mem0 in action with our Playground tool.
|
||||
|
||||
<Steps>
|
||||
<Step title="Create Mem0 Account">
|
||||
You'll need to create a free Mem0 account to use the playground – this helps ensure responses are more tailored to you by associating interactions with an individual profile.
|
||||
<Card title="Sign up to Mem0" icon="right-to-bracket" href="https://mem0.dev/pd" horizontal="true">
|
||||
</Card>
|
||||
</Step>
|
||||
<Step title="Go to Playground">
|
||||
<Card title="Mem0 Playground" icon="play" href="https://mem0.dev/pd-pg" horizontal="true">
|
||||
</Card>
|
||||
</Step>
|
||||
<Step title="Start adding memories">
|
||||
Chat with the assistant to start adding memories.
|
||||

|
||||
</Step>
|
||||
<Step title="Experience the power of Mem0">
|
||||
Memories are stored in context for all future conversations, creating truly personal AI.
|
||||

|
||||
</Step>
|
||||
</Steps>
|
||||
|
||||
+78
-23
@@ -1,10 +1,14 @@
|
||||
---
|
||||
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).
|
||||
|
||||
Check out our [Playground](https://mem0.dev/pd-pg) to see Mem0 in action.
|
||||
|
||||
<CardGroup cols={2}>
|
||||
<Card title="Mem0 Platform" icon="chart-simple" href="#mem0-platform-managed-solution">
|
||||
<Card title="Mem0 Platform (Managed Solution)" icon="chart-simple" href="#mem0-platform-managed-solution">
|
||||
Better, faster, fully managed, and hassle free solution.
|
||||
</Card>
|
||||
<Card title="Mem0 Open Source" icon="code-branch" href="#mem0-open-source">
|
||||
@@ -17,6 +21,8 @@ Mem0 offers two powerful ways to leverage our technology: [our managed platform]
|
||||
|
||||
Our fully managed platform provides a hassle-free way to integrate Mem0's capabilities into your AI agents and assistants. Sign up for Mem0 platform [here](https://mem0.dev/pd).
|
||||
|
||||
The Mem0 SDK supports both Python and JavaScript, with full [TypeScript](/platform/quickstart/#4-11-working-with-mem0-in-typescript) support as well.
|
||||
|
||||
Follow the steps below to get started with Mem0 Platform:
|
||||
|
||||
1. [Install Mem0](#1-install-mem0)
|
||||
@@ -53,8 +59,12 @@ npm install mem0ai
|
||||
<Accordion title="Instantiate client">
|
||||
<CodeGroup>
|
||||
```python Python
|
||||
import os
|
||||
from mem0 import MemoryClient
|
||||
client = MemoryClient(api_key="your-api-key")
|
||||
|
||||
os.environ["MEM0_API_KEY"] = "your-api-key"
|
||||
|
||||
client = MemoryClient()
|
||||
```
|
||||
|
||||
```javascript JavaScript
|
||||
@@ -98,7 +108,15 @@ curl -X POST "https://api.mem0.ai/v1/memories/" \
|
||||
```
|
||||
|
||||
```json Output
|
||||
{'message': 'ok'}
|
||||
[{'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'}]
|
||||
```
|
||||
</CodeGroup>
|
||||
</Accordion>
|
||||
@@ -112,23 +130,43 @@ curl -X POST "https://api.mem0.ai/v1/memories/" \
|
||||
|
||||
```python Python
|
||||
query = "What can I cook for dinner tonight?"
|
||||
client.search(query, user_id="alex")
|
||||
filters = {
|
||||
"AND": [
|
||||
{
|
||||
"user_id": "alex"
|
||||
}
|
||||
]
|
||||
}
|
||||
client.search(query, version="v2", filters=filters)
|
||||
```
|
||||
|
||||
```javascript JavaScript
|
||||
const query = "What can I cook for dinner tonight?";
|
||||
client.search(query, { user_id: "alex" })
|
||||
const filters = {
|
||||
"AND": [
|
||||
{
|
||||
"user_id": "alex"
|
||||
}
|
||||
]
|
||||
};
|
||||
client.search(query, { version: "v2", filters })
|
||||
.then(results => console.log(results))
|
||||
.catch(error => console.error(error));
|
||||
```
|
||||
|
||||
```bash cURL
|
||||
curl -X POST "https://api.mem0.ai/v1/memories/search/" \
|
||||
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?",
|
||||
"user_id": "alex"
|
||||
"filters": {
|
||||
"AND": [
|
||||
{
|
||||
"user_id": "alex"
|
||||
}
|
||||
]
|
||||
}
|
||||
}'
|
||||
```
|
||||
|
||||
@@ -137,18 +175,7 @@ curl -X POST "https://api.mem0.ai/v1/memories/search/" \
|
||||
{
|
||||
"id": "7f165f7e-b411-4afe-b7e5-35789b72c4a5",
|
||||
"memory": "Name: Alex. Vegetarian. Allergic to nuts.",
|
||||
"input": [
|
||||
{
|
||||
"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."
|
||||
}
|
||||
],
|
||||
"user_id": "alex",
|
||||
"hash": "9ee7e1455e84d1dab700ed8749aed75a",
|
||||
"metadata": null,
|
||||
"created_at": "2024-07-20T01:30:36.275141-07:00",
|
||||
"updated_at": "2024-07-20T01:30:36.275172-07:00"
|
||||
@@ -163,18 +190,44 @@ curl -X POST "https://api.mem0.ai/v1/memories/search/" \
|
||||
<CodeGroup>
|
||||
|
||||
```python Python
|
||||
user_memories = client.get_all(user_id="alex")
|
||||
filters = {
|
||||
"AND": [
|
||||
{
|
||||
"user_id": "alice"
|
||||
}
|
||||
]
|
||||
}
|
||||
|
||||
all_memories = client.get_all(version="v2", filters=filters, page=1, page_size=50)
|
||||
```
|
||||
|
||||
```javascript JavaScript
|
||||
client.getAll({ user_id: "alex" })
|
||||
const filters = {
|
||||
"AND": [
|
||||
{
|
||||
"user_id": "alice"
|
||||
}
|
||||
]
|
||||
};
|
||||
|
||||
client.getAll({ version: "v2", filters, page: 1, page_size: 50 })
|
||||
.then(memories => console.log(memories))
|
||||
.catch(error => console.error(error));
|
||||
```
|
||||
|
||||
```bash cURL
|
||||
curl -X GET "https://api.mem0.ai/v1/memories/?user_id=alex" \
|
||||
-H "Authorization: Token your-api-key"
|
||||
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": [
|
||||
{
|
||||
"user_id": "alice"
|
||||
}
|
||||
]
|
||||
}
|
||||
}'
|
||||
```
|
||||
|
||||
```json Output
|
||||
@@ -244,7 +297,9 @@ result = m.add("I like to take long walks on weekends.", user_id="alice", metada
|
||||
```
|
||||
|
||||
```json Output
|
||||
{'message': 'ok'}
|
||||
[{'id': 'ea9b08ee-09d7-4e8b-9912-687ad65548b4',
|
||||
'memory': 'Likes to take long walks on weekends',
|
||||
'event': 'ADD'}]
|
||||
```
|
||||
</CodeGroup>
|
||||
</Accordion>
|
||||
|
||||
@@ -2,7 +2,7 @@
|
||||
title: 'Full Stack'
|
||||
---
|
||||
|
||||
The Full Stack app example can be found [here](https://github.com/embedchain/embedchain/tree/main/examples/full_stack).
|
||||
The Full Stack app example can be found [here](https://github.com/mem0ai/mem0/tree/main/embedchain/examples/full_stack).
|
||||
|
||||
This guide will help you setup the full stack app on your local machine.
|
||||
|
||||
|
||||
@@ -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
|
||||
|
||||
+159
-47
@@ -14,6 +14,8 @@ logger = logging.getLogger(__name__)
|
||||
# Setup user config
|
||||
setup_config()
|
||||
|
||||
warnings.filterwarnings("default", category=DeprecationWarning)
|
||||
|
||||
|
||||
class APIError(Exception):
|
||||
"""Exception raised for errors in the API."""
|
||||
@@ -48,8 +50,6 @@ class MemoryClient:
|
||||
api_key (str): The API key for authenticating with the Mem0 API.
|
||||
host (str): The base URL for the Mem0 API.
|
||||
client (httpx.Client): The HTTP client used for making API requests.
|
||||
organization (str, optional): (Deprecated) Organization name.
|
||||
project (str, optional): (Deprecated) Project name.
|
||||
org_id (str, optional): Organization ID.
|
||||
project_id (str, optional): Project ID.
|
||||
user_id (str): Unique identifier for the user.
|
||||
@@ -59,8 +59,6 @@ class MemoryClient:
|
||||
self,
|
||||
api_key: Optional[str] = None,
|
||||
host: Optional[str] = None,
|
||||
organization: Optional[str] = None,
|
||||
project: Optional[str] = None,
|
||||
org_id: Optional[str] = None,
|
||||
project_id: Optional[str] = None,
|
||||
):
|
||||
@@ -70,8 +68,6 @@ class MemoryClient:
|
||||
api_key: The API key for authenticating with the Mem0 API. If not provided,
|
||||
it will attempt to use the MEM0_API_KEY environment variable.
|
||||
host: The base URL for the Mem0 API. Defaults to "https://api.mem0.ai".
|
||||
organization: (Deprecated) The name of the organization. Use org_id instead.
|
||||
project: (Deprecated) The name of the project. Use project_id instead.
|
||||
org_id: The ID of the organization.
|
||||
project_id: The ID of the project.
|
||||
|
||||
@@ -80,8 +76,6 @@ class MemoryClient:
|
||||
"""
|
||||
self.api_key = api_key or os.getenv("MEM0_API_KEY")
|
||||
self.host = host or "https://api.mem0.ai"
|
||||
self.organization = organization
|
||||
self.project = project
|
||||
self.org_id = org_id
|
||||
self.project_id = project_id
|
||||
self.user_id = get_user_id()
|
||||
@@ -89,18 +83,10 @@ class MemoryClient:
|
||||
if not self.api_key:
|
||||
raise ValueError("Mem0 API Key not provided. Please provide an API Key.")
|
||||
|
||||
if organization or project:
|
||||
warnings.warn(
|
||||
"Using 'organization' and 'project' parameters is deprecated and will be removed in version 0.1.40. "
|
||||
"Please use 'org_id' and 'project_id' instead.",
|
||||
DeprecationWarning,
|
||||
stacklevel=2,
|
||||
)
|
||||
|
||||
self.client = httpx.Client(
|
||||
base_url=self.host,
|
||||
headers={"Authorization": f"Token {self.api_key}", "Mem0-User-ID": self.user_id},
|
||||
timeout=60,
|
||||
timeout=300,
|
||||
)
|
||||
self._validate_api_key()
|
||||
capture_client_event("client.init", self)
|
||||
@@ -110,16 +96,21 @@ class MemoryClient:
|
||||
try:
|
||||
params = self._prepare_params()
|
||||
response = self.client.get("/v1/ping/", params=params)
|
||||
data = response.json()
|
||||
|
||||
response.raise_for_status()
|
||||
|
||||
if response.status_code == 200:
|
||||
data = response.json()
|
||||
if data.get("org_id") and data.get("project_id"):
|
||||
self.org_id = data.get("org_id")
|
||||
self.project_id = data.get("project_id")
|
||||
if data.get("org_id") and data.get("project_id"):
|
||||
self.org_id = data.get("org_id")
|
||||
self.project_id = data.get("project_id")
|
||||
|
||||
except httpx.HTTPStatusError:
|
||||
raise ValueError("Invalid API Key. Please get a valid API Key from https://app.mem0.ai")
|
||||
except httpx.HTTPStatusError as e:
|
||||
try:
|
||||
error_data = e.response.json()
|
||||
error_message = error_data.get("detail", str(e))
|
||||
except:
|
||||
error_message = str(e)
|
||||
raise ValueError(f"Error: {error_message}")
|
||||
|
||||
@api_error_handler
|
||||
def add(self, messages: Union[str, List[Dict[str, str]]], **kwargs) -> Dict[str, Any]:
|
||||
@@ -136,6 +127,14 @@ class MemoryClient:
|
||||
APIError: If the API request fails.
|
||||
"""
|
||||
kwargs = self._prepare_params(kwargs)
|
||||
if kwargs.get("output_format") != "v1.1":
|
||||
warnings.warn(
|
||||
"Using default output format 'v1.0' is deprecated and will be removed in version 0.1.70. "
|
||||
"Please use output_format='v1.1' for enhanced memory details. "
|
||||
"Check out the docs for more information: https://docs.mem0.ai/platform/quickstart#4-1-create-memories",
|
||||
DeprecationWarning,
|
||||
stacklevel=2,
|
||||
)
|
||||
payload = self._prepare_payload(messages, kwargs)
|
||||
response = self.client.post("/v1/memories/", json=payload)
|
||||
response.raise_for_status()
|
||||
@@ -169,7 +168,7 @@ class MemoryClient:
|
||||
|
||||
Args:
|
||||
version: The API version to use for the search endpoint.
|
||||
**kwargs: Optional parameters for filtering (user_id, agent_id, app_id, limit).
|
||||
**kwargs: Optional parameters for filtering (user_id, agent_id, app_id, top_k).
|
||||
|
||||
Returns:
|
||||
A list of dictionaries containing memories.
|
||||
@@ -203,7 +202,7 @@ class MemoryClient:
|
||||
Args:
|
||||
query: The search query string.
|
||||
version: The API version to use for the search endpoint.
|
||||
**kwargs: Additional parameters such as user_id, agent_id, app_id, limit, filters.
|
||||
**kwargs: Additional parameters such as user_id, agent_id, app_id, top_k, filters.
|
||||
|
||||
Returns:
|
||||
A list of dictionaries containing search results.
|
||||
@@ -525,6 +524,97 @@ class MemoryClient:
|
||||
"""
|
||||
raise NotImplementedError("Chat is not implemented yet")
|
||||
|
||||
@api_error_handler
|
||||
def get_webhooks(self, project_id: str) -> Dict[str, Any]:
|
||||
"""Get webhooks configuration for the project.
|
||||
|
||||
Args:
|
||||
project_id: The ID of the project to get webhooks for.
|
||||
|
||||
Returns:
|
||||
Dictionary containing webhook details.
|
||||
|
||||
Raises:
|
||||
APIError: If the API request fails.
|
||||
ValueError: If project_id is not set.
|
||||
"""
|
||||
|
||||
response = self.client.get(f"api/v1/webhooks/{project_id}/webhook/")
|
||||
response.raise_for_status()
|
||||
capture_client_event("client.get_webhook", self)
|
||||
return response.json()
|
||||
|
||||
@api_error_handler
|
||||
def create_webhook(self, url: str, name: str, project_id: str, event_types: List[str]) -> Dict[str, Any]:
|
||||
"""Create a webhook for the current project.
|
||||
|
||||
Args:
|
||||
url: The URL to send the webhook to.
|
||||
name: The name of the webhook.
|
||||
event_types: List of event types to trigger the webhook for.
|
||||
|
||||
Returns:
|
||||
Dictionary containing the created webhook details.
|
||||
|
||||
Raises:
|
||||
APIError: If the API request fails.
|
||||
ValueError: If project_id is not set.
|
||||
"""
|
||||
|
||||
payload = {"url": url, "name": name, "event_types": event_types}
|
||||
response = self.client.post(f"api/v1/webhooks/{project_id}/webhook/", json=payload)
|
||||
response.raise_for_status()
|
||||
capture_client_event("client.create_webhook", self)
|
||||
return response.json()
|
||||
|
||||
@api_error_handler
|
||||
def update_webhook(
|
||||
self, webhook_id: int, project_id: str, name: Optional[str] = None, url: Optional[str] = None, event_types: Optional[List[str]] = None
|
||||
) -> Dict[str, Any]:
|
||||
"""Update a webhook configuration.
|
||||
|
||||
Args:
|
||||
webhook_id: ID of the webhook to update
|
||||
project_id: The ID of the project to update the webhook for.
|
||||
name: Optional new name for the webhook
|
||||
url: Optional new URL for the webhook
|
||||
event_types: Optional list of event types to trigger the webhook for.
|
||||
|
||||
Returns:
|
||||
Dictionary containing the updated webhook details.
|
||||
|
||||
Raises:
|
||||
APIError: If the API request fails.
|
||||
ValueError: If project_id is not set.
|
||||
"""
|
||||
|
||||
payload = {k: v for k, v in {"name": name, "url": url, "event_types": event_types}.items() if v is not None}
|
||||
response = self.client.put(f"api/v1/webhooks/{project_id}/webhook/{webhook_id}/", json=payload)
|
||||
response.raise_for_status()
|
||||
capture_client_event("client.update_webhook", self, {"webhook_id": webhook_id})
|
||||
return response.json()
|
||||
|
||||
@api_error_handler
|
||||
def delete_webhook(self, webhook_id: int, project_id: str) -> Dict[str, str]:
|
||||
"""Delete a webhook configuration.
|
||||
|
||||
Args:
|
||||
webhook_id: ID of the webhook to delete
|
||||
project_id: The ID of the project to delete the webhook for.
|
||||
|
||||
Returns:
|
||||
Dictionary containing success message.
|
||||
|
||||
Raises:
|
||||
APIError: If the API request fails.
|
||||
ValueError: If project_id is not set.
|
||||
"""
|
||||
|
||||
response = self.client.delete(f"api/v1/webhooks/{project_id}/webhook/{webhook_id}/")
|
||||
response.raise_for_status()
|
||||
capture_client_event("client.delete_webhook", self, {"webhook_id": webhook_id})
|
||||
return response.json()
|
||||
|
||||
def _prepare_payload(
|
||||
self, messages: Union[str, List[Dict[str, str]], None], kwargs: Dict[str, Any]
|
||||
) -> Dict[str, Any]:
|
||||
@@ -556,21 +646,12 @@ class MemoryClient:
|
||||
A dictionary containing the prepared parameters.
|
||||
|
||||
Raises:
|
||||
ValueError: If both org_id/project_id and org_name/project_name are provided.
|
||||
ValueError: If either org_id or project_id is provided but not both.
|
||||
"""
|
||||
|
||||
if kwargs is None:
|
||||
kwargs = {}
|
||||
|
||||
has_new = bool(self.org_id or self.project_id)
|
||||
has_old = bool(self.organization or self.project)
|
||||
|
||||
if has_new and has_old:
|
||||
raise ValueError(
|
||||
"Please use either org_id/project_id or org_name/project_name, not both. "
|
||||
"Note that org_name/project_name are deprecated."
|
||||
)
|
||||
|
||||
# Add org_id and project_id if both are available
|
||||
if self.org_id and self.project_id:
|
||||
kwargs["org_id"] = self.org_id
|
||||
@@ -578,13 +659,6 @@ class MemoryClient:
|
||||
elif self.org_id or self.project_id:
|
||||
raise ValueError("Please provide both org_id and project_id")
|
||||
|
||||
# Add deprecated org_name and project_name if both are available
|
||||
if self.organization and self.project:
|
||||
kwargs["org_name"] = self.organization
|
||||
kwargs["project_name"] = self.project
|
||||
elif self.organization or self.project:
|
||||
raise ValueError("Please provide both org_name and project_name")
|
||||
|
||||
return {k: v for k, v in kwargs.items() if v is not None}
|
||||
|
||||
|
||||
@@ -603,16 +677,14 @@ class AsyncMemoryClient:
|
||||
self,
|
||||
api_key: Optional[str] = None,
|
||||
host: Optional[str] = None,
|
||||
organization: Optional[str] = None,
|
||||
project: Optional[str] = None,
|
||||
org_id: Optional[str] = None,
|
||||
project_id: Optional[str] = None,
|
||||
):
|
||||
self.sync_client = MemoryClient(api_key, host, organization, project, org_id, project_id)
|
||||
self.sync_client = MemoryClient(api_key, host, org_id, project_id)
|
||||
self.async_client = httpx.AsyncClient(
|
||||
base_url=self.sync_client.host,
|
||||
headers=self.sync_client.client.headers,
|
||||
timeout=60,
|
||||
timeout=300,
|
||||
)
|
||||
|
||||
async def __aenter__(self):
|
||||
@@ -886,3 +958,43 @@ class AsyncMemoryClient:
|
||||
|
||||
async def chat(self):
|
||||
raise NotImplementedError("Chat is not implemented yet")
|
||||
|
||||
@api_error_handler
|
||||
async def get_webhooks(self, project_id: str) -> Dict[str, Any]:
|
||||
|
||||
response = await self.async_client.get(
|
||||
f"api/v1/webhooks/{project_id}/webhook/",
|
||||
)
|
||||
response.raise_for_status()
|
||||
capture_client_event("async_client.get_webhook", self.sync_client)
|
||||
return response.json()
|
||||
|
||||
@api_error_handler
|
||||
async def create_webhook(self, url: str, name: str, project_id: str, event_types: List[str]) -> Dict[str, Any]:
|
||||
|
||||
payload = {"url": url, "name": name, "event_types": event_types}
|
||||
response = await self.async_client.post(
|
||||
f"api/v1/webhooks/{project_id}/webhook/", json=payload
|
||||
)
|
||||
response.raise_for_status()
|
||||
capture_client_event("async_client.create_webhook", self.sync_client)
|
||||
return response.json()
|
||||
|
||||
@api_error_handler
|
||||
async def update_webhook(
|
||||
self, webhook_id: int,project_id: str, name: Optional[str] = None, url: Optional[str] = None, event_types: Optional[List[str]] = None
|
||||
) -> Dict[str, Any]:
|
||||
|
||||
payload = {k: v for k, v in {"name": name, "url": url, "event_types": event_types}.items() if v is not None}
|
||||
response = await self.async_client.put(f"api/v1/webhooks/{project_id}/webhook/{webhook_id}/", json=payload)
|
||||
response.raise_for_status()
|
||||
capture_client_event("async_client.update_webhook", self.sync_client, {"webhook_id": webhook_id})
|
||||
return response.json()
|
||||
|
||||
@api_error_handler
|
||||
async def delete_webhook(self, webhook_id: int, project_id: str) -> Dict[str, str]:
|
||||
|
||||
response = await self.async_client.delete(f"api/v1/webhooks/{project_id}/webhook/{webhook_id}/")
|
||||
response.raise_for_status()
|
||||
capture_client_event("async_client.delete_webhook", self.sync_client, {"webhook_id": webhook_id})
|
||||
return response.json()
|
||||
|
||||
@@ -0,0 +1,42 @@
|
||||
from typing import Any, Dict, Optional
|
||||
|
||||
from pydantic import BaseModel, Field, model_validator
|
||||
|
||||
|
||||
class OpenSearchConfig(BaseModel):
|
||||
collection_name: str = Field("mem0", description="Name of the index")
|
||||
host: str = Field("localhost", description="OpenSearch host")
|
||||
port: int = Field(9200, description="OpenSearch port")
|
||||
user: Optional[str] = Field(None, description="Username for authentication")
|
||||
password: Optional[str] = Field(None, description="Password for authentication")
|
||||
api_key: Optional[str] = Field(None, description="API key for authentication (if applicable)")
|
||||
embedding_model_dims: int = Field(1536, description="Dimension of the embedding vector")
|
||||
verify_certs: bool = Field(False, description="Verify SSL certificates (default False for OpenSearch)")
|
||||
use_ssl: bool = Field(False, description="Use SSL for connection (default False for OpenSearch)")
|
||||
auto_create_index: bool = Field(True, description="Automatically create index during initialization")
|
||||
|
||||
@model_validator(mode="before")
|
||||
@classmethod
|
||||
def validate_auth(cls, values: Dict[str, Any]) -> Dict[str, Any]:
|
||||
# Check if host is provided
|
||||
if not values.get("host"):
|
||||
raise ValueError("Host must be provided for OpenSearch")
|
||||
|
||||
# Authentication: Either API key or user/password must be provided
|
||||
if not any([values.get("api_key"), (values.get("user") and values.get("password"))]):
|
||||
raise ValueError("Either api_key or user/password must be provided for OpenSearch authentication")
|
||||
|
||||
return values
|
||||
|
||||
@model_validator(mode="before")
|
||||
@classmethod
|
||||
def validate_extra_fields(cls, values: Dict[str, Any]) -> Dict[str, Any]:
|
||||
allowed_fields = set(cls.model_fields.keys())
|
||||
input_fields = set(values.keys())
|
||||
extra_fields = input_fields - allowed_fields
|
||||
if extra_fields:
|
||||
raise ValueError(
|
||||
f"Extra fields not allowed: {', '.join(extra_fields)}. "
|
||||
f"Allowed fields: {', '.join(allowed_fields)}"
|
||||
)
|
||||
return values
|
||||
+2
-1
@@ -63,6 +63,7 @@ class OpenAILLM(LLMBase):
|
||||
response_format=None,
|
||||
tools: Optional[List[Dict]] = None,
|
||||
tool_choice: str = "auto",
|
||||
max_tokens: int = 100,
|
||||
):
|
||||
"""
|
||||
Generate a response based on the given messages using OpenAI.
|
||||
@@ -80,7 +81,7 @@ class OpenAILLM(LLMBase):
|
||||
"model": self.config.model,
|
||||
"messages": messages,
|
||||
"temperature": self.config.temperature,
|
||||
"max_tokens": self.config.max_tokens,
|
||||
"max_tokens": max_tokens,
|
||||
"top_p": self.config.top_p,
|
||||
}
|
||||
|
||||
|
||||
+9
-4
@@ -9,7 +9,7 @@ from typing import Any, Dict
|
||||
|
||||
import pytz
|
||||
from pydantic import ValidationError
|
||||
|
||||
from mem0.memory.utils import parse_vision_messages
|
||||
from mem0.configs.base import MemoryConfig, MemoryItem
|
||||
from mem0.configs.prompts import get_update_memory_messages
|
||||
from mem0.memory.base import MemoryBase
|
||||
@@ -114,6 +114,8 @@ class Memory(MemoryBase):
|
||||
if isinstance(messages, str):
|
||||
messages = [{"role": "user", "content": messages}]
|
||||
|
||||
messages = parse_vision_messages(messages)
|
||||
|
||||
with concurrent.futures.ThreadPoolExecutor() as executor:
|
||||
future1 = executor.submit(self._add_to_vector_store, messages, metadata, filters)
|
||||
future2 = executor.submit(self._add_to_graph, messages, filters)
|
||||
@@ -143,7 +145,7 @@ class Memory(MemoryBase):
|
||||
|
||||
if self.custom_prompt:
|
||||
system_prompt = self.custom_prompt
|
||||
user_prompt = f"Input: {parsed_messages}"
|
||||
user_prompt = f"Input:\n{parsed_messages}"
|
||||
else:
|
||||
system_prompt, user_prompt = get_fact_retrieval_messages(parsed_messages)
|
||||
|
||||
@@ -174,7 +176,10 @@ class Memory(MemoryBase):
|
||||
)
|
||||
for mem in existing_memories:
|
||||
retrieved_old_memory.append({"id": mem.id, "text": mem.payload["data"]})
|
||||
|
||||
unique_data = {}
|
||||
for item in retrieved_old_memory:
|
||||
unique_data[item['id']] = item
|
||||
retrieved_old_memory = list(unique_data.values())
|
||||
logging.info(f"Total existing memories: {len(retrieved_old_memory)}")
|
||||
|
||||
# mapping UUIDs with integers for handling UUID hallucinations
|
||||
@@ -432,7 +437,7 @@ class Memory(MemoryBase):
|
||||
return {"results": original_memories}
|
||||
else:
|
||||
warnings.warn(
|
||||
"The current get_all API output format is deprecated. "
|
||||
"The current search API output format is deprecated. "
|
||||
"To use the latest format, set `api_version='v1.1'`. "
|
||||
"The current format will be removed in mem0ai 1.1.0 and later versions.",
|
||||
category=DeprecationWarning,
|
||||
|
||||
+110
-103
@@ -1,89 +1,93 @@
|
||||
import sqlite3
|
||||
import uuid
|
||||
import threading
|
||||
|
||||
|
||||
class SQLiteManager:
|
||||
def __init__(self, db_path=":memory:"):
|
||||
self.connection = sqlite3.connect(db_path, check_same_thread=False)
|
||||
self._lock = threading.Lock()
|
||||
self._migrate_history_table()
|
||||
self._create_history_table()
|
||||
|
||||
def _migrate_history_table(self):
|
||||
with self.connection:
|
||||
cursor = self.connection.cursor()
|
||||
with self._lock:
|
||||
with self.connection:
|
||||
cursor = self.connection.cursor()
|
||||
|
||||
cursor.execute("SELECT name FROM sqlite_master WHERE type='table' AND name='history'")
|
||||
table_exists = cursor.fetchone() is not None
|
||||
cursor.execute("SELECT name FROM sqlite_master WHERE type='table' AND name='history'")
|
||||
table_exists = cursor.fetchone() is not None
|
||||
|
||||
if table_exists:
|
||||
# Get the current schema of the history table
|
||||
cursor.execute("PRAGMA table_info(history)")
|
||||
current_schema = {row[1]: row[2] for row in cursor.fetchall()}
|
||||
if table_exists:
|
||||
# Get the current schema of the history table
|
||||
cursor.execute("PRAGMA table_info(history)")
|
||||
current_schema = {row[1]: row[2] for row in cursor.fetchall()}
|
||||
|
||||
# Define the expected schema
|
||||
expected_schema = {
|
||||
"id": "TEXT",
|
||||
"memory_id": "TEXT",
|
||||
"old_memory": "TEXT",
|
||||
"new_memory": "TEXT",
|
||||
"new_value": "TEXT",
|
||||
"event": "TEXT",
|
||||
"created_at": "DATETIME",
|
||||
"updated_at": "DATETIME",
|
||||
"is_deleted": "INTEGER",
|
||||
}
|
||||
# Define the expected schema
|
||||
expected_schema = {
|
||||
"id": "TEXT",
|
||||
"memory_id": "TEXT",
|
||||
"old_memory": "TEXT",
|
||||
"new_memory": "TEXT",
|
||||
"new_value": "TEXT",
|
||||
"event": "TEXT",
|
||||
"created_at": "DATETIME",
|
||||
"updated_at": "DATETIME",
|
||||
"is_deleted": "INTEGER",
|
||||
}
|
||||
|
||||
# Check if the schemas are the same
|
||||
if current_schema != expected_schema:
|
||||
# Rename the old table
|
||||
cursor.execute("ALTER TABLE history RENAME TO old_history")
|
||||
# Check if the schemas are the same
|
||||
if current_schema != expected_schema:
|
||||
# Rename the old table
|
||||
cursor.execute("ALTER TABLE history RENAME TO old_history")
|
||||
|
||||
cursor.execute(
|
||||
cursor.execute(
|
||||
"""
|
||||
CREATE TABLE IF NOT EXISTS history (
|
||||
id TEXT PRIMARY KEY,
|
||||
memory_id TEXT,
|
||||
old_memory TEXT,
|
||||
new_memory TEXT,
|
||||
new_value TEXT,
|
||||
event TEXT,
|
||||
created_at DATETIME,
|
||||
updated_at DATETIME,
|
||||
is_deleted INTEGER
|
||||
)
|
||||
"""
|
||||
CREATE TABLE IF NOT EXISTS history (
|
||||
id TEXT PRIMARY KEY,
|
||||
memory_id TEXT,
|
||||
old_memory TEXT,
|
||||
new_memory TEXT,
|
||||
new_value TEXT,
|
||||
event TEXT,
|
||||
created_at DATETIME,
|
||||
updated_at DATETIME,
|
||||
is_deleted INTEGER
|
||||
)
|
||||
"""
|
||||
)
|
||||
|
||||
# Copy data from the old table to the new table
|
||||
cursor.execute(
|
||||
"""
|
||||
INSERT INTO history (id, memory_id, old_memory, new_memory, new_value, event, created_at, updated_at, is_deleted)
|
||||
SELECT id, memory_id, prev_value, new_value, new_value, event, timestamp, timestamp, is_deleted
|
||||
FROM old_history
|
||||
""" # noqa: E501
|
||||
)
|
||||
# Copy data from the old table to the new table
|
||||
cursor.execute(
|
||||
"""
|
||||
INSERT INTO history (id, memory_id, old_memory, new_memory, new_value, event, created_at, updated_at, is_deleted)
|
||||
SELECT id, memory_id, prev_value, new_value, new_value, event, timestamp, timestamp, is_deleted
|
||||
FROM old_history
|
||||
""" # noqa: E501
|
||||
)
|
||||
|
||||
cursor.execute("DROP TABLE old_history")
|
||||
cursor.execute("DROP TABLE old_history")
|
||||
|
||||
self.connection.commit()
|
||||
self.connection.commit()
|
||||
|
||||
def _create_history_table(self):
|
||||
with self.connection:
|
||||
self.connection.execute(
|
||||
with self._lock:
|
||||
with self.connection:
|
||||
self.connection.execute(
|
||||
"""
|
||||
CREATE TABLE IF NOT EXISTS history (
|
||||
id TEXT PRIMARY KEY,
|
||||
memory_id TEXT,
|
||||
old_memory TEXT,
|
||||
new_memory TEXT,
|
||||
new_value TEXT,
|
||||
event TEXT,
|
||||
created_at DATETIME,
|
||||
updated_at DATETIME,
|
||||
is_deleted INTEGER
|
||||
)
|
||||
"""
|
||||
CREATE TABLE IF NOT EXISTS history (
|
||||
id TEXT PRIMARY KEY,
|
||||
memory_id TEXT,
|
||||
old_memory TEXT,
|
||||
new_memory TEXT,
|
||||
new_value TEXT,
|
||||
event TEXT,
|
||||
created_at DATETIME,
|
||||
updated_at DATETIME,
|
||||
is_deleted INTEGER
|
||||
)
|
||||
"""
|
||||
)
|
||||
|
||||
def add_history(
|
||||
self,
|
||||
@@ -95,49 +99,52 @@ class SQLiteManager:
|
||||
updated_at=None,
|
||||
is_deleted=0,
|
||||
):
|
||||
with self.connection:
|
||||
self.connection.execute(
|
||||
"""
|
||||
INSERT INTO history (id, memory_id, old_memory, new_memory, event, created_at, updated_at, is_deleted)
|
||||
VALUES (?, ?, ?, ?, ?, ?, ?, ?)
|
||||
""",
|
||||
(
|
||||
str(uuid.uuid4()),
|
||||
memory_id,
|
||||
old_memory,
|
||||
new_memory,
|
||||
event,
|
||||
created_at,
|
||||
updated_at,
|
||||
is_deleted,
|
||||
),
|
||||
)
|
||||
with self._lock:
|
||||
with self.connection:
|
||||
self.connection.execute(
|
||||
"""
|
||||
INSERT INTO history (id, memory_id, old_memory, new_memory, event, created_at, updated_at, is_deleted)
|
||||
VALUES (?, ?, ?, ?, ?, ?, ?, ?)
|
||||
""",
|
||||
(
|
||||
str(uuid.uuid4()),
|
||||
memory_id,
|
||||
old_memory,
|
||||
new_memory,
|
||||
event,
|
||||
created_at,
|
||||
updated_at,
|
||||
is_deleted,
|
||||
),
|
||||
)
|
||||
|
||||
def get_history(self, memory_id):
|
||||
cursor = self.connection.execute(
|
||||
"""
|
||||
SELECT id, memory_id, old_memory, new_memory, event, created_at, updated_at
|
||||
FROM history
|
||||
WHERE memory_id = ?
|
||||
ORDER BY updated_at ASC
|
||||
""",
|
||||
(memory_id,),
|
||||
)
|
||||
rows = cursor.fetchall()
|
||||
return [
|
||||
{
|
||||
"id": row[0],
|
||||
"memory_id": row[1],
|
||||
"old_memory": row[2],
|
||||
"new_memory": row[3],
|
||||
"event": row[4],
|
||||
"created_at": row[5],
|
||||
"updated_at": row[6],
|
||||
}
|
||||
for row in rows
|
||||
]
|
||||
with self._lock:
|
||||
cursor = self.connection.execute(
|
||||
"""
|
||||
SELECT id, memory_id, old_memory, new_memory, event, created_at, updated_at
|
||||
FROM history
|
||||
WHERE memory_id = ?
|
||||
ORDER BY updated_at ASC
|
||||
""",
|
||||
(memory_id,),
|
||||
)
|
||||
rows = cursor.fetchall()
|
||||
return [
|
||||
{
|
||||
"id": row[0],
|
||||
"memory_id": row[1],
|
||||
"old_memory": row[2],
|
||||
"new_memory": row[3],
|
||||
"event": row[4],
|
||||
"created_at": row[5],
|
||||
"updated_at": row[6],
|
||||
}
|
||||
for row in rows
|
||||
]
|
||||
|
||||
def reset(self):
|
||||
with self.connection:
|
||||
self.connection.execute("DROP TABLE IF EXISTS history")
|
||||
self._create_history_table()
|
||||
with self._lock:
|
||||
with self.connection:
|
||||
self.connection.execute("DROP TABLE IF EXISTS history")
|
||||
self._create_history_table()
|
||||
|
||||
+44
-2
@@ -1,10 +1,10 @@
|
||||
import re
|
||||
|
||||
from mem0.configs.prompts import FACT_RETRIEVAL_PROMPT
|
||||
from mem0.llms.openai import OpenAILLM
|
||||
|
||||
|
||||
def get_fact_retrieval_messages(message):
|
||||
return FACT_RETRIEVAL_PROMPT, f"Input: {message}"
|
||||
return FACT_RETRIEVAL_PROMPT, f"Input:\n{message}"
|
||||
|
||||
|
||||
def parse_messages(messages):
|
||||
@@ -43,3 +43,45 @@ def remove_code_blocks(content: str) -> str:
|
||||
pattern = r"^```[a-zA-Z0-9]*\n([\s\S]*?)\n```$"
|
||||
match = re.match(pattern, content.strip())
|
||||
return match.group(1).strip() if match else content.strip()
|
||||
|
||||
|
||||
def get_image_description(image_url):
|
||||
"""
|
||||
Get the description of the image
|
||||
"""
|
||||
llm = OpenAILLM()
|
||||
response = llm.generate_response(
|
||||
messages=[
|
||||
{
|
||||
"role": "user",
|
||||
"content": [
|
||||
{"type": "text", "text": "Provide a description of the image and do not include any additional text."},
|
||||
{"type": "image_url", "image_url": {"url": image_url}}
|
||||
],
|
||||
},
|
||||
],
|
||||
max_tokens=100,
|
||||
)
|
||||
return response
|
||||
|
||||
|
||||
def parse_vision_messages(messages):
|
||||
"""
|
||||
Parse the vision messages from the messages
|
||||
"""
|
||||
returned_messages = []
|
||||
for msg in messages:
|
||||
if msg["role"] != "system":
|
||||
if not isinstance(msg["content"], str) and msg["content"]["type"] == "image_url":
|
||||
image_url = msg["content"]["image_url"]["url"]
|
||||
try:
|
||||
description = get_image_description(image_url)
|
||||
msg["content"]["text"] = description
|
||||
returned_messages.append({"role": msg["role"], "content": description})
|
||||
except Exception:
|
||||
raise Exception(f"Error while downloading {image_url}.")
|
||||
else:
|
||||
returned_messages.append(msg)
|
||||
else:
|
||||
returned_messages.append(msg)
|
||||
return returned_messages
|
||||
|
||||
@@ -68,6 +68,7 @@ class VectorStoreFactory:
|
||||
"azure_ai_search": "mem0.vector_stores.azure_ai_search.AzureAISearch",
|
||||
"redis": "mem0.vector_stores.redis.RedisDB",
|
||||
"elasticsearch": "mem0.vector_stores.elasticsearch.ElasticsearchDB",
|
||||
"opensearch": "mem0.vector_stores.opensearch.OpenSearchDB"
|
||||
}
|
||||
|
||||
@classmethod
|
||||
|
||||
@@ -76,6 +76,9 @@ class AzureAISearch(VectorStoreBase):
|
||||
|
||||
fields = [
|
||||
SimpleField(name="id", type=SearchFieldDataType.String, key=True),
|
||||
SimpleField(name="user_id", type=SearchFieldDataType.String, filterable=True),
|
||||
SimpleField(name="run_id", type=SearchFieldDataType.String, filterable=True),
|
||||
SimpleField(name="agent_id", type=SearchFieldDataType.String, filterable=True),
|
||||
SearchField(
|
||||
name="vector",
|
||||
type=vector_type,
|
||||
@@ -96,6 +99,14 @@ class AzureAISearch(VectorStoreBase):
|
||||
index = SearchIndex(name=self.index_name, fields=fields, vector_search=vector_search)
|
||||
self.index_client.create_or_update_index(index)
|
||||
|
||||
def _generate_document(self, vector, payload, id):
|
||||
document = {"id": id, "vector": vector, "payload": json.dumps(payload)}
|
||||
# Extract additional fields if they exist
|
||||
for field in ["user_id", "run_id", "agent_id"]:
|
||||
if field in payload:
|
||||
document[field] = payload[field]
|
||||
return document
|
||||
|
||||
def insert(self, vectors, payloads=None, ids=None):
|
||||
"""Insert vectors into the index.
|
||||
|
||||
@@ -105,12 +116,26 @@ class AzureAISearch(VectorStoreBase):
|
||||
ids (List[str], optional): List of IDs corresponding to vectors.
|
||||
"""
|
||||
logger.info(f"Inserting {len(vectors)} vectors into index {self.index_name}")
|
||||
|
||||
documents = [
|
||||
{"id": id, "vector": vector, "payload": json.dumps(payload)}
|
||||
self._generate_document(vector, payload, id)
|
||||
for id, vector, payload in zip(ids, vectors, payloads)
|
||||
]
|
||||
self.search_client.upload_documents(documents)
|
||||
|
||||
def _build_filter_expression(self, filters):
|
||||
filter_conditions = []
|
||||
for key, value in filters.items():
|
||||
# If the value is a string, add quotes
|
||||
if isinstance(value, str):
|
||||
condition = f"{key} eq '{value}'"
|
||||
else:
|
||||
condition = f"{key} eq {value}"
|
||||
filter_conditions.append(condition)
|
||||
# Use 'and' to join multiple conditions
|
||||
filter_expression = ' and '.join(filter_conditions)
|
||||
return filter_expression
|
||||
|
||||
def search(self, query, limit=5, filters=None):
|
||||
"""Search for similar vectors.
|
||||
|
||||
@@ -122,17 +147,23 @@ class AzureAISearch(VectorStoreBase):
|
||||
Returns:
|
||||
list: Search results.
|
||||
"""
|
||||
# Build filter expression
|
||||
filter_expression = None
|
||||
if filters:
|
||||
filter_expression = self._build_filter_expression(filters)
|
||||
|
||||
vector_query = VectorizedQuery(vector=query, k_nearest_neighbors=limit, fields="vector")
|
||||
search_results = self.search_client.search(vector_queries=[vector_query], top=limit)
|
||||
vector_query = VectorizedQuery(
|
||||
vector=query, k_nearest_neighbors=limit, fields="vector"
|
||||
)
|
||||
search_results = self.search_client.search(
|
||||
vector_queries=[vector_query],
|
||||
filter=filter_expression,
|
||||
top=limit
|
||||
)
|
||||
|
||||
results = []
|
||||
for result in search_results:
|
||||
payload = json.loads(result["payload"])
|
||||
if filters:
|
||||
for key, value in filters.items():
|
||||
if key not in payload or payload[key] != value:
|
||||
continue
|
||||
results.append(OutputData(id=result["id"], score=result["@search.score"], payload=payload))
|
||||
return results
|
||||
|
||||
@@ -143,6 +174,7 @@ class AzureAISearch(VectorStoreBase):
|
||||
vector_id (str): ID of the vector to delete.
|
||||
"""
|
||||
self.search_client.delete_documents(documents=[{"id": vector_id}])
|
||||
logger.info(f"Deleted document with ID '{vector_id}' from index '{self.index_name}'.")
|
||||
|
||||
def update(self, vector_id, vector=None, payload=None):
|
||||
"""Update a vector and its payload.
|
||||
@@ -156,7 +188,10 @@ class AzureAISearch(VectorStoreBase):
|
||||
if vector:
|
||||
document["vector"] = vector
|
||||
if payload:
|
||||
document["payload"] = json.dumps(payload)
|
||||
json_payload = json.dumps(payload)
|
||||
document["payload"] = json_payload
|
||||
for field in ["user_id", "run_id", "agent_id"]:
|
||||
document[field] = payload.get(field)
|
||||
self.search_client.merge_or_upload_documents(documents=[document])
|
||||
|
||||
def get(self, vector_id) -> OutputData:
|
||||
@@ -206,18 +241,19 @@ class AzureAISearch(VectorStoreBase):
|
||||
Returns:
|
||||
List[OutputData]: List of vectors.
|
||||
"""
|
||||
search_results = self.search_client.search(search_text="*", top=limit)
|
||||
filter_expression = None
|
||||
if filters:
|
||||
filter_expression = self._build_filter_expression(filters)
|
||||
|
||||
search_results = self.search_client.search(
|
||||
search_text="*",
|
||||
filter=filter_expression,
|
||||
top=limit
|
||||
)
|
||||
results = []
|
||||
for result in search_results:
|
||||
payload = json.loads(result["payload"])
|
||||
include_result = True
|
||||
if filters:
|
||||
for key, value in filters.items():
|
||||
if (key not in payload) or (payload[key] != filters[key]):
|
||||
include_result = False
|
||||
break
|
||||
if include_result:
|
||||
results.append(OutputData(id=result["id"], score=result["@search.score"], payload=payload))
|
||||
results.append(OutputData(id=result["id"], score=result["@search.score"], payload=payload))
|
||||
|
||||
return [results]
|
||||
|
||||
|
||||
@@ -18,6 +18,7 @@ class VectorStoreConfig(BaseModel):
|
||||
"azure_ai_search": "AzureAISearchConfig",
|
||||
"redis": "RedisDBConfig",
|
||||
"elasticsearch": "ElasticsearchConfig",
|
||||
"opensearch": "OpenSearchConfig",
|
||||
}
|
||||
|
||||
@model_validator(mode="after")
|
||||
|
||||
@@ -0,0 +1,189 @@
|
||||
import logging
|
||||
from typing import Any, Dict, List, Optional
|
||||
|
||||
try:
|
||||
from opensearchpy import OpenSearch
|
||||
from opensearchpy.helpers import bulk
|
||||
except ImportError:
|
||||
raise ImportError("OpenSearch requires extra dependencies. Install with `pip install opensearch-py`") from None
|
||||
|
||||
from pydantic import BaseModel
|
||||
|
||||
from mem0.configs.vector_stores.opensearch import OpenSearchConfig
|
||||
from mem0.vector_stores.base import VectorStoreBase
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
|
||||
class OutputData(BaseModel):
|
||||
id: str
|
||||
score: float
|
||||
payload: Dict
|
||||
|
||||
|
||||
class OpenSearchDB(VectorStoreBase):
|
||||
def __init__(self, **kwargs):
|
||||
config = OpenSearchConfig(**kwargs)
|
||||
|
||||
# Initialize OpenSearch client
|
||||
self.client = OpenSearch(
|
||||
hosts=[{"host": config.host, "port": config.port or 9200}],
|
||||
http_auth=(config.user, config.password) if (config.user and config.password) else None,
|
||||
use_ssl=config.use_ssl,
|
||||
verify_certs=config.verify_certs,
|
||||
)
|
||||
|
||||
self.collection_name = config.collection_name
|
||||
self.vector_dim = config.embedding_model_dims
|
||||
|
||||
# Create index only if auto_create_index is True
|
||||
if config.auto_create_index:
|
||||
self.create_index()
|
||||
|
||||
def create_index(self) -> None:
|
||||
"""Create OpenSearch index with proper mappings if it doesn't exist."""
|
||||
index_settings = {
|
||||
# ToDo change replicas to 1
|
||||
"settings": {
|
||||
"index": {"number_of_replicas": 1, "number_of_shards": 5, "refresh_interval": "1s", "knn": True}
|
||||
},
|
||||
"mappings": {
|
||||
"properties": {
|
||||
"text": {"type": "text"},
|
||||
"vector": {
|
||||
"type": "knn_vector",
|
||||
"dimension": self.vector_dim
|
||||
},
|
||||
"metadata": {"type": "object", "properties": {"user_id": {"type": "keyword"}}},
|
||||
}
|
||||
},
|
||||
}
|
||||
|
||||
if not self.client.indices.exists(index=self.collection_name):
|
||||
self.client.indices.create(index=self.collection_name, body=index_settings)
|
||||
logger.info(f"Created index {self.collection_name}")
|
||||
else:
|
||||
logger.info(f"Index {self.collection_name} already exists")
|
||||
|
||||
def create_col(self, name: str, vector_size: int) -> None:
|
||||
"""Create a new collection (index in OpenSearch)."""
|
||||
index_settings = {
|
||||
"mappings": {
|
||||
"properties": {
|
||||
"vector": {
|
||||
"type": "knn_vector",
|
||||
"dimension": vector_size,
|
||||
"method": { "engine": "lucene", "name": "hnsw", "space_type": "cosinesimil"},
|
||||
},
|
||||
"payload": {"type": "object"},
|
||||
"id": {"type": "keyword"},
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if not self.client.indices.exists(index=name):
|
||||
self.client.indices.create(index=name, body=index_settings)
|
||||
logger.info(f"Created index {name}")
|
||||
|
||||
def insert(
|
||||
self, vectors: List[List[float]], payloads: Optional[List[Dict]] = None, ids: Optional[List[str]] = None
|
||||
) -> List[OutputData]:
|
||||
"""Insert vectors into the index."""
|
||||
if not ids:
|
||||
ids = [str(i) for i in range(len(vectors))]
|
||||
|
||||
if payloads is None:
|
||||
payloads = [{} for _ in range(len(vectors))]
|
||||
|
||||
actions = []
|
||||
for i, (vec, id_) in enumerate(zip(vectors, ids)):
|
||||
action = {
|
||||
"_index": self.collection_name,
|
||||
"_id": id_,
|
||||
"_source": {
|
||||
"vector": vec,
|
||||
"metadata": payloads[i], # Store metadata in the metadata field
|
||||
},
|
||||
}
|
||||
actions.append(action)
|
||||
|
||||
bulk(self.client, actions)
|
||||
|
||||
results = []
|
||||
for i, id_ in enumerate(ids):
|
||||
results.append(OutputData(id=id_, score=1.0, payload=payloads[i]))
|
||||
return results
|
||||
|
||||
def search(self, query: List[float], limit: int = 5, filters: Optional[Dict] = None) -> List[OutputData]:
|
||||
"""Search for similar vectors using OpenSearch k-NN search with pre-filtering."""
|
||||
search_query = {
|
||||
"size": limit,
|
||||
"query": {
|
||||
"knn": {
|
||||
"vector": {
|
||||
"vector": query,
|
||||
"k": limit,
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if filters:
|
||||
filter_conditions = [{"term": {f"metadata.{key}": value}} for key, value in filters.items()]
|
||||
search_query["query"]["knn"]["vector"]["filter"] = { "bool": {"filter": filter_conditions} }
|
||||
|
||||
response = self.client.search(index=self.collection_name, body=search_query)
|
||||
|
||||
results = [
|
||||
OutputData(id=hit["_id"], score=hit["_score"], payload=hit["_source"].get("metadata", {}))
|
||||
for hit in response["hits"]["hits"]
|
||||
]
|
||||
return results
|
||||
|
||||
def delete(self, vector_id: str) -> None:
|
||||
"""Delete a vector by ID."""
|
||||
self.client.delete(index=self.collection_name, id=vector_id)
|
||||
|
||||
def update(self, vector_id: str, vector: Optional[List[float]] = None, payload: Optional[Dict] = None) -> None:
|
||||
"""Update a vector and its payload."""
|
||||
doc = {}
|
||||
if vector is not None:
|
||||
doc["vector"] = vector
|
||||
if payload is not None:
|
||||
doc["metadata"] = payload
|
||||
|
||||
self.client.update(index=self.collection_name, id=vector_id, body={"doc": doc})
|
||||
|
||||
def get(self, vector_id: str) -> Optional[OutputData]:
|
||||
"""Retrieve a vector by ID."""
|
||||
try:
|
||||
response = self.client.get(index=self.collection_name, id=vector_id)
|
||||
return OutputData(id=response["_id"], score=1.0, payload=response["_source"].get("metadata", {}))
|
||||
except Exception as e:
|
||||
logger.error(f"Error retrieving vector {vector_id}: {e}")
|
||||
return None
|
||||
|
||||
def list_cols(self) -> List[str]:
|
||||
"""List all collections (indices)."""
|
||||
return list(self.client.indices.get_alias().keys())
|
||||
|
||||
def delete_col(self) -> None:
|
||||
"""Delete a collection (index)."""
|
||||
self.client.indices.delete(index=self.collection_name)
|
||||
|
||||
def col_info(self, name: str) -> Any:
|
||||
"""Get information about a collection (index)."""
|
||||
return self.client.indices.get(index=name)
|
||||
|
||||
def list(self, filters: Optional[Dict] = None, limit: Optional[int] = None) -> List[List[OutputData]]:
|
||||
"""List all memories."""
|
||||
query = {"query": {"match_all": {}}}
|
||||
|
||||
if filters:
|
||||
query["query"] = {"bool": {"must": [{"term": {f"metadata.{key}": value}} for key, value in filters.items()]}}
|
||||
|
||||
if limit:
|
||||
query["size"] = limit
|
||||
|
||||
response = self.client.search(index=self.collection_name, body=query)
|
||||
return [[OutputData(id=hit["_id"], score=1.0, payload=hit["_source"].get("metadata", {})) for hit in response["hits"]["hits"]]]
|
||||
Generated
+649
-419
File diff suppressed because it is too large
Load Diff
+1
-1
@@ -1,6 +1,6 @@
|
||||
[tool.poetry]
|
||||
name = "mem0ai"
|
||||
version = "0.1.48"
|
||||
version = "0.1.53"
|
||||
description = "Long-term memory for AI Agents"
|
||||
authors = ["Mem0 <founders@mem0.ai>"]
|
||||
exclude = [
|
||||
|
||||
@@ -97,8 +97,8 @@ def test_generate_response_with_tools(mock_openai_client):
|
||||
[None, {"Firstkey": "FirstVal", "SecondKey": "SecondVal"}],
|
||||
)
|
||||
def test_generate_with_http_proxies(default_headers):
|
||||
mock_http_client = Mock(spec=httpx.Client)
|
||||
mock_http_client_instance = Mock(spec=httpx.Client)
|
||||
mock_http_client = Mock()
|
||||
mock_http_client_instance = Mock()
|
||||
mock_http_client.return_value = mock_http_client_instance
|
||||
azure_kwargs = {"api_key": "test"}
|
||||
if default_headers:
|
||||
@@ -106,7 +106,7 @@ def test_generate_with_http_proxies(default_headers):
|
||||
|
||||
with (
|
||||
patch("mem0.llms.azure_openai.AzureOpenAI") as mock_azure_openai,
|
||||
patch("httpx.Client", new=mock_http_client) as mock_http_client,
|
||||
patch("httpx.Client", new=mock_http_client),
|
||||
):
|
||||
config = BaseLlmConfig(
|
||||
model=MODEL,
|
||||
|
||||
@@ -0,0 +1,150 @@
|
||||
import os
|
||||
import unittest
|
||||
from unittest.mock import MagicMock, patch
|
||||
|
||||
import dotenv
|
||||
|
||||
try:
|
||||
from opensearchpy import OpenSearch
|
||||
except ImportError:
|
||||
raise ImportError(
|
||||
"OpenSearch requires extra dependencies. Install with `pip install opensearch-py`"
|
||||
) from None
|
||||
|
||||
from mem0.vector_stores.opensearch import OpenSearchDB
|
||||
|
||||
|
||||
class TestOpenSearchDB(unittest.TestCase):
|
||||
@classmethod
|
||||
def setUpClass(cls):
|
||||
dotenv.load_dotenv()
|
||||
cls.original_env = {
|
||||
'OS_URL': os.getenv('OS_URL', 'http://localhost:9200'),
|
||||
'OS_USERNAME': os.getenv('OS_USERNAME', 'test_user'),
|
||||
'OS_PASSWORD': os.getenv('OS_PASSWORD', 'test_password')
|
||||
}
|
||||
os.environ['OS_URL'] = 'http://localhost'
|
||||
os.environ['OS_USERNAME'] = 'test_user'
|
||||
os.environ['OS_PASSWORD'] = 'test_password'
|
||||
|
||||
def setUp(self):
|
||||
self.client_mock = MagicMock(spec=OpenSearch)
|
||||
self.client_mock.indices = MagicMock()
|
||||
self.client_mock.indices.exists = MagicMock(return_value=False)
|
||||
self.client_mock.indices.create = MagicMock()
|
||||
self.client_mock.indices.delete = MagicMock()
|
||||
self.client_mock.indices.get_alias = MagicMock()
|
||||
self.client_mock.get = MagicMock()
|
||||
self.client_mock.update = MagicMock()
|
||||
self.client_mock.delete = MagicMock()
|
||||
self.client_mock.search = MagicMock()
|
||||
|
||||
patcher = patch('mem0.vector_stores.opensearch.OpenSearch', return_value=self.client_mock)
|
||||
self.mock_os = patcher.start()
|
||||
self.addCleanup(patcher.stop)
|
||||
|
||||
self.os_db = OpenSearchDB(
|
||||
host=os.getenv('OS_URL'),
|
||||
port=9200,
|
||||
collection_name="test_collection",
|
||||
embedding_model_dims=1536,
|
||||
user=os.getenv('OS_USERNAME'),
|
||||
password=os.getenv('OS_PASSWORD'),
|
||||
verify_certs=False,
|
||||
use_ssl=False,
|
||||
auto_create_index=False
|
||||
)
|
||||
self.client_mock.reset_mock()
|
||||
|
||||
@classmethod
|
||||
def tearDownClass(cls):
|
||||
for key, value in cls.original_env.items():
|
||||
if value is not None:
|
||||
os.environ[key] = value
|
||||
else:
|
||||
os.environ.pop(key, None)
|
||||
|
||||
def tearDown(self):
|
||||
self.client_mock.reset_mock()
|
||||
|
||||
def test_create_index(self):
|
||||
self.client_mock.indices.exists.return_value = False
|
||||
self.os_db.create_index()
|
||||
self.client_mock.indices.create.assert_called_once()
|
||||
create_args = self.client_mock.indices.create.call_args[1]
|
||||
self.assertEqual(create_args["index"], "test_collection")
|
||||
mappings = create_args["body"]["mappings"]["properties"]
|
||||
self.assertEqual(mappings["vector"]["type"], "knn_vector")
|
||||
self.assertEqual(mappings["vector"]["dimension"], 1536)
|
||||
self.client_mock.reset_mock()
|
||||
self.client_mock.indices.exists.return_value = True
|
||||
self.os_db.create_index()
|
||||
self.client_mock.indices.create.assert_not_called()
|
||||
|
||||
def test_insert(self):
|
||||
vectors = [[0.1] * 1536, [0.2] * 1536]
|
||||
payloads = [{"key1": "value1"}, {"key2": "value2"}]
|
||||
ids = ["id1", "id2"]
|
||||
with patch('mem0.vector_stores.opensearch.bulk') as mock_bulk:
|
||||
mock_bulk.return_value = (2, [])
|
||||
results = self.os_db.insert(vectors=vectors, payloads=payloads, ids=ids)
|
||||
mock_bulk.assert_called_once()
|
||||
actions = mock_bulk.call_args[0][1]
|
||||
self.assertEqual(actions[0]["_index"], "test_collection")
|
||||
self.assertEqual(actions[0]["_id"], "id1")
|
||||
self.assertEqual(actions[0]["_source"]["vector"], vectors[0])
|
||||
self.assertEqual(actions[0]["_source"]["metadata"], payloads[0])
|
||||
self.assertEqual(len(results), 2)
|
||||
self.assertEqual(results[0].id, "id1")
|
||||
self.assertEqual(results[0].payload, payloads[0])
|
||||
|
||||
def test_get(self):
|
||||
mock_response = {"_id": "id1", "_source": {"metadata": {"key1": "value1"}}}
|
||||
self.client_mock.get.return_value = mock_response
|
||||
result = self.os_db.get("id1")
|
||||
self.client_mock.get.assert_called_once_with(index="test_collection", id="id1")
|
||||
self.assertIsNotNone(result)
|
||||
self.assertEqual(result.id, "id1")
|
||||
self.assertEqual(result.payload, {"key1": "value1"})
|
||||
|
||||
def test_update(self):
|
||||
vector = [0.3] * 1536
|
||||
payload = {"key3": "value3"}
|
||||
self.os_db.update("id1", vector=vector, payload=payload)
|
||||
self.client_mock.update.assert_called_once()
|
||||
update_args = self.client_mock.update.call_args[1]
|
||||
self.assertEqual(update_args["index"], "test_collection")
|
||||
self.assertEqual(update_args["id"], "id1")
|
||||
self.assertEqual(update_args["body"], {"doc": {"vector": vector, "metadata": payload}})
|
||||
|
||||
def test_list_cols(self):
|
||||
self.client_mock.indices.get_alias.return_value = {"test_collection": {}}
|
||||
result = self.os_db.list_cols()
|
||||
self.client_mock.indices.get_alias.assert_called_once()
|
||||
self.assertEqual(result, ["test_collection"])
|
||||
|
||||
def test_search(self):
|
||||
mock_response = {"hits": {"hits": [{"_id": "id1", "_score": 0.8, "_source": {"vector": [0.1] * 1536, "metadata": {"key1": "value1"}}}]}}
|
||||
self.client_mock.search.return_value = mock_response
|
||||
query_vector = [0.1] * 1536
|
||||
results = self.os_db.search(query=query_vector, limit=5)
|
||||
self.client_mock.search.assert_called_once()
|
||||
search_args = self.client_mock.search.call_args[1]
|
||||
self.assertEqual(search_args["index"], "test_collection")
|
||||
body = search_args["body"]
|
||||
self.assertIn("knn", body["query"])
|
||||
self.assertIn("vector", body["query"]["knn"])
|
||||
self.assertEqual(body["query"]["knn"]["vector"]["vector"], query_vector)
|
||||
self.assertEqual(body["query"]["knn"]["vector"]["k"], 5)
|
||||
self.assertEqual(len(results), 1)
|
||||
self.assertEqual(results[0].id, "id1")
|
||||
self.assertEqual(results[0].score, 0.8)
|
||||
self.assertEqual(results[0].payload, {"key1": "value1"})
|
||||
|
||||
def test_delete(self):
|
||||
self.os_db.delete(vector_id="id1")
|
||||
self.client_mock.delete.assert_called_once_with(index="test_collection", id="id1")
|
||||
|
||||
def test_delete_col(self):
|
||||
self.os_db.delete_col()
|
||||
self.client_mock.indices.delete.assert_called_once_with(index="test_collection")
|
||||
Reference in New Issue
Block a user