Compare commits
293 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| 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 | |||
| 203943919b | |||
| 04bbad67ac | |||
| e1b527b73f | |||
| 625846caf8 | |||
| c1bd4e19fe | |||
| 8d172d6139 | |||
| a5355f7488 | |||
| f13f3b9283 | |||
| 56351d1f8d | |||
| a9d1383909 | |||
| 80c9c6a577 | |||
| e4e5511642 | |||
| a4b085553a | |||
| e12273c7cb | |||
| ee2b5adfc0 | |||
| 205a03a5f2 | |||
| 7be029a26f | |||
| 0bd177b30c | |||
| 82359774b7 | |||
| 3fa4b80deb | |||
| e96fd5d269 | |||
| 927644d712 | |||
| 7397279872 | |||
| 6851fac327 | |||
| 254524a624 | |||
| 7f0d766c09 | |||
| ac8cf59473 | |||
| 9c4acdcba7 | |||
| a6b9721ede | |||
| a8f3ec25b7 | |||
| 21854c6a24 | |||
| 09bf7ad916 | |||
| 0cc528f3b1 | |||
| cbd845fe41 | |||
| 2e782b0963 | |||
| 4c31c65649 | |||
| c90f87e657 | |||
| c63c0aca9d | |||
| d4dbed9dbd | |||
| e9188a51fe | |||
| d893033dcf | |||
| 78a2ef41d7 | |||
| 542153ad4f | |||
| 49802137fa | |||
| 0091b31762 | |||
| 339a990510 | |||
| 4c2a903618 | |||
| 8851969169 | |||
| 3a5e5851dd | |||
| 716824860b | |||
| 64c80e3fbc | |||
| 9032e68917 | |||
| e7da9eb00c | |||
| 6b99457381 | |||
| be4188c6b4 | |||
| 4d08c16bd8 | |||
| 763f804277 | |||
| 400b1f4eac | |||
| 6bc86d7d2c | |||
| df68a6b397 | |||
| b739cbbc2e | |||
| f645e50c5c | |||
| 2eff703e72 | |||
| dd06333732 | |||
| 847e1cc986 | |||
| af29ecc93f | |||
| 52eaddbd8a | |||
| 06d1757038 | |||
| 9900b4f5e4 | |||
| 25ef5dda53 | |||
| 2e1d257f36 | |||
| 4b34751bda | |||
| ba9c2e68f9 | |||
| 86d3e36ace | |||
| 7284317cef | |||
| 1508a5a418 | |||
| 9b55b717e0 | |||
| 8c087fcabc | |||
| 4b8e32830a | |||
| 62ca0ddbe2 | |||
| bcb41f85c9 | |||
| 751f5d5a19 | |||
| 5ab09ffd5a | |||
| 13374a12e9 | |||
| a02597ed59 | |||
| 8a56f0ed4a | |||
| fd7fab4e08 | |||
| e909e3e76c | |||
| 1ebe5b643d | |||
| c0b9a10224 | |||
| 802231c105 | |||
| 0d5085454b | |||
| 6d535951df | |||
| eaf295756e | |||
| 11894c64b3 | |||
| b9e22beecb | |||
| 6f051036d9 | |||
| 3731965537 | |||
| 549e5e3ce8 | |||
| 48bbfcbb2c | |||
| 4cc91d7505 | |||
| 77b0912808 | |||
| 6a00643bfa | |||
| 2e74667cc6 | |||
| d2b653ab10 | |||
| 2c94e6b817 | |||
| a6ac4a6698 | |||
| e7cc8b9552 | |||
| f6290a0e48 | |||
| 6668be3d5b | |||
| cf12148bc7 | |||
| d928ea4a2b | |||
| efd45c0c4d | |||
| 4896d5c66f | |||
| 61a24f011a | |||
| 8d9eb225a8 | |||
| 605558da9d | |||
| dca74a1ec0 | |||
| fb3eef6cf5 | |||
| 10d3209e5a | |||
| aace88d2e7 | |||
| 228eaa16d5 | |||
| f3416aa46a | |||
| eb32fb912d | |||
| 8c4ee7569f | |||
| fbf1d8c372 | |||
| c5d298eec8 | |||
| 078aa66b90 | |||
| d4ffed9822 | |||
| ff7761aaf8 | |||
| f058cda152 | |||
| b6f9054567 | |||
| 5667bc1eab | |||
| 4661d55913 | |||
| 9c52d72dc1 | |||
| 2cd9f94ea6 | |||
| 2b262a65b2 | |||
| bd5ce7c6d2 | |||
| 20c3aee636 | |||
| 721d765921 | |||
| 84eb666618 | |||
| 3f2d5bee34 | |||
| 9341d9f597 | |||
| aacc7c25d3 | |||
| b59fbb0bd2 | |||
| ae7b1a666e | |||
| bf57d253a5 | |||
| c689f94c52 | |||
| ab862d0d40 | |||
| 29178a4c72 | |||
| d107b639b3 | |||
| c09c4926a7 | |||
| 395af18d88 | |||
| ecefb793fc | |||
| c6b9035956 | |||
| 3513a9def6 | |||
| 0d45c61aa3 | |||
| f324462cc3 | |||
| 52bd8fca5c | |||
| c45f14e77d | |||
| 0dbfcbe6d9 | |||
| 23279d4248 | |||
| 68c7355f47 | |||
| aaf8e6e7ff | |||
| 699741c760 | |||
| 2d3dda3a4c | |||
| 61dd5a5ea4 | |||
| 41be228e5c | |||
| 0491854298 | |||
| 44ee48e924 | |||
| 5525c4e6fe | |||
| 3914f4d6ac | |||
| 8511eca03b | |||
| 56ceecb4e3 | |||
| db5cb1986a | |||
| 6102aa76bb | |||
| fc88cae628 | |||
| 8c3c9e1520 | |||
| 55c54beeab | |||
| 0a78cb9f7a | |||
| 3502344e89 | |||
| 30edf49aaf | |||
| 5b9be679a8 | |||
| 8e2f7f2bfb | |||
| dc5a26fe95 | |||
| d66654bf67 | |||
| 959f4bb059 | |||
| f9634b4bf3 | |||
| 47a8e677e9 | |||
| f40a2e7603 | |||
| ac7b7aa20a | |||
| 5eeeb4e38c | |||
| db835cdcb8 | |||
| e3aca7026b | |||
| 3bd49b57cc | |||
| 5b9b65c395 | |||
| bbddb98aca | |||
| b081e43b8d | |||
| 58f29d8781 | |||
| f01e8a083e | |||
| 7170edd13f | |||
| bf0cf2d9c4 | |||
| 51c4f2aae8 | |||
| a972d2fb07 | |||
| 6a54d27286 | |||
| d32ae1a0b1 | |||
| 965f7a3735 | |||
| 136b5545ec | |||
| 8099d60e0e | |||
| da2fd1a51a | |||
| 18d069d10c | |||
| 851b665c11 | |||
| c674625e88 | |||
| 23e2ed2163 | |||
| 0b1ca090f5 | |||
| bf3ad37369 | |||
| f21ca9b765 | |||
| d113037a4f | |||
| b2f683f3cc | |||
| 83eb800fb3 | |||
| af8454811c | |||
| 8dbfe28bbb | |||
| 5d53b0c2ca | |||
| 65056311a6 | |||
| d03ba0fc8a | |||
| 9804f078d0 | |||
| c886764b62 | |||
| 2262fadd5b | |||
| 462aaebd6c | |||
| 077d0c47f9 | |||
| ad233034ef | |||
| 9d0932971d | |||
| 822a8acedb | |||
| 28bc4fe05b | |||
| df5b7109f5 | |||
| 4bbbc904b6 | |||
| fee3c27af3 | |||
| deeb4f2250 | |||
| a80796b5ff | |||
| a279ed0694 | |||
| 06d6fe7d76 | |||
| 6057cf5202 | |||
| a94bd11a76 | |||
| e8004537c1 | |||
| c8a47b2f98 | |||
| c545dcf412 | |||
| b80925e857 | |||
| 3fb4f2655b | |||
| 324e17b226 | |||
| b3d6e645b7 | |||
| cb2f86551b | |||
| 4f5a40a84f | |||
| ea86dc1576 | |||
| 7de35b4a68 | |||
| 2d66c23116 | |||
| 515fb86497 | |||
| 8ea12ca24b | |||
| 448a21f617 | |||
| a7f5fb59c3 | |||
| c64e0824da | |||
| 9b7a882d57 | |||
| e3a3a48973 | |||
| 6a9f5341b5 | |||
| e31ca239a0 | |||
| 0e0d0b8fc7 |
+2
-1
@@ -103,7 +103,7 @@ ipython_config.py
|
||||
# pdm
|
||||
# Similar to Pipfile.lock, it is generally recommended to include pdm.lock in version control.
|
||||
#pdm.lock
|
||||
# pdm stores project-wide configurations in .pdm.toml, but it is recommended to not include it
|
||||
# pdm stores project-wide configurations in .pdm.toml, but it is recommended not to include it
|
||||
# in version control.
|
||||
# https://pdm.fming.dev/#use-with-ide
|
||||
.pdm.toml
|
||||
@@ -184,3 +184,4 @@ notebooks/*.yaml
|
||||
eval/
|
||||
qdrant_storage/
|
||||
.crossnote
|
||||
testing.ipynb
|
||||
|
||||
@@ -0,0 +1,16 @@
|
||||
repos:
|
||||
- repo: local
|
||||
hooks:
|
||||
- id: ruff
|
||||
name: Ruff
|
||||
entry: ruff check
|
||||
language: system
|
||||
types: [python]
|
||||
args: [--fix]
|
||||
|
||||
- id: isort
|
||||
name: isort
|
||||
entry: isort
|
||||
language: system
|
||||
types: [python]
|
||||
args: ["--profile", "black"]
|
||||
@@ -0,0 +1,55 @@
|
||||
# Contributing to mem0
|
||||
|
||||
Let us make contribution easy, collaborative and fun.
|
||||
|
||||
## Submit your Contribution through PR
|
||||
|
||||
To make a contribution, follow these steps:
|
||||
|
||||
1. Fork and clone this repository
|
||||
2. Do the changes on your fork with dedicated feature branch `feature/f1`
|
||||
3. If you modified the code (new feature or bug-fix), please add tests for it
|
||||
4. Include proper documentation / docstring and examples to run the feature
|
||||
5. Ensure that all tests pass
|
||||
6. Submit a pull request
|
||||
|
||||
For more details about pull requests, please read [GitHub's guides](https://docs.github.com/en/pull-requests/collaborating-with-pull-requests/proposing-changes-to-your-work-with-pull-requests/creating-a-pull-request).
|
||||
|
||||
|
||||
### 📦 Package manager
|
||||
|
||||
We use `poetry` as our package manager. You can install poetry by following the instructions [here](https://python-poetry.org/docs/#installation).
|
||||
|
||||
Please DO NOT use pip or conda to install the dependencies. Instead, use poetry:
|
||||
|
||||
```bash
|
||||
make install_all
|
||||
|
||||
#activate
|
||||
|
||||
poetry shell
|
||||
```
|
||||
|
||||
### 📌 Pre-commit
|
||||
|
||||
To ensure our standards, make sure to install pre-commit before starting to contribute.
|
||||
|
||||
```bash
|
||||
pre-commit install
|
||||
```
|
||||
|
||||
### 🧪 Testing
|
||||
|
||||
We use `pytest` to test our code. You can run the tests by running the following command:
|
||||
|
||||
```bash
|
||||
poetry run pytest tests
|
||||
|
||||
# or
|
||||
|
||||
make test
|
||||
```
|
||||
|
||||
Several packages have been removed from Poetry to make the package lighter. Therefore, it is recommended to run `make install_all` to install the remaining packages and ensure all tests pass. Make sure that all tests pass before submitting a pull request.
|
||||
|
||||
We look forward to your pull requests and can't wait to see your contributions!
|
||||
@@ -12,19 +12,20 @@ install:
|
||||
|
||||
install_all:
|
||||
poetry install
|
||||
poetry run pip install groq together boto3 litellm ollama
|
||||
poetry run pip install groq together boto3 litellm ollama chromadb sentence_transformers vertexai \
|
||||
google-generativeai elasticsearch
|
||||
|
||||
# Format code with ruff
|
||||
format:
|
||||
poetry run ruff check . --fix $(RUFF_OPTIONS)
|
||||
poetry run ruff format mem0/
|
||||
|
||||
# Sort imports with isort
|
||||
sort:
|
||||
poetry run isort . $(ISORT_OPTIONS)
|
||||
poetry run isort mem0/
|
||||
|
||||
# Lint code with ruff
|
||||
lint:
|
||||
poetry run ruff .
|
||||
poetry run ruff check mem0/
|
||||
|
||||
docs:
|
||||
cd docs && mintlify dev
|
||||
|
||||
@@ -2,66 +2,68 @@
|
||||
<a href="https://github.com/mem0ai/mem0">
|
||||
<img src="docs/images/banner-sm.png" width="800px" alt="Mem0 - The Memory Layer for Personalized AI">
|
||||
</a>
|
||||
<p align="center" style="display: flex; justify-content: center; gap: 20px; align-items: center;">
|
||||
<a href="https://trendshift.io/repositories/11194" target="_blank">
|
||||
<img src="https://trendshift.io/api/badge/repositories/11194" alt="mem0ai%2Fmem0 | Trendshift" style="width: 250px; height: 55px;" width="250" height="55"/>
|
||||
</a>
|
||||
<a href="https://www.ycombinator.com/launches/LpA-mem0-open-source-memory-layer-for-ai-apps" target="_blank">
|
||||
<img alt="Launch YC: Mem0 - Open Source Memory Layer for AI Apps" src="https://www.ycombinator.com/launches/LpA-mem0-open-source-memory-layer-for-ai-apps/upvote_embed.svg"/>
|
||||
</a>
|
||||
</p>
|
||||
|
||||
|
||||
<p align="center">
|
||||
<a href="https://mem0.ai">Learn more</a>
|
||||
·
|
||||
<a href="https://mem0.ai/discord">Join Discord</a>
|
||||
<a href="https://mem0.dev/DiG">Join Discord</a>
|
||||
</p>
|
||||
</p>
|
||||
|
||||
<p align="center">
|
||||
<a href="https://mem0.ai/discord">
|
||||
<a href="https://mem0.dev/DiG">
|
||||
<img src="https://dcbadge.vercel.app/api/server/6PzXDgEjG5?style=flat" alt="Mem0 Discord">
|
||||
</a>
|
||||
<a href="https://pepy.tech/project/mem0ai">
|
||||
<img src="https://img.shields.io/pypi/dm/mem0ai" alt="Mem0 PyPI - Downloads" >
|
||||
</a>
|
||||
<a href="https://github.com/mem0ai/mem0">
|
||||
<img src="https://img.shields.io/github/commit-activity/m/mem0ai/mem0?style=flat-square" alt="GitHub commit activity">
|
||||
</a>
|
||||
<a href="https://pypi.org/project/mem0ai" target="_blank">
|
||||
<img src="https://img.shields.io/pypi/v/mem0ai?color=%2334D058&label=pypi%20package" alt="Package version">
|
||||
</a>
|
||||
<a href="https://www.npmjs.com/package/mem0ai" target="_blank">
|
||||
<img src="https://img.shields.io/npm/v/mem0ai" alt="Npm package">
|
||||
</a>
|
||||
<a href="https://www.ycombinator.com/companies/mem0">
|
||||
<img src="https://img.shields.io/badge/Y%20Combinator-S24-orange?style=flat-square" alt="Y Combinator S24">
|
||||
</a>
|
||||
</p>
|
||||
|
||||
|
||||
# Introduction
|
||||
|
||||
[Mem0](https://mem0.ai)(pronounced "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.
|
||||
[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.
|
||||
|
||||
### Core Features
|
||||
### Features & Use Cases
|
||||
|
||||
- **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
|
||||
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
|
||||
|
||||
### 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:
|
||||
|
||||
@@ -69,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).
|
||||
@@ -78,94 +78,94 @@ 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[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).
|
||||
|
||||
|
||||
[Chrome Extension Demo](https://github.com/user-attachments/assets/ca92e40b-c453-4ff6-b25e-739fb18a8650)
|
||||
|
||||
<br/><br/>
|
||||
|
||||
- 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)
|
||||
|
||||
|
||||
|
||||
## 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
|
||||
|
||||
Join our community for support and discussions. If you have any questions, feel free to reach out to us using one of the following methods:
|
||||
|
||||
- [Join our Discord](https://mem0.ai/discord)
|
||||
- [Join our Discord](https://mem0.dev/DiG)
|
||||
- [Follow us on Twitter](https://x.com/mem0ai)
|
||||
- [Email founders](mailto:founders@mem0.ai)
|
||||
|
||||
## Contributors
|
||||
|
||||
Join our [Discord community](https://mem0.ai/discord) 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>
|
||||
|
||||
## License
|
||||
|
||||
This project is licensed under the Apache 2.0 License - see the [LICENSE](LICENSE) file for details.
|
||||
This project is licensed under the Apache 2.0 License - see the [LICENSE](LICENSE) file for details.
|
||||
|
||||
@@ -1,40 +0,0 @@
|
||||
# This example shows how to use vector config to use QDRANT CLOUD
|
||||
import os
|
||||
from dotenv import load_dotenv
|
||||
from mem0 import Memory
|
||||
|
||||
# Loading OpenAI API Key
|
||||
load_dotenv()
|
||||
OPENAI_API_KEY = os.environ.get('OPENAI_API_KEY')
|
||||
USER_ID = "test"
|
||||
quadrant_host="xx.gcp.cloud.qdrant.io"
|
||||
|
||||
# creating the config attributes
|
||||
collection_name="memory" # this is the collection I created in QDRANT cloud
|
||||
api_key=os.environ.get("QDRANT_API_KEY") # Getting the QDRANT api KEY
|
||||
host=quadrant_host
|
||||
port=6333 #Default port for QDRANT cloud
|
||||
|
||||
# Creating the config dict
|
||||
config = {
|
||||
"vector_store": {
|
||||
"provider": "qdrant",
|
||||
"config": {
|
||||
"collection_name": collection_name,
|
||||
"host": host,
|
||||
"port": port,
|
||||
"path": None,
|
||||
"api_key":api_key
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
# this is the change, create the memory class using from config
|
||||
memory = Memory().from_config(config)
|
||||
|
||||
USER_DATA = """
|
||||
I am a strong believer in memory architecture.
|
||||
"""
|
||||
|
||||
response = memory.add(USER_DATA, user_id=USER_ID)
|
||||
print(response)
|
||||
@@ -0,0 +1,239 @@
|
||||
{
|
||||
"cells": [
|
||||
{
|
||||
"cell_type": "code",
|
||||
"execution_count": 1,
|
||||
"metadata": {},
|
||||
"outputs": [],
|
||||
"source": [
|
||||
"import os\n",
|
||||
"from typing import List, Dict\n",
|
||||
"from mem0 import Memory\n",
|
||||
"from datetime import datetime\n",
|
||||
"import anthropic\n",
|
||||
"\n",
|
||||
"# Set up environment variables\n",
|
||||
"os.environ[\"OPENAI_API_KEY\"] = \"your_openai_api_key\" # needed for embedding model\n",
|
||||
"os.environ[\"ANTHROPIC_API_KEY\"] = \"your_anthropic_api_key\""
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "code",
|
||||
"execution_count": 2,
|
||||
"metadata": {},
|
||||
"outputs": [],
|
||||
"source": [
|
||||
"class SupportChatbot:\n",
|
||||
" def __init__(self):\n",
|
||||
" # Initialize Mem0 with Anthropic's Claude\n",
|
||||
" self.config = {\n",
|
||||
" \"llm\": {\n",
|
||||
" \"provider\": \"anthropic\",\n",
|
||||
" \"config\": {\n",
|
||||
" \"model\": \"claude-3-5-sonnet-latest\",\n",
|
||||
" \"temperature\": 0.1,\n",
|
||||
" \"max_tokens\": 2000,\n",
|
||||
" }\n",
|
||||
" }\n",
|
||||
" }\n",
|
||||
" self.client = anthropic.Client(api_key=os.environ[\"ANTHROPIC_API_KEY\"])\n",
|
||||
" self.memory = Memory.from_config(self.config)\n",
|
||||
"\n",
|
||||
" # Define support context\n",
|
||||
" self.system_context = \"\"\"\n",
|
||||
" You are a helpful customer support agent. Use the following guidelines:\n",
|
||||
" - Be polite and professional\n",
|
||||
" - Show empathy for customer issues\n",
|
||||
" - Reference past interactions when relevant\n",
|
||||
" - Maintain consistent information across conversations\n",
|
||||
" - If you're unsure about something, ask for clarification\n",
|
||||
" - Keep track of open issues and follow-ups\n",
|
||||
" \"\"\"\n",
|
||||
"\n",
|
||||
" def store_customer_interaction(self,\n",
|
||||
" user_id: str,\n",
|
||||
" message: str,\n",
|
||||
" response: str,\n",
|
||||
" metadata: Dict = None):\n",
|
||||
" \"\"\"Store customer interaction in memory.\"\"\"\n",
|
||||
" if metadata is None:\n",
|
||||
" metadata = {}\n",
|
||||
"\n",
|
||||
" # Add timestamp to metadata\n",
|
||||
" metadata[\"timestamp\"] = datetime.now().isoformat()\n",
|
||||
"\n",
|
||||
" # Format conversation for storage\n",
|
||||
" conversation = [\n",
|
||||
" {\"role\": \"user\", \"content\": message},\n",
|
||||
" {\"role\": \"assistant\", \"content\": response}\n",
|
||||
" ]\n",
|
||||
"\n",
|
||||
" # Store in Mem0\n",
|
||||
" self.memory.add(\n",
|
||||
" conversation,\n",
|
||||
" user_id=user_id,\n",
|
||||
" metadata=metadata\n",
|
||||
" )\n",
|
||||
"\n",
|
||||
" def get_relevant_history(self, user_id: str, query: str) -> List[Dict]:\n",
|
||||
" \"\"\"Retrieve relevant past interactions.\"\"\"\n",
|
||||
" return self.memory.search(\n",
|
||||
" query=query,\n",
|
||||
" user_id=user_id,\n",
|
||||
" limit=5 # Adjust based on needs\n",
|
||||
" )\n",
|
||||
"\n",
|
||||
" def handle_customer_query(self, user_id: str, query: str) -> str:\n",
|
||||
" \"\"\"Process customer query with context from past interactions.\"\"\"\n",
|
||||
"\n",
|
||||
" # Get relevant past interactions\n",
|
||||
" relevant_history = self.get_relevant_history(user_id, query)\n",
|
||||
"\n",
|
||||
" # Build context from relevant history\n",
|
||||
" context = \"Previous relevant interactions:\\n\"\n",
|
||||
" for memory in relevant_history:\n",
|
||||
" context += f\"Customer: {memory['memory']}\\n\"\n",
|
||||
" context += f\"Support: {memory['memory']}\\n\"\n",
|
||||
" context += \"---\\n\"\n",
|
||||
"\n",
|
||||
" # Prepare prompt with context and current query\n",
|
||||
" prompt = f\"\"\"\n",
|
||||
" {self.system_context}\n",
|
||||
"\n",
|
||||
" {context}\n",
|
||||
"\n",
|
||||
" Current customer query: {query}\n",
|
||||
"\n",
|
||||
" Provide a helpful response that takes into account any relevant past interactions.\n",
|
||||
" \"\"\"\n",
|
||||
"\n",
|
||||
" # Generate response using Claude\n",
|
||||
" response = self.client.messages.create(\n",
|
||||
" model=\"claude-3-5-sonnet-latest\",\n",
|
||||
" messages=[{\"role\": \"user\", \"content\": prompt}],\n",
|
||||
" max_tokens=2000,\n",
|
||||
" temperature=0.1\n",
|
||||
" )\n",
|
||||
"\n",
|
||||
" # Store interaction\n",
|
||||
" self.store_customer_interaction(\n",
|
||||
" user_id=user_id,\n",
|
||||
" message=query,\n",
|
||||
" response=response,\n",
|
||||
" metadata={\"type\": \"support_query\"}\n",
|
||||
" )\n",
|
||||
"\n",
|
||||
" return response.content[0].text"
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "code",
|
||||
"execution_count": 3,
|
||||
"metadata": {},
|
||||
"outputs": [
|
||||
{
|
||||
"name": "stdout",
|
||||
"output_type": "stream",
|
||||
"text": [
|
||||
"Welcome to Customer Support! Type 'exit' to end the conversation.\n",
|
||||
"Customer: Hi, I'm having trouble connecting my new smartwatch to the mobile app. It keeps showing a connection error.\n"
|
||||
]
|
||||
},
|
||||
{
|
||||
"name": "stderr",
|
||||
"output_type": "stream",
|
||||
"text": [
|
||||
"/var/folders/5x/9kmqjfm947g5yh44m7fjk75r0000gn/T/ipykernel_99777/1076713094.py:55: DeprecationWarning: The current get_all 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.\n",
|
||||
" return self.memory.search(\n",
|
||||
"/var/folders/5x/9kmqjfm947g5yh44m7fjk75r0000gn/T/ipykernel_99777/1076713094.py:47: DeprecationWarning: The current add 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.\n",
|
||||
" self.memory.add(\n"
|
||||
]
|
||||
},
|
||||
{
|
||||
"name": "stdout",
|
||||
"output_type": "stream",
|
||||
"text": [
|
||||
"Support: Hello! Thank you for reaching out about the connection issue with your smartwatch. I understand how frustrating it can be when a new device won't connect properly. I'll be happy to help you resolve this.\n",
|
||||
"\n",
|
||||
"To better assist you, could you please provide me with:\n",
|
||||
"1. The model of your smartwatch\n",
|
||||
"2. The type of phone you're using (iOS or Android)\n",
|
||||
"3. Whether you've already installed the companion app on your phone\n",
|
||||
"4. If you've tried pairing the devices before\n",
|
||||
"\n",
|
||||
"These details will help me provide you with the most accurate troubleshooting steps. In the meantime, here are some general tips that might help:\n",
|
||||
"- Make sure Bluetooth is enabled on your phone\n",
|
||||
"- Keep your smartwatch and phone within close range (within 3 feet) during pairing\n",
|
||||
"- Ensure both devices have sufficient battery power\n",
|
||||
"- Check if your phone's operating system meets the minimum requirements for the smartwatch\n",
|
||||
"\n",
|
||||
"Please provide the requested information, and I'll guide you through the specific steps to resolve the connection error.\n",
|
||||
"\n",
|
||||
"Is there anything else you'd like to share about the issue? \n",
|
||||
"\n",
|
||||
"\n",
|
||||
"Customer: The connection issue is still happening even after trying the steps you suggested.\n",
|
||||
"Support: I apologize that you're still experiencing connection issues with your smartwatch. I understand how frustrating it must be to have this problem persist even after trying the initial troubleshooting steps. Let's try some additional solutions to resolve this.\n",
|
||||
"\n",
|
||||
"Before we proceed, could you please confirm:\n",
|
||||
"1. Which specific steps you've already attempted?\n",
|
||||
"2. Are you seeing any particular error message?\n",
|
||||
"3. What model of smartwatch and phone are you using?\n",
|
||||
"\n",
|
||||
"This information will help me provide more targeted solutions and avoid suggesting steps you've already tried. In the meantime, here are a few advanced troubleshooting steps we can consider:\n",
|
||||
"\n",
|
||||
"1. Completely resetting the Bluetooth connection\n",
|
||||
"2. Checking for any software updates for both the watch and phone\n",
|
||||
"3. Testing the connection with a different mobile device to isolate the issue\n",
|
||||
"\n",
|
||||
"Would you be able to provide those details so I can better assist you? I'll make sure to document this ongoing issue to help track its resolution. \n",
|
||||
"\n",
|
||||
"\n",
|
||||
"Customer: exit\n",
|
||||
"Thank you for using our support service. Goodbye!\n"
|
||||
]
|
||||
}
|
||||
],
|
||||
"source": [
|
||||
"chatbot = SupportChatbot()\n",
|
||||
"user_id = \"customer_bot\"\n",
|
||||
"print(\"Welcome to Customer Support! Type 'exit' to end the conversation.\")\n",
|
||||
"\n",
|
||||
"while True:\n",
|
||||
" # Get user input\n",
|
||||
" query = input()\n",
|
||||
" print(\"Customer:\", query)\n",
|
||||
" \n",
|
||||
" # Check if user wants to exit\n",
|
||||
" if query.lower() == 'exit':\n",
|
||||
" print(\"Thank you for using our support service. Goodbye!\")\n",
|
||||
" break\n",
|
||||
" \n",
|
||||
" # Handle the query and print the response\n",
|
||||
" response = chatbot.handle_customer_query(user_id, query)\n",
|
||||
" print(\"Support:\", response, \"\\n\\n\")"
|
||||
]
|
||||
}
|
||||
],
|
||||
"metadata": {
|
||||
"kernelspec": {
|
||||
"display_name": ".venv",
|
||||
"language": "python",
|
||||
"name": "python3"
|
||||
},
|
||||
"language_info": {
|
||||
"codemirror_mode": {
|
||||
"name": "ipython",
|
||||
"version": 3
|
||||
},
|
||||
"file_extension": ".py",
|
||||
"mimetype": "text/x-python",
|
||||
"name": "python",
|
||||
"nbconvert_exporter": "python",
|
||||
"pygments_lexer": "ipython3",
|
||||
"version": "3.12.4"
|
||||
}
|
||||
},
|
||||
"nbformat": 4,
|
||||
"nbformat_minor": 2
|
||||
}
|
||||
@@ -0,0 +1,170 @@
|
||||
# Copyright (c) 2023 - 2024, Owners of https://github.com/autogen-ai
|
||||
#
|
||||
# SPDX-License-Identifier: Apache-2.0
|
||||
#
|
||||
# Portions derived from https://github.com/microsoft/autogen are under the MIT License.
|
||||
# SPDX-License-Identifier: MIT
|
||||
# forked from autogen.agentchat.contrib.capabilities.teachability.Teachability
|
||||
|
||||
from typing import Dict, Optional, Union
|
||||
from autogen.agentchat.assistant_agent import ConversableAgent
|
||||
from autogen.agentchat.contrib.capabilities.agent_capability import AgentCapability
|
||||
from autogen.agentchat.contrib.text_analyzer_agent import TextAnalyzerAgent
|
||||
from termcolor import colored
|
||||
from mem0 import Memory
|
||||
|
||||
|
||||
class Mem0Teachability(AgentCapability):
|
||||
def __init__(
|
||||
self,
|
||||
verbosity: Optional[int] = 0,
|
||||
reset_db: Optional[bool] = False,
|
||||
recall_threshold: Optional[float] = 1.5,
|
||||
max_num_retrievals: Optional[int] = 10,
|
||||
llm_config: Optional[Union[Dict, bool]] = None,
|
||||
agent_id: Optional[str] = None,
|
||||
memory_client: Optional[Memory] = None,
|
||||
):
|
||||
self.verbosity = verbosity
|
||||
self.recall_threshold = recall_threshold
|
||||
self.max_num_retrievals = max_num_retrievals
|
||||
self.llm_config = llm_config
|
||||
self.analyzer = None
|
||||
self.teachable_agent = None
|
||||
self.agent_id = agent_id
|
||||
self.memory = memory_client if memory_client else Memory()
|
||||
|
||||
if reset_db:
|
||||
self.memory.reset()
|
||||
|
||||
def add_to_agent(self, agent: ConversableAgent):
|
||||
self.teachable_agent = agent
|
||||
agent.register_hook(hookable_method="process_last_received_message", hook=self.process_last_received_message)
|
||||
|
||||
if self.llm_config is None:
|
||||
self.llm_config = agent.llm_config
|
||||
assert self.llm_config, "Teachability requires a valid llm_config."
|
||||
|
||||
self.analyzer = TextAnalyzerAgent(llm_config=self.llm_config)
|
||||
|
||||
agent.update_system_message(
|
||||
agent.system_message
|
||||
+ "\nYou've been given the special ability to remember user teachings from prior conversations."
|
||||
)
|
||||
|
||||
def process_last_received_message(self, text: Union[Dict, str]):
|
||||
expanded_text = text
|
||||
if self.memory.get_all(agent_id=self.agent_id):
|
||||
expanded_text = self._consider_memo_retrieval(text)
|
||||
self._consider_memo_storage(text)
|
||||
return expanded_text
|
||||
|
||||
def _consider_memo_storage(self, comment: Union[Dict, str]):
|
||||
response = self._analyze(
|
||||
comment,
|
||||
"Does any part of the TEXT ask the agent to perform a task or solve a problem? Answer with just one word, yes or no.",
|
||||
)
|
||||
|
||||
if "yes" in response.lower():
|
||||
advice = self._analyze(
|
||||
comment,
|
||||
"Briefly copy any advice from the TEXT that may be useful for a similar but different task in the future. But if no advice is present, just respond with 'none'.",
|
||||
)
|
||||
|
||||
if "none" not in advice.lower():
|
||||
task = self._analyze(
|
||||
comment,
|
||||
"Briefly copy just the task from the TEXT, then stop. Don't solve it, and don't include any advice.",
|
||||
)
|
||||
|
||||
general_task = self._analyze(
|
||||
task,
|
||||
"Summarize very briefly, in general terms, the type of task described in the TEXT. Leave out details that might not appear in a similar problem.",
|
||||
)
|
||||
|
||||
if self.verbosity >= 1:
|
||||
print(colored("\nREMEMBER THIS TASK-ADVICE PAIR", "light_yellow"))
|
||||
self.memory.add(
|
||||
[{"role": "user", "content": f"Task: {general_task}\nAdvice: {advice}"}], agent_id=self.agent_id
|
||||
)
|
||||
|
||||
response = self._analyze(
|
||||
comment,
|
||||
"Does the TEXT contain information that could be committed to memory? Answer with just one word, yes or no.",
|
||||
)
|
||||
|
||||
if "yes" in response.lower():
|
||||
question = self._analyze(
|
||||
comment,
|
||||
"Imagine that the user forgot this information in the TEXT. How would they ask you for this information? Include no other text in your response.",
|
||||
)
|
||||
|
||||
answer = self._analyze(
|
||||
comment, "Copy the information from the TEXT that should be committed to memory. Add no explanation."
|
||||
)
|
||||
|
||||
if self.verbosity >= 1:
|
||||
print(colored("\nREMEMBER THIS QUESTION-ANSWER PAIR", "light_yellow"))
|
||||
self.memory.add(
|
||||
[{"role": "user", "content": f"Question: {question}\nAnswer: {answer}"}], agent_id=self.agent_id
|
||||
)
|
||||
|
||||
def _consider_memo_retrieval(self, comment: Union[Dict, str]):
|
||||
if self.verbosity >= 1:
|
||||
print(colored("\nLOOK FOR RELEVANT MEMOS, AS QUESTION-ANSWER PAIRS", "light_yellow"))
|
||||
memo_list = self._retrieve_relevant_memos(comment)
|
||||
|
||||
response = self._analyze(
|
||||
comment,
|
||||
"Does any part of the TEXT ask the agent to perform a task or solve a problem? Answer with just one word, yes or no.",
|
||||
)
|
||||
|
||||
if "yes" in response.lower():
|
||||
if self.verbosity >= 1:
|
||||
print(colored("\nLOOK FOR RELEVANT MEMOS, AS TASK-ADVICE PAIRS", "light_yellow"))
|
||||
task = self._analyze(
|
||||
comment, "Copy just the task from the TEXT, then stop. Don't solve it, and don't include any advice."
|
||||
)
|
||||
|
||||
general_task = self._analyze(
|
||||
task,
|
||||
"Summarize very briefly, in general terms, the type of task described in the TEXT. Leave out details that might not appear in a similar problem.",
|
||||
)
|
||||
|
||||
memo_list.extend(self._retrieve_relevant_memos(general_task))
|
||||
|
||||
memo_list = list(set(memo_list))
|
||||
return comment + self._concatenate_memo_texts(memo_list)
|
||||
|
||||
def _retrieve_relevant_memos(self, input_text: str) -> list:
|
||||
search_results = self.memory.search(input_text, agent_id=self.agent_id, limit=self.max_num_retrievals)
|
||||
memo_list = [result["memory"] for result in search_results if result["score"] <= self.recall_threshold]
|
||||
|
||||
if self.verbosity >= 1 and not memo_list:
|
||||
print(colored("\nTHE CLOSEST MEMO IS BEYOND THE THRESHOLD:", "light_yellow"))
|
||||
if search_results["results"]:
|
||||
print(search_results["results"][0])
|
||||
print()
|
||||
|
||||
return memo_list
|
||||
|
||||
def _concatenate_memo_texts(self, memo_list: list) -> str:
|
||||
memo_texts = ""
|
||||
if memo_list:
|
||||
info = "\n# Memories that might help\n"
|
||||
for memo in memo_list:
|
||||
info += f"- {memo}\n"
|
||||
if self.verbosity >= 1:
|
||||
print(colored(f"\nMEMOS APPENDED TO LAST MESSAGE...\n{info}\n", "light_yellow"))
|
||||
memo_texts += "\n" + info
|
||||
return memo_texts
|
||||
|
||||
def _analyze(self, text_to_analyze: Union[Dict, str], analysis_instructions: Union[Dict, str]):
|
||||
self.analyzer.reset()
|
||||
self.teachable_agent.send(
|
||||
recipient=self.analyzer, message=text_to_analyze, request_reply=False, silent=(self.verbosity < 2)
|
||||
)
|
||||
self.teachable_agent.send(
|
||||
recipient=self.analyzer, message=analysis_instructions, request_reply=True, silent=(self.verbosity < 2)
|
||||
)
|
||||
return self.teachable_agent.last_message(self.analyzer)["content"]
|
||||
File diff suppressed because it is too large
Load Diff
File diff suppressed because one or more lines are too long
@@ -1,306 +0,0 @@
|
||||
{
|
||||
"cells": [
|
||||
{
|
||||
"cell_type": "code",
|
||||
"source": [
|
||||
"!pip install mem0ai"
|
||||
],
|
||||
"metadata": {
|
||||
"id": "fu3euPKZsbaC"
|
||||
},
|
||||
"execution_count": null,
|
||||
"outputs": []
|
||||
},
|
||||
{
|
||||
"cell_type": "code",
|
||||
"execution_count": null,
|
||||
"metadata": {
|
||||
"id": "U2VC_0FElQid"
|
||||
},
|
||||
"outputs": [],
|
||||
"source": [
|
||||
"import os\n",
|
||||
"from openai import OpenAI\n",
|
||||
"from mem0 import MemoryClient\n",
|
||||
"from multion.client import MultiOn\n",
|
||||
"\n",
|
||||
"# Configuration\n",
|
||||
"OPENAI_API_KEY = 'sk-xxx' # Replace with your actual OpenAI API key\n",
|
||||
"MULTION_API_KEY = 'xx' # Replace with your actual MultiOn API key\n",
|
||||
"MEM0_API_KEY = 'xx' # Replace with your actual Mem0 API key\n",
|
||||
"USER_ID = \"test_travel_agent\"\n",
|
||||
"\n",
|
||||
"# Set up OpenAI API key\n",
|
||||
"os.environ['OPENAI_API_KEY'] = OPENAI_API_KEY\n",
|
||||
"\n",
|
||||
"# Initialize Mem0 and MultiOn\n",
|
||||
"memory = MemoryClient(api_key=MEM0_API_KEY)\n",
|
||||
"multion = MultiOn(api_key=MULTION_API_KEY)"
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "code",
|
||||
"execution_count": null,
|
||||
"metadata": {
|
||||
"id": "sq-OdPHKlQie",
|
||||
"outputId": "1d605222-0bf5-4ac9-99b9-6059b502c20b"
|
||||
},
|
||||
"outputs": [
|
||||
{
|
||||
"data": {
|
||||
"text/plain": [
|
||||
"{'message': 'Memory added successfully!'}"
|
||||
]
|
||||
},
|
||||
"execution_count": 2,
|
||||
"metadata": {},
|
||||
"output_type": "execute_result"
|
||||
}
|
||||
],
|
||||
"source": [
|
||||
"# Add conversation to Mem0\n",
|
||||
"conversation = [\n",
|
||||
" {\n",
|
||||
" \"role\": \"user\",\n",
|
||||
" \"content\": \"What are the best travel destinations in the world?\"\n",
|
||||
" },\n",
|
||||
" {\n",
|
||||
" \"role\": \"assistant\",\n",
|
||||
" \"content\": \"Could you please specify your interests or the type of travel information you are looking for? This will help me find the most relevant information for you.\"\n",
|
||||
" },\n",
|
||||
" {\n",
|
||||
" \"role\": \"user\",\n",
|
||||
" \"content\": \"Sure, I want to travel to San Francisco.\"\n",
|
||||
" },\n",
|
||||
" {\n",
|
||||
" \"role\": \"assistant\",\n",
|
||||
" \"content\": \"\"\"\n",
|
||||
" Based on the information gathered from TripAdvisor, here are some popular attractions, activities, and travel tips for San Francisco:\n",
|
||||
"\n",
|
||||
" 1. **Golden Gate Bridge**: A must-see iconic landmark.\n",
|
||||
" 2. **Alcatraz Island**: Famous former prison offering tours.\n",
|
||||
" 3. **Fisherman's Wharf**: Popular tourist area with shops, restaurants, and sea lions.\n",
|
||||
" 4. **Chinatown**: The largest Chinatown outside of Asia.\n",
|
||||
" 5. **Golden Gate Park**: Large urban park with gardens, museums, and recreational activities.\n",
|
||||
" 6. **Cable Cars**: Historic streetcars offering a unique way to see the city.\n",
|
||||
" 7. **Exploratorium**: Interactive science museum.\n",
|
||||
" 8. **San Francisco Museum of Modern Art (SFMOMA)**: Modern and contemporary art museum.\n",
|
||||
" 9. **Lombard Street**: Known for its steep, one-block section with eight hairpin turns.\n",
|
||||
" 10. **Union Square**: Major shopping and cultural hub.\n",
|
||||
"\n",
|
||||
" Travel Tips:\n",
|
||||
" - **Weather**: San Francisco has a mild climate, but it can be foggy and windy. Dress in layers.\n",
|
||||
" - **Transportation**: Use public transportation like BART, Muni, and cable cars to get around.\n",
|
||||
" - **Safety**: Be aware of your surroundings, especially in crowded tourist areas.\n",
|
||||
" - **Dining**: Try local specialties like sourdough bread, seafood, and Mission-style burritos.\n",
|
||||
" \"\"\"\n",
|
||||
" },\n",
|
||||
" {\n",
|
||||
" \"role\": \"user\",\n",
|
||||
" \"content\": \"Show me hotels around Golden Gate Bridge.\"\n",
|
||||
" },\n",
|
||||
" {\n",
|
||||
" \"role\": \"assistant\",\n",
|
||||
" \"content\": \"\"\"\n",
|
||||
" The search results for hotels around Golden Gate Bridge in San Francisco include:\n",
|
||||
"\n",
|
||||
" 1. Hilton Hotels In San Francisco - Hotel Near Fishermans Wharf (hilton.com)\n",
|
||||
" 2. The 10 Closest Hotels to Golden Gate Bridge (tripadvisor.com)\n",
|
||||
" 3. Hotels near Golden Gate Bridge (expedia.com)\n",
|
||||
" 4. Hotels near Golden Gate Bridge (hotels.com)\n",
|
||||
" 5. Holiday Inn Express & Suites San Francisco Fishermans Wharf, an IHG Hotel $146 (1.8K) 3-star hotel Golden Gate Bridge • 3.5 mi DEAL 19% less than usual\n",
|
||||
" 6. Holiday Inn San Francisco-Golden Gateway, an IHG Hotel $151 (3.5K) 3-star hotel Golden Gate Bridge • 3.7 mi Casual hotel with dining, a bar & a pool\n",
|
||||
" 7. Hotel Zephyr San Francisco $159 (3.8K) 4-star hotel Golden Gate Bridge • 3.7 mi Nautical-themed lodging with bay views\n",
|
||||
" 8. Lodge at the Presidio\n",
|
||||
" 9. The Inn Above Tide\n",
|
||||
" 10. Cavallo Point\n",
|
||||
" 11. Casa Madrona Hotel and Spa\n",
|
||||
" 12. Cow Hollow Inn and Suites\n",
|
||||
" 13. Samesun San Francisco\n",
|
||||
" 14. Inn on Broadway\n",
|
||||
" 15. Coventry Motor Inn\n",
|
||||
" 16. HI San Francisco Fisherman's Wharf Hostel\n",
|
||||
" 17. Loews Regency San Francisco Hotel\n",
|
||||
" 18. Fairmont Heritage Place Ghirardelli Square\n",
|
||||
" 19. Hotel Drisco Pacific Heights\n",
|
||||
" 20. Travelodge by Wyndham Presidio San Francisco\n",
|
||||
" \"\"\"\n",
|
||||
" }\n",
|
||||
"]\n",
|
||||
"\n",
|
||||
"memory.add(conversation, user_id=USER_ID)\n"
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "code",
|
||||
"execution_count": null,
|
||||
"metadata": {
|
||||
"id": "hO8z9aNTlQif"
|
||||
},
|
||||
"outputs": [],
|
||||
"source": [
|
||||
"def get_travel_info(question, use_memory=True):\n",
|
||||
" \"\"\"\n",
|
||||
" Get travel information based on user's question and optionally their preferences from memory.\n",
|
||||
"\n",
|
||||
" \"\"\"\n",
|
||||
" if use_memory:\n",
|
||||
" previous_memories = memory.search(question, user_id=USER_ID)\n",
|
||||
" relevant_memories_text = \"\"\n",
|
||||
" if previous_memories:\n",
|
||||
" print(\"Using previous memories to enhance the search...\")\n",
|
||||
" relevant_memories_text = '\\n'.join(mem[\"memory\"] for mem in previous_memories)\n",
|
||||
"\n",
|
||||
" command = \"Find travel information based on my interests:\"\n",
|
||||
" prompt = f\"{command}\\n Question: {question} \\n My preferences: {relevant_memories_text}\"\n",
|
||||
" else:\n",
|
||||
" command = \"Find travel information based on my interests:\"\n",
|
||||
" prompt = f\"{command}\\n Question: {question}\"\n",
|
||||
"\n",
|
||||
"\n",
|
||||
" print(\"Searching for travel information...\")\n",
|
||||
" browse_result = multion.browse(cmd=prompt)\n",
|
||||
" return browse_result.message"
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "markdown",
|
||||
"metadata": {
|
||||
"id": "Wp2xpzMrlQig"
|
||||
},
|
||||
"source": [
|
||||
"## Example 1"
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "code",
|
||||
"execution_count": null,
|
||||
"metadata": {
|
||||
"id": "bPRPwqsplQig"
|
||||
},
|
||||
"outputs": [],
|
||||
"source": [
|
||||
"question = \"Show me flight details for it.\"\n",
|
||||
"answer_without_memory = get_travel_info(question, use_memory=False)\n",
|
||||
"answer_with_memory = get_travel_info(question, use_memory=True)"
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "markdown",
|
||||
"metadata": {
|
||||
"id": "a76ifa2HlQig"
|
||||
},
|
||||
"source": [
|
||||
"| Without Memory | With Memory |\n",
|
||||
"|--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|\n",
|
||||
"| I have performed a Google search for \"flight details\" and reviewed the search results. Here are some relevant links and information: | Memorizing the following information: Flight details for San Francisco: |\n",
|
||||
"| 1. **FlightStats Global Flight Tracker** - Track the real-time flight status of your flight. See if your flight has been delayed or cancelled and track the live status. <br> [Flight Tracker - FlightStats](https://www.flightstats.com/flight-tracker/search) | 1. Prices from $232. Depart Thursday, August 22. Return Thursday, August 29. <br> 2. Prices from $216. Depart Friday, August 23. Return Friday, August 30. <br> 3. Prices from $236. Depart Saturday, August 24. Return Saturday, August 31. <br> 4. Prices from $215. Depart Sunday, August 25. Return Sunday, September 1. |\n",
|
||||
"| 2. **FlightAware - Flight Tracker** - Track live flights worldwide, see flight cancellations, and browse by airport. <br> [FlightAware - Flight Tracker](https://www.flightaware.com) | 5. Prices from $218. Depart Monday, August 26. Return Monday, September 2. <br> 6. Prices from $211. Depart Tuesday, August 27. Return Tuesday, September 3. <br> 7. Prices from $198. Depart Wednesday, August 28. Return Wednesday, September 4. <br> 8. Prices from $218. Depart Thursday, August 29. Return Thursday, September 5. |\n",
|
||||
"| 3. **Google Flights** - Show flights based on your search. <br> [Google Flights](https://www.google.com/flights) | 9. Prices from $194. Depart Friday, August 30. Return Friday, September 6. <br> 10. Prices from $218. Depart Saturday, August 31. Return Saturday, September 7. <br> 11. Prices from $212. Depart Sunday, September 1. Return Sunday, September 8. <br> 12. Prices from $247. Depart Monday, September 2. Return Monday, September 9. |\n",
|
||||
"| | 13. Prices from $212. Depart Tuesday, September 3. Return Tuesday, September 10. <br> 14. Prices from $203. Depart Wednesday, September 4. Return Wednesday, September 11. <br> 15. Prices from $242. Depart Thursday, September 5. Return Thursday, September 12. <br> 16. Prices from $191. Depart Friday, September 6. Return Friday, September 13. |\n",
|
||||
"| | 17. Prices from $215. Depart Saturday, September 7. Return Saturday, September 14. <br> 18. Prices from $229. Depart Sunday, September 8. Return Sunday, September 15. <br> 19. Prices from $183. Depart Monday, September 9. Return Monday, September 16. <br> 65. Prices from $194. Depart Friday, October 25. Return Friday, November 1. |\n",
|
||||
"| | 66. Prices from $205. Depart Saturday, October 26. Return Saturday, November 2. <br> 67. Prices from $241. Depart Sunday, October 27. Return Sunday, November 3. |\n"
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "markdown",
|
||||
"metadata": {
|
||||
"id": "0cXpiAwMlQig"
|
||||
},
|
||||
"source": [
|
||||
"## Example 2"
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "code",
|
||||
"execution_count": null,
|
||||
"metadata": {
|
||||
"id": "LpprKfpslQih"
|
||||
},
|
||||
"outputs": [],
|
||||
"source": [
|
||||
"question = \"What places to visit there?\"\n",
|
||||
"answer_without_memory = get_travel_info(question, use_memory=False)\n",
|
||||
"answer_with_memory = get_travel_info(question, use_memory=True)"
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "markdown",
|
||||
"metadata": {
|
||||
"id": "kpfjeY1_lQih"
|
||||
},
|
||||
"source": [
|
||||
"| Without Memory | With Memory |\n",
|
||||
"|---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|\n",
|
||||
"| Based on the information gathered, here are some top travel destinations to consider visiting: | Based on the information gathered, here are some top places to visit in San Francisco: |\n",
|
||||
"| 1. **Paris**: Known for its iconic attractions like the Eiffel Tower and the Louvre, Paris offers quaint cafes, trendy shopping districts, and beautiful Haussmann architecture. It's a city where you can always discover something new with each visit. | 1. **Golden Gate Bridge** - An iconic symbol of San Francisco, perfect for walking, biking, or simply enjoying the view. <br> 2. **Alcatraz Island** - The historic former prison offers tours and insights into its storied past. <br> 3. **Fisherman's Wharf** - A bustling waterfront area known for its seafood, shopping, and attractions like Pier 39. <br> 4. **Golden Gate Park** - A large urban park with gardens, museums, and recreational activities. <br> 5. **Chinatown San Francisco** - One of the oldest and most famous Chinatowns in North America, offering unique shops and delicious food. <br> 6. **Coit Tower** - Offers panoramic views of the city and murals depicting San Francisco's history. <br> 7. **Lands End** - A beautiful coastal trail with stunning views of the Pacific Ocean and the Golden Gate Bridge. <br> 8. **Palace of Fine Arts** - A picturesque structure and park, perfect for a leisurely stroll or photo opportunities. <br> 9. **Crissy Field & The Presidio Tunnel Tops** - Great for outdoor activities and scenic views of the bay. |\n",
|
||||
"| 2. **Bora Bora**: This small island in French Polynesia is famous for its stunning turquoise waters, luxurious overwater bungalows, and vibrant coral reefs. It's a popular destination for honeymooners and those seeking a tropical paradise. | |\n",
|
||||
"| 3. **Glacier National Park**: Located in Montana, USA, this park is known for its breathtaking landscapes, including rugged mountains, pristine lakes, and diverse wildlife. It's a haven for outdoor enthusiasts and hikers. | |\n",
|
||||
"| 4. **Rome**: The capital of Italy, Rome is rich in history and culture, featuring landmarks such as the Colosseum, the Vatican, and the Pantheon. It's a city where ancient history meets modern life. | |\n",
|
||||
"| 5. **Swiss Alps**: Renowned for their stunning natural beauty, the Swiss Alps offer opportunities for skiing, hiking, and enjoying picturesque mountain villages. | |\n",
|
||||
"| 6. **Maui**: One of Hawaii's most popular islands, Maui is known for its beautiful beaches, lush rainforests, and the scenic Hana Highway. It's a great destination for both relaxation and adventure. | |\n",
|
||||
"| 7. **London, England**: A vibrant city with a mix of historical landmarks like the Tower of London and modern attractions such as the London Eye. London offers diverse cultural experiences, world-class museums, and a bustling nightlife. | |\n",
|
||||
"| 8. **Maldives**: This tropical paradise in the Indian Ocean is famous for its crystal-clear waters, luxurious resorts, and abundant marine life. It's an ideal destination for snorkeling, diving, and relaxation. | |\n",
|
||||
"| 9. **Turks & Caicos**: Known for its pristine beaches and turquoise waters, this Caribbean destination is perfect for water sports, beach lounging, and exploring coral reefs. | |\n",
|
||||
"| 10. **Tokyo**: Japan's bustling capital offers a unique blend of traditional and modern attractions, from ancient temples to futuristic skyscrapers. Tokyo is also known for its vibrant food scene and shopping districts. | |\n"
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "markdown",
|
||||
"metadata": {
|
||||
"id": "XdpkcMrclQih"
|
||||
},
|
||||
"source": [
|
||||
"## Example 3"
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "code",
|
||||
"execution_count": null,
|
||||
"metadata": {
|
||||
"id": "Nntl2FxulQih"
|
||||
},
|
||||
"outputs": [],
|
||||
"source": [
|
||||
"question = \"What the weather there?\"\n",
|
||||
"answer_without_memory = get_travel_info(question, use_memory=False)\n",
|
||||
"answer_with_memory = get_travel_info(question, use_memory=True)"
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "markdown",
|
||||
"metadata": {
|
||||
"id": "yt2pj1irlQih"
|
||||
},
|
||||
"source": [
|
||||
"| Without Memory | With Memory |\n",
|
||||
"|---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|\n",
|
||||
"| The current weather in Paris is light rain with a temperature of 67°F. The precipitation is at 50%, humidity is 95%, and the wind speed is 5 mph. | The current weather in San Francisco is as follows: <br> - **Temperature**: 59°F <br> - **Condition**: Clear with periodic clouds <br> - **Precipitation**: 3% <br> - **Humidity**: 87% <br> - **Wind**: 12 mph |\n"
|
||||
]
|
||||
}
|
||||
],
|
||||
"metadata": {
|
||||
"kernelspec": {
|
||||
"display_name": ".venv",
|
||||
"language": "python",
|
||||
"name": "python3"
|
||||
},
|
||||
"language_info": {
|
||||
"codemirror_mode": {
|
||||
"name": "ipython",
|
||||
"version": 3
|
||||
},
|
||||
"file_extension": ".py",
|
||||
"mimetype": "text/x-python",
|
||||
"name": "python",
|
||||
"nbconvert_exporter": "python",
|
||||
"pygments_lexer": "ipython3",
|
||||
"version": "3.12.3"
|
||||
},
|
||||
"colab": {
|
||||
"provenance": []
|
||||
}
|
||||
},
|
||||
"nbformat": 4,
|
||||
"nbformat_minor": 0
|
||||
}
|
||||
@@ -1,11 +1,11 @@
|
||||
<CardGroup cols={3}>
|
||||
<Card title="Discord" icon="discord" href="https://mem0.ai/discord" color="#7289DA">
|
||||
<Card title="Discord" icon="discord" href="https://mem0.dev/DiD" color="#7289DA">
|
||||
Join our community
|
||||
</Card>
|
||||
<Card title="GitHub" icon="github" href="https://github.com/mem0ai/mem0">
|
||||
Star us on GitHub
|
||||
<Card title="GitHub" icon="github" href="https://github.com/mem0ai/mem0/discussions/new?category=q-a">
|
||||
Ask questions on GitHub
|
||||
</Card>
|
||||
<Card title="Support" icon="calendar" href="mailto:taranjeet@mem0.ai">
|
||||
<Card title="Support" icon="calendar" href="https://cal.com/taranjeetio/meet">
|
||||
Talk to founders
|
||||
</Card>
|
||||
</CardGroup>
|
||||
|
||||
@@ -0,0 +1,4 @@
|
||||
---
|
||||
title: 'Delete User'
|
||||
openapi: delete /v1/entities/{entity_type}/{entity_id}/
|
||||
---
|
||||
@@ -0,0 +1,4 @@
|
||||
---
|
||||
title: 'Get Users'
|
||||
openapi: get /v1/entities/
|
||||
---
|
||||
@@ -0,0 +1,4 @@
|
||||
---
|
||||
title: 'Add Memories'
|
||||
openapi: post /v1/memories/
|
||||
---
|
||||
@@ -0,0 +1,4 @@
|
||||
---
|
||||
title: 'Batch Delete Memories'
|
||||
openapi: delete /v1/batch/
|
||||
---
|
||||
@@ -0,0 +1,4 @@
|
||||
---
|
||||
title: 'Batch Update Memories'
|
||||
openapi: put /v1/batch/
|
||||
---
|
||||
@@ -0,0 +1,6 @@
|
||||
---
|
||||
title: 'Create Memory Export'
|
||||
openapi: post /v1/exports/
|
||||
---
|
||||
|
||||
Submit a job to create a structured export of memories using a customizable Pydantic schema. This process may take some time to complete, especially if you’re exporting a large number of memories. You can tailor the export by applying various filters (e.g., user_id, agent_id, run_id, or session_id) and by modifying the Pydantic schema to ensure the final data matches your exact needs.
|
||||
@@ -0,0 +1,4 @@
|
||||
---
|
||||
title: 'Delete Memories'
|
||||
openapi: delete /v1/memories/
|
||||
---
|
||||
@@ -0,0 +1,4 @@
|
||||
---
|
||||
title: 'Delete Memory'
|
||||
openapi: delete /v1/memories/{memory_id}/
|
||||
---
|
||||
@@ -0,0 +1,6 @@
|
||||
---
|
||||
title: 'Get Memory Export'
|
||||
openapi: get /v1/exports/
|
||||
---
|
||||
|
||||
Retrieve the latest structured memory export after submitting an export job. You can filter the export by `user_id`, `run_id`, `session_id`, or `app_id` to get the most recent export matching your filters.
|
||||
@@ -0,0 +1,4 @@
|
||||
---
|
||||
title: 'Get Memory'
|
||||
openapi: get /v1/memories/{memory_id}/
|
||||
---
|
||||
@@ -0,0 +1,4 @@
|
||||
---
|
||||
title: 'Memory History'
|
||||
openapi: get /v1/memories/{memory_id}/history/
|
||||
---
|
||||
@@ -0,0 +1,4 @@
|
||||
---
|
||||
title: 'Update Memory'
|
||||
openapi: put /v1/memories/{memory_id}/
|
||||
---
|
||||
@@ -0,0 +1,4 @@
|
||||
---
|
||||
title: 'V1 Get Memories'
|
||||
openapi: get /v1/memories/
|
||||
---
|
||||
@@ -0,0 +1,4 @@
|
||||
---
|
||||
title: 'V1 Search Memories'
|
||||
openapi: post /v1/memories/search/
|
||||
---
|
||||
@@ -0,0 +1,74 @@
|
||||
---
|
||||
title: 'V2 Get Memories'
|
||||
openapi: post /v2/memories/
|
||||
---
|
||||
|
||||
|
||||
Mem0 offers two versions of the get memories API: v1 and v2. Here's how they differ:
|
||||
|
||||
<Tabs>
|
||||
<Tab title="v1 Get Memories">
|
||||
<CodeGroup>
|
||||
```python Code
|
||||
memories = m.get_all(user_id="alex")
|
||||
```
|
||||
|
||||
```json Output
|
||||
[
|
||||
{
|
||||
"id":"f38b689d-6b24-45b7-bced-17fbb4d8bac7",
|
||||
"memory":"travelling to Paris",
|
||||
"user_id":"alex",
|
||||
"hash":"62bc074f56d1f909f1b4c2b639f56f6a",
|
||||
"metadata":null,
|
||||
"created_at":"2023-02-25T23:57:00.108347-07:00",
|
||||
"updated_at":"2024-07-25T23:57:00.108367-07:00"
|
||||
}
|
||||
]
|
||||
```
|
||||
</CodeGroup>
|
||||
</Tab>
|
||||
|
||||
<Tab title="v2 Get Memories">
|
||||
<CodeGroup>
|
||||
```python Code
|
||||
memories = m.get_all(
|
||||
filters={
|
||||
"AND": [
|
||||
{
|
||||
"user_id": "alex"
|
||||
},
|
||||
{
|
||||
"created_at": {
|
||||
"gte": "2024-07-01",
|
||||
"lte": "2024-07-31"
|
||||
}
|
||||
}
|
||||
]
|
||||
},
|
||||
version="v2"
|
||||
)
|
||||
```
|
||||
|
||||
```json Output
|
||||
[
|
||||
{
|
||||
"id":"f38b689d-6b24-45b7-bced-17fbb4d8bac7",
|
||||
"memory":"Name: Alex. Vegetarian. Allergic to nuts.",
|
||||
"user_id":"alex",
|
||||
"hash":"62bc074f56d1f909f1b4c2b639f56f6a",
|
||||
"metadata":null,
|
||||
"created_at":"2024-07-25T23:57:00.108347-07:00",
|
||||
"updated_at":"2024-07-25T23:57:00.108367-07:00"
|
||||
}
|
||||
]
|
||||
```
|
||||
</CodeGroup>
|
||||
</Tab>
|
||||
</Tabs>
|
||||
|
||||
Key difference between v1 and v2 get memories:
|
||||
|
||||
• **Filters**: v2 allows you to apply filters to narrow down memory retrieval based on specific criteria. This includes support for complex logical operations (AND, OR) and comparison operators (IN, gte, lte, gt, lt, ne, icontains) for advanced filtering capabilities.
|
||||
|
||||
The v2 get memories API is more powerful and flexible, allowing for more precise memory retrieval without the need for a search query.
|
||||
@@ -0,0 +1,83 @@
|
||||
---
|
||||
title: 'V2 Search Memories'
|
||||
openapi: post /v2/memories/search/
|
||||
---
|
||||
|
||||
Mem0 offers two versions of the search API: v1 and v2. Here's how they differ:
|
||||
|
||||
<Tabs>
|
||||
<Tab title="v1 Search">
|
||||
<CodeGroup>
|
||||
```python Code
|
||||
related_memories = m.search(query="What are Alice's hobbies?", user_id="alice")
|
||||
```
|
||||
|
||||
```json Output
|
||||
[
|
||||
{
|
||||
"id":"ea925981-272f-40dd-b576-be64e4871429",
|
||||
"memory":"Likes to play cricket and plays cricket on weekends.",
|
||||
"metadata":{
|
||||
"category":"hobbies"
|
||||
},
|
||||
"score":0.32116443111457704,
|
||||
"created_at":"2024-07-26T10:29:36.630547-07:00",
|
||||
"updated_at":"None",
|
||||
"user_id":"alice"
|
||||
}
|
||||
]
|
||||
```
|
||||
</CodeGroup>
|
||||
</Tab>
|
||||
|
||||
<Tab title="v2 Search">
|
||||
<CodeGroup>
|
||||
```python Code
|
||||
related_memories = m.vsearch(
|
||||
query="What are Alice's hobbies?",
|
||||
filters={
|
||||
"AND":[
|
||||
{
|
||||
"user_id":"alice"
|
||||
},
|
||||
{
|
||||
"agent_id":{
|
||||
"in":[
|
||||
"travelling",
|
||||
"sports"
|
||||
]
|
||||
}
|
||||
}
|
||||
]
|
||||
},
|
||||
version="v2"
|
||||
)
|
||||
```
|
||||
|
||||
```json Output
|
||||
{
|
||||
"memories": [
|
||||
{
|
||||
"id": "ea925981-272f-40dd-b576-be64e4871429",
|
||||
"memory": "Likes to play cricket and plays cricket on weekends.",
|
||||
"metadata": {
|
||||
"category": "hobbies"
|
||||
},
|
||||
"score": 0.32116443111457704,
|
||||
"created_at": "2024-07-26T10:29:36.630547-07:00",
|
||||
"updated_at": null,
|
||||
"user_id": "alice",
|
||||
"agent_id": "sports"
|
||||
}
|
||||
],
|
||||
}
|
||||
```
|
||||
</CodeGroup>
|
||||
</Tab>
|
||||
</Tabs>
|
||||
|
||||
Key difference between v1 and v2 search:
|
||||
|
||||
• **Filters**: v2 allows you to apply filters to narrow down search results based on specific criteria. This includes support for complex logical operations (AND, OR) and comparison operators (IN, gte, lte, gt, lt, ne, icontains) for advanced filtering capabilities.
|
||||
|
||||
The v2 search API is more powerful and flexible, allowing for more precise memory retrieval.
|
||||
@@ -0,0 +1,9 @@
|
||||
---
|
||||
title: 'Add Member'
|
||||
openapi: post /api/v1/orgs/organizations/{org_id}/members/
|
||||
---
|
||||
|
||||
The API provides two roles for organization members:
|
||||
|
||||
- `READER`: Allows viewing of organization resources.
|
||||
- `OWNER`: Grants full administrative access to manage the organization and its resources.
|
||||
@@ -0,0 +1,4 @@
|
||||
---
|
||||
title: 'Create Organization'
|
||||
openapi: post /api/v1/orgs/organizations/
|
||||
---
|
||||
@@ -0,0 +1,4 @@
|
||||
---
|
||||
title: 'Delete Member'
|
||||
openapi: delete /api/v1/orgs/organizations/{org_id}/members/
|
||||
---
|
||||
@@ -0,0 +1,4 @@
|
||||
---
|
||||
title: 'Delete Organization'
|
||||
openapi: delete /api/v1/orgs/organizations/{org_id}/
|
||||
---
|
||||
@@ -0,0 +1,4 @@
|
||||
---
|
||||
title: 'Get Members'
|
||||
openapi: get /api/v1/orgs/organizations/{org_id}/members/
|
||||
---
|
||||
@@ -0,0 +1,4 @@
|
||||
---
|
||||
title: 'Get Organization'
|
||||
openapi: get /api/v1/orgs/organizations/{org_id}/
|
||||
---
|
||||
@@ -0,0 +1,4 @@
|
||||
---
|
||||
title: 'Get Organizations'
|
||||
openapi: get /api/v1/orgs/organizations/
|
||||
---
|
||||
@@ -0,0 +1,9 @@
|
||||
---
|
||||
title: 'Update Member'
|
||||
openapi: put /api/v1/orgs/organizations/{org_id}/members/
|
||||
---
|
||||
|
||||
The API provides two roles for organization members:
|
||||
|
||||
- `READER`: Allows viewing of organization resources.
|
||||
- `OWNER`: Grants full administrative access to manage the organization and its resources.
|
||||
@@ -0,0 +1,71 @@
|
||||
---
|
||||
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.
|
||||
|
||||
## Key Features
|
||||
|
||||
- **Memory Management**: Add, retrieve, update, and delete memories with ease.
|
||||
- **Entity-based Operations**: Perform operations on memories associated with specific users, agents, apps, or runs.
|
||||
- **Advanced Search**: Utilize our search API to find relevant memories based on various criteria.
|
||||
- **History Tracking**: Access the history of memory interactions for comprehensive analysis.
|
||||
- **User Management**: Manage user entities and their associated memories.
|
||||
|
||||
## API Structure
|
||||
|
||||
Our API is organized into several main categories:
|
||||
|
||||
1. **Memory APIs**: Core operations for managing individual memories and collections.
|
||||
2. **Entities APIs**: Manage different entity types (users, agents, etc.) and their associated memories.
|
||||
3. **Search API**: Advanced search functionality to retrieve relevant memories.
|
||||
4. **History API**: Track and retrieve the history of memory interactions.
|
||||
|
||||
## Authentication
|
||||
|
||||
All API requests require authentication using HTTP Basic Auth. Ensure you include your API key in the Authorization header of each request.
|
||||
|
||||
## Organizations and projects (optional)
|
||||
|
||||
Organizations and projects provide the following capabilities:
|
||||
|
||||
- **Multi-org/project Support**: Specify organization and project when initializing the Mem0 client to attribute API usage appropriately
|
||||
- **Member Management**: Control access to data through organization and project membership
|
||||
- **Access Control**: Only members can access memories and data within their organization/project scope
|
||||
- **Team Isolation**: Maintain data separation between different teams and projects for secure collaboration
|
||||
|
||||
Example with the mem0 Python package:
|
||||
|
||||
```python
|
||||
from mem0 import MemoryClient
|
||||
|
||||
# Recommended: Using organization and project IDs
|
||||
client = MemoryClient(
|
||||
org_id='YOUR_ORG_ID', # It can be found on the organization settings page in dashboard
|
||||
project_id='YOUR_PROJECT_ID',
|
||||
)
|
||||
```
|
||||
|
||||
Example with the mem0 Node.js package:
|
||||
|
||||
```javascript
|
||||
import { MemoryClient } from "mem0ai";
|
||||
|
||||
# Recommended: Using organization and project IDs
|
||||
const client = new MemoryClient({
|
||||
organizationId: "YOUR_ORG_ID",
|
||||
projectId: "YOUR_PROJECT_ID"
|
||||
});
|
||||
```
|
||||
|
||||
## Getting Started
|
||||
|
||||
To begin using the Mem0 API, you'll need to:
|
||||
|
||||
1. Sign up for a [Mem0 account](https://app.mem0.ai) and obtain your API key.
|
||||
2. Familiarize yourself with the API endpoints and their functionalities.
|
||||
3. Make your first API call to add or retrieve a memory.
|
||||
|
||||
Explore the detailed documentation for each API endpoint to learn more about request/response formats, parameters, and example usage.
|
||||
@@ -0,0 +1,9 @@
|
||||
---
|
||||
title: 'Add Member'
|
||||
openapi: post /api/v1/orgs/organizations/{org_id}/projects/{project_id}/members/
|
||||
---
|
||||
|
||||
The API provides two roles for project members:
|
||||
|
||||
- `READER`: Allows viewing of project resources.
|
||||
- `OWNER`: Grants full administrative access to manage the project and its resources.
|
||||
@@ -0,0 +1,4 @@
|
||||
---
|
||||
title: 'Create Project'
|
||||
openapi: post /api/v1/orgs/organizations/{org_id}/projects/
|
||||
---
|
||||
@@ -0,0 +1,4 @@
|
||||
---
|
||||
title: 'Delete Member'
|
||||
openapi: delete /api/v1/orgs/organizations/{org_id}/projects/{project_id}/members/
|
||||
---
|
||||
@@ -0,0 +1,4 @@
|
||||
---
|
||||
title: 'Delete Project'
|
||||
openapi: delete /api/v1/orgs/organizations/{org_id}/projects/{project_id}/
|
||||
---
|
||||
@@ -0,0 +1,4 @@
|
||||
---
|
||||
title: 'Get Members'
|
||||
openapi: get /api/v1/orgs/organizations/{org_id}/projects/{project_id}/members/
|
||||
---
|
||||
@@ -0,0 +1,4 @@
|
||||
---
|
||||
title: 'Get Project'
|
||||
openapi: get /api/v1/orgs/organizations/{org_id}/projects/{project_id}/
|
||||
---
|
||||
@@ -0,0 +1,4 @@
|
||||
---
|
||||
title: 'Get Projects'
|
||||
openapi: get /api/v1/orgs/organizations/{org_id}/projects/
|
||||
---
|
||||
@@ -0,0 +1,9 @@
|
||||
---
|
||||
title: 'Update Member'
|
||||
openapi: put /api/v1/orgs/organizations/{org_id}/projects/{project_id}/members/
|
||||
---
|
||||
|
||||
The API provides two roles for project members:
|
||||
|
||||
- `READER`: Allows viewing of project resources.
|
||||
- `OWNER`: Grants full administrative access to manage the project and its resources.
|
||||
@@ -0,0 +1,4 @@
|
||||
---
|
||||
title: 'Update Project'
|
||||
openapi: patch /api/v1/orgs/organizations/{org_id}/projects/{project_id}/
|
||||
---
|
||||
@@ -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:
|
||||
|
||||
@@ -48,8 +52,12 @@ Here's a comprehensive list of all parameters that can be used across different
|
||||
| `model` | Embedding model to use |
|
||||
| `api_key` | API key of the provider |
|
||||
| `embedding_dims` | Dimensions of the embedding model |
|
||||
| `http_client_proxies` | Allow proxy server settings |
|
||||
| `ollama_base_url` | Base URL for the Ollama embedding model |
|
||||
| `model_kwargs` | Key-Value arguments for the Huggingface embedding model |
|
||||
| `azure_kwargs` | Key-Value arguments for the AzureOpenAI embedding model |
|
||||
| `openai_base_url` | Base URL for OpenAI API | OpenAI |
|
||||
| `vertex_credentials_json` | Path to the Google Cloud credentials JSON file for VertexAI |
|
||||
|
||||
|
||||
## Supported Embedding Models
|
||||
|
||||
@@ -1,4 +1,8 @@
|
||||
To use Azure OpenAI embedding models, set the `AZURE_OPENAI_API_KEY` environment variable. You can obtain the Azure OpenAI API key from the Azure.
|
||||
---
|
||||
title: Azure OpenAI
|
||||
---
|
||||
|
||||
To use Azure OpenAI embedding models, set the `EMBEDDING_AZURE_OPENAI_API_KEY`, `EMBEDDING_AZURE_DEPLOYMENT`, `EMBEDDING_AZURE_ENDPOINT` and `EMBEDDING_AZURE_API_VERSION` environment variables. You can obtain the Azure OpenAI API key from the Azure.
|
||||
|
||||
### Usage
|
||||
|
||||
@@ -6,8 +10,12 @@ To use Azure OpenAI embedding models, set the `AZURE_OPENAI_API_KEY` environment
|
||||
import os
|
||||
from mem0 import Memory
|
||||
|
||||
os.environ["OPENAI_API_KEY"] = "your_api_key"
|
||||
os.environ["AZURE_OPENAI_API_KEY"] = "your_api_key"
|
||||
os.environ["EMBEDDING_AZURE_OPENAI_API_KEY"] = "your-api-key"
|
||||
os.environ["EMBEDDING_AZURE_DEPLOYMENT"] = "your-deployment-name"
|
||||
os.environ["EMBEDDING_AZURE_ENDPOINT"] = "your-api-base-url"
|
||||
os.environ["EMBEDDING_AZURE_API_VERSION"] = "version-to-use"
|
||||
|
||||
os.environ["OPENAI_API_KEY"] = "your_api_key" # For LLM
|
||||
|
||||
|
||||
config = {
|
||||
@@ -15,6 +23,15 @@ config = {
|
||||
"provider": "azure_openai",
|
||||
"config": {
|
||||
"model": "text-embedding-3-large"
|
||||
"azure_kwargs": {
|
||||
"api_version": "",
|
||||
"azure_deployment": "",
|
||||
"azure_endpoint": "",
|
||||
"api_key": "",
|
||||
"default_headers": {
|
||||
"CustomHeader": "your-custom-header",
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -31,4 +48,4 @@ Here are the parameters available for configuring Azure OpenAI embedder:
|
||||
| --- | --- | --- |
|
||||
| `model` | The name of the embedding model to use | `text-embedding-3-small` |
|
||||
| `embedding_dims` | Dimensions of the embedding model | `1536` |
|
||||
| `api_key` | The Azure OpenAI API key | `None` |
|
||||
| `azure_kwargs` | The Azure OpenAI configs | `config_keys` |
|
||||
|
||||
@@ -0,0 +1,37 @@
|
||||
---
|
||||
title: Gemini
|
||||
---
|
||||
|
||||
To use Gemini embedding models, set the `GOOGLE_API_KEY` environment variables. You can obtain the Gemini API key from [here](https://aistudio.google.com/app/apikey).
|
||||
|
||||
### Usage
|
||||
|
||||
```python
|
||||
import os
|
||||
from mem0 import Memory
|
||||
|
||||
os.environ["GOOGLE_API_KEY"] = "key"
|
||||
os.environ["OPENAI_API_KEY"] = "your_api_key" # For LLM
|
||||
|
||||
config = {
|
||||
"embedder": {
|
||||
"provider": "gemini",
|
||||
"config": {
|
||||
"model": "models/text-embedding-004",
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
m = Memory.from_config(config)
|
||||
m.add("I'm visiting Paris", user_id="john")
|
||||
```
|
||||
|
||||
### Config
|
||||
|
||||
Here are the parameters available for configuring Gemini embedder:
|
||||
|
||||
| Parameter | Description | Default Value |
|
||||
| --- | --- | --- |
|
||||
| `model` | The name of the embedding model to use | `models/text-embedding-004` |
|
||||
| `embedding_dims` | Dimensions of the embedding model | `768` |
|
||||
| `api_key` | The Gemini API key | `None` |
|
||||
@@ -1,3 +1,7 @@
|
||||
---
|
||||
title: Hugging Face
|
||||
---
|
||||
|
||||
You can use embedding models from Huggingface to run Mem0 locally.
|
||||
|
||||
### Usage
|
||||
@@ -6,7 +10,7 @@ You can use embedding models from Huggingface to run Mem0 locally.
|
||||
import os
|
||||
from mem0 import Memory
|
||||
|
||||
os.environ["OPENAI_API_KEY"] = "your_api_key"
|
||||
os.environ["OPENAI_API_KEY"] = "your_api_key" # For LLM
|
||||
|
||||
config = {
|
||||
"embedder": {
|
||||
|
||||
@@ -6,7 +6,7 @@ You can use embedding models from Ollama to run Mem0 locally.
|
||||
import os
|
||||
from mem0 import Memory
|
||||
|
||||
os.environ["OPENAI_API_KEY"] = "your_api_key"
|
||||
os.environ["OPENAI_API_KEY"] = "your_api_key" # For LLM
|
||||
|
||||
config = {
|
||||
"embedder": {
|
||||
|
||||
@@ -1,3 +1,7 @@
|
||||
---
|
||||
title: OpenAI
|
||||
---
|
||||
|
||||
To use OpenAI embedding models, set the `OPENAI_API_KEY` environment variable. You can obtain the OpenAI API key from the [OpenAI Platform](https://platform.openai.com/account/api-keys).
|
||||
|
||||
### Usage
|
||||
|
||||
@@ -0,0 +1,39 @@
|
||||
---
|
||||
title: Together
|
||||
---
|
||||
|
||||
To use Together embedding models, set the `TOGETHER_API_KEY` environment variable. You can obtain the Together API key from the [Together Platform](https://api.together.xyz/settings/api-keys).
|
||||
|
||||
### Usage
|
||||
|
||||
<Note> The `embedding_model_dims` parameter for `vector_store` should be set to `768` for Together embedder. </Note>
|
||||
|
||||
```python
|
||||
import os
|
||||
from mem0 import Memory
|
||||
|
||||
os.environ["TOGETHER_API_KEY"] = "your_api_key"
|
||||
os.environ["OPENAI_API_KEY"] = "your_api_key" # For LLM
|
||||
|
||||
config = {
|
||||
"embedder": {
|
||||
"provider": "together",
|
||||
"config": {
|
||||
"model": "togethercomputer/m2-bert-80M-8k-retrieval"
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
m = Memory.from_config(config)
|
||||
m.add("I'm visiting Paris", user_id="john")
|
||||
```
|
||||
|
||||
### Config
|
||||
|
||||
Here are the parameters available for configuring Together embedder:
|
||||
|
||||
| Parameter | Description | Default Value |
|
||||
| --- | --- | --- |
|
||||
| `model` | The name of the embedding model to use | `togethercomputer/m2-bert-80M-8k-retrieval` |
|
||||
| `embedding_dims` | Dimensions of the embedding model | `768` |
|
||||
| `api_key` | The Together API key | `None` |
|
||||
@@ -0,0 +1,36 @@
|
||||
### Vertex AI
|
||||
|
||||
To use Google Cloud's Vertex AI for text embedding models, set the `GOOGLE_APPLICATION_CREDENTIALS` environment variable to point to the path of your service account's credentials JSON file. These credentials can be created in the [Google Cloud Console](https://console.cloud.google.com/).
|
||||
|
||||
### Usage
|
||||
|
||||
```python
|
||||
import os
|
||||
from mem0 import Memory
|
||||
|
||||
# Set the path to your Google Cloud credentials JSON file
|
||||
os.environ["GOOGLE_APPLICATION_CREDENTIALS"] = "/path/to/your/credentials.json"
|
||||
os.environ["OPENAI_API_KEY"] = "your_api_key" # For LLM
|
||||
|
||||
config = {
|
||||
"embedder": {
|
||||
"provider": "vertexai",
|
||||
"config": {
|
||||
"model": "text-embedding-004"
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
m = Memory.from_config(config)
|
||||
m.add("I'm visiting Paris", user_id="john")
|
||||
```
|
||||
|
||||
### Config
|
||||
|
||||
Here are the parameters available for configuring the Vertex AI embedder:
|
||||
|
||||
| Parameter | Description | Default Value |
|
||||
| ------------------------- | ------------------------------------------------ | -------------------- |
|
||||
| `model` | The name of the Vertex AI embedding model to use | `text-embedding-004` |
|
||||
| `vertex_credentials_json` | Path to the Google Cloud credentials JSON file | `None` |
|
||||
| `embedding_dims` | Dimensions of the embedding model | `256` |
|
||||
@@ -1,15 +1,27 @@
|
||||
---
|
||||
title: Overview
|
||||
icon: "info"
|
||||
iconType: "solid"
|
||||
---
|
||||
|
||||
Mem0 offers support for various embedding models, allowing users to choose the one that best suits their needs.
|
||||
|
||||
## Supported Embedders
|
||||
|
||||
See the list of supported embedders below.
|
||||
|
||||
<CardGroup cols={4}>
|
||||
<Card title="OpenAI" href="/components/embedders/models/openai"></Card>
|
||||
<Card title="Azure OpenAI" href="/components/embedders/models/azure_openai"></Card>
|
||||
<Card title="Ollama" href="/components/embedders/models/ollama"></Card>
|
||||
<Card title="Hugging Face" href="/components/embedders/models/huggingface"></Card>
|
||||
<Card title="Gemini" href="/components/embedders/models/gemini"></Card>
|
||||
<Card title="Vertex AI" href="/components/embedders/models/vertexai"></Card>
|
||||
<Card title="Together" href="/components/embedders/models/together"></Card>
|
||||
</CardGroup>
|
||||
|
||||
## Usage
|
||||
|
||||
To utilize a embedder, you must provide a configuration to customize its usage. If no configuration is supplied, a default configuration will be applied, and `OpenAI` will be used as the embedder.
|
||||
|
||||
For a comprehensive list of available parameters for embedder configuration, please refer to [Config](./config).
|
||||
|
||||
To view all supported embedders, visit the [Supported embedders](./models).
|
||||
|
||||
|
||||
|
||||
@@ -1,14 +1,26 @@
|
||||
## 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
|
||||
|
||||
### Config Values Precedence
|
||||
|
||||
Config values are applied in the following order of precedence (from highest to lowest):
|
||||
|
||||
1. Values explicitly set in the `config` dictionary
|
||||
2. Environment variables (e.g., `OPENAI_API_KEY`, `OPENAI_API_BASE`)
|
||||
3. Default values defined in the LLM implementation
|
||||
|
||||
This means that values specified in the `config` dictionary will override corresponding environment variables, which in turn override default values.
|
||||
|
||||
## How to Use Config
|
||||
|
||||
Here's a general example of how to use the config with mem0:
|
||||
@@ -53,12 +65,16 @@ Here's the table based on the provided parameters:
|
||||
| `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 |
|
||||
|
||||
|
||||
## Supported LLMs
|
||||
|
||||
@@ -11,9 +11,9 @@ os.environ["ANTHROPIC_API_KEY"] = "your-api-key"
|
||||
|
||||
config = {
|
||||
"llm": {
|
||||
"provider": "litellm",
|
||||
"provider": "anthropic",
|
||||
"config": {
|
||||
"model": "claude-3-opus-20240229",
|
||||
"model": "claude-3-5-sonnet-latest",
|
||||
"temperature": 0.1,
|
||||
"max_tokens": 2000,
|
||||
}
|
||||
|
||||
@@ -1,3 +1,7 @@
|
||||
---
|
||||
title: AWS Bedrock
|
||||
---
|
||||
|
||||
### Setup
|
||||
- Before using the AWS Bedrock LLM, make sure you have the appropriate model access from [Bedrock Console](https://us-east-1.console.aws.amazon.com/bedrock/home?region=us-east-1#/modelaccess).
|
||||
- You will also need to authenticate the `boto3` client by using a method in the [AWS documentation](https://boto3.amazonaws.com/v1/documentation/api/latest/guide/credentials.html#configuring-credentials)
|
||||
|
||||
@@ -1,4 +1,8 @@
|
||||
To use Azure OpenAI models, you have to set the `AZURE_OPENAI_API_KEY`, `AZURE_OPENAI_ENDPOINT`, and `OPENAI_API_VERSION` environment variables. You can obtain the Azure API key from the [Azure](https://azure.microsoft.com/).
|
||||
---
|
||||
title: Azure OpenAI
|
||||
---
|
||||
|
||||
To use Azure OpenAI models, you have to set the `LLM_AZURE_OPENAI_API_KEY`, `LLM_AZURE_ENDPOINT`, `LLM_AZURE_DEPLOYMENT` and `LLM_AZURE_API_VERSION` environment variables. You can obtain the Azure API key from the [Azure](https://azure.microsoft.com/).
|
||||
|
||||
## Usage
|
||||
|
||||
@@ -6,9 +10,10 @@ To use Azure OpenAI models, you have to set the `AZURE_OPENAI_API_KEY`, `AZURE_O
|
||||
import os
|
||||
from mem0 import Memory
|
||||
|
||||
os.environ["AZURE_OPENAI_API_KEY"] = "your-api-key"
|
||||
os.environ["AZURE_OPENAI_ENDPOINT"] = "your-api-base-url"
|
||||
os.environ["OPENAI_API_VERSION"] = "version-to-use"
|
||||
os.environ["LLM_AZURE_OPENAI_API_KEY"] = "your-api-key"
|
||||
os.environ["LLM_AZURE_DEPLOYMENT"] = "your-deployment-name"
|
||||
os.environ["LLM_AZURE_ENDPOINT"] = "your-api-base-url"
|
||||
os.environ["LLM_AZURE_API_VERSION"] = "version-to-use"
|
||||
|
||||
config = {
|
||||
"llm": {
|
||||
@@ -17,6 +22,15 @@ config = {
|
||||
"model": "your-deployment-name",
|
||||
"temperature": 0.1,
|
||||
"max_tokens": 2000,
|
||||
"azure_kwargs": {
|
||||
"azure_deployment": "",
|
||||
"api_version": "",
|
||||
"azure_endpoint": "",
|
||||
"api_key": "",
|
||||
"default_headers": {
|
||||
"CustomHeader": "your-custom-header",
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -25,6 +39,38 @@ m = Memory.from_config(config)
|
||||
m.add("Likes to play cricket on weekends", user_id="alice", metadata={"category": "hobbies"})
|
||||
```
|
||||
|
||||
We also support the new [OpenAI structured-outputs](https://platform.openai.com/docs/guides/structured-outputs/introduction) model.
|
||||
|
||||
```python
|
||||
import os
|
||||
from mem0 import Memory
|
||||
|
||||
os.environ["LLM_AZURE_OPENAI_API_KEY"] = "your-api-key"
|
||||
os.environ["LLM_AZURE_DEPLOYMENT"] = "your-deployment-name"
|
||||
os.environ["LLM_AZURE_ENDPOINT"] = "your-api-base-url"
|
||||
os.environ["LLM_AZURE_API_VERSION"] = "version-to-use"
|
||||
|
||||
config = {
|
||||
"llm": {
|
||||
"provider": "azure_openai_structured",
|
||||
"config": {
|
||||
"model": "your-deployment-name",
|
||||
"temperature": 0.1,
|
||||
"max_tokens": 2000,
|
||||
"azure_kwargs": {
|
||||
"azure_deployment": "",
|
||||
"api_version": "",
|
||||
"azure_endpoint": "",
|
||||
"api_key": "",
|
||||
"default_headers": {
|
||||
"CustomHeader": "your-custom-header",
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
## Config
|
||||
|
||||
All available parameters for the `azure_openai` config are present in [Master List of All Params in Config](../config).
|
||||
All available parameters for the `azure_openai` config are present in [Master List of All Params in Config](../config).
|
||||
|
||||
@@ -0,0 +1,49 @@
|
||||
---
|
||||
title: DeepSeek
|
||||
---
|
||||
|
||||
To use DeepSeek LLM models, you have to set the `DEEPSEEK_API_KEY` environment variable. You can also optionally set `DEEPSEEK_API_BASE` if you need to use a different API endpoint (defaults to "https://api.deepseek.com").
|
||||
|
||||
## Usage
|
||||
|
||||
```python
|
||||
import os
|
||||
from mem0 import Memory
|
||||
|
||||
os.environ["DEEPSEEK_API_KEY"] = "your-api-key"
|
||||
os.environ["OPENAI_API_KEY"] = "your-api-key" # for embedder model
|
||||
|
||||
config = {
|
||||
"llm": {
|
||||
"provider": "deepseek",
|
||||
"config": {
|
||||
"model": "deepseek-chat", # default model
|
||||
"temperature": 0.2,
|
||||
"max_tokens": 1500,
|
||||
"top_p": 1.0
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
m = Memory.from_config(config)
|
||||
m.add("Likes to play cricket on weekends", user_id="alice", metadata={"category": "hobbies"})
|
||||
```
|
||||
|
||||
You can also configure the API base URL in the config:
|
||||
|
||||
```python
|
||||
config = {
|
||||
"llm": {
|
||||
"provider": "deepseek",
|
||||
"config": {
|
||||
"model": "deepseek-chat",
|
||||
"deepseek_base_url": "https://your-custom-endpoint.com",
|
||||
"api_key": "your-api-key" # alternatively to using environment variable
|
||||
}
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
## Config
|
||||
|
||||
All available parameters for the `deepseek` config are present in [Master List of All Params in Config](../config).
|
||||
@@ -0,0 +1,33 @@
|
||||
---
|
||||
title: Gemini
|
||||
---
|
||||
|
||||
To use Gemini model, you have to set the `GEMINI_API_KEY` environment variable. You can obtain the Gemini API key from the [Google AI Studio](https://aistudio.google.com/app/apikey)
|
||||
|
||||
## Usage
|
||||
|
||||
```python
|
||||
import os
|
||||
from mem0 import Memory
|
||||
|
||||
os.environ["OPENAI_API_KEY"] = "your-api-key" # used for embedding model
|
||||
os.environ["GEMINI_API_KEY"] = "your-api-key"
|
||||
|
||||
config = {
|
||||
"llm": {
|
||||
"provider": "gemini",
|
||||
"config": {
|
||||
"model": "gemini-1.5-flash-latest",
|
||||
"temperature": 0.2,
|
||||
"max_tokens": 1500,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
m = Memory.from_config(config)
|
||||
m.add("Likes to play cricket on weekends", user_id="alice", metadata={"category": "hobbies"})
|
||||
```
|
||||
|
||||
## Config
|
||||
|
||||
All available parameters for the `Gemini` config are present in [Master List of All Params in Config](../config).
|
||||
@@ -1,3 +1,7 @@
|
||||
---
|
||||
title: Google AI
|
||||
---
|
||||
|
||||
To use Google AI model, you have to set the `GOOGLE_API_KEY` environment variable. You can obtain the Google API key from the [Google Maker Suite](https://makersuite.google.com/app/apikey)
|
||||
|
||||
## Usage
|
||||
|
||||
@@ -12,7 +12,7 @@ config = {
|
||||
"llm": {
|
||||
"provider": "litellm",
|
||||
"config": {
|
||||
"model": "gpt-3.5-turbo",
|
||||
"model": "gpt-4o-mini",
|
||||
"temperature": 0.2,
|
||||
"max_tokens": 1500,
|
||||
}
|
||||
|
||||
@@ -1,3 +1,7 @@
|
||||
---
|
||||
title: Mistral AI
|
||||
---
|
||||
|
||||
To use mistral's models, please Obtain the Mistral AI api key from their [console](https://console.mistral.ai/). Set the `MISTRAL_API_KEY` environment variable to use the model as given below in the example.
|
||||
|
||||
## Usage
|
||||
|
||||
@@ -1,3 +1,7 @@
|
||||
---
|
||||
title: OpenAI
|
||||
---
|
||||
|
||||
To use OpenAI LLM models, you have to set the `OPENAI_API_KEY` environment variable. You can obtain the OpenAI API key from the [OpenAI Platform](https://platform.openai.com/account/api-keys).
|
||||
|
||||
## Usage
|
||||
@@ -34,6 +38,29 @@ m = Memory.from_config(config)
|
||||
m.add("Likes to play cricket on weekends", user_id="alice", metadata={"category": "hobbies"})
|
||||
```
|
||||
|
||||
We also support the new [OpenAI structured-outputs](https://platform.openai.com/docs/guides/structured-outputs/introduction) model.
|
||||
|
||||
```python
|
||||
import os
|
||||
from mem0 import Memory
|
||||
|
||||
os.environ["OPENAI_API_KEY"] = "your-api-key"
|
||||
|
||||
config = {
|
||||
"llm": {
|
||||
"provider": "openai_structured",
|
||||
"config": {
|
||||
"model": "gpt-4o-2024-08-06",
|
||||
"temperature": 0.0,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
m = Memory.from_config(config)
|
||||
```
|
||||
|
||||
|
||||
|
||||
## Config
|
||||
|
||||
All available parameters for the `openai` config are present in [Master List of All Params in Config](../config).
|
||||
@@ -11,7 +11,7 @@ os.environ["TOGETHER_API_KEY"] = "your-api-key"
|
||||
|
||||
config = {
|
||||
"llm": {
|
||||
"provider": "togetherai",
|
||||
"provider": "together",
|
||||
"config": {
|
||||
"model": "mistralai/Mixtral-8x7B-Instruct-v0.1",
|
||||
"temperature": 0.2,
|
||||
|
||||
@@ -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.
|
||||
@@ -11,3 +13,42 @@ To use a llm, you must provide a configuration to customize its usage. If no con
|
||||
For a comprehensive list of available parameters for llm configuration, please refer to [Config](./config).
|
||||
|
||||
To view all supported llms, visit the [Supported LLMs](./models).
|
||||
|
||||
<CardGroup cols={4}>
|
||||
<Card title="OpenAI" href="/components/llms/models/openai"></Card>
|
||||
<Card title="Ollama" href="/components/llms/models/ollama"></Card>
|
||||
<Card title="Azure OpenAI" href="/components/llms/models/azure_openai"></Card>
|
||||
<Card title="Anthropic" href="/components/llms/models/anthropic"></Card>
|
||||
<Card title="Together" href="/components/llms/models/together"></Card>
|
||||
<Card title="Groq" href="/components/llms/models/groq"></Card>
|
||||
<Card title="Litellm" href="/components/llms/models/litellm"></Card>
|
||||
<Card title="Mistral AI" href="/components/llms/models/mistral_ai"></Card>
|
||||
<Card title="Google AI" href="/components/llms/models/google_ai"></Card>
|
||||
<Card title="AWS bedrock" href="/components/llms/models/aws_bedrock"></Card>
|
||||
<Card title="Gemini" href="/components/llms/models/gemini"></Card>
|
||||
<Card title="DeepSeek" href="/components/llms/models/deepseek"></Card>
|
||||
</CardGroup>
|
||||
|
||||
## Structured vs Unstructured Outputs
|
||||
|
||||
Mem0 supports two types of OpenAI LLM formats, each with its own strengths and use cases:
|
||||
|
||||
### Structured Outputs
|
||||
|
||||
Structured outputs are LLMs that align with OpenAI's structured outputs model:
|
||||
|
||||
- **Optimized for:** Returning structured responses (e.g., JSON objects)
|
||||
- **Benefits:** Precise, easily parseable data
|
||||
- **Ideal for:** Data extraction, form filling, API responses
|
||||
- **Learn more:** [OpenAI Structured Outputs Guide](https://platform.openai.com/docs/guides/structured-outputs/introduction)
|
||||
|
||||
### Unstructured Outputs
|
||||
|
||||
Unstructured outputs correspond to OpenAI's standard, free-form text model:
|
||||
|
||||
- **Flexibility:** Returns open-ended, natural language responses
|
||||
- **Customization:** Use the `response_format` parameter to guide output
|
||||
- **Trade-off:** Less efficient than structured outputs for specific data needs
|
||||
- **Best for:** Creative writing, explanations, general conversation
|
||||
|
||||
Choose the format that best suits your application's requirements for optimal performance and usability.
|
||||
|
||||
@@ -1,12 +1,14 @@
|
||||
## 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")
|
||||
- `provider`: The name of the vector database (e.g., "chroma", "pgvector", "qdrant", "milvus","azure_ai_search")
|
||||
- `config`: A nested dictionary containing provider-specific settings
|
||||
|
||||
## How to Use Config
|
||||
|
||||
@@ -0,0 +1,38 @@
|
||||
[Azure AI Search](https://learn.microsoft.com/en-us/azure/search/search-what-is-azure-search/) (formerly known as "Azure Cognitive Search") provides secure information retrieval at scale over user-owned content in traditional and generative AI search applications.
|
||||
|
||||
### Usage
|
||||
|
||||
```python
|
||||
import os
|
||||
from mem0 import Memory
|
||||
|
||||
os.environ["OPENAI_API_KEY"] = "sk-xx" #this key is used for embedding purpose
|
||||
|
||||
config = {
|
||||
"vector_store": {
|
||||
"provider": "azure_ai_search",
|
||||
"config": {
|
||||
"service_name": "ai-search-test",
|
||||
"api_key": "*****",
|
||||
"collection_name": "mem0",
|
||||
"embedding_model_dims": 1536 ,
|
||||
"use_compression": False
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
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 `qdrant` config:
|
||||
service_name (str): Azure Cognitive Search service name.
|
||||
| Parameter | Description | Default Value |
|
||||
| --- | --- | --- |
|
||||
| `service_name` | Azure AI Search service name | `None` |
|
||||
| `api_key` | API key of the Azure AI Search service | `None` |
|
||||
| `collection_name` | The name of the collection/index to store the vectors, it will be created automatically if not exist | `mem0` |
|
||||
| `embedding_model_dims` | Dimensions of the embedding model | `1536` |
|
||||
| `use_compression` | Use scalar quantization vector compression | False |
|
||||
@@ -0,0 +1,58 @@
|
||||
[Elasticsearch](https://www.elastic.co/) is a distributed, RESTful search and analytics engine that can efficiently store and search vector data using dense vectors and k-NN search.
|
||||
|
||||
### Installation
|
||||
|
||||
Elasticsearch support requires additional dependencies. Install them with:
|
||||
|
||||
```bash
|
||||
pip install elasticsearch>=8.0.0
|
||||
```
|
||||
|
||||
### Usage
|
||||
|
||||
```python
|
||||
import os
|
||||
from mem0 import Memory
|
||||
|
||||
os.environ["OPENAI_API_KEY"] = "sk-xx"
|
||||
|
||||
config = {
|
||||
"vector_store": {
|
||||
"provider": "elasticsearch",
|
||||
"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 `elasticsearch` 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 Elasticsearch server is running | `localhost` |
|
||||
| `port` | The port where the Elasticsearch server is running | `9200` |
|
||||
| `cloud_id` | Cloud ID for Elastic Cloud deployment | `None` |
|
||||
| `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 | `True` |
|
||||
| `auto_create_index` | Whether to automatically create the index | `True` |
|
||||
|
||||
### Features
|
||||
|
||||
- Efficient vector search using Elasticsearch's native k-NN search
|
||||
- Support for both local and cloud deployments (Elastic Cloud)
|
||||
- Multiple authentication methods (Basic Auth, API Key)
|
||||
- Automatic index creation with optimized mappings for vector search
|
||||
- Memory isolation through payload filtering
|
||||
@@ -0,0 +1,35 @@
|
||||
[Milvus](https://milvus.io/) Milvus is an open-source vector database that suits AI applications of every size from running a demo chatbot in Jupyter notebook to building web-scale search that serves billions of users.
|
||||
|
||||
### Usage
|
||||
|
||||
```python
|
||||
import os
|
||||
from mem0 import Memory
|
||||
|
||||
config = {
|
||||
"vector_store": {
|
||||
"provider": "milvus",
|
||||
"config": {
|
||||
"collection_name": "test",
|
||||
"embedding_model_dims": "123",
|
||||
"url": "127.0.0.1",
|
||||
"token": "8e4b8ca8cf2c67",
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
m = Memory.from_config(config)
|
||||
m.add("Likes to play cricket on weekends", user_id="alice", metadata={"category": "hobbies"})
|
||||
```
|
||||
|
||||
### Config
|
||||
|
||||
Here's the parameters available for configuring Milvus Database:
|
||||
|
||||
| Parameter | Description | Default Value |
|
||||
| --- | --- | --- |
|
||||
| `url` | Full URL/Uri for Milvus/Zilliz server | `http://localhost:19530` |
|
||||
| `token` | Token for Zilliz server / for local setup defaults to None. | `None` |
|
||||
| `collection_name` | The name of the collection | `mem0` |
|
||||
| `embedding_model_dims` | Dimensions of the embedding model | `1536` |
|
||||
| `metric_type` | Metric type for similarity search | `L2` |
|
||||
@@ -30,10 +30,12 @@ Here's the parameters available for configuring pgvector:
|
||||
|
||||
| Parameter | Description | Default Value |
|
||||
| --- | --- | --- |
|
||||
| `dbname` | The name of the database | `postgres` |
|
||||
| `dbname` | The name of the | `postgres` |
|
||||
| `collection_name` | The name of the collection | `mem0` |
|
||||
| `embedding_model_dims` | Dimensions of the embedding model | `1536` |
|
||||
| `user` | User name to connect to the database | `None` |
|
||||
| `password` | Password to connect to the database | `None` |
|
||||
| `host` | The host where the Postgres server is running | `None` |
|
||||
| `port` | The port where the Postgres server is running | `None` |
|
||||
| `port` | The port where the Postgres server is running | `None` |
|
||||
| `diskann` | Whether to use diskann for vector similarity search (requires pgvectorscale) | `True` |
|
||||
| `hnsw` | Whether to use hnsw for vector similarity search | `False` |
|
||||
@@ -0,0 +1,44 @@
|
||||
[Redis](https://redis.io/) is a scalable, real-time database that can store, search, and analyze vector data.
|
||||
|
||||
### Installation
|
||||
```bash
|
||||
pip install redis redisvl
|
||||
```
|
||||
|
||||
Redis Stack using Docker:
|
||||
```bash
|
||||
docker run -d --name redis-stack -p 6379:6379 -p 8001:8001 redis/redis-stack:latest
|
||||
```
|
||||
|
||||
### Usage
|
||||
|
||||
```python
|
||||
import os
|
||||
from mem0 import Memory
|
||||
|
||||
os.environ["OPENAI_API_KEY"] = "sk-xx"
|
||||
|
||||
config = {
|
||||
"vector_store": {
|
||||
"provider": "redis",
|
||||
"config": {
|
||||
"collection_name": "mem0",
|
||||
"embedding_model_dims": 1536,
|
||||
"redis_url": "redis://localhost:6379"
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
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 `redis` config:
|
||||
|
||||
| Parameter | Description | Default Value |
|
||||
| --- | --- | --- |
|
||||
| `collection_name` | The name of the collection to store the vectors | `mem0` |
|
||||
| `embedding_model_dims` | Dimensions of the embedding model | `1536` |
|
||||
| `redis_url` | The URL of the Redis server | `None` |
|
||||
@@ -1,17 +1,31 @@
|
||||
---
|
||||
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.
|
||||
|
||||
## Supported Vector Databases
|
||||
|
||||
See the list of supported vector databases below.
|
||||
|
||||
<CardGroup cols={3}>
|
||||
<Card title="Qdrant" href="/components/vectordbs/dbs/qdrant"></Card>
|
||||
<Card title="Chroma" href="/components/vectordbs/dbs/chroma"></Card>
|
||||
<Card title="Pgvector" href="/components/vectordbs/dbs/pgvector"></Card>
|
||||
<Card title="Milvus" href="/components/vectordbs/dbs/milvus"></Card>
|
||||
<Card title="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>
|
||||
</CardGroup>
|
||||
|
||||
## Usage
|
||||
|
||||
To utilize a vector database, you must provide a configuration to customize its usage. If no configuration is supplied, a default configuration will be applied, and `Qdrant` will be used as the vector database.
|
||||
|
||||
For a comprehensive list of available parameters for vector database configuration, please refer to [Config](./config).
|
||||
|
||||
To view all supported vector databases, visit the [Supported Vector Databases](./dbs).
|
||||
|
||||
## Common issues
|
||||
|
||||
### Using model with different dimensions
|
||||
@@ -22,3 +36,4 @@ for example 768, you may encounter below error:
|
||||
`ValueError: shapes (0,1536) and (768,) not aligned: 1536 (dim 1) != 768 (dim 0)`
|
||||
|
||||
you could add `"embedding_model_dims": 768,` to the config of the vector_store to overcome this issue.
|
||||
|
||||
|
||||
+296
@@ -0,0 +1,296 @@
|
||||
{
|
||||
"$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": "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"
|
||||
]
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
"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"
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,123 +0,0 @@
|
||||
---
|
||||
title: LangGraph with Mem0
|
||||
---
|
||||
|
||||
This guide demonstrates how to create a personalized Customer Support AI Agent using LangGraph and Mem0. The agent retains information across interactions, enabling a personalized and efficient support experience.
|
||||
|
||||
## Overview
|
||||
The Customer Support AI Agent leverages LangGraph for conversational flow and Mem0 for memory retention, creating a more context-aware and personalized support experience.
|
||||
|
||||
## Setup
|
||||
Install the necessary packages using pip:
|
||||
|
||||
```bash
|
||||
pip install langgraph langchain-openai mem0ai
|
||||
```
|
||||
|
||||
## Full Code Example
|
||||
Below is the complete code to create and interact with a Customer Support AI Agent using LangGraph and Mem0:
|
||||
|
||||
```python
|
||||
from typing import Annotated, TypedDict, List
|
||||
from langgraph.graph import StateGraph, START
|
||||
from langgraph.graph.message import add_messages
|
||||
from langchain_openai import ChatOpenAI
|
||||
from mem0 import Memory
|
||||
from langchain_core.messages import SystemMessage, HumanMessage, AIMessage
|
||||
|
||||
llm = ChatOpenAI(model="gpt-4o")
|
||||
mem0 = Memory()
|
||||
|
||||
# Define the State
|
||||
class State(TypedDict):
|
||||
messages: Annotated[List[HumanMessage | AIMessage], add_messages]
|
||||
mem0_user_id: str
|
||||
|
||||
graph = StateGraph(State)
|
||||
|
||||
|
||||
def chatbot(state: State):
|
||||
messages = state["messages"]
|
||||
user_id = state["mem0_user_id"]
|
||||
|
||||
# Retrieve relevant memories
|
||||
memories = mem0.search(messages[-1].content, user_id=user_id)
|
||||
|
||||
context = "Relevant information from previous conversations:\n"
|
||||
for memory in memories:
|
||||
context += f"- {memory['memory']}\n"
|
||||
|
||||
system_message = SystemMessage(content=f"""You are a helpful customer support assistant. Use the provided context to personalize your responses and remember user preferences and past interactions.
|
||||
{context}""")
|
||||
|
||||
full_messages = [system_message] + messages
|
||||
response = llm.invoke(full_messages)
|
||||
|
||||
# Store the interaction in Mem0
|
||||
mem0.add(f"User: {messages[-1].content}\nAssistant: {response.content}", user_id=user_id)
|
||||
return {"messages": [response]}
|
||||
|
||||
# Add nodes to the graph
|
||||
graph.add_node("chatbot", chatbot)
|
||||
|
||||
# Add edge from START to chatbot
|
||||
graph.add_edge(START, "chatbot")
|
||||
|
||||
# Add edge from chatbot back to itself
|
||||
graph.add_edge("chatbot", "chatbot")
|
||||
|
||||
compiled_graph = graph.compile()
|
||||
|
||||
def run_conversation(user_input: str, mem0_user_id: str):
|
||||
config = {"configurable": {"thread_id": mem0_user_id}}
|
||||
state = {"messages": [HumanMessage(content=user_input)], "mem0_user_id": mem0_user_id}
|
||||
|
||||
for event in compiled_graph.stream(state, config):
|
||||
for value in event.values():
|
||||
if value.get("messages"):
|
||||
print("Customer Support:", value["messages"][-1].content)
|
||||
return # Exit after printing the response
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
print("Welcome to Customer Support! How can I assist you today?")
|
||||
mem0_user_id = "test123"
|
||||
while True:
|
||||
user_input = input("You: ")
|
||||
if user_input.lower() in ['quit', 'exit', 'bye']:
|
||||
print("Customer Support: Thank you for contacting us. Have a great day!")
|
||||
break
|
||||
run_conversation(user_input, mem0_user_id)
|
||||
```
|
||||
|
||||
## Key Components
|
||||
|
||||
1. **State Definition**: The `State` class defines the structure of the conversation state, including messages and user ID.
|
||||
|
||||
2. **Chatbot Node**: The `chatbot` function handles the core logic, including:
|
||||
- Retrieving relevant memories
|
||||
- Preparing context and system message
|
||||
- Generating responses
|
||||
- Storing interactions in Mem0
|
||||
|
||||
3. **Graph Setup**: The code sets up a `StateGraph` with the chatbot node and necessary edges.
|
||||
|
||||
4. **Conversation Runner**: The `run_conversation` function manages the flow of the conversation, processing user input and displaying responses.
|
||||
|
||||
## Usage
|
||||
|
||||
To use the Customer Support AI Agent:
|
||||
|
||||
1. Run the script.
|
||||
2. Enter your queries when prompted.
|
||||
3. Type 'quit', 'exit', or 'bye' to end the conversation.
|
||||
|
||||
## Key Points
|
||||
|
||||
- **Memory Integration**: Mem0 is used to store and retrieve relevant information from past interactions.
|
||||
- **Personalization**: The agent uses past interactions to provide more contextual and personalized responses.
|
||||
- **Flexible Architecture**: The LangGraph structure allows for easy expansion and modification of the conversation flow.
|
||||
|
||||
## Conclusion
|
||||
|
||||
This Customer Support AI Agent demonstrates the power of combining LangGraph for conversation management and Mem0 for memory retention. As the conversation progresses, the agent's responses become increasingly personalized, providing an improved support experience.
|
||||
@@ -0,0 +1,172 @@
|
||||
---
|
||||
title: LlamaIndex ReAct Agent
|
||||
---
|
||||
Create a ReAct Agent with LlamaIndex which uses Mem0 as the memory store.
|
||||
|
||||
### Overview
|
||||
A ReAct agent combines reasoning and action capabilities, making it versatile for tasks requiring both thought processes (reasoning) and interaction with tools or APIs (acting). Mem0 as memory enhances these capabilities by allowing the agent to store and retrieve contextual information from past interactions.
|
||||
|
||||
### Setup
|
||||
```bash
|
||||
pip install llama-index-core llama-index-memory-mem0
|
||||
```
|
||||
|
||||
Initialize the LLM.
|
||||
```python
|
||||
import os
|
||||
from llama_index.llms.openai import OpenAI
|
||||
|
||||
os.environ["OPENAI_API_KEY"] = "<your-openai-api-key>"
|
||||
llm = OpenAI(model="gpt-4o")
|
||||
```
|
||||
|
||||
Initialize the Mem0 client. You can find your API key [here](https://app.mem0.ai/dashboard/). Read about Mem0 [Open Source](https://docs.mem0.ai/open-source/quickstart).
|
||||
```python
|
||||
os.environ["MEM0_API_KEY"] = "<your-mem0-api-key>"
|
||||
|
||||
from llama_index.memory.mem0 import Mem0Memory
|
||||
|
||||
context = {"user_id": "david"}
|
||||
memory_from_client = Mem0Memory.from_client(
|
||||
context=context,
|
||||
api_key=os.environ["MEM0_API_KEY"],
|
||||
search_msg_limit=4, # optional, default is 5
|
||||
)
|
||||
```
|
||||
|
||||
Create the tools. These tools will be used by the agent to perform actions.
|
||||
```python
|
||||
from llama_index.core.tools import FunctionTool
|
||||
|
||||
def call_fn(name: str):
|
||||
"""Call the provided name.
|
||||
Args:
|
||||
name: str (Name of the person)
|
||||
"""
|
||||
return f"Calling... {name}"
|
||||
|
||||
def email_fn(name: str):
|
||||
"""Email the provided name.
|
||||
Args:
|
||||
name: str (Name of the person)
|
||||
"""
|
||||
return f"Emailing... {name}"
|
||||
|
||||
def order_food(name: str, dish: str):
|
||||
"""Order food for the provided name.
|
||||
Args:
|
||||
name: str (Name of the person)
|
||||
dish: str (Name of the dish)
|
||||
"""
|
||||
return f"Ordering {dish} for {name}"
|
||||
|
||||
call_tool = FunctionTool.from_defaults(fn=call_fn)
|
||||
email_tool = FunctionTool.from_defaults(fn=email_fn)
|
||||
order_food_tool = FunctionTool.from_defaults(fn=order_food)
|
||||
```
|
||||
|
||||
Initialize the agent with tools and memory.
|
||||
```python
|
||||
from llama_index.core.agent import FunctionCallingAgent
|
||||
|
||||
agent = FunctionCallingAgent.from_tools(
|
||||
[call_tool, email_tool, order_food_tool],
|
||||
llm=llm,
|
||||
memory=memory_from_client, # or memory_from_config
|
||||
verbose=True,
|
||||
)
|
||||
```
|
||||
|
||||
Start the chat.
|
||||
<Note> The agent will use the Mem0 to store the relavant memories from the chat. </Note>
|
||||
|
||||
Input
|
||||
```python
|
||||
response = agent.chat("Hi, My name is David")
|
||||
print(response)
|
||||
```
|
||||
Output
|
||||
```text
|
||||
> Running step bf44a75a-a920-4cf3-944e-b6e6b5695043. Step input: Hi, My name is David
|
||||
Added user message to memory: Hi, My name is David
|
||||
=== LLM Response ===
|
||||
Hello, David! How can I assist you today?
|
||||
```
|
||||
|
||||
Input
|
||||
```python
|
||||
response = agent.chat("I love to eat pizza on weekends")
|
||||
print(response)
|
||||
```
|
||||
Output
|
||||
```text
|
||||
> Running step 845783b0-b85b-487c-baee-8460ebe8b38d. Step input: I love to eat pizza on weekends
|
||||
Added user message to memory: I love to eat pizza on weekends
|
||||
=== LLM Response ===
|
||||
Pizza is a great choice for the weekend! If you'd like, I can help you order some. Just let me know what kind of pizza you prefer!
|
||||
```
|
||||
Input
|
||||
```python
|
||||
response = agent.chat("My preferred way of communication is email")
|
||||
print(response)
|
||||
```
|
||||
Output
|
||||
```text
|
||||
> Running step 345842f0-f8a0-42ea-a1b7-612265d72a92. Step input: My preferred way of communication is email
|
||||
Added user message to memory: My preferred way of communication is email
|
||||
=== LLM Response ===
|
||||
Got it! If you need any assistance or have any requests, feel free to let me know, and I can communicate with you via email.
|
||||
```
|
||||
|
||||
### Using the agent WITHOUT memory
|
||||
Input
|
||||
```python
|
||||
agent = FunctionCallingAgent.from_tools(
|
||||
[call_tool, email_tool, order_food_tool],
|
||||
# memory is not provided
|
||||
llm=llm,
|
||||
verbose=True,
|
||||
)
|
||||
response = agent.chat("I am feeling hungry, order me something and send me the bill")
|
||||
print(response)
|
||||
```
|
||||
Output
|
||||
```text
|
||||
> Running step e89eb75d-75e1-4dea-a8c8-5c3d4b77882d. Step input: I am feeling hungry, order me something and send me the bill
|
||||
Added user message to memory: I am feeling hungry, order me something and send me the bill
|
||||
=== LLM Response ===
|
||||
Please let me know your name and the dish you'd like to order, and I'll take care of it for you!
|
||||
```
|
||||
<Note> The agent is not able to remember the past prefernces that user shared in previous chats. </Note>
|
||||
|
||||
### Using the agent WITH memory
|
||||
Input
|
||||
```python
|
||||
agent = FunctionCallingAgent.from_tools(
|
||||
[call_tool, email_tool, order_food_tool],
|
||||
llm=llm,
|
||||
# memory is provided
|
||||
memory=memory_from_client, # or memory_from_config
|
||||
verbose=True,
|
||||
)
|
||||
response = agent.chat("I am feeling hungry, order me something and send me the bill")
|
||||
print(response)
|
||||
```
|
||||
|
||||
Output
|
||||
```text
|
||||
> Running step 5e473db9-3973-4cb1-a5fd-860be0ab0006. Step input: I am feeling hungry, order me something and send me the bill
|
||||
Added user message to memory: I am feeling hungry, order me something and send me the bill
|
||||
=== Calling Function ===
|
||||
Calling function: order_food with args: {"name": "David", "dish": "pizza"}
|
||||
=== Function Output ===
|
||||
Ordering pizza for David
|
||||
=== Calling Function ===
|
||||
Calling function: email_fn with args: {"name": "David"}
|
||||
=== Function Output ===
|
||||
Emailing... David
|
||||
> Running step 38080544-6b37-4bb2-aab2-7670100d926e. Step input: None
|
||||
=== LLM Response ===
|
||||
I've ordered a pizza for you, and the bill has been sent to your email. Enjoy your meal! If there's anything else you need, feel free to let me know.
|
||||
```
|
||||
<Note> The agent is able to remember the past prefernces that user shared and use them to perform actions. </Note>
|
||||
@@ -14,19 +14,22 @@ With Mem0, you can create stateful LLM-based applications such as chatbots, virt
|
||||
|
||||
Here are some examples of how Mem0 can be integrated into various applications:
|
||||
|
||||
## Example Use Cases
|
||||
## Examples
|
||||
|
||||
<CardGroup cols={1}>
|
||||
<Card title="Personal AI Tutor" icon="square-1" href="/examples/personal-ai-tutor">
|
||||
<img width="100%" src="/images/ai-tutor.png" />
|
||||
<CardGroup cols={2}>
|
||||
<Card title="Mem0 with Ollama" icon="square-1" href="/examples/mem0-with-ollama">
|
||||
Run Mem0 locally with Ollama.
|
||||
</Card>
|
||||
<Card title="Personal AI Tutor" icon="square-2" href="/examples/personal-ai-tutor">
|
||||
Create a Personalized AI Tutor that adapts to student progress and learning preferences.
|
||||
</Card>
|
||||
<Card title="Personal Travel Assistant" icon="square-2" href="/examples/personal-travel-assistant">
|
||||
<img src="/images/personal-travel-agent.png" />
|
||||
<Card title="Personal Travel Assistant" icon="square-3" href="/examples/personal-travel-assistant">
|
||||
Build a Personalized AI Travel Assistant that understands your travel preferences and past itineraries.
|
||||
</Card>
|
||||
<Card title="Customer Support Agent" icon="square-3" href="/examples/customer-support-agent">
|
||||
<img width="100%" src="/images/customer-support-agent.png" />
|
||||
<Card title="Customer Support Agent" icon="square-4" href="/examples/customer-support-agent">
|
||||
Develop a Personal AI Assistant that remembers user preferences, past interactions, and context to provide personalized and efficient assistance.
|
||||
</Card>
|
||||
</CardGroup>
|
||||
<Card title="LlamaIndex Mem0" icon="square-5" href="/examples/llama-index-mem0">
|
||||
Create a ReAct Agent with LlamaIndex which uses Mem0 as the memory store.
|
||||
</Card>
|
||||
</CardGroup>
|
||||
|
||||
@@ -19,7 +19,99 @@ pip install openai mem0ai
|
||||
|
||||
Here's the complete code to create and interact with a Personalized AI Travel Assistant using Mem0:
|
||||
|
||||
```python
|
||||
<CodeGroup>
|
||||
|
||||
```python After v1.1
|
||||
import os
|
||||
from openai import OpenAI
|
||||
from mem0 import Memory
|
||||
|
||||
# Set the OpenAI API key
|
||||
os.environ['OPENAI_API_KEY'] = "sk-xxx"
|
||||
|
||||
config = {
|
||||
"llm": {
|
||||
"provider": "openai",
|
||||
"config": {
|
||||
"model": "gpt-4o",
|
||||
"temperature": 0.1,
|
||||
"max_tokens": 2000,
|
||||
}
|
||||
},
|
||||
"embedder": {
|
||||
"provider": "openai",
|
||||
"config": {
|
||||
"model": "text-embedding-3-large"
|
||||
}
|
||||
},
|
||||
"vector_store": {
|
||||
"provider": "qdrant",
|
||||
"config": {
|
||||
"collection_name": "test",
|
||||
"embedding_model_dims": 3072,
|
||||
}
|
||||
},
|
||||
"version": "v1.1",
|
||||
}
|
||||
|
||||
class PersonalTravelAssistant:
|
||||
def __init__(self):
|
||||
self.client = OpenAI()
|
||||
self.memory = Memory.from_config(config)
|
||||
self.messages = [{"role": "system", "content": "You are a personal AI Assistant."}]
|
||||
|
||||
def ask_question(self, question, user_id):
|
||||
# Fetch previous related memories
|
||||
previous_memories = self.search_memories(question, user_id=user_id)
|
||||
prompt = question
|
||||
if previous_memories:
|
||||
prompt = f"User input: {question}\n Previous memories: {previous_memories}"
|
||||
self.messages.append({"role": "user", "content": prompt})
|
||||
|
||||
# Generate response using GPT-4o
|
||||
response = self.client.chat.completions.create(
|
||||
model="gpt-4o",
|
||||
messages=self.messages
|
||||
)
|
||||
answer = response.choices[0].message.content
|
||||
self.messages.append({"role": "assistant", "content": answer})
|
||||
|
||||
# Store the question in memory
|
||||
self.memory.add(question, user_id=user_id)
|
||||
return answer
|
||||
|
||||
def get_memories(self, user_id):
|
||||
memories = self.memory.get_all(user_id=user_id)
|
||||
return [m['memory'] for m in memories['memories']]
|
||||
|
||||
def search_memories(self, query, user_id):
|
||||
memories = self.memory.search(query, user_id=user_id)
|
||||
return [m['memory'] for m in memories['memories']]
|
||||
|
||||
# Usage example
|
||||
user_id = "traveler_123"
|
||||
ai_assistant = PersonalTravelAssistant()
|
||||
|
||||
def main():
|
||||
while True:
|
||||
question = input("Question: ")
|
||||
if question.lower() in ['q', 'exit']:
|
||||
print("Exiting...")
|
||||
break
|
||||
|
||||
answer = ai_assistant.ask_question(question, user_id=user_id)
|
||||
print(f"Answer: {answer}")
|
||||
memories = ai_assistant.get_memories(user_id=user_id)
|
||||
print("Memories:")
|
||||
for memory in memories:
|
||||
print(f"- {memory}")
|
||||
print("-----")
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
```
|
||||
|
||||
```python Before v1.1
|
||||
import os
|
||||
from openai import OpenAI
|
||||
from mem0 import Memory
|
||||
@@ -55,11 +147,11 @@ class PersonalTravelAssistant:
|
||||
|
||||
def get_memories(self, user_id):
|
||||
memories = self.memory.get_all(user_id=user_id)
|
||||
return [m['text'] for m in memories]
|
||||
return [m['memory'] for m in memories['memories']]
|
||||
|
||||
def search_memories(self, query, user_id):
|
||||
memories = self.memory.search(query, user_id=user_id)
|
||||
return [m['text'] for m in memories]
|
||||
return [m['memory'] for m in memories['memories']]
|
||||
|
||||
# Usage example
|
||||
user_id = "traveler_123"
|
||||
@@ -83,6 +175,8 @@ def main():
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
```
|
||||
</CodeGroup>
|
||||
|
||||
|
||||
## Key Components
|
||||
|
||||
|
||||
@@ -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>
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
+5
-41
@@ -1,56 +1,20 @@
|
||||
---
|
||||
title: Features
|
||||
icon: "wrench"
|
||||
iconType: "solid"
|
||||
---
|
||||
|
||||
## Core features
|
||||
|
||||
- **User, Session, and AI Agent Memory**: Retains information across user sessions, interactions, and AI agents, ensuring continuity and context.
|
||||
- **Adaptive Personalization**: Continuously improves personalization based on user interactions and feedback.
|
||||
- **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
|
||||
|
||||
|
||||
## 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.
|
||||
|
||||
|
||||
## Common Use Cases
|
||||
|
||||
- **Personalized Learning Assistants**: Long-term memory allows learning assistants to remember user preferences, past interactions, 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 meaningful.
|
||||
|
||||
- **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.
|
||||
|
||||
- **Recency, Relevancy, and Decay**: Mem0 prioritizes recent interactions and gradually forgets outdated information, ensuring the memory remains relevant and up-to-date for more accurate responses.
|
||||
|
||||
- **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" />
|
||||
@@ -0,0 +1,174 @@
|
||||
---
|
||||
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.
|
||||
|
||||
## Initialization
|
||||
|
||||
To use the async client, you first need to initialize it:
|
||||
|
||||
<CodeGroup>
|
||||
|
||||
```python Python
|
||||
from mem0 import AsyncMemoryClient
|
||||
client = AsyncMemoryClient(api_key="your-api-key")
|
||||
```
|
||||
|
||||
```javascript JavaScript
|
||||
const { MemoryClient } = require('mem0ai');
|
||||
const client = new MemoryClient('your-api-key');
|
||||
```
|
||||
|
||||
</CodeGroup>
|
||||
|
||||
## Methods
|
||||
|
||||
The `AsyncMemoryClient` provides the following methods:
|
||||
|
||||
### Add
|
||||
|
||||
Add a new memory asynchronously.
|
||||
|
||||
<CodeGroup>
|
||||
|
||||
```python Python
|
||||
messages = [
|
||||
{"role": "user", "content": "Alice loves playing badminton"},
|
||||
{"role": "assistant", "content": "That's great! Alice is a fitness freak"},
|
||||
]
|
||||
await client.add(messages, user_id="alice")
|
||||
```
|
||||
|
||||
```javascript JavaScript
|
||||
const messages = [
|
||||
{"role": "user", "content": "Alice loves playing badminton"},
|
||||
{"role": "assistant", "content": "That's great! Alice is a fitness freak"},
|
||||
];
|
||||
await client.add(messages, { user_id: "alice" });
|
||||
```
|
||||
|
||||
</CodeGroup>
|
||||
|
||||
### Search
|
||||
|
||||
Search for memories based on a query asynchronously.
|
||||
|
||||
<CodeGroup>
|
||||
|
||||
```python Python
|
||||
await client.search(query="What is Alice's favorite sport?", user_id="alice")
|
||||
```
|
||||
|
||||
```javascript JavaScript
|
||||
await client.search("What is Alice's favorite sport?", { user_id: "alice" });
|
||||
```
|
||||
|
||||
</CodeGroup>
|
||||
|
||||
### Get All
|
||||
|
||||
Retrieve all memories for a user asynchronously.
|
||||
|
||||
<CodeGroup>
|
||||
|
||||
```python Python
|
||||
await client.get_all(user_id="alice")
|
||||
```
|
||||
|
||||
```javascript JavaScript
|
||||
await client.getAll({ user_id: "alice" });
|
||||
```
|
||||
|
||||
</CodeGroup>
|
||||
|
||||
### Delete
|
||||
|
||||
Delete a specific memory asynchronously.
|
||||
|
||||
<CodeGroup>
|
||||
|
||||
```python Python
|
||||
await client.delete(memory_id="memory-id-here")
|
||||
```
|
||||
|
||||
```javascript JavaScript
|
||||
await client.delete("memory-id-here");
|
||||
```
|
||||
|
||||
</CodeGroup>
|
||||
|
||||
### Delete All
|
||||
|
||||
Delete all memories for a user asynchronously.
|
||||
|
||||
<CodeGroup>
|
||||
|
||||
```python Python
|
||||
await client.delete_all(user_id="alice")
|
||||
```
|
||||
|
||||
```javascript JavaScript
|
||||
await client.deleteAll({ user_id: "alice" });
|
||||
```
|
||||
|
||||
</CodeGroup>
|
||||
|
||||
### History
|
||||
|
||||
Get the history of a specific memory asynchronously.
|
||||
|
||||
<CodeGroup>
|
||||
|
||||
```python Python
|
||||
await client.history(memory_id="memory-id-here")
|
||||
```
|
||||
|
||||
```javascript JavaScript
|
||||
await client.history("memory-id-here");
|
||||
```
|
||||
|
||||
</CodeGroup>
|
||||
|
||||
### Users
|
||||
|
||||
Get all users, agents, and runs which have memories associated with them asynchronously.
|
||||
|
||||
<CodeGroup>
|
||||
|
||||
```python Python
|
||||
await client.users()
|
||||
```
|
||||
|
||||
```javascript JavaScript
|
||||
await client.users();
|
||||
```
|
||||
|
||||
</CodeGroup>
|
||||
|
||||
### Reset
|
||||
|
||||
Reset the client, deleting all users and memories asynchronously.
|
||||
|
||||
<CodeGroup>
|
||||
|
||||
```python Python
|
||||
await client.reset()
|
||||
```
|
||||
|
||||
```javascript JavaScript
|
||||
await client.reset();
|
||||
```
|
||||
|
||||
</CodeGroup>
|
||||
|
||||
## Conclusion
|
||||
|
||||
The `AsyncMemoryClient` provides a powerful way to interact with the Mem0 API asynchronously, allowing for more efficient and responsive applications. By using this client, you can perform memory operations without blocking your application's execution.
|
||||
|
||||
If you have any questions or need further assistance, please don't hesitate to reach out:
|
||||
|
||||
<Snippet file="get-help.mdx" />
|
||||
@@ -0,0 +1,193 @@
|
||||
---
|
||||
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?
|
||||
|
||||
You can now create custom categories tailored to your specific needs, instead of using the default categories such as travel, sports, music, and more (see [default categories](#default-categories) below). **When custom categories are provided, they will override the default categories.**
|
||||
|
||||
There are two ways to set custom categories:
|
||||
|
||||
### 1. Project Level
|
||||
|
||||
You can set custom categories at the project level, which will be applied to all memories added within that project. Mem0 will automatically assign relevant categories from your custom set to new memories based on their content. Setting custom categories at the project level will override the default categories.
|
||||
|
||||
Here's how to set custom categories:
|
||||
|
||||
<CodeGroup>
|
||||
```python Code
|
||||
from mem0 import MemoryClient
|
||||
|
||||
client = MemoryClient(api_key="<your_mem0_api_key>")
|
||||
|
||||
# Update custom categories
|
||||
new_categories = [
|
||||
{"lifestyle_management_concerns": "Tracks daily routines, habits, hobbies and interests including cooking, time management and work-life balance"},
|
||||
{"seeking_structure": "Documents goals around creating routines, schedules, and organized systems in various life areas"},
|
||||
{"personal_information": "Basic information about the user including name, preferences, and personality traits"}
|
||||
]
|
||||
|
||||
response = client.update_project(custom_categories = new_categories)
|
||||
print(response)
|
||||
```
|
||||
|
||||
```json Output
|
||||
{
|
||||
"message": "Updated custom categories"
|
||||
}
|
||||
```
|
||||
</CodeGroup>
|
||||
|
||||
This is how you will use these custom categories during the `add` API call:
|
||||
|
||||
<CodeGroup>
|
||||
```python Code
|
||||
messages = [
|
||||
{"role": "user", "content": "My name is Alice. I need help organizing my daily schedule better. I feel overwhelmed trying to balance work, exercise, and social life."},
|
||||
{"role": "assistant", "content": "I understand how overwhelming that can feel. Let's break this down together. What specific areas of your schedule feel most challenging to manage?"},
|
||||
{"role": "user", "content": "I want to be more productive at work, maintain a consistent workout routine, and still have energy for friends and hobbies."},
|
||||
{"role": "assistant", "content": "Those are great goals for better time management. What's one small change you could make to start improving your daily routine?"},
|
||||
]
|
||||
|
||||
# Add memories with custom categories
|
||||
client.add(messages, user_id="alice")
|
||||
```
|
||||
|
||||
```python Memories with categories
|
||||
# Following categories will be created for the memories added
|
||||
Wants to have energy for friends and hobbies (lifestyle_management_concerns)
|
||||
Wants to maintain a consistent workout routine (seeking_structure, lifestyle_management_concerns)
|
||||
Wants to be more productive at work (lifestyle_management_concerns, seeking_structure)
|
||||
Name is Alice (personal_information)
|
||||
```
|
||||
</CodeGroup>
|
||||
|
||||
You can also retrieve the current custom categories:
|
||||
|
||||
<CodeGroup>
|
||||
```python Code
|
||||
# Get current custom categories
|
||||
categories = client.get_project(fields=["custom_categories"])
|
||||
print(categories)
|
||||
```
|
||||
|
||||
```json Output
|
||||
{
|
||||
"custom_categories": [
|
||||
{"lifestyle_management_concerns": "Tracks daily routines, habits, hobbies and interests including cooking, time management and work-life balance"},
|
||||
{"seeking_structure": "Documents goals around creating routines, schedules, and organized systems in various life areas"},
|
||||
{"personal_information": "Basic information about the user including name, preferences, and personality traits"}
|
||||
]
|
||||
}
|
||||
|
||||
```
|
||||
</CodeGroup>
|
||||
|
||||
These project-level categories will be automatically applied to all new memories added to the project.
|
||||
|
||||
|
||||
|
||||
### 2. During the `add` API call
|
||||
You can also set custom categories during the `add` API call. This will override any project-level custom categories for that specific memory addition. For example, if you want to use different categories for food-related memories, you can provide custom categories like "food" and "user_preferences" in the `add` call. These custom categories will be used instead of the project-level categories when categorizing those specific memories.
|
||||
|
||||
<CodeGroup>
|
||||
```python Code
|
||||
from mem0 import MemoryClient
|
||||
|
||||
client = MemoryClient(api_key="<your_mem0_api_key>")
|
||||
|
||||
custom_categories = [
|
||||
{"seeking_structure": "Documents goals around creating routines, schedules, and organized systems in various life areas"},
|
||||
{"personal_information": "Basic information about the user including name, preferences, and personality traits"}
|
||||
]
|
||||
|
||||
messages = [
|
||||
{"role": "user", "content": "My name is Alice. I need help organizing my daily schedule better. I feel overwhelmed trying to balance work, exercise, and social life."},
|
||||
{"role": "assistant", "content": "I understand how overwhelming that can feel. Let's break this down together. What specific areas of your schedule feel most challenging to manage?"},
|
||||
{"role": "user", "content": "I want to be more productive at work, maintain a consistent workout routine, and still have energy for friends and hobbies."},
|
||||
{"role": "assistant", "content": "Those are great goals for better time management. What's one small change you could make to start improving your daily routine?"},
|
||||
]
|
||||
|
||||
client.add(messages, user_id="alice", custom_categories=custom_categories)
|
||||
```
|
||||
|
||||
```python Memories with categories
|
||||
# Following categories will be created for the memories added
|
||||
Wants to have energy for friends and hobbies (seeking_structure)
|
||||
Wants to maintain a consistent workout routine (seeking_structure)
|
||||
Wants to be more productive at work (seeking_structure)
|
||||
Name is Alice (personal_information)
|
||||
```
|
||||
</CodeGroup>
|
||||
|
||||
<Note>Providing more detailed and specific category descriptions will lead to more accurate and relevant memory categorization.</Note>
|
||||
|
||||
|
||||
## Default Categories
|
||||
Here is the list of **default categories**. If you don't specify any custom categories using the above methods, these will be used as default categories.
|
||||
```
|
||||
- personal_details
|
||||
- family
|
||||
- professional_details
|
||||
- sports
|
||||
- travel
|
||||
- food
|
||||
- music
|
||||
- health
|
||||
- technology
|
||||
- hobbies
|
||||
- fashion
|
||||
- entertainment
|
||||
- milestones
|
||||
- user_preferences
|
||||
- misc
|
||||
```
|
||||
|
||||
<CodeGroup>
|
||||
```python Code
|
||||
from mem0 import MemoryClient
|
||||
|
||||
client = MemoryClient(api_key="<your_mem0_api_key>")
|
||||
|
||||
messages = [
|
||||
{"role": "user", "content": "Hi, my name is Alice."},
|
||||
{"role": "assistant", "content": "Hi Alice, what sports do you like to play?"},
|
||||
{"role": "user", "content": "I love playing badminton, football, and basketball. I'm quite athletic!"},
|
||||
{"role": "assistant", "content": "That's great! Alice seems to enjoy both individual sports like badminton and team sports like football and basketball."},
|
||||
{"role": "user", "content": "Sometimes, I also draw and sketch in my free time."},
|
||||
{"role": "assistant", "content": "That's cool! I'm sure you're good at it."}
|
||||
]
|
||||
|
||||
# Add memories with default categories
|
||||
client.add(messages, user_id='alice')
|
||||
```
|
||||
|
||||
```python Memories with categories
|
||||
# Following categories will be created for the memories added
|
||||
Sometimes draws and sketches in free time (hobbies)
|
||||
Is quite athletic (sports)
|
||||
Loves playing badminton, football, and basketball (sports)
|
||||
Name is Alice (personal_details)
|
||||
```
|
||||
</CodeGroup>
|
||||
|
||||
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_project(["custom_categories"])
|
||||
```
|
||||
|
||||
```json Output
|
||||
{
|
||||
'custom_categories': None
|
||||
}
|
||||
```
|
||||
</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" />
|
||||
@@ -0,0 +1,76 @@
|
||||
---
|
||||
title: Custom Instructions
|
||||
description: 'Enhance your product experience by adding custom instructions tailored to your needs'
|
||||
icon: "pencil"
|
||||
iconType: "solid"
|
||||
---
|
||||
|
||||
## Introduction to Custom Instructions
|
||||
|
||||
Custom instructions allow you to define specific guidelines for your project. This feature helps ensure consistency and provides clear direction for handling project-specific requirements.
|
||||
|
||||
Custom instructions are particularly useful when you want to:
|
||||
- Define how information should be extracted from conversations
|
||||
- Specify what types of data should be captured or ignored
|
||||
- Set rules for categorizing and organizing memories
|
||||
- Maintain consistent handling of project-specific requirements
|
||||
|
||||
When custom instructions are set at the project level, they will be applied to all new memories added within that project. This ensures that your data is processed according to your defined guidelines across your entire project.
|
||||
|
||||
## Setting Custom Instructions
|
||||
|
||||
You can set custom instructions for your project using the following method:
|
||||
|
||||
<CodeGroup>
|
||||
```python Code
|
||||
# Update custom instructions
|
||||
prompt ="""
|
||||
Your Task: Extract ONLY health-related information from conversations, focusing on the following areas:
|
||||
|
||||
1. Medical Conditions, Symptoms, and Diagnoses:
|
||||
- Illnesses, disorders, or symptoms (e.g., fever, diabetes).
|
||||
- Confirmed or suspected diagnoses.
|
||||
|
||||
2. Medications, Treatments, and Procedures:
|
||||
- Prescription or OTC medications (names, dosages).
|
||||
- Treatments, therapies, or medical procedures.
|
||||
|
||||
3. Diet, Exercise, and Sleep:
|
||||
- Dietary habits, fitness routines, and sleep patterns.
|
||||
|
||||
4. Doctor Visits and Appointments:
|
||||
- Past, upcoming, or regular medical visits.
|
||||
|
||||
5. Health Metrics:
|
||||
- Data like weight, BP, cholesterol, or sugar levels.
|
||||
|
||||
Guidelines:
|
||||
- Focus solely on health-related content.
|
||||
- Maintain clarity and context accuracy while recording.
|
||||
"""
|
||||
response = client.update_project(custom_instructions=prompt)
|
||||
print(response)
|
||||
```
|
||||
|
||||
```json Output
|
||||
{
|
||||
"message": "Updated custom instructions"
|
||||
}
|
||||
```
|
||||
</CodeGroup>
|
||||
|
||||
You can also retrieve the current custom instructions:
|
||||
|
||||
<CodeGroup>
|
||||
```python Code
|
||||
# Retrieve current custom instructions
|
||||
response = client.get_project(fields=["custom_instructions"])
|
||||
print(response)
|
||||
```
|
||||
|
||||
```json Output
|
||||
{
|
||||
"custom_instructions": "Your Task: Extract ONLY health-related information from conversations, focusing on the following areas:\n1. Medical Conditions, Symptoms, and Diagnoses - illnesses, disorders, or symptoms (e.g., fever, diabetes), confirmed or suspected diagnoses.\n2. Medications, Treatments, and Procedures - prescription or OTC medications (names, dosages), treatments, therapies, or medical procedures.\n3. Diet, Exercise, and Sleep - dietary habits, fitness routines, and sleep patterns.\n4. Doctor Visits and Appointments - past, upcoming, or regular medical visits.\n5. Health Metrics - data like weight, BP, cholesterol, or sugar levels.\n\nGuidelines: Focus solely on health-related content. Maintain clarity and context accuracy while recording."
|
||||
}
|
||||
```
|
||||
</CodeGroup>
|
||||
@@ -0,0 +1,111 @@
|
||||
---
|
||||
title: Custom Prompts
|
||||
description: 'Enhance your product experience by adding custom prompts tailored to your needs'
|
||||
icon: "pencil"
|
||||
iconType: "solid"
|
||||
---
|
||||
|
||||
## Introduction to Custom Prompts
|
||||
|
||||
Custom prompts allow you to tailor the behavior of your Mem0 instance to specific use cases or domains.
|
||||
By defining a custom prompt, you can control how information is extracted, processed, and stored in your memory system.
|
||||
|
||||
To create an effective custom prompt:
|
||||
1. Be specific about the information to extract.
|
||||
2. Provide few-shot examples to guide the LLM.
|
||||
3. Ensure examples follow the format shown below.
|
||||
|
||||
Example of a custom prompt:
|
||||
|
||||
```python
|
||||
custom_prompt = """
|
||||
Please only extract entities containing customer support information, order details, and user information.
|
||||
Here are some few shot examples:
|
||||
|
||||
Input: Hi.
|
||||
Output: {{"facts" : []}}
|
||||
|
||||
Input: The weather is nice today.
|
||||
Output: {{"facts" : []}}
|
||||
|
||||
Input: My order #12345 hasn't arrived yet.
|
||||
Output: {{"facts" : ["Order #12345 not received"]}}
|
||||
|
||||
Input: I'm John Doe, and I'd like to return the shoes I bought last week.
|
||||
Output: {{"facts" : ["Customer name: John Doe", "Wants to return shoes", "Purchase made last week"]}}
|
||||
|
||||
Input: I ordered a red shirt, size medium, but received a blue one instead.
|
||||
Output: {{"facts" : ["Ordered red shirt, size medium", "Received blue shirt instead"]}}
|
||||
|
||||
Return the facts and customer information in a json format as shown above.
|
||||
"""
|
||||
|
||||
```
|
||||
|
||||
Here we initialize the custom prompt in the config.
|
||||
|
||||
```python
|
||||
from mem0 import Memory
|
||||
|
||||
config = {
|
||||
"llm": {
|
||||
"provider": "openai",
|
||||
"config": {
|
||||
"model": "gpt-4o",
|
||||
"temperature": 0.2,
|
||||
"max_tokens": 1500,
|
||||
}
|
||||
},
|
||||
"custom_prompt": custom_prompt,
|
||||
"version": "v1.1"
|
||||
}
|
||||
|
||||
m = Memory.from_config(config_dict=config, user_id="alice")
|
||||
```
|
||||
|
||||
### Example 1
|
||||
|
||||
In this example, we are adding a memory of a user ordering a laptop. As seen in the output, the custom prompt is used to extract the relevant information from the user's message.
|
||||
|
||||
<CodeGroup>
|
||||
```python Code
|
||||
m.add("Yesterday, I ordered a laptop, the order id is 12345", user_id="alice")
|
||||
```
|
||||
|
||||
```json Output
|
||||
{
|
||||
"results": [
|
||||
{
|
||||
"memory": "Ordered a laptop",
|
||||
"event": "ADD"
|
||||
},
|
||||
{
|
||||
"memory": "Order ID: 12345",
|
||||
"event": "ADD"
|
||||
},
|
||||
{
|
||||
"memory": "Order placed yesterday",
|
||||
"event": "ADD"
|
||||
}
|
||||
],
|
||||
"relations": []
|
||||
}
|
||||
```
|
||||
</CodeGroup>
|
||||
|
||||
### Example 2
|
||||
|
||||
In this example, we are adding a memory of a user liking to go on hikes. This add message is not specific to the use-case mentioned in the custom prompt.
|
||||
Hence, the memory is not added.
|
||||
<CodeGroup>
|
||||
```python Code
|
||||
m.add("I like going to hikes", user_id="alice")
|
||||
```
|
||||
|
||||
```json Output
|
||||
{
|
||||
"results": [],
|
||||
"relations": []
|
||||
}
|
||||
```
|
||||
</CodeGroup>
|
||||
@@ -0,0 +1,104 @@
|
||||
---
|
||||
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?
|
||||
The Direct Import feature allows users to skip the memory deduction phase and directly input pre-defined memories into the system for storage and retrieval.
|
||||
To enable this feature, you need to set the `infer` parameter to `False` in the `add` method.
|
||||
|
||||
|
||||
<CodeGroup>
|
||||
|
||||
|
||||
```python Python
|
||||
messages = [
|
||||
{"role": "user", "content": "Alice loves playing badminton"},
|
||||
{"role": "assistant", "content": "That's great! Alice is a fitness freak"},
|
||||
{"role": "user", "content": "Alice mostly cook at home because of gym plan"},
|
||||
]
|
||||
|
||||
|
||||
client.add(messages, user_id="alice", infer=False)
|
||||
```
|
||||
|
||||
```markdown Output
|
||||
[]
|
||||
```
|
||||
</CodeGroup>
|
||||
|
||||
You can see that the output of add call is an empty list.
|
||||
|
||||
<Note> Only messages with the role "user" will be used for storage. Messages with roles such as "assistant" or "system" will be ignored during the storage process. </Note>
|
||||
|
||||
|
||||
## How to retrieve memories?
|
||||
|
||||
You can retrieve memories using the `search` method.
|
||||
|
||||
<CodeGroup>
|
||||
|
||||
```python Python
|
||||
client.search(query="What is Alice's favorite sport?", user_id="alice", output_format="v1.1")
|
||||
```
|
||||
|
||||
```json Output
|
||||
{
|
||||
"results": [
|
||||
{
|
||||
"id": "19d6d7aa-2454-4e58-96fc-e74d9e9f8dd1",
|
||||
"memory": "Alice loves playing badminton",
|
||||
"user_id": "pc123",
|
||||
"metadata": null,
|
||||
"categories": null,
|
||||
"created_at": "2024-10-15T21:52:11.474901-07:00",
|
||||
"updated_at": "2024-10-15T21:52:11.474912-07:00"
|
||||
}
|
||||
]
|
||||
}
|
||||
```
|
||||
|
||||
</CodeGroup>
|
||||
|
||||
## How to retrieve all memories?
|
||||
|
||||
You can retrieve all memories using the `get_all` method.
|
||||
|
||||
<CodeGroup>
|
||||
|
||||
```python Python
|
||||
client.get_all(query="What is Alice's favorite sport?", user_id="alice", output_format="v1.1")
|
||||
```
|
||||
|
||||
```json Output
|
||||
{
|
||||
"results": [
|
||||
{
|
||||
"id": "19d6d7aa-2454-4e58-96fc-e74d9e9f8dd1",
|
||||
"memory": "Alice loves playing badminton",
|
||||
"user_id": "pc123",
|
||||
"metadata": null,
|
||||
"categories": null,
|
||||
"created_at": "2024-10-15T21:52:11.474901-07:00",
|
||||
"updated_at": "2024-10-15T21:52:11.474912-07:00"
|
||||
},
|
||||
{
|
||||
"id": "8557f05d-7b3c-47e5-b409-9886f9e314fc",
|
||||
"memory": "Alice mostly cook at home because of gym plan",
|
||||
"user_id": "pc123",
|
||||
"metadata": null,
|
||||
"categories": null,
|
||||
"created_at": "2024-10-15T21:52:11.474929-07:00",
|
||||
"updated_at": "2024-10-15T21:52:11.474932-07:00"
|
||||
}
|
||||
]
|
||||
}
|
||||
```
|
||||
|
||||
</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" />
|
||||
@@ -0,0 +1,147 @@
|
||||
---
|
||||
title: Memory Export
|
||||
description: 'Export memories in a structured format using customizable Pydantic schemas'
|
||||
icon: "file-export"
|
||||
iconType: "solid"
|
||||
---
|
||||
|
||||
## Overview
|
||||
|
||||
The Memory Export feature allows you to create structured exports of memories using customizable Pydantic schemas. This process enables you to transform your stored memories into specific data formats that match your needs. You can apply various filters to narrow down which memories to export and define exactly how the data should be structured.
|
||||
|
||||
## Creating a Memory Export
|
||||
|
||||
To create a memory export, you'll need to:
|
||||
1. Define your schema structure
|
||||
2. Submit an export job
|
||||
3. Retrieve the exported data
|
||||
|
||||
### Define Schema
|
||||
|
||||
Here's an example schema for extracting professional profile information:
|
||||
|
||||
```json
|
||||
{
|
||||
"$defs": {
|
||||
"EducationLevel": {
|
||||
"enum": ["high_school", "bachelors", "masters"],
|
||||
"title": "EducationLevel",
|
||||
"type": "string"
|
||||
},
|
||||
"EmploymentStatus": {
|
||||
"enum": ["full_time", "part_time", "student"],
|
||||
"title": "EmploymentStatus",
|
||||
"type": "string"
|
||||
}
|
||||
},
|
||||
"properties": {
|
||||
"full_name": {
|
||||
"anyOf": [
|
||||
{
|
||||
"maxLength": 100,
|
||||
"minLength": 2,
|
||||
"type": "string"
|
||||
},
|
||||
{
|
||||
"type": "null"
|
||||
}
|
||||
],
|
||||
"default": null,
|
||||
"description": "The professional's full name",
|
||||
"title": "Full Name"
|
||||
},
|
||||
"current_role": {
|
||||
"anyOf": [
|
||||
{
|
||||
"type": "string"
|
||||
},
|
||||
{
|
||||
"type": "null"
|
||||
}
|
||||
],
|
||||
"default": null,
|
||||
"description": "Current job title or role",
|
||||
"title": "Current Role"
|
||||
}
|
||||
},
|
||||
"title": "ProfessionalProfile",
|
||||
"type": "object"
|
||||
}
|
||||
```
|
||||
|
||||
### Submit Export Job
|
||||
|
||||
<CodeGroup>
|
||||
|
||||
```python Python
|
||||
response = client.create_memory_export(
|
||||
schema=json_schema,
|
||||
user_id="user123"
|
||||
)
|
||||
print(response)
|
||||
```
|
||||
|
||||
```bash cURL
|
||||
curl -X POST "https://api.mem0.ai/v1/memories/export/" \
|
||||
-H "Authorization: Token your-api-key" \
|
||||
-H "Content-Type: application/json" \
|
||||
-d '{
|
||||
"schema": {json_schema},
|
||||
"user_id": "user123"
|
||||
}'
|
||||
```
|
||||
|
||||
```json Output
|
||||
{
|
||||
"message": "Memory export request received. The export will be ready in a few seconds.",
|
||||
"id": "550e8400-e29b-41d4-a716-446655440000"
|
||||
}
|
||||
```
|
||||
|
||||
</CodeGroup>
|
||||
|
||||
### Retrieve Export
|
||||
|
||||
Once the export job is complete, you can retrieve the structured data:
|
||||
|
||||
<CodeGroup>
|
||||
|
||||
```python Python
|
||||
response = client.get_memory_export(user_id="user123")
|
||||
print(response)
|
||||
```
|
||||
|
||||
```bash cURL
|
||||
curl -X GET "https://api.mem0.ai/v1/memories/export/?user_id=user123" \
|
||||
-H "Authorization: Token your-api-key"
|
||||
```
|
||||
|
||||
```json Output
|
||||
{
|
||||
"full_name": "John Doe",
|
||||
"current_role": "Senior Software Engineer",
|
||||
"years_experience": 8,
|
||||
"employment_status": "full_time",
|
||||
"education_level": "masters",
|
||||
"skills": ["Python", "AWS", "Machine Learning"]
|
||||
}
|
||||
```
|
||||
|
||||
</CodeGroup>
|
||||
|
||||
## Available Filters
|
||||
|
||||
You can apply various filters to customize which memories are included in the export:
|
||||
|
||||
- `user_id`: Filter memories by specific user
|
||||
- `agent_id`: Filter memories by specific agent
|
||||
- `run_id`: Filter memories by specific run
|
||||
- `session_id`: Filter memories by specific session
|
||||
|
||||
<Note>
|
||||
The export process may take some time to complete, especially when dealing with a large number of memories or complex schemas.
|
||||
</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" />
|
||||
@@ -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,8 +1,81 @@
|
||||
---
|
||||
title: OpenAI Compatibility
|
||||
icon: "code"
|
||||
iconType: "solid"
|
||||
---
|
||||
|
||||
Mem0 seamlessly offers an OpenAI-compatible API, making it easy to incorporate into existing projects.
|
||||
Mem0 can be easily integrated into chat applications to enhance conversational agents with structured memory. Mem0's APIs are designed to be compatible with OpenAI's, with the goal of making it easy to leverage Mem0 in applications you may have already built.
|
||||
|
||||
If you have a `Mem0 API key`, you can use it to initialize the client. Alternatively, you can initialize Mem0 without an API key if you're using it locally.
|
||||
|
||||
Mem0 supports several language models (LLMs) through integration with various [providers](https://litellm.vercel.app/docs/providers).
|
||||
|
||||
## Use Mem0 Platform
|
||||
|
||||
```python
|
||||
from mem0.proxy.main import Mem0
|
||||
|
||||
client = Mem0(api_key="m0-xxx")
|
||||
|
||||
# First interaction: Storing user preferences
|
||||
messages = [
|
||||
{
|
||||
"role": "user",
|
||||
"content": "I love indian food but I cannot eat pizza since allergic to cheese."
|
||||
},
|
||||
]
|
||||
user_id = "alice"
|
||||
chat_completion = client.chat.completions.create(
|
||||
messages=messages,
|
||||
model="gpt-4o-mini",
|
||||
user_id=user_id
|
||||
)
|
||||
# Memory saved after this will look like: "Loves Indian food. Allergic to cheese and cannot eat pizza."
|
||||
|
||||
# Second interaction: Leveraging stored memory
|
||||
messages = [
|
||||
{
|
||||
"role": "user",
|
||||
"content": "Suggest restaurants in San Francisco to eat.",
|
||||
}
|
||||
]
|
||||
|
||||
chat_completion = client.chat.completions.create(
|
||||
messages=messages,
|
||||
model="gpt-4o-mini",
|
||||
user_id=user_id
|
||||
)
|
||||
print(chat_completion.choices[0].message.content)
|
||||
# Answer: You might enjoy Indian restaurants in San Francisco, such as Amber India, Dosa, or Curry Up Now, which offer delicious options without cheese.
|
||||
```
|
||||
|
||||
In this example, you can see how the second response is tailored based on the information provided in the first interaction. Mem0 remembers the user's preference for Indian food and their cheese allergy, using this information to provide more relevant and personalized restaurant suggestions in San Francisco.
|
||||
|
||||
### Use Mem0 OSS
|
||||
|
||||
```python
|
||||
config = {
|
||||
"vector_store": {
|
||||
"provider": "qdrant",
|
||||
"config": {
|
||||
"host": "localhost",
|
||||
"port": 6333,
|
||||
}
|
||||
},
|
||||
}
|
||||
|
||||
client = Mem0(config=config)
|
||||
|
||||
chat_completion = client.chat.completions.create(
|
||||
messages=[
|
||||
{
|
||||
"role": "user",
|
||||
"content": "What's the capital of France?",
|
||||
}
|
||||
],
|
||||
model="gpt-4o",
|
||||
)
|
||||
```
|
||||
|
||||
## Mem0 Params for Chat Completion
|
||||
|
||||
|
||||
@@ -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" />
|
||||
@@ -0,0 +1,108 @@
|
||||
---
|
||||
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
|
||||
|
||||
Memory customization offers several key benefits:
|
||||
|
||||
• **Focused Storage**: Store only relevant information for a streamlined system.
|
||||
|
||||
• **Improved Accuracy**: Curate memories for more accurate and relevant retrieval.
|
||||
|
||||
• **Enhanced Privacy**: Exclude sensitive information for better privacy control.
|
||||
|
||||
• **Resource Efficiency**: Optimize storage and processing by keeping only pertinent data.
|
||||
|
||||
• **Personalization**: Tailor the experience to individual user preferences.
|
||||
|
||||
• **Contextual Relevance**: Improve effectiveness in specialized domains or applications.
|
||||
|
||||
These benefits allow users to fine-tune their memory systems, creating a more powerful and personalized AI assistant experience.
|
||||
|
||||
|
||||
## Memory Inclusion
|
||||
Users can define specific kinds of memories to store. This feature enhances memory management by focusing on relevant information, resulting in a more efficient and personalized experience.
|
||||
Here’s how you can do it:
|
||||
|
||||
```python
|
||||
from mem0 import MemoryClient
|
||||
|
||||
m = MemoryClient(api_key="xxx")
|
||||
|
||||
# Define what to include
|
||||
includes = "sports related things"
|
||||
|
||||
messages = [
|
||||
{"role": "user", "content": "Hi, my name is Alice and I love to play badminton"},
|
||||
{"role": "assistant", "content": "Nice to meet you, Alice! Badminton is a great sport."},
|
||||
{"role": "user", "content": "I love music festivals"},
|
||||
{"role": "assistant", "content": "Music festivals are exciting! Do you have a favorite one?"},
|
||||
{"role": "user", "content": "I love eating spicy food"},
|
||||
{"role": "assistant", "content": "Spicy food is delicious! What's your favorite spicy dish?"},
|
||||
{"role": "user", "content": "I love playing baseball with my friends"},
|
||||
{"role": "assistant", "content": "Baseball with friends sounds fun!"},
|
||||
]
|
||||
```
|
||||
|
||||
<CodeGroup>
|
||||
```python Code
|
||||
client.add(messages, user_id="alice", includes=includes)
|
||||
```
|
||||
|
||||
```json Stored Memories
|
||||
User's name is Alice.
|
||||
Alice loves to play badminton.
|
||||
User loves playing baseball with friends.
|
||||
```
|
||||
</CodeGroup>
|
||||
|
||||
|
||||
|
||||
|
||||
## Memory Exclusion
|
||||
|
||||
In addition to specifying what to include, users can also define exclusion rules for their memory management. This feature allows for fine-tuning the memory system by instructing it to omit certain types of information.
|
||||
Here’s how you can do it:
|
||||
|
||||
```python
|
||||
from mem0 import MemoryClient
|
||||
|
||||
m = MemoryClient(api_key="xxx")
|
||||
|
||||
# Define what to exclude
|
||||
excludes = "food preferences"
|
||||
|
||||
messages = [
|
||||
{"role": "user", "content": "Hi, my name is Alice and I love to play badminton"},
|
||||
{"role": "assistant", "content": "Nice to meet you, Alice! Badminton is a great sport."},
|
||||
{"role": "user", "content": "I love music festivals"},
|
||||
{"role": "assistant", "content": "Music festivals are exciting! Do you have a favorite one?"},
|
||||
{"role": "user", "content": "I love eating spicy food"},
|
||||
{"role": "assistant", "content": "Spicy food is delicious! What's your favorite spicy dish?"},
|
||||
{"role": "user", "content": "I love playing baseball with my friends"},
|
||||
{"role": "assistant", "content": "Baseball with friends sounds fun!"},
|
||||
]
|
||||
```
|
||||
|
||||
<CodeGroup>
|
||||
```python Code
|
||||
client.add(messages, user_id="alice", includes=includes)
|
||||
```
|
||||
|
||||
```json Stored Memories
|
||||
User's name is Alice.
|
||||
Alice loves to play badminton.
|
||||
Loves music festivals.
|
||||
User loves playing baseball with friends.
|
||||
```
|
||||
</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" />
|
||||
@@ -0,0 +1,223 @@
|
||||
---
|
||||
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
|
||||
|
||||
### Get Webhooks
|
||||
|
||||
Retrieve all webhooks configured for your project. By default, it uses the project_id from your client configuration, but you can optionally specify a different project:
|
||||
|
||||
<CodeGroup>
|
||||
|
||||
```python Python
|
||||
from mem0 import MemoryClient
|
||||
|
||||
client = MemoryClient(api_key="your-api-key")
|
||||
|
||||
# Get webhooks for the default project
|
||||
webhooks = client.get_webhooks()
|
||||
|
||||
# Or specify a different project
|
||||
webhooks = client.get_webhooks(project_id="proj_123")
|
||||
print(webhooks)
|
||||
```
|
||||
|
||||
```javascript JavaScript
|
||||
const { MemoryClient } = require('mem0ai');
|
||||
const client = new MemoryClient('your-api-key');
|
||||
|
||||
// Get webhooks for the default project
|
||||
const webhooks = await client.getWebhooks();
|
||||
|
||||
// Or specify a different project
|
||||
const webhooks = await client.getWebhooks("proj_123");
|
||||
console.log(webhooks);
|
||||
```
|
||||
|
||||
```json Output
|
||||
[
|
||||
{
|
||||
'webhook_id': "wh_123",
|
||||
'url': 'https://mem0.ai',
|
||||
'name': 'mem0',
|
||||
'owner': 'john',
|
||||
'project': 'default-project',
|
||||
'secret': '3254dde069fe2490216dba7ca4e0f3595619a28e5909ba80d45caed7577f1040',
|
||||
'is_active': True,
|
||||
'created_at': '2025-02-18T22:59:56.804993-08:00',
|
||||
'updated_at': '2025-02-18T23:06:41.479361-08:00'
|
||||
}
|
||||
]
|
||||
|
||||
```
|
||||
|
||||
</CodeGroup>
|
||||
|
||||
### Create Webhook
|
||||
|
||||
Create a new webhook for your project. The webhook will only receive events from the specified project:
|
||||
|
||||
<CodeGroup>
|
||||
|
||||
```python Python
|
||||
# Create a webhook in the default project
|
||||
webhook = client.create_webhook(
|
||||
url="https://your-app.com/webhook",
|
||||
name="Memory Logger"
|
||||
)
|
||||
|
||||
# Or create in a specific project
|
||||
webhook = client.create_webhook(
|
||||
url="https://your-app.com/webhook",
|
||||
name="Memory Logger",
|
||||
project_id="proj_123"
|
||||
)
|
||||
print(webhook)
|
||||
```
|
||||
|
||||
```javascript JavaScript
|
||||
// Create a webhook in the default project
|
||||
const webhook = await client.createWebhook({
|
||||
url: "https://your-app.com/webhook",
|
||||
name: "Memory Logger"
|
||||
});
|
||||
|
||||
// Or create in a specific project
|
||||
const webhook = await client.createWebhook({
|
||||
url: "https://your-app.com/webhook",
|
||||
name: "Memory Logger",
|
||||
projectId: "proj_123"
|
||||
});
|
||||
console.log(webhook);
|
||||
```
|
||||
|
||||
```json Output
|
||||
{
|
||||
'webhook_id': "wh_123",
|
||||
'name': 'Memory Logger',
|
||||
'url': 'https://your-app.com/webhook',
|
||||
'project': 'default-project',
|
||||
'secret': '3254dde069fe2490216dba7ca4e0f3595619a28e5909ba80d45caed7577f1040',
|
||||
'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 in default project
|
||||
updated_webhook = client.update_webhook(
|
||||
webhook_id="wh_123",
|
||||
name="Updated Logger",
|
||||
url="https://your-app.com/new-webhook"
|
||||
)
|
||||
|
||||
# Or update in a specific project
|
||||
updated_webhook = client.update_webhook(
|
||||
webhook_id="wh_123",
|
||||
name="Updated Logger",
|
||||
url="https://your-app.com/new-webhook",
|
||||
project_id="proj_123"
|
||||
)
|
||||
print(updated_webhook)
|
||||
```
|
||||
|
||||
```javascript JavaScript
|
||||
// Update webhook in default project
|
||||
const updatedWebhook = await client.updateWebhook("wh_123", {
|
||||
name: "Updated Logger",
|
||||
url: "https://your-app.com/new-webhook"
|
||||
});
|
||||
|
||||
// Or update in a specific project
|
||||
const updatedWebhook = await client.updateWebhook("wh_123", {
|
||||
name: "Updated Logger",
|
||||
url: "https://your-app.com/new-webhook",
|
||||
projectId: "proj_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 default project
|
||||
response = client.delete_webhook(webhook_id="wh_123")
|
||||
|
||||
# Or delete from a specific project
|
||||
response = client.delete_webhook(webhook_id="wh_123", project_id="proj_123")
|
||||
print(response)
|
||||
```
|
||||
|
||||
```javascript JavaScript
|
||||
// Delete webhook from default project
|
||||
const response = await client.deleteWebhook("wh_123");
|
||||
|
||||
// Or delete from a specific project
|
||||
const response = await client.deleteWebhook("wh_123", "proj_123");
|
||||
console.log(response);
|
||||
```
|
||||
|
||||
```json Output
|
||||
{
|
||||
"message": "Webhook deleted successfully"
|
||||
}
|
||||
```
|
||||
|
||||
</CodeGroup>
|
||||
|
||||
## Webhook Payload
|
||||
|
||||
When a memory event occurs in your project, Mem0 sends a POST request to your webhook URL with the following payload structure:
|
||||
|
||||
```json
|
||||
{
|
||||
"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: 27 KiB |
Binary file not shown.
|
After Width: | Height: | Size: 58 KiB |
Binary file not shown.
|
After Width: | Height: | Size: 59 KiB |
Binary file not shown.
|
After Width: | Height: | Size: 71 KiB |
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user