### Initialize Open-Source Mode with Interactive Wizard Source: https://docs.mem0.ai/integrations/openclaw Run this command to start the guided wizard for setting up Mem0 in Open-Source mode. This is the recommended approach for interactive setup. ```bash openclaw mem0 init --mode open-source ``` -------------------------------- ### Mem0 OSS Setup with Docker Source: https://docs.mem0.ai/core-concepts/memory-evaluation Clone the repository, install dependencies, configure the .env file with your OpenAI API key, and start the local Mem0 server and Qdrant using Docker Compose. ```bash git clone https://github.com/mem0ai/memory-benchmarks.git cd memory-benchmarks pip install -r requirements.txt # Copy and configure environment cp .env.example .env # Edit .env to add OPENAI_API_KEY # Start local Mem0 server + Qdrant docker compose up -d # Mem0 server: http://localhost:8888 # Qdrant: http://localhost:6333 ``` -------------------------------- ### Mem0 Cloud Setup Source: https://docs.mem0.ai/core-concepts/memory-evaluation Clone the memory benchmarks repository, install dependencies, and set your API keys for Mem0 Cloud and OpenAI. ```bash git clone https://github.com/mem0ai/memory-benchmarks.git cd memory-benchmarks pip install -r requirements.txt # Set your API keys export MEM0_API_KEY=m0-your-key export OPENAI_API_KEY=sk-your-key ``` -------------------------------- ### Install Cassandra on Ubuntu/Debian Source: https://docs.mem0.ai/components/vectordbs/dbs/cassandra Install Apache Cassandra locally on Ubuntu or Debian systems. This involves adding the repository, installing the package, and starting the service. ```bash # Add Apache Cassandra repository echo "deb https://downloads.apache.org/cassandra/debian 40x main" | sudo tee -a /etc/apt/sources.list.d/cassandra.sources.list curl https://downloads.apache.org/cassandra/KEYS | sudo apt-key add - # Install Cassandra sudo apt-get update sudo apt-get install cassandra # Start Cassandra sudo systemctl start cassandra # Verify installation nodetool status ``` -------------------------------- ### Get Project Details (Go) Source: https://docs.mem0.ai/api-reference/project/get-project This Go code snippet demonstrates fetching project details using the Mem0 Go SDK. Install the SDK with 'go get github.com/mem0ai/mem0-go'. ```Go // To use the Go SDK, install the package: // go get github.com/mem0ai/mem0-go package main import ( "fmt" "github.com/mem0ai/mem0-go" ) func main() { client := mem0.NewClient("your-api-key") response, err := client.GetProject() if err != nil { fmt.Printf("Error: %v\n", err) return } fmt.Printf("%+v\n", response) } ``` -------------------------------- ### LiveKit Agent Session Setup and Entrypoint Source: https://docs.mem0.ai/integrations/livekit Defines the main entrypoint for the LiveKit agent, setting up the agent session with specified STT, LLM, TTS, turn detection, and VAD configurations. It then starts the session and initiates an initial greeting. ```python async def entrypoint(ctx: JobContext): """Main entrypoint for the agent.""" await ctx.connect() session = AgentSession( stt=deepgram.STT(), llm=openai.LLM(model="gpt-5-mini"), tts=openai.TTS(voice="ash",), turn_detection=EnglishModel(), vad=silero.VAD.load(), ) await session.start( agent=MemoryEnabledAgent(), room=ctx.room, room_input_options=RoomInputOptions( noise_cancellation=noise_cancellation.BVC(), ), ) # Initial greeting await session.generate_reply( instructions="Greet the user warmly as George the travel guide and ask how you can help them plan their next adventure.", allow_interruptions=True ) # Run the application if __name__ == "__main__": cli.run_app(WorkerOptions(entrypoint_fnc=entrypoint)) ``` -------------------------------- ### Install Dependencies Source: https://docs.mem0.ai/cookbooks/companions/ai-tutor Install the necessary packages for the AI Tutor using pip. ```bash pip install openai mem0ai ``` -------------------------------- ### Initialize Memory in Mem0 Open Source (Old) Source: https://docs.mem0.ai/migration/oss-to-platform Example of initializing the Memory class in Mem0 Open Source using a configuration object. This setup is for local or self-hosted instances. ```python from mem0 import Memory config = { "vector_store": { "provider": "qdrant", "config": {"host": "localhost", "port": 6333} }, "llm": { "provider": "openai", "config": {"model": "gpt-4"} } } m = Memory.from_config(config) ``` -------------------------------- ### Full Code Example for Local Ollama Setup Source: https://docs.mem0.ai/cookbooks/companions/local-companion-ollama This snippet shows the complete configuration and usage of Mem0 with Ollama for local LLM and embedding models. Ensure Ollama is running and accessible at the specified base URL. ```python from mem0 import Memory config = { "vector_store": { "provider": "qdrant", "config": { "collection_name": "test", "host": "localhost", "port": 6333, "embedding_model_dims": 768, # Change this according to your local model's dimensions }, }, "llm": { "provider": "ollama", "config": { "model": "llama3.1:latest", "temperature": 0, "max_tokens": 2000, "ollama_base_url": "http://localhost:11434", # Ensure this URL is correct }, }, "embedder": { "provider": "ollama", "config": { "model": "nomic-embed-text:latest", # Alternatively, you can use "snowflake-arctic-embed:latest" "ollama_base_url": "http://localhost:11434", }, }, } # Initialize Memory with the configuration m = Memory.from_config(config) # Add a memory m.add("I'm visiting Paris", user_id="john") # Retrieve memories memories = m.get_all(filters={"user_id": "john"}) ``` -------------------------------- ### Install LangGraph, Langchain-OpenAI, Mem0ai, and Python-dotenv Source: https://docs.mem0.ai/integrations/langgraph Install the necessary Python libraries for building the customer support agent. Ensure you have Python 3.7+ installed. ```bash pip install langgraph langchain-openai mem0ai python-dotenv ``` -------------------------------- ### Install Dependencies Source: https://docs.mem0.ai/cookbooks/integrations/openai-tool-calls Install the necessary packages for Mem0, OpenAI, and Zod integration. ```bash npm install mem0ai openai zod ``` -------------------------------- ### Get Project Details (PHP) Source: https://docs.mem0.ai/api-reference/project/get-project Example of how to get project details using the Mem0 PHP SDK. Ensure you have installed the package via Composer ('composer require mem0ai/mem0-php'). ```PHP getProject(); print_r($response); } catch (Exception $e) { echo 'Error: ' . $e->getMessage(); } ``` -------------------------------- ### Setup TutorAgent Source: https://docs.mem0.ai/cookbooks/frameworks/llamaindex-multiagent Configures the TutorAgent with a name, description, system prompt emphasizing memory-driven teaching, defined tools, LLM, and handoff capabilities. ```python from llama_index.core.agent import FunctionAgent from llama_index.llms.openai import OpenAI self.llm = OpenAI(model="gpt-5-mini", temperature=0.2) # AGENTS # Tutor Agent - Main teaching and explanation self.tutor_agent = FunctionAgent( name="TutorAgent", description="Primary instructor that explains concepts and adapts to student needs", system_prompt=""" You are a patient, adaptive programming tutor. Your key strength is REMEMBERING and BUILDING on previous interactions. Key Behaviors: 1. Always check what the student has learned before (use memory context) 2. Adapt explanations based on their preferred learning style 3. Reference previous struggles or successes 4. Build progressively on past lessons 5. Use assess_understanding to evaluate responses and save insights MEMORY-DRIVEN TEACHING: - "Last time you struggled with X, so let's approach Y differently..." - "Since you prefer visual examples, here's a diagram..." - "Building on the functions we covered yesterday..." When student shows understanding, hand off to PracticeAgent for exercises. """, tools=tools, llm=self.llm, can_handoff_to=["PracticeAgent"] ) ``` -------------------------------- ### Multi-Agent Workflow Setup Source: https://docs.mem0.ai/integrations/openai-agents-sdk Sets up specialized agents for a multi-agent workflow, enabling them to share memory and context. This example initializes a 'Travel Planner' and a 'Health Advisor' agent, both equipped with memory tools for context retrieval and conversation storage. ```python from agents import Agent, Runner, handoffs, function_tool # Specialized agents travel_agent = Agent( name="Travel Planner", instructions="""You are a travel planning specialist. Use get_user_context to understand the user's travel preferences and history before making recommendations. After providing your response, use store_conversation to save important details.""", tools=[search_memory, save_memory], model="gpt-5-mini" ) health_agent = Agent( name="Health Advisor", instructions="""You are a health and wellness advisor. Use get_user_context to understand the user's health goals and dietary preferences. After providing advice, use store_conversation to save relevant information.""", tools=[search_memory, save_memory], model="gpt-5-mini" ) ``` -------------------------------- ### Setup PracticeAgent Source: https://docs.mem0.ai/cookbooks/frameworks/llamaindex-multiagent Configures the PracticeAgent with a name, description, system prompt focusing on memory-driven practice, defined tools, LLM, and handoff capabilities. ```python from llama_index.core.agent import FunctionAgent from llama_index.llms.openai import OpenAI self.llm = OpenAI(model="gpt-5-mini", temperature=0.2) # AGENTS # Practice Agent - Exercises and reinforcement self.practice_agent = FunctionAgent( name="PracticeAgent", description="Creates practice exercises and tracks progress based on student's learning history", system_prompt=""" You create personalized practice exercises based on the student's learning history and current level. Key Behaviors: 1. Generate problems that match their skill level (from memory) 2. Focus on areas they've struggled with previously 3. Gradually increase difficulty based on their progress 4. Use track_progress to record their performance 5. Provide encouraging feedback that references their growth MEMORY-DRIVEN PRACTICE: - "Let's practice loops again since you wanted more examples..." - "Here's a harder version of the problem you solved yesterday..." - "You've improved a lot in functions, ready for the next level?" After practice, can hand back to TutorAgent for concept review if needed. """, tools=tools, llm=self.llm, can_handoff_to=["TutorAgent"] ) ``` -------------------------------- ### Install and Start Flowise Source: https://docs.mem0.ai/integrations/flowise Install Flowise globally using npm and start the application. NodeJS version 18.15.0 or higher is required. ```bash npm install -g flowise npx flowise start ``` -------------------------------- ### Install Libraries Source: https://docs.mem0.ai/integrations/autogen Install the necessary Python libraries for AutoGen, Mem0, OpenAI, and dotenv. ```bash pip install autogen mem0ai openai python-dotenv ``` -------------------------------- ### v0.x Configuration Options Example Source: https://docs.mem0.ai/migration/api-changes Example configuration dictionary for v0.x, highlighting the unsupported 'version' field. ```python config = { "vector_store": {...}, "llm": {...}, "embedder": {...}, "graph_store": {...}, "version": "v1.0", # ❌ v1.0 no longer supported "history_db_path": "...", "custom_instructions": "..." } ``` -------------------------------- ### Install Cassandra on macOS Source: https://docs.mem0.ai/components/vectordbs/dbs/cassandra Install Apache Cassandra on macOS using Homebrew. This includes starting the service and connecting to the CQL shell. ```bash # Using Homebrew brew install cassandra # Start Cassandra brew services start cassandra # Connect to CQL shell cqlsh ``` -------------------------------- ### 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 ``` -------------------------------- ### Install Provider SDKs (Qdrant + OpenAI) Source: https://docs.mem0.ai/open-source/configuration Install necessary SDKs for specific providers like Qdrant and OpenAI. ```bash pip install qdrant-client openai ``` -------------------------------- ### TypeScript Setup Placeholder Source: https://docs.mem0.ai/templates/cookbook_template Placeholder for the equivalent TypeScript setup code. This should be replaced with the actual imports and initializations required for TypeScript examples. ```typescript // Equivalent TypeScript setup goes here ``` -------------------------------- ### Get Users with Java Source: https://docs.mem0.ai/api-reference/entities/get-users An example using Unirest to make a GET request for retrieving users. This requires the Unirest library to be included in your project. ```Java HttpResponse response = Unirest.get("https://api.mem0.ai/v1/entities/") ``` -------------------------------- ### v1.0.0 Configuration Options Example Source: https://docs.mem0.ai/migration/api-changes Example configuration dictionary for v1.0.0, showing new 'reranker' and 'custom_update_memory_prompt' options. ```python config = { "vector_store": {...}, "llm": {...}, "embedder": {...}, "graph_store": {...}, "reranker": { # ✅ NEW: Reranker support "provider": "cohere", "config": {...} }, "version": "v1.1", # ✅ v1.1+ only "history_db_path": "...", "custom_instructions": "...", "custom_update_memory_prompt": "..." # ✅ NEW: Custom update prompt } ``` -------------------------------- ### Run Mintlify Development Server Source: https://docs.mem0.ai/contributing/documentation Start the local documentation development server. Navigate to the 'docs/' directory before running this command. ```bash mintlify dev ``` -------------------------------- ### Start LiveKit Voice Agent Source: https://docs.mem0.ai/integrations/livekit Run the voice agent script to start the application. Ensure Python 3.11+ is installed and dependencies are set up. ```shell python mem0-livekit-voice-agent.py start ``` -------------------------------- ### Setup Mem0 and OpenAI Client (Platform) Source: https://docs.mem0.ai/cookbooks/operations/content-writing Initialize Mem0 and OpenAI clients using API keys for cloud-based operations. Ensure MEM0_API_KEY and OPENAI_API_KEY environment variables are set. ```python import os from openai import OpenAI from mem0 import MemoryClient os.environ["MEM0_API_KEY"] = "your-mem0-api-key" os.environ["OPENAI_API_KEY"] = "your-openai-api-key" # Set up Mem0 and OpenAI client client = MemoryClient() openai = OpenAI() USER_ID = "content_writer" RUN_ID = "smart_editing_session" ``` -------------------------------- ### Get Memory Export with cURL Source: https://docs.mem0.ai/api-reference/memory/get-memory-export Example of how to call the get memory export endpoint using cURL, including the necessary authorization header and data payload. ```cURL curl --request POST \ --url 'https://api.mem0.ai/v1/exports/get/' \ --header 'Authorization: Token ' \ --data '{ \ "memory_export_id": "" \ }' ``` -------------------------------- ### Install Mem0 Plugin via Chat Source: https://docs.mem0.ai/integrations/openclaw The recommended method to install the Mem0 plugin is by sending a setup command directly within your OpenClaw chat interface. ```text Setup Mem0 from mem0.ai/claw-setup ``` -------------------------------- ### Initialize and Run Multi-Agent Learning System Source: https://docs.mem0.ai/cookbooks/frameworks/llamaindex-multiagent Demonstrates the initialization of a MultiAgentLearningSystem for a specific student and starting a learning session with a given topic and user background. It also shows how to start a subsequent session to continue learning and retrieve the learning history. ```python # Initialize the learning system learning_system = MultiAgentLearningSystem(student_id="Alexander") # Start a learning session response = await learning_system.start_learning_session( "Vision Language Models", "I'm new to machine learning but I have good hold on Python and have 4 years of work experience." ) # Continue learning in a new session (memory persists) response2 = await learning_system.start_learning_session( "Machine Learning", "what all did I cover so far?" ) # Check learning history history = await learning_system.get_learning_history() ``` -------------------------------- ### Quick Start: Add a Memory Source: https://docs.mem0.ai/platform/cli Add a new memory to the Mem0 platform with a text description and associate it with a user ID. ```bash # Add a memory mem0 add "I prefer dark mode and use vim keybindings" --user-id alice ``` -------------------------------- ### Get Project Details (Python) Source: https://docs.mem0.ai/api-reference/project/get-project Use this snippet to retrieve project details using the Mem0 Python SDK. Ensure you have installed the SDK using 'pip install mem0ai'. ```Python # To use the Python SDK, install the package: # pip install mem0ai from mem0 import MemoryClient client = MemoryClient(api_key="your_api_key") response = client.get_project() print(response) ``` -------------------------------- ### Initialize Voice Companion Environment Source: https://docs.mem0.ai/cookbooks/companions/voice-companion-openai Set up the environment by importing necessary modules, configuring API keys, defining a user ID, and initializing the Mem0 client. ```python # OpenAI Agents SDK imports from agents import ( Agent, function_tool ) from agents.voice import ( AudioInput, SingleAgentVoiceWorkflow, VoicePipeline ) from agents.extensions.handoff_prompt import prompt_with_handoff_instructions # Mem0 imports from mem0 import AsyncMemoryClient # Set up API keys (replace with your actual keys) os.environ["OPENAI_API_KEY"] = "your-openai-api-key" os.environ["MEM0_API_KEY"] = "your-mem0-api-key" # Define a global user ID for simplicity USER_ID = "voice_user" # Initialize Mem0 client mem0_client = AsyncMemoryClient() ``` -------------------------------- ### Full Example Run Source: https://docs.mem0.ai/cookbooks/integrations/tavily-search Executes a series of personalized searches for a given user, demonstrating the end-to-end workflow. This script shows how to initialize user history and iterate through queries. ```python if __name__ == "__main__": user_id = "john" setup_user_history(user_id) queries = [ "good coffee shops nearby for working", "what can I make for my kid in lunch?" ] for q in queries: results = conduct_personalized_search(user_id, q) print(f"\nQuery: {q}") print(f"Personalized Response: {results['agent_response']}") ``` -------------------------------- ### Get Webhooks Output Source: https://docs.mem0.ai/platform/features/webhooks This is an example of the JSON output when retrieving a list of webhooks for a project. ```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" } ] ``` -------------------------------- ### Quick Start: Get a Specific Memory Source: https://docs.mem0.ai/platform/cli Retrieve a specific memory using its unique ID. ```bash # Get a specific memory mem0 get ``` -------------------------------- ### Install Mem0 and Partner SDKs (Python) Source: https://docs.mem0.ai/templates/integration_guide_template Install the necessary Python SDKs for Mem0 and the partner service. Ensure you have the correct packages for your integration. ```bash pip install mem0ai [partner-package] ``` -------------------------------- ### Get and Create Webhooks with Go Source: https://docs.mem0.ai/api-reference/webhook/get-webhook Shows how to fetch all webhooks and subsequently create a new webhook using Go's standard `net/http` package. Error handling is omitted for brevity. ```go package main import ( "fmt" "strings" "net/http" "io/ioutil" ) func main() { // Get all webhooks req, _ := http.NewRequest("GET", "https://api.mem0.ai/api/v1/webhooks/your_project_id/webhook/", nil) req.Header.Add("Authorization", "Token your-api-key") res, _ := http.DefaultClient.Do(req) defer res.Body.Close() body, _ := ioutil.ReadAll(res.Body) fmt.Println(string(body)) // Create a webhook payload := strings.NewReader(`{ "url": "https://your-webhook-url.com", "name": "My Webhook", "event_types": ["memory:add"] }`) req, _ = http.NewRequest("POST", "https://api.mem0.ai/api/v1/webhooks/your_project_id/webhook/", payload) req.Header.Add("Authorization", "Token your-api-key") req.Header.Add("Content-Type", "application/json") res, _ = http.DefaultClient.Do(req) defer res.Body.Close() body, _ = ioutil.ReadAll(res.Body) fmt.Println(string(body)) } ``` -------------------------------- ### Start Mem0 API Server Stack with Docker Compose Source: https://docs.mem0.ai/open-source/features/rest-api Start only the Mem0 API server stack using 'docker compose up -d' if you intend to complete the setup via the browser wizard. ```bash cd server docker compose up -d ``` -------------------------------- ### Configure Mem0 Environment Variables Source: https://docs.mem0.ai/cookbooks/frameworks/eliza-os-character Set up your .env file with Mem0 API keys and configuration. Use .env.example as a reference. ```bash # Mem0 Configuration MEM0_API_KEY= # Mem0 API Key (get from https://app.mem0.ai/dashboard/api-keys?utm_source=oss&utm_medium=cookbook-eliza-os) MEM0_USER_ID= # Default: eliza-os-user MEM0_PROVIDER= # Default: openai MEM0_PROVIDER_API_KEY= # API Key for the provider (OpenAI, Anthropic, etc.) SMALL_MEM0_MODEL= # Default: gpt-4.1-nano MEDIUM_MEM0_MODEL= # Default: gpt-4o LARGE_MEM0_MODEL= # Default: gpt-4o ``` -------------------------------- ### Get Memory Export with PHP Source: https://docs.mem0.ai/api-reference/memory/get-memory-export Example using PHP's cURL functions to call the get memory export API. The request includes an Authorization header and a JSON payload with the memory export ID. ```PHP '']); curl_setopt_array($curl, [ CURLOPT_URL => "https://api.mem0.ai/v1/exports/get/", CURLOPT_RETURNTRANSFER => true, CURLOPT_ENCODING => "", CURLOPT_MAXREDIRS => 10, CURLOPT_TIMEOUT => 30, CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1, CURLOPT_CUSTOMREQUEST => "POST", CURLOPT_POSTFIELDS => $data, CURLOPT_HTTPHEADER => [ "Authorization: Token ", ``` -------------------------------- ### Display CLI Version Source: https://docs.mem0.ai/platform/cli Get the currently installed version of the Mem0 CLI by running the `mem0 version` command. ```bash mem0 version ``` -------------------------------- ### Initialize Mem0 Client and Set API Keys Source: https://docs.mem0.ai/integrations/crewai Set up environment variables for API keys and initialize the Mem0 client. Ensure you have API keys for Mem0, OpenAI, and Serper Dev. ```python import os from mem0 import MemoryClient # Configuration os.environ["MEM0_API_KEY"] = "your-mem0-api-key" os.environ["OPENAI_API_KEY"] = "your-openai-api-key" os.environ["SERPER_API_KEY"] = "your-serper-api-key" # Initialize Mem0 client client = MemoryClient() ``` -------------------------------- ### Get Users with JavaScript SDK Source: https://docs.mem0.ai/api-reference/entities/get-users Retrieve all users using the JavaScript SDK. Install the mem0ai package first. ```JavaScript // To use the JavaScript SDK, install the package: # npm i mem0ai import MemoryClient from 'mem0ai'; const client = new MemoryClient({ apiKey: "your-api-key" }); // Retrieve all users client.users() .then(result => console.log(result)) .catch(error => console.error(error)); ``` -------------------------------- ### Initialize LangChain and Mem0 Clients Source: https://docs.mem0.ai/integrations/langgraph Set up the language model and memory client. Load environment variables for API keys. Ensure your OpenAI API key and Mem0 API key are set in your environment. ```python from typing import Annotated, TypedDict, List from langgraph.graph import StateGraph, START from langgraph.graph.message import add_messages from langchain_openai import ChatOpenAI from mem0 import MemoryClient from langchain_core.messages import SystemMessage, HumanMessage, AIMessage from dotenv import load_dotenv load_dotenv() # Configuration # OPENAI_API_KEY = 'sk-xxx' # Replace with your actual OpenAI API key # MEM0_API_KEY = 'your-mem0-key' # Replace with your actual Mem0 API key # Initialize LangChain and Mem0 llm = ChatOpenAI(model="gpt-4") mem0 = MemoryClient() ``` -------------------------------- ### Get Users with Python SDK Source: https://docs.mem0.ai/api-reference/entities/get-users Use the Python SDK to retrieve all users. Ensure you have installed the mem0ai package. ```Python # To use the Python SDK, install the package: # pip install mem0ai from mem0 import MemoryClient client = MemoryClient(api_key="your_api_key") users = client.users() print(users) ``` -------------------------------- ### Get Memory with cURL Source: https://docs.mem0.ai/api-reference/memory/get-memory Example of how to retrieve a memory using cURL. Replace '{memory_id}' and '' with your specific values. ```cURL curl --request GET \ --url https://api.mem0.ai/v1/memories/{memory_id}/ \ --header 'Authorization: Token ' ``` -------------------------------- ### Run Eliza OS Project Source: https://docs.mem0.ai/cookbooks/frameworks/eliza-os-character Start the Eliza OS project after configuration to interact with your personalized character. ```bash pnpm start ``` -------------------------------- ### Get Users with cURL Source: https://docs.mem0.ai/api-reference/entities/get-users Example of how to fetch users using a cURL request. Replace with your actual API key. ```cURL curl --request GET \ --url https://api.mem0.ai/v1/entities/ \ --header 'Authorization: Token ' ``` -------------------------------- ### Start Development Server Source: https://docs.mem0.ai/cookbooks/companions/quickstart-demo Run the pnpm run dev command to start the Next.js development server for the demo application. ```bash pnpm run dev ``` -------------------------------- ### Basic Reranker Configuration Source: https://docs.mem0.ai/components/rerankers/config Example of configuring a reranker with a specific provider and model. This setup is used for optimizing search results. ```Python config = { "vector_store": { "provider": "chroma", "config": { "collection_name": "my_memories", "path": "./chroma_db" } }, "llm": { "provider": "openai", "config": { "model": "gpt-5-mini" } }, "reranker": { "provider": "zero_entropy", "config": { "model": "zerank-1", "top_k": 5 } } } ``` -------------------------------- ### Python Configuration Example Source: https://docs.mem0.ai/components/llms/config Initialize Mem0 with a custom configuration in Python. Ensure environment variables like OPENAI_API_KEY are set if required by your provider. ```python import os from mem0 import Memory os.environ["OPENAI_API_KEY"] = "sk-xx" # for embedder config = { "llm": { "provider": "your_chosen_provider", "config": { # Provider-specific settings go here } } } m = Memory.from_config(config) m.add("Your text here", user_id="user", metadata={"category": "example"}) ``` -------------------------------- ### Start Containers with Make Source: https://docs.mem0.ai/open-source/setup Use this command to start the Mem0 REST API and dashboard containers. It also runs necessary database migrations. The API will be available at http://localhost:8888 and the dashboard at http://localhost:3000. ```bash cd server make up ``` -------------------------------- ### MDX Template for Concept Guide Source: https://docs.mem0.ai/templates/concept_guide_template This MDX template provides a structured skeleton for creating concept guides. It includes frontmatter, definitions, key terms, lifecycle explanations, comparisons, and calls to action. Use this as a starting point for your concept documentation. ```mdx --- title: [Concept name] description: [One-sentence promise of understanding] icon: "lightbulb" --- # [Concept headline] [Define the concept in one sentence.] [Add an analogy or context hook.] **Why it matters** - [Impact bullet] - [Impact bullet] - [Impact bullet] ## Key terms - **[Term]** – [Short definition] - **[Term]** – [Short definition] {/* Optional: delete if not needed */} ```mermaid graph LR A[Input] --> B[Concept] B --> C[Outcome] ``` ## How does it work? [Explain lifecycle or architecture.] ```python # Minimal snippet that anchors the concept in code ``` [Nuance or best practice related to this concept.] ## When should you use it? - [Scenario 1] - [Scenario 2] - [Scenario 3] ## How it compares | Option | Best for | Trade-offs | | --- | --- | --- | | [Concept] | [Use case] | [Caveat] | | [Alternative] | [Use case] | [Caveat] | [Optional limitation or beta note.] Delete if not needed. ## Put it into practice - [Operation or feature doc that relies on this concept] - [Another supporting doc] ## See it live - [Cookbook or integration demonstrating the concept] - [Recording, demo, or sample repo] {/* DEBUG: verify CTA targets */} ``` -------------------------------- ### Basic Reranker Setup Source: https://docs.mem0.ai/open-source/features/reranker-search Configure Mem0 to use a reranker model for enhanced search relevance. This example uses the Cohere provider. ```python from mem0 import Memory config = { "reranker": { "provider": "cohere", "config": { "model": "rerank-english-v3.0", "api_key": "your-cohere-api-key" } } } m = Memory.from_config(config) ``` -------------------------------- ### Python: Set and Retrieve Project Custom Instructions Source: https://docs.mem0.ai/platform/features/custom-instructions Demonstrates how to set custom instructions for a project and then retrieve the currently configured instructions using the Mem0 client. ```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"]) ``` -------------------------------- ### Install Weaviate Client Source: https://docs.mem0.ai/components/vectordbs/dbs/weaviate Install the necessary Weaviate and Mem0 client libraries using pip. ```bash pip install weaviate weaviate-client ``` -------------------------------- ### Get Events in Java Source: https://docs.mem0.ai/api-reference/events/get-events A concise Java example using Unirest to retrieve events. Replace '' with your Mem0 API key for authentication. ```Java HttpResponse response = Unirest.get("https://api.mem0.ai/v1/events/") .header("Authorization", "Token ") .asString(); ``` -------------------------------- ### Navigate to Demo Directory Source: https://docs.mem0.ai/cookbooks/companions/quickstart-demo Change your current directory to the mem0-demo application folder within the cloned repository. ```bash cd mem0/examples/mem0-demo ``` -------------------------------- ### Get Memory Export with JavaScript SDK Source: https://docs.mem0.ai/api-reference/memory/get-memory-export Retrieve a memory export using the JavaScript SDK. Install the mem0ai package via npm. ```JavaScript // To use the JavaScript SDK, install the package: // npm i mem0ai import MemoryClient from 'mem0ai'; const client = new MemoryClient({ apiKey: "your-api-key" }); const memory_export_id = ""; // Get memory export client.getMemoryExport({ memory_export_id }) .then(result => console.log(result)) .catch(error => console.error(error)); ``` -------------------------------- ### Get Memory Export with Python SDK Source: https://docs.mem0.ai/api-reference/memory/get-memory-export Use the Python SDK to retrieve a memory export by its ID. Ensure you have installed the mem0ai package. ```Python # To use the Python SDK, install the package: # pip install mem0ai from mem0 import MemoryClient client = MemoryClient(api_key="your_api_key") memory_export_id = "" response = client.get_memory_export(memory_export_id=memory_export_id) print(response) ``` -------------------------------- ### Install Mem0 and Keywords AI SDKs Source: https://docs.mem0.ai/integrations/keywords Install the necessary Python libraries for Mem0 and Keywords AI. This is the first step before configuring the environment variables. ```bash pip install mem0ai keywordsai-sdk ``` -------------------------------- ### Install mem0.ai SDK with async extras (Python) Source: https://docs.mem0.ai/platform/advanced-memory-operations Install the Python SDK with asynchronous capabilities. Ensure you have Python 3.10+. ```bash pip install "mem0ai[async]" ``` -------------------------------- ### Get Project Details (cURL) Source: https://docs.mem0.ai/api-reference/project/get-project Example of how to retrieve project details using a cURL command. Replace '{org_id}', '{project_id}', and '' with your specific values. ```cURL curl --request GET \ --url https://api.mem0.ai/api/v1/orgs/organizations/{org_id}/projects/{project_id}/ \ --header 'Authorization: Token ' ``` -------------------------------- ### Get Project Details (JavaScript) Source: https://docs.mem0.ai/api-reference/project/get-project This JavaScript snippet shows how to fetch project details with the Mem0 SDK. Install the SDK using 'npm i mem0ai'. ```JavaScript // To use the JavaScript SDK, install the package: // npm i mem0ai import MemoryClient from 'mem0ai'; const client = new MemoryClient({ apiKey: "your-api-key" }); client.getProject() .then(response => console.log(response)) .catch(err => console.error(err)); ``` -------------------------------- ### Initialize Open-Source Mode with Ollama and Qdrant Source: https://docs.mem0.ai/integrations/openclaw Use this command for a fully local Open-Source setup with Ollama for LLM and embeddings, and Qdrant for vector storage. Ensure Ollama and Qdrant are running. ```bash # Fully local with Ollama + Qdrant openclaw mem0 init --mode open-source \ --oss-llm ollama --oss-embedder ollama --oss-vector qdrant ``` -------------------------------- ### Default Python Setup Source: https://docs.mem0.ai/templates/cookbook_template This snippet shows the default language setting for Python examples. Replace 'python' with the actual imports needed for your specific cookbook. ```python default_language = "python" # replace with real imports ``` -------------------------------- ### Get Memory with Python SDK Source: https://docs.mem0.ai/api-reference/memory/get-memory Use the Python SDK to fetch a memory by its ID. Ensure you have installed the SDK and replaced '' and 'your_api_key' with actual values. ```Python # To use the Python SDK, install the package: # pip install mem0ai from mem0 import MemoryClient client = MemoryClient(api_key="your_api_key") memory = client.get(memory_id="") ``` -------------------------------- ### MemoryClient Initialization (v0.x) Source: https://docs.mem0.ai/migration/api-changes Example of initializing MemoryClient in v0.x, where async_mode might require explicit setting. ```python from mem0 import MemoryClient client = MemoryClient(api_key="your-key") # async_mode had to be explicitly set or had different default result = client.add("content", user_id="alice", async_mode=True) ``` -------------------------------- ### Example Workflow: Seamless Task Continuation Source: https://docs.mem0.ai/integrations/claude-code This example demonstrates how Mem0 leverages its memory management across different sessions. It shows how Claude Code, with Mem0's assistance, can recall previous decisions and context, allowing for a more efficient and continuous workflow. ```text # Session 1: Working on a feature You: Let's refactor the auth module to use JWT tokens instead of sessions. # Claude searches memories, finds nothing relevant, proceeds with the work. # After completing the task, Mem0 stores: # - Decision: "Migrated auth from sessions to JWT tokens" # - Files modified: auth/middleware.ts, auth/token.ts # - User preference: "Prefers TypeScript, uses ESLint" # Session 2 (days later): Related work You: Add refresh token rotation to the auth system. # Claude searches memories, retrieves the JWT migration context. # Knows the file structure, decisions made, and user preferences. # Continues seamlessly without re-explaining the codebase. ``` -------------------------------- ### Get Project Webhooks (PHP) Source: https://docs.mem0.ai/api-reference/webhook/get-webhook Initiate a cURL request to retrieve all webhooks for a specific project using PHP. This snippet shows the setup for the cURL request. ```PHP