Update Docs (#3315)
This commit is contained in:
@@ -1,3 +0,0 @@
|
||||
<Note type="info">
|
||||
🔐 Mem0 is now <strong>SOC 2</strong> and <strong>HIPAA</strong> compliant! We're committed to the highest standards of data security and privacy, enabling secure memory for enterprises, healthcare, and beyond. [Learn more](https://mem0.ai/security)
|
||||
</Note>
|
||||
@@ -4,8 +4,6 @@ icon: "info"
|
||||
iconType: "solid"
|
||||
---
|
||||
|
||||
<Snippet file="async-memory-add.mdx" />
|
||||
|
||||
Mem0 provides a powerful set of APIs that allow you to integrate advanced memory management capabilities into your applications. Our APIs are designed to be intuitive, efficient, and scalable, enabling you to create, retrieve, update, and delete memories across various entities such as users, agents, apps, and runs.
|
||||
|
||||
## Key Features
|
||||
|
||||
@@ -1,4 +0,0 @@
|
||||
---
|
||||
title: 'Delete Member'
|
||||
openapi: delete /api/v1/orgs/organizations/{org_id}/members/
|
||||
---
|
||||
@@ -1,9 +0,0 @@
|
||||
---
|
||||
title: 'Update Member'
|
||||
openapi: put /api/v1/orgs/organizations/{org_id}/members/
|
||||
---
|
||||
|
||||
The API provides two roles for organization members:
|
||||
|
||||
- `READER`: Allows viewing of organization resources.
|
||||
- `OWNER`: Grants full administrative access to manage the organization and its resources.
|
||||
@@ -1,4 +0,0 @@
|
||||
---
|
||||
title: 'Delete Member'
|
||||
openapi: delete /api/v1/orgs/organizations/{org_id}/projects/{project_id}/members/
|
||||
---
|
||||
@@ -1,9 +0,0 @@
|
||||
---
|
||||
title: 'Update Member'
|
||||
openapi: put /api/v1/orgs/organizations/{org_id}/projects/{project_id}/members/
|
||||
---
|
||||
|
||||
The API provides two roles for project members:
|
||||
|
||||
- `READER`: Allows viewing of project resources.
|
||||
- `OWNER`: Grants full administrative access to manage the project and its resources.
|
||||
@@ -1,4 +0,0 @@
|
||||
---
|
||||
title: 'Update Project'
|
||||
openapi: patch /api/v1/orgs/organizations/{org_id}/projects/{project_id}/
|
||||
---
|
||||
@@ -3,7 +3,6 @@ title: "Product Updates"
|
||||
mode: "wide"
|
||||
---
|
||||
|
||||
<Snippet file="blank-notif.mdx" />
|
||||
|
||||
<Tabs>
|
||||
<Tab title="Python">
|
||||
@@ -577,7 +576,6 @@ mode: "wide"
|
||||
**Improvements:**
|
||||
- **OSS:** Added baseURL param in LLM Config.
|
||||
</Update>
|
||||
|
||||
<Update label="2025-05-23" description="v2.1.26">
|
||||
**Improvements:**
|
||||
- **Client:** Removed type `string` from `messages` interface
|
||||
|
||||
@@ -4,7 +4,6 @@ icon: "gear"
|
||||
iconType: "solid"
|
||||
---
|
||||
|
||||
<Snippet file="blank-notif.mdx" />
|
||||
|
||||
Config in mem0 is a dictionary that specifies the settings for your embedding models. It allows you to customize the behavior and connection details of your chosen embedder.
|
||||
|
||||
|
||||
@@ -4,8 +4,6 @@ icon: "info"
|
||||
iconType: "solid"
|
||||
---
|
||||
|
||||
<Snippet file="blank-notif.mdx" />
|
||||
|
||||
Mem0 offers support for various embedding models, allowing users to choose the one that best suits their needs.
|
||||
|
||||
## Supported Embedders
|
||||
|
||||
@@ -4,8 +4,6 @@ icon: "gear"
|
||||
iconType: "solid"
|
||||
---
|
||||
|
||||
<Snippet file="blank-notif.mdx" />
|
||||
|
||||
## How to define configurations?
|
||||
|
||||
<Tabs>
|
||||
|
||||
@@ -2,7 +2,6 @@
|
||||
title: Anthropic
|
||||
---
|
||||
|
||||
<Snippet file="blank-notif.mdx" />
|
||||
|
||||
To use Anthropic's models, please set the `ANTHROPIC_API_KEY` which you find on their [Account Settings Page](https://console.anthropic.com/account/keys).
|
||||
|
||||
|
||||
@@ -2,8 +2,6 @@
|
||||
title: AWS Bedrock
|
||||
---
|
||||
|
||||
<Snippet file="blank-notif.mdx" />
|
||||
|
||||
### Setup
|
||||
- Before using the AWS Bedrock LLM, make sure you have the appropriate model access from [Bedrock Console](https://us-east-1.console.aws.amazon.com/bedrock/home?region=us-east-1#/modelaccess).
|
||||
- You will also need to authenticate the `boto3` client by using a method in the [AWS documentation](https://boto3.amazonaws.com/v1/documentation/api/latest/guide/credentials.html#configuring-credentials)
|
||||
|
||||
@@ -2,8 +2,6 @@
|
||||
title: Azure OpenAI
|
||||
---
|
||||
|
||||
<Snippet file="blank-notif.mdx" />
|
||||
|
||||
<Note> Mem0 Now Supports Azure OpenAI Models in TypeScript SDK </Note>
|
||||
|
||||
To use Azure OpenAI models, you have to set the `LLM_AZURE_OPENAI_API_KEY`, `LLM_AZURE_ENDPOINT`, `LLM_AZURE_DEPLOYMENT` and `LLM_AZURE_API_VERSION` environment variables. You can obtain the Azure API key from the [Azure](https://azure.microsoft.com/).
|
||||
|
||||
@@ -2,8 +2,6 @@
|
||||
title: DeepSeek
|
||||
---
|
||||
|
||||
<Snippet file="blank-notif.mdx" />
|
||||
|
||||
To use DeepSeek LLM models, you have to set the `DEEPSEEK_API_KEY` environment variable. You can also optionally set `DEEPSEEK_API_BASE` if you need to use a different API endpoint (defaults to "https://api.deepseek.com").
|
||||
|
||||
## Usage
|
||||
|
||||
@@ -0,0 +1,76 @@
|
||||
---
|
||||
title: Gemini
|
||||
---
|
||||
|
||||
|
||||
|
||||
To use the Gemini model, set the `GEMINI_API_KEY` environment variable. You can obtain the Gemini API key from [Google AI Studio](https://aistudio.google.com/app/apikey).
|
||||
|
||||
> **Note:** As of the latest release, Mem0 uses the new `google.genai` SDK instead of the deprecated `google.generativeai`. All message formatting and model interaction now use the updated `types` module from `google.genai`.
|
||||
|
||||
> **Note:** Some Gemini models are being deprecated and will retire soon. It is recommended to migrate to the latest stable models like `"gemini-2.0-flash-001"` or `"gemini-2.0-flash-lite-001"` to ensure ongoing support and improvements.
|
||||
|
||||
## Usage
|
||||
|
||||
<CodeGroup>
|
||||
```python Python
|
||||
import os
|
||||
from mem0 import Memory
|
||||
|
||||
os.environ["OPENAI_API_KEY"] = "your-openai-api-key" # Used for embedding model
|
||||
os.environ["GEMINI_API_KEY"] = "your-gemini-api-key"
|
||||
|
||||
config = {
|
||||
"llm": {
|
||||
"provider": "gemini",
|
||||
"config": {
|
||||
"model": "gemini-2.0-flash-001",
|
||||
"temperature": 0.2,
|
||||
"max_tokens": 2000,
|
||||
"top_p": 1.0
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
m = Memory.from_config(config)
|
||||
|
||||
messages = [
|
||||
{"role": "user", "content": "I'm planning to watch a movie tonight. Any recommendations?"},
|
||||
{"role": "assistant", "content": "How about thriller movies? They can be quite engaging."},
|
||||
{"role": "user", "content": "I’m not a big fan of thrillers, but I love sci-fi movies."},
|
||||
{"role": "assistant", "content": "Got it! I'll avoid thrillers and suggest sci-fi movies instead."}
|
||||
]
|
||||
|
||||
m.add(messages, user_id="alice", metadata={"category": "movies"})
|
||||
|
||||
```
|
||||
```typescript TypeScript
|
||||
import { Memory } from "mem0ai/oss";
|
||||
|
||||
const config = {
|
||||
llm: {
|
||||
// You can also use "google" as provider ( for backward compatibility )
|
||||
provider: "gemini",
|
||||
config: {
|
||||
model: "gemini-2.0-flash-001",
|
||||
temperature: 0.1
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
const memory = new Memory(config);
|
||||
|
||||
const messages = [
|
||||
{ role: "user", content: "I'm planning to watch a movie tonight. Any recommendations?" },
|
||||
{ role: "assistant", content: "How about thriller movies? They can be quite engaging." },
|
||||
{ role: "user", content: "I’m not a big fan of thrillers, but I love sci-fi movies." },
|
||||
{ role: "assistant", content: "Got it! I'll avoid thrillers and suggest sci-fi movies instead." }
|
||||
]
|
||||
|
||||
await memory.add(messages, { userId: "alice", metadata: { category: "movies" } });
|
||||
```
|
||||
</CodeGroup>
|
||||
|
||||
## Config
|
||||
|
||||
All available parameters for the `Gemini` config are present in [Master List of All Params in Config](../config).
|
||||
@@ -2,8 +2,6 @@
|
||||
title: Google AI
|
||||
---
|
||||
|
||||
<Snippet file="blank-notif.mdx" />
|
||||
|
||||
To use the Gemini model, set the `GOOGLE_API_KEY` environment variable. You can obtain the Google/Gemini API key from [Google AI Studio](https://aistudio.google.com/app/apikey).
|
||||
|
||||
> **Note:** As of the latest release, Mem0 uses the new `google.genai` SDK instead of the deprecated `google.generativeai`. All message formatting and model interaction now use the updated `types` module from `google.genai`.
|
||||
|
||||
@@ -2,8 +2,6 @@
|
||||
title: Groq
|
||||
---
|
||||
|
||||
<Snippet file="blank-notif.mdx" />
|
||||
|
||||
[Groq](https://groq.com/) is the creator of the world's first Language Processing Unit (LPU), providing exceptional speed performance for AI workloads running on their LPU Inference Engine.
|
||||
|
||||
In order to use LLMs from Groq, go to their [platform](https://console.groq.com/keys) and get the API key. Set the API key as `GROQ_API_KEY` environment variable to use the model as given below in the example.
|
||||
|
||||
@@ -2,7 +2,6 @@
|
||||
title: LangChain
|
||||
---
|
||||
|
||||
<Snippet file="blank-notif.mdx" />
|
||||
|
||||
Mem0 supports LangChain as a provider to access a wide range of LLM models. LangChain is a framework for developing applications powered by language models, making it easy to integrate various LLM providers through a consistent interface.
|
||||
|
||||
|
||||
@@ -1,5 +1,3 @@
|
||||
<Snippet file="blank-notif.mdx" />
|
||||
|
||||
[Litellm](https://litellm.vercel.app/docs/) is compatible with over 100 large language models (LLMs), all using a standardized input/output format. You can explore the [available models](https://litellm.vercel.app/docs/providers) to use with Litellm. Ensure you set the `API_KEY` for the model you choose to use.
|
||||
|
||||
## Usage
|
||||
|
||||
@@ -2,8 +2,6 @@
|
||||
title: LM Studio
|
||||
---
|
||||
|
||||
<Snippet file="blank-notif.mdx" />
|
||||
|
||||
To use LM Studio with Mem0, you'll need to have LM Studio running locally with its server enabled. LM Studio provides a way to run local LLMs with an OpenAI-compatible API.
|
||||
|
||||
## Usage
|
||||
|
||||
@@ -2,8 +2,6 @@
|
||||
title: Mistral AI
|
||||
---
|
||||
|
||||
<Snippet file="blank-notif.mdx" />
|
||||
|
||||
To use mistral's models, please obtain the Mistral AI api key from their [console](https://console.mistral.ai/). Set the `MISTRAL_API_KEY` environment variable to use the model as given below in the example.
|
||||
|
||||
## Usage
|
||||
|
||||
@@ -1,5 +1,3 @@
|
||||
<Snippet file="blank-notif.mdx" />
|
||||
|
||||
You can use LLMs from Ollama to run Mem0 locally. These [models](https://ollama.com/search?c=tools) support tool support.
|
||||
|
||||
## Usage
|
||||
|
||||
@@ -2,8 +2,6 @@
|
||||
title: OpenAI
|
||||
---
|
||||
|
||||
<Snippet file="blank-notif.mdx" />
|
||||
|
||||
To use OpenAI LLM models, you have to set the `OPENAI_API_KEY` environment variable. You can obtain the OpenAI API key from the [OpenAI Platform](https://platform.openai.com/account/api-keys).
|
||||
|
||||
> **Note**: The following are currently unsupported with reasoning models `Parallel tool calling`,`temperature`, `top_p`, `presence_penalty`, `frequency_penalty`, `logprobs`, `top_logprobs`, `logit_bias`, `max_tokens`
|
||||
|
||||
@@ -2,8 +2,6 @@
|
||||
title: Sarvam AI
|
||||
---
|
||||
|
||||
<Snippet file="blank-notif.mdx" />
|
||||
|
||||
**Sarvam AI** is an Indian AI company developing language models with a focus on Indian languages and cultural context. Their latest model **Sarvam-M** is designed to understand and generate content in multiple Indian languages while maintaining high performance in English.
|
||||
|
||||
To use Sarvam AI's models, please set the `SARVAM_API_KEY` which you can get from their [platform](https://dashboard.sarvam.ai/).
|
||||
|
||||
@@ -1,5 +1,3 @@
|
||||
<Snippet file="blank-notif.mdx" />
|
||||
|
||||
To use TogetherAI LLM models, you have to set the `TOGETHER_API_KEY` environment variable. You can obtain the TogetherAI API key from their [Account settings page](https://api.together.xyz/settings/api-keys).
|
||||
|
||||
## Usage
|
||||
|
||||
@@ -2,8 +2,6 @@
|
||||
title: vLLM
|
||||
---
|
||||
|
||||
<Snippet file="blank-notif.mdx" />
|
||||
|
||||
[vLLM](https://docs.vllm.ai/) is a high-performance inference engine for large language models that provides significant performance improvements for local inference. It's designed to maximize throughput and memory efficiency for serving LLMs.
|
||||
|
||||
## Prerequisites
|
||||
|
||||
@@ -2,8 +2,6 @@
|
||||
title: xAI
|
||||
---
|
||||
|
||||
<Snippet file="blank-notif.mdx" />
|
||||
|
||||
[xAI](https://x.ai/) is a new AI company founded by Elon Musk that develops large language models, including Grok. Grok is trained on real-time data from X (formerly Twitter) and aims to provide accurate, up-to-date responses with a touch of wit and humor.
|
||||
|
||||
In order to use LLMs from xAI, go to their [platform](https://console.x.ai) and get the API key. Set the API key as `XAI_API_KEY` environment variable to use the model as given below in the example.
|
||||
|
||||
@@ -4,8 +4,6 @@ icon: "info"
|
||||
iconType: "solid"
|
||||
---
|
||||
|
||||
<Snippet file="blank-notif.mdx" />
|
||||
|
||||
Mem0 includes built-in support for various popular large language models. Memory can utilize the LLM provided by the user, ensuring efficient use for specific needs.
|
||||
|
||||
## Usage
|
||||
|
||||
@@ -4,8 +4,6 @@ icon: "gear"
|
||||
iconType: "solid"
|
||||
---
|
||||
|
||||
<Snippet file="blank-notif.mdx" />
|
||||
|
||||
## How to define configurations?
|
||||
|
||||
The `config` is defined as an object with two main keys:
|
||||
|
||||
@@ -4,8 +4,6 @@ icon: "info"
|
||||
iconType: "solid"
|
||||
---
|
||||
|
||||
<Snippet file="blank-notif.mdx" />
|
||||
|
||||
Mem0 includes built-in support for various popular databases. Memory can utilize the database provided by the user, ensuring efficient use for specific needs.
|
||||
|
||||
## Supported Vector Databases
|
||||
|
||||
@@ -3,8 +3,6 @@ title: Development
|
||||
icon: "code"
|
||||
---
|
||||
|
||||
<Snippet file="blank-notif.mdx" />
|
||||
|
||||
# Development Contributions
|
||||
|
||||
We strive to make contributions **easy, collaborative, and enjoyable**. Follow the steps below to ensure a smooth contribution process.
|
||||
|
||||
@@ -3,8 +3,6 @@ title: Documentation
|
||||
icon: "book"
|
||||
---
|
||||
|
||||
<Snippet file="blank-notif.mdx" />
|
||||
|
||||
# Documentation Contributions
|
||||
|
||||
## 📌 Prerequisites
|
||||
|
||||
@@ -1,62 +0,0 @@
|
||||
---
|
||||
title: Memory Operations
|
||||
description: Understanding the core operations for managing memories in AI applications
|
||||
icon: "gear"
|
||||
iconType: "solid"
|
||||
---
|
||||
|
||||
<Snippet file="blank-notif.mdx" />
|
||||
|
||||
Mem0 provides two core operations for managing memories in AI applications: adding new memories and searching existing ones. This guide covers how these operations work and how to use them effectively in your application.
|
||||
|
||||
|
||||
## Core Operations
|
||||
|
||||
Mem0 exposes two main endpoints for interacting with memories:
|
||||
- The `add` endpoint for ingesting conversations and storing them as memories
|
||||
- The `search` endpoint for retrieving relevant memories based on queries
|
||||
|
||||
### Adding Memories
|
||||
|
||||
<Frame caption="Architecture diagram illustrating the process of adding memories.">
|
||||
<img src="../images/add_architecture.png" />
|
||||
</Frame>
|
||||
|
||||
The add operation processes conversations through several steps:
|
||||
|
||||
1. **Information Extraction**
|
||||
* An LLM extracts relevant memories from the conversation
|
||||
* It identifies important entities and their relationships
|
||||
|
||||
2. **Conflict Resolution**
|
||||
* The system compares new information with existing data
|
||||
* It identifies and resolves any contradictions
|
||||
|
||||
3. **Memory Storage**
|
||||
* Vector database stores the actual memories
|
||||
* Graph database maintains relationship information
|
||||
* Information is continuously updated with each interaction
|
||||
|
||||
### Searching Memories
|
||||
|
||||
<Frame caption="Architecture diagram illustrating the memory search process.">
|
||||
<img src="../images/search_architecture.png" />
|
||||
</Frame>
|
||||
|
||||
The search operation retrieves memories through a multi-step process:
|
||||
|
||||
1. **Query Processing**
|
||||
* LLM processes and optimizes the search query
|
||||
* System prepares filters for targeted search
|
||||
|
||||
2. **Vector Search**
|
||||
* Performs semantic search using the optimized query
|
||||
* Ranks results by relevance to the query
|
||||
* Applies specified filters (user, agent, metadata, etc.)
|
||||
|
||||
3. **Result Processing**
|
||||
* Combines and ranks the search results
|
||||
* Returns memories with relevance scores
|
||||
* Includes associated metadata and timestamps
|
||||
|
||||
This semantic search approach ensures accurate memory retrieval, whether you're looking for specific information or exploring related concepts.
|
||||
@@ -5,7 +5,6 @@ icon: "plus"
|
||||
iconType: "solid"
|
||||
---
|
||||
|
||||
<Snippet file="blank-notif.mdx" />
|
||||
|
||||
## Overview
|
||||
|
||||
|
||||
@@ -5,8 +5,6 @@ icon: "trash"
|
||||
iconType: "solid"
|
||||
---
|
||||
|
||||
<Snippet file="blank-notif.mdx" />
|
||||
|
||||
## Overview
|
||||
|
||||
Memories can become outdated, irrelevant, or need to be removed for privacy or compliance reasons. Mem0 offers flexible ways to delete memory:
|
||||
|
||||
@@ -5,8 +5,6 @@ icon: "magnifying-glass"
|
||||
iconType: "solid"
|
||||
---
|
||||
|
||||
<Snippet file="blank-notif.mdx" />
|
||||
|
||||
## Overview
|
||||
|
||||
The `search` operation allows you to retrieve relevant memories based on a natural language query and optional filters like user ID, agent ID, categories, and more. This is the foundation of giving your agents memory-aware behavior.
|
||||
|
||||
@@ -5,8 +5,6 @@ icon: "pencil"
|
||||
iconType: "solid"
|
||||
---
|
||||
|
||||
<Snippet file="blank-notif.mdx" />
|
||||
|
||||
## Overview
|
||||
|
||||
User preferences, interests, and behaviors often evolve over time. The `update` operation lets you revise a stored memory, whether it's updating facts and memories, rephrasing a message, or enriching metadata.
|
||||
|
||||
@@ -5,8 +5,6 @@ icon: "memory"
|
||||
iconType: "solid"
|
||||
---
|
||||
|
||||
<Snippet file="blank-notif.mdx" />
|
||||
|
||||
To build useful AI applications, we need to understand how different memory systems work together. This guide explores the fundamental types of memory in AI systems and shows how Mem0 implements these concepts.
|
||||
|
||||
## Why Memory Matters
|
||||
|
||||
+4
-1
@@ -22,7 +22,7 @@
|
||||
"group": "Getting Started",
|
||||
"icon": "rocket",
|
||||
"pages": [
|
||||
"what-is-mem0",
|
||||
"introduction",
|
||||
"quickstart",
|
||||
"faqs"
|
||||
]
|
||||
@@ -50,6 +50,7 @@
|
||||
"pages": [
|
||||
"platform/overview",
|
||||
"platform/quickstart",
|
||||
"platform/advanced-memory-operations",
|
||||
{
|
||||
"group": "Features",
|
||||
"icon": "star",
|
||||
@@ -153,6 +154,8 @@
|
||||
"components/vectordbs/dbs/elasticsearch",
|
||||
"components/vectordbs/dbs/opensearch",
|
||||
"components/vectordbs/dbs/supabase",
|
||||
"components/vectordbs/dbs/upstash-vector",
|
||||
"components/vectordbs/dbs/vectorize",
|
||||
"components/vectordbs/dbs/vertex_ai",
|
||||
"components/vectordbs/dbs/weaviate",
|
||||
"components/vectordbs/dbs/faiss",
|
||||
|
||||
+2
-5
@@ -3,9 +3,6 @@ title: Overview
|
||||
description: How to use mem0 in your existing applications?
|
||||
---
|
||||
|
||||
<Snippet file="blank-notif.mdx" />
|
||||
|
||||
|
||||
With Mem0, you can create stateful LLM-based applications such as chatbots, virtual assistants, or AI agents. Mem0 enhances your applications by providing a memory layer that makes responses:
|
||||
|
||||
- More personalized
|
||||
@@ -41,8 +38,8 @@ Explore how **Mem0** can power real-world applications and bring personalized, i
|
||||
Build a **Customer Support AI** that recalls user preferences, past chats, and provides context-aware, efficient help.
|
||||
</Card>
|
||||
|
||||
<Card title="Personalized Search Assistant" icon="magnifying-glass" href="/examples/personalized-search-tavily-mem0">
|
||||
Build a **Personalized Search Assistant** that tailors search according to user preferences.
|
||||
<Card title="LlamaIndex + Mem0" icon="book-open" href="/examples/llama-index-mem0">
|
||||
Combine **LlamaIndex** and Mem0 to create a powerful **ReAct Agent** with persistent memory for smarter interactions.
|
||||
</Card>
|
||||
|
||||
<Card title="LlamaIndex + Mem0 Learning System" icon="book-open" href="/examples/llama-index-mem0">
|
||||
|
||||
@@ -1,168 +0,0 @@
|
||||
---
|
||||
title: AI Companion
|
||||
---
|
||||
|
||||
<Snippet file="blank-notif.mdx" />
|
||||
|
||||
You can create a personalised AI Companion using Mem0. This guide will walk you through the necessary steps and provide the complete code to get you started.
|
||||
|
||||
## Overview
|
||||
|
||||
The Personalized AI Companion leverages Mem0 to retain information across interactions, enabling a tailored learning experience. It creates separate memories for both the user and the companion. By integrating with OpenAI's GPT-4 model, the companion can provide detailed and context-aware responses to user queries.
|
||||
|
||||
## Setup
|
||||
Before you begin, ensure you have the required dependencies installed. You can install the necessary packages using pip:
|
||||
|
||||
```bash
|
||||
pip install openai mem0ai
|
||||
```
|
||||
|
||||
## Full Code Example
|
||||
|
||||
Below is the complete code to create and interact with an AI Companion using Mem0:
|
||||
|
||||
```python
|
||||
from openai import OpenAI
|
||||
from mem0 import Memory
|
||||
import os
|
||||
|
||||
# Set the OpenAI API key
|
||||
os.environ['OPENAI_API_KEY'] = 'sk-xxx'
|
||||
|
||||
# Initialize the OpenAI client
|
||||
client = OpenAI()
|
||||
|
||||
class Companion:
|
||||
def __init__(self, user_id, companion_id):
|
||||
"""
|
||||
Initialize the Companion with memory configuration, OpenAI client, and user IDs.
|
||||
:param user_id: ID for storing user-related memories
|
||||
:param companion_id: ID for storing companion-related memories
|
||||
"""
|
||||
config = {
|
||||
"vector_store": {
|
||||
"provider": "qdrant",
|
||||
"config": {
|
||||
"host": "localhost",
|
||||
"port": 6333,
|
||||
}
|
||||
},
|
||||
}
|
||||
self.memory = Memory.from_config(config)
|
||||
self.client = client
|
||||
self.app_id = "app-1"
|
||||
self.USER_ID = user_id
|
||||
self.companion_id = companion_id
|
||||
|
||||
def analyze_question(self, question):
|
||||
"""
|
||||
Analyze the question to determine whether it's about the user or the companion.
|
||||
"""
|
||||
check_prompt = f"""
|
||||
Analyze the given input and determine whether the user is primarily:
|
||||
1) Talking about themselves or asking for personal advice. They may use words like "I" for this.
|
||||
2) Inquiring about the AI companion's capabilities or characteristics They may use words like "you" for this.
|
||||
|
||||
Respond with a single word:
|
||||
- 'user' if the input is focused on the user
|
||||
- 'companion' if the input is focused on the AI companion
|
||||
|
||||
If the input is ambiguous or doesn't clearly fit either category, respond with 'user'.
|
||||
|
||||
Input: {question}
|
||||
"""
|
||||
response = self.client.chat.completions.create(
|
||||
model="gpt-4",
|
||||
messages=[{"role": "user", "content": check_prompt}]
|
||||
)
|
||||
return response.choices[0].message.content
|
||||
|
||||
def ask(self, question):
|
||||
"""
|
||||
Ask a question to the AI and store the relevant facts in memory
|
||||
:param question: The question to ask the AI.
|
||||
"""
|
||||
check_answer = self.analyze_question(question)
|
||||
user_id_to_use = self.USER_ID if check_answer == "user" else self.companion_id
|
||||
|
||||
previous_memories = self.memory.search(question, user_id=user_id_to_use)
|
||||
relevant_memories_text = ""
|
||||
if previous_memories and previous_memories.get('results'):
|
||||
relevant_memories_text = '\n'.join(mem["memory"] for mem in previous_memories['results'])
|
||||
|
||||
prompt = f"User input: {question}\nPrevious {check_answer} memories: {relevant_memories_text}"
|
||||
|
||||
messages = [
|
||||
{
|
||||
"role": "system",
|
||||
"content": "You are the user's romantic companion. Use the user's input and previous memories to respond. Answer based on the context provided."
|
||||
},
|
||||
{
|
||||
"role": "user",
|
||||
"content": prompt
|
||||
}
|
||||
]
|
||||
|
||||
stream = self.client.chat.completions.create(
|
||||
model="gpt-4",
|
||||
stream=True,
|
||||
messages=messages
|
||||
)
|
||||
|
||||
answer = ""
|
||||
for chunk in stream:
|
||||
if chunk.choices[0].delta.content is not None:
|
||||
content = chunk.choices[0].delta.content
|
||||
print(content, end="")
|
||||
answer += content
|
||||
# Store the question and answer in memory
|
||||
self.memory.add(question, user_id=self.USER_ID, metadata={"app_id": self.app_id})
|
||||
self.memory.add(answer, user_id=self.companion_id, metadata={"app_id": self.app_id})
|
||||
|
||||
def get_memories(self, user_id=None):
|
||||
"""
|
||||
Retrieve all memories associated with the given user ID.
|
||||
:param user_id: Optional user ID to filter memories.
|
||||
:return: List of memories.
|
||||
"""
|
||||
return self.memory.get_all(user_id=user_id)
|
||||
|
||||
# Example usage:
|
||||
user_id = "user"
|
||||
companion_id = "companion"
|
||||
ai_companion = Companion(user_id, companion_id)
|
||||
|
||||
# Ask a question
|
||||
ai_companion.ask("Ive been missing you. What have you been up to off late?")
|
||||
```
|
||||
|
||||
### Fetching Memories
|
||||
|
||||
You can fetch all the memories at any point in time using the following code:
|
||||
|
||||
```python
|
||||
def print_memories(user_id, label):
|
||||
print(f"\n{label} Memories:")
|
||||
memories = ai_companion.get_memories(user_id=user_id)
|
||||
if memories:
|
||||
for m in memories:
|
||||
print(f"- {m['memory']}")
|
||||
else:
|
||||
print("No memories found.")
|
||||
|
||||
# Print user memories
|
||||
print_memories(user_id, "User")
|
||||
|
||||
# Print companion memories
|
||||
print_memories(companion_id, "Companion")
|
||||
```
|
||||
|
||||
### Key Points
|
||||
|
||||
- **Initialization**: The Companion class is initialized with the necessary memory configuration and OpenAI client setup.
|
||||
- **Asking Questions**: The ask method sends a question to the AI and stores the relevant information in memory.
|
||||
- **Retrieving Memories**: The get_memories method fetches all stored memories associated with a user.
|
||||
|
||||
### Conclusion
|
||||
|
||||
As the conversation progresses, Mem0's memory automatically updates based on the interactions, providing a continuously improving personalized experience. This setup ensures that the AI Companion can offer contextually relevant and accurate responses, enhancing the user's experience.
|
||||
@@ -2,8 +2,6 @@
|
||||
title: AI Companion in Node.js
|
||||
---
|
||||
|
||||
<Snippet file="blank-notif.mdx" />
|
||||
|
||||
You can create a personalised AI Companion using Mem0. This guide will walk you through the necessary steps and provide the complete code to get you started.
|
||||
|
||||
## Overview
|
||||
|
||||
@@ -2,8 +2,6 @@
|
||||
title: Amazon Stack: AWS Bedrock, AOSS, and Neptune Analytics
|
||||
---
|
||||
|
||||
<Snippet file="blank-notif.mdx" />
|
||||
|
||||
This example demonstrates how to configure and use the `mem0ai` SDK with **AWS Bedrock**, **OpenSearch Service (AOSS)**, and **AWS Neptune Analytics** for persistent memory capabilities in Python.
|
||||
|
||||
## Installation
|
||||
|
||||
@@ -1,7 +1,5 @@
|
||||
# Mem0 Chrome Extension
|
||||
|
||||
<Snippet file="blank-notif.mdx" />
|
||||
|
||||
Enhance your AI interactions with **Mem0**, a Chrome extension that introduces a universal memory layer across platforms like `ChatGPT`, `Claude`, and `Perplexity`. Mem0 ensures seamless context sharing, making your AI experiences more personalized and efficient.
|
||||
|
||||
<Note>
|
||||
|
||||
@@ -2,8 +2,6 @@
|
||||
title: Multi-User Collaboration with Mem0
|
||||
---
|
||||
|
||||
<Snippet file="blank-notif.mdx" />
|
||||
|
||||
## Overview
|
||||
|
||||
Build a multi-user collaborative chat or task management system with Mem0. Each message is attributed to its author, and all messages are stored in a shared project space. Mem0 makes it easy to track contributions, sort and group messages, and collaborate in real time.
|
||||
|
||||
@@ -2,7 +2,6 @@
|
||||
title: Customer Support AI Agent
|
||||
---
|
||||
|
||||
<Snippet file="blank-notif.mdx" />
|
||||
|
||||
You can create a personalized Customer Support AI Agent using Mem0. This guide will walk you through the necessary steps and provide the complete code to get you started.
|
||||
|
||||
|
||||
@@ -2,8 +2,6 @@
|
||||
title: Eliza OS Character
|
||||
---
|
||||
|
||||
<Snippet file="blank-notif.mdx" />
|
||||
|
||||
You can create a personalised Eliza OS Character using Mem0. This guide will walk you through the necessary steps and provide the complete code to get you started.
|
||||
|
||||
## Overview
|
||||
|
||||
@@ -2,8 +2,6 @@
|
||||
title: Email Processing with Mem0
|
||||
---
|
||||
|
||||
<Snippet file="blank-notif.mdx" />
|
||||
|
||||
This guide demonstrates how to build an intelligent email processing system using Mem0's memory capabilities. You'll learn how to store, categorize, retrieve, and analyze emails to create a smart email management solution.
|
||||
|
||||
## Overview
|
||||
|
||||
@@ -1,7 +1,6 @@
|
||||
---
|
||||
title: LlamaIndex ReAct Agent
|
||||
---
|
||||
<Snippet file="blank-notif.mdx" />
|
||||
|
||||
Create a ReAct Agent with LlamaIndex which uses Mem0 as the memory store.
|
||||
|
||||
|
||||
@@ -2,7 +2,6 @@
|
||||
title: Mem0 as an Agentic Tool
|
||||
---
|
||||
|
||||
<Snippet file="blank-notif.mdx" />
|
||||
|
||||
Integrate Mem0's memory capabilities with OpenAI's Agents SDK to create AI agents with persistent memory.
|
||||
You can create agents that remember past conversations and use that context to provide better responses.
|
||||
|
||||
@@ -2,9 +2,6 @@
|
||||
title: Mem0 Demo
|
||||
---
|
||||
|
||||
|
||||
<Snippet file="blank-notif.mdx" />
|
||||
|
||||
You can create a personalized AI Companion using Mem0. This guide will walk you through the necessary steps and provide the complete setup instructions to get you started.
|
||||
|
||||
<video
|
||||
|
||||
@@ -3,7 +3,6 @@ title: 'Healthcare Assistant with Mem0 and Google ADK'
|
||||
description: 'Build a personalized healthcare agent that remembers patient information across conversations using Mem0 and Google ADK'
|
||||
---
|
||||
|
||||
<Snippet file="blank-notif.mdx" />
|
||||
|
||||
# Healthcare Assistant with Memory
|
||||
|
||||
|
||||
@@ -2,8 +2,6 @@
|
||||
title: Mem0 with Mastra
|
||||
---
|
||||
|
||||
<Snippet file="blank-notif.mdx" />
|
||||
|
||||
In this example you'll learn how to use the Mem0 to add long-term memory capabilities to [Mastra's agent](https://mastra.ai/) via tool-use.
|
||||
This memory integration can work alongside Mastra's [agent memory features](https://mastra.ai/docs/agents/01-agent-memory).
|
||||
|
||||
|
||||
@@ -3,8 +3,6 @@ title: 'Mem0 with OpenAI Agents SDK for Voice'
|
||||
description: 'Integrate memory capabilities into your voice agents using Mem0 and OpenAI Agents SDK'
|
||||
---
|
||||
|
||||
<Snippet file="blank-notif.mdx" />
|
||||
|
||||
# Building Voice Agents with Memory using Mem0 and OpenAI Agents SDK
|
||||
|
||||
This guide demonstrates how to combine OpenAI's Agents SDK for voice applications with Mem0's memory capabilities to create a voice assistant that remembers user preferences and past interactions.
|
||||
|
||||
@@ -2,8 +2,6 @@
|
||||
title: Mem0 with Ollama
|
||||
---
|
||||
|
||||
<Snippet file="blank-notif.mdx" />
|
||||
|
||||
## Running Mem0 Locally with Ollama
|
||||
|
||||
Mem0 can be utilized entirely locally by leveraging Ollama for both the embedding model and the language model (LLM). This guide will walk you through the necessary steps and provide the complete code to get you started.
|
||||
|
||||
@@ -1,7 +1,6 @@
|
||||
---
|
||||
title: Memory-Guided Content Writing
|
||||
---
|
||||
<Snippet file="blank-notif.mdx" />
|
||||
|
||||
This guide demonstrates how to leverage **Mem0** to streamline content writing by applying your unique writing style and preferences using persistent memory.
|
||||
|
||||
|
||||
@@ -2,8 +2,6 @@
|
||||
title: Multimodal Demo with Mem0
|
||||
---
|
||||
|
||||
<Snippet file="blank-notif.mdx" />
|
||||
|
||||
Enhance your AI interactions with **Mem0**'s multimodal capabilities. Mem0 now supports image understanding, allowing for richer context and more natural interactions across supported AI platforms.
|
||||
|
||||
> Experience the power of multimodal AI! Test out Mem0's image understanding capabilities at [multimodal-demo.mem0.ai](https://multimodal-demo.mem0.ai)
|
||||
|
||||
@@ -2,8 +2,6 @@
|
||||
title: OpenAI Inbuilt Tools
|
||||
---
|
||||
|
||||
<Snippet file="blank-notif.mdx" />
|
||||
|
||||
Integrate Mem0’s memory capabilities with OpenAI’s Inbuilt Tools to create AI agents with persistent memory.
|
||||
|
||||
## Getting Started
|
||||
|
||||
@@ -2,8 +2,6 @@
|
||||
title: Personalized AI Tutor
|
||||
---
|
||||
|
||||
<Snippet file="blank-notif.mdx" />
|
||||
|
||||
You can create a personalized AI Tutor using Mem0. This guide will walk you through the necessary steps and provide the complete code to get you started.
|
||||
|
||||
## Overview
|
||||
|
||||
@@ -2,7 +2,6 @@
|
||||
title: Personal AI Travel Assistant
|
||||
---
|
||||
|
||||
<Snippet file="blank-notif.mdx" />
|
||||
|
||||
Create a personalized AI Travel Assistant using Mem0. This guide provides step-by-step instructions and the complete code to get you started.
|
||||
|
||||
|
||||
@@ -2,8 +2,6 @@
|
||||
title: Personalized Deep Research
|
||||
---
|
||||
|
||||
<Snippet file="blank-notif.mdx" />
|
||||
|
||||
Deep Research is an intelligent agent that synthesizes large amounts of online data and completes complex research tasks, customized to your unique preferences and insights. Built on Mem0's technology, it enhances AI-driven online exploration with personalized memories.
|
||||
|
||||
You can checkout GitHub repositry here: [Personalized Deep Research](https://github.com/mem0ai/personalized-deep-research/tree/mem0)
|
||||
|
||||
@@ -2,8 +2,6 @@
|
||||
title: YouTube Assistant Extension
|
||||
---
|
||||
|
||||
<Snippet file="blank-notif.mdx" />
|
||||
|
||||
Enhance your YouTube experience with Mem0's **YouTube Assistant**, a Chrome extension that brings AI-powered chat directly to your YouTube videos. Get instant, personalized answers about video content while leveraging your own knowledge and memories - all without leaving the page.
|
||||
|
||||
## Features
|
||||
|
||||
@@ -4,8 +4,6 @@ icon: "question"
|
||||
iconType: "solid"
|
||||
---
|
||||
|
||||
<Snippet file="async-memory-add.mdx" />
|
||||
|
||||
<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.
|
||||
|
||||
@@ -1,23 +0,0 @@
|
||||
---
|
||||
title: Features
|
||||
icon: "wrench"
|
||||
iconType: "solid"
|
||||
---
|
||||
|
||||
<Snippet file="blank-notif.mdx" />
|
||||
|
||||
## Core features
|
||||
|
||||
- **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 relevant memories instead of complete transcripts to context window
|
||||
|
||||
|
||||
|
||||
|
||||
If you have any questions, please feel free to reach out to us using one of the following methods:
|
||||
|
||||
<Snippet file="get-help.mdx" />
|
||||
@@ -3,8 +3,6 @@ title: Overview
|
||||
description: How to integrate Mem0 into other frameworks
|
||||
---
|
||||
|
||||
<Snippet file="blank-notif.mdx" />
|
||||
|
||||
Mem0 seamlessly integrates with popular AI frameworks and tools to enhance your LLM-based applications with persistent memory capabilities. By integrating Mem0, your applications benefit from:
|
||||
|
||||
- Enhanced context management across multiple frameworks
|
||||
@@ -300,8 +298,7 @@ Here are the available integrations for Mem0:
|
||||
<path d="M17.5 12c-.83 0-1.5-.67-1.5-1.5s.67-1.5 1.5-1.5 1.5.67 1.5 1.5-.67 1.5-1.5 1.5z" fill="currentColor"/>
|
||||
<path d="M6.5 12c-.83 0-1.5-.67-1.5-1.5S5.67 9 6.5 9s1.5.67 1.5 1.5S7.33 12 6.5 12z" fill="currentColor"/>
|
||||
</svg>
|
||||
}
|
||||
href="/integrations/pipecat"
|
||||
} href="/integrations/pipecat"
|
||||
>
|
||||
Build conversational AI agents with memory using Pipecat.
|
||||
</Card>
|
||||
|
||||
@@ -1,7 +1,6 @@
|
||||
---
|
||||
title: AgentOps
|
||||
---
|
||||
<Snippet file="blank-notif.mdx" />
|
||||
|
||||
Integrate [**Mem0**](https://github.com/mem0ai/mem0) with [AgentOps](https://agentops.ai), a comprehensive monitoring and analytics platform for AI agents. This integration enables automatic tracking and analysis of memory operations, providing insights into agent performance and memory usage patterns.
|
||||
|
||||
|
||||
@@ -1,8 +1,6 @@
|
||||
---
|
||||
title: Agno
|
||||
---
|
||||
<Snippet file="blank-notif.mdx" />
|
||||
|
||||
|
||||
This integration of [**Mem0**](https://github.com/mem0ai/mem0) with [Agno](https://github.com/agno-agi/agno, enables persistent, multimodal memory for Agno-based agents - improving personalization, context awareness, and continuity across conversations.
|
||||
|
||||
|
||||
@@ -1,7 +1,5 @@
|
||||
Build conversational AI agents with memory capabilities. This integration combines AutoGen for creating AI agents with Mem0 for memory management, enabling context-aware and personalized interactions.
|
||||
|
||||
<Snippet file="blank-notif.mdx" />
|
||||
|
||||
## Overview
|
||||
|
||||
In this guide, we'll explore an example of creating a conversational AI system with memory:
|
||||
|
||||
@@ -2,8 +2,6 @@
|
||||
title: AWS Bedrock
|
||||
---
|
||||
|
||||
<Snippet file="blank-notif.mdx" />
|
||||
|
||||
This integration demonstrates how to use **Mem0** with **AWS Bedrock** and **Amazon OpenSearch Service (AOSS)** to enable persistent, semantic memory in intelligent agents.
|
||||
|
||||
## Overview
|
||||
|
||||
@@ -2,8 +2,6 @@
|
||||
title: CrewAI
|
||||
---
|
||||
|
||||
<Snippet file="blank-notif.mdx" />
|
||||
|
||||
Build an AI system that combines CrewAI's agent-based architecture with Mem0's memory capabilities. This integration enables persistent memory across agent interactions and personalized task execution based on user history.
|
||||
|
||||
## Overview
|
||||
|
||||
@@ -2,8 +2,6 @@
|
||||
title: Dify
|
||||
---
|
||||
|
||||
<Snippet file="blank-notif.mdx" />
|
||||
|
||||
# Integrating Mem0 with Dify AI
|
||||
|
||||
Mem0 brings a robust memory layer to Dify AI, empowering your AI agents with persistent conversation storage and retrieval capabilities. With Mem0, your Dify applications gain the ability to recall past interactions and maintain context, ensuring more natural and insightful conversations.
|
||||
|
||||
@@ -2,8 +2,6 @@
|
||||
title: ElevenLabs
|
||||
---
|
||||
|
||||
<Snippet file="blank-notif.mdx" />
|
||||
|
||||
Create voice-based conversational AI agents with memory capabilities by integrating ElevenLabs and Mem0. This integration enables persistent, context-aware voice interactions that remember past conversations.
|
||||
|
||||
## Overview
|
||||
|
||||
@@ -2,8 +2,6 @@
|
||||
title: Flowise
|
||||
---
|
||||
|
||||
<Snippet file="blank-notif.mdx" />
|
||||
|
||||
The [**Mem0 Memory**](https://github.com/mem0ai/mem0) integration with [Flowise](https://github.com/FlowiseAI/Flowise) enables persistent memory capabilities for your AI chatflows. [Flowise](https://flowiseai.com/) is an open-source low-code tool for developers to build customized LLM orchestration flows & AI agents using a drag & drop interface.
|
||||
|
||||
## Overview
|
||||
|
||||
@@ -2,8 +2,6 @@
|
||||
title: Google Agent Development Kit
|
||||
---
|
||||
|
||||
<Snippet file="blank-notif.mdx" />
|
||||
|
||||
Integrate [**Mem0**](https://github.com/mem0ai/mem0) with [Google Agent Development Kit (ADK)](https://github.com/google/adk-python), an open-source framework for building multi-agent workflows. This integration enables agents to access persistent memory across conversations, enhancing context retention and personalization.
|
||||
|
||||
## Overview
|
||||
|
||||
@@ -2,8 +2,6 @@
|
||||
title: Keywords AI
|
||||
---
|
||||
|
||||
<Snippet file="blank-notif.mdx" />
|
||||
|
||||
Build AI applications with persistent memory and comprehensive LLM observability by integrating Mem0 with Keywords AI.
|
||||
|
||||
## Overview
|
||||
|
||||
@@ -3,8 +3,6 @@ title: Langchain Tools
|
||||
description: 'Integrate Mem0 with LangChain tools to enable AI agents to store, search, and manage memories through structured interfaces'
|
||||
---
|
||||
|
||||
<Snippet file="blank-notif.mdx" />
|
||||
|
||||
## Overview
|
||||
|
||||
Mem0 provides a suite of tools for storing, searching, and retrieving memories, enabling agents to maintain context and learn from past interactions. The tools are built as Langchain tools, making them easily integrable with any AI agent implementation.
|
||||
|
||||
@@ -2,8 +2,6 @@
|
||||
title: Langchain
|
||||
---
|
||||
|
||||
<Snippet file="blank-notif.mdx" />
|
||||
|
||||
Build a personalized Travel Agent AI using LangChain for conversation flow and Mem0 for memory retention. This integration enables context-aware and efficient travel planning experiences.
|
||||
|
||||
## Overview
|
||||
|
||||
@@ -2,8 +2,6 @@
|
||||
title: LangGraph
|
||||
---
|
||||
|
||||
<Snippet file="blank-notif.mdx" />
|
||||
|
||||
Build a personalized Customer Support AI Agent using LangGraph for conversation flow and Mem0 for memory retention. This integration enables context-aware and efficient support experiences.
|
||||
|
||||
## Overview
|
||||
|
||||
@@ -2,8 +2,6 @@
|
||||
title: Livekit
|
||||
---
|
||||
|
||||
<Snippet file="blank-notif.mdx" />
|
||||
|
||||
This guide demonstrates how to create a memory-enabled voice assistant using LiveKit, Deepgram, OpenAI, and Mem0, focusing on creating an intelligent, context-aware travel planning agent.
|
||||
|
||||
## Prerequisites
|
||||
|
||||
@@ -2,8 +2,6 @@
|
||||
title: LlamaIndex
|
||||
---
|
||||
|
||||
<Snippet file="blank-notif.mdx" />
|
||||
|
||||
LlamaIndex supports Mem0 as a [memory store](https://llamahub.ai/l/memory/llama-index-memory-mem0). In this guide, we'll show you how to use it.
|
||||
|
||||
<Note type="info">
|
||||
|
||||
@@ -2,8 +2,6 @@
|
||||
title: Mastra
|
||||
---
|
||||
|
||||
<Snippet file="blank-notif.mdx" />
|
||||
|
||||
The [**Mastra**](https://mastra.ai/) integration demonstrates how to use Mastra's agent system with Mem0 as the memory backend through custom tools. This enables agents to remember and recall information across conversations.
|
||||
|
||||
## Overview
|
||||
|
||||
@@ -1,62 +0,0 @@
|
||||
---
|
||||
title: MCP Server
|
||||
---
|
||||
|
||||
<Snippet file="blank-notif.mdx" />
|
||||
|
||||
## Integrating mem0 as an MCP Server in Cursor
|
||||
[mem0](https://github.com/mem0ai/mem0-mcp) is a powerful tool designed to enhance AI-driven workflows, particularly in code generation and contextual memory. In this guide, we'll walk through integrating mem0 as an **MCP (Model Context Protocol) server** within [Cursor](https://cursor.sh/), an AI-powered coding editor.
|
||||
|
||||
## Prerequisites
|
||||
Before proceeding, ensure you have the following installed:
|
||||
- Cursor IDE
|
||||
- Python (>=3.8)
|
||||
- Git
|
||||
- [mem0-mcp](https://github.com/mem0ai/mem0-mcp) (Clone the repository and set up as per the instructions in the README)
|
||||
|
||||
|
||||
## Configuring Cursor to use mem0 as an MCP Server
|
||||
|
||||
1. **Open Cursor.**
|
||||
2. **Navigate to `Settings` > `Cursor Settings` > `Features` > `MCP Servers`.**
|
||||
3. **Add a new provider using the MCP server:**
|
||||
- Click on **`Add new MCP server`**
|
||||
- Provide a name for the server, e.g. `mem0` and select type as `sse`
|
||||
- Enter the **SSE Endpoint**: `http://0.0.0.0:8080/sse`
|
||||
4. **Save and Restart Cursor** to apply changes.
|
||||
|
||||
## Demo
|
||||
<iframe width="560" height="315" src="https://www.youtube.com/embed/fWa6KX7cpG8?si=cmJDz2sQevGnItSI" title="YouTube video player" frameborder="0" allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture; web-share" referrerpolicy="strict-origin-when-cross-origin" allowfullscreen></iframe>
|
||||
|
||||
## Using mem0 in Cursor
|
||||
Once integrated, mem0 can assist with contextual memory and AI-driven coding enhancements. Some key functionalities include:
|
||||
|
||||
### 1. Storing Coding Preferences
|
||||
Mem0 can store and manage coding preferences, including:
|
||||
- Complete code snippets with dependencies
|
||||
- Language/framework versions
|
||||
- Documentation and comments
|
||||
- Best practices and example usage
|
||||
|
||||
### 2. Retrieving Stored Preferences
|
||||
Access all stored coding references to:
|
||||
- Review implementations
|
||||
- Maintain consistency in coding practices
|
||||
|
||||
### 3. Semantic Search for Preferences
|
||||
Use natural language queries to find:
|
||||
- Code snippets
|
||||
- Technical documentation
|
||||
- Best practices
|
||||
- Setup guides
|
||||
|
||||
## Benefits of Using mem0 in Cursor
|
||||
- **Persistent Context Storage**: Retain and reuse coding insights across sessions.
|
||||
- **Seamless Integration**: Works directly within Cursor as an MCP server.
|
||||
- **Efficient Search**: Retrieve relevant coding insights using semantic search.
|
||||
|
||||
## Conclusion
|
||||
By integrating mem0 as an MCP server within Cursor, you enhance your development workflow with AI-powered memory and context-aware assistance. Follow the steps above to set up and start leveraging mem0 in your coding environment.
|
||||
|
||||
For more details on MCP integration, refer to Cursor's [Model Context Protocol documentation](https://docs.cursor.com/context/model-context-protocol).
|
||||
|
||||
@@ -1,216 +0,0 @@
|
||||
---
|
||||
title: MultiOn
|
||||
---
|
||||
|
||||
<Snippet file="blank-notif.mdx" />
|
||||
|
||||
Build a personal browser agent that remembers user preferences and automates web tasks. It integrates Mem0 for memory management with MultiOn for executing browser actions, enabling personalized and efficient web interactions.
|
||||
|
||||
## Overview
|
||||
|
||||
In this guide, we'll explore two examples of creating Browser-based AI Agents:
|
||||
1. An agent that searches [arxiv.org](https://arxiv.org) for research papers relevant to user's research interests.
|
||||
2. A travel agent that provides personalized travel information based on user preferences. Refer to the [notebook](https://github.com/MULTI-ON/cookbook/blob/main/personalized-travel-agent/mem0_travel_agent.ipynb) for detailed code.
|
||||
|
||||
## Setup and Configuration
|
||||
|
||||
Install necessary libraries:
|
||||
|
||||
```bash
|
||||
pip install mem0ai multion openai
|
||||
```
|
||||
|
||||
First, we'll import the necessary libraries and set up our configurations.
|
||||
|
||||
```python
|
||||
import os
|
||||
from mem0 import Memory, MemoryClient
|
||||
from multion.client import MultiOn
|
||||
from openai import OpenAI
|
||||
|
||||
# Configuration
|
||||
OPENAI_API_KEY = 'sk-xxx' # Replace with your actual OpenAI API key
|
||||
MULTION_API_KEY = 'your-multion-key' # Replace with your actual MultiOn API key
|
||||
MEM0_API_KEY = 'your-mem0-key' # Replace with your actual Mem0 API key
|
||||
USER_ID = "your-user-id"
|
||||
|
||||
# Set up OpenAI API key
|
||||
os.environ['OPENAI_API_KEY'] = OPENAI_API_KEY
|
||||
os.environ['MEM0_API_KEY'] = MEM0_API_KEY
|
||||
|
||||
# Initialize Mem0 and MultiOn
|
||||
memory = Memory() # For local usage
|
||||
memory_client = MemoryClient() # For API usage
|
||||
multion = MultiOn(api_key=MULTION_API_KEY)
|
||||
```
|
||||
|
||||
## Example 1: Research Paper Search Agent
|
||||
|
||||
### Add memories to Mem0
|
||||
|
||||
Define user data and add it to Mem0.
|
||||
|
||||
```python
|
||||
USER_DATA = """
|
||||
About me
|
||||
- I'm Deshraj Yadav, Co-founder and CTO at Mem0, interested in AI and ML Infrastructure.
|
||||
- Previously, I was a Senior Autopilot Engineer at Tesla, leading the AI Platform for Autopilot.
|
||||
- I built EvalAI at Georgia Tech, an open-source platform for evaluating ML algorithms.
|
||||
- Outside of work, I enjoy playing cricket in two leagues in the San Francisco.
|
||||
"""
|
||||
|
||||
memory.add(USER_DATA, user_id=USER_ID)
|
||||
print("User data added to memory.")
|
||||
```
|
||||
|
||||
### Retrieving Relevant Memories
|
||||
|
||||
Define search command and retrieve relevant memories from Mem0.
|
||||
|
||||
```python
|
||||
command = "Find papers on arxiv that I should read based on my interests."
|
||||
|
||||
relevant_memories = memory.search(command, user_id=USER_ID, limit=3)
|
||||
relevant_memories_text = '\n'.join(mem['memory'] for mem in relevant_memories['results'])
|
||||
print(f"Relevant memories:")
|
||||
print(relevant_memories_text)
|
||||
```
|
||||
|
||||
### Browsing arXiv
|
||||
|
||||
Use MultiOn to browse arXiv based on the command and relevant memories.
|
||||
|
||||
```python
|
||||
prompt = f"{command}\n My past memories: {relevant_memories_text}"
|
||||
browse_result = multion.browse(cmd=prompt, url="https://arxiv.org/")
|
||||
print(browse_result)
|
||||
```
|
||||
|
||||
## Example 2: Travel Agent
|
||||
|
||||
### Get Travel Information
|
||||
|
||||
Add conversation to Mem0 and create a function to get travel information based on user's question and optionally their preferences from memory.
|
||||
|
||||
<CodeGroup>
|
||||
```python Code
|
||||
def get_travel_info(question, use_memory=True):
|
||||
if use_memory:
|
||||
previous_memories = memory_client.search(question, user_id=USER_ID)
|
||||
relevant_memories_text = ""
|
||||
if previous_memories and previous_memories.get('results'):
|
||||
print("Using previous memories to enhance the search...")
|
||||
relevant_memories_text = '\n'.join(mem["memory"] for mem in previous_memories['results'])
|
||||
|
||||
command = "Find travel information based on my interests:"
|
||||
prompt = f"{command}\n Question: {question} \n My preferences: {relevant_memories_text}"
|
||||
else:
|
||||
command = "Find travel information based on my interests:"
|
||||
prompt = f"{command}\n Question: {question}"
|
||||
|
||||
print("Searching for travel information...")
|
||||
browse_result = multion.browse(cmd=prompt)
|
||||
return browse_result.message
|
||||
|
||||
# Example usage
|
||||
question = "Show me flight details for it."
|
||||
answer_without_memory = get_travel_info(question, use_memory=False)
|
||||
answer_with_memory = get_travel_info(question, use_memory=True)
|
||||
|
||||
print("Answer without memory:", answer_without_memory)
|
||||
print("Answer with memory:", answer_with_memory)
|
||||
|
||||
# Another example
|
||||
question = "What is the best place to eat there?"
|
||||
answer_without_memory = get_travel_info(question, use_memory=False)
|
||||
answer_with_memory = get_travel_info(question, use_memory=True)
|
||||
|
||||
print("Answer without memory:", answer_without_memory)
|
||||
print("Answer with memory:", answer_with_memory)
|
||||
```
|
||||
|
||||
```json Conversation
|
||||
# Add conversation to Mem0
|
||||
conversation = [
|
||||
{
|
||||
"role": "user",
|
||||
"content": "What are the best travel destinations in the world?"
|
||||
},
|
||||
{
|
||||
"role": "assistant",
|
||||
"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."
|
||||
},
|
||||
{
|
||||
"role": "user",
|
||||
"content": "Sure, I want to travel to San Francisco."
|
||||
},
|
||||
{
|
||||
"role": "assistant",
|
||||
"content": """
|
||||
Based on the information gathered from TripAdvisor, here are some popular attractions, activities, and travel tips for San Francisco: \
|
||||
|
||||
1. **Golden Gate Bridge**: A must-see iconic landmark. \
|
||||
2. **Alcatraz Island**: Famous former prison offering tours. \
|
||||
3. **Fisherman's Wharf**: Popular tourist area with shops, restaurants, and sea lions. \
|
||||
4. **Chinatown**: The largest Chinatown outside of Asia. \
|
||||
5. **Golden Gate Park**: Large urban park with gardens, museums, and recreational activities. \
|
||||
6. **Cable Cars**: Historic streetcars offering a unique way to see the city. \
|
||||
7. **Exploratorium**: Interactive science museum. \
|
||||
8. **San Francisco Museum of Modern Art (SFMOMA)**: Modern and contemporary art museum. \
|
||||
9. **Lombard Street**: Known for its steep, one-block section with eight hairpin turns. \
|
||||
10. **Union Square**: Major shopping and cultural hub. \
|
||||
|
||||
Travel Tips: \
|
||||
- **Weather**: San Francisco has a mild climate, but it can be foggy and windy. Dress in layers. \
|
||||
- **Transportation**: Use public transportation like BART, Muni, and cable cars to get around. \
|
||||
- **Safety**: Be aware of your surroundings, especially in crowded tourist areas. \
|
||||
- **Dining**: Try local specialities like sourdough bread, seafood, and Mission-style burritos. \
|
||||
"""
|
||||
},
|
||||
{
|
||||
"role": "user",
|
||||
"content": "Show me hotels around Golden Gate Bridge."
|
||||
},
|
||||
{
|
||||
"role": "assistant",
|
||||
"content": """The search results for hotels around Golden Gate Bridge in San Francisco include: \
|
||||
|
||||
1. Hilton Hotels In San Francisco - Hotel Near Fishermans Wharf (hilton.com) \
|
||||
2. The 10 Closest Hotels to Golden Gate Bridge (tripadvisor.com) \
|
||||
3. Hotels near Golden Gate Bridge (expedia.com) \
|
||||
4. Hotels near Golden Gate Bridge (hotels.com) \
|
||||
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 \
|
||||
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 \
|
||||
7. Hotel Zephyr San Francisco $159 (3.8K) 4-star hotel Golden Gate Bridge • 3.7 mi Nautical-themed lodging with bay views \
|
||||
8. Lodge at the Presidio \
|
||||
9. The Inn Above Tide \
|
||||
10. Cavallo Point \
|
||||
11. Casa Madrona Hotel and Spa \
|
||||
12. Cow Hollow Inn and Suites \
|
||||
13. Samesun San Francisco \
|
||||
14. Inn on Broadway \
|
||||
15. Coventry Motor Inn \
|
||||
16. HI San Francisco Fisherman's Wharf Hostel \
|
||||
17. Loews Regency San Francisco Hotel \
|
||||
18. Fairmont Heritage Place Ghirardelli Square \
|
||||
19. Hotel Drisco Pacific Heights \
|
||||
20. Travelodge by Wyndham Presidio San Francisco \
|
||||
"""
|
||||
}
|
||||
]
|
||||
```
|
||||
</CodeGroup>
|
||||
|
||||
## Conclusion
|
||||
|
||||
By integrating Mem0 with MultiOn, you've created personalized browser agents that remember user preferences and automate web tasks. The first example demonstrates a research-focused agent, while the second example shows a travel agent capable of providing personalized recommendations.
|
||||
|
||||
These examples illustrate how combining memory management with web browsing capabilities can create powerful, context-aware AI agents for various applications.
|
||||
|
||||
## Help
|
||||
|
||||
- For more details and advanced usage, refer to the full [cookbooks here](https://github.com/mem0ai/mem0/blob/main/cookbooks).
|
||||
- Feel free to visit our [Github](https://github.com/mem0ai/mem0) or [Mem0 Platform](https://app.mem0.ai/).
|
||||
- For any questions or assistance, please reach out to `taranjeetio` on [Discord](https://mem0.dev/DiD).
|
||||
|
||||
<Snippet file="get-help.mdx" />
|
||||
@@ -2,8 +2,6 @@
|
||||
title: OpenAI Agents SDK
|
||||
---
|
||||
|
||||
<Snippet file="blank-notif.mdx" />
|
||||
|
||||
Integrate [**Mem0**](https://github.com/mem0ai/mem0) with [OpenAI Agents SDK](https://github.com/openai/openai-agents-python), a lightweight framework for building multi-agent workflows. This integration enables agents to access persistent memory across conversations, enhancing context retention and personalization.
|
||||
|
||||
## Overview
|
||||
|
||||
@@ -3,8 +3,6 @@ title: 'Pipecat'
|
||||
description: 'Integrate Mem0 with Pipecat for conversational memory in AI agents'
|
||||
---
|
||||
|
||||
<Snippet file="blank-notif.mdx" />
|
||||
|
||||
# Pipecat Integration
|
||||
|
||||
Mem0 seamlessly integrates with [Pipecat](https://pipecat.ai), providing long-term memory capabilities for conversational AI agents. This integration allows your Pipecat-powered applications to remember past conversations and provide personalized responses based on user history.
|
||||
|
||||
@@ -3,8 +3,6 @@ title: "Raycast Extension"
|
||||
description: "Mem0 Raycast extension for intelligent memory management"
|
||||
---
|
||||
|
||||
<Snippet file="blank-notif.mdx" />
|
||||
|
||||
Mem0 is a self-improving memory layer for LLM applications, enabling personalized AI experiences that save costs and delight users. This extension lets you store and retrieve text snippets using Mem0's intelligent memory system. Find Mem0 in [Raycast Store](https://www.raycast.com/dev_khant/mem0) for using it.
|
||||
|
||||
## Getting Started
|
||||
|
||||
@@ -2,8 +2,6 @@
|
||||
title: Vercel AI SDK
|
||||
---
|
||||
|
||||
<Snippet file="blank-notif.mdx" />
|
||||
|
||||
The [**Mem0 AI SDK Provider**](https://www.npmjs.com/package/@mem0/vercel-ai-provider) is a library developed by **Mem0** to integrate with the Vercel AI SDK. This library brings enhanced AI interaction capabilities to your applications by introducing persistent memory functionality.
|
||||
|
||||
<Note type="info">
|
||||
|
||||
@@ -1,11 +1,9 @@
|
||||
---
|
||||
title: What is Mem0?
|
||||
icon: "brain"
|
||||
title: Introduction
|
||||
icon: "book"
|
||||
iconType: "solid"
|
||||
---
|
||||
|
||||
<Snippet file="async-memory-add.mdx" />
|
||||
|
||||
Mem0 is a memory layer designed for modern AI agents. It acts as a persistent memory layer that agents can use to:
|
||||
|
||||
- Recall relevant past interactions
|
||||
@@ -1,6 +0,0 @@
|
||||
---
|
||||
title: Introduction
|
||||
description: A collection of answers to Frequently asked questions about Mem0.
|
||||
---
|
||||
|
||||
Coming soon.
|
||||
@@ -5,8 +5,6 @@ icon: "bolt"
|
||||
iconType: "solid"
|
||||
---
|
||||
|
||||
<Snippet file="blank-notif.mdx" />
|
||||
|
||||
## AsyncMemory
|
||||
|
||||
The `AsyncMemory` class is a direct asynchronous interface to Mem0's in-process memory operations. Unlike the memory, which interacts with an API, `AsyncMemory` works directly with the underlying storage systems. This makes it ideal for applications where you want to embed Mem0 directly into your codebase.
|
||||
@@ -46,13 +44,17 @@ All methods in `AsyncMemory` have the same parameters as the synchronous `Memory
|
||||
Add a new memory asynchronously:
|
||||
|
||||
```python Python
|
||||
await memory.add(
|
||||
messages=[
|
||||
{"role": "user", "content": "I'm travelling to SF"},
|
||||
{"role": "assistant", "content": "That's great to hear!"}
|
||||
],
|
||||
user_id="alice"
|
||||
)
|
||||
try:
|
||||
result = await memory.add(
|
||||
messages=[
|
||||
{"role": "user", "content": "I'm travelling to SF"},
|
||||
{"role": "assistant", "content": "That's great to hear!"}
|
||||
],
|
||||
user_id="alice"
|
||||
)
|
||||
print("Memory added successfully:", result)
|
||||
except Exception as e:
|
||||
print(f"Error adding memory: {e}")
|
||||
```
|
||||
|
||||
#### Retrieve memories
|
||||
@@ -60,10 +62,14 @@ await memory.add(
|
||||
Retrieve memories related to a query:
|
||||
|
||||
```python Python
|
||||
await memory.search(
|
||||
query="Where am I travelling?",
|
||||
user_id="alice"
|
||||
)
|
||||
try:
|
||||
results = await memory.search(
|
||||
query="Where am I travelling?",
|
||||
user_id="alice"
|
||||
)
|
||||
print("Found memories:", results)
|
||||
except Exception as e:
|
||||
print(f"Error searching memories: {e}")
|
||||
```
|
||||
|
||||
#### List memories
|
||||
@@ -71,12 +77,11 @@ await memory.search(
|
||||
List all memories for a `user_id`, `agent_id`, and/or `run_id`:
|
||||
|
||||
```python Python
|
||||
await memory.get_all(user_id="alice")
|
||||
|
||||
# Get memories with agent and run context
|
||||
await memory.get_all(user_id="alice", agent_id="assistant")
|
||||
await memory.get_all(user_id="alice", run_id="session-001")
|
||||
await memory.get_all(user_id="alice", agent_id="assistant", run_id="session-001")
|
||||
try:
|
||||
all_memories = await memory.get_all(user_id="alice")
|
||||
print(f"Retrieved {len(all_memories)} memories")
|
||||
except Exception as e:
|
||||
print(f"Error retrieving memories: {e}")
|
||||
```
|
||||
|
||||
#### Get specific memory
|
||||
@@ -84,7 +89,11 @@ await memory.get_all(user_id="alice", agent_id="assistant", run_id="session-001"
|
||||
Retrieve a specific memory by its ID:
|
||||
|
||||
```python Python
|
||||
await memory.get(memory_id="memory-id-here")
|
||||
try:
|
||||
specific_memory = await memory.get(memory_id="memory-id-here")
|
||||
print("Retrieved memory:", specific_memory)
|
||||
except Exception as e:
|
||||
print(f"Error retrieving memory: {e}")
|
||||
```
|
||||
|
||||
#### Update memory
|
||||
@@ -92,10 +101,14 @@ await memory.get(memory_id="memory-id-here")
|
||||
Update an existing memory by ID:
|
||||
|
||||
```python Python
|
||||
await memory.update(
|
||||
memory_id="memory-id-here",
|
||||
data="I'm travelling to Seattle"
|
||||
)
|
||||
try:
|
||||
updated_memory = await memory.update(
|
||||
memory_id="memory-id-here",
|
||||
data="I'm travelling to Seattle"
|
||||
)
|
||||
print("Memory updated successfully:", updated_memory)
|
||||
except Exception as e:
|
||||
print(f"Error updating memory: {e}")
|
||||
```
|
||||
|
||||
#### Delete memory
|
||||
@@ -103,7 +116,11 @@ await memory.update(
|
||||
Delete a specific memory by ID:
|
||||
|
||||
```python Python
|
||||
await memory.delete(memory_id="memory-id-here")
|
||||
try:
|
||||
result = await memory.delete(memory_id="memory-id-here")
|
||||
print("Memory deleted successfully")
|
||||
except Exception as e:
|
||||
print(f"Error deleting memory: {e}")
|
||||
```
|
||||
|
||||
#### Delete all memories
|
||||
@@ -111,10 +128,16 @@ await memory.delete(memory_id="memory-id-here")
|
||||
Delete all memories for a specific user, agent, or run:
|
||||
|
||||
```python Python
|
||||
await memory.delete_all(user_id="alice")
|
||||
try:
|
||||
result = await memory.delete_all(user_id="alice")
|
||||
print("All memories deleted successfully")
|
||||
except Exception as e:
|
||||
print(f"Error deleting memories: {e}")
|
||||
```
|
||||
|
||||
Note: At least one filter (user_id, agent_id, or run_id) is required when using delete_all.
|
||||
<Note>
|
||||
At least one filter (user_id, agent_id, or run_id) is required when using delete_all.
|
||||
</Note>
|
||||
|
||||
### Advanced Memory Organization
|
||||
|
||||
@@ -150,7 +173,11 @@ session_search = await memory.search("What do you know about me?", user_id="alic
|
||||
Get the history of changes for a specific memory:
|
||||
|
||||
```python Python
|
||||
await memory.history(memory_id="memory-id-here")
|
||||
try:
|
||||
history = await memory.history(memory_id="memory-id-here")
|
||||
print("Memory history:", history)
|
||||
except Exception as e:
|
||||
print(f"Error retrieving history: {e}")
|
||||
```
|
||||
|
||||
### Example: Concurrent Usage with Other APIs
|
||||
@@ -166,22 +193,26 @@ async_openai_client = AsyncOpenAI()
|
||||
async_memory = AsyncMemory()
|
||||
|
||||
async def chat_with_memories(message: str, user_id: str = "default_user") -> str:
|
||||
# Retrieve relevant memories
|
||||
search_result = await async_memory.search(query=message, user_id=user_id, limit=3)
|
||||
relevant_memories = search_result["results"]
|
||||
memories_str = "\n".join(f"- {entry['memory']}" for entry in relevant_memories)
|
||||
try:
|
||||
# Retrieve relevant memories
|
||||
search_result = await async_memory.search(query=message, user_id=user_id, limit=3)
|
||||
relevant_memories = search_result["results"]
|
||||
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 = await async_openai_client.chat.completions.create(model="gpt-4o-mini", messages=messages)
|
||||
assistant_response = response.choices[0].message.content
|
||||
# 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 = await async_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})
|
||||
await async_memory.add(messages, user_id=user_id)
|
||||
# Create new memories from the conversation
|
||||
messages.append({"role": "assistant", "content": assistant_response})
|
||||
await async_memory.add(messages, user_id=user_id)
|
||||
|
||||
return assistant_response
|
||||
return assistant_response
|
||||
except Exception as e:
|
||||
print(f"Error in chat_with_memories: {e}")
|
||||
return "I apologize, but I encountered an error processing your request."
|
||||
|
||||
async def async_main():
|
||||
print("Chat with AI (type 'exit' to quit)")
|
||||
@@ -200,6 +231,226 @@ if __name__ == "__main__":
|
||||
main()
|
||||
```
|
||||
|
||||
## Error Handling and Best Practices
|
||||
|
||||
### Common Error Types
|
||||
|
||||
When working with `AsyncMemory`, you may encounter these common errors:
|
||||
|
||||
#### Connection and Configuration Errors
|
||||
|
||||
```python Python
|
||||
import asyncio
|
||||
from mem0 import AsyncMemory
|
||||
from mem0.configs.base import MemoryConfig
|
||||
|
||||
async def handle_initialization_errors():
|
||||
try:
|
||||
# Initialize with custom config
|
||||
config = MemoryConfig(
|
||||
vector_store={"provider": "chroma", "config": {"path": "./chroma_db"}},
|
||||
llm={"provider": "openai", "config": {"model": "gpt-4o-mini"}}
|
||||
)
|
||||
memory = AsyncMemory(config=config)
|
||||
print("AsyncMemory initialized successfully")
|
||||
except ValueError as e:
|
||||
print(f"Configuration error: {e}")
|
||||
except ConnectionError as e:
|
||||
print(f"Connection error: {e}")
|
||||
except Exception as e:
|
||||
print(f"Unexpected initialization error: {e}")
|
||||
|
||||
asyncio.run(handle_initialization_errors())
|
||||
```
|
||||
|
||||
#### Memory Operation Errors
|
||||
|
||||
```python Python
|
||||
async def handle_memory_operation_errors():
|
||||
memory = AsyncMemory()
|
||||
|
||||
try:
|
||||
# Memory not found error
|
||||
result = await memory.get(memory_id="non-existent-id")
|
||||
except ValueError as e:
|
||||
print(f"Invalid memory ID: {e}")
|
||||
except Exception as e:
|
||||
print(f"Memory retrieval error: {e}")
|
||||
|
||||
try:
|
||||
# Invalid search parameters
|
||||
results = await memory.search(query="", user_id="alice")
|
||||
except ValueError as e:
|
||||
print(f"Invalid search query: {e}")
|
||||
except Exception as e:
|
||||
print(f"Search error: {e}")
|
||||
```
|
||||
|
||||
### Performance Optimization
|
||||
|
||||
#### Concurrent Operations
|
||||
|
||||
Take advantage of AsyncMemory's concurrent capabilities:
|
||||
|
||||
```python Python
|
||||
async def batch_operations():
|
||||
memory = AsyncMemory()
|
||||
|
||||
# Process multiple operations concurrently
|
||||
tasks = []
|
||||
for i in range(5):
|
||||
task = memory.add(
|
||||
messages=[{"role": "user", "content": f"Message {i}"}],
|
||||
user_id=f"user_{i}"
|
||||
)
|
||||
tasks.append(task)
|
||||
|
||||
try:
|
||||
results = await asyncio.gather(*tasks, return_exceptions=True)
|
||||
for i, result in enumerate(results):
|
||||
if isinstance(result, Exception):
|
||||
print(f"Task {i} failed: {result}")
|
||||
else:
|
||||
print(f"Task {i} completed successfully")
|
||||
except Exception as e:
|
||||
print(f"Batch operation error: {e}")
|
||||
```
|
||||
|
||||
#### Resource Management
|
||||
|
||||
Properly manage AsyncMemory lifecycle:
|
||||
|
||||
```python Python
|
||||
import asyncio
|
||||
from contextlib import asynccontextmanager
|
||||
|
||||
@asynccontextmanager
|
||||
async def get_memory():
|
||||
memory = AsyncMemory()
|
||||
try:
|
||||
yield memory
|
||||
finally:
|
||||
# Clean up resources if needed
|
||||
pass
|
||||
|
||||
async def safe_memory_usage():
|
||||
async with get_memory() as memory:
|
||||
try:
|
||||
result = await memory.search("test query", user_id="alice")
|
||||
return result
|
||||
except Exception as e:
|
||||
print(f"Memory operation failed: {e}")
|
||||
return None
|
||||
```
|
||||
|
||||
### Timeout and Retry Strategies
|
||||
|
||||
Implement timeout and retry logic for robustness:
|
||||
|
||||
```python Python
|
||||
async def with_timeout_and_retry(operation, max_retries=3, timeout=10.0):
|
||||
for attempt in range(max_retries):
|
||||
try:
|
||||
result = await asyncio.wait_for(operation(), timeout=timeout)
|
||||
return result
|
||||
except asyncio.TimeoutError:
|
||||
print(f"Timeout on attempt {attempt + 1}")
|
||||
except Exception as e:
|
||||
print(f"Error on attempt {attempt + 1}: {e}")
|
||||
|
||||
if attempt < max_retries - 1:
|
||||
await asyncio.sleep(2 ** attempt) # Exponential backoff
|
||||
|
||||
raise Exception(f"Operation failed after {max_retries} attempts")
|
||||
|
||||
# Usage example
|
||||
async def robust_memory_search():
|
||||
memory = AsyncMemory()
|
||||
|
||||
async def search_operation():
|
||||
return await memory.search("test query", user_id="alice")
|
||||
|
||||
try:
|
||||
result = await with_timeout_and_retry(search_operation)
|
||||
print("Search successful:", result)
|
||||
except Exception as e:
|
||||
print(f"Search failed permanently: {e}")
|
||||
```
|
||||
|
||||
### Integration with Async Frameworks
|
||||
|
||||
#### FastAPI Integration
|
||||
|
||||
```python Python
|
||||
from fastapi import FastAPI, HTTPException
|
||||
from mem0 import AsyncMemory
|
||||
import asyncio
|
||||
|
||||
app = FastAPI()
|
||||
memory = AsyncMemory()
|
||||
|
||||
@app.post("/memories/")
|
||||
async def add_memory(messages: list, user_id: str):
|
||||
try:
|
||||
result = await memory.add(messages=messages, user_id=user_id)
|
||||
return {"status": "success", "data": result}
|
||||
except Exception as e:
|
||||
raise HTTPException(status_code=500, detail=str(e))
|
||||
|
||||
@app.get("/memories/search")
|
||||
async def search_memories(query: str, user_id: str, limit: int = 10):
|
||||
try:
|
||||
result = await memory.search(query=query, user_id=user_id, limit=limit)
|
||||
return {"status": "success", "data": result}
|
||||
except Exception as e:
|
||||
raise HTTPException(status_code=500, detail=str(e))
|
||||
```
|
||||
|
||||
### Troubleshooting Guide
|
||||
|
||||
| Issue | Possible Causes | Solutions |
|
||||
|-------|----------------|-----------|
|
||||
| **Initialization fails** | Missing dependencies, invalid config | Check dependencies, validate configuration |
|
||||
| **Slow operations** | Large datasets, network latency | Implement caching, optimize queries |
|
||||
| **Memory not found** | Invalid memory ID, deleted memory | Validate IDs, implement existence checks |
|
||||
| **Connection timeouts** | Network issues, server overload | Implement retry logic, check network |
|
||||
| **Out of memory errors** | Large batch operations | Process in smaller batches |
|
||||
|
||||
### Monitoring and Logging
|
||||
|
||||
Add comprehensive logging to your async memory operations:
|
||||
|
||||
```python Python
|
||||
import logging
|
||||
import time
|
||||
from functools import wraps
|
||||
|
||||
logging.basicConfig(level=logging.INFO)
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
def log_async_operation(operation_name):
|
||||
def decorator(func):
|
||||
@wraps(func)
|
||||
async def wrapper(*args, **kwargs):
|
||||
start_time = time.time()
|
||||
logger.info(f"Starting {operation_name}")
|
||||
try:
|
||||
result = await func(*args, **kwargs)
|
||||
duration = time.time() - start_time
|
||||
logger.info(f"{operation_name} completed in {duration:.2f}s")
|
||||
return result
|
||||
except Exception as e:
|
||||
duration = time.time() - start_time
|
||||
logger.error(f"{operation_name} failed after {duration:.2f}s: {e}")
|
||||
raise
|
||||
return wrapper
|
||||
return decorator
|
||||
|
||||
@log_async_operation("Memory Add")
|
||||
async def logged_memory_add(memory, messages, user_id):
|
||||
return await memory.add(messages=messages, user_id=user_id)
|
||||
```
|
||||
|
||||
If you have any questions or need further assistance, please don't hesitate to reach out:
|
||||
|
||||
<Snippet file="get-help.mdx" />
|
||||
|
||||
@@ -5,8 +5,6 @@ icon: "pencil"
|
||||
iconType: "solid"
|
||||
---
|
||||
|
||||
<Snippet file="blank-notif.mdx" />
|
||||
|
||||
## Introduction to Custom Fact Extraction Prompt
|
||||
|
||||
Custom fact extraction prompt allow you to tailor the behavior of your Mem0 instance to specific use cases or domains.
|
||||
|
||||
@@ -4,7 +4,6 @@ icon: "pencil"
|
||||
iconType: "solid"
|
||||
---
|
||||
|
||||
<Snippet file="blank-notif.mdx" />
|
||||
|
||||
Update memory prompt is a prompt used to determine the action to be performed on the memory.
|
||||
By customizing this prompt, you can control how the memory is updated.
|
||||
|
||||
@@ -5,13 +5,17 @@ icon: "image"
|
||||
iconType: "solid"
|
||||
---
|
||||
|
||||
<Snippet file="blank-notif.mdx" />
|
||||
|
||||
Mem0 extends its capabilities beyond text by supporting multimodal data. With this feature, users can seamlessly integrate images into their interactions—allowing Mem0 to extract relevant information.
|
||||
Mem0 extends its capabilities beyond text by supporting multimodal data. With this feature, you can seamlessly integrate images into your interactions—allowing Mem0 to extract relevant information and context from visual content.
|
||||
|
||||
## How It Works
|
||||
|
||||
When a user submits an image, Mem0 processes it to extract textual information and other pertinent details. These details are then added to the user's memory, enhancing the system's ability to understand and recall multimodal inputs.
|
||||
When you submit an image, Mem0:
|
||||
1. **Processes the visual content** using advanced vision models
|
||||
2. **Extracts textual information** and relevant details from the image
|
||||
3. **Stores the extracted information** as searchable memories
|
||||
4. **Maintains context** between visual and textual interactions
|
||||
|
||||
This enables more comprehensive understanding of user interactions that include both text and visual elements.
|
||||
|
||||
<CodeGroup>
|
||||
```python Python
|
||||
@@ -62,7 +66,246 @@ client.add(messages, user_id="alice")
|
||||
```
|
||||
</CodeGroup>
|
||||
|
||||
Using these methods, you can seamlessly incorporate various media types into your interactions, further enhancing Mem0's multimodal capabilities.
|
||||
## Supported Image Formats
|
||||
|
||||
Mem0 supports common image formats:
|
||||
- **JPEG/JPG** - Standard photos and images
|
||||
- **PNG** - Images with transparency support
|
||||
- **WebP** - Modern web-optimized format
|
||||
- **GIF** - Animated and static graphics
|
||||
|
||||
## Local Files vs URLs
|
||||
|
||||
### Using Image URLs
|
||||
Images can be referenced via publicly accessible URLs:
|
||||
|
||||
```python
|
||||
content = {
|
||||
"type": "image_url",
|
||||
"image_url": {
|
||||
"url": "https://example.com/my-image.jpg"
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
### Using Local Files
|
||||
For local images, convert them to base64 format:
|
||||
|
||||
<CodeGroup>
|
||||
```python Python
|
||||
import base64
|
||||
from mem0 import Memory
|
||||
|
||||
def encode_image(image_path):
|
||||
with open(image_path, "rb") as image_file:
|
||||
return base64.b64encode(image_file.read()).decode('utf-8')
|
||||
|
||||
client = Memory()
|
||||
|
||||
# Encode local image
|
||||
base64_image = encode_image("path/to/your/image.jpg")
|
||||
|
||||
messages = [
|
||||
{
|
||||
"role": "user",
|
||||
"content": [
|
||||
{
|
||||
"type": "text",
|
||||
"text": "What's in this image?"
|
||||
},
|
||||
{
|
||||
"type": "image_url",
|
||||
"image_url": {
|
||||
"url": f"data:image/jpeg;base64,{base64_image}"
|
||||
}
|
||||
}
|
||||
]
|
||||
}
|
||||
]
|
||||
|
||||
client.add(messages, user_id="alice")
|
||||
```
|
||||
|
||||
```javascript JavaScript
|
||||
import fs from 'fs';
|
||||
import { Memory } from 'mem0ai';
|
||||
|
||||
function encodeImage(imagePath) {
|
||||
const imageBuffer = fs.readFileSync(imagePath);
|
||||
return imageBuffer.toString('base64');
|
||||
}
|
||||
|
||||
const client = new Memory();
|
||||
|
||||
// Encode local image
|
||||
const base64Image = encodeImage("path/to/your/image.jpg");
|
||||
|
||||
const messages = [
|
||||
{
|
||||
role: "user",
|
||||
content: [
|
||||
{
|
||||
type: "text",
|
||||
text: "What's in this image?"
|
||||
},
|
||||
{
|
||||
type: "image_url",
|
||||
image_url: {
|
||||
url: `data:image/jpeg;base64,${base64Image}`
|
||||
}
|
||||
}
|
||||
]
|
||||
}
|
||||
];
|
||||
|
||||
await client.add(messages, { user_id: "alice" });
|
||||
```
|
||||
</CodeGroup>
|
||||
|
||||
## Advanced Examples
|
||||
|
||||
### Restaurant Menu Analysis
|
||||
```python
|
||||
from mem0 import Memory
|
||||
|
||||
client = Memory()
|
||||
|
||||
messages = [
|
||||
{
|
||||
"role": "user",
|
||||
"content": "I'm looking at this restaurant menu. Help me remember my preferences."
|
||||
},
|
||||
{
|
||||
"role": "user",
|
||||
"content": {
|
||||
"type": "image_url",
|
||||
"image_url": {
|
||||
"url": "https://example.com/restaurant-menu.jpg"
|
||||
}
|
||||
}
|
||||
},
|
||||
{
|
||||
"role": "user",
|
||||
"content": "I'm allergic to peanuts and prefer vegetarian options."
|
||||
}
|
||||
]
|
||||
|
||||
result = client.add(messages, user_id="user123")
|
||||
print(result)
|
||||
```
|
||||
|
||||
### Document Analysis
|
||||
```python
|
||||
# Analyzing receipts, invoices, or documents
|
||||
messages = [
|
||||
{
|
||||
"role": "user",
|
||||
"content": "Store this receipt information for my expense tracking."
|
||||
},
|
||||
{
|
||||
"role": "user",
|
||||
"content": {
|
||||
"type": "image_url",
|
||||
"image_url": {
|
||||
"url": "https://example.com/receipt.jpg"
|
||||
}
|
||||
}
|
||||
}
|
||||
]
|
||||
|
||||
client.add(messages, user_id="user123")
|
||||
```
|
||||
|
||||
## File Size and Performance Considerations
|
||||
|
||||
### Image Size Limits
|
||||
- **Maximum file size**: 20MB per image
|
||||
- **Recommended size**: Under 5MB for optimal performance
|
||||
- **Resolution**: Images are automatically resized if needed
|
||||
|
||||
### Performance Tips
|
||||
1. **Compress large images** before sending to reduce processing time
|
||||
2. **Use appropriate formats** - JPEG for photos, PNG for graphics with text
|
||||
3. **Batch processing** - Send multiple images in separate requests for better reliability
|
||||
|
||||
## Error Handling
|
||||
|
||||
Handle common errors when working with images:
|
||||
|
||||
<CodeGroup>
|
||||
```python Python
|
||||
from mem0 import Memory
|
||||
from mem0.exceptions import InvalidImageError, FileSizeError
|
||||
|
||||
client = Memory()
|
||||
|
||||
try:
|
||||
messages = [{
|
||||
"role": "user",
|
||||
"content": {
|
||||
"type": "image_url",
|
||||
"image_url": {"url": "https://example.com/image.jpg"}
|
||||
}
|
||||
}]
|
||||
|
||||
result = client.add(messages, user_id="user123")
|
||||
print("Image processed successfully")
|
||||
|
||||
except InvalidImageError:
|
||||
print("Invalid image format or corrupted file")
|
||||
except FileSizeError:
|
||||
print("Image file too large")
|
||||
except Exception as e:
|
||||
print(f"Unexpected error: {e}")
|
||||
```
|
||||
|
||||
```javascript JavaScript
|
||||
import { Memory } from 'mem0ai';
|
||||
|
||||
const client = new Memory();
|
||||
|
||||
try {
|
||||
const messages = [{
|
||||
role: "user",
|
||||
content: {
|
||||
type: "image_url",
|
||||
image_url: { url: "https://example.com/image.jpg" }
|
||||
}
|
||||
}];
|
||||
|
||||
const result = await client.add(messages, { user_id: "user123" });
|
||||
console.log("Image processed successfully");
|
||||
|
||||
} catch (error) {
|
||||
if (error.type === 'invalid_image') {
|
||||
console.log("Invalid image format or corrupted file");
|
||||
} else if (error.type === 'file_size_exceeded') {
|
||||
console.log("Image file too large");
|
||||
} else {
|
||||
console.log(`Unexpected error: ${error.message}`);
|
||||
}
|
||||
}
|
||||
```
|
||||
</CodeGroup>
|
||||
|
||||
## Best Practices
|
||||
|
||||
### Image Selection
|
||||
- **Use high-quality images** with clear, readable text and details
|
||||
- **Ensure good lighting** in photos for better text extraction
|
||||
- **Avoid heavily stylized fonts** that may be difficult to read
|
||||
|
||||
### Memory Context
|
||||
- **Provide context** about what information you want extracted
|
||||
- **Combine with text** to give Mem0 better understanding of the image's purpose
|
||||
- **Be specific** about what aspects of the image are important
|
||||
|
||||
### Privacy and Security
|
||||
- **Avoid sensitive information** in images (SSN, passwords, private data)
|
||||
- **Use secure image hosting** for URLs to prevent unauthorized access
|
||||
- **Consider local processing** for highly sensitive visual content
|
||||
|
||||
Using these methods, you can seamlessly incorporate various visual content types into your interactions, further enhancing Mem0's multimodal capabilities for more comprehensive memory management.
|
||||
|
||||
If you have any questions, please feel free to reach out to us using one of the following methods:
|
||||
|
||||
|
||||
@@ -4,8 +4,6 @@ icon: "code"
|
||||
iconType: "solid"
|
||||
---
|
||||
|
||||
<Snippet file="blank-notif.mdx" />
|
||||
|
||||
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.
|
||||
|
||||
@@ -4,8 +4,6 @@ icon: "server"
|
||||
iconType: "solid"
|
||||
---
|
||||
|
||||
<Snippet file="blank-notif.mdx" />
|
||||
|
||||
Mem0 provides a REST API server (written using FastAPI). Users can perform all operations through REST endpoints. The API also includes OpenAPI documentation, accessible at `/docs` when the server is running.
|
||||
|
||||
<Frame caption="APIs supported by Mem0 REST API Server">
|
||||
|
||||
@@ -5,8 +5,6 @@ icon: "list-check"
|
||||
iconType: "solid"
|
||||
---
|
||||
|
||||
<Snippet file="blank-notif.mdx" />
|
||||
|
||||
Graph Memory is a powerful feature that allows users to create and utilize complex relationships between pieces of information.
|
||||
|
||||
## Graph Memory supports the following features:
|
||||
|
||||
@@ -5,8 +5,6 @@ icon: "info"
|
||||
iconType: "solid"
|
||||
---
|
||||
|
||||
<Snippet file="blank-notif.mdx" />
|
||||
|
||||
Mem0 now supports **Graph Memory**.
|
||||
With Graph Memory, users can now create and utilize complex relationships between pieces of information, allowing for more nuanced and context-aware responses.
|
||||
This integration enables users to leverage the strengths of both vector-based and graph-based approaches, resulting in more accurate and comprehensive information retrieval and generation.
|
||||
|
||||
@@ -4,8 +4,6 @@ icon: "image"
|
||||
iconType: "solid"
|
||||
---
|
||||
|
||||
<Snippet file="blank-notif.mdx" />
|
||||
|
||||
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
|
||||
|
||||
@@ -5,8 +5,6 @@ icon: "node"
|
||||
iconType: "solid"
|
||||
---
|
||||
|
||||
<Snippet file="blank-notif.mdx" />
|
||||
|
||||
> Welcome to the Mem0 quickstart guide. This guide will help you get up and running with Mem0 in no time.
|
||||
|
||||
## Installation
|
||||
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user