diff --git a/docs/_snippets/security-compliance.mdx b/docs/_snippets/security-compliance.mdx deleted file mode 100644 index e59e4251a..000000000 --- a/docs/_snippets/security-compliance.mdx +++ /dev/null @@ -1,3 +0,0 @@ - - 🔐 Mem0 is now SOC 2 and HIPAA 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) - diff --git a/docs/api-reference.mdx b/docs/api-reference.mdx index 18359539d..a175d2aec 100644 --- a/docs/api-reference.mdx +++ b/docs/api-reference.mdx @@ -4,8 +4,6 @@ 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 diff --git a/docs/api-reference/organization/delete-org-member.mdx b/docs/api-reference/organization/delete-org-member.mdx deleted file mode 100644 index 4e4c45e45..000000000 --- a/docs/api-reference/organization/delete-org-member.mdx +++ /dev/null @@ -1,4 +0,0 @@ ---- -title: 'Delete Member' -openapi: delete /api/v1/orgs/organizations/{org_id}/members/ ---- \ No newline at end of file diff --git a/docs/api-reference/organization/update-org-member.mdx b/docs/api-reference/organization/update-org-member.mdx deleted file mode 100644 index d682bbcf8..000000000 --- a/docs/api-reference/organization/update-org-member.mdx +++ /dev/null @@ -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. \ No newline at end of file diff --git a/docs/api-reference/project/delete-project-member.mdx b/docs/api-reference/project/delete-project-member.mdx deleted file mode 100644 index 3099cae72..000000000 --- a/docs/api-reference/project/delete-project-member.mdx +++ /dev/null @@ -1,4 +0,0 @@ ---- -title: 'Delete Member' -openapi: delete /api/v1/orgs/organizations/{org_id}/projects/{project_id}/members/ ---- \ No newline at end of file diff --git a/docs/api-reference/project/update-project-member.mdx b/docs/api-reference/project/update-project-member.mdx deleted file mode 100644 index 5b3fb7ec3..000000000 --- a/docs/api-reference/project/update-project-member.mdx +++ /dev/null @@ -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. diff --git a/docs/api-reference/project/update-project.mdx b/docs/api-reference/project/update-project.mdx deleted file mode 100644 index 9ceaba7e9..000000000 --- a/docs/api-reference/project/update-project.mdx +++ /dev/null @@ -1,4 +0,0 @@ ---- -title: 'Update Project' -openapi: patch /api/v1/orgs/organizations/{org_id}/projects/{project_id}/ ---- \ No newline at end of file diff --git a/docs/changelog.mdx b/docs/changelog.mdx index 96f39925c..2bf37067c 100644 --- a/docs/changelog.mdx +++ b/docs/changelog.mdx @@ -3,8 +3,7 @@ title: "Product Updates" mode: "wide" --- - - + @@ -153,7 +152,7 @@ mode: "wide" **Improvements:** -- **Documentation:** +- **Documentation:** - Updated Livekit documentation migration - Updated OpenMemory hosted version documentation - **Core:** Updated categorization flow @@ -190,7 +189,7 @@ mode: "wide" - **LLM:** Added support for OpenAI compatible LLM providers with baseUrl configuration **Improvements:** -- **Documentation:** +- **Documentation:** - Fixed broken links - Improved Graph Memory features documentation clarity - Updated enable_graph documentation @@ -207,14 +206,14 @@ mode: "wide" - **OpenMemory:** Added LLM and Embedding Providers support **Improvements:** -- **Documentation:** +- **Documentation:** - Updated memory export documentation - Enhanced role-based memory attribution rules documentation - Updated API reference and messages documentation - Added Mastra and Raycast documentation - Added NOT filter documentation for Search and GetAll V2 - Announced Claude 4 support -- **Core:** +- **Core:** - Removed support for passing string as input in client.add() - Added support for sarvam-m model - **TypeScript SDK:** Fixed types from message interface @@ -231,7 +230,7 @@ mode: "wide" - **Neo4j:** Added base label configuration support **Improvements:** -- **Documentation:** +- **Documentation:** - Updated Healthcare example index - Enhanced collaborative task agent documentation clarity - Added criteria-based filtering documentation @@ -327,7 +326,7 @@ mode: "wide" - **Vector Stores:** Added reset function for VectorDBs **Improvements:** -- **Documentation:** +- **Documentation:** - Updated timestamp and expiration_date documentation - Fixed v2 search documentation - Added "memory" in EC "Custom config" section @@ -366,12 +365,12 @@ mode: "wide" **New Features:** - **LLM Integrations:** Added Azure OpenAI Embedding Model -- **Examples:** +- **Examples:** - Added movie recommendation using grok3 - Added Voice Assistant using Elevenlabs **Improvements:** -- **Documentation:** +- **Documentation:** - Added keywords AI - Reformatted navbar page URLs - Updated changelog @@ -386,7 +385,7 @@ mode: "wide" - **LLM Integrations:** Added Mistral AI as LLM provider **Improvements:** -- **Documentation:** +- **Documentation:** - Updated changelog - Fixed memory exclusion example - Updated xAI documentation @@ -403,7 +402,7 @@ mode: "wide" **New Features:** - **Langchain Integration:** Added support for Langchain VectorStores -- **Examples:** +- **Examples:** - Added personal assistant example - Added personal study buddy example - Added YouTube assistant Chrome extension example @@ -577,7 +576,6 @@ mode: "wide" **Improvements:** - **OSS:** Added baseURL param in LLM Config. - **Improvements:** - **Client:** Removed type `string` from `messages` interface @@ -1014,7 +1012,7 @@ mode: "wide" **Improvements:** -- **Vercel AI SDK:** Added support for graceful failure in cases services are down. +- **Vercel AI SDK:** Added support for graceful failure in cases services are down. diff --git a/docs/components/embedders/config.mdx b/docs/components/embedders/config.mdx index d2f55b627..dc805e8a0 100644 --- a/docs/components/embedders/config.mdx +++ b/docs/components/embedders/config.mdx @@ -4,7 +4,6 @@ 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. diff --git a/docs/components/embedders/overview.mdx b/docs/components/embedders/overview.mdx index 21afcfd08..4a5990b61 100644 --- a/docs/components/embedders/overview.mdx +++ b/docs/components/embedders/overview.mdx @@ -4,8 +4,6 @@ icon: "info" iconType: "solid" --- - - Mem0 offers support for various embedding models, allowing users to choose the one that best suits their needs. ## Supported Embedders diff --git a/docs/components/llms/config.mdx b/docs/components/llms/config.mdx index 5a7ca6459..08332cb11 100644 --- a/docs/components/llms/config.mdx +++ b/docs/components/llms/config.mdx @@ -4,8 +4,6 @@ icon: "gear" iconType: "solid" --- - - ## How to define configurations? diff --git a/docs/components/llms/models/anthropic.mdx b/docs/components/llms/models/anthropic.mdx index fc06754b2..688d85050 100644 --- a/docs/components/llms/models/anthropic.mdx +++ b/docs/components/llms/models/anthropic.mdx @@ -2,7 +2,6 @@ title: Anthropic --- - To use Anthropic's models, please set the `ANTHROPIC_API_KEY` which you find on their [Account Settings Page](https://console.anthropic.com/account/keys). diff --git a/docs/components/llms/models/aws_bedrock.mdx b/docs/components/llms/models/aws_bedrock.mdx index d919f3cc1..ae1287b83 100644 --- a/docs/components/llms/models/aws_bedrock.mdx +++ b/docs/components/llms/models/aws_bedrock.mdx @@ -2,8 +2,6 @@ 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) diff --git a/docs/components/llms/models/azure_openai.mdx b/docs/components/llms/models/azure_openai.mdx index 0752a571b..11194647a 100644 --- a/docs/components/llms/models/azure_openai.mdx +++ b/docs/components/llms/models/azure_openai.mdx @@ -2,8 +2,6 @@ title: Azure OpenAI --- - - Mem0 Now Supports Azure OpenAI Models in TypeScript SDK 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/). diff --git a/docs/components/llms/models/deepseek.mdx b/docs/components/llms/models/deepseek.mdx index 5098a4eb2..af1783a1c 100644 --- a/docs/components/llms/models/deepseek.mdx +++ b/docs/components/llms/models/deepseek.mdx @@ -2,8 +2,6 @@ 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 diff --git a/docs/components/llms/models/gemini.mdx b/docs/components/llms/models/gemini.mdx new file mode 100644 index 000000000..61579dcad --- /dev/null +++ b/docs/components/llms/models/gemini.mdx @@ -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 + + +```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" } }); +``` + + +## Config + +All available parameters for the `Gemini` config are present in [Master List of All Params in Config](../config). \ No newline at end of file diff --git a/docs/components/llms/models/google_AI.mdx b/docs/components/llms/models/google_AI.mdx index 03ca7230c..aad05d022 100644 --- a/docs/components/llms/models/google_AI.mdx +++ b/docs/components/llms/models/google_AI.mdx @@ -2,8 +2,6 @@ title: Google AI --- - - 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`. diff --git a/docs/components/llms/models/groq.mdx b/docs/components/llms/models/groq.mdx index b5e4451d5..d8f0727ce 100644 --- a/docs/components/llms/models/groq.mdx +++ b/docs/components/llms/models/groq.mdx @@ -2,8 +2,6 @@ title: Groq --- - - [Groq](https://groq.com/) is the creator of the world's first Language Processing Unit (LPU), providing exceptional speed performance for AI workloads running on their LPU Inference Engine. In order to use LLMs from Groq, go to their [platform](https://console.groq.com/keys) and get the API key. Set the API key as `GROQ_API_KEY` environment variable to use the model as given below in the example. diff --git a/docs/components/llms/models/langchain.mdx b/docs/components/llms/models/langchain.mdx index 62d4b3894..c8f4eaa1f 100644 --- a/docs/components/llms/models/langchain.mdx +++ b/docs/components/llms/models/langchain.mdx @@ -2,7 +2,6 @@ title: LangChain --- - 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. diff --git a/docs/components/llms/models/litellm.mdx b/docs/components/llms/models/litellm.mdx index 96839259a..d66669f86 100644 --- a/docs/components/llms/models/litellm.mdx +++ b/docs/components/llms/models/litellm.mdx @@ -1,5 +1,3 @@ - - [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 diff --git a/docs/components/llms/models/lmstudio.mdx b/docs/components/llms/models/lmstudio.mdx index a0fe68935..cb4281235 100644 --- a/docs/components/llms/models/lmstudio.mdx +++ b/docs/components/llms/models/lmstudio.mdx @@ -2,8 +2,6 @@ title: LM Studio --- - - To use LM Studio with Mem0, you'll need to have LM Studio running locally with its server enabled. LM Studio provides a way to run local LLMs with an OpenAI-compatible API. ## Usage diff --git a/docs/components/llms/models/mistral_AI.mdx b/docs/components/llms/models/mistral_AI.mdx index 6207306fd..632d48772 100644 --- a/docs/components/llms/models/mistral_AI.mdx +++ b/docs/components/llms/models/mistral_AI.mdx @@ -2,8 +2,6 @@ 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 diff --git a/docs/components/llms/models/ollama.mdx b/docs/components/llms/models/ollama.mdx index e755d22ff..757fd2cc0 100644 --- a/docs/components/llms/models/ollama.mdx +++ b/docs/components/llms/models/ollama.mdx @@ -1,5 +1,3 @@ - - You can use LLMs from Ollama to run Mem0 locally. These [models](https://ollama.com/search?c=tools) support tool support. ## Usage diff --git a/docs/components/llms/models/openai.mdx b/docs/components/llms/models/openai.mdx index 064607a2f..d31723838 100644 --- a/docs/components/llms/models/openai.mdx +++ b/docs/components/llms/models/openai.mdx @@ -2,8 +2,6 @@ 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). > **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` diff --git a/docs/components/llms/models/sarvam.mdx b/docs/components/llms/models/sarvam.mdx index eaa67a257..0bf1e52df 100644 --- a/docs/components/llms/models/sarvam.mdx +++ b/docs/components/llms/models/sarvam.mdx @@ -2,8 +2,6 @@ title: Sarvam AI --- - - **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/). diff --git a/docs/components/llms/models/together.mdx b/docs/components/llms/models/together.mdx index 7ad4ec669..63182918e 100644 --- a/docs/components/llms/models/together.mdx +++ b/docs/components/llms/models/together.mdx @@ -1,5 +1,3 @@ - - 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 diff --git a/docs/components/llms/models/vllm.mdx b/docs/components/llms/models/vllm.mdx index 901f6f255..1b60c1ab9 100644 --- a/docs/components/llms/models/vllm.mdx +++ b/docs/components/llms/models/vllm.mdx @@ -2,8 +2,6 @@ title: vLLM --- - - [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 diff --git a/docs/components/llms/models/xAI.mdx b/docs/components/llms/models/xAI.mdx index 70e624356..39b159ca4 100644 --- a/docs/components/llms/models/xAI.mdx +++ b/docs/components/llms/models/xAI.mdx @@ -2,8 +2,6 @@ title: xAI --- - - [xAI](https://x.ai/) is a new AI company founded by Elon Musk that develops large language models, including Grok. Grok is trained on real-time data from X (formerly Twitter) and aims to provide accurate, up-to-date responses with a touch of wit and humor. In order to use LLMs from xAI, go to their [platform](https://console.x.ai) and get the API key. Set the API key as `XAI_API_KEY` environment variable to use the model as given below in the example. diff --git a/docs/components/llms/overview.mdx b/docs/components/llms/overview.mdx index 6f875f28f..c5efdce63 100644 --- a/docs/components/llms/overview.mdx +++ b/docs/components/llms/overview.mdx @@ -4,8 +4,6 @@ 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. ## Usage diff --git a/docs/components/vectordbs/config.mdx b/docs/components/vectordbs/config.mdx index ac4272cad..a36e55795 100644 --- a/docs/components/vectordbs/config.mdx +++ b/docs/components/vectordbs/config.mdx @@ -4,8 +4,6 @@ icon: "gear" iconType: "solid" --- - - ## How to define configurations? The `config` is defined as an object with two main keys: diff --git a/docs/components/vectordbs/overview.mdx b/docs/components/vectordbs/overview.mdx index 1c0ac10d7..332a0fdbd 100644 --- a/docs/components/vectordbs/overview.mdx +++ b/docs/components/vectordbs/overview.mdx @@ -4,8 +4,6 @@ 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 diff --git a/docs/contributing/development.mdx b/docs/contributing/development.mdx index c2a455c55..3292c33aa 100644 --- a/docs/contributing/development.mdx +++ b/docs/contributing/development.mdx @@ -3,8 +3,6 @@ title: Development icon: "code" --- - - # Development Contributions We strive to make contributions **easy, collaborative, and enjoyable**. Follow the steps below to ensure a smooth contribution process. diff --git a/docs/contributing/documentation.mdx b/docs/contributing/documentation.mdx index 067f13ad1..33b445deb 100644 --- a/docs/contributing/documentation.mdx +++ b/docs/contributing/documentation.mdx @@ -3,8 +3,6 @@ title: Documentation icon: "book" --- - - # Documentation Contributions ## 📌 Prerequisites diff --git a/docs/core-concepts/memory-operations.mdx b/docs/core-concepts/memory-operations.mdx deleted file mode 100644 index e44c9433c..000000000 --- a/docs/core-concepts/memory-operations.mdx +++ /dev/null @@ -1,62 +0,0 @@ ---- -title: Memory Operations -description: Understanding the core operations for managing memories in AI applications -icon: "gear" -iconType: "solid" ---- - - - -Mem0 provides two core operations for managing memories in AI applications: adding new memories and searching existing ones. This guide covers how these operations work and how to use them effectively in your application. - - -## Core Operations - -Mem0 exposes two main endpoints for interacting with memories: -- The `add` endpoint for ingesting conversations and storing them as memories -- The `search` endpoint for retrieving relevant memories based on queries - -### Adding Memories - - - - - -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 - - - - - -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. \ No newline at end of file diff --git a/docs/core-concepts/memory-operations/add.mdx b/docs/core-concepts/memory-operations/add.mdx index 75e3c9a27..37305b39d 100644 --- a/docs/core-concepts/memory-operations/add.mdx +++ b/docs/core-concepts/memory-operations/add.mdx @@ -5,7 +5,6 @@ icon: "plus" iconType: "solid" --- - ## Overview diff --git a/docs/core-concepts/memory-operations/delete.mdx b/docs/core-concepts/memory-operations/delete.mdx index 7f49b57bb..bdfd35637 100644 --- a/docs/core-concepts/memory-operations/delete.mdx +++ b/docs/core-concepts/memory-operations/delete.mdx @@ -5,8 +5,6 @@ icon: "trash" iconType: "solid" --- - - ## Overview Memories can become outdated, irrelevant, or need to be removed for privacy or compliance reasons. Mem0 offers flexible ways to delete memory: diff --git a/docs/core-concepts/memory-operations/search.mdx b/docs/core-concepts/memory-operations/search.mdx index ad6802d77..496c1eb00 100644 --- a/docs/core-concepts/memory-operations/search.mdx +++ b/docs/core-concepts/memory-operations/search.mdx @@ -5,8 +5,6 @@ icon: "magnifying-glass" iconType: "solid" --- - - ## 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. diff --git a/docs/core-concepts/memory-operations/update.mdx b/docs/core-concepts/memory-operations/update.mdx index a3dcc8fd9..94d22c3aa 100644 --- a/docs/core-concepts/memory-operations/update.mdx +++ b/docs/core-concepts/memory-operations/update.mdx @@ -5,8 +5,6 @@ icon: "pencil" iconType: "solid" --- - - ## 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. diff --git a/docs/core-concepts/memory-types.mdx b/docs/core-concepts/memory-types.mdx index 599a06786..18d10a530 100644 --- a/docs/core-concepts/memory-types.mdx +++ b/docs/core-concepts/memory-types.mdx @@ -5,8 +5,6 @@ icon: "memory" iconType: "solid" --- - - To build useful AI applications, we need to understand how different memory systems work together. This guide explores the fundamental types of memory in AI systems and shows how Mem0 implements these concepts. ## Why Memory Matters diff --git a/docs/docs.json b/docs/docs.json index c93bcdbdc..c6c745ee7 100644 --- a/docs/docs.json +++ b/docs/docs.json @@ -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", diff --git a/docs/examples.mdx b/docs/examples.mdx index 418af5283..908dc4aeb 100644 --- a/docs/examples.mdx +++ b/docs/examples.mdx @@ -3,9 +3,6 @@ title: Overview description: How to use mem0 in your existing applications? --- - - - 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 @@ -20,72 +17,72 @@ Here are some examples of how Mem0 can be integrated into various applications: Explore how **Mem0** can power real-world applications and bring personalized, intelligent experiences to life: - - - Build a personalized AI Companion in **Node.js** that remembers conversations and adapts over time using Mem0. - - - - Run **Mem0 locally** with **Ollama** to create private, stateful AI experiences without relying on cloud APIs. - - - - Create an **AI Tutor** that adapts to student progress, learning style, and history — for a truly customized learning experience. - - - - Develop a **Personal Travel Assistant** that remembers your preferences, past trips, and helps plan future adventures. - - - - Build a **Customer Support AI** that recalls user preferences, past chats, and provides context-aware, efficient help. + + + Build a personalized AI Companion in **Node.js** that remembers conversations and adapts over time using Mem0. - - Build a **Personalized Search Assistant** that tailors search according to user preferences. + + Run **Mem0 locally** with **Ollama** to create private, stateful AI experiences without relying on cloud APIs. + + + + Create an **AI Tutor** that adapts to student progress, learning style, and history — for a truly customized learning experience. + + + + Develop a **Personal Travel Assistant** that remembers your preferences, past trips, and helps plan future adventures. + + + + Build a **Customer Support AI** that recalls user preferences, past chats, and provides context-aware, efficient help. + + + + Combine **LlamaIndex** and Mem0 to create a powerful **ReAct Agent** with persistent memory for smarter interactions. Multi-agent learning system powered by memory. - + - - Add **long-term memory** to ChatGPT, Claude, or Perplexity via the **Mem0 Chrome Extension** — personalize your AI chats anywhere. - + + Add **long-term memory** to ChatGPT, Claude, or Perplexity via the **Mem0 Chrome Extension** — personalize your AI chats anywhere. + - + Integrate **Mem0** into **YouTube's** native UI, providing personalized responses with video context. - - Create a **Writing Assistant** that understands and adapts to your unique style, improving consistency and productivity. - + + Create a **Writing Assistant** that understands and adapts to your unique style, improving consistency and productivity. + - - Supercharge AI with **Mem0's multimodal memory** — blend text, images, and more for richer, context-aware interactions. - + + Supercharge AI with **Mem0's multimodal memory** — blend text, images, and more for richer, context-aware interactions. + - - Build a **Deep Research AI** that remembers your research goals and compiles insights from vast information sources. - + + Build a **Deep Research AI** that remembers your research goals and compiles insights from vast information sources. + - - Integrate Mem0's memory capabilities with OpenAI's Agents SDK to create AI agents with persistent memory. - + + Integrate Mem0's memory capabilities with OpenAI's Agents SDK to create AI agents with persistent memory. + - - Use Mem0's memory capabilities with OpenAI's Inbuilt Tools to create AI agents with persistent memory. - + + Use Mem0's memory capabilities with OpenAI's Inbuilt Tools to create AI agents with persistent memory. + - - Use Mem0's memory capabilities with OpenAI's Inbuilt Tools to create AI agents with persistent memory. + + Use Mem0's memory capabilities with OpenAI's Inbuilt Tools to create AI agents with persistent memory. Build a personalized healthcare assistant with persistent memory using Google's ADK and Mem0. - - Use Mem0's memory capabilities to process emails and create AI agents with persistent memory. - + + Use Mem0's memory capabilities to process emails and create AI agents with persistent memory. + diff --git a/docs/examples/ai_companion.mdx b/docs/examples/ai_companion.mdx deleted file mode 100644 index 485e4a171..000000000 --- a/docs/examples/ai_companion.mdx +++ /dev/null @@ -1,168 +0,0 @@ ---- -title: AI Companion ---- - - - -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. diff --git a/docs/examples/ai_companion_js.mdx b/docs/examples/ai_companion_js.mdx index acd68b502..d170d12bd 100644 --- a/docs/examples/ai_companion_js.mdx +++ b/docs/examples/ai_companion_js.mdx @@ -2,8 +2,6 @@ title: AI Companion in Node.js --- - - You can create a personalised AI Companion using Mem0. This guide will walk you through the necessary steps and provide the complete code to get you started. ## Overview diff --git a/docs/examples/aws_example.mdx b/docs/examples/aws_example.mdx index f27d5ff05..c8a6b3428 100644 --- a/docs/examples/aws_example.mdx +++ b/docs/examples/aws_example.mdx @@ -2,8 +2,6 @@ title: Amazon Stack: AWS Bedrock, AOSS, and Neptune Analytics --- - - 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 diff --git a/docs/examples/chrome-extension.mdx b/docs/examples/chrome-extension.mdx index e97a4d713..a9ed8e3d1 100644 --- a/docs/examples/chrome-extension.mdx +++ b/docs/examples/chrome-extension.mdx @@ -1,7 +1,5 @@ # Mem0 Chrome Extension - - Enhance your AI interactions with **Mem0**, a Chrome extension that introduces a universal memory layer across platforms like `ChatGPT`, `Claude`, and `Perplexity`. Mem0 ensures seamless context sharing, making your AI experiences more personalized and efficient. diff --git a/docs/examples/collaborative-task-agent.mdx b/docs/examples/collaborative-task-agent.mdx index 7995bd2f8..c46e8881f 100644 --- a/docs/examples/collaborative-task-agent.mdx +++ b/docs/examples/collaborative-task-agent.mdx @@ -2,8 +2,6 @@ title: Multi-User Collaboration with Mem0 --- - - ## 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. diff --git a/docs/examples/customer-support-agent.mdx b/docs/examples/customer-support-agent.mdx index 9fb3f4162..e7ff5c0c7 100644 --- a/docs/examples/customer-support-agent.mdx +++ b/docs/examples/customer-support-agent.mdx @@ -2,7 +2,6 @@ title: Customer Support AI Agent --- - 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. diff --git a/docs/examples/eliza_os.mdx b/docs/examples/eliza_os.mdx index 3150eec14..8d0178008 100644 --- a/docs/examples/eliza_os.mdx +++ b/docs/examples/eliza_os.mdx @@ -2,8 +2,6 @@ title: Eliza OS Character --- - - 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 diff --git a/docs/examples/email_processing.mdx b/docs/examples/email_processing.mdx index ee42c4f73..572d18323 100644 --- a/docs/examples/email_processing.mdx +++ b/docs/examples/email_processing.mdx @@ -2,8 +2,6 @@ title: Email Processing with Mem0 --- - - 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 diff --git a/docs/examples/llama-index-mem0.mdx b/docs/examples/llama-index-mem0.mdx index 5ddb2f42e..d7d57715b 100644 --- a/docs/examples/llama-index-mem0.mdx +++ b/docs/examples/llama-index-mem0.mdx @@ -1,7 +1,6 @@ --- title: LlamaIndex ReAct Agent --- - Create a ReAct Agent with LlamaIndex which uses Mem0 as the memory store. diff --git a/docs/examples/mem0-agentic-tool.mdx b/docs/examples/mem0-agentic-tool.mdx index e37cd2509..a616876e4 100644 --- a/docs/examples/mem0-agentic-tool.mdx +++ b/docs/examples/mem0-agentic-tool.mdx @@ -2,7 +2,6 @@ title: Mem0 as an Agentic Tool --- - Integrate Mem0's memory capabilities with OpenAI's Agents SDK to create AI agents with persistent memory. You can create agents that remember past conversations and use that context to provide better responses. diff --git a/docs/examples/mem0-demo.mdx b/docs/examples/mem0-demo.mdx index 7e2840467..5b129f6f4 100644 --- a/docs/examples/mem0-demo.mdx +++ b/docs/examples/mem0-demo.mdx @@ -2,9 +2,6 @@ title: Mem0 Demo --- - - - You can create a personalized AI Companion using Mem0. This guide will walk you through the necessary steps and provide the complete setup instructions to get you started. diff --git a/docs/integrations/agentops.mdx b/docs/integrations/agentops.mdx index 3f4a77064..315cca554 100644 --- a/docs/integrations/agentops.mdx +++ b/docs/integrations/agentops.mdx @@ -1,7 +1,6 @@ --- title: AgentOps --- - 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. diff --git a/docs/integrations/agno.mdx b/docs/integrations/agno.mdx index 7b4a9d10a..e35e94bf9 100644 --- a/docs/integrations/agno.mdx +++ b/docs/integrations/agno.mdx @@ -1,8 +1,6 @@ --- title: Agno --- - - 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. diff --git a/docs/integrations/autogen.mdx b/docs/integrations/autogen.mdx index 4fa877038..82e407f45 100644 --- a/docs/integrations/autogen.mdx +++ b/docs/integrations/autogen.mdx @@ -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. - - ## Overview In this guide, we'll explore an example of creating a conversational AI system with memory: diff --git a/docs/integrations/aws-bedrock.mdx b/docs/integrations/aws-bedrock.mdx index 89ba4c0fc..4c6b9bec7 100644 --- a/docs/integrations/aws-bedrock.mdx +++ b/docs/integrations/aws-bedrock.mdx @@ -2,8 +2,6 @@ title: AWS Bedrock --- - - This integration demonstrates how to use **Mem0** with **AWS Bedrock** and **Amazon OpenSearch Service (AOSS)** to enable persistent, semantic memory in intelligent agents. ## Overview diff --git a/docs/integrations/crewai.mdx b/docs/integrations/crewai.mdx index f9c5fd75a..3f69fcefc 100644 --- a/docs/integrations/crewai.mdx +++ b/docs/integrations/crewai.mdx @@ -2,8 +2,6 @@ title: CrewAI --- - - 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 diff --git a/docs/integrations/dify.mdx b/docs/integrations/dify.mdx index cfb3d2a72..e08b367bf 100644 --- a/docs/integrations/dify.mdx +++ b/docs/integrations/dify.mdx @@ -2,8 +2,6 @@ title: Dify --- - - # 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. diff --git a/docs/integrations/elevenlabs.mdx b/docs/integrations/elevenlabs.mdx index fc5df9a6b..6e6710fa3 100644 --- a/docs/integrations/elevenlabs.mdx +++ b/docs/integrations/elevenlabs.mdx @@ -2,8 +2,6 @@ title: ElevenLabs --- - - 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 diff --git a/docs/integrations/flowise.mdx b/docs/integrations/flowise.mdx index d70ade147..9f1d747d9 100644 --- a/docs/integrations/flowise.mdx +++ b/docs/integrations/flowise.mdx @@ -2,8 +2,6 @@ title: Flowise --- - - 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 diff --git a/docs/integrations/google-ai-adk.mdx b/docs/integrations/google-ai-adk.mdx index 166292fc0..7220a34d4 100644 --- a/docs/integrations/google-ai-adk.mdx +++ b/docs/integrations/google-ai-adk.mdx @@ -2,8 +2,6 @@ title: Google Agent Development Kit --- - - 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 diff --git a/docs/integrations/keywords.mdx b/docs/integrations/keywords.mdx index 0590fefbf..805f702f3 100644 --- a/docs/integrations/keywords.mdx +++ b/docs/integrations/keywords.mdx @@ -2,8 +2,6 @@ title: Keywords AI --- - - Build AI applications with persistent memory and comprehensive LLM observability by integrating Mem0 with Keywords AI. ## Overview diff --git a/docs/integrations/langchain-tools.mdx b/docs/integrations/langchain-tools.mdx index abc3bb6ea..62b3b0d71 100644 --- a/docs/integrations/langchain-tools.mdx +++ b/docs/integrations/langchain-tools.mdx @@ -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' --- - - ## 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. diff --git a/docs/integrations/langchain.mdx b/docs/integrations/langchain.mdx index 42fbdbd75..b485e4167 100644 --- a/docs/integrations/langchain.mdx +++ b/docs/integrations/langchain.mdx @@ -2,8 +2,6 @@ title: Langchain --- - - 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 diff --git a/docs/integrations/langgraph.mdx b/docs/integrations/langgraph.mdx index 7cf6cebae..c4d5f5a4e 100644 --- a/docs/integrations/langgraph.mdx +++ b/docs/integrations/langgraph.mdx @@ -2,8 +2,6 @@ title: LangGraph --- - - 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 diff --git a/docs/integrations/livekit.mdx b/docs/integrations/livekit.mdx index ee06a7adb..ad44235e5 100644 --- a/docs/integrations/livekit.mdx +++ b/docs/integrations/livekit.mdx @@ -2,8 +2,6 @@ title: Livekit --- - - 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 diff --git a/docs/integrations/llama-index.mdx b/docs/integrations/llama-index.mdx index e3d37ccdb..472f3f7d2 100644 --- a/docs/integrations/llama-index.mdx +++ b/docs/integrations/llama-index.mdx @@ -2,8 +2,6 @@ title: LlamaIndex --- - - 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. diff --git a/docs/integrations/mastra.mdx b/docs/integrations/mastra.mdx index 173fd1f97..9b126a44a 100644 --- a/docs/integrations/mastra.mdx +++ b/docs/integrations/mastra.mdx @@ -2,8 +2,6 @@ title: Mastra --- - - 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 diff --git a/docs/integrations/mcp-server.mdx b/docs/integrations/mcp-server.mdx deleted file mode 100644 index 3119fd908..000000000 --- a/docs/integrations/mcp-server.mdx +++ /dev/null @@ -1,62 +0,0 @@ ---- -title: MCP Server ---- - - - -## 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 - - -## 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). - diff --git a/docs/integrations/multion.mdx b/docs/integrations/multion.mdx deleted file mode 100644 index ce07c1ce0..000000000 --- a/docs/integrations/multion.mdx +++ /dev/null @@ -1,216 +0,0 @@ ---- -title: MultiOn ---- - - - -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. - - -```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 \ - """ - } -] -``` - - -## 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). - - \ No newline at end of file diff --git a/docs/integrations/openai-agents-sdk.mdx b/docs/integrations/openai-agents-sdk.mdx index 58d75d76d..084a89607 100644 --- a/docs/integrations/openai-agents-sdk.mdx +++ b/docs/integrations/openai-agents-sdk.mdx @@ -2,8 +2,6 @@ title: OpenAI Agents SDK --- - - 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 diff --git a/docs/integrations/pipecat.mdx b/docs/integrations/pipecat.mdx index 83f9bcb2d..231451b08 100644 --- a/docs/integrations/pipecat.mdx +++ b/docs/integrations/pipecat.mdx @@ -3,8 +3,6 @@ title: 'Pipecat' description: 'Integrate Mem0 with Pipecat for conversational memory in AI agents' --- - - # 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. diff --git a/docs/integrations/raycast.mdx b/docs/integrations/raycast.mdx index cf7b464d7..456bf14df 100644 --- a/docs/integrations/raycast.mdx +++ b/docs/integrations/raycast.mdx @@ -3,8 +3,6 @@ title: "Raycast Extension" description: "Mem0 Raycast extension for intelligent memory management" --- - - 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 diff --git a/docs/integrations/vercel-ai-sdk.mdx b/docs/integrations/vercel-ai-sdk.mdx index 098f1ed95..7983ce0a6 100644 --- a/docs/integrations/vercel-ai-sdk.mdx +++ b/docs/integrations/vercel-ai-sdk.mdx @@ -2,8 +2,6 @@ title: Vercel AI SDK --- - - The [**Mem0 AI SDK Provider**](https://www.npmjs.com/package/@mem0/vercel-ai-provider) is a library developed by **Mem0** to integrate with the Vercel AI SDK. This library brings enhanced AI interaction capabilities to your applications by introducing persistent memory functionality. diff --git a/docs/what-is-mem0.mdx b/docs/introduction.mdx similarity index 98% rename from docs/what-is-mem0.mdx rename to docs/introduction.mdx index e299cab7d..431494beb 100644 --- a/docs/what-is-mem0.mdx +++ b/docs/introduction.mdx @@ -1,11 +1,9 @@ --- -title: What is Mem0? -icon: "brain" +title: Introduction +icon: "book" iconType: "solid" --- - - 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 diff --git a/docs/knowledge-base/introduction.mdx b/docs/knowledge-base/introduction.mdx deleted file mode 100644 index 0672eb1b9..000000000 --- a/docs/knowledge-base/introduction.mdx +++ /dev/null @@ -1,6 +0,0 @@ ---- -title: Introduction -description: A collection of answers to Frequently asked questions about Mem0. ---- - -Coming soon. \ No newline at end of file diff --git a/docs/open-source/features/async-memory.mdx b/docs/open-source/features/async-memory.mdx index a0b4e340b..27437cb5f 100644 --- a/docs/open-source/features/async-memory.mdx +++ b/docs/open-source/features/async-memory.mdx @@ -5,8 +5,6 @@ icon: "bolt" iconType: "solid" --- - - ## 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. + +At least one filter (user_id, agent_id, or run_id) is required when using delete_all. + ### 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) - - # 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 + 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 - # 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: diff --git a/docs/open-source/features/custom-fact-extraction-prompt.mdx b/docs/open-source/features/custom-fact-extraction-prompt.mdx index 5a37aa8f7..1bb471390 100644 --- a/docs/open-source/features/custom-fact-extraction-prompt.mdx +++ b/docs/open-source/features/custom-fact-extraction-prompt.mdx @@ -5,8 +5,6 @@ icon: "pencil" iconType: "solid" --- - - ## Introduction to Custom Fact Extraction Prompt Custom fact extraction prompt allow you to tailor the behavior of your Mem0 instance to specific use cases or domains. diff --git a/docs/open-source/features/custom-update-memory-prompt.mdx b/docs/open-source/features/custom-update-memory-prompt.mdx index 2365eed9c..cf0cd7611 100644 --- a/docs/open-source/features/custom-update-memory-prompt.mdx +++ b/docs/open-source/features/custom-update-memory-prompt.mdx @@ -4,7 +4,6 @@ icon: "pencil" iconType: "solid" --- - Update memory prompt is a prompt used to determine the action to be performed on the memory. By customizing this prompt, you can control how the memory is updated. diff --git a/docs/open-source/features/multimodal-support.mdx b/docs/open-source/features/multimodal-support.mdx index 4ebcc4f7b..95abe1f23 100644 --- a/docs/open-source/features/multimodal-support.mdx +++ b/docs/open-source/features/multimodal-support.mdx @@ -5,13 +5,17 @@ icon: "image" iconType: "solid" --- - - -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. ```python Python @@ -62,7 +66,246 @@ client.add(messages, user_id="alice") ``` -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: + + +```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" }); +``` + + +## 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: + + +```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}`); + } +} +``` + + +## 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: diff --git a/docs/open-source/features/openai_compatibility.mdx b/docs/open-source/features/openai_compatibility.mdx index 96b219b6f..6cd52ec32 100644 --- a/docs/open-source/features/openai_compatibility.mdx +++ b/docs/open-source/features/openai_compatibility.mdx @@ -4,8 +4,6 @@ icon: "code" iconType: "solid" --- - - Mem0 can be easily integrated into chat applications to enhance conversational agents with structured memory. Mem0's APIs are designed to be compatible with OpenAI's, with the goal of making it easy to leverage Mem0 in applications you may have already built. 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. diff --git a/docs/open-source/features/rest-api.mdx b/docs/open-source/features/rest-api.mdx index 00e3004ba..4198bcacc 100644 --- a/docs/open-source/features/rest-api.mdx +++ b/docs/open-source/features/rest-api.mdx @@ -4,8 +4,6 @@ icon: "server" iconType: "solid" --- - - Mem0 provides a REST API server (written using FastAPI). Users can perform all operations through REST endpoints. The API also includes OpenAPI documentation, accessible at `/docs` when the server is running. diff --git a/docs/open-source/graph_memory/features.mdx b/docs/open-source/graph_memory/features.mdx index f5253391d..846ed0334 100644 --- a/docs/open-source/graph_memory/features.mdx +++ b/docs/open-source/graph_memory/features.mdx @@ -5,8 +5,6 @@ icon: "list-check" iconType: "solid" --- - - 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: diff --git a/docs/open-source/graph_memory/overview.mdx b/docs/open-source/graph_memory/overview.mdx index 52a6cb90a..75b5d832e 100644 --- a/docs/open-source/graph_memory/overview.mdx +++ b/docs/open-source/graph_memory/overview.mdx @@ -5,8 +5,6 @@ icon: "info" iconType: "solid" --- - - 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. diff --git a/docs/open-source/multimodal-support.mdx b/docs/open-source/multimodal-support.mdx index 3902261c8..fcf910493 100644 --- a/docs/open-source/multimodal-support.mdx +++ b/docs/open-source/multimodal-support.mdx @@ -4,8 +4,6 @@ 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 diff --git a/docs/open-source/node-quickstart.mdx b/docs/open-source/node-quickstart.mdx index 233c860eb..8b6ea60d8 100644 --- a/docs/open-source/node-quickstart.mdx +++ b/docs/open-source/node-quickstart.mdx @@ -5,8 +5,6 @@ icon: "node" iconType: "solid" --- - - > Welcome to the Mem0 quickstart guide. This guide will help you get up and running with Mem0 in no time. ## Installation diff --git a/docs/open-source/overview.mdx b/docs/open-source/overview.mdx index bbc8fab1c..c060b70c9 100644 --- a/docs/open-source/overview.mdx +++ b/docs/open-source/overview.mdx @@ -4,8 +4,6 @@ icon: "eye" iconType: "solid" --- - - Welcome to Mem0 Open Source - a powerful, self-hosted memory management solution for AI agents and assistants. With Mem0 OSS, you get full control over your infrastructure while maintaining complete customization flexibility. We offer two SDKs for Python and Node.js. diff --git a/docs/open-source/python-quickstart.mdx b/docs/open-source/python-quickstart.mdx index 9df1b0721..622310ef7 100644 --- a/docs/open-source/python-quickstart.mdx +++ b/docs/open-source/python-quickstart.mdx @@ -5,8 +5,6 @@ icon: "python" iconType: "solid" --- - - > Welcome to the Mem0 quickstart guide. This guide will help you get up and running with Mem0 in no time. ## Installation diff --git a/docs/openmemory/integrations.mdx b/docs/openmemory/integrations.mdx index 475285b43..25fbf7bb9 100644 --- a/docs/openmemory/integrations.mdx +++ b/docs/openmemory/integrations.mdx @@ -4,8 +4,6 @@ icon: "plug" iconType: "solid" --- - - ## Connecting an MCP Client Once your OpenMemory server is running locally, you can connect any compatible MCP client to your personal memory stream. This enables a seamless memory layer integration for AI tools and agents. diff --git a/docs/openmemory/overview.mdx b/docs/openmemory/overview.mdx index b9d1ea3b6..7bdcef65c 100644 --- a/docs/openmemory/overview.mdx +++ b/docs/openmemory/overview.mdx @@ -4,8 +4,6 @@ icon: "info" iconType: "solid" --- - - ## 🚀 Hosted OpenMemory MCP Now Available! #### Sign Up Now - [app.openmemory.dev](https://app.openmemory.dev) diff --git a/docs/openmemory/quickstart.mdx b/docs/openmemory/quickstart.mdx index 4bdc8236b..e7e7a83ff 100644 --- a/docs/openmemory/quickstart.mdx +++ b/docs/openmemory/quickstart.mdx @@ -4,8 +4,6 @@ icon: "terminal" iconType: "solid" --- - - ## 🚀 Hosted OpenMemory MCP Now Available! #### Sign Up Now - [app.openmemory.dev](https://app.openmemory.dev) diff --git a/docs/overview.mdx b/docs/overview.mdx deleted file mode 100644 index 92ec026b8..000000000 --- a/docs/overview.mdx +++ /dev/null @@ -1,51 +0,0 @@ ---- -title: Overview -icon: "info" -iconType: "solid" ---- - - - - -# Introduction - -[Mem0](https://mem0.dev/wd) (pronounced "mem-zero") enhances AI assistants by giving them persistent, contextual memory. AI systems using Mem0 actively learn from and adapt to user interactions over time. - -Mem0's memory layer combines LLMs with vector based storage. LLMs extract and process key information from conversations, while the vector storage enables efficient semantic search and retrieval of memories. This architecture helps AI agents connect past interactions with current context for more relevant responses. - -## Key Features - -- **Memory Processing**: Uses LLMs to automatically extract and store important information from conversations while maintaining full context -- **Memory Management**: Continuously updates and resolves contradictions in stored information to maintain accuracy -- **Dual Storage Architecture**: Combines vector database for memory storage and graph database for relationship tracking -- **Smart Retrieval System**: Employs semantic search and graph queries to find relevant memories based on importance and recency -- **Simple API Integration**: Provides easy-to-use endpoints for adding (`add`) and retrieving (`search`) memories - -## Use Cases - -- **Customer Support Chatbots**: Create support agents that remember customer history, preferences, and past interactions to provide personalized assistance -- **Personal AI Tutors**: Build educational assistants that track student progress, adapt to learning patterns, and provide contextual help -- **Healthcare Applications**: Develop healthcare assistants that maintain patient history and provide personalized care recommendations -- **Enterprise Knowledge Management**: Power systems that learn from organizational interactions and maintain institutional knowledge -- **Personalized AI Assistants**: Create assistants that learn user preferences and adapt their responses over time - -## Getting Started -Mem0 offers two powerful ways to leverage our technology: our [managed platform](/platform/overview) and our [open source solution](/open-source/quickstart). - - - - - Integrate Mem0 in a few lines of code - - - Mem0 in action - - - See what you can build with Mem0 - - - -## Need help? -If you have any questions, please feel free to reach out to us using one of the following methods: - - \ No newline at end of file diff --git a/docs/platform/advanced-memory-operations.mdx b/docs/platform/advanced-memory-operations.mdx new file mode 100644 index 000000000..ae087cd6f --- /dev/null +++ b/docs/platform/advanced-memory-operations.mdx @@ -0,0 +1,1218 @@ +--- +title: Advanced Memory Operations +description: 'Comprehensive guide to advanced memory operations and features' +icon: "gear" +iconType: "solid" +--- + +This guide covers advanced memory operations including complex filtering, batch operations, and detailed API usage. If you're just getting started, check out the [Quickstart](/platform/quickstart) first. + +## Advanced Memory Creation + +### Async Client (Python) + +For asynchronous operations in Python, use the AsyncMemoryClient: + +```python Python +import os +from mem0 import AsyncMemoryClient + +os.environ["MEM0_API_KEY"] = "your-api-key" +client = AsyncMemoryClient() + +async def main(): + messages = [ + {"role": "user", "content": "I'm travelling to SF"} + ] + response = await client.add(messages, user_id="john") + print(response) + +await main() +``` + +### Detailed Memory Creation Examples + +#### Long-term memory with full context + + + +```python Python +messages = [ + {"role": "user", "content": "Hi, I'm Alex. I'm a vegetarian and I'm allergic to nuts."}, + {"role": "assistant", "content": "Hello Alex! I've noted that you're a vegetarian and have a nut allergy. I'll keep this in mind for any food-related recommendations or discussions."} +] + +client.add(messages, user_id="alex", metadata={"food": "vegan"}) +``` + +```javascript JavaScript +const messages = [ + {"role": "user", "content": "Hi, I'm Alex. I'm a vegetarian and I'm allergic to nuts."}, + {"role": "assistant", "content": "Hello Alex! I've noted that you're a vegetarian and have a nut allergy. I'll keep this in mind for any food-related recommendations or discussions."} +]; +client.add(messages, { user_id: "alex", metadata: { food: "vegan" } }) + .then(response => console.log(response)) + .catch(error => console.error(error)); +``` + +```bash cURL +curl -X POST "https://api.mem0.ai/v1/memories/" \ + -H "Authorization: Token your-api-key" \ + -H "Content-Type: application/json" \ + -d '{ + "messages": [ + {"role": "user", "content": "Hi, I'm Alex. I'm a vegetarian and I'm allergic to nuts."}, + {"role": "assistant", "content": "Hello Alex! I've noted that you're a vegetarian and have a nut allergy. I'll keep this in mind for any food-related recommendations or discussions."} + ], + "user_id": "alex", + "metadata": { + "food": "vegan" + } + }' +``` + +```json Output +{ + "results": [ + { + "memory": "Name is Alex", + "event": "ADD" + }, + { + "memory": "Is a vegetarian", + "event": "ADD" + }, + { + "memory": "Is allergic to nuts", + "event": "ADD" + } + ] +} +``` + + + + + When passing `user_id`, memories are primarily created based on user messages, but may be influenced by assistant messages for contextual understanding. For example, in a conversation about food preferences, both the user's stated preferences and their responses to the assistant's questions would form user memories. Similarly, when using `agent_id`, assistant messages are prioritized, but user messages might influence the agent's memories based on context. + + **Example:** + ``` + User: My favorite cuisine is Italian + Assistant: Nice! What about Indian cuisine? + User: Don't like it much since I cannot eat spicy food + + Resulting user memories: + memory1 - Likes Italian food + memory2 - Doesn't like Indian food since cannot eat spicy + + (memory2 comes from user's response about Indian cuisine) + ``` + + +Metadata allows you to store structured information (location, timestamp, user state) with memories. Add it during creation to enable precise filtering and retrieval during searches. + +#### Short-term memory for sessions + + + +```python Python +messages = [ + {"role": "user", "content": "I'm planning a trip to Japan next month."}, + {"role": "assistant", "content": "That's exciting, Alex! A trip to Japan next month sounds wonderful. Would you like some recommendations for vegetarian-friendly restaurants in Japan?"}, + {"role": "user", "content": "Yes, please! Especially in Tokyo."}, + {"role": "assistant", "content": "Great! I'll remember that you're interested in vegetarian restaurants in Tokyo for your upcoming trip. I'll prepare a list for you in our next interaction."} +] + +client.add(messages, user_id="alex", run_id="trip-planning-2024") +``` + +```javascript JavaScript +const messages = [ + {"role": "user", "content": "I'm planning a trip to Japan next month."}, + {"role": "assistant", "content": "That's exciting, Alex! A trip to Japan next month sounds wonderful. Would you like some recommendations for vegetarian-friendly restaurants in Japan?"}, + {"role": "user", "content": "Yes, please! Especially in Tokyo."}, + {"role": "assistant", "content": "Great! I'll remember that you're interested in vegetarian restaurants in Tokyo for your upcoming trip. I'll prepare a list for you in our next interaction."} +]; +client.add(messages, { user_id: "alex", run_id: "trip-planning-2024" }) + .then(response => console.log(response)) + .catch(error => console.error(error)); +``` + +```bash cURL +curl -X POST "https://api.mem0.ai/v1/memories/" \ + -H "Authorization: Token your-api-key" \ + -H "Content-Type: application/json" \ + -d '{ + "messages": [ + {"role": "user", "content": "I'm planning a trip to Japan next month."}, + {"role": "assistant", "content": "That's exciting, Alex! A trip to Japan next month sounds wonderful. Would you like some recommendations for vegetarian-friendly restaurants in Japan?"}, + {"role": "user", "content": "Yes, please! Especially in Tokyo."}, + {"role": "assistant", "content": "Great! I'll remember that you're interested in vegetarian restaurants in Tokyo for your upcoming trip. I'll prepare a list for you in our next interaction."} + ], + "user_id": "alex", + "run_id": "trip-planning-2024" + }' +``` + +```json Output +{ + "results": [ + { + "memory": "Planning a trip to Japan next month", + "event": "ADD" + }, + { + "memory": "Interested in vegetarian restaurants in Tokyo", + "event": "ADD" + } + ] +} +``` + + + +#### Agent memories + + + +```python Python +messages = [ + {"role": "system", "content": "You are an AI tutor with a personality. Give yourself a name for the user."}, + {"role": "assistant", "content": "Understood. I'm an AI tutor with a personality. My name is Alice."} +] + +client.add(messages, agent_id="ai-tutor") +``` + +```javascript JavaScript +const messages = [ + {"role": "system", "content": "You are an AI tutor with a personality. Give yourself a name for the user."}, + {"role": "assistant", "content": "Understood. I'm an AI tutor with a personality. My name is Alice."} +]; +client.add(messages, { agent_id: "ai-tutor" }) + .then(response => console.log(response)) + .catch(error => console.error(error)); +``` + +```bash cURL +curl -X POST "https://api.mem0.ai/v1/memories/" \ + -H "Authorization: Token your-api-key" \ + -H "Content-Type: application/json" \ + -d '{ + "messages": [ + {"role": "system", "content": "You are an AI tutor with a personality. Give yourself a name for the user."}, + {"role": "assistant", "content": "Understood. I'm an AI tutor with a personality. My name is Alice."} + ], + "agent_id": "ai-tutor" + }' +``` + + + + + The `agent_id` retains memories exclusively based on messages generated by the assistant or those explicitly provided as input to the assistant. Messages outside these criteria are not stored as memory. + + +#### Dual user and agent memories + +When you provide both `user_id` and `agent_id`, Mem0 will store memories for both identifiers separately: +- Memories from messages with `"role": "user"` are automatically tagged with the provided `user_id` +- Memories from messages with `"role": "assistant"` are automatically tagged with the provided `agent_id` +- During retrieval, you can provide either `user_id` or `agent_id` to access the respective memories +- You can continuously enrich existing memory collections by adding new memories to the same `user_id` or `agent_id` in subsequent API calls, either together or separately, allowing for progressive memory building over time +- This dual-tagging approach enables personalized experiences for both users and AI agents in your application + + + +```python Python +messages = [ + {"role": "user", "content": "I'm travelling to San Francisco"}, + {"role": "assistant", "content": "That's great! I'm going to Dubai next month."}, +] + +client.add(messages=messages, user_id="user1", agent_id="agent1") +``` + +```javascript JavaScript +const messages = [ + {"role": "user", "content": "I'm travelling to San Francisco"}, + {"role": "assistant", "content": "That's great! I'm going to Dubai next month."}, +] + +client.add(messages, { user_id: "user1", agent_id: "agent1" }) + .then(response => console.log(response)) + .catch(error => console.error(error)); +``` + +```bash cURL +curl -X POST "https://api.mem0.ai/v1/memories/" \ + -H "Authorization: Token your-api-key" \ + -H "Content-Type: application/json" \ + -d '{ + "messages": [ + {"role": "user", "content": "I'm travelling to San Francisco"}, + {"role": "assistant", "content": "That's great! I'm going to Dubai next month."}, + ], + "user_id": "user1", + "agent_id": "agent1" + }' +``` + +```json Output +{ + "results": [ + { + // memory from user1 + "id": "c57abfa2-f0ac-48af-896a-21728dbcecee0", + "data": {"memory": "Travelling to San Francisco"}, + "event": "ADD" + }, + { + // memory from agent1 + "id": "0e8c003f-7db7-426a-9fdc-a46f9331a0c2", + "data": {"memory": "Going to Dubai next month"}, + "event": "ADD" + } + ] +} +``` + + + +## Advanced Search Operations + +### Search with Custom Filters + +Our advanced search allows you to set custom search filters. You can filter by user_id, agent_id, app_id, run_id, created_at, updated_at, categories, and text. The filters support logical operators (AND, OR) and comparison operators (in, gte, lte, gt, lt, ne, contains, icontains, *). The wildcard character (*) matches everything for a specific field. + +Here you need to define `version` as `v2` in the search method. + +#### Example 1: Search using user_id and agent_id filters + + + +```python Python +query = "What do you know about me?" +filters = { + "OR":[ + { + "user_id":"alex" + }, + { + "agent_id":{ + "in":[ + "travel-assistant", + "customer-support" + ] + } + } + ] +} +client.search(query, version="v2", filters=filters) +``` + +```javascript JavaScript +const query = "What do you know about me?"; +const filters = { + "OR":[ + { + "user_id":"alex" + }, + { + "agent_id":{ + "in":[ + "travel-assistant", + "customer-support" + ] + } + } + ] +}; +client.search(query, { version: "v2", filters }) + .then(results => console.log(results)) + .catch(error => console.error(error)); +``` + +```bash cURL +curl -X POST "https://api.mem0.ai/v1/memories/search/?version=v2" \ + -H "Authorization: Token your-api-key" \ + -H "Content-Type: application/json" \ + -d '{ + "query": "What do you know about me?", + "filters": { + "OR": [ + { + "user_id": "alex" + }, + { + "agent_id": { + "in": ["travel-assistant", "customer-support"] + } + } + ] + } + }' +``` + + + +#### Example 2: Search using date filters + + +```python Python +query = "What do you know about me?" +filters = { + "AND": [ + {"created_at": {"gte": "2024-07-20", "lte": "2024-07-10"}}, + {"user_id": "alex"} + ] +} +client.search(query, version="v2", filters=filters) +``` + +```javascript JavaScript +const query = "What do you know about me?"; +const filters = { + "AND": [ + {"created_at": {"gte": "2024-07-20", "lte": "2024-07-10"}}, + {"user_id": "alex"} + ] +}; + +client.search(query, { version: "v2", filters }) + .then(results => console.log(results)) + .catch(error => console.error(error)); +``` + +```bash cURL +curl -X POST "https://api.mem0.ai/v1/memories/search/?version=v2" \ + -H "Authorization: Token your-api-key" \ + -H "Content-Type: application/json" \ + -d '{ + "query": "What do you know about me?", + "filters": { + "AND": [ + { + "created_at": { + "gte": "2024-07-20", + "lte": "2024-07-10" + } + }, + { + "user_id": "alex" + } + ] + } + }' +``` + + +#### Example 3: Search using metadata and categories + + +```python Python +query = "What do you know about me?" +filters = { + "AND": [ + {"metadata": {"food": "vegan"}}, + { + "categories":{ + "contains": "food_preferences" + } + } + ] +} +client.search(query, version="v2", filters=filters) +``` + +```javascript JavaScript +const query = "What do you know about me?"; +const filters = { + "AND": [ + {"metadata": {"food": "vegan"}}, + { + "categories": { + "contains": "food_preferences" + } + } + ] +}; + +client.search(query, { version: "v2", filters }) + .then(results => console.log(results)) + .catch(error => console.error(error)); +``` + +```bash cURL +curl -X POST "https://api.mem0.ai/v1/memories/search/?version=v2" \ + -H "Authorization: Token your-api-key" \ + -H "Content-Type: application/json" \ + -d '{ + "query": "What do you know about me?", + "filters": { + "AND": [ + { + "metadata": { + "food": "vegan" + } + }, + { + "categories": { + "contains": "food_preferences" + } + } + ] + } + }' +``` + + +#### Example 4: Search using NOT filters + + +```python Python +query = "What do you know about me?" +filters = { + "NOT": [ + { + "categories": { + "contains": "food_preferences" + } + } + ] +} +client.search(query, version="v2", filters=filters) +``` + +```javascript JavaScript +const query = "What do you know about me?"; +const filters = { + "NOT": [ + { + "categories": { + "contains": "food_preferences" + } + } + ] +}; + +client.search(query, { version: "v2", filters }) + .then(results => console.log(results)) + .catch(error => console.error(error)); +``` + +```bash cURL +curl -X POST "https://api.mem0.ai/v1/memories/search/?version=v2" \ + -H "Authorization: Token your-api-key" \ + -H "Content-Type: application/json" \ + -d '{ + "query": "What do you know about me?", + "filters": { + "NOT": [ + { + "categories": { + "contains": "food_preferences" + } + } + ] + } + }' +``` + + +#### Example 5: Search using wildcard filters + + +```python Python +query = "What do you know about me?" +filters = { + "AND": [ + { + "user_id": "alex" + }, + { + "run_id": "*" # Matches all run_ids + } + ] +} +client.search(query, version="v2", filters=filters) +``` + +```javascript JavaScript +const query = "What do you know about me?"; +const filters = { + "AND": [ + { + "user_id": "alex" + }, + { + "run_id": "*" // Matches all run_ids + } + ] +}; + +client.search(query, { version: "v2", filters }) + .then(results => console.log(results)) + .catch(error => console.error(error)); +``` + +```bash cURL +curl -X POST "https://api.mem0.ai/v1/memories/search/?version=v2" \ + -H "Authorization: Token your-api-key" \ + -H "Content-Type: application/json" \ + -d '{ + "query": "What do you know about me?", + "filters": { + "AND": [ + { + "user_id": "alex" + }, + { + "run_id": "*" + } + ] + } + }' +``` + + +## Advanced Retrieval Operations + +### Get All Memories with Pagination + + The `get_all` method supports two output formats: `v1.0` (default) and `v1.1`. To use the latest format, which provides more detailed information about each memory operation, set the `output_format` parameter to `v1.1`. + + We're soon deprecating the default output format for get_all() method, which returned a list. Once the changes are live, paginated response will be the only supported format, with 100 memories per page by default. You can customize this using the `page` and `page_size` parameters. + +#### Get all memories of a user + + + +```python Python +memories = client.get_all(user_id="alex", page=1, page_size=50) +``` + +```javascript JavaScript +client.getAll({ user_id: "alex", page: 1, page_size: 50 }) + .then(memories => console.log(memories)) + .catch(error => console.error(error)); +``` + +```bash cURL +curl -X GET "https://api.mem0.ai/v1/memories/?user_id=alex&page=1&page_size=50" \ + -H "Authorization: Token your-api-key" +``` + +```json Output (v1.1) +{ + "count": 204, + "next": "https://api.mem0.ai/v1/memories/?user_id=alex&output_format=v1.1&page=2&page_size=50", + "previous": null, + "results": [ + { + "id":"f38b689d-6b24-45b7-bced-17fbb4d8bac7", + "memory":"是素食主义者,对坚果过敏。", + "agent_id":"travel-assistant", + "hash":"62bc074f56d1f909f1b4c2b639f56f6a", + "metadata":null, + "immutable": false, + "expiration_date": null, + "created_at":"2024-07-25T23:57:00.108347-07:00", + "updated_at":"2024-07-25T23:57:00.108367-07:00", + "categories":null + } + ] +} +``` + + + +#### Get all memories by categories + +You can filter memories by their categories when using get_all: + + + +```python Python +# Get memories with specific categories +memories = client.get_all(user_id="alex", categories=["likes"]) + +# Get memories with multiple categories +memories = client.get_all(user_id="alex", categories=["likes", "food_preferences"]) + +# Custom pagination with categories +memories = client.get_all(user_id="alex", categories=["likes"], page=1, page_size=50) + +# Get memories with specific keywords +memories = client.get_all(user_id="alex", keywords="to play", page=1, page_size=50) +``` + +```javascript JavaScript +// Get memories with specific categories +client.getAll({ user_id: "alex", categories: ["likes"] }) + .then(memories => console.log(memories)) + .catch(error => console.error(error)); + +// Get memories with multiple categories +client.getAll({ user_id: "alex", categories: ["likes", "food_preferences"] }) + .then(memories => console.log(memories)) + .catch(error => console.error(error)); + +// Custom pagination with categories +client.getAll({ user_id: "alex", categories: ["likes"], page: 1, page_size: 50 }) + .then(memories => console.log(memories)) + .catch(error => console.error(error)); + +// Get memories with specific keywords +client.getAll({ user_id: "alex", keywords: "to play", page: 1, page_size: 50 }) + .then(memories => console.log(memories)) + .catch(error => console.error(error)); +``` + +```bash cURL +# Get memories with specific categories +curl -X GET "https://api.mem0.ai/v1/memories/?user_id=alex&categories=likes" \ + -H "Authorization: Token your-api-key" + +# Get memories with multiple categories +curl -X GET "https://api.mem0.ai/v1/memories/?user_id=alex&categories=likes,food_preferences" \ + -H "Authorization: Token your-api-key" + +# Custom pagination with categories +curl -X GET "https://api.mem0.ai/v1/memories/?user_id=alex&categories=likes&page=1&page_size=50" \ + -H "Authorization: Token your-api-key" + +# Get memories with specific keywords +curl -X GET "https://api.mem0.ai/v1/memories/?user_id=alex&keywords=to play&page=1&page_size=50" \ + -H "Authorization: Token your-api-key" +``` + + + +#### Get all memories using custom filters + +Our advanced retrieval allows you to set custom filters when fetching memories. You can filter by user_id, agent_id, app_id, run_id, created_at, updated_at, categories, and keywords. The filters support logical operators (AND, OR) and comparison operators (in, gte, lte, gt, lt, ne, contains, icontains, *). The wildcard character (*) matches everything for a specific field. + +Here you need to define `version` as `v2` in the get_all method. + + + +```python Python +filters = { + "AND":[ + { + "user_id":"alex" + }, + { + "created_at":{ + "gte":"2024-07-01", + "lte":"2024-07-31" + } + }, + { + "categories":{ + "contains": "food_preferences" + } + } + ] +} + +# Default (No Pagination) +client.get_all(version="v2", filters=filters) + +# Pagination (You can also use the page and page_size parameters) +client.get_all(version="v2", filters=filters, page=1, page_size=50) +``` + +```javascript JavaScript +const filters = { + "AND":[ + { + "user_id":"alex" + }, + { + "created_at":{ + "gte":"2024-07-01", + "lte":"2024-07-31" + } + }, + { + "categories":{ + "contains": "food_preferences" + } + } + ] +}; + +// Default (No Pagination) +client.getAll({ version: "v2", filters }) + .then(memories => console.log(memories)) + .catch(error => console.error(error)); + +// Pagination (You can also use the page and page_size parameters) +client.getAll({ version: "v2", filters, page: 1, page_size: 50 }) + .then(memories => console.log(memories)) + .catch(error => console.error(error)); +``` + +```bash cURL +# Default (No Pagination) +curl -X GET "https://api.mem0.ai/v1/memories/?version=v2" \ + -H "Authorization: Token your-api-key" \ + -H "Content-Type: application/json" \ + -d '{ + "filters": { + "AND": [ + {"user_id":"alex"}, + {"created_at":{ + "gte":"2024-07-01", + "lte":"2024-07-31" + }}, + {"categories":{ + "contains": "food_preferences" + }} + ] + } + }' + +# Pagination (You can also use the page and page_size parameters) +curl -X GET "https://api.mem0.ai/v1/memories/?version=v2&page=1&page_size=50" \ + -H "Authorization: Token your-api-key" \ + -H "Content-Type: application/json" \ + -d '{ + "filters": { + "AND": [ + {"user_id":"alex"}, + {"created_at":{ + "gte":"2024-07-01", + "lte":"2024-07-31" + }}, + {"categories":{ + "contains": "food_preferences" + }} + ] + } + }' +``` + + + +## Memory Management Operations + +### Memory History + +Get history of how a memory has changed over time. + + + +```python Python +# Add some message to create history +messages = [{"role": "user", "content": "I recently tried chicken and I loved it. I'm thinking of trying more non-vegetarian dishes.."}] +client.add(messages, user_id="alex") + +# Add second message to update history +messages.append({'role': 'user', 'content': 'I turned vegetarian now.'}) +client.add(messages, user_id="alex") + +# Get history of how memory changed over time +memory_id = "" +history = client.history(memory_id) +``` + +```javascript JavaScript +// Add some message to create history +let messages = [{ role: "user", content: "I recently tried chicken and I loved it. I'm thinking of trying more non-vegetarian dishes.." }]; +client.add(messages, { user_id: "alex" }) + .then(result => { + // Add second message to update history + messages.push({ role: 'user', content: 'I turned vegetarian now.' }); + return client.add(messages, { user_id: "alex" }); + }) + .then(result => { + // Get history of how memory changed over time + const memoryId = result.id; // Assuming the API returns the memory ID + return client.history(memoryId); + }) + .then(history => console.log(history)) + .catch(error => console.error(error)); +``` + +```bash cURL +# First, add the initial memory +curl -X POST "https://api.mem0.ai/v1/memories/" \ + -H "Authorization: Token your-api-key" \ + -H "Content-Type: application/json" \ + -d '{ + "messages": [{"role": "user", "content": "I recently tried chicken and I loved it. I'm thinking of trying more non-vegetarian dishes.."}], + "user_id": "alex" + }' + +# Then, update the memory +curl -X POST "https://api.mem0.ai/v1/memories/" \ + -H "Authorization: Token your-api-key" \ + -H "Content-Type: application/json" \ + -d '{ + "messages": [ + {"role": "user", "content": "I recently tried chicken and I loved it. I'm thinking of trying more non-vegetarian dishes.."}, + {"role": "user", "content": "I turned vegetarian now."} + ], + "user_id": "alex" + }' + +# Finally, get the history (replace with the actual memory ID) +curl -X GET "https://api.mem0.ai/v1/memories//history/" \ + -H "Authorization: Token your-api-key" +``` + +```json Output +[ + { + "id":"d6306e85-eaa6-400c-8c2f-ab994a8c4d09", + "memory_id":"b163df0e-ebc8-4098-95df-3f70a733e198", + "input":[ + { + "role":"user", + "content":"I recently tried chicken and I loved it. I'm thinking of trying more non-vegetarian dishes.." + }, + { + "role":"user", + "content":"I turned vegetarian now." + } + ], + "old_memory":"None", + "new_memory":"Turned vegetarian.", + "user_id":"alex", + "event":"ADD", + "metadata":"None", + "created_at":"2024-07-26T01:02:41.737310-07:00", + "updated_at":"2024-07-26T01:02:41.726073-07:00" + } +] +``` + + +### Update Memory + +Update a memory with new data. You can update the memory's text, metadata, or both. + + + +```python Python +client.update( + memory_id="", + text="I am now a vegetarian.", + metadata={"diet": "vegetarian"} +) +``` + +```javascript JavaScript +client.update("memory-id-here", { text: "I am now a vegetarian.", metadata: { diet: "vegetarian" } }) + .then(result => console.log(result)) + .catch(error => console.error(error)); +``` + +```bash cURL +curl -X PUT "https://api.mem0.ai/v1/memories/" \ + -H "Authorization: Token your-api-key" \ + -H "Content-Type: application/json" \ + -d '{ + "message": "I recently tried chicken and I loved it. I'm thinking of trying more non-vegetarian dishes.." + }' +``` + +```json Output +{ + "id":"c190ab1a-a2f1-4f6f-914a-495e9a16b76e", + "memory":"I recently tried chicken and I loved it. I'm thinking of trying more non-vegetarian dishes..", + "agent_id":"travel-assistant", + "hash":"af1161983e03667063d1abb60e6d5c06", + "metadata":"None", + "created_at":"2024-07-30T22:46:40.455758-07:00", + "updated_at":"2024-07-30T22:48:35.257828-07:00" +} +``` + + + +## Batch Operations + +### Batch Update Memories + +Update multiple memories in a single API call. You can update up to 1000 memories at once. + + +```python Python +update_memories = [ + { + "memory_id": "285ed74b-6e05-4043-b16b-3abd5b533496", + "text": "Watches football" + }, + { + "memory_id": "2c9bd859-d1b7-4d33-a6b8-94e0147c4f07", + "text": "Loves to travel" + } +] + +response = client.batch_update(update_memories) +print(response) +``` + +```javascript JavaScript +const updateMemories = [ + { + "memory_id": "285ed74b-6e05-4043-b16b-3abd5b533496", + text: "Watches football" + }, + { + "memory_id": "2c9bd859-d1b7-4d33-a6b8-94e0147c4f07", + text: "Loves to travel" + } +]; + +client.batchUpdate(updateMemories) + .then(response => console.log('Batch update response:', response)) + .catch(error => console.error(error)); +``` + +```bash cURL +curl -X PUT "https://api.mem0.ai/v1/memories/batch/" \ + -H "Authorization: Token your-api-key" \ + -H "Content-Type: application/json" \ + -d '{ + "memories": [ + { + "memory_id": "285ed74b-6e05-4043-b16b-3abd5b533496", + "text": "Watches football" + }, + { + "memory_id": "2c9bd859-d1b7-4d33-a6b8-94e0147c4f07", + "text": "Loves to travel" + } + ] + }' +``` + +```json Output +{ + "message": "Successfully updated 2 memories" +} +``` + + +### Batch Delete Memories + +Delete multiple memories in a single API call. You can delete up to 1000 memories at once. + + +```python Python +delete_memories = [ + {"memory_id": "285ed74b-6e05-4043-b16b-3abd5b533496"}, + {"memory_id": "2c9bd859-d1b7-4d33-a6b8-94e0147c4f07"} +] + +response = client.batch_delete(delete_memories) +print(response) +``` + +```javascript JavaScript +const deleteMemories = [ + {"memory_id": "285ed74b-6e05-4043-b16b-3abd5b533496"}, + {"memory_id": "2c9bd859-d1b7-4d33-a6b8-94e0147c4f07"} +]; + +client.batchDelete(deleteMemories) + .then(response => console.log('Batch delete response:', response)) + .catch(error => console.error(error)); +``` + +```bash cURL +curl -X DELETE "https://api.mem0.ai/v1/memories/batch/" \ + -H "Authorization: Token your-api-key" \ + -H "Content-Type: application/json" \ + -d '{ + "memory_ids": [ + {"memory_id": "285ed74b-6e05-4043-b16b-3abd5b533496"}, + {"memory_id": "2c9bd859-d1b7-4d33-a6b8-94e0147c4f07"} + ] + }' +``` + +```json Output +{ + "message": "Successfully deleted 2 memories" +} +``` + + +## Entity Management + +### Get All Users + +Get all users, agents, and runs which have memories associated with them. + + + +```python Python +client.users() +``` + +```javascript JavaScript +client.users() + .then(users => console.log(users)) + .catch(error => console.error(error)); +``` + +```bash cURL +curl -X GET "https://api.mem0.ai/v1/entities/" \ + -H "Authorization: Token your-api-key" +``` + +```json Output +[ + { + "id": "1", + "name": "user123", + "created_at": "2024-07-17T16:47:23.899900-07:00", + "updated_at": "2024-07-17T16:47:23.899918-07:00", + "total_memories": 5, + "owner": "alex", + "metadata": {"foo": "bar"}, + "type": "user" + }, + { + "id": "2", + "name": "travel-agent", + "created_at": "2024-07-01T17:59:08.187250-07:00", + "updated_at": "2024-07-01T17:59:08.187266-07:00", + "total_memories": 10, + "owner": "alex", + "metadata": {"agent_id": "123"}, + "type": "agent" + } +] +``` + + + +### Delete Operations + +Delete specific memory: + + + +```python Python +client.delete(memory_id) +``` + +```javascript JavaScript +client.delete("memory-id-here") + .then(result => console.log(result)) + .catch(error => console.error(error)); +``` + +```bash cURL +curl -X DELETE "https://api.mem0.ai/v1/memories/memory-id-here" \ + -H "Authorization: Token your-api-key" +``` + + + +Delete all memories of a user: + + + +```python Python +client.delete_all(user_id="alex") +``` + +```javascript JavaScript +client.deleteAll({ user_id: "alex" }) + .then(result => console.log(result)) + .catch(error => console.error(error)); +``` + +```bash cURL +curl -X DELETE "https://api.mem0.ai/v1/memories/?user_id=alex" \ + -H "Authorization: Token your-api-key" +``` + + + +Delete specific user or agent: + + +```python Python +# Delete specific user +client.delete_users(user_id="alex") + +# Delete specific agent +# client.delete_users(agent_id="travel-assistant") +``` + +```javascript JavaScript +client.delete_users({ user_id: "alex" }) + .then(result => console.log(result)) + .catch(error => console.error(error)); +``` + +```bash cURL +curl -X DELETE "https://api.mem0.ai/v2/entities/user/alex" \ + -H "Authorization: Token your-api-key" +``` + + +### Reset Client + + + +```python Python +client.reset() +``` + +```json Output +{'message': 'Client reset successful. All users and memories deleted.'} +``` + + + +### Natural Language Delete + +You can also delete memories using natural language commands: + + + +```python Python +messages = [ + {"role": "user", "content": "Delete all of my food preferences"} +] +client.add(messages, user_id="alex") +``` + +```javascript JavaScript +const messages = [ + {"role": "user", "content": "Delete all of my food preferences"} +] +client.add(messages, { user_id: "alex" }) + .then(result => console.log(result)) + .catch(error => console.error(error)); +``` + +```bash cURL +curl -X POST "https://api.mem0.ai/v1/memories/" \ + -H "Authorization: Token your-api-key" \ + -H "Content-Type: application/json" \ + -d '{ + "messages": [{"role": "user", "content": "Delete all of my food preferences"}], + "user_id": "alex" + }' +``` + + + +## Monitor Memory Operations + +You can monitor memory operations on the platform dashboard: + +![Mem0 Platform Activity](/images/platform/activity.png) + +For more detailed information, see our [API Reference](/api-reference) or explore specific features in the [Platform Features](/platform/features/platform-overview) section. \ No newline at end of file diff --git a/docs/platform/features/advanced-retrieval.mdx b/docs/platform/features/advanced-retrieval.mdx index d3db8f445..7cc2aa83a 100644 --- a/docs/platform/features/advanced-retrieval.mdx +++ b/docs/platform/features/advanced-retrieval.mdx @@ -2,174 +2,282 @@ title: Advanced Retrieval icon: "magnifying-glass" iconType: "solid" +description: "Advanced memory search with keyword expansion, intelligent reranking, and precision filtering" --- - +## What is Advanced Retrieval? -Mem0’s **Advanced Retrieval** provides additional control over how memories are selected and ranked during search. While the default search uses embedding-based semantic similarity, Advanced Retrieval introduces specialized options to improve recall, ranking accuracy, or filtering based on specific use case. +Advanced Retrieval gives you precise control over how memories are found and ranked. While basic search uses semantic similarity, these advanced options help you find exactly what you need, when you need it. -You can enable any of the following modes independently or together: + -- Keyword Search -- Reranking -- Filtering +## Search Enhancement Options -Each enhancement can be toggled independently via the `search()` API call. These flags are off by default. These are useful when building agents that require fine-grained retrieval control +### Keyword Search +**Expands results** to include memories with specific terms, names, and technical keywords. -## Keyword Search - -Keyword search expands the result set by including memories that contain lexically similar terms and important keywords from the query, even if they're not semantically similar. - -### When to use -- You are searching for specific entities, names, or technical terms -- When you need comprehensive coverage of a topic -- You want broader recall at the cost of slight noise - - -### API Usage -```python + + +- Searching for specific entities, names, or technical terms +- Need comprehensive coverage of a topic +- Want broader recall even if some results are less relevant +- Working with domain-specific terminology + + +```python Python +# Find memories containing specific food-related terms results = client.search( - query="What are my food preferences?", + query="What foods should I avoid?", keyword_search=True, - user_id="alex" + user_id="user123" ) + +# Results might include: +# ✓ "Allergic to peanuts and shellfish" +# ✓ "Lactose intolerant - avoid dairy" +# ✓ "Mentioned avoiding gluten last week" ``` + + +- **Latency**: ~10ms additional +- **Recall**: Significantly increased +- **Precision**: Slightly decreased +- **Best for**: Entity search, comprehensive coverage + + -### Example +### Reranking +**Reorders results** using deep semantic understanding to put the most relevant memories first. -**Without keyword_search:** -- "Vegetarian. Allergic to nuts." -- "Prefers spicy food and enjoys Thai cuisine" - -**With keyword_search=True:** -- "Vegetarian. Allergic to nuts." -- "Prefers spicy food and enjoys Thai cuisine" -- "Mentioned disliking seafood during restaurant discussion" - -### Trade-offs -- Increases recall -- May slightly reduce precision -- Adds ~10ms latency - - - -## Reranking - -Reranking reorders the retrieved results using a deep semantic relevance model that improves the position of the most relevant matches. - -### When to use -- You rely on top-1 or top-N precision -- When result order is critical for your application -- You want consistent result quality across sessions - -### API Usage -```python + + +- Need the most relevant result at the top +- Result order is critical for your application +- Want consistent quality across different queries +- Building user-facing features where accuracy matters + + +```python Python +# Get the most relevant travel plans first results = client.search( - query="What are my travel plans?", + query="What are my upcoming travel plans?", rerank=True, - user_id="alex" + user_id="user123" ) + +# Before reranking: After reranking: +# 1. "Went to Paris" → 1. "Tokyo trip next month" +# 2. "Tokyo trip next" → 2. "Need to book hotel in Tokyo" +# 3. "Need hotel" → 3. "Went to Paris last year" ``` + + +- **Latency**: 150-200ms additional +- **Accuracy**: Significantly improved +- **Ordering**: Much more relevant +- **Best for**: Top-N precision, user-facing results + + -### Example +### Memory Filtering +**Filters results** to keep only the most precisely relevant memories. -**Without rerank:** -1. "Traveled to France last year" -2. "Planning a trip to Japan next month" -3. "Interested in visiting Tokyo restaurants" - -**With rerank=True:** -1. "Planning a trip to Japan next month" -2. "Interested in visiting Tokyo restaurants" -3. "Traveled to France last year" - -### Trade-offs -- Significantly improves result ordering accuracy -- Ensures most relevant memories appear first -- Adds ~150–200ms latency -- Higher computational cost - - - -## Filtering - -Filtering allows you to narrow down search results by applying specific criteria from the set of retrieved memories. - -### When to use -- You require highly specific results -- You are working with huge amount of data where noise is problematic -- You require quality over quantity results - -### API Usage -```python + + +- Need highly specific, focused results +- Working with large datasets where noise is problematic +- Quality over quantity is essential +- Building production or safety-critical applications + + +```python Python +# Get only the most relevant dietary restrictions results = client.search( query="What are my dietary restrictions?", filter_memories=True, - user_id="alex" + user_id="user123" ) + +# Before filtering: After filtering: +# • "Allergic to nuts" → • "Allergic to nuts" +# • "Likes Italian food" → • "Vegetarian diet" +# • "Vegetarian diet" → +# • "Eats dinner at 7pm" → ``` + + +- **Latency**: 200-300ms additional +- **Precision**: Maximized +- **Recall**: May be reduced +- **Best for**: Focused queries, production systems + + -### Example +## Real-World Use Cases -**Without filtering:** -- "Vegetarian. Allergic to nuts." -- "I enjoy cooking Italian food on weekends" -- "Mentioned disliking seafood during restaurant discussion" -- "Prefers to eat dinner at 7pm" - -**With filter_memories=True:** -- "Vegetarian. Allergic to nuts." -- "Mentioned disliking seafood during restaurant discussion" - -### Trade-offs -- Maximizes precision (highly relevant results only) -- May reduce recall (filters out some relevant memories) -- Adds ~200-300ms latency -- Best for focused, specific queries - - - -## Combining Modes - -You can combine all three retrieval modes as needed: - -```python + + +```python Python +# Smart home assistant finding device preferences results = client.search( - query="What are my travel plans?", - keyword_search=True, - rerank=True, - filter_memories=True, - user_id="alex" + query="How do I like my bedroom temperature?", + keyword_search=True, # Find specific temperature mentions + rerank=True, # Get most recent preferences first + user_id="user123" ) + +# Finds: "Keep bedroom at 68°F", "Too cold last night at 65°F", etc. +``` + + +```python Python +# Find specific product issues with high precision +results = client.search( + query="Problems with premium subscription billing", + keyword_search=True, # Find "premium", "billing", "subscription" + filter_memories=True, # Only billing-related issues + user_id="customer456" +) + +# Returns only relevant billing problems, not general questions +``` + + +```python Python +# Critical medical information needs perfect accuracy +results = client.search( + query="Patient allergies and contraindications", + rerank=True, # Most important info first + filter_memories=True, # Only medical restrictions + user_id="patient789" +) + +# Ensures critical allergy info appears first and filters out non-medical data +``` + + +```python Python +# Find learning progress for specific topics +results = client.search( + query="Python programming progress and difficulties", + keyword_search=True, # Find "Python", "programming", specific concepts + rerank=True, # Recent progress first + user_id="student123" +) + +# Gets comprehensive view of Python learning journey +``` + + + +## Choosing the Right Combination + +### Recommended Configurations + + +```python Python +# Fast and broad - good for exploration +def quick_search(query, user_id): + return client.search( + query=query, + keyword_search=True, + user_id=user_id + ) + +# Balanced - good for most applications +def standard_search(query, user_id): + return client.search( + query=query, + keyword_search=True, + rerank=True, + user_id=user_id + ) + +# High precision - good for critical applications +def precise_search(query, user_id): + return client.search( + query=query, + rerank=True, + filter_memories=True, + user_id=user_id + ) ``` -This configuration broadens the candidate pool with keywords, improves ordering via rerank, and finally cuts noise with filtering. - Combining all modes may add up to ~450ms latency per query. +```javascript JavaScript +// Fast and broad - good for exploration +function quickSearch(query, userId) { + return client.search(query, { + user_id: userId, + keyword_search: true + }); +} +// Balanced - good for most applications +function standardSearch(query, userId) { + return client.search(query, { + user_id: userId, + keyword_search: true, + rerank: true + }); +} +// High precision - good for critical applications +function preciseSearch(query, userId) { + return client.search(query, { + user_id: userId, + rerank: true, + filter_memories: true + }); +} +``` + -## Performance Benchmarks +## Best Practices -| **Mode** | **Approximate Latency** | -|------------------|-------------------------| -| `keyword_search` | <10ms | -| `rerank` | 150–200ms | -| `filter_memories`| 200–300ms | +### ✅ Do +- **Start simple** with just one enhancement and measure impact +- **Use keyword search** for entity-heavy queries (names, places, technical terms) +- **Use reranking** when the top result quality matters most +- **Use filtering** for production systems where precision is critical +- **Handle empty results** gracefully when filtering is too aggressive +- **Monitor latency** and adjust based on your application's needs +### ❌ Don't +- Enable all options by default without measuring necessity +- Use filtering for broad exploratory queries +- Ignore latency impact in real-time applications +- Forget to handle cases where filtering returns no results +- Use advanced retrieval for simple, fast lookup scenarios +## Performance Guidelines -## Best Practices & Limitations +### Latency Expectations -- Use `keyword_search` for broader recall when query context is limited -- Use `rerank` to prioritize the top-most relevant result -- Use `filter_memories` in production-facing or safety-critical agents -- Combine filtering and reranking for maximum accuracy -- Filters may eliminate all results—always handle the empty set gracefully -- Filtering uses LLM evaluation and may be rate-limited depending on your plan +```python Python +# Performance monitoring example +import time - 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. +start_time = time.time() +results = client.search( + query="user preferences", + keyword_search=True, # +10ms + rerank=True, # +150ms + filter_memories=True, # +250ms + user_id="user123" +) +latency = time.time() - start_time +print(f"Search completed in {latency:.2f}s") # ~0.41s expected +``` + +### Optimization Tips + +1. **Cache frequent queries** to avoid repeated advanced processing +2. **Use session-specific search** with `run_id` to reduce search space +3. **Implement fallback logic** when filtering returns empty results +4. **Monitor and alert** on search latency patterns --- -If you have any questions, please feel free to reach out to us using one of the following methods: + +**Ready to enhance your search?** Start with keyword search for broader coverage, add reranking for better ordering, and use filtering when precision is critical. diff --git a/docs/platform/features/async-client.mdx b/docs/platform/features/async-client.mdx index b36040944..1ee048fad 100644 --- a/docs/platform/features/async-client.mdx +++ b/docs/platform/features/async-client.mdx @@ -5,7 +5,6 @@ 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 diff --git a/docs/platform/features/contextual-add.mdx b/docs/platform/features/contextual-add.mdx index ec5162db7..5b291be84 100644 --- a/docs/platform/features/contextual-add.mdx +++ b/docs/platform/features/contextual-add.mdx @@ -1,207 +1,256 @@ --- -title: Contextual Add (ADD v2) +title: Contextual Memory Creation icon: "square-plus" iconType: "solid" +description: "Add messages with automatic context management - no manual history tracking required" --- - +## What is Contextual Memory Creation? -Mem0 now supports an contextual add version (v2). To use it, set `version="v2"` during the add call. The default version is v1, which is deprecated now. We recommend migrating to `v2` for new applications. - -## Key Differences Between v1 and v2 - -### Version 1 (Legacy) -In v1 (default), users needed to pass either the entire conversation history or past k messages with each new message to generate properly contextualized memories. This approach required: - -- Manually tracking and sending previous messages using a sliding window approach -- Increased payload sizes as conversations grew longer, requiring careful window size management +Contextual memory creation automatically manages message history for you, so you can focus on building great AI experiences instead of tracking interactions manually. Simply send new messages, and Mem0 handles the context automatically. +```python Python +# Just send new messages - Mem0 handles the context +messages = [ + {"role": "user", "content": "I love Italian food, especially pasta"}, + {"role": "assistant", "content": "Great! I'll remember your preference for Italian cuisine."} +] +client.add(messages, user_id="user123", version="v2") +``` + +```javascript JavaScript +// Just send new messages - Mem0 handles the context +const messages = [ + {"role": "user", "content": "I love Italian food, especially pasta"}, + {"role": "assistant", "content": "Great! I'll remember your preference for Italian cuisine."} +]; + +await client.add(messages, { user_id: "user123", version: "v2" }); +``` + + +## Why Use Contextual Memory Creation? + +- **Simple**: Send only new messages, no manual history tracking +- **Efficient**: Smaller payloads and faster processing +- **Automatic**: Context management handled by Mem0 +- **Reliable**: No risk of missing interaction history +- **Scalable**: Works seamlessly as your application grows + +## How It Works + +### Basic Usage + + ```python Python # First interaction messages1 = [ - {"role": "user", "content": "Hi, I'm Alex and I live in San Francisco."}, - {"role": "assistant", "content": "Hello Alex! Nice to meet you. San Francisco is a beautiful city."} + {"role": "user", "content": "Hi, I'm Sarah from New York"}, + {"role": "assistant", "content": "Hello Sarah! Nice to meet you."} ] -client.add(messages1, user_id="alex") +client.add(messages1, user_id="sarah", version="v2") -# Second interaction - must include previous messages for context +# Later interaction - just send new messages messages2 = [ - {"role": "user", "content": "Hi, I'm Alex and I live in San Francisco."}, - {"role": "assistant", "content": "Hello Alex! Nice to meet you. San Francisco is a beautiful city."}, - {"role": "user", "content": "I like to eat sushi, and yesterday I went to Sunnyvale to eat sushi with my friends."}, - {"role": "assistant", "content": "Sushi is really a tasty choice. What did you do this weekend?"} + {"role": "user", "content": "I'm planning a trip to Italy next month"}, + {"role": "assistant", "content": "How exciting! Italy is beautiful this time of year."} ] -client.add(messages2, user_id="alex") +client.add(messages2, user_id="sarah", version="v2") +# Mem0 automatically knows Sarah is from New York and can use this context ``` ```javascript JavaScript // First interaction const messages1 = [ - {"role": "user", "content": "Hi, I'm Alex and I live in San Francisco."}, - {"role": "assistant", "content": "Hello Alex! Nice to meet you. San Francisco is a beautiful city."} + {"role": "user", "content": "Hi, I'm Sarah from New York"}, + {"role": "assistant", "content": "Hello Sarah! Nice to meet you."} ]; -client.add(messages1, { user_id: "alex" }) - .then(response => console.log(response)) - .catch(error => console.error(error)); +await client.add(messages1, { user_id: "sarah", version: "v2" }); -// Second interaction - must include previous messages for context +// Later interaction - just send new messages const messages2 = [ - {"role": "user", "content": "Hi, I'm Alex and I live in San Francisco."}, - {"role": "assistant", "content": "Hello Alex! Nice to meet you. San Francisco is a beautiful city."}, - {"role": "user", "content": "I like to eat sushi, and yesterday I went to Sunnyvale to eat sushi with my friends."}, - {"role": "assistant", "content": "Sushi is really a tasty choice. What did you do this weekend?"} + {"role": "user", "content": "I'm planning a trip to Italy next month"}, + {"role": "assistant", "content": "How exciting! Italy is beautiful this time of year."} ]; -client.add(messages2, { user_id: "alex" }) - .then(response => console.log(response)) - .catch(error => console.error(error)); +await client.add(messages2, { user_id: "sarah", version: "v2" }); +// Mem0 automatically knows Sarah is from New York and can use this context ``` - -### Version 2 (Recommended) -In v2, Mem0 automatically manages conversation context. Users only need to send new messages, and the system will: +## Organization Strategies -- Automatically retrieve relevant conversation history -- Generate properly contextualized memories -- Reduce payload sizes and simplify integration +Choose the right approach based on your application's needs: + +### User-Level Memories (`user_id` only) + +Best for: Personal preferences, profile information, long-term user data - ```python Python -# First interaction +# Persistent user memories across all interactions +messages = [ + {"role": "user", "content": "I'm allergic to nuts and dairy"}, + {"role": "assistant", "content": "I've noted your allergies for future reference."} +] + +client.add(messages, user_id="user123", version="v2") +# This allergy info will be available in ALL future interactions +``` + +```javascript JavaScript +// Persistent user memories across all interactions +const messages = [ + {"role": "user", "content": "I'm allergic to nuts and dairy"}, + {"role": "assistant", "content": "I've noted your allergies for future reference."} +]; + +await client.add(messages, { user_id: "user123", version: "v2" }); +// This allergy info will be available in ALL future interactions +``` + + +### Session-Specific Memories (`user_id` + `run_id`) + +Best for: Task-specific context, separate interaction threads, project-based sessions + + +```python Python +# Trip planning session messages1 = [ - {"role": "user", "content": "Hi, I'm Alex and I live in San Francisco."}, - {"role": "assistant", "content": "Hello Alex! Nice to meet you. San Francisco is a beautiful city."} + {"role": "user", "content": "I want to plan a 5-day trip to Tokyo"}, + {"role": "assistant", "content": "Perfect! Let's plan your Tokyo adventure."} ] -client.add(messages1, user_id="alex", version="v2") +client.add(messages1, user_id="user123", run_id="tokyo-trip-2024", version="v2") -# Second interaction - only need to send new messages +# Later in the same trip planning session messages2 = [ - {"role": "user", "content": "I like to eat sushi, and yesterday I went to Sunnyvale to eat sushi with my friends."}, - {"role": "assistant", "content": "Sushi is really a tasty choice. What did you do this weekend?"} + {"role": "user", "content": "I prefer staying near Shibuya"}, + {"role": "assistant", "content": "Great choice! Shibuya is very convenient."} ] -client.add(messages2, user_id="alex", version="v2") +client.add(messages2, user_id="user123", run_id="tokyo-trip-2024", version="v2") + +# Different session for work project (separate context) +work_messages = [ + {"role": "user", "content": "Let's discuss the Q4 marketing strategy"}, + {"role": "assistant", "content": "Sure! What are your main goals for Q4?"} +] +client.add(work_messages, user_id="user123", run_id="q4-marketing", version="v2") ``` ```javascript JavaScript -// First interaction +// Trip planning session const messages1 = [ - {"role": "user", "content": "Hi, I'm Alex and I live in San Francisco."}, - {"role": "assistant", "content": "Hello Alex! Nice to meet you. San Francisco is a beautiful city."} + {"role": "user", "content": "I want to plan a 5-day trip to Tokyo"}, + {"role": "assistant", "content": "Perfect! Let's plan your Tokyo adventure."} ]; -client.add(messages1, { user_id: "alex", version: "v2" }) - .then(response => console.log(response)) - .catch(error => console.error(error)); +await client.add(messages1, { user_id: "user123", run_id: "tokyo-trip-2024", version: "v2" }); -// Second interaction - only need to send new messages +// Later in the same trip planning session const messages2 = [ - {"role": "user", "content": "I like to eat sushi, and yesterday I went to Sunnyvale to eat sushi with my friends."}, - {"role": "assistant", "content": "Sushi is really a tasty choice. What did you do this weekend?"} + {"role": "user", "content": "I prefer staying near Shibuya"}, + {"role": "assistant", "content": "Great choice! Shibuya is very convenient."} ]; -client.add(messages2, { user_id: "alex", version: "v2" }) - .then(response => console.log(response)) - .catch(error => console.error(error)); -``` +await client.add(messages2, { user_id: "user123", run_id: "tokyo-trip-2024", version: "v2" }); +// Different session for work project (separate context) +const workMessages = [ + {"role": "user", "content": "Let's discuss the Q4 marketing strategy"}, + {"role": "assistant", "content": "Sure! What are your main goals for Q4?"} +]; +await client.add(workMessages, { user_id: "user123", run_id: "q4-marketing", version: "v2" }); +``` -## Benefits of Using v2 - -1. **Simplified Integration**: No need to track and manage conversation history -2. **Reduced Payload Size**: Only send new messages, not the entire conversation -3. **Improved Memory Quality**: Automatic context retrieval ensures better memory generation - -## Understanding ID Parameters in v2 - -When using contextual add v2, you have different options for how to organize and retrieve memories: - -### Using Only `user_id` - -When you provide only a `user_id`: - -- Memories are associated with this user's long-term memory store -- The system will automatically retrieve relevant context from all of the user's previous conversations -- These memories persist indefinitely across all of the user's sessions -- Ideal for maintaining persistent user information (preferences, personal details, etc.) - - +## Real-World Use Cases + + ```python Python -# Adding to long-term user memory +# Support ticket context - keeps interaction focused messages = [ - {"role": "user", "content": "I'm allergic to peanuts and shellfish."}, - {"role": "assistant", "content": "I've noted your allergies to peanuts and shellfish."} + {"role": "user", "content": "My subscription isn't working"}, + {"role": "assistant", "content": "I can help with that. What specific issue are you experiencing?"}, + {"role": "user", "content": "I can't access premium features even though I paid"} ] -client.add(messages, user_id="alex", version="v2") + +# Each support ticket gets its own run_id +client.add(messages, + user_id="customer123", + run_id="ticket-2024-001", + version="v2" +) ``` - -```javascript JavaScript -// Adding to long-term user memory -const messages = [ - {"role": "user", "content": "I'm allergic to peanuts and shellfish."}, - {"role": "assistant", "content": "I've noted your allergies to peanuts and shellfish."} -]; -client.add(messages, { user_id: "alex", version: "v2" }) - .then(response => console.log(response)) - .catch(error => console.error(error)); -``` - - - -### Using `user_id` with `run_id` - -When you provide both `user_id` and `run_id`: - -- Memories are associated with a specific conversation session or interaction -- The system will retrieve context primarily from this specific session -- These memories are still tied to the user but are organized by the specific session -- Ideal for maintaining context within a specific conversation flow or task -- Helps prevent context from different conversations from interfering with each other - - - + + ```python Python -# Adding to a specific conversation session -messages = [ - {"role": "user", "content": "For this trip to Paris, I want to focus on art museums."}, - {"role": "assistant", "content": "Great! I'll help you plan your Paris trip with a focus on art museums."} +# Personal preferences (persistent across all interactions) +preference_messages = [ + {"role": "user", "content": "I prefer morning workouts and vegetarian meals"}, + {"role": "assistant", "content": "Got it! I'll keep your fitness and dietary preferences in mind."} ] -client.add(messages, user_id="alex", run_id="paris-trip-2024", version="v2") -# Later in the same conversation session -messages2 = [ - {"role": "user", "content": "I'd like to visit the Louvre on Monday."}, - {"role": "assistant", "content": "The Louvre is a great choice for Monday. Would you like information about opening hours?"} +client.add(preference_messages, user_id="user456", version="v2") + +# Daily planning session (session-specific) +planning_messages = [ + {"role": "user", "content": "Help me plan tomorrow's schedule"}, + {"role": "assistant", "content": "Of course! I'll consider your morning workout preference."} ] -client.add(messages2, user_id="alex", run_id="paris-trip-2024", version="v2") + +client.add(planning_messages, + user_id="user456", + run_id="daily-plan-2024-01-15", + version="v2" +) ``` + + +```python Python +# Student profile (persistent) +profile_messages = [ + {"role": "user", "content": "I'm studying computer science and struggle with math"}, + {"role": "assistant", "content": "I'll tailor explanations to help with math concepts."} +] -```javascript JavaScript -// Adding to a specific conversation session -const messages = [ - {"role": "user", "content": "For this trip to Paris, I want to focus on art museums."}, - {"role": "assistant", "content": "Great! I'll help you plan your Paris trip with a focus on art museums."} -]; -client.add(messages, { user_id: "alex", run_id: "paris-trip-2024", version: "v2" }) - .then(response => console.log(response)) - .catch(error => console.error(error)); +client.add(profile_messages, user_id="student789", version="v2") -// Later in the same conversation session -const messages2 = [ - {"role": "user", "content": "I'd like to visit the Louvre on Monday."}, - {"role": "assistant", "content": "The Louvre is a great choice for Monday. Would you like information about opening hours?"} -]; -client.add(messages2, { user_id: "alex", run_id: "paris-trip-2024", version: "v2" }) - .then(response => console.log(response)) - .catch(error => console.error(error)); +# Specific lesson session +lesson_messages = [ + {"role": "user", "content": "Can you explain algorithms?"}, + {"role": "assistant", "content": "Sure! I'll explain algorithms with math-friendly examples."} +] + +client.add(lesson_messages, + user_id="student789", + run_id="algorithms-lesson-1", + version="v2" +) ``` + + - +## Best Practices -Using `run_id` helps you organize memories into logical sessions or tasks, making it easier to maintain context for specific interactions while still associating everything with the user's overall profile. +### ✅ Do +- **Organize by context scope**: Use `user_id` only for persistent data, add `run_id` for session-specific context +- **Keep messages focused** on the current interaction +- **Test with real interaction flows** to ensure context works as expected + +### ❌ Don't +- Send duplicate messages or interaction history +- Forget to include `version="v2"` parameter +- Mix contextual and non-contextual approaches in the same application + +## Troubleshooting + +| Issue | Solution | +|-------|----------| +| **Context not working** | Ensure you're using `version="v2"` and consistent `user_id` | +| **Wrong context retrieved** | Check if you need separate `run_id` values for different interaction topics | +| **Missing interaction history** | Verify all messages in the interaction thread use the same `user_id` and `run_id` | +| **Too much irrelevant context** | Use more specific `run_id` values to separate different interaction types | -If you have any questions, please feel free to reach out to us using one of the following methods: \ No newline at end of file diff --git a/docs/platform/features/criteria-retrieval.mdx b/docs/platform/features/criteria-retrieval.mdx index f52cc38d6..a269fc5b2 100644 --- a/docs/platform/features/criteria-retrieval.mdx +++ b/docs/platform/features/criteria-retrieval.mdx @@ -4,9 +4,6 @@ icon: "magnifying-glass-plus" iconType: "solid" --- - - - Mem0’s **Criteria Retrieval** feature allows you to retrieve memories based on your defined criteria. It goes beyond generic semantic relevance and rank memories based on what matters to your application - emotional tone, intent, behavioral signals, or other custom traits. Instead of just searching for "how similar a memory is to this query?", you can define what *relevance* really means for your project. For example: diff --git a/docs/platform/features/custom-categories.mdx b/docs/platform/features/custom-categories.mdx index c1ce5ad25..6a921e0d7 100644 --- a/docs/platform/features/custom-categories.mdx +++ b/docs/platform/features/custom-categories.mdx @@ -5,8 +5,6 @@ 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.** diff --git a/docs/platform/features/custom-instructions.mdx b/docs/platform/features/custom-instructions.mdx index b9281272c..846dbbc8a 100644 --- a/docs/platform/features/custom-instructions.mdx +++ b/docs/platform/features/custom-instructions.mdx @@ -1,78 +1,338 @@ --- title: Custom Instructions -description: 'Enhance your product experience by adding custom instructions tailored to your needs' +description: 'Control how Mem0 extracts and stores memories using natural language guidelines' icon: "pencil" iconType: "solid" --- - +## What are Custom Instructions? -## 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: +Custom instructions are natural language guidelines that tell Mem0 exactly what information to extract and remember from conversations. Think of them as smart filters that ensure your AI application captures only the most relevant data for your specific use case. -```python Code -# Update custom instructions -prompt =""" -Your Task: Extract ONLY health-related information from conversations, focusing on the following areas: +```python Python +# Simple example: Health app focusing on wellness +prompt = """ +Extract only health and wellness information: +- Symptoms, medications, and treatments +- Exercise routines and dietary habits +- Doctor appointments and health goals -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. +Exclude: Personal identifiers, financial data """ -response = client.project.update(custom_instructions=prompt) -print(response) + +client.project.update(custom_instructions=prompt) ``` -```json Output -{ - "message": "Updated custom instructions" -} +```javascript JavaScript +// Simple example: Health app focusing on wellness +const prompt = ` +Extract only health and wellness information: +- Symptoms, medications, and treatments +- Exercise routines and dietary habits +- Doctor appointments and health goals + +Exclude: Personal identifiers, financial data +`; + +await client.project.update({ custom_instructions: prompt }); ``` -You can also retrieve the current custom instructions: +## Why Use Custom Instructions? + +- **Focus on What Matters**: Only capture information relevant to your application +- **Maintain Privacy**: Explicitly exclude sensitive data like passwords or personal identifiers +- **Ensure Consistency**: All memories follow the same extraction rules across your project +- **Improve Quality**: Filter out noise and irrelevant conversations + +## How to Set Custom Instructions + +### Basic Setup -```python Code -# Retrieve current custom instructions +```python Python +# Set instructions for your project +client.project.update(custom_instructions="Your guidelines here...") + +# Retrieve current instructions response = client.project.get(fields=["custom_instructions"]) -print(response) +print(response["custom_instructions"]) ``` -```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." -} +```javascript JavaScript +// Set instructions for your project +await client.project.update({ custom_instructions: "Your guidelines here..." }); + +// Retrieve current instructions +const response = await client.project.get({ fields: ["custom_instructions"] }); +console.log(response.custom_instructions); ``` - \ No newline at end of file + + +### Best Practice Template + +Structure your instructions using this proven template: + +``` +Your Task: [Brief description of what to extract] + +Information to Extract: +1. [Category 1]: + - [Specific details] + - [What to look for] + +2. [Category 2]: + - [Specific details] + - [What to look for] + +Guidelines: +- [Processing rules] +- [Quality requirements] + +Exclude: +- [Sensitive data to avoid] +- [Irrelevant information] +``` + +## Real-World Examples + + + + +```python Python +instructions = """ +Extract customer service information for better support: + +1. Product Issues: + - Product names, SKUs, defects + - Return/exchange requests + - Quality complaints + +2. Customer Preferences: + - Preferred brands, sizes, colors + - Shopping frequency and habits + - Price sensitivity + +3. Service Experience: + - Satisfaction with support + - Resolution time expectations + - Communication preferences + +Exclude: Payment card numbers, passwords, personal identifiers. +""" + +client.project.update(custom_instructions=instructions) +``` + +```javascript JavaScript +const instructions = ` +Extract customer service information for better support: + +1. Product Issues: + - Product names, SKUs, defects + - Return/exchange requests + - Quality complaints + +2. Customer Preferences: + - Preferred brands, sizes, colors + - Shopping frequency and habits + - Price sensitivity + +3. Service Experience: + - Satisfaction with support + - Resolution time expectations + - Communication preferences + +Exclude: Payment card numbers, passwords, personal identifiers. +`; + +await client.project.update({ custom_instructions: instructions }); +``` + + + + +```python Python +education_prompt = """ +Extract learning-related information for personalized education: + +1. Learning Progress: + - Course completions and current modules + - Skills acquired and improvement areas + - Learning goals and objectives + +2. Student Preferences: + - Learning styles (visual, audio, hands-on) + - Time availability and scheduling + - Subject interests and career goals + +3. Performance Data: + - Assignment feedback and patterns + - Areas of struggle or strength + - Study habits and engagement + +Exclude: Specific grades, personal identifiers, financial information. +""" + +client.project.update(custom_instructions=education_prompt) +``` + +```javascript JavaScript +const educationPrompt = ` +Extract learning-related information for personalized education: + +1. Learning Progress: + - Course completions and current modules + - Skills acquired and improvement areas + - Learning goals and objectives + +2. Student Preferences: + - Learning styles (visual, audio, hands-on) + - Time availability and scheduling + - Subject interests and career goals + +3. Performance Data: + - Assignment feedback and patterns + - Areas of struggle or strength + - Study habits and engagement + +Exclude: Specific grades, personal identifiers, financial information. +`; + +await client.project.update({ custom_instructions: educationPrompt }); +``` + + + + +```python Python +finance_prompt = """ +Extract financial planning information for advisory services: + +1. Financial Goals: + - Retirement and investment objectives + - Risk tolerance and preferences + - Short-term and long-term goals + +2. Life Events: + - Career and income changes + - Family changes (marriage, children) + - Major planned purchases + +3. Investment Interests: + - Asset allocation preferences + - ESG or ethical investment interests + - Previous investment experience + +Exclude: Account numbers, SSNs, passwords, specific financial amounts. +""" + +client.project.update(custom_instructions=finance_prompt) +``` + +```javascript JavaScript +const financePrompt = ` +Extract financial planning information for advisory services: + +1. Financial Goals: + - Retirement and investment objectives + - Risk tolerance and preferences + - Short-term and long-term goals + +2. Life Events: + - Career and income changes + - Family changes (marriage, children) + - Major planned purchases + +3. Investment Interests: + - Asset allocation preferences + - ESG or ethical investment interests + - Previous investment experience + +Exclude: Account numbers, SSNs, passwords, specific financial amounts. +`; + +await client.project.update({ custom_instructions: financePrompt }); +``` + + + + +## Advanced Techniques + +### Conditional Processing + +Handle different conversation types with conditional logic: + + +```python Python +advanced_prompt = """ +Extract information based on conversation context: + +IF customer support conversation: +- Issue type, severity, resolution status +- Customer satisfaction indicators + +IF sales conversation: +- Product interests, budget range +- Decision timeline and influencers + +IF onboarding conversation: +- User experience level +- Feature interests and priorities + +Always exclude personal identifiers and maintain professional context. +""" + +client.project.update(custom_instructions=advanced_prompt) +``` + + +### Testing Your Instructions + +Always test your custom instructions with real messages examples: + + +```python Python +# Test with sample messages +messages = [ + {"role": "user", "content": "I'm having billing issues with my subscription"}, + {"role": "assistant", "content": "I can help with that. What's the specific problem?"}, + {"role": "user", "content": "I'm being charged twice each month"} +] + +# Add the messages and check extracted memories +result = client.add(messages, user_id="test_user") +memories = client.get_all(user_id="test_user") + +# Review if the right information was extracted +for memory in memories: + print(f"Extracted: {memory['memory']}") +``` + + +## Best Practices + +### ✅ Do +- **Be specific** about what information to extract +- **Use clear categories** to organize your instructions +- **Test with real conversations** before deploying +- **Explicitly state exclusions** for privacy and compliance +- **Start simple** and iterate based on results + +### ❌ Don't +- Make instructions too long or complex +- Create conflicting rules within your guidelines +- Be overly restrictive (balance specificity with flexibility) +- Forget to exclude sensitive information +- Skip testing with diverse conversation examples + +## Common Issues and Solutions + +| Issue | Solution | +|-------|----------| +| **Instructions too long** | Break into focused categories, keep concise | +| **Missing important data** | Add specific examples of what to capture | +| **Capturing irrelevant info** | Strengthen exclusion rules and be more specific | +| **Inconsistent results** | Clarify guidelines and test with more examples | diff --git a/docs/platform/features/direct-import.mdx b/docs/platform/features/direct-import.mdx index ec3c2a656..a1619eceb 100644 --- a/docs/platform/features/direct-import.mdx +++ b/docs/platform/features/direct-import.mdx @@ -5,8 +5,6 @@ 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. diff --git a/docs/platform/features/expiration-date.mdx b/docs/platform/features/expiration-date.mdx index abc02f636..64b757342 100644 --- a/docs/platform/features/expiration-date.mdx +++ b/docs/platform/features/expiration-date.mdx @@ -5,8 +5,6 @@ icon: "clock" iconType: "solid" --- - - ## Benefits of Memory Expiration Setting expiration dates for memories offers several advantages: diff --git a/docs/platform/features/feedback-mechanism.mdx b/docs/platform/features/feedback-mechanism.mdx index c28a939cc..92dd6c7f4 100644 --- a/docs/platform/features/feedback-mechanism.mdx +++ b/docs/platform/features/feedback-mechanism.mdx @@ -4,8 +4,6 @@ icon: "thumbs-up" iconType: "solid" --- - - Mem0's **Feedback Mechanism** allows you to provide feedback on the memories generated by your application. This feedback is used to improve the accuracy of the memories and the search results. ## How it works @@ -50,15 +48,154 @@ The `feedback` parameter can be one of the following values: ## Parameters -The `feedback` method takes the following parameters: +The `feedback` method accepts these parameters: -- `memory_id`: The ID of the memory to give feedback on. -- `feedback`: The feedback to give on the memory. (Optional) -- `feedback_reason`: The reason for the feedback. (Optional) - -The `feedback_reason` parameter is optional and can be used to provide a reason for the feedback. +| Parameter | Type | Required | Description | +|-----------|------|----------|-------------| +| `memory_id` | string | Yes | The ID of the memory to give feedback on | +| `feedback` | string | No | Type of feedback: `POSITIVE`, `NEGATIVE`, or `VERY_NEGATIVE` | +| `feedback_reason` | string | No | Optional explanation for the feedback | -You can pass `None` or `null` to the `feedback` and `feedback_reason` parameters to remove the feedback for a memory. +Pass `None` or `null` to the `feedback` and `feedback_reason` parameters to remove existing feedback for a memory. +## Bulk Feedback Operations + +For applications with high volumes of feedback, you can provide feedback on multiple memories at once: + + + +```python Python +from mem0 import MemoryClient + +client = MemoryClient(api_key="your_api_key") + +# Bulk feedback example +feedback_data = [ + { + "memory_id": "memory-1", + "feedback": "POSITIVE", + "feedback_reason": "Accurately captured the user's preference" + }, + { + "memory_id": "memory-2", + "feedback": "NEGATIVE", + "feedback_reason": "Contains outdated information" + } +] + +for item in feedback_data: + client.feedback(**item) +``` + +```javascript JavaScript +import MemoryClient from 'mem0ai'; + +const client = new MemoryClient({ apiKey: 'your-api-key'}); + +// Bulk feedback example +const feedbackData = [ + { + memory_id: "memory-1", + feedback: "POSITIVE", + feedback_reason: "Accurately captured the user's preference" + }, + { + memory_id: "memory-2", + feedback: "NEGATIVE", + feedback_reason: "Contains outdated information" + } +]; + +for (const item of feedbackData) { + await client.feedback(item); +} +``` + + + +## Best Practices + +### When to Provide Feedback +- **Immediately after memory retrieval** when you can assess relevance +- **During user interactions** when users explicitly indicate satisfaction/dissatisfaction +- **Through automated evaluation** using your application's success metrics + +### Effective Feedback Reasons +Provide specific, actionable feedback reasons: + +✅ **Good examples:** +- "Contains outdated contact information" +- "Accurately captured the user's dietary restrictions" +- "Irrelevant to the current conversation context" + +❌ **Avoid vague reasons:** +- "Bad memory" +- "Wrong" +- "Not good" + +### Feedback Strategy +1. **Be consistent** - Apply the same criteria across similar memories +2. **Be specific** - Detailed reasons help improve the system faster +3. **Monitor patterns** - Regular feedback analysis helps identify improvement areas + +## Error Handling + +Handle potential errors when submitting feedback: + + + +```python Python +from mem0 import MemoryClient +from mem0.exceptions import MemoryNotFoundError, APIError + +client = MemoryClient(api_key="your_api_key") + +try: + client.feedback( + memory_id="memory-123", + feedback="POSITIVE", + feedback_reason="Helpful context for user query" + ) + print("Feedback submitted successfully") +except MemoryNotFoundError: + print("Memory not found") +except APIError as e: + print(f"API error: {e}") +except Exception as e: + print(f"Unexpected error: {e}") +``` + +```javascript JavaScript +import MemoryClient from 'mem0ai'; + +const client = new MemoryClient({ apiKey: 'your-api-key'}); + +try { + await client.feedback({ + memory_id: "memory-123", + feedback: "POSITIVE", + feedback_reason: "Helpful context for user query" + }); + console.log("Feedback submitted successfully"); +} catch (error) { + if (error.status === 404) { + console.log("Memory not found"); + } else { + console.log(`Error: ${error.message}`); + } +} +``` + + + +## Feedback Analytics + +Track the impact of your feedback by monitoring memory performance over time. Consider implementing: + +- **Feedback completion rates** - What percentage of memories receive feedback +- **Feedback distribution** - Balance of positive vs. negative feedback +- **Memory quality trends** - How accuracy improves with feedback volume +- **User satisfaction metrics** - Correlation between feedback and user experience + diff --git a/docs/platform/features/graph-memory.mdx b/docs/platform/features/graph-memory.mdx index 89c0d57c9..b36beef77 100644 --- a/docs/platform/features/graph-memory.mdx +++ b/docs/platform/features/graph-memory.mdx @@ -5,8 +5,6 @@ iconType: "solid" description: "Enable graph-based memory retrieval for more contextually relevant results" --- - - ## Overview Graph Memory enhances memory pipeline by creating relationships between entities in your data. It builds a network of interconnected information for more contextually relevant search results. diff --git a/docs/platform/features/memory-export.mdx b/docs/platform/features/memory-export.mdx index bca4d9f04..3aed222b1 100644 --- a/docs/platform/features/memory-export.mdx +++ b/docs/platform/features/memory-export.mdx @@ -5,8 +5,6 @@ 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. diff --git a/docs/platform/features/multimodal-support.mdx b/docs/platform/features/multimodal-support.mdx index 24b33c1ba..6754b357b 100644 --- a/docs/platform/features/multimodal-support.mdx +++ b/docs/platform/features/multimodal-support.mdx @@ -5,8 +5,6 @@ icon: "image" iconType: "solid" --- - - Mem0 extends its capabilities beyond text by supporting multimodal data, including images and documents. With this feature, users can seamlessly integrate visual and document content into their interactions—allowing Mem0 to extract relevant information from various media types and enrich the memory system. ## How It Works diff --git a/docs/platform/features/platform-overview.mdx b/docs/platform/features/platform-overview.mdx index 1500019ef..1f96eb595 100644 --- a/docs/platform/features/platform-overview.mdx +++ b/docs/platform/features/platform-overview.mdx @@ -4,8 +4,6 @@ icon: "info" iconType: "solid" --- - - Learn about the key features and capabilities that make Mem0 a powerful platform for memory management and retrieval. ## Core Features diff --git a/docs/platform/features/selective-memory.mdx b/docs/platform/features/selective-memory.mdx index 01e9599bf..6b731e6da 100644 --- a/docs/platform/features/selective-memory.mdx +++ b/docs/platform/features/selective-memory.mdx @@ -5,8 +5,6 @@ icon: "filter" iconType: "solid" --- - - ## Benefits of Memory Customization Memory customization offers several key benefits: diff --git a/docs/platform/features/timestamp.mdx b/docs/platform/features/timestamp.mdx index 4484268f4..0b4fe0ba9 100644 --- a/docs/platform/features/timestamp.mdx +++ b/docs/platform/features/timestamp.mdx @@ -5,8 +5,6 @@ icon: "clock" iconType: "solid" --- - - ## Overview The Memory Timestamps feature allows you to specify when a memory was created, regardless of when it's actually added to the system. This powerful capability enables you to: diff --git a/docs/platform/features/webhooks.mdx b/docs/platform/features/webhooks.mdx index bc4ba71dd..8994d490e 100644 --- a/docs/platform/features/webhooks.mdx +++ b/docs/platform/features/webhooks.mdx @@ -5,8 +5,6 @@ icon: "webhook" iconType: "solid" --- - - ## Overview Webhooks enable real-time notifications for memory events in your Mem0 project. Webhooks are configured at the project level, meaning each webhook is tied to a specific project and receives events solely from that project. You can configure webhooks to send HTTP POST requests to your specified URLs whenever memories are created, updated, or deleted. diff --git a/docs/platform/overview.mdx b/docs/platform/overview.mdx index 2b63c5e7b..19383077e 100644 --- a/docs/platform/overview.mdx +++ b/docs/platform/overview.mdx @@ -5,8 +5,6 @@ icon: "eye" iconType: "solid" --- - - ## Welcome to Mem0 Platform The Mem0 Platform is a managed service and the easiest way to add our powerful memory layer to your applications. diff --git a/docs/platform/quickstart.mdx b/docs/platform/quickstart.mdx index 82e61e272..e27d709a7 100644 --- a/docs/platform/quickstart.mdx +++ b/docs/platform/quickstart.mdx @@ -5,11 +5,7 @@ icon: "bolt" iconType: "solid" --- - - - - 🎉 Looking for TypeScript support? Mem0 has you covered! Check out an example [here](/platform/quickstart/#4-11-working-with-mem0-in-typescript). - +Get up and running with Mem0 Platform quickly. This guide covers the essential steps to start storing and retrieving memories. ## 1. Installation @@ -21,7 +17,6 @@ pip install mem0ai ```bash npm npm install mem0ai ``` - ## 2. API Key Setup @@ -31,7 +26,7 @@ npm install mem0ai ![Get API Key from Mem0 Platform](/images/platform/api-key.png) -## 3. Instantiate Client +## 3. Initialize Client ```python Python @@ -39,7 +34,6 @@ import os from mem0 import MemoryClient os.environ["MEM0_API_KEY"] = "your-api-key" - client = MemoryClient() ``` @@ -47,2132 +41,181 @@ client = MemoryClient() import MemoryClient from 'mem0ai'; const client = new MemoryClient({ apiKey: 'your-api-key' }); ``` - -### 3.1 Instantiate Async Client (Python only) +## 4. Basic Operations -For asynchronous operations in Python, you can use the AsyncMemoryClient: +### Add Memories -```python Python -import os -from mem0 import AsyncMemoryClient - -os.environ["MEM0_API_KEY"] = "your-api-key" - -client = AsyncMemoryClient() - - -async def main(): - messages = [ - {"role": "user", "content": "I'm travelling to SF"} - ] - response = await client.add(messages, user_id="john") - print(response) - -await main() -``` - -## 4. Memory Operations - -Mem0 provides a simple and customizable interface for performing CRUD operations on memory. - -### 4.1 Create Memories - -#### Long-term memory for a user - -These memory instances persist across multiple sessions. Ideal for maintaining memory over long time spans. +Store user preferences and context: - ```python Python messages = [ - {"role": "user", "content": "Hi, I'm Alex. I'm a vegetarian and I'm allergic to nuts."}, - {"role": "assistant", "content": "Hello Alex! I've noted that you're a vegetarian and have a nut allergy. I'll keep this in mind for any food-related recommendations or discussions."} + {"role": "user", "content": "Hi, I'm Alex. I'm a vegetarian and allergic to nuts."}, + {"role": "assistant", "content": "Hello Alex! I'll remember your dietary preferences."} ] -client.add(messages, user_id="alex", metadata={"food": "vegan"}) +result = client.add(messages, user_id="alex") +print(result) ``` ```javascript JavaScript const messages = [ - {"role": "user", "content": "Hi, I'm Alex. I'm a vegetarian and I'm allergic to nuts."}, - {"role": "assistant", "content": "Hello Alex! I've noted that you're a vegetarian and have a nut allergy. I'll keep this in mind for any food-related recommendations or discussions."} + {"role": "user", "content": "Hi, I'm Alex. I'm a vegetarian and allergic to nuts."}, + {"role": "assistant", "content": "Hello Alex! I'll remember your dietary preferences."} ]; -client.add(messages, { user_id: "alex", metadata: { food: "vegan" } }) - .then(response => console.log(response)) + +client.add(messages, { user_id: "alex" }) + .then(result => console.log(result)) .catch(error => console.error(error)); ``` - -```bash cURL -curl -X POST "https://api.mem0.ai/v1/memories/" \ - -H "Authorization: Token your-api-key" \ - -H "Content-Type: application/json" \ - -d '{ - "messages": [ - {"role": "user", "content": "Hi, I'm Alex. I'm a vegetarian and I'm allergic to nuts."}, - {"role": "assistant", "content": "Hello Alex! I've noted that you're a vegetarian and have a nut allergy. I'll keep this in mind for any food-related recommendations or discussions."} - ], - "user_id": "alex", - "metadata": { - "food": "vegan" - } - }' -``` - -```json Output -{ - "results": [ - { - "memory": "Name is Alex", - "event": "ADD" - }, - { - "memory": "Is a vegetarian", - "event": "ADD" - }, - { - "memory": "Is allergic to nuts", - "event": "ADD" - } - ] -} -``` - - - When passing `user_id`, memories are primarily created based on user messages, but may be influenced by assistant messages for contextual understanding. For example, in a conversation about food preferences, both the user's stated preferences and their responses to the assistant's questions would form user memories. Similarly, when using `agent_id`, assistant messages are prioritized, but user messages might influence the agent's memories based on context. This approach ensures comprehensive memory creation while maintaining appropriate attribution to either users or agents. - - **Example:** - ``` - User: My favorite cuisine is Italian - Assistant: Nice! What about Indian cuisine? - User: Don't like it much since I cannot eat spicy food - - Resulting user memories: - memory1 - Likes Italian food - memory2 - Doesn't like Indian food since cannot eat spicy - - (memory2 comes from user's response about Indian cuisine) - ``` - +### Search Memories -Metadata allows you to store structured information (location, timestamp, user state) with memories. Add it during creation to enable precise filtering and retrieval during searches. - - -#### Short-term memory for a user session - -These memory instances persist only for the duration of a user session. Ideal for non-repetitive interactions and managing context windows efficiently. +Retrieve relevant memories based on queries: - ```python Python -messages = [ - {"role": "user", "content": "I'm planning a trip to Japan next month."}, - {"role": "assistant", "content": "That's exciting, Alex! A trip to Japan next month sounds wonderful. Would you like some recommendations for vegetarian-friendly restaurants in Japan?"}, - {"role": "user", "content": "Yes, please! Especially in Tokyo."}, - {"role": "assistant", "content": "Great! I'll remember that you're interested in vegetarian restaurants in Tokyo for your upcoming trip. I'll prepare a list for you in our next interaction."} -] - -client.add(messages, user_id="alex", run_id="trip-planning-2024") +query = "What should I cook for dinner?" +results = client.search(query, user_id="alex") +print(results) ``` ```javascript JavaScript -const messages = [ - {"role": "user", "content": "I'm planning a trip to Japan next month."}, - {"role": "assistant", "content": "That's exciting, Alex! A trip to Japan next month sounds wonderful. Would you like some recommendations for vegetarian-friendly restaurants in Japan?"}, - {"role": "user", "content": "Yes, please! Especially in Tokyo."}, - {"role": "assistant", "content": "Great! I'll remember that you're interested in vegetarian restaurants in Tokyo for your upcoming trip. I'll prepare a list for you in our next interaction."} -]; -client.add(messages, { user_id: "alex", run_id: "trip-planning-2024" }) - .then(response => console.log(response)) +const query = "What should I cook for dinner?"; +client.search(query, { user_id: "alex" }) + .then(results => console.log(results)) .catch(error => console.error(error)); ``` - -```bash cURL -curl -X POST "https://api.mem0.ai/v1/memories/" \ - -H "Authorization: Token your-api-key" \ - -H "Content-Type: application/json" \ - -d '{ - "messages": [ - {"role": "user", "content": "I'm planning a trip to Japan next month."}, - {"role": "assistant", "content": "That's exciting, Alex! A trip to Japan next month sounds wonderful. Would you like some recommendations for vegetarian-friendly restaurants in Japan?"}, - {"role": "user", "content": "Yes, please! Especially in Tokyo."}, - {"role": "assistant", "content": "Great! I'll remember that you're interested in vegetarian restaurants in Tokyo for your upcoming trip. I'll prepare a list for you in our next interaction."} - ], - "user_id": "alex", - "run_id": "trip-planning-2024" - }' -``` - -```json Output -{ - "results": [ - { - "memory": "Planning a trip to Japan next month", - "event": "ADD" - }, - { - "memory": "Interested in vegetarian restaurants in Tokyo", - "event": "ADD" - } - ] -} -``` - -#### Long-term memory for agents -Add a memory layer for the assistants and agents so that their responses remain consistent across sessions. +### Get All Memories + +Fetch all memories for a user: - ```python Python -messages = [ - {"role": "system", "content": "You are an AI tutor with a personality. Give yourself a name for the user."}, - {"role": "assistant", "content": "Understood. I'm an AI tutor with a personality. My name is Alice."} -] - -client.add(messages, agent_id="ai-tutor") +memories = client.get_all(user_id="alex") +print(memories) ``` ```javascript JavaScript -const messages = [ - {"role": "system", "content": "You are an AI tutor with a personality. Give yourself a name for the user."}, - {"role": "assistant", "content": "Understood. I'm an AI tutor with a personality. My name is Alice."} -]; -client.add(messages, { agent_id: "ai-tutor" }) - .then(response => console.log(response)) +client.getAll({ user_id: "alex" }) + .then(memories => console.log(memories)) .catch(error => console.error(error)); ``` - -```bash cURL -curl -X POST "https://api.mem0.ai/v1/memories/" \ - -H "Authorization: Token your-api-key" \ - -H "Content-Type: application/json" \ - -d '{ - "messages": [ - {"role": "system", "content": "You are an AI tutor with a personality. Give yourself a name for the user."}, - {"role": "assistant", "content": "Understood. I'm an AI tutor with a personality. My name is Alice."} - ], - "agent_id": "ai-tutor" - }' -``` - -```json Output -{ - "results": [ - { - "memory": "Name is Alex", - "event": "ADD" - }, - { - "memory": "Is a vegetarian", - "event": "ADD" - }, - { - "memory": "Is allergic to nuts", - "event": "ADD" - } - ] -} -``` - - The `agent_id` retains memories exclusively based on messages generated by the assistant or those explicitly provided as input to the assistant. Messages outside these criteria are not stored as memory. - +## 5. Memory Types -#### Long-term memory for both users and agents -When you provide both `user_id` and `agent_id`, Mem0 will store memories for both identifiers separately: -- Memories from messages with `"role": "user"` are automatically tagged with the provided `user_id` -- Memories from messages with `"role": "assistant"` are automatically tagged with the provided `agent_id` -- During retrieval, you can provide either `user_id` or `agent_id` to access the respective memories -- You can continuously enrich existing memory collections by adding new memories to the same `user_id` or `agent_id` in subsequent API calls, either together or separately, allowing for progressive memory building over time -- This dual-tagging approach enables personalized experiences for both users and AI agents in your application +### User Memories +Long-term memories that persist across sessions: - ```python Python -messages = [ - {"role": "user", "content": "I'm travelling to San Francisco"}, - {"role": "assistant", "content": "That's great! I'm going to Dubai next month."}, -] - -client.add(messages=messages, user_id="user1", agent_id="agent1") +client.add(messages, user_id="alex", metadata={"category": "preferences"}) ``` ```javascript JavaScript -const messages = [ - {"role": "user", "content": "I'm travelling to San Francisco"}, - {"role": "assistant", "content": "That's great! I'm going to Dubai next month."}, -] - -client.add(messages, { user_id: "user1", agent_id: "agent1" }) - .then(response => console.log(response)) - .catch(error => console.error(error)); +client.add(messages, { user_id: "alex", metadata: { category: "preferences" } }); ``` - -```bash cURL -curl -X POST "https://api.mem0.ai/v1/memories/" \ - -H "Authorization: Token your-api-key" \ - -H "Content-Type: application/json" \ - -d '{ - "messages": [ - {"role": "user", "content": "I'm travelling to San Francisco"}, - {"role": "assistant", "content": "That's great! I'm going to Dubai next month."}, - ], - "user_id": "user1", - "agent_id": "agent1" - }' -``` - -```json Output -{ - "results": [ - { - // memory from user1 - "id": "c57abfa2-f0ac-48af-896a-21728dbcecee0", - "data": {"memory": "Travelling to San Francisco"}, - "event": "ADD" - }, - { - // memory from agent1 - "id": "0e8c003f-7db7-426a-9fdc-a46f9331a0c2", - "data": {"memory": "Going to Dubai next month"}, - "event": "ADD" - } - ] -} -``` - - -#### Async Memory Addition - -When you set `async_mode=True`, memory processing happens completely asynchronously in the background. This allows for faster API responses while your memories are processed. The memories will be available on the dashboard and for retrieval within a few seconds. +### Session Memories +Short-term memories for specific conversations: - ```python Python -messages = [ - {"role": "user", "content": "I love hiking and outdoor activities"}, - {"role": "assistant", "content": "That's great! I'll remember your interest in hiking and outdoor activities for future recommendations."} -] +client.add(messages, user_id="alex", run_id="session-123") +``` +```javascript JavaScript +client.add(messages, { user_id: "alex", run_id: "session-123" }); +``` + + +### Agent Memories +Memories for AI assistants and agents: + + +```python Python +client.add(messages, agent_id="support-bot") +``` + +```javascript JavaScript +client.add(messages, { agent_id: "support-bot" }); +``` + + +## 6. Advanced Features + +### Async Processing +Process memories in the background for faster responses: + + +```python Python client.add(messages, user_id="alex", async_mode=True) ``` ```javascript JavaScript -const messages = [ - {"role": "user", "content": "I love hiking and outdoor activities"}, - {"role": "assistant", "content": "That's great! I'll remember your interest in hiking and outdoor activities for future recommendations."} -]; - -client.add(messages, { user_id: "alex", async_mode: true }) - .then(response => console.log(response)) - .catch(error => console.error(error)); -``` - -```bash cURL -curl -X POST "https://api.mem0.ai/v1/memories/" \ - -H "Authorization: Token your-api-key" \ - -H "Content-Type: application/json" \ - -d '{ - "messages": [ - {"role": "user", "content": "I love hiking and outdoor activities"}, - {"role": "assistant", "content": "That's great! I'll remember your interest in hiking and outdoor activities for future recommendations."} - ], - "user_id": "alex", - "async_mode": true - }' -``` - -```json Output -{ - "results": [ - { - "message": "Memory processing has been queued for background execution" - } - ] -} -``` - - - -#### Monitor Memories - -You can monitor memory operations on the platform dashboard: - -![Mem0 Platform Activity](/images/platform/activity.png) - -### 4.2 Search Memories - -#### General Memory Search - -Pass user messages, interactions, and queries into our search method to retrieve relevant memories. - - The `search` method supports two output formats: `v1.0` (default) and `v1.1`. To use the latest format, which provides more detailed information about each memory operation, set the `output_format` parameter to `v1.1`: - - - -```python Python -query = "What should I cook for dinner today?" - -client.search(query, user_id="alex") -``` - -```javascript JavaScript -const query = "What should I cook for dinner today?"; -client.search(query, { user_id: "alex", output_format: "v1.1" }) - .then(results => console.log(results)) - .catch(error => console.error(error)); -``` - -```bash cURL -curl -X POST "https://api.mem0.ai/v1/memories/search/" \ - -H "Authorization: Token your-api-key" \ - -H "Content-Type: application/json" \ - -d '{ - "query": "What should I cook for dinner today?", - "user_id": "alex", - "output_format": "v1.1" - }' -``` - -```json Output -{ - "results": [ - { - "id": "7f165f7e-b411-4afe-b7e5-35789b72c4a5", - "memory": "Vegetarian. Allergic to nuts.", - "user_id": "alex", - "metadata": {"food": "vegan"}, - "categories": ["food_preferences"], - "immutable": false, - "expiration_date": null, - "created_at": "2024-07-20T01:30:36.275141-07:00", - "updated_at": "2024-07-20T01:30:36.275172-07:00" - } - ] -} +client.add(messages, { user_id: "alex", async_mode: true }); ``` -Use category and metadata filters: - - - -```python Python -query = "What do you know about me?" - -client.search(query, categories=["food_preferences"], metadata={"food": "vegan"}) -``` - -```javascript JavaScript -const query = "What do you know about me?"; -client.search(query, categories=["food_preferences"], metadata={"food": "vegan"}) - .then(results => console.log(results)) - .catch(error => console.error(error)); -``` - -```bash cURL -curl -X POST "https://api.mem0.ai/v1/memories/search/?version=v2" \ - -H "Authorization: Token your-api-key" \ - -H "Content-Type: application/json" \ - -d '{ - "query": "What do you know about me?", - "categories": ["food_preferences"], - "metadata": {"food": "vegan"} - }' -``` - -```json Output -{ - "results": [ - { - "id": "7f165f7e-b411-4afe-b7e5-35789b72c4a5", - "memory": "Name: Alex. Vegetarian. Allergic to nuts.", - "user_id": "alex", - "metadata": {"food": "vegan"}, - "categories": ["food_preferences"], - "immutable": false, - "expiration_date": null, - "created_at": "2024-07-20T01:30:36.275141-07:00", - "updated_at": "2024-07-20T01:30:36.275172-07:00" - } - ] -} -``` - - - -#### Search using custom filters - -Our advanced search allows you to set custom search filters. You can filter by user_id, agent_id, app_id, run_id, created_at, updated_at, categories, and text. The filters support logical operators (AND, OR) and comparison operators (in, gte, lte, gt, lt, ne, contains, icontains, *). The wildcard character (*) matches everything for a specific field. For more details, see [V2 Search Memories](/api-reference/memory/v2-search-memories). - -Here you need to define `version` as `v2` in the search method. - -Example 1: Search using user_id and agent_id filters - - - -```python Python -query = "What do you know about me?" -filters = { - "OR":[ - { - "user_id":"alex" - }, - { - "agent_id":{ - "in":[ - "travel-assistant", - "customer-support" - ] - } - } - ] -} -client.search(query, version="v2", filters=filters) -``` - -```javascript JavaScript -const query = "What do you know about me?"; -const filters = { - "OR":[ - { - "user_id":"alex" - }, - { - "agent_id":{ - "in":[ - "travel-assistant", - "customer-support" - ] - } - } - ] -}; -client.search(query, { version: "v2", filters }) - .then(results => console.log(results)) - .catch(error => console.error(error)); -``` - -```bash cURL -curl -X POST "https://api.mem0.ai/v1/memories/search/?version=v2" \ - -H "Authorization : Token your - api - key" \ - -H "Content-Type : application / json" \ - -d '{ - "query": "What do you know about me?", - "filters": { - "OR": [ - { - "user_id": "alex" - }, - { - "agent_id": { - "in": ["travel-assistant", "customer-support"] - } - } - ] - } - }' -``` - -```json Output -{ - "results": [ - { - "id": "7f165f7e-b411-4afe-b7e5-35789b72c4a5", - "memory": "Name: Alex. Vegetarian. Allergic to nuts.", - "user_id": "alex", - "metadata": null, - "categories": ["food_preferences"], - "immutable": false, - "expiration_date": null, - "created_at": "2024-07-20T01:30:36.275141-07:00", - "updated_at": "2024-07-20T01:30:36.275172-07:00" - } - ] -} -``` - - -Example 2: Search using date filters - -```python Python -query = "What do you know about me?" -filters = { - "AND": [ - {"created_at": {"gte": "2024-07-20", "lte": "2024-07-10"}}, - {"user_id": "alex"} - ] -} -client.search(query, version="v2", filters=filters) -``` - -```javascript JavaScript -const query = "What do you know about me?"; -const filters = { - "AND": [ - {"created_at": {"gte": "2024-07-20", "lte": "2024-07-10"}}, - {"user_id": "alex"} - ] -}; - -client.search(query, { version: "v2", filters }) - .then(results => console.log(results)) - .catch(error => console.error(error)); -``` - -```bash cURL -curl -X POST "https://api.mem0.ai/v1/memories/search/?version=v2" \ - -H "Authorization: Token your-api-key" \ - -H "Content-Type: application/json" \ - -d '{ - "query": "What do you know about me?", - "filters": { - "AND": [ - { - "created_at": { - "gte": "2024-07-20", - "lte": "2024-07-10" - } - }, - { - "user_id": "alex" - } - ] - } - }' -``` - -```json Output -{ - "results": [ - { - "id": "7f165f7e-b411-4afe-b7e5-35789b72c4a5", - "memory": "Name: Alex. Vegetarian. Allergic to nuts.", - "user_id": "alex", - "metadata": null, - "categories": ["food_preferences"], - "immutable": false, - "expiration_date": null, - "created_at": "2024-07-20T01:30:36.275141-07:00", - "updated_at": "2024-07-20T01:30:36.275172-07:00" - } - ] -} -``` - - -Example 3: Search using metadata and categories Filters - -```python Python -query = "What do you know about me?" -filters = { - "AND": [ - {"metadata": {"food": "vegan"}}, - { - "categories":{ - "contains": "food_preferences" - } - } - ] -} -client.search(query, version="v2", filters=filters) -``` - -```javascript JavaScript -const query = "What do you know about me?"; -const filters = { - "AND": [ - {"metadata": {"food": "vegan"}}, - { - "categories": { - "contains": "food_preferences" - } - } - ] -}; - -client.search(query, { version: "v2", filters }) - .then(results => console.log(results)) - .catch(error => console.error(error)); -``` - -```bash cURL -curl -X POST "https://api.mem0.ai/v1/memories/search/?version=v2" \ - -H "Authorization: Token your-api-key" \ - -H "Content-Type: application/json" \ - -d '{ - "query": "What do you know about me?", - "filters": { - "AND": [ - { - "metadata": { - "food": "vegan" - } - }, - { - "categories": { - "contains": "food_preferences" - } - } - ] - } - }' -``` - -```json Output -{ - "results": [ - { - "id": "654fee-b411-4afe-b7e5-35789b72c4a5", - "memory": "Name: Alex. Vegetarian. Allergic to nuts.", - "user_id": "alex", - "metadata": {"food": "vegan"}, - "categories": ["food_preferences"], - "immutable": false, - "expiration_date": null, - "created_at": "2024-07-20T01:30:36.275141-07:00", - "updated_at": "2024-07-20T01:30:36.275172-07:00" - } - ] -} -``` - - - -Example 4: Search using NOT filters - -```python Python -query = "What do you know about me?" -filters = { - "NOT": [ - { - "categories": { - "contains": "food_preferences" - } - } - ] -} -client.search(query, version="v2", filters=filters) -``` - -```javascript JavaScript -const query = "What do you know about me?"; -const filters = { - "NOT": [ - { - "categories": { - "contains": "food_preferences" - } - } - ] -}; - -client.search(query, { version: "v2", filters }) - .then(results => console.log(results)) - .catch(error => console.error(error)); -``` - -```bash cURL -curl -X POST "https://api.mem0.ai/v1/memories/search/?version=v2" \ - -H "Authorization: Token your-api-key" \ - -H "Content-Type: application/json" \ - -d '{ - "query": "What do you know about me?", - "filters": { - "NOT": [ - { - "categories": { - "contains": "food_preferences" - } - } - ] - } - }' -``` - -```json Output -{ - "results": [ - { - "id": "123abc-d456-7890-efgh-ijklmnopqrst", - "memory": "Lives in San Francisco", - "user_id": "alex", - "metadata": null, - "categories": ["location"], - "immutable": false, - "expiration_date": null, - "created_at": "2024-07-20T01:30:36.275141-07:00", - "updated_at": "2024-07-20T01:30:36.275172-07:00" - } - ] -} -``` - - - -Example 5: Search using wildcard filters - -```python Python -query = "What do you know about me?" -filters = { - "AND": [ - { - "user_id": "alex" - }, - { - "run_id": "*" # Matches all run_ids - } - ] -} -client.search(query, version="v2", filters=filters) -``` - -```javascript JavaScript -const query = "What do you know about me?"; -const filters = { - "AND": [ - { - "user_id": "alex" - }, - { - "run_id": "*" // Matches all run_ids - } - ] -}; - -client.search(query, { version: "v2", filters }) - .then(results => console.log(results)) - .catch(error => console.error(error)); -``` - -```bash cURL -curl -X POST "https://api.mem0.ai/v1/memories/search/?version=v2" \ - -H "Authorization: Token your-api-key" \ - -H "Content-Type: application/json" \ - -d '{ - "query": "What do you know about me?", - "filters": { - "AND": [ - { - "user_id": "alex" - }, - { - "run_id": "*" - } - ] - } - }' -``` - -```json Output -{ - "results": [ - { - "id": "7f165f7e-b411-4afe-b7e5-35789b72c4a5", - "memory": "Name: Alex. Vegetarian. Allergic to nuts.", - "user_id": "alex", - "run_id": "session-1", - "metadata": null, - "categories": ["food_preferences"], - "immutable": false, - "expiration_date": null, - "created_at": "2024-07-20T01:30:36.275141-07:00", - "updated_at": "2024-07-20T01:30:36.275172-07:00" - } - ] -} -``` - - - - -### 4.3 Get All Users - -Get all users, agents, and runs which have memories associated with them. - - - -```python Python -client.users() -``` - -```javascript JavaScript -client.users() - .then(users => console.log(users)) - .catch(error => console.error(error)); -``` - -```bash cURL -curl -X GET "https://api.mem0.ai/v1/entities/" \ - -H "Authorization: Token your-api-key" -``` - - -```json Output -[ - { - "id": "1", - "name": "user123", - "created_2024-07-17T16:47:23.899900-07:00", - "updated_at": "2024-07-17T16:47:23.899918-07:00", - "total_memories": 5, - "owner": "alex", - "metadata": {"foo": "bar"}, - "type": "user" - }, - { - "id": "2", - "name": "travel-agent", - "created_at": "2024-07-01T17:59:08.187250-07:00", - "updated_at": "2024-07-01T17:59:08.187266-07:00", - "total_memories": 10, - "owner": "alex", - "metadata": {"agent_id": "123"}, - "type": "agent" - } -] -``` - - - - -### 4.4 Get All Memories - -Fetch all memories for a user, agent, or run using the getAll() method. - - The `get_all` method supports two output formats: `v1.0` (default) and `v1.1`. To use the latest format, which provides more detailed information about each memory operation, set the `output_format` parameter to `v1.1`: - We're soon deprecating the default output format for get_all() method, which returned a list. Once the changes are live, paginated response will be the only supported format, with 100 memories per page by default. You can customize this using the `page` and `page_size` parameters. - -The following examples showcase the paginated output format. - -#### Get all memories of a user - - - -```python Python -memories = client.get_all(user_id="alex", page=1, page_size=50) -``` - -```javascript JavaScript -client.getAll({ user_id: "alex", page: 1, page_size: 50 }) - .then(memories => console.log(memories)) - .catch(error => console.error(error)); -``` - -```bash cURL -curl -X GET "https://api.mem0.ai/v1/memories/?user_id=alex&page=1&page_size=50" \ - -H "Authorization: Token your-api-key" -``` - -```json Output (v1.1) -{ - "count": 204, - "next": "https://api.mem0.ai/v1/memories/?user_id=alex&output_format=v1.1&page=2&page_size=50", - "previous": null, - "results": - [ - { - "id":"f38b689d-6b24-45b7-bced-17fbb4d8bac7", - "memory":"是素食主义者,对坚果过敏。", - "agent_id":"travel-assistant", - "hash":"62bc074f56d1f909f1b4c2b639f56f6a", - "metadata":None, - "immutable": false, - "expiration_date": null, - "created_at":"2024-07-25T23:57:00.108347-07:00", - "updated_at":"2024-07-25T23:57:00.108367-07:00", - "categories":None - }, - { - "id":"0a14d8f0-e364-4f5c-b305-10da1f0d0878", - "memory":"Will maintain personalized travel preferences for each user. Provide customized recommendations based on dietary restrictions, interests, and past interactions.", - "agent_id":"travel-assistant", - "hash":"35a305373d639b0bffc6c2a3e2eb4244", - "metadata":"None", - "immutable": false, - "expiration_date": null, - "created_at":"2024-07-26T00:31:03.543759-07:00", - "updated_at":"2024-07-26T00:31:03.543778-07:00", - "categories":None - } - ... (remaining 48 memories) - ] -} -``` - - - - -#### Get all memories of an AI Agent +### Search with Filters +Filter results by categories and metadata: ```python Python -agent_memories = client.get_all(agent_id="ai-tutor", page=1, page_size=50) -``` - -```javascript JavaScript -client.getAll({ agent_id: "ai-tutor", page: 1, page_size: 50 }) - .then(memories => console.log(memories)) - .catch(error => console.error(error)); -``` - -```bash cURL -curl -X GET "https://api.mem0.ai/v1/memories/?agent_id=ai-tutor&page=1&page_size=50" \ - -H "Authorization: Token your-api-key" -``` - -```json Output (v1.1) -{ - "count": 78, - "next": "https://api.mem0.ai/v1/memories/?agent_id=ai-tutor&output_format=v1.1&page=2&page_size=50", - "previous": null, - "results": - [ - { - "id": "f38b689d-6b24-45b7-bced-17fbb4d8bac7", - "memory": "是素食主义者,对坚果过敏。", - "agent_id": "ai-tutor", - "hash": "62bc074f56d1f909f1b4c2b639f56f6a", - "metadata":None, - "immutable": false, - "expiration_date": null, - "created_at": "2024-07-25T23:57:00.108347-07:00", - "updated_at": "2024-07-25T23:57:00.108367-07:00" - }, - { - "id": "0a14d8f0-e364-4f5c-b305-10da1f0d0878", - "memory": "My name is Alice.", - "agent_id": "ai-tutor", - "hash": "35a305373d639b0bffc6c2a3e2eb4244", - "metadata":None, - "immutable": false, - "expiration_date": null, - "created_at": "2024-07-26T00:31:03.543759-07:00", - "updated_at": "2024-07-26T00:31:03.543778-07:00" - } - ... (remaining 48 memories) - ] -} -``` - - -#### Get the short-term memories for a session - - - -```python Python -short_term_memories = client.get_all(user_id="alex", run_id="trip-planning-2024", page=1, page_size=50) -``` - -```javascript JavaScript -client.getAll({ user_id: "alex", run_id: "trip-planning-2024", page: 1, page_size: 50 }) - .then(memories => console.log(memories)) - .catch(error => console.error(error)); -``` - -```bash cURL -curl -X GET "https://api.mem0.ai/v1/memories/?user_id=alex&run_id=trip-planning-2024&page=1&page_size=50" \ - -H "Authorization: Token your-api-key" -``` - -```json Output -{ - "count": 18, - "next": null, - "previous": null, - "results": - [ - { - "id": "06d8df63-7bd2-4fad-9acb-60871bcecee0", - "memory": "Planning a trip to Japan next month. Interested in vegetarian restaurants in Tokyo.", - "user_id": "alex", - "hash": "d2088c936e259f2f5d2d75543d31401c", - "metadata":None, - "immutable": false, - "expiration_date": null, - "created_at": "2024-07-26T00:25:16.566471-07:00", - "updated_at": "2024-07-26T00:25:16.566492-07:00", - "categories": ["food_preferences"] - }, - { - "id": "b4229775-d860-4ccb-983f-0f628ca112f5", - "memory": "Planning a trip to Japan next month. Interested in vegetarian restaurants in Tokyo.", - "user_id": "alex", - "hash": "d2088c936e259f2f5d2d75543d31401c", - "metadata":None, - "immutable": false, - "expiration_date": null, - "created_at": "2024-07-26T00:33:20.350542-07:00", - "updated_at": "2024-07-26T00:33:20.350560-07:00", - "categories": ["food_preferences"] - }, - { - "id": "df1aca24-76cf-4b92-9f58-d03857efcb64", - "memory": "Planning a trip to Japan next month. Interested in vegetarian restaurants in Tokyo.", - "user_id": "alex", - "hash": "d2088c936e259f2f5d2d75543d31401c", - "metadata":None, - "immutable": false, - "expiration_date": null, - "created_at": "2024-07-26T00:51:09.642275-07:00", - "updated_at": "2024-07-26T00:51:09.642295-07:00", - "categories": None - } - ... (remaining 15 memories) - ] -} -``` - - - -#### Get specific memory - - - -```python Python -memory = client.get(memory_id="582bbe6d-506b-48c6-a4c6-5df3b1e63428") -``` - -```javascript JavaScript -client.get("582bbe6d-506b-48c6-a4c6-5df3b1e63428") - .then(memory => console.log(memory)) - .catch(error => console.error(error)); -``` - -```bash cURL -curl -X GET "https://api.mem0.ai/v1/memories/582bbe6d-506b-48c6-a4c6-5df3b1e63428" \ - -H "Authorization: Token your-api-key" -``` - -```json Output -{ - "id":"06d8df63-7bd2-4fad-9acb-60871bcecee0", - "memory":"Planning a trip to Japan next month. Interested in vegetarian restaurants in Tokyo.", - "user_id":"alex", - "hash":"d2088c936e259f2f5d2d75543d31401c", - "metadata":"None", - "immutable": false, - "expiration_date": null, - "created_at":"2024-07-26T00:25:16.566471-07:00", - "updated_at":"2024-07-26T00:25:16.566492-07:00", - "categories": ["travel"] -} -``` - - -#### Get all memories by categories - -You can filter memories by their categories when using get_all: - - - -```python Python -# Get memories with specific categories -memories = client.get_all(user_id="alex", categories=["likes"]) - -# Get memories with multiple categories -memories = client.get_all(user_id="alex", categories=["likes", "food_preferences"]) - -# Custom pagination with categories -memories = client.get_all(user_id="alex", categories=["likes"], page=1, page_size=50) - -# Get memories with specific keywords -memories = client.get_all(user_id="alex", keywords="to play", page=1, page_size=50) -``` - -```javascript JavaScript -// Get memories with specific categories -client.getAll({ user_id: "alex", categories: ["likes"] }) - .then(memories => console.log(memories)) - .catch(error => console.error(error)); - -// Get memories with multiple categories -client.getAll({ user_id: "alex", categories: ["likes", "food_preferences"] }) - .then(memories => console.log(memories)) - .catch(error => console.error(error)); - -// Custom pagination with categories -client.getAll({ user_id: "alex", categories: ["likes"], page: 1, page_size: 50 }) - .then(memories => console.log(memories)) - .catch(error => console.error(error)); - -// Get memories with specific keywords -client.getAll({ user_id: "alex", keywords: "to play", page: 1, page_size: 50 }) - .then(memories => console.log(memories)) - .catch(error => console.error(error)); -``` - -```bash cURL -# Get memories with specific categories -curl -X GET "https://api.mem0.ai/v1/memories/?user_id=alex&categories=likes" \ - -H "Authorization: Token your-api-key" - -# Get memories with multiple categories -curl -X GET "https://api.mem0.ai/v1/memories/?user_id=alex&categories=likes,food_preferences" \ - -H "Authorization: Token your-api-key" - -# Custom pagination with categories -curl -X GET "https://api.mem0.ai/v1/memories/?user_id=alex&categories=likes&page=1&page_size=50" \ - -H "Authorization: Token your-api-key" - -# Get memories with specific keywords -curl -X GET "https://api.mem0.ai/v1/memories/?user_id=alex&keywords=to play&page=1&page_size=50" \ - -H "Authorization: Token your-api-key" -``` - -```json Output(Paginated) -{ - "count": 2, - "next": null, - "previous": null, - "results": [ - { - "id": "06d8df63-7bd2-4fad-9acb-60871bcecee0", - "memory": "Likes pizza and pasta", - "user_id": "alex", - "hash": "d2088c936e259f2f5d2d75543d31401c", - "metadata": null, - "immutable": false, - "expiration_date": null, - "created_at": "2024-07-26T00:25:16.566471-07:00", - "updated_at": "2024-07-26T00:25:16.566492-07:00", - "categories": ["likes", "food_preferences"] - }, - { - "id": "b4229775-d860-4ccb-983f-0f628ca112f5", - "memory": "Likes to travel to beach destinations", - "user_id": "alex", - "hash": "d2088c936e259f2f5d2d75543d31401c", - "metadata": null, - "immutable": false, - "expiration_date": null, - "created_at": "2024-07-26T00:33:20.350542-07:00", - "updated_at": "2024-07-26T00:33:20.350560-07:00", - "categories": ["likes"] - } - ] -} -``` - - - -#### Get all memories using custom filters - -Our advanced retrieval allows you to set custom filters when fetching memories. You can filter by user_id, agent_id, app_id, run_id, created_at, updated_at, categories, and keywords. The filters support logical operators (AND, OR) and comparison operators (in, gte, lte, gt, lt, ne, contains, icontains, *). The wildcard character (*) matches everything for a specific field. For more details, see [v2 Get Memories](/api-reference/memory/v2-get-memories). - -Here you need to define `version` as `v2` in the get_all method. - -Example 1. Get all memories using user_id and date filters - - - -```python Python -filters = { - "AND":[ - { - "user_id":"alex" - }, - { - "created_at":{ - "gte":"2024-07-01", - "lte":"2024-07-31" - } - }, - { - "categories":{ - "contains": "food_preferences" - } - } - ] -} - -# Default (No Pagination) -client.get_all(version="v2", filters=filters) - -# Pagination (You can also use the page and page_size parameters) -client.get_all(version="v2", filters=filters, page=1, page_size=50) -``` - -```javascript JavaScript -const filters = { - "AND":[ - { - "user_id":"alex" - }, - { - "created_at":{ - "gte":"2024-07-01", - "lte":"2024-07-31" - } - }, - { - "categories":{ - "contains": "food_preferences" - } - } - ] -}; - -// Default (No Pagination) -client.getAll({ version: "v2", filters }) - .then(memories => console.log(memories)) - .catch(error => console.error(error)); - -// Pagination (You can also use the page and page_size parameters) -client.getAll({ version: "v2", filters, page: 1, page_size: 50 }) - .then(memories => console.log(memories)) - .catch(error => console.error(error)); -``` - -```bash cURL -# Default (No Pagination) -curl -X GET "https://api.mem0.ai/v1/memories/?version=v2" \ - -H "Authorization: Token your-api-key" \ - -H "Content-Type: application/json" \ - -d '{ - "filters": { - "AND": [ - {"user_id":"alex"}, - {"created_at":{ - "gte":"2024-07-01", - "lte":"2024-07-31" - }}, - {"categories":{ - "contains": "food_preferences" - }} - ] - } - }' - -# Pagination (You can also use the page and page_size parameters) -curl -X GET "https://api.mem0.ai/v1/memories/?version=v2&page=1&page_size=50" \ - -H "Authorization: Token your-api-key" \ - -H "Content-Type: application/json" \ - -d '{ - "filters": { - "AND": [ - {"user_id":"alex"}, - {"created_at":{ - "gte":"2024-07-01", - "lte":"2024-07-31" - }}, - {"categories":{ - "contains": "food_preferences" - }} - ] - } - }' -``` - -```json Output (Default) -[ - { - "id":"f38b689d-6b24-45b7-bced-17fbb4d8bac7", - "memory":"Name: Alex. Vegetarian. Allergic to nuts.", - "user_id":"alex", - "hash":"62bc074f56d1f909f1b4c2b639f56f6a", - "metadata":null, - "immutable": false, - "expiration_date": null, - "created_at":"2024-07-25T23:57:00.108347-07:00", - "updated_at":"2024-07-25T23:57:00.108367-07:00", - "categories": ["food_preferences"] - } -] -``` - -```json Output (Paginated) -{ - "count": 1, - "next": null, - "previous": null, - "results": [ - { - "id":"f38b689d-6b24-45b7-bced-17fbb4d8bac7", - "memory":"Name: Alex. Vegetarian. Allergic to nuts.", - "user_id":"alex", - "hash":"62bc074f56d1f909f1b4c2b639f56f6a", - "metadata":None, - "immutable": false, - "expiration_date": null, - "created_at":"2024-07-25T23:57:00.108347-07:00", - "updated_at":"2024-07-25T23:57:00.108367-07:00", - "categories": ["food_preferences"] - } - ] -} -``` - - - -Example 2: Search using metadata and categories Filters - -```python Python -filters = { - "AND": [ - {"metadata": {"food": "vegan"}}, - { - "categories":{ - "contains": "food_preferences" - } - } - ] -} -# Default (No Pagination) -client.get_all(version="v2", filters=filters) - -# Pagination (You can also use the page and page_size parameters) -client.get_all(version="v2", filters=filters, page=1, page_size=50) -``` - -```javascript JavaScript -const filters = { - "AND": [ - {"metadata": {"food": "vegan"}}, - { - "categories": { - "contains": "food_preferences" - } - } - ] -}; - -// Default (No Pagination) -client.getAll({ version: "v2", filters }) - .then(memories => console.log(memories)) - .catch(error => console.error(error)); - -// Pagination (You can also use the page and page_size parameters) -client.getAll({ version: "v2", filters, page: 1, page_size: 50 }) - .then(memories => console.log(memories)) - .catch(error => console.error(error)); -``` - -```bash cURL -# Default (No Pagination) -curl -X GET "https://api.mem0.ai/v1/memories/?version=v2" \ - -H "Authorization: Token your-api-key" \ - -H "Content-Type: application/json" \ - -d '{ - "filters": { - "AND": [ - {"metadata": {"food": "vegan"}}, - { - "categories": { - "contains": "food_preferences" - } - }} - ] - } - }' - -# Pagination (You can also use the page and page_size parameters) -curl -X GET "https://api.mem0.ai/v1/memories/?version=v2&page=1&page_size=50" \ - -H "Authorization: Token your-api-key" \ - -H "Content-Type: application/json" \ - -d '{ - "filters": { - "AND": [ - {"metadata": {"food": "vegan"}}, - { - "categories": { - "contains": "food_preferences" - } - }} - ] - } - }' -``` - -```json Output -[ - { - "id": "654fee-b411-4afe-b7e5-35789b72c4a5", - "memory": "Name: Alex. Vegetarian. Allergic to nuts.", - "user_id": "alex", - "metadata": {"food": "vegan"}, - "categories": ["food_preferences"], - "immutable": false, - "expiration_date": null, - "created_at": "2024-07-20T01:30:36.275141-07:00", - "updated_at": "2024-07-20T01:30:36.275172-07:00" - } -] -``` - - - -Example 3: Get all memories using NOT filters - -```python Python -filters = { - "NOT": [ - { - "categories": { - "contains": "food_preferences" - } - } - ] -} - -# Default (No Pagination) -client.get_all(version="v2", filters=filters) - -# Pagination (You can also use the page and page_size parameters) -client.get_all(version="v2", filters=filters, page=1, page_size=50) -``` - -```javascript JavaScript -const filters = { - "NOT": [ - { - "categories": { - "contains": "food_preferences" - } - } - ] -}; - -// Default (No Pagination) -client.getAll({ version: "v2", filters }) - .then(memories => console.log(memories)) - .catch(error => console.error(error)); - -// Pagination (You can also use the page and page_size parameters) -client.getAll({ version: "v2", filters, page: 1, page_size: 50 }) - .then(memories => console.log(memories)) - .catch(error => console.error(error)); -``` - -```bash cURL -# Default (No Pagination) -curl -X GET "https://api.mem0.ai/v1/memories/?version=v2" \ - -H "Authorization: Token your-api-key" \ - -H "Content-Type: application/json" \ - -d '{ - "filters": { - "NOT": [ - { - "categories": { - "contains": "food_preferences" - } - } - ] - } - }' - -# Pagination (You can also use the page and page_size parameters) -curl -X GET "https://api.mem0.ai/v1/memories/?version=v2&page=1&page_size=50" \ - -H "Authorization: Token your-api-key" \ - -H "Content-Type: application/json" \ - -d '{ - "filters": { - "NOT": [ - { - "categories": { - "contains": "food_preferences" - } - } - ] - } - }' -``` - -```json Output -[ - { - "id": "789xyz-e012-3456-fghi-jklmnopqrstu", - "memory": "Works as a software engineer", - "user_id": "alex", - "metadata": {"job": "tech"}, - "categories": ["work"], - "immutable": false, - "expiration_date": null, - "created_at": "2024-07-20T01:30:36.275141-07:00", - "updated_at": "2024-07-20T01:30:36.275172-07:00" - } -] -``` - -```json Output (Paginated) -{ - "count": 1, - "next": null, - "previous": null, - "results": [ - { - "id": "789xyz-e012-3456-fghi-jklmnopqrstu", - "memory": "Works as a software engineer", - "user_id": "alex", - "metadata": {"job": "tech"}, - "categories": ["work"], - "immutable": false, - "expiration_date": null, - "created_at": "2024-07-20T01:30:36.275141-07:00", - "updated_at": "2024-07-20T01:30:36.275172-07:00" - } - ] -} -``` - - - -Example 4: Get all memories using wildcard filters - -```python Python -filters = { - "AND": [ - { - "user_id": "alex" - }, - { - "run_id": "*" # Matches all run_ids - } - ] -} - -# Default (No Pagination) -client.get_all(version="v2", filters=filters) - -# Pagination (You can also use the page and page_size parameters) -client.get_all(version="v2", filters=filters, page=1, page_size=50) -``` - -```javascript JavaScript -const filters = { - "AND": [ - { - "user_id": "alex" - }, - { - "run_id": "*" // Matches all run_ids - } - ] -}; - -// Default (No Pagination) -client.getAll({ version: "v2", filters }) - .then(memories => console.log(memories)) - .catch(error => console.error(error)); - -// Pagination (You can also use the page and page_size parameters) -client.getAll({ version: "v2", filters, page: 1, page_size: 50 }) - .then(memories => console.log(memories)) - .catch(error => console.error(error)); -``` - -```bash cURL -# Default (No Pagination) -curl -X GET "https://api.mem0.ai/v1/memories/?version=v2" \ - -H "Authorization: Token your-api-key" \ - -H "Content-Type: application/json" \ - -d '{ - "filters": { - "AND": [ - {"user_id":"alex"}, - {"run_id": "*"} - ] - } - }' - -# Pagination (You can also use the page and page_size parameters) -curl -X GET "https://api.mem0.ai/v1/memories/?version=v2&page=1&page_size=50" \ - -H "Authorization: Token your-api-key" \ - -H "Content-Type: application/json" \ - -d '{ - "filters": { - "AND": [ - {"user_id":"alex"}, - {"run_id": "*"} - ] - } - }' -``` - -```json Output (Default) -[ - { - "id": "f38b689d-6b24-45b7-bced-17fbb4d8bac7", - "memory": "Name: Alex. Vegetarian. Allergic to nuts.", - "user_id": "alex", - "run_id": "session-1", - "metadata": null, - "categories": ["food_preferences"], - "immutable": false, - "expiration_date": null, - "created_at": "2024-07-20T01:30:36.275141-07:00", - "updated_at": "2024-07-20T01:30:36.275172-07:00" - } -] -``` - -```json Output (Paginated) -{ - "count": 1, - "next": null, - "previous": null, - "results": [ - { - "id": "f38b689d-6b24-45b7-bced-17fbb4d8bac7", - "memory": "Name: Alex. Vegetarian. Allergic to nuts.", - "user_id": "alex", - "run_id": "session-1", - "metadata": null, - "categories": ["food_preferences"], - "immutable": false, - "expiration_date": null, - "created_at": "2024-07-20T01:30:36.275141-07:00", - "updated_at": "2024-07-20T01:30:36.275172-07:00" - } - ] -} -``` - - - - -### 4.5 Memory History - -Get history of how a memory has changed over time. - - - -```python Python -# Add some message to create history -messages = [{"role": "user", "content": "I recently tried chicken and I loved it. I'm thinking of trying more non-vegetarian dishes.."}] -client.add(messages, user_id="alex") - -# Add second message to update history -messages.append({'role': 'user', 'content': 'I turned vegetarian now.'}) -client.add(messages, user_id="alex") - -# Get history of how memory changed over time -memory_id = "" -history = client.history(memory_id) -``` - -```javascript JavaScript -// Add some message to create history -let messages = [{ role: "user", content: "I recently tried chicken and I loved it. I'm thinking of trying more non-vegetarian dishes.." }]; -client.add(messages, { user_id: "alex" }) - .then(result => { - // Add second message to update history - messages.push({ role: 'user', content: 'I turned vegetarian now.' }); - return client.add(messages, { user_id: "alex" }); - }) - .then(result => { - // Get history of how memory changed over time - const memoryId = result.id; // Assuming the API returns the memory ID - return client.history(memoryId); - }) - .then(history => console.log(history)) - .catch(error => console.error(error)); -``` - -```bash cURL -# First, add the initial memory -curl -X POST "https://api.mem0.ai/v1/memories/" \ - -H "Authorization: Token your-api-key" \ - -H "Content-Type: application/json" \ - -d '{ - "messages": [{"role": "user", "content": "I recently tried chicken and I loved it. I'm thinking of trying more non-vegetarian dishes.."}], - "user_id": "alex" - }' - -# Then, update the memory -curl -X POST "https://api.mem0.ai/v1/memories/" \ - -H "Authorization: Token your-api-key" \ - -H "Content-Type: application/json" \ - -d '{ - "messages": [ - {"role": "user", "content": "I recently tried chicken and I loved it. I'm thinking of trying more non-vegetarian dishes.."}, - {"role": "user", "content": "I turned vegetarian now."} - ], - "user_id": "alex" - }' - -# Finally, get the history (replace with the actual memory ID) -curl -X GET "https://api.mem0.ai/v1/memories//history/" \ - -H "Authorization: Token your-api-key" -``` - -```json Output -[ - { - "id":"d6306e85-eaa6-400c-8c2f-ab994a8c4d09", - "memory_id":"b163df0e-ebc8-4098-95df-3f70a733e198", - "input":[ - { - "role":"user", - "content":"I recently tried chicken and I loved it. I'm thinking of trying more non-vegetarian dishes.." - }, - { - "role":"user", - "content":"I turned vegetarian now." - } - ], - "old_memory":"None", - "new_memory":"Turned vegetarian.", - "user_id":"alex", - "event":"ADD", - "metadata":"None", - "created_at":"2024-07-26T01:02:41.737310-07:00", - "updated_at":"2024-07-26T01:02:41.726073-07:00" - } -] -``` - - -### 4.6 Update Memory - -Update a memory with new data. You can update the memory's text, metadata, or both. - - - -```python Python -client.update( - memory_id="", - text="I am now a vegetarian.", - metadata={"diet": "vegetarian"} +results = client.search( + "food preferences", + user_id="alex", + categories=["preferences"], + metadata={"category": "food"} ) ``` ```javascript JavaScript -client.update("memory-id-here", { text: "I am now a vegetarian.", metadata: { diet: "vegetarian" } }) - .then(result => console.log(result)) - .catch(error => console.error(error)); -``` - -```bash cURL -curl -X PUT "https://api.mem0.ai/v1/memories/" \ - -H "Authorization: Token your-api-key" \ - -H "Content-Type: application/json" \ - -d '{ - "message": "I recently tried chicken and I loved it. I'm thinking of trying more non-vegetarian dishes.." - }' -``` - -```json Output -{ - "id":"c190ab1a-a2f1-4f6f-914a-495e9a16b76e", - "memory":"I recently tried chicken and I loved it. I'm thinking of trying more non-vegetarian dishes..", - "agent_id":"travel-assistant", - "hash":"af1161983e03667063d1abb60e6d5c06", - "metadata":"None", - "created_at":"2024-07-30T22:46:40.455758-07:00", - "updated_at":"2024-07-30T22:48:35.257828-07:00" -} -``` - - - -### 4.7 Delete Memory - -Delete specific memory. - - - -```python Python -client.delete(memory_id) -``` - -```javascript JavaScript -client.delete("memory-id-here") - .then(result => console.log(result)) - .catch(error => console.error(error)); -``` - -```bash cURL -curl -X DELETE "https://api.mem0.ai/v1/memories/memory-id-here" \ - -H "Authorization: Token your-api-key" -``` - -```json Output -{'message': 'Memory deleted successfully'} +client.search("food preferences", { + user_id: "alex", + categories: ["preferences"], + metadata: { category: "food" } +}); ``` -Delete all memories of a user. - - - -```python Python -client.delete_all(user_id="alex") -``` - -```javascript JavaScript -client.deleteAll({ user_id: "alex" }) - .then(result => console.log(result)) - .catch(error => console.error(error)); -``` - -```bash cURL -curl -X DELETE "https://api.mem0.ai/v1/memories/?user_id=alex" \ - -H "Authorization: Token your-api-key" -``` - -```json Output -{'message': 'Memories deleted successfully!'} -``` - - - -Delete all users. - - - -```python Python -client.delete_users() -``` - -```javascript JavaScript -client.delete_users() - .then(users => console.log(users)) - .catch(error => console.error(error)); -``` - -```json Output -{'message': 'All users, agents, and runs deleted.'} -``` - - -Delete specific user or agent or app or run. - - -```python Python -# Delete specific user -client.delete_users(user_id="alex") - -# Delete specific agent -# client.delete_users(agent_id="travel-assistant") -``` - -```javascript JavaScript -client.delete_users({ user_id: "alex" }) - .then(result => console.log(result)) - .catch(error => console.error(error)); -``` - -```bash cURL -curl -X DELETE "https://api.mem0.ai/v2/entities/user/alex" \ - -H "Authorization: Token your-api-key" -``` - -```json Output -{'message': 'Entity deleted successfully.'} -``` - - - -### 4.8 Reset Client - - - -```python Python -client.reset() -``` - -```json Output -{'message': 'Client reset successful. All users and memories deleted.'} -``` - - - - -Fun fact: You can also delete the memory using the `add()` method by passing a natural language command: - - - -```python Python -messages = [ - {"role": "user", "content": "Delete all of my food preferences"} -] -client.add(messages, user_id="alex") -``` - -```javascript JavaScript -const messages = [ - {"role": "user", "content": "Delete all of my food preferences"} -] -client.add(messages, { user_id: "alex" }) - .then(result => console.log(result)) - .catch(error => console.error(error)); -``` - -```bash cURL -curl -X POST "https://api.mem0.ai/v1/memories/" \ - -H "Authorization: Token your-api-key" \ - -H "Content-Type: application/json" \ - -d '{ - "messages": [{"role": "user", "content": "Delete all of my food preferences"}], - "user_id": "alex" - }' -``` - -```json Output -[{'id': '3f4eccba-3b09-497a-81ab-cca1ababb36b', - 'memory': 'Is allergic to nuts', - 'event': 'DELETE'}, - {'id': 'f5dcfbf4-5f0b-422a-8ad4-cadb9e941e25', - 'memory': 'Is a vegetarian', - 'event': 'DELETE'}, - {'id': 'dd32f70c-fa69-4fc7-997b-fb4a66d1a0fa', - 'memory': 'Name is Alex', - 'event': 'DELETE'}]{'message': 'ok'} - {'id': '3f4eccba-3b09-497a-81ab-cca1ababb36b', - 'memory': 'Likes Chicken', - 'event': 'DELETE'} -``` - - - -### 4.9 Batch Update Memories -Update multiple memories in a single API call. You can update up to 1000 memories at once. - -```python Python -update_memories = [ - { - "memory_id": "285ed74b-6e05-4043-b16b-3abd5b533496", - "text": "Watches football" - }, - { - "memory_id": "2c9bd859-d1b7-4d33-a6b8-94e0147c4f07", - "text": "Loves to travel" - } -] - -response = client.batch_update(update_memories) -print(response) -``` -```javascript JavaScript -const updateMemories = [{"memory_id": "285ed74b-6e05-4043-b16b-3abd5b533496", - text: "Watches football" - }, - {"memory_id": "2c9bd859-d1b7-4d33-a6b8-94e0147c4f07", - text: "Loves to travel" - } -]; - -client.batchUpdate(updateMemories) - .then(response => console.log('Batch update response:', response)) - .catch(error => console.error(error)); -``` -```bash cURL -curl -X PUT "https://api.mem0.ai/v1/memories/batch/" \ - -H "Authorization: Token your-api-key" \ - -H "Content-Type: application/json" \ - -d '{ - "memories": [ - { - "memory_id": "285ed74b-6e05-4043-b16b-3abd5b533496", - "text": "Watches football" - }, - { - "memory_id": "2c9bd859-d1b7-4d33-a6b8-94e0147c4f07", - "text": "Loves to travel" - } - ] - }' -``` -```json Output -{ - "message": "Successfully updated 2 memories" -} -``` - -### 4.10 Batch Delete Memories -Delete multiple memories in a single API call. You can delete up to 1000 memories at once. - -```python Python -delete_memories = [ - {"memory_id": "285ed74b-6e05-4043-b16b-3abd5b533496"}, - {"memory_id": "2c9bd859-d1b7-4d33-a6b8-94e0147c4f07"} -] - -response = client.batch_delete(delete_memories) -print(response) -``` -```javascript JavaScript -const deleteMemories = [{"memory_id": "285ed74b-6e05-4043-b16b-3abd5b533496"}, - {"memory_id": "2c9bd859-d1b7-4d33-a6b8-94e0147c4f07"} -]; - -client.batchDelete(deleteMemories) - .then(response => console.log('Batch delete response:', response)) - .catch(error => console.error(error)); -``` -```bash cURL -curl -X DELETE "https://api.mem0.ai/v1/memories/batch/" \ - -H "Authorization: Token your-api-key" \ - -H "Content-Type: application/json" \ - -d '{ - "memory_ids": [ - {"memory_id": "285ed74b-6e05-4043-b16b-3abd5b533496"}, - {"memory_id": "2c9bd859-d1b7-4d33-a6b8-94e0147c4f07"} - ] - }' -``` -```json Output -{ - "message": "Successfully deleted 2 memories" -} -``` - - -### 4.11 Working with Mem0 in TypeScript -Manage memories using TypeScript with Mem0. Mem0 has completet TypeScript support Below is an example demonstrating how to add and search memories. +## TypeScript Example ```typescript TypeScript -import MemoryClient, { Message, SearchOptions, MemoryOptions } from 'mem0ai'; +import MemoryClient, { Message, MemoryOptions } from 'mem0ai'; -const apiKey = 'your-api-key-here'; -const client = new MemoryClient(apiKey); +const client = new MemoryClient('your-api-key'); -// Messages const messages: Message[] = [ - { role: "user", content: "Hi, I'm Alex. I'm a vegetarian and I'm allergic to nuts." }, - { role: "assistant", content: "Hello Alex! I've noted that you're a vegetarian and have a nut allergy. I'll keep this in mind for any food-related recommendations or discussions." } + { role: "user", content: "I love Italian food" }, + { role: "assistant", content: "Noted! I'll remember your preference for Italian cuisine." } ]; -// ADD -const memoryOptions: MemoryOptions = { +const options: MemoryOptions = { user_id: "alex", - agent_id: "travel-assistant" -} + metadata: { category: "food_preferences" } +}; -client.add(messages, memoryOptions) - .then(result => console.log(result)) - .catch(error => console.error(error)); - -// SEARCH -const query: string = "What do you know about me?"; -const searchOptions: SearchOptions = { - user_id: "alex", - filters: { - OR: [ - { agent_id: "travel-assistant" }, - { user_id: "alex" } - ] - }, - threshold: 0.1, - api_version: 'v2' -} - -client.search(query, searchOptions) -.then(results => console.log(results)) -.catch(error => console.error(error)); +client.add(messages, options) + .then(result => console.log(result)) + .catch(error => console.error(error)); ``` -If you have any questions, please feel free to reach out to us using one of the following methods: +## Next Steps + +Now that you're up and running, explore more advanced features: + +- **[Advanced Memory Operations](/core-concepts/memory-operations)** - Learn about filtering, updating, and managing memories +- **[Platform Features](/platform/features/platform-overview)** - Discover advanced platform capabilities +- **[API Reference](/api-reference)** - Complete API documentation \ No newline at end of file diff --git a/docs/quickstart.mdx b/docs/quickstart.mdx index a56b34344..c6282c57b 100644 --- a/docs/quickstart.mdx +++ b/docs/quickstart.mdx @@ -4,9 +4,6 @@ icon: "bolt" iconType: "solid" --- - - - Mem0 offers two powerful ways to leverage our technology: [our managed platform](#mem0-platform-managed-solution) and [our open source solution](#mem0-open-source). Check out our [Playground](https://mem0.dev/pd-pg) to see Mem0 in action. diff --git a/docs/snippets/snippet-intro.mdx b/docs/snippets/snippet-intro.mdx deleted file mode 100644 index e20fbb6fc..000000000 --- a/docs/snippets/snippet-intro.mdx +++ /dev/null @@ -1,4 +0,0 @@ -One of the core principles of software development is DRY (Don't Repeat -Yourself). This is a principle that applies to documentation as -well. If you find yourself repeating the same content in multiple places, you -should consider creating a custom snippet to keep your content in sync.