### Complete Example: Multiple File Types Source: https://docs.mem0.ai/platform/features/multimodal-support Demonstrates adding an image URL, a text document URL, and a PDF URL to Mem0. This example consolidates various file addition methods. ```python import base64 from mem0 import MemoryClient client = MemoryClient() def file_to_base64(file_path): with open(file_path, "rb") as file: return base64.b64encode(file.read()).decode('utf-8') # Example 1: Using an image URL image_message = { "role": "user", "content": { "type": "image_url", "image_url": { "url": "https://example.com/sample-image.jpg" } } } # Example 2: Using a text document URL text_message = { "role": "user", "content": { "type": "mdx_url", "mdx_url": { "url": "https://www.w3.org/TR/2003/REC-PNG-20031110/iso_8859-1.txt" } } } # Example 3: Using a PDF URL pdf_message = { "role": "user", "content": { "type": "pdf_url", "pdf_url": { "url": "https://www.w3.org/WAI/ER/tests/xhtml/testfiles/resources/pdf/dummy.pdf" } } } # Add each message to the memory system client.add([image_message], user_id="alice") client.add([text_message], user_id="alice") client.add([pdf_message], user_id="alice") ``` -------------------------------- ### Install mem0ai SDK with async extras (Python) Source: https://docs.mem0.ai/platform/advanced-memory-operations Install the Python SDK with support for asynchronous operations. This is a prerequisite for using async memory clients. ```bash pip install "mem0ai[async]" ``` -------------------------------- ### Install mem0ai SDK (TypeScript) Source: https://docs.mem0.ai/platform/advanced-memory-operations Install the Node.js SDK for mem0ai. This command installs the base package. ```bash npm install mem0ai ``` -------------------------------- ### Search Results Example Source: https://docs.mem0.ai/platform/quickstart Example JSON output for a memory search query. ```json { "results": [ { "id": "14e1b28a-2014-40ad-ac42-69c9ef42193d", "memory": "Allergic to nuts", "user_id": "user123", "categories": ["health"], "created_at": "2025-10-22T04:40:22.864647-07:00", "score": 0.30 } ] } ``` -------------------------------- ### Install and Sign Up AI Agent (npm) Source: https://docs.mem0.ai/platform/agent-signup Install the Mem0 CLI using npm and sign up as an AI agent. Replace 'claude-code' with your agent's name. This is the first step in enabling persistent memory for autonomous coding tools. ```bash # 1. Install npm install -g @mem0/cli # 2. Sign up as an agent (replace `claude-code` with your name) mem0 init --agent --agent-caller claude-code # 3. Push a memory mem0 add "I am using mem0" # 4. Verify mem0 search "am I using mem0" ``` -------------------------------- ### Install Mem0 SDK with pip Source: https://docs.mem0.ai/platform/quickstart Install the Mem0 SDK using pip for Python projects. ```bash pip install mem0ai ``` -------------------------------- ### Quick Start: Get a Specific Memory Source: https://docs.mem0.ai/platform/cli Retrieve a specific memory using its unique memory ID. ```bash # Get a specific memory mem0 get ``` -------------------------------- ### Install Mem0 CLI with npm Source: https://docs.mem0.ai/platform/cli Install the Mem0 CLI globally using npm. This command is used for Node.js environments. ```bash npm install -g @mem0/cli ``` -------------------------------- ### Quick Start: List All Memories Source: https://docs.mem0.ai/platform/cli List all memories associated with a specific user ID. ```bash # List all memories for a user mem0 list --user-id alice ``` -------------------------------- ### Install and Sign Up AI Agent (pip) Source: https://docs.mem0.ai/platform/agent-signup Install the Mem0 CLI using pip and sign up as an AI agent. Replace 'claude-code' with your agent's name. This workflow allows autonomous coding tools to quickly establish a persistent memory store. ```bash # 1. Install pip install mem0-cli # 2. Sign up as an agent (replace `claude-code` with your name) mem0 init --agent --agent-caller claude-code # 3. Push a memory mem0 add "I am using mem0" # 4. Verify mem0 search "am I using mem0" ``` -------------------------------- ### Example AI agent interactions with MCP tools Source: https://docs.mem0.ai/platform/features/mcp-integration These examples show how an AI agent can interact with memory tools like add_memory and search_memories. The agent automatically decides when to use these tools based on the conversation context. ```text User: Remember that I'm allergic to peanuts Agent: [calls add_memory] Got it! I've saved your peanut allergy. User: What dietary restrictions do I know about? Agent: [calls search_memories] You have a peanut allergy. ``` -------------------------------- ### Quick Start: Add a Memory Source: https://docs.mem0.ai/platform/cli Add a new memory with the specified text and associate it with a user ID. ```bash # Add a memory mem0 add "I prefer dark mode and use vim keybindings" --user-id alice ``` -------------------------------- ### Install Mem0 CLI with pip Source: https://docs.mem0.ai/platform/cli Install the Mem0 CLI using pip. This command is used for Python environments. ```bash pip install mem0-cli ``` -------------------------------- ### Print CLI Version Source: https://docs.mem0.ai/platform/cli Use `mem0 version` to display the installed version of the Mem0 CLI. ```bash mem0 version ``` -------------------------------- ### Basic Setup: Set and Retrieve Custom Instructions (Python) Source: https://docs.mem0.ai/platform/features/custom-instructions This snippet demonstrates how to set custom instructions for your project and then retrieve the currently active instructions. ```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["custom_instructions"]) ``` -------------------------------- ### Basic Setup: Set and Retrieve Custom Instructions (JavaScript) Source: https://docs.mem0.ai/platform/features/custom-instructions This snippet demonstrates how to set custom instructions for your project and then retrieve the currently active instructions. ```javascript // Set instructions for your project await client.project.update({ customInstructions: "Your guidelines here..." }); // Retrieve current instructions const response = await client.project.get({ fields: ["customInstructions"] }); console.log(response.customInstructions); ``` -------------------------------- ### Initialize Mem0 CLI (Interactive) Source: https://docs.mem0.ai/platform/cli Run the interactive setup wizard to configure your API key and default user ID. This command prompts for necessary information and validates the connection. ```bash mem0 init ``` -------------------------------- ### Quick Start: Update a Memory Source: https://docs.mem0.ai/platform/cli Update the content of an existing memory identified by its memory ID. ```bash # Update a memory mem0 update "I prefer light mode now" ``` -------------------------------- ### Basic Agent Commands Source: https://docs.mem0.ai/platform/cli Examples of using the `--agent` flag for common memory operations like search, add, list, and delete. ```bash mem0 --agent search "response preferences" --user-id user-42 ``` ```bash mem0 --agent add "User prefers concise responses" --user-id user-42 ``` ```bash mem0 --agent list --user-id user-42 ``` ```bash mem0 --agent delete --all --user-id user-42 --force ``` -------------------------------- ### Get Webhooks Source: https://docs.mem0.ai/platform/features/webhooks Retrieve all webhooks for your project. ```APIDOC ## GET /webhooks ### Description Retrieve all webhooks for a specific project. ### Method GET ### Endpoint /webhooks ### Parameters #### Query Parameters - **project_id** (string) - Required - The ID of the project to retrieve webhooks for. ### Response #### Success Response (200) - An array of webhook objects, each containing: - **webhook_id** (string) - The unique identifier for the webhook. - **url** (string) - The URL of the webhook. - **name** (string) - The name of the webhook. - **owner** (string) - The owner of the webhook. - **event_types** (array of strings) - The event types configured for the webhook. - **project** (string) - The project associated with the webhook. - **is_active** (boolean) - Indicates if the webhook is active. - **created_at** (string) - The timestamp when the webhook was created. - **updated_at** (string) - The timestamp when the webhook was last updated. #### Response Example ```json [ { "webhook_id": "wh_123", "url": "https://mem0.ai", "name": "mem0", "owner": "john", "event_types": ["memory_add"], "project": "default-project", "is_active": true, "created_at": "2025-02-18T22:59:56.804993-08:00", "updated_at": "2025-02-18T23:06:41.479361-08:00" } ] ``` ``` -------------------------------- ### Perform Search with JSON Output Source: https://docs.mem0.ai/platform/cli Example of performing a search and piping the JSON output to 'jq' for further processing. This is useful for programmatic consumption of search results. ```bash mem0 search "user preferences" --user-id alice --output json | jq '.data.results[].memory' ``` -------------------------------- ### Quick Start: Search Memories Source: https://docs.mem0.ai/platform/cli Search for memories related to a given query and scope the search to a specific user. ```bash # Search memories mem0 search "What are Alice's preferences?" --user-id alice ``` -------------------------------- ### Add Mem0 MCP to all supported clients Source: https://docs.mem0.ai/platform/features/mcp-integration Use this command to add Mem0 MCP to all supported clients. Ensure you have npx installed. ```bash npx mcp-add \ --name mem0-mcp \ --type http \ --url "https://mcp.mem0.ai/mcp" \ --clients "claude,claude code,cursor,windsurf,vscode,opencode" ``` -------------------------------- ### Get All Users in JavaScript Source: https://docs.mem0.ai/platform/features/async-client Retrieve a list of all users, agents, and runs associated with memories. ```javascript await client.users(); ``` -------------------------------- ### Quick Start: Delete a Memory Source: https://docs.mem0.ai/platform/cli Delete a memory using its unique memory ID. ```bash # Delete a memory mem0 delete ``` -------------------------------- ### Codex Sideloaded Plugin Setup Source: https://docs.mem0.ai/platform/mem0-mcp Clone the Mem0 repository and add its marketplace manifest to Codex to sideload the plugin. This provides the full experience including memory protocol skills. ```bash git clone https://github.com/mem0ai/mem0.git ~/codex-plugins/mem0-source codex plugin marketplace add ~/codex-plugins/mem0-source ``` -------------------------------- ### Get Webhooks in Python Source: https://docs.mem0.ai/platform/features/webhooks Retrieve all webhooks associated with a specific project ID. ```python # Get webhooks for a specific project webhooks = client.get_webhooks(project_id="proj_123") print(webhooks) ``` -------------------------------- ### Get All Users Source: https://docs.mem0.ai/platform/features/async-client Asynchronously retrieve a list of all users, agents, and runs that have memories associated with them. ```APIDOC ## Get All Users ### Description Asynchronously retrieve a list of all users, agents, and runs that have memories associated with them. ### Request Example ```python await client.users() ``` ```javascript await client.users(); ``` ``` -------------------------------- ### Configure a specific client with Mem0 MCP Source: https://docs.mem0.ai/platform/features/mcp-integration Use this command to add Mem0 MCP to a specific client, such as Cursor. Ensure you have npx installed. ```bash npx mcp-add \ --name mem0-mcp \ --type http \ --url "https://mcp.mem0.ai/mcp" \ --clients "cursor" ``` -------------------------------- ### Set Custom Instructions for Project (JavaScript) Source: https://docs.mem0.ai/platform/features/custom-instructions Use this to set specific natural language guidelines for your project's memory extraction. This example shows how to define instructions for a health app. ```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({ customInstructions: prompt }); ``` -------------------------------- ### Add Memory in Python Source: https://docs.mem0.ai/platform/quickstart Add a memory to the Mem0 Platform using the Python SDK. This example includes user and assistant messages. ```python messages = [ {"role": "user", "content": "I'm a vegetarian and allergic to nuts."}, {"role": "assistant", "content": "Got it! I'll remember your dietary preferences."} ] client.add(messages, user_id="user123") ``` -------------------------------- ### Set Custom Instructions for Project (Python) Source: https://docs.mem0.ai/platform/features/custom-instructions Use this to set specific natural language guidelines for your project's memory extraction. This example shows how to define instructions for a health app. ```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 Exclude: Personal identifiers, financial data """ client.project.update(custom_instructions=prompt) ``` -------------------------------- ### Get All Users Asynchronously in Python Source: https://docs.mem0.ai/platform/features/async-client Retrieve a list of all users, agents, and runs that have memories associated with them. ```python await client.users() ``` -------------------------------- ### Example Search Results with Criteria Source: https://docs.mem0.ai/platform/features/criteria-retrieval Sample output of a Mem0 search when criteria are enabled. Results are ranked based on semantic relevance and the defined criteria weights. ```json [ {"memory": "User feels refreshed and ready to take on anything on a beautiful sunny day", "score": 0.666, ...}, {"memory": "User finally has time to draw something after a long time", "score": 0.616, ...}, {"memory": "User is happy today", "score": 0.500, ...}, {"memory": "User is curious about how storms form and what triggers them in the atmosphere.", "score": 0.400, ...}, {"memory": "It has been raining for days, making everything feel heavier.", "score": 0.116, ...} ] ``` -------------------------------- ### Get Command Tree as JSON Source: https://docs.mem0.ai/platform/cli Retrieve the complete command tree in JSON format using `mem0 help --json`. This is useful for agents to discover available commands. ```bash mem0 help --json ``` -------------------------------- ### Process Document URL Source: https://docs.mem0.ai/platform/features/multimodal-support Ingest text documents from a URL into the Mem0 memory system. This example is a placeholder and requires implementation. ```python # Placeholder for document URL ingestion # client.add(url="your-document-url.mdx", user_id="alice") ``` -------------------------------- ### Submit Memory Export Job (cURL) Source: https://docs.mem0.ai/platform/features/memory-export Example cURL command to create a memory export request. Demonstrates setting the schema, filters, and optional export instructions. ```bash curl -X POST "https://api.mem0.ai/v1/memories/export/" \ -H "Authorization: Token your-api-key" \ -H "Content-Type: application/json" \ -d '{ "schema": {json_schema}, "filters": {"user_id": "alice"}, "export_instructions": "1. Create a comprehensive profile with detailed information\n2. Only mark fields as \"None\" when absolutely no relevant information exists" }' ``` -------------------------------- ### Add Memory in JavaScript Source: https://docs.mem0.ai/platform/quickstart Add a memory to the Mem0 Platform using the JavaScript SDK. This example includes user and assistant messages. ```javascript const messages = [ {"role": "user", "content": "I'm a vegetarian and allergic to nuts."}, {"role": "assistant", "content": "Got it! I'll remember your dietary preferences."} ]; await client.add(messages, { userId: "user123" }); ``` -------------------------------- ### Enable Agent Mode with --output json Source: https://docs.mem0.ai/platform/cli Use the `--output json` flag to get raw, unsanitized structured data from the CLI. ```bash mem0 --output json ``` -------------------------------- ### Get Help with Mem0 AI Platform Source: https://docs.mem0.ai/platform/features/contextual-add This snippet is a placeholder for code related to obtaining help or support within the Mem0 AI Platform. It is typically used to integrate help functionalities into your application. ```mdx ``` -------------------------------- ### Manage CLI Configuration Source: https://docs.mem0.ai/platform/cli The `mem0 config` command allows viewing and modifying the local CLI configuration. You can show the current config, get specific values, or set new values. ```bash mem0 config show # Display current config (secrets redacted) ``` ```bash mem0 config get api_key # Get a specific value ``` ```bash mem0 config set user_id bob # Set a value ``` -------------------------------- ### Check API Connection and Project Source: https://docs.mem0.ai/platform/cli Run `mem0 status` to verify your API connection and display the current project context. ```bash mem0 status ``` -------------------------------- ### Initialize Mem0 CLI Source: https://docs.mem0.ai/platform/quickstart Initialize the Mem0 CLI with your API key. ```bash mem0 init --api-key "your-api-key" ``` -------------------------------- ### Initialize MemoryClient Source: https://docs.mem0.ai/platform/features/criteria-retrieval Initialize the MemoryClient with your API key. This is the first step before configuring any criteria. ```python from mem0 import MemoryClient client = MemoryClient(api_key="your_mem0_api_key") ``` -------------------------------- ### Create Async Memory Client (Python) Source: https://docs.mem0.ai/platform/advanced-memory-operations Instantiate an asynchronous client for mem0ai. Ensure your API key is set as an environment variable. ```python import os from mem0 import AsyncMemoryClient memory = AsyncMemoryClient(api_key=os.environ["MEM0_API_KEY"]) ``` -------------------------------- ### Get Webhooks in JavaScript Source: https://docs.mem0.ai/platform/features/webhooks Retrieve all webhooks associated with a specific project ID. ```javascript # Get webhooks for a specific project const webhooks = await client.getWebhooks({projectId: "proj_123"}); console.log(webhooks); ``` -------------------------------- ### Get Memory History Source: https://docs.mem0.ai/platform/features/async-client Asynchronously retrieve the history of a specific memory using its memory_id. ```APIDOC ## Get Memory History ### Description Asynchronously retrieve the history of a specific memory using its memory_id. ### Request Example ```python await client.history(memory_id="memory-id-here") ``` ```javascript await client.history("memory-id-here"); ``` ``` -------------------------------- ### Configure Mem0 Memory Client Source: https://docs.mem0.ai/platform/features/entity-scoped-memory Initialize the MemoryClient with your API key to establish a connection to the Mem0 platform. Use this to interact with project details and manage memories. ```python from mem0 import MemoryClient client = MemoryClient(api_key="m0-...") ``` -------------------------------- ### Get All Memories Source: https://docs.mem0.ai/platform/features/async-client Asynchronously retrieve all memories for a specific user. Filters are required for this operation. ```APIDOC ## Get All Memories ### Description Asynchronously retrieve all memories for a specific user. Filters are required for this operation. ### Callout `get_all()` now requires filters to be specified. ### Request Example ```python await client.get_all(filters={"AND": [{"user_id": "alice"}]}) ``` ```javascript await client.getAll({ filters: {"AND": [{"user_id": "alice"}]} }); ``` ``` -------------------------------- ### Get Memory History in JavaScript Source: https://docs.mem0.ai/platform/features/async-client Retrieve the history of a specific memory by providing its ID. ```javascript await client.history("memory-id-here"); ``` -------------------------------- ### Test Custom Instructions with Sample Messages Source: https://docs.mem0.ai/platform/features/custom-instructions Test your custom instructions by adding sample messages and reviewing the extracted memories. This helps verify that the correct information is being captured. ```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(filters={"AND": [{"user_id": "test_user"}]}) # Review if the right information was extracted for memory in memories: print(f"Extracted: {memory['memory']}") ``` -------------------------------- ### Initialize Mem0 CLI (Non-Interactive) Source: https://docs.mem0.ai/platform/cli Configure the Mem0 CLI non-interactively by providing the API key and user ID as flags. This is useful for CI/CD environments. ```bash mem0 init --api-key m0-xxx --user-id alice ``` -------------------------------- ### Get All Memories Asynchronously in Python Source: https://docs.mem0.ai/platform/features/async-client Retrieve all memories for a user. Requires filters to be specified, such as 'user_id'. ```python await client.get_all(filters={"AND": [{"user_id": "alice"}]}) ``` -------------------------------- ### Initialize MemoryClient in JavaScript Source: https://docs.mem0.ai/platform/features/async-client Initialize the MemoryClient for interacting with the Mem0 API. Pass your API key during instantiation. ```javascript const { MemoryClient } = require('mem0ai'); const client = new MemoryClient({ apiKey: 'your-api-key'}); ``` -------------------------------- ### Get Memory History Asynchronously in Python Source: https://docs.mem0.ai/platform/features/async-client Retrieve the history of a specific memory using its memory ID. ```python await client.history(memory_id="memory-id-here") ``` -------------------------------- ### Get All Memories in JavaScript Source: https://docs.mem0.ai/platform/features/async-client Retrieve all memories for a user. Filters, including 'userId', must be provided in the options object. ```javascript await client.getAll({ filters: {"AND": [{"user_id": "alice"}]} }); ``` -------------------------------- ### Get Project Decay Status Source: https://docs.mem0.ai/platform/features/memory-decay Fetch the decay status of a project. Use the `fields` parameter to retrieve only the decay field. ```python response = client.project.get(fields=["decay"]) print(response["decay"]) ``` ```javascript const response = await client.project.get({ fields: ["decay"] }); console.log(response.decay); ``` ```cURL curl "https://api.mem0.ai/api/v1/orgs/organizations/$ORG_ID/projects/$PROJECT_ID/?fields=decay" \ -H "Authorization: Token $MEM0_API_KEY" ``` ```json { "decay": true } ``` -------------------------------- ### Apply Criteria to Project Source: https://docs.mem0.ai/platform/features/criteria-retrieval Register the defined retrieval criteria to your Mem0 project. Once set, these criteria affect all subsequent searches automatically. ```python client.project.update(retrieval_criteria=retrieval_criteria) ``` -------------------------------- ### Filter by User ID Source: https://docs.mem0.ai/platform/features/v2-memory-filters Example of filtering memories to retrieve data exclusively for a specific user. This is useful for isolating user-specific information. ```python # Narrow to one user's memories filters = {"AND": [{"user_id": "user_123"}]} ``` -------------------------------- ### Instantiate Async Memory Client (TypeScript) Source: https://docs.mem0.ai/platform/advanced-memory-operations Instantiate an asynchronous client for mem0ai in TypeScript. The API key is passed during instantiation. ```typescript import { Memory } from "mem0ai"; const memory = new Memory({ apiKey: process.env.MEM0_API_KEY!, async: true }); ``` -------------------------------- ### Date Range Filtering Source: https://docs.mem0.ai/platform/features/v2-memory-filters Use 'gte' for the start date and 'lt' for the end date to define a date range for filtering records. ```python {"AND": [{"created_at": {"gte": "2024-01-01"}}, {"created_at": {"lt": "2024-02-01"}}]} ``` -------------------------------- ### Add Memory from Text, File, or Stdin Source: https://docs.mem0.ai/platform/cli Demonstrates different ways to add memories: directly from text, from a JSON file, or piped from standard input. ```bash mem0 add "I prefer dark mode" --user-id alice mem0 add --file conversation.json --user-id alice echo "Loves hiking on weekends" | mem0 add --user-id alice ``` -------------------------------- ### Customize Personalized Learning Platform Instructions (Python) Source: https://docs.mem0.ai/platform/features/custom-instructions Use this snippet to set custom instructions for extracting learning-related information for a personalized education platform. It specifies data points for progress, preferences, and performance. ```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) ``` -------------------------------- ### AsyncMemoryClient Initialization Source: https://docs.mem0.ai/platform/features/async-client Initialize the AsyncMemoryClient for non-blocking memory operations. Ensure your MEM0_API_KEY is set as an environment variable. ```APIDOC ## AsyncMemoryClient Initialization ### Description Initialize the AsyncMemoryClient for non-blocking memory operations. Ensure your MEM0_API_KEY is set as an environment variable. ### Request Example ```python import os from mem0 import AsyncMemoryClient os.environ["MEM0_API_KEY"] = "your-api-key" client = AsyncMemoryClient() ``` ```javascript const { MemoryClient } = require('mem0ai'); const client = new MemoryClient({ apiKey: 'your-api-key'}); ``` ``` -------------------------------- ### Filter by Metadata Source: https://docs.mem0.ai/platform/features/v2-memory-filters Example of filtering memories based on metadata key-value pairs. Note that only 'eq', 'contains', and 'ne' operators are supported for metadata. ```python {"metadata": {"key": "value"}} ``` -------------------------------- ### Basic Usage: First and Later Interactions (Python) Source: https://docs.mem0.ai/platform/features/contextual-add Demonstrates adding messages for a user in two separate interactions. Mem0 automatically retains context from the first interaction for the second. ```python # First interaction messages1 = [ {"role": "user", "content": "Hi, I'm Sarah from New York"}, {"role": "assistant", "content": "Hello Sarah! Nice to meet you."} ] client.add(messages1, user_id="sarah") # Later interaction - just send new messages messages2 = [ {"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="sarah") # Mem0 automatically knows Sarah is from New York and can use this context ``` -------------------------------- ### Define Professional Profile Schema Source: https://docs.mem0.ai/platform/features/memory-export Example Pydantic schema for extracting professional profile information, including education level and employment status. ```json { "$defs": { "EducationLevel": { "enum": ["high_school", "bachelors", "masters"], "title": "EducationLevel", "type": "string" }, "EmploymentStatus": { "enum": ["full_time", "part_time", "student"], "title": "EmploymentStatus", "type": "string" } }, "properties": { "full_name": { "anyOf": [ { "maxLength": 100, "minLength": 2, "type": "string" }, { "type": "null" } ], "default": null, "description": "The professional's full name", "title": "Full Name" }, "current_role": { "anyOf": [ { "type": "string" }, { "type": "null" } ], "default": null, "description": "Current job title or role", "title": "Current Role" } }, "title": "ProfessionalProfile", "type": "object" } ``` -------------------------------- ### Retrieve a Specific Memory Source: https://docs.mem0.ai/platform/cli Use the `mem0 get` command followed by the memory ID to fetch a single memory. The output can be formatted as JSON. ```bash mem0 get 7b3c1a2e-4d5f-6789-abcd-ef0123456789 ``` ```bash mem0 get 7b3c1a2e-4d5f-6789-abcd-ef0123456789 --output json ``` -------------------------------- ### Activate Agent Mode with JSON Output Source: https://docs.mem0.ai/platform/cli Demonstrates activating agent mode using the --agent or --json flag. This ensures consistent JSON output and suppresses human-readable elements for AI agent consumption. ```bash mem0 search "user preferences" --user-id alice --agent ``` -------------------------------- ### Initialize Mem0 CLI with Force Option Source: https://docs.mem0.ai/platform/cli Force overwrite of existing Mem0 CLI configuration without confirmation. Useful for automated environments like CI/CD pipelines. ```bash mem0 init --api-key m0-xxx --user-id alice --force ``` -------------------------------- ### Display Agent Rush Error Message Source: https://docs.mem0.ai/platform/cli The CLI pretty-prints specific error codes into human-readable hints. This example shows the 'search_first' rule violation. ```text [error] Error: AGENTRUSH error: agentrush_search_first Run 3 'mem0 agent-rush search' commands before adding. ``` -------------------------------- ### Advanced: Nested NOT/OR Logic Source: https://docs.mem0.ai/platform/features/v2-memory-filters Combine `NOT` and `OR` operators for complex exclusion rules. This example retrieves user memories from 2024, excluding specific categories. ```python # User memories from 2024, excluding spam and test filters = { "AND": [ {"user_id": "user_123"}, {"created_at": {"gte": "2024-01-01T00:00:00Z"}}, {"NOT": { "OR": [ {"categories": {"in": ["spam"]}}, {"categories": {"in": ["test"]}} ] }} ] } ``` -------------------------------- ### Create Webhook in Python Source: https://docs.mem0.ai/platform/features/webhooks Use this to create a new webhook for a specific project. You can specify the URL, name, project ID, and the event types to subscribe to. ```python import os from mem0 import MemoryClient os.environ["MEM0_API_KEY"] = "your-api-key" client = MemoryClient() # Create webhook in a specific project webhook = client.create_webhook( url="https://your-app.com/webhook", name="Memory Logger", project_id="proj_123", event_types=["memory_add", "memory_categorize"] ) print(webhook) ``` -------------------------------- ### Search for Memories Source: https://docs.mem0.ai/platform/features/direct-import Retrieve memories using the `search` method with specified filters. This example searches for memories related to Alice's favorite sport. ```python client.search("What is Alice's favorite sport?", filters={"user_id": "alice"}) ``` -------------------------------- ### Customize AI Financial Advisor Instructions (Python) Source: https://docs.mem0.ai/platform/features/custom-instructions Use this snippet to set custom instructions for extracting financial planning information for advisory services. It outlines goals, life events, and investment interests to consider. ```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) ``` -------------------------------- ### Customize Personalized Learning Platform Instructions (JavaScript) Source: https://docs.mem0.ai/platform/features/custom-instructions Use this snippet to set custom instructions for extracting learning-related information for a personalized education platform. It specifies data points for progress, preferences, and performance. ```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({ customInstructions: educationPrompt }); ``` -------------------------------- ### Memory Export Request Response Source: https://docs.mem0.ai/platform/features/memory-export Example JSON response received after submitting a memory export request, indicating the request was received and providing an export ID. ```json { "message": "Memory export request received. The export will be ready in a few seconds.", "id": "550e8400-e29b-41d4-a716-446655440000" } ``` -------------------------------- ### Initialize AsyncMemoryClient in Python Source: https://docs.mem0.ai/platform/features/async-client Initialize the AsyncMemoryClient for non-blocking memory operations. Ensure your MEM0_API_KEY is set as an environment variable. ```python import os from mem0 import AsyncMemoryClient os.environ["MEM0_API_KEY"] = "your-api-key" client = AsyncMemoryClient() ``` -------------------------------- ### Backfill Agent Attribution Source: https://docs.mem0.ai/platform/agent-signup If you forgot to specify the `--agent-caller` during the initial `mem0 init` command, use this command to add your agent's name retroactively. This ensures proper attribution without changing the API key or disrupting the agent. ```bash mem0 identify ``` -------------------------------- ### Get Agent Identity Source: https://docs.mem0.ai/platform/cli The `mem0 whoami` command prints the agent's stable identity, stored in `~/.mem0/config.json`. It exits with code 1 if no identity is configured. ```bash mem0 whoami # Your AGENTRUSH identifier: user_a1b2c3d4e5f6 # Find your row at https://mem0.ai/agentrush ``` -------------------------------- ### Create Webhook in JavaScript Source: https://docs.mem0.ai/platform/features/webhooks Use this to create a new webhook for a specific project. You can specify the URL, name, project ID, and the event types to subscribe to. ```javascript const { MemoryClient } = require('mem0ai'); const client = new MemoryClient({ apiKey: 'your-api-key'}); // Create webhook in a specific project const webhook = await client.createWebhook({ url: "https://your-app.com/webhook", name: "Memory Logger", projectId: "proj_123", eventTypes: ["memory_add", "memory_categorize"] }); console.log(webhook); ``` -------------------------------- ### Set Mem0 API Key via Environment Variable Source: https://docs.mem0.ai/platform/cli Configure the Mem0 API key by setting the MEM0_API_KEY environment variable. This is an alternative to using flags during initialization. ```bash export MEM0_API_KEY="m0-xxx" ``` -------------------------------- ### Get Memories for a Specific Participant Source: https://docs.mem0.ai/platform/features/group-chat Retrieve all memories associated with a specific user ID and run ID from a group chat. Ensure the client is initialized before use. ```python # Get memories for a specific participant filters = { "AND": [ {"user_id": "charlie"}, {"run_id": "group_chat_1"} ] } charlie_memories = client.get_all(filters=filters, page=1) print(charlie_memories) ``` ```json [ { "id": "147559a8-c5f7-44d0-9418-91f53f7a89a4", "memory": "suggests considering Angular because it has great enterprise support", "user_id": "charlie", "run_id": "group_chat_1", "created_at": "2025-06-21T05:51:11.007223-07:00", "updated_at": "2025-06-21T05:51:11.626562-07:00" } ] ``` -------------------------------- ### Agent Search Command with JSON Output Source: https://docs.mem0.ai/platform/cli Demonstrates the JSON output of the `mem0 --agent search` command, showing retrieved memories and their metadata. ```bash mem0 --agent search "dark mode" --user-id alice theme={null} ``` ```json { "status": "success", "command": "search", "duration_ms": 134, "scope": { "user_id": "alice" }, "count": 2, "data": [ { "id": "abc-123", "memory": "User prefers dark mode", "score": 0.97, "created_at": "2026-01-15", "categories": ["preferences"] }, { "id": "def-456", "memory": "User uses vim keybindings", "score": 0.81, "created_at": "2026-01-10", "categories": ["tools"] } ] } ``` -------------------------------- ### Basic Usage: First and Later Interactions (JavaScript) Source: https://docs.mem0.ai/platform/features/contextual-add Demonstrates adding messages for a user in two separate interactions using JavaScript. Mem0 automatically retains context from the first interaction for the second. ```javascript // First interaction const messages1 = [ {"role": "user", "content": "Hi, I'm Sarah from New York"}, {"role": "assistant", "content": "Hello Sarah! Nice to meet you."} ]; await client.add(messages1, { userId: "sarah", version: "v2" }); // Later interaction - just send new messages const messages2 = [ {"role": "user", "content": "I'm planning a trip to Italy next month"}, {"role": "assistant", "content": "How exciting! Italy is beautiful this time of year."} ]; await client.add(messages2, { userId: "sarah", version: "v2" }); // Mem0 automatically knows Sarah is from New York and can use this context ``` -------------------------------- ### Advanced: Multi-dimensional Filtering Source: https://docs.mem0.ai/platform/features/v2-memory-filters Combine multiple criteria including keywords, categories, and date ranges for precise filtering. This example finds invoice memories in Q1 2024 for a specific user. ```python # Invoice memories in Q1 2024 filters = { "AND": [ {"user_id": "user_123"}, {"keywords": {"icontains": "invoice"}}, {"categories": {"in": ["finance"]}}, {"created_at": {"gte": "2024-01-01T00:00:00Z"}}, {"created_at": {"lt": "2024-04-01T00:00:00Z"}} ] } ``` -------------------------------- ### Create Webhook Source: https://docs.mem0.ai/platform/features/webhooks Create a webhook for your project. It will receive events only from that project. ```APIDOC ## POST /webhooks ### Description Create a webhook for your project. It will receive events only from that project. ### Method POST ### Endpoint /webhooks ### Parameters #### Request Body - **url** (string) - Required - The URL to which the webhook will send HTTP POST requests. - **name** (string) - Required - A descriptive name for the webhook. - **project_id** (string) - Required - The ID of the project for which the webhook is being created. - **event_types** (array of strings) - Required - A list of event types that will trigger the webhook. ### Request Example ```json { "url": "https://your-app.com/webhook", "name": "Memory Logger", "project_id": "proj_123", "event_types": ["memory_add", "memory_categorize"] } ``` ### Response #### Success Response (200) - **webhook_id** (string) - The unique identifier for the created webhook. - **name** (string) - The name of the webhook. - **url** (string) - The URL of the webhook. - **event_types** (array of strings) - The event types configured for the webhook. - **project** (string) - The project associated with the webhook. - **is_active** (boolean) - Indicates if the webhook is active. - **created_at** (string) - The timestamp when the webhook was created. - **updated_at** (string) - The timestamp when the webhook was last updated. #### Response Example ```json { "webhook_id": "wh_123", "name": "Memory Logger", "url": "https://your-app.com/webhook", "event_types": ["memory_add"], "project": "default-project", "is_active": true, "created_at": "2025-02-18T22:59:56.804993-08:00", "updated_at": "2025-02-18T23:06:41.479361-08:00" } ``` ``` -------------------------------- ### Filter by Time Range Source: https://docs.mem0.ai/platform/features/v2-memory-filters Example of filtering memories based on their creation or update timestamps. Use operators like 'gte' (greater than or equal to) and 'lt' (less than) for date range queries. ```python {"created_at": {"gte": "2024-01-01"}} ``` ```python {"updated_at": {"lt": "2024-12-31"}} ``` ```python {"timestamp": {"gt": "2024-01-01"}} ```