diff --git a/docs/cookbooks/essentials/building-ai-companion.mdx b/docs/cookbooks/essentials/building-ai-companion.mdx index 0885d798d..48f7c1347 100644 --- a/docs/cookbooks/essentials/building-ai-companion.mdx +++ b/docs/cookbooks/essentials/building-ai-companion.mdx @@ -1,5 +1,5 @@ --- -title: Build a Mem0 Companion +title: Build a Companion with Mem0 description: "Spin up a fitness coach that remembers goals, adapts tone, and keeps sessions personal." --- diff --git a/docs/cookbooks/overview.mdx b/docs/cookbooks/overview.mdx index fa7b3d8a5..53e33a5a2 100644 --- a/docs/cookbooks/overview.mdx +++ b/docs/cookbooks/overview.mdx @@ -16,17 +16,17 @@ Here are some examples of how Mem0 can be integrated into various applications: ## Essentials - - Learn the core memory lifecycle before diving into codebases. + + Learn core memory lifecycle patterns. - Balance personalization with consistent assistant behavior. + Balance personalization with consistent behavior. - Filter speculation, enforce formats, and gate low-confidence data. + Filter speculation and low-confidence data. - Define short-term versus long-term retention strategies. + Short-term vs long-term retention strategies. @@ -34,45 +34,27 @@ Here are some examples of how Mem0 can be integrated into various applications: - Spin up the showcase app to see Mem0 memories in action. - - - Build a JavaScript coach that remembers user goals. - - - Deliver lessons that adapt to student progress and gaps. - - - Plan itineraries that remember traveler preferences across trips. + See Mem0 memories in action. - Layer personalized context over any video in the browser. + Personalized context for video browsing. - Pair the OpenAI Agents SDK with Mem0 for voice-first experiences. - - - Run Mem0 end-to-end on your machine with Ollama models. + Voice-first experiences with Agents SDK. ## Ops & Automations - - Keep past tickets and resolutions at an agent's fingertips. - - Capture, categorize, and recall inbox threads via memory. + Capture and recall inbox threads. - Store tone and style guidelines once—apply them everywhere. + Store tone and style guidelines. - Run multi-session investigations without repeating yourself. - - - Coordinate projects with shared memories across contributors. + Multi-session investigations without repeating. @@ -80,25 +62,19 @@ Here are some examples of how Mem0 can be integrated into various applications: - Expose Mem0 memories as callable tools inside agent workflows. + Callable tools inside agent workflows. - Drop memories into OpenAI's inbuilt function-calling flows. + Memories in function-calling flows. - Extend Mastra agents with persistent memory state. + Persistent memory for Mastra agents. - Remember patient history across ADK sessions. - - - Pair Mem0 with Bedrock, OpenSearch, and Neptune Analytics. - - - Build a hybrid vector + graph memory store on AWS. + Patient history across ADK sessions. - Blend realtime search with personal context. + Realtime search with personal context. @@ -106,19 +82,19 @@ Here are some examples of how Mem0 can be integrated into various applications: - Teach a ReAct agent to store and recall context via Mem0. + ReAct agents with memory storage. - Share a persistent memory layer across collaborating agents. + Shared memory across collaborating agents. - Store and recall visual context alongside text conversations. + Visual context alongside text conversations. - Bring persistent personality to Eliza OS agents. + Persistent personality for Eliza agents. - Add Mem0's universal memory layer to Chrome chat surfaces. + Universal memory layer for Chrome. diff --git a/docs/integrations/agentops.mdx b/docs/integrations/agentops.mdx index cd89aa839..363ad0b72 100644 --- a/docs/integrations/agentops.mdx +++ b/docs/integrations/agentops.mdx @@ -163,10 +163,12 @@ Organize your monitoring with structured sessions: 4. **Tagging**: Use tags to organize different types of memory operations 5. **Environment Separation**: Use different projects or tags for dev/staging/prod -## Help + + + Monitor multi-agent CrewAI systems + + + Track LangChain agent performance + + -- [AgentOps Documentation](https://docs.agentops.ai/) -- [AgentOps Dashboard](https://app.agentops.ai/) -- [Mem0 Platform](https://app.mem0.ai/) - - \ No newline at end of file diff --git a/docs/integrations/agno.mdx b/docs/integrations/agno.mdx index c48dc5d15..27c357af2 100644 --- a/docs/integrations/agno.mdx +++ b/docs/integrations/agno.mdx @@ -195,9 +195,12 @@ Customize the integration to your needs: - **Memory Search**: Configure search relevance and result count - **Memory Formatting**: Support for various OpenAI message formats -## Help + + + Build agents with OpenAI SDK and Mem0 + + + Create intelligent agents with Mastra framework + + -- [Agno Documentation](https://docs.agno.com/introduction) -- [Mem0 Platform](https://app.mem0.ai/) - - diff --git a/docs/integrations/autogen.mdx b/docs/integrations/autogen.mdx index b645fa915..2c3c61397 100644 --- a/docs/integrations/autogen.mdx +++ b/docs/integrations/autogen.mdx @@ -130,6 +130,12 @@ By integrating AutoGen with Mem0, you've created a conversational AI system with This integration enables the creation of more intelligent and personalized AI agents for various applications, such as customer support, virtual assistants, and interactive chatbots. -## Help + + + Build multi-agent systems with CrewAI and Mem0 + + + Create stateful workflows with LangGraph + + - diff --git a/docs/integrations/aws-bedrock.mdx b/docs/integrations/aws-bedrock.mdx index b4498cb07..7a311f915 100644 --- a/docs/integrations/aws-bedrock.mdx +++ b/docs/integrations/aws-bedrock.mdx @@ -120,11 +120,12 @@ all_memories = m.get_all(user_id="alice") 4. **User-specific Memory Spaces**: Memories are isolated per user ID 5. **Persistent Memory Context**: Maintain and recall history across sessions -## Help - -- [AWS Bedrock Documentation](https://docs.aws.amazon.com/bedrock/) -- [Amazon OpenSearch Service Docs](https://docs.aws.amazon.com/opensearch-service/) -- [Mem0 Platform](https://app.mem0.ai) - - + + + Complete guide to using Bedrock with Mem0 + + + Build graph memory with AWS Neptune + + diff --git a/docs/integrations/crewai.mdx b/docs/integrations/crewai.mdx index 17d0a664f..f40886ca9 100644 --- a/docs/integrations/crewai.mdx +++ b/docs/integrations/crewai.mdx @@ -160,9 +160,12 @@ if __name__ == "__main__": By combining CrewAI with Mem0, you can create sophisticated AI systems that maintain context and provide personalized experiences while leveraging the power of autonomous agents. -## Help + + + Build multi-agent systems with AutoGen and Mem0 + + + Create stateful agent workflows with memory + + -- [CrewAI Documentation](https://docs.crewai.com/) -- [Mem0 Platform](https://app.mem0.ai/) - - diff --git a/docs/integrations/dify.mdx b/docs/integrations/dify.mdx index e08b367bf..ce6178fea 100644 --- a/docs/integrations/dify.mdx +++ b/docs/integrations/dify.mdx @@ -31,4 +31,11 @@ Mem0 brings a robust memory layer to Dify AI, empowering your AI agents with per Enhance your Dify-powered AI with Mem0 and transform your conversational experiences. Start integrating intelligent memory management today and give your agents the context they need to excel! -[Explore Mem0 on Dify Marketplace](https://marketplace.dify.ai/plugins/yevanchen/mem0) \ No newline at end of file + + + Build visual AI workflows with Flowise + + + Create LangChain-powered applications + + diff --git a/docs/integrations/elevenlabs.mdx b/docs/integrations/elevenlabs.mdx index 71ce97403..2e3792215 100644 --- a/docs/integrations/elevenlabs.mdx +++ b/docs/integrations/elevenlabs.mdx @@ -436,9 +436,12 @@ By integrating ElevenLabs Conversational AI with Mem0, you can create voice agen - Reduced need for users to repeat information - Long-term relationship building between users and AI agents -## Help + + + Build real-time voice and video agents + + + Create voice-first AI applications + + -- [ElevenLabs Conversational AI Documentation](https://elevenlabs.io/docs/api-reference/conversational-ai) -- [Mem0 Platform](https://app.mem0.ai/) - - \ No newline at end of file diff --git a/docs/integrations/flowise.mdx b/docs/integrations/flowise.mdx index d21b2b7f5..743579526 100644 --- a/docs/integrations/flowise.mdx +++ b/docs/integrations/flowise.mdx @@ -115,11 +115,12 @@ Additional settings available in [Mem0 Project Settings](https://app.mem0.ai/das 2. **Memory Organization**: Utilize projects and organizations for better memory management 3. **Regular Maintenance**: Monitor and clean up unused memories periodically -## Help + + + Build LangChain-powered flows with memory + + + Create AI workflows with Dify platform + + -- [Flowise Documentation](https://flowiseai.com/docs) -- [Flowise GitHub Repository](https://github.com/FlowiseAI/Flowise) -- [Flowise Website](https://flowiseai.com/) -- [Mem0 Platform](https://app.mem0.ai/) - - \ No newline at end of file diff --git a/docs/integrations/google-ai-adk.mdx b/docs/integrations/google-ai-adk.mdx index 774c1456a..4a520a99d 100644 --- a/docs/integrations/google-ai-adk.mdx +++ b/docs/integrations/google-ai-adk.mdx @@ -285,9 +285,12 @@ os.environ["GOOGLE_CLOUD_PROJECT"] = "your-project-id" os.environ["GOOGLE_CLOUD_LOCATION"] = "us-central1" ``` -## Help + + + Build HIPAA-compliant healthcare agents with Google ADK + + + Compare with OpenAI's agent framework + + -- [Google ADK Documentation](https://google.github.io/adk-docs/) -- [Mem0 Platform](https://app.mem0.ai/) - - \ No newline at end of file diff --git a/docs/integrations/keywords.mdx b/docs/integrations/keywords.mdx index d5c681761..e6def67cd 100644 --- a/docs/integrations/keywords.mdx +++ b/docs/integrations/keywords.mdx @@ -131,9 +131,12 @@ For detailed information on this integration, refer to the official [Keywords AI Integrating Mem0 with Keywords AI provides a powerful combination for building AI applications with persistent memory and comprehensive observability. This integration enables more personalized user experiences while providing insights into your application's memory usage. -## Help + + + Build monitored agents with OpenAI SDK + + + Monitor agent performance with AgentOps + + -- [Keywords AI Documentation](https://docs.keywordsai.co) -- [Mem0 Platform](https://app.mem0.ai/) - - diff --git a/docs/integrations/langchain-tools.mdx b/docs/integrations/langchain-tools.mdx index 9a51ab48a..3710107b6 100644 --- a/docs/integrations/langchain-tools.mdx +++ b/docs/integrations/langchain-tools.mdx @@ -320,6 +320,12 @@ All tools are implemented as Langchain `StructuredTool` instances, making them c Each tool provides structured input validation through Pydantic models and returns consistent responses that can be processed by your agent. -## Help + + + Build conversational agents with LangChain and Mem0 + + + Create stateful workflows with LangGraph + + - diff --git a/docs/integrations/langchain.mdx b/docs/integrations/langchain.mdx index 5d89494b3..62034a044 100644 --- a/docs/integrations/langchain.mdx +++ b/docs/integrations/langchain.mdx @@ -161,10 +161,13 @@ if __name__ == "__main__": By integrating LangChain with Mem0, you can build a personalized Travel Agent AI that can maintain context across interactions and provide tailored travel recommendations and assistance. -## Help + + + Build stateful agents with LangGraph and Mem0 + + + Use Mem0 as LangChain tools for agent workflows + + -- [LangChain Documentation](https://python.langchain.com/) -- [Mem0 Platform](https://app.mem0.ai/) - - diff --git a/docs/integrations/langgraph.mdx b/docs/integrations/langgraph.mdx index 17e80aa75..59ac494bd 100644 --- a/docs/integrations/langgraph.mdx +++ b/docs/integrations/langgraph.mdx @@ -163,9 +163,12 @@ if __name__ == "__main__": By integrating LangGraph with Mem0, you can build a personalized Customer Support AI Agent that can maintain context across interactions and provide personalized assistance. -## Help + + + Build conversational agents with LangChain and Mem0 + + + Create multi-agent systems with CrewAI + + -- [LangGraph Documentation](https://python.langchain.com/docs/langgraph) -- [Mem0 Platform](https://app.mem0.ai/) - - diff --git a/docs/integrations/livekit.mdx b/docs/integrations/livekit.mdx index 3b77b7209..9f0004301 100644 --- a/docs/integrations/livekit.mdx +++ b/docs/integrations/livekit.mdx @@ -228,10 +228,12 @@ logger = logging.getLogger("memory_voice_agent") - Check the logs for any issues with API keys, connectivity, or memory operations. - Ensure your `.env` file is correctly configured and loaded. + + + Build conversational voice agents with ElevenLabs + + + Create real-time voice applications with Pipecat + + -## Help - -- [LiveKit Documentation](https://docs.livekit.io/) -- [Mem0 Platform](https://app.mem0.ai/) - - diff --git a/docs/integrations/llama-index.mdx b/docs/integrations/llama-index.mdx index 1a6cb83d0..3ce30c634 100644 --- a/docs/integrations/llama-index.mdx +++ b/docs/integrations/llama-index.mdx @@ -204,13 +204,12 @@ print(response) By integrating LlamaIndex with Mem0, you can build a personalized agent that can maintain context across interactions with the agent and provide tailored recommendations and assistance. -## Help - -- [LlamaIndex Documentation](https://llamahub.ai/l/memory/llama-index-memory-mem0) -- [Mem0 Platform](https://app.mem0.ai/) - - - - - + + + Build multi-agent systems with LlamaIndex and Mem0 + + + Create ReAct agents with LlamaIndex + + diff --git a/docs/integrations/mastra.mdx b/docs/integrations/mastra.mdx index bf36eb3ba..e3b0b4ccb 100644 --- a/docs/integrations/mastra.mdx +++ b/docs/integrations/mastra.mdx @@ -125,9 +125,12 @@ const mem0Agent = new Agent({ By integrating Mastra with Mem0, you can build intelligent agents that learn and remember information across conversations. The tool-based approach provides transparency and control over memory operations, making it easy to create personalized and context-aware AI experiences. -## Help + + + Build a complete Mastra agent with persistent memory + + + Create web applications with Vercel AI SDK + + -- [Mastra Documentation](https://docs.mastra.ai/) -- [Mem0 Platform](https://app.mem0.ai/) - - \ No newline at end of file diff --git a/docs/integrations/openai-agents-sdk.mdx b/docs/integrations/openai-agents-sdk.mdx index 81cf3889b..32d216622 100644 --- a/docs/integrations/openai-agents-sdk.mdx +++ b/docs/integrations/openai-agents-sdk.mdx @@ -225,9 +225,12 @@ mem0.add( ) ``` -## Help + + + Learn how to integrate Mem0 with OpenAI function calling + + + Build agents with OpenAI SDK tools + + -- [OpenAI Agents SDK Documentation](https://openai.github.io/openai-agents-python/) -- [Mem0 Platform](https://app.mem0.ai/) - - \ No newline at end of file diff --git a/docs/integrations/pipecat.mdx b/docs/integrations/pipecat.mdx index 626edb29b..ef6ca3a9a 100644 --- a/docs/integrations/pipecat.mdx +++ b/docs/integrations/pipecat.mdx @@ -211,8 +211,12 @@ memory = Mem0MemoryService( ) ``` -## Resources - -- [Mem0 Pipecat Integration](https://docs.pipecat.ai/server/services/memory/mem0) -- [Pipecat Documentation](https://docs.pipecat.ai) + + + Build real-time voice and video agents + + + Create conversational voice agents + + diff --git a/docs/integrations/raycast.mdx b/docs/integrations/raycast.mdx index 5e589b4eb..9c9753b4b 100644 --- a/docs/integrations/raycast.mdx +++ b/docs/integrations/raycast.mdx @@ -40,6 +40,11 @@ d. Enter this key in the extension preferences **No More Repetition**: Stop explaining the same things repeatedly. Your AI remembers your context and preferences. ---- - - + + + Build desktop AI agents with OpenAI SDK + + + Create intelligent desktop workflows + + diff --git a/docs/integrations/vercel-ai-sdk.mdx b/docs/integrations/vercel-ai-sdk.mdx index ab486211e..21d464bf0 100644 --- a/docs/integrations/vercel-ai-sdk.mdx +++ b/docs/integrations/vercel-ai-sdk.mdx @@ -314,11 +314,14 @@ The `getMemories` function will return an object with two keys: `results` and `r ## Conclusion -Mem0’s Vercel AI SDK enables the creation of intelligent, context-aware applications with persistent memory and seamless integration. +Mem0's Vercel AI SDK enables the creation of intelligent, context-aware applications with persistent memory and seamless integration. -## Help + + + Build agents with OpenAI SDK and Mem0 + + + Create intelligent agents with Mastra framework + + -- [Vercel AI SDK Documentation](https://sdk.vercel.ai/docs/introduction) -- [Mem0 Platform](https://app.mem0.ai/) - - \ 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 4cadb341f..f19425bba 100644 --- a/docs/open-source/features/async-memory.mdx +++ b/docs/open-source/features/async-memory.mdx @@ -1,24 +1,62 @@ --- title: Async Memory -description: 'Asynchronous memory for Mem0' +description: Run Mem0 operations without blocking your event loop. +icon: "bolt" --- -## AsyncMemory +`AsyncMemory` gives you a non-blocking interface to Mem0’s storage layer so Python applications can add, search, and manage memories directly from async code. Use it when you embed Mem0 inside FastAPI services, background workers, or any workflow that relies on `asyncio`. -The `AsyncMemory` class is a direct asynchronous interface to Mem0's in-process memory operations. Unlike the synchronous memory class, 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. + + **You’ll use this when…** + - Your agent already runs in an async framework and you need memory calls to await cleanly. + - You want to embed Mem0’s storage locally without sending requests through the synchronous client. + - You plan to mix memory operations with other async APIs (OpenAI, HTTP calls, databases). + -### Initialization + + `AsyncMemory` expects a running event loop. Always call it inside `async def` functions or through helpers like `asyncio.run()` to avoid runtime errors. + -To use `AsyncMemory`, import it from the `mem0.memory` module: + + Working in TypeScript? The Node SDK still uses synchronous calls—use `Memory` there and rely on Python’s `AsyncMemory` when you need awaited operations. + -```python Python +## Feature anatomy + +- **Direct storage access:** `AsyncMemory` talks to the same backends as the synchronous client but keeps everything in-process for lower latency. +- **Method parity:** Each memory operation (`add`, `search`, `get_all`, `delete`, etc.) mirrors the synchronous API, letting you reuse payload shapes. +- **Concurrent execution:** Non-blocking I/O lets you schedule multiple memory tasks with `asyncio.gather`. +- **Scoped organization:** Continue using `user_id`, `agent_id`, and `run_id` to separate memories across sessions and agents. + + + + | Operation | Async signature | Notes | + | --- | --- | --- | + | Create memories | `await memory.add(...)` | Same arguments as synchronous `Memory.add`. | + | Search memories | `await memory.search(...)` | Returns dict with `results`, identical shape. | + | List memories | `await memory.get_all(...)` | Filter by `user_id`, `agent_id`, `run_id`. | + | Retrieve memory | `await memory.get(memory_id=...)` | Raises `ValueError` if ID is invalid. | + | Update memory | `await memory.update(memory_id=..., data=...)` | Accepts partial updates. | + | Delete memory | `await memory.delete(memory_id=...)` | Returns confirmation payload. | + | Delete in bulk | `await memory.delete_all(...)` | Requires at least one scope filter. | + | History | `await memory.history(memory_id=...)` | Fetches change log for auditing. | + + + +--- + +## Configure it + +### Initialize the client + +```python import asyncio from mem0 import AsyncMemory -# Initialize with default configuration +# Default configuration memory = AsyncMemory() -# Or initialize with custom configuration +# Custom configuration from mem0.configs.base import MemoryConfig custom_config = MemoryConfig( # Your custom configuration here @@ -26,301 +64,20 @@ custom_config = MemoryConfig( memory = AsyncMemory(config=custom_config) ``` -### Key Features + + Run `await memory.search(...)` once right after initialization. If it returns memories without errors, your configuration works. + -1. **Non-blocking Operations**: All memory operations use `asyncio` to avoid blocking the event loop. -2. **Concurrent Processing**: Parallel execution of vector store and graph operations. -3. **Efficient Resource Utilization**: Better handling of I/O-bound operations. -4. **Compatible with Async Frameworks**: Seamless integration with FastAPI, aiohttp, and other async frameworks. + + Keep configuration objects close to the async client so you can reuse them across workers without recreating vector store connections. + -### Methods +### Manage lifecycle and concurrency -All methods in `AsyncMemory` have the same parameters as the synchronous `Memory` class but are designed to be used with `async/await`. - -#### Create memories - -Add a new memory asynchronously: - -```python Python -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 - -Retrieve memories related to a query: - -```python Python -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 - -List all memories for a `user_id`, `agent_id`, and/or `run_id`: - -```python Python -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 - -Retrieve a specific memory by its ID: - -```python Python -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 - -Update an existing memory by ID: - -```python Python -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 - -Delete a specific memory by ID: - -```python Python -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 - -Delete all memories for a specific user, agent, or run: - -```python Python -try: - result = await memory.delete_all(user_id="alice") - print("All memories deleted successfully") -except Exception as e: - print(f"Error deleting memories: {e}") -``` - - -At least one filter (user_id, agent_id, or run_id) is required when using delete_all. - - -### Advanced Memory Organization - -AsyncMemory supports the same three-parameter organization system as the synchronous Memory class: - -```python Python -# Store memories with full context -await memory.add( - messages=[{"role": "user", "content": "I prefer vegetarian food"}], - user_id="alice", - agent_id="diet-assistant", - run_id="consultation-001" -) - -# Retrieve memories with different scopes -all_user_memories = await memory.get_all(user_id="alice") -agent_memories = await memory.get_all(user_id="alice", agent_id="diet-assistant") -session_memories = await memory.get_all(user_id="alice", run_id="consultation-001") -specific_memories = await memory.get_all( - user_id="alice", - agent_id="diet-assistant", - run_id="consultation-001" -) - -# Search with context -general_search = await memory.search("What do you know about me?", user_id="alice") -agent_search = await memory.search("What do you know about me?", user_id="alice", agent_id="diet-assistant") -session_search = await memory.search("What do you know about me?", user_id="alice", run_id="consultation-001") -``` - -#### Memory History - -Get the history of changes for a specific memory: - -```python Python -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 - -`AsyncMemory` can be effectively combined with other async operations. Here's an example showing how to use it alongside OpenAI API calls: - -```python Python -import asyncio -from openai import AsyncOpenAI -from mem0 import AsyncMemory - -async_openai_client = AsyncOpenAI() -async_memory = AsyncMemory() - -async def chat_with_memories(message: str, user_id: str = "default_user") -> str: - 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-4.1-nano-2025-04-14", 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) - - 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)") - while True: - user_input = input("You: ").strip() - if user_input.lower() == 'exit': - print("Goodbye!") - break - response = await chat_with_memories(user_input) - print(f"AI: {response}") - -def main(): - asyncio.run(async_main()) - -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-4.1-nano-2025-04-14"}} - ) - 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 +```python import asyncio from contextlib import asynccontextmanager +from mem0 import AsyncMemory @asynccontextmanager async def get_memory(): @@ -333,56 +90,227 @@ async def get_memory(): 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 + return await memory.search("test query", user_id="alice") ``` -### Timeout and Retry Strategies + + Wrap the client in an async context manager when you need a clean shutdown (for example, inside FastAPI startup/shutdown hooks). + -Implement timeout and retry logic for robustness: +```python +async def batch_operations(): + memory = AsyncMemory() + + tasks = [ + memory.add( + messages=[{"role": "user", "content": f"Message {i}"}], + user_id=f"user_{i}" + ) + for i in range(5) + ] + + 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") +``` + + + When concurrency works correctly, successful tasks return memory IDs while failures surface as exceptions in the `results` list. + + +### Add resilience with retries + +```python +import asyncio +from mem0 import AsyncMemory -```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 + return await asyncio.wait_for(operation(), timeout=timeout) except asyncio.TimeoutError: print(f"Timeout on attempt {attempt + 1}") - except Exception as e: - print(f"Error on attempt {attempt + 1}: {e}") - + except Exception as exc: + print(f"Error on attempt {attempt + 1}: {exc}") + if attempt < max_retries - 1: - await asyncio.sleep(2 ** attempt) # Exponential backoff - + await asyncio.sleep(2 ** attempt) + 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}") + + return await with_timeout_and_retry(search_operation) ``` -### Integration with Async Frameworks + + Always cap retries—runaway loops can keep the event loop busy and block other tasks. + -#### FastAPI Integration +--- -```python Python +## See it in action + +### Core operations + +```python +# Create memories +result = await memory.add( + messages=[ + {"role": "user", "content": "I'm travelling to SF"}, + {"role": "assistant", "content": "That's great to hear!"} + ], + user_id="alice" +) + +# Search memories +results = await memory.search( + query="Where am I travelling?", + user_id="alice" +) + +# List memories +all_memories = await memory.get_all(user_id="alice") + +# Get a specific memory +specific_memory = await memory.get(memory_id="memory-id-here") + +# Update a memory +updated_memory = await memory.update( + memory_id="memory-id-here", + data="I'm travelling to Seattle" +) + +# Delete a memory +await memory.delete(memory_id="memory-id-here") + +# Delete scoped memories +await memory.delete_all(user_id="alice") +``` + + + Confirm each call returns the same response fields as the synchronous client (IDs, `results`, or confirmation objects). Missing keys usually mean the coroutine wasn’t awaited. + + + + `delete_all` requires at least one of `user_id`, `agent_id`, or `run_id`. Provide all three to narrow deletion to a single session. + + +### Scoped organization + +```python +await memory.add( + messages=[{"role": "user", "content": "I prefer vegetarian food"}], + user_id="alice", + agent_id="diet-assistant", + run_id="consultation-001" +) + +all_user_memories = await memory.get_all(user_id="alice") +agent_memories = await memory.get_all(user_id="alice", agent_id="diet-assistant") +session_memories = await memory.get_all(user_id="alice", run_id="consultation-001") +specific_memories = await memory.get_all( + user_id="alice", + agent_id="diet-assistant", + run_id="consultation-001" +) + +history = await memory.history(memory_id="memory-id-here") +``` + + + Use `history` when you need audit trails for compliance or debugging update logic. + + +### Blend with other async APIs + +```python +import asyncio +from openai import AsyncOpenAI +from mem0 import AsyncMemory + +async_openai_client = AsyncOpenAI() +async_memory = AsyncMemory() + +async def chat_with_memories(message: str, user_id: str = "default_user") -> str: + 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) + + system_prompt = ( + "You are a helpful AI. Answer the question based on query and memories.\n" + f"User Memories:\n{memories_str}" + ) + + messages = [ + {"role": "system", "content": system_prompt}, + {"role": "user", "content": message}, + ] + + response = await async_openai_client.chat.completions.create( + model="gpt-4.1-nano-2025-04-14", + messages=messages + ) + + assistant_response = response.choices[0].message.content + messages.append({"role": "assistant", "content": assistant_response}) + await async_memory.add(messages, user_id=user_id) + + return assistant_response +``` + + + When everything is wired correctly, the OpenAI response should incorporate recent memories and the follow-up `add` call should persist the new assistant turn. + + +### Handle errors gracefully + +```python +from mem0 import AsyncMemory +from mem0.configs.base import MemoryConfig + +async def handle_initialization_errors(): + try: + config = MemoryConfig( + vector_store={"provider": "chroma", "config": {"path": "./chroma_db"}}, + llm={"provider": "openai", "config": {"model": "gpt-4.1-nano-2025-04-14"}} + ) + AsyncMemory(config=config) + print("AsyncMemory initialized successfully") + except ValueError as err: + print(f"Configuration error: {err}") + except ConnectionError as err: + print(f"Connection error: {err}") + +async def handle_memory_operation_errors(): + memory = AsyncMemory() + try: + await memory.get(memory_id="non-existent-id") + except ValueError as err: + print(f"Invalid memory ID: {err}") + + try: + await memory.search(query="", user_id="alice") + except ValueError as err: + print(f"Invalid search query: {err}") +``` + + + Catch and log `ValueError` exceptions from invalid inputs—async stack traces can otherwise disappear inside background tasks. + + +### Serve through FastAPI + +```python from fastapi import FastAPI, HTTPException from mem0 import AsyncMemory -import asyncio app = FastAPI() memory = AsyncMemory() @@ -392,33 +320,25 @@ 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)) + except Exception as exc: + raise HTTPException(status_code=500, detail=str(exc)) @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)) + except Exception as exc: + raise HTTPException(status_code=500, detail=str(exc)) ``` -### Troubleshooting Guide + + Create one `AsyncMemory` instance per process when using FastAPI—startup hooks are a good place to configure and reuse it. + -| 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 | +### Instrument logging -### Monitoring and Logging - -Add comprehensive logging to your async memory operations: - -```python Python +```python import logging import time from functools import wraps @@ -437,9 +357,9 @@ def log_async_operation(operation_name): duration = time.time() - start_time logger.info(f"{operation_name} completed in {duration:.2f}s") return result - except Exception as e: + except Exception as exc: duration = time.time() - start_time - logger.error(f"{operation_name} failed after {duration:.2f}s: {e}") + logger.error(f"{operation_name} failed after {duration:.2f}s: {exc}") raise return wrapper return decorator @@ -449,6 +369,48 @@ 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: + + Logged durations give you the baseline needed to spot regressions once AsyncMemory is in production. + - +--- + +## Verify the feature is working + +- Run a quick add/search cycle and confirm the returned memory content matches your input. +- Inspect application logs to ensure async tasks complete without blocking the event loop. +- In FastAPI or other frameworks, hit health endpoints to verify the shared client handles concurrent requests. +- Monitor retry counters—unexpected spikes indicate configuration or connectivity issues. + +--- + +## Best practices + +1. **Keep operations awaited:** Forgetting `await` is the fastest way to miss writes—lint for it or add helper wrappers. +2. **Scope deletions carefully:** Always supply `user_id`, `agent_id`, or `run_id` to avoid purging too much data. +3. **Batch writes thoughtfully:** Use `asyncio.gather` for throughput but cap concurrency based on backend capacity. +4. **Log errors with context:** Capture user and agent scopes to triage failures quickly. +5. **Reuse clients:** Instantiate `AsyncMemory` once per worker to avoid repeated backend handshakes. + +--- + +## Troubleshooting + +| Issue | Possible causes | Fix | +| --- | --- | --- | +| Initialization fails | Missing dependencies, invalid config | Validate `MemoryConfig` settings and environment variables. | +| Slow operations | Large datasets, network latency | Cache heavy queries and tune vector store parameters. | +| Memory not found | Invalid ID or deleted record | Check ID source and handle soft-deleted states. | +| Connection timeouts | Network issues, overloaded backend | Apply retries/backoff and inspect infrastructure health. | +| Out-of-memory errors | Oversized batches | Reduce concurrency or chunk operations into smaller sets. | + +--- + + + + Review how add, search, update, and delete behave across synchronous and async clients. + + + Follow a full workflow that mixes AsyncMemory with OpenAI tool-call automation. + + diff --git a/docs/open-source/features/custom-fact-extraction-prompt.mdx b/docs/open-source/features/custom-fact-extraction-prompt.mdx index 8ac5c44e8..3738becbd 100644 --- a/docs/open-source/features/custom-fact-extraction-prompt.mdx +++ b/docs/open-source/features/custom-fact-extraction-prompt.mdx @@ -1,18 +1,45 @@ --- title: Custom Fact Extraction Prompt -description: 'Enhance your product experience by adding custom fact extraction prompt tailored to your needs' +description: Tailor fact extraction so Mem0 stores only the details you care about. +icon: "wand-magic-sparkles" --- -## Introduction to Custom Fact Extraction Prompt +Custom fact extraction prompts let you decide exactly which facts Mem0 records from a conversation. Define a focused prompt, give a few examples, and Mem0 will add only the memories that match your use case. -Custom fact extraction prompts allow you to tailor the behavior of your Mem0 instance to specific use cases or domains. By defining them, you can control how information is extracted from the user's messages. + + **You’ll use this when…** + - A project needs domain-specific facts (order numbers, customer info) without storing casual chatter. + - You already have a clear schema for memories and want the LLM to follow it. + - You must prevent irrelevant details from entering long-term storage. + -To create an effective custom fact extraction prompt: -1. Be specific about the information to extract. -2. Provide few-shot examples to guide the LLM. -3. Ensure examples follow the format shown below. + + Prompts that are too broad cause unrelated facts to slip through. Keep instructions tight and test them with real transcripts. + -Example of a custom fact extraction prompt: +--- + +## Feature anatomy + +- **Prompt instructions:** Describe which entities or phrases to keep. Specific guidance keeps the extractor focused. +- **Few-shot examples:** Show positive and negative cases so the model copies the right format. +- **Structured output:** Responses return JSON with a `facts` array that Mem0 converts into individual memories. +- **LLM configuration:** `custom_fact_extraction_prompt` (Python) or `customPrompt` (TypeScript) lives alongside your model settings. + + + + 1. State the allowed fact types. + 2. Include short examples that mirror production messages. + 3. Show both empty (`[]`) and populated outputs. + 4. Remind the model to return JSON with a `facts` key only. + + + +--- + +## Configure it + +### Write the custom prompt ```python Python @@ -21,25 +48,25 @@ Please only extract entities containing customer support information, order deta Here are some few shot examples: Input: Hi. -Output: {{"facts" : []}} +Output: {"facts" : []} Input: The weather is nice today. -Output: {{"facts" : []}} +Output: {"facts" : []} Input: My order #12345 hasn't arrived yet. -Output: {{"facts" : ["Order #12345 not received"]}} +Output: {"facts" : ["Order #12345 not received"]} Input: I'm John Doe, and I'd like to return the shoes I bought last week. -Output: {{"facts" : ["Customer name: John Doe", "Wants to return shoes", "Purchase made last week"]}} +Output: {"facts" : ["Customer name: John Doe", "Wants to return shoes", "Purchase made last week"]} Input: I ordered a red shirt, size medium, but received a blue one instead. -Output: {{"facts" : ["Ordered red shirt, size medium", "Received blue shirt instead"]}} +Output: {"facts" : ["Ordered red shirt, size medium", "Received blue shirt instead"]} Return the facts and customer information in a json format as shown above. """ ``` -```typescript TypeScript +```ts TypeScript const customPrompt = ` Please only extract entities containing customer support information, order details, and user information. Here are some few shot examples: @@ -64,7 +91,11 @@ Return the facts and customer information in a json format as shown above. ``` -Here we initialize the custom fact extraction prompt in the config: + + Keep example pairs short and mirror the capitalization, punctuation, and tone you see in real user messages. + + +### Load the prompt in configuration ```python Python @@ -86,72 +117,71 @@ config = { m = Memory.from_config(config_dict=config) ``` -```typescript TypeScript -import { Memory } from 'mem0ai/oss'; +```ts TypeScript +import { Memory } from "mem0ai/oss"; const config = { - version: 'v1.1', + version: "v1.1", llm: { - provider: 'openai', + provider: "openai", config: { - apiKey: process.env.OPENAI_API_KEY || '', - model: 'gpt-4-turbo-preview', + apiKey: process.env.OPENAI_API_KEY ?? "", + model: "gpt-4-turbo-preview", temperature: 0.2, maxTokens: 1500, }, }, - customPrompt: customPrompt + customPrompt: customPrompt, }; const memory = new Memory(config); ``` -### Example 1 + + After initialization, run a quick `add` call with a known example and confirm the response splits into separate facts. + -In this example, we are adding a memory of a user ordering a laptop. As seen in the output, the custom prompt is used to extract the relevant information from the user's message. +--- + +## See it in action + +### Example: Order support memory ```python Python m.add("Yesterday, I ordered a laptop, the order id is 12345", user_id="alice") ``` -```typescript TypeScript -await memory.add('Yesterday, I ordered a laptop, the order id is 12345', { userId: "user123" }); +```ts TypeScript +await memory.add("Yesterday, I ordered a laptop, the order id is 12345", { userId: "user123" }); ``` ```json Output { "results": [ - { - "memory": "Ordered a laptop", - "event": "ADD" - }, - { - "memory": "Order ID: 12345", - "event": "ADD" - }, - { - "memory": "Order placed yesterday", - "event": "ADD" - } + {"memory": "Ordered a laptop", "event": "ADD"}, + {"memory": "Order ID: 12345", "event": "ADD"}, + {"memory": "Order placed yesterday", "event": "ADD"} ], "relations": [] } ``` -### Example 2 + + The output contains only the facts described in your prompt, each stored as a separate memory entry. + -In this example, we are adding a memory of a user liking to go on hikes. This message is not specific to the use case mentioned in the custom prompt. Hence, the memory is not added. +### Example: Irrelevant message filtered out ```python Python m.add("I like going to hikes", user_id="alice") ``` -```typescript TypeScript -await memory.add('I like going to hikes', { userId: "user123" }); +```ts TypeScript +await memory.add("I like going to hikes", { userId: "user123" }); ``` ```json Output @@ -162,4 +192,35 @@ await memory.add('I like going to hikes', { userId: "user123" }); ``` -The custom fact extraction prompt will process both the user and assistant messages to extract relevant information according to the defined format. + + Empty `results` show the prompt successfully ignored content outside your target domain. + + +--- + +## Verify the feature is working + +- Log every call during rollout and confirm the `facts` array matches your schema. +- Check that unrelated messages return an empty `results` array. +- Run regression samples whenever you edit the prompt to ensure previously accepted facts still pass. + +--- + +## Best practices + +1. **Be precise:** Call out the exact categories or fields you want to capture. +2. **Show negative cases:** Include examples that should produce `[]` so the model learns to skip them. +3. **Keep JSON strict:** Avoid extra keys; only return `facts` to simplify downstream parsing. +4. **Version prompts:** Track prompt changes with a version number so you can roll back quickly. +5. **Review outputs regularly:** Spot-check stored memories to catch drift early. + +--- + + + + Refresh how Mem0 stores memories and how prompts influence fact creation. + + + Apply custom extraction to route customer requests in a full workflow. + + diff --git a/docs/open-source/features/custom-update-memory-prompt.mdx b/docs/open-source/features/custom-update-memory-prompt.mdx index 81d1c5703..06ce6566a 100644 --- a/docs/open-source/features/custom-update-memory-prompt.mdx +++ b/docs/open-source/features/custom-update-memory-prompt.mdx @@ -1,22 +1,47 @@ --- title: Custom Update Memory Prompt -description: 'Control memory update actions with a custom prompt' +description: Decide how Mem0 adds, updates, or deletes memories using your own rules. +icon: "arrows-rotate" --- +The custom update memory prompt tells Mem0 how to handle changes when new facts arrive. Craft the prompt so the LLM can compare incoming facts with existing memories and choose the right action. -The update memory prompt is used to determine the action to be performed on the memory. By customizing this prompt, you can control how the memory is updated. + + **You’ll use this when…** + - Stored memories need to stay consistent as users change preferences or correct past statements. + - Your product has clear rules for when to add, update, delete, or leave a memory untouched. + - You want traceable decisions (ADD, UPDATE, DELETE, NONE) for auditing or compliance. + -## Introduction + + Prompts that mix instructions or omit examples can lead to wrong actions like deleting valid memories. Keep the language simple and test each action path. + -The Mem0 memory system compares newly retrieved facts with existing memory and determines the action to be performed. The types of actions are: -- **Add**: Add the newly retrieved facts to the memory. -- **Update**: Update the existing memory with the newly retrieved facts. -- **Delete**: Delete the existing memory. -- **No Change**: Do not make any changes to the memory. +--- -### Example +## Feature anatomy -Example of a custom update memory prompt: +- **Action verbs:** The prompt teaches the model to return `ADD`, `UPDATE`, `DELETE`, or `NONE` for every memory entry. +- **ID retention:** Updates reuse the original memory ID so downstream systems maintain history. +- **Old vs. new text:** Updates include `old_memory` so you can track what changed. +- **Decision table:** Your prompt should explain when to use each action and show concrete examples. + + + + | Action | When to choose it | Output details | + | --- | --- | --- | + | `ADD` | Fact is new and not stored yet | Generate a new ID and set `event: "ADD"`. | + | `UPDATE` | Fact replaces older info about the same topic | Keep the original ID, include `old_memory`. | + | `DELETE` | Fact contradicts the stored memory or you explicitly remove it | Keep ID, set `event: "DELETE"`. | + | `NONE` | Fact matches existing memory or is irrelevant | Keep ID with `event: "NONE"`. | + + + +--- + +## Configure it + +### Author the prompt ```python Python @@ -170,67 +195,112 @@ Please note to return the IDs in the output from the input IDs only and do not g } """ ``` - + -## Output Format +### Define the expected output format -The prompt needs to guide the output to follow the structure as shown below: ```json Add { - "memory": [ - { - "id" : "0", - "text" : "This information is new", - "event" : "ADD" - } - ] + "memory": [ + { + "id": "0", + "text": "This information is new", + "event": "ADD" + } + ] } ``` ```json Update { - "memory": [ - { - "id" : "0", - "text" : "This information replaces the old information", - "event" : "UPDATE", - "old_memory" : "Old information" - } - ] + "memory": [ + { + "id": "0", + "text": "This information replaces the old information", + "event": "UPDATE", + "old_memory": "Old information" + } + ] } ``` ```json Delete { - "memory": [ - { - "id" : "0", - "text" : "This information will be deleted", - "event" : "DELETE" - } - ] + "memory": [ + { + "id": "0", + "text": "This information will be deleted", + "event": "DELETE" + } + ] } ``` ```json No Change { - "memory": [ - { - "id" : "0", - "text" : "No changes for this information", - "event" : "NONE" - } - ] + "memory": [ + { + "id": "0", + "text": "No changes for this information", + "event": "NONE" + } + ] } ``` - - -## Custom Update Memory Prompt vs Custom Prompt -| Feature | `custom_update_memory_prompt` | `custom_prompt` | -|---------|-------------------------------|-----------------| -| Use case | Determine the action to be performed on the memory | Extract facts from messages | -| Reference | Retrieved facts from messages and old memory | Messages | -| Output | Action to be performed on the memory | Extracted facts | + + Consistent JSON structure makes it easy to parse decisions downstream or log them for auditing. + + +--- + +## See it in action + +- Run reconciliation jobs that compare retrieved facts to existing memories. +- Feed both sources into the custom prompt, then apply the returned actions (add new entries, update text, delete outdated facts). +- Log each decision so product teams can review why a change happened. + + + The prompt works alongside `custom_fact_extraction_prompt`—fact extraction identifies candidate facts, and the update prompt decides how to merge them into long-term storage. + + +--- + +## Verify the feature is working + +- Test all four actions with targeted examples, including edge cases where facts differ only slightly. +- Confirm update responses keep the original IDs and include `old_memory`. +- Ensure delete actions only trigger when contradictions appear or when you explicitly request removal. + +--- + +## Best practices + +1. **Keep instructions brief:** Remove redundant wording so the LLM focuses on the decision logic. +2. **Document your schema:** Share the prompt and examples with your team so everyone knows how memories evolve. +3. **Track prompt versions:** When rules change, bump a version number and archive the prior prompt. +4. **Review outputs regularly:** Skim audit logs weekly to spot drift or repeated mistakes. +5. **Pair with monitoring:** Visualize counts of each action to detect spikes in deletes or updates. + +--- + +## Compare prompts + +| Feature | `custom_update_memory_prompt` | `custom_fact_extraction_prompt` | +| --- | --- | --- | +| Primary job | Decide memory actions (ADD/UPDATE/DELETE/NONE) | Pull facts from user and assistant messages | +| Inputs | Retrieved facts + existing memory entries | Raw conversation turns | +| Output | Structured memory array with events | Array of extracted facts | + +--- + + + + Coordinate both prompts so fact extraction feeds clean inputs into the update flow. + + + See how update prompts keep customer profiles current in a working automation. + + diff --git a/docs/open-source/features/graph-memory.mdx b/docs/open-source/features/graph-memory.mdx index 0c403cf02..ba2d6a56c 100644 --- a/docs/open-source/features/graph-memory.mdx +++ b/docs/open-source/features/graph-memory.mdx @@ -1,6 +1,7 @@ --- title: Graph Memory description: "Layer relationships onto Mem0 search so agents remember who did what, when, and with whom." +icon: "network-wired" --- Graph Memory extends Mem0 by persisting nodes and edges alongside embeddings, so recalls stitch together people, places, and events instead of just keywords. diff --git a/docs/open-source/features/metadata-filtering.mdx b/docs/open-source/features/metadata-filtering.mdx index 686e48acb..8011c78ab 100644 --- a/docs/open-source/features/metadata-filtering.mdx +++ b/docs/open-source/features/metadata-filtering.mdx @@ -1,19 +1,47 @@ --- title: Enhanced Metadata Filtering -description: 'Advanced filtering capabilities for precise memory retrieval in Mem0 1.0.0 ' +description: Fine-grained metadata queries for precise OSS memory retrieval. +icon: "filter" --- +Enhanced metadata filtering in Mem0 1.0.0 lets you run complex queries across memory metadata. Combine comparisons, logical operators, and wildcard matches to zero in on the exact memories your agent needs. + -Enhanced metadata filtering is available in **Mem0 1.0.0 ** and later versions. This feature provides powerful filtering capabilities with logical operators and comparison functions. + **You’ll use this when…** + - Retrieval must respect multiple metadata conditions before returning context. + - You need to mix numeric, boolean, and string filters in a single query. + - Agents rely on deterministic filtering instead of broad semantic search alone. -## Overview + + Enhanced filtering requires Mem0 1.0.0 or later and a vector store that supports the operators you enable. Unsupported operators fall back to simple equality filters. + -Mem0 1.0.0 introduces enhanced metadata filtering that allows you to perform complex queries on your memory metadata. You can now use logical operators, comparison functions, and advanced filtering patterns to retrieve exactly the memories you need. + + The TypeScript SDK accepts the same filter shape shown here—transpose the dictionaries to objects and reuse the keys unchanged. + -## Basic Filtering +--- -### Simple Key-Value Filtering +## Feature anatomy + + + + | Operator | Meaning | When to use it | + | --- | --- | --- | + | `eq` / `ne` | Equals / not equals | Exact matches on strings, numbers, or booleans. | + | `gt` / `gte` | Greater than / greater than or equal | Rank results by score, confidence, or any numeric field. | + | `lt` / `lte` | Less than / less than or equal | Cap numeric values (e.g., ratings, timestamps). | + | `in` / `nin` | In list / not in list | Pre-approve or block sets of values without chaining multiple filters. | + | `contains` / `icontains` | Case-sensitive / case-insensitive substring match | Scan text fields for keywords. | + | `*` | Wildcard | Require that a field exists, regardless of value. | + | `AND` / `OR` / `NOT` | Combine filters | Build logic trees so multiple conditions work together. | + + + +### Metadata selectors + +Start with key-value filters when you need direct matches on metadata fields. ```python from mem0 import Memory @@ -28,24 +56,13 @@ results = m.search( ) ``` -### Exact Match Filtering + + Expect only memories tagged with `category="preferences"` to return for the given `user_id`. + -```python -# Multiple exact match filters -results = m.search( - "movie recommendations", - user_id="alice", - filters={ - "category": "entertainment", - "type": "recommendation", - "priority": "high" - } -) -``` +### Comparison operators -## Advanced Filtering with Operators - -### Comparison Operators +Layer greater-than/less-than comparisons to rank results by score, confidence, or any numeric field. Equality helpers (`eq`, `ne`) keep string and boolean checks explicit. ```python # Greater than / Less than @@ -53,10 +70,10 @@ results = m.search( "recent activities", user_id="alice", filters={ - "score": {"gt": 0.8}, # score > 0.8 - "priority": {"gte": 5}, # priority >= 5 - "confidence": {"lt": 0.9}, # confidence < 0.9 - "rating": {"lte": 3} # rating <= 3 + "score": {"gt": 0.8}, + "priority": {"gte": 5}, + "confidence": {"lt": 0.9}, + "rating": {"lte": 3} } ) @@ -65,13 +82,15 @@ results = m.search( "specific content", user_id="alice", filters={ - "status": {"eq": "active"}, # status == "active" - "archived": {"ne": True} # archived != True + "status": {"eq": "active"}, + "archived": {"ne": True} } ) ``` -### List-based Operators +### List-based operators + +Use `in` and `nin` when you want to pre-approve or exclude specific values without writing multiple equality checks. ```python # In / Not in operators @@ -85,7 +104,13 @@ results = m.search( ) ``` -### String Operators + + Verify the response includes only memories in the whitelisted categories and omits any with archived or deleted status. + + +### String operators + +`contains` and `icontains` capture substring matches, making it easy to scan descriptions or tags for keywords without retrieving irrelevant memories. ```python # Text matching operators @@ -93,14 +118,16 @@ results = m.search( "content search", user_id="alice", filters={ - "title": {"contains": "meeting"}, # case-sensitive contains - "description": {"icontains": "important"}, # case-insensitive contains + "title": {"contains": "meeting"}, + "description": {"icontains": "important"}, "tags": {"contains": "urgent"} } ) ``` -### Wildcard Matching +### Wildcard matching + +Allow any value for a field while still requiring the field to exist—handy when the mere presence of a field matters. ```python # Match any value for a field @@ -108,17 +135,17 @@ results = m.search( "all with category", user_id="alice", filters={ - "category": "*" # Any memory that has a category field + "category": "*" } ) ``` -## Logical Operators +### Logical combinations -### AND Operations +Combine filters with `AND`, `OR`, and `NOT` to express complex decision trees. Nest logical operators to encode multi-branch workflows. ```python -# Logical AND - all conditions must be true +# Logical AND results = m.search( "complex query", user_id="alice", @@ -130,12 +157,8 @@ results = m.search( ] } ) -``` -### OR Operations - -```python -# Logical OR - any condition can be true +# Logical OR results = m.search( "flexible query", user_id="alice", @@ -147,12 +170,8 @@ results = m.search( ] } ) -``` -### NOT Operations - -```python -# Logical NOT - exclude matches +# Logical NOT results = m.search( "exclusion query", user_id="alice", @@ -163,12 +182,8 @@ results = m.search( ] } ) -``` -### Complex Nested Logic - -```python -# Combine multiple logical operators +# Complex nested logic results = m.search( "advanced query", user_id="alice", @@ -191,9 +206,115 @@ results = m.search( ) ``` -## Real-world Examples + + Inspect the response metadata—each returned memory should satisfy the combined logic tree exactly. If results look too broad, log the raw filters sent to your vector store. + -### Project Management Filtering +--- + +## Configure it + +Tune your vector store so filter-heavy queries stay fast. Index fields you frequently filter on and keep complex checks for later in the evaluation order. + +```python +# Ensure your vector store supports indexing on filtered fields +config = { + "vector_store": { + "provider": "qdrant", + "config": { + "host": "localhost", + "port": 6333, + "indexed_fields": ["category", "priority", "status", "user_id"] + } + } +} +``` + + + After enabling indexing, benchmark the same query—latency should drop once the store can prune documents on indexed fields before vector scoring. + + + + Put simple key=value filters on indexed fields before your range or text conditions so the store trims results early. + + +```python +# More efficient: Filter on indexed fields first +good_filters = { + "AND": [ + {"user_id": "alice"}, + {"category": "work"}, + {"content": {"contains": "meeting"}} + ] +} + +# Less efficient: Complex operations first +avoid_filters = { + "AND": [ + {"description": {"icontains": "complex text search"}}, + {"user_id": "alice"} + ] +} +``` + + + When you reorder filters so indexed fields come first (`good_filters` example), queries typically return faster than the `avoid_filters` pattern where expensive text searches run before simple checks. + + +Vector store support varies. Confirm operator coverage before shipping: + + + + Full comparison, list, and logical support. Handles deeply nested boolean logic efficiently. + + + Equality and basic comparisons only. Limited nesting—break large trees into smaller calls. + + + Comparisons plus `in`/`nin`. Text operators are constrained; rely on tags where possible. + + + Full operator coverage with advanced text filters. Best option when you need hybrid text + metadata queries. + + + + + If an operator is unsupported, most stores silently ignore that branch. Add validation before execution so you can fall back to simpler queries instead of returning empty results. + + +### Migrate from earlier filters + +```python +# Before (v0.x) - simple key-value filtering only +results = m.search( + "query", + user_id="alice", + filters={"category": "work", "status": "active"} +) + +# After (v1.0.0) - enhanced filtering with operators +results = m.search( + "query", + user_id="alice", + filters={ + "AND": [ + {"category": "work"}, + {"status": {"ne": "archived"}}, + {"priority": {"gte": 5}} + ] + } +) +``` + + + Existing equality filters continue to work; add new operator branches gradually so agents can adopt richer queries without downtime. + + +--- + +## See it in action + +### Project management filtering ```python # Find high-priority active tasks @@ -216,7 +337,11 @@ results = m.search( ) ``` -### Customer Support Filtering + + Tasks returned should belong to the targeted projects, remain incomplete, and be assigned to one of the listed teammates. + + +### Customer support filtering ```python # Find recent unresolved tickets @@ -238,7 +363,11 @@ results = m.search( ) ``` -### Content Recommendation Filtering + + Pair `agent_id` filters with ticket-specific metadata so shared support bots return only the tickets they can act on in the current session. + + +### Content recommendation filtering ```python # Personalized content filtering @@ -261,71 +390,11 @@ results = m.search( ) ``` -## Performance Considerations + + Confirm personalized feeds show only unread titles that meet the rating and language criteria. + -### Indexing Strategy - -```python -# Ensure your vector store supports indexing on filtered fields -config = { - "vector_store": { - "provider": "qdrant", - "config": { - "host": "localhost", - "port": 6333, - # Enable indexing on frequently filtered fields - "indexed_fields": ["category", "priority", "status", "user_id"] - } - } -} -``` - -### Filter Optimization - -```python -# More efficient: Filter on indexed fields first -good_filters = { - "AND": [ - {"user_id": "alice"}, # Indexed field first - {"category": "work"}, # Then other indexed fields - {"content": {"contains": "meeting"}} # Text search last - ] -} - -# Less efficient: Complex operations first -avoid_filters = { - "AND": [ - {"description": {"icontains": "complex text search"}}, # Expensive first - {"user_id": "alice"} # Indexed field last - ] -} -``` - -## Vector Store Compatibility - -Different vector stores support different filtering capabilities: - -### Qdrant --  Full support for all operators --  Efficient nested logical operations --  Indexed field optimization - -### Chroma --  Basic operators (eq, ne, gt, lt, gte, lte) --  Simple logical operations --  Limited nested operations - -### Pinecone --  Good support for comparison operators --  In/nin operations --  Limited text operations - -### Weaviate --  Full operator support --  Advanced text operations --  Efficient filtering - -## Error Handling +### Handle invalid operators ```python try: @@ -338,7 +407,6 @@ try: ) except ValueError as e: print(f"Filter error: {e}") - # Fallback to simple filtering results = m.search( "test query", user_id="alice", @@ -346,42 +414,35 @@ except ValueError as e: ) ``` -## Migration from Simple Filters + + Validate filters before executing searches so you can catch typos or unsupported operators during development instead of at runtime. + -### Before (v0.x) -```python -# Simple key-value filtering only -results = m.search( - "query", - user_id="alice", - filters={"category": "work", "status": "active"} -) -``` +--- -### After (v1.0.0 ) -```python -# Enhanced filtering with operators -results = m.search( - "query", - user_id="alice", - filters={ - "AND": [ - {"category": "work"}, - {"status": {"ne": "archived"}}, - {"priority": {"gte": 5}} - ] - } -) -``` +## Verify the feature is working -## Best Practices +- Log the filters sent to your vector store and confirm the response metadata matches every clause. +- Benchmark queries before and after indexing to ensure latency improvements materialize. +- Add analytics or debug logging to track how often fallbacks execute when operators fail validation. -1. **Use Indexed Fields**: Filter on indexed fields for better performance -2. **Combine Operators**: Use logical operators to create precise queries -3. **Test Filter Performance**: Benchmark complex filters with your data -4. **Graceful Degradation**: Implement fallbacks for unsupported operations -5. **Validate Filters**: Check filter syntax before executing queries +--- - -Enhanced metadata filtering provides powerful capabilities for precise memory retrieval. Start with simple filters and gradually adopt more complex patterns as needed. - +## Best practices + +1. **Use indexed fields first:** Order filters so equality checks run before complex string operations. +2. **Combine operators intentionally:** Keep logical trees readable—large nests are harder to debug. +3. **Test performance regularly:** Benchmark critical queries with production-like payloads. +4. **Plan graceful degradation:** Provide fallback filters when an operator isn’t available. +5. **Validate syntax early:** Catch malformed filters during development to protect agents at runtime. + +--- + + + + Compare operator coverage and indexing strategies across supported stores. + + + Practice building workflows that label and retrieve memories with clear metadata filters. + + diff --git a/docs/open-source/features/multimodal-support.mdx b/docs/open-source/features/multimodal-support.mdx index 138c32fa2..776e6a53d 100644 --- a/docs/open-source/features/multimodal-support.mdx +++ b/docs/open-source/features/multimodal-support.mdx @@ -1,93 +1,95 @@ --- title: Multimodal Support -description: Integrate images into your interactions with Mem0 +description: Capture and recall memories from both text and images. +icon: "image" --- -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. +Multimodal support lets Mem0 extract facts from images alongside regular text. Add screenshots, receipts, or product photos and Mem0 will store the insights as searchable memories so agents can recall them later. -## How It Works + + **You’ll use this when…** + - Users share screenshots, menus, or documents and you want the details to become memories. + - You already collect text conversations but need visual context for better answers. + - You want a single workflow that handles both URLs and local image files. + -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 + + Images larger than 20 MB are rejected. Compress or resize files before sending them to avoid errors. + -This enables more comprehensive understanding of user interactions that include both text and visual elements. +--- + +## Feature anatomy + +- **Vision processing:** Mem0 runs the image through a vision model that extracts text and key details. +- **Memory creation:** Extracted information is stored as standard memories so search, filters, and analytics continue to work. +- **Context linking:** Visual and textual turns in the same conversation stay linked, giving agents richer context. +- **Flexible inputs:** Accept publicly accessible URLs or base64-encoded local files in both Python and JavaScript SDKs. + + + + | Format | Used for | Notes | + | --- | --- | --- | + | JPEG / JPG | Photos and screenshots | Default option for camera captures. | + | PNG | Images with transparency | Keeps sharp text and UI elements crisp. | + | WebP | Web-optimized images | Smaller payloads for faster uploads. | + | GIF | Static or animated graphics | Works for simple graphics and short loops. | + + + +--- + +## Configure it + +### Add image messages from URLs ```python Python -import os from mem0 import Memory client = Memory() messages = [ - { - "role": "user", - "content": "Hi, my name is Alice." - }, - { - "role": "assistant", - "content": "Nice to meet you, Alice! What do you like to eat?" - }, + {"role": "user", "content": "Hi, my name is Alice."}, { "role": "user", "content": { "type": "image_url", "image_url": { - "url": "https://www.superhealthykids.com/wp-content/uploads/2021/10/best-veggie-pizza-featured-image-square-2.jpg" + "url": "https://example.com/menu.jpg" } } - }, + } ] -# Calling the add method to ingest messages into the memory system client.add(messages, user_id="alice") ``` -```json Output -{ - "results": [ - { - "memory": "Name is Alice", - "event": "ADD", - "id": "7ae113a3-3cb5-46e9-b6f7-486c36391847" - }, - { - "memory": "Likes large pizza with toppings including cherry tomatoes, black olives, green spinach, yellow bell peppers, diced ham, and sliced mushrooms", - "event": "ADD", - "id": "56545065-7dee-4acf-8bf2-a5b2535aabb3" +```ts TypeScript +import { Memory } from "mem0ai"; + +const client = new Memory(); + +const messages = [ + { role: "user", content: "Hi, my name is Alice." }, + { + role: "user", + content: { + type: "image_url", + image_url: { url: "https://example.com/menu.jpg" } } - ] -} + } +]; + +await client.add(messages, { user_id: "alice" }); ``` -## Supported Image Formats + + Inspect the response payload—the memories list should include entries extracted from the menu image as well as the text turns. + -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: +### Upload local images as base64 ```python Python @@ -96,21 +98,16 @@ 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') + 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", + "role": "user", "content": [ - { - "type": "text", - "text": "What's in this image?" - }, + {"type": "text", "text": "What's in this image?"}, { "type": "image_url", "image_url": { @@ -124,45 +121,47 @@ messages = [ client.add(messages, user_id="alice") ``` -```javascript JavaScript -import fs from 'fs'; -import { Memory } from 'mem0ai'; +```ts TypeScript +import fs from "fs"; +import { Memory } from "mem0ai"; -function encodeImage(imagePath) { - const imageBuffer = fs.readFileSync(imagePath); - return imageBuffer.toString('base64'); +function encodeImage(imagePath: string) { + const buffer = fs.readFileSync(imagePath); + return buffer.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}` - } - } - ] - } + { + 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 + + Keep base64 payloads under 5 MB to speed up uploads and avoid hitting the 20 MB limit. + + +--- + +## See it in action + +### Restaurant menu memory -### Restaurant Menu Analysis ```python from mem0 import Memory @@ -171,10 +170,10 @@ client = Memory() messages = [ { "role": "user", - "content": "I'm looking at this restaurant menu. Help me remember my preferences." + "content": "Help me remember which dishes I liked." }, { - "role": "user", + "role": "user", "content": { "type": "image_url", "image_url": { @@ -184,7 +183,7 @@ messages = [ }, { "role": "user", - "content": "I'm allergic to peanuts and prefer vegetarian options." + "content": "I’m allergic to peanuts and prefer vegetarian meals." } ] @@ -192,18 +191,22 @@ result = client.add(messages, user_id="user123") print(result) ``` -### Document Analysis + + The response should capture both the allergy note and menu items extracted from the photo so future searches can combine them. + + +### Document capture + ```python -# Analyzing receipts, invoices, or documents messages = [ { "role": "user", - "content": "Store this receipt information for my expense tracking." + "content": "Store this receipt information for expenses." }, { "role": "user", "content": { - "type": "image_url", + "type": "image_url", "image_url": { "url": "https://example.com/receipt.jpg" } @@ -214,21 +217,11 @@ messages = [ client.add(messages, user_id="user123") ``` -## File Size and Performance Considerations + + Combine the receipt upload with structured metadata (tags, categories) if you need to filter expenses later. + -### 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: +### Error handling ```python Python @@ -245,66 +238,88 @@ try: "image_url": {"url": "https://example.com/image.jpg"} } }] - - result = client.add(messages, user_id="user123") + + 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}") +except Exception as exc: + print(f"Unexpected error: {exc}") ``` -```javascript JavaScript -import { Memory } from 'mem0ai'; +```ts TypeScript +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}`); + const messages = [{ + role: "user", + content: { + type: "image_url", + image_url: { url: "https://example.com/image.jpg" } } + }]; + + await client.add(messages, { user_id: "user123" }); + console.log("Image processed successfully"); +} catch (error: any) { + 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 + + Fail fast on invalid formats so you can prompt users to re-upload before losing their context. + -### 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. +## Verify the feature is working -### 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. +- After calling `add`, inspect the returned memories and confirm they include image-derived text (menu items, receipt totals, etc.). +- Run a follow-up `search` for a detail from the image; the memory should surface alongside related text. +- Monitor image upload latency—large files should still complete under your acceptable response time. +- Log file size and URL sources to troubleshoot repeated failures. -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: +## Best practices - +1. **Ask for intent:** Prompt users to explain why they sent an image so the memory includes the right context. +2. **Keep images readable:** Encourage clear photos without heavy filters or shadows for better extraction. +3. **Split bulk uploads:** Send multiple images as separate `add` calls to isolate failures and improve reliability. +4. **Watch privacy:** Avoid uploading sensitive documents unless your environment is secured for that data. +5. **Validate file size early:** Check file size before encoding to save bandwidth and time. + +--- + +## Troubleshooting + +| Issue | Cause | Fix | +| --- | --- | --- | +| Upload rejected | File larger than 20 MB | Compress or resize before sending. | +| Memory missing image data | Low-quality or blurry image | Retake the photo with better lighting. | +| Invalid format error | Unsupported file type | Convert to JPEG or PNG first. | +| Slow processing | High-resolution images | Downscale or compress to under 5 MB. | +| Base64 errors | Incorrect prefix or encoding | Ensure `data:image/;base64,` is present and the string is valid. | + +--- + + + + Review supported vision-capable models and configuration details. + + + Follow an end-to-end workflow pairing text and image memories. + + diff --git a/docs/open-source/features/openai_compatibility.mdx b/docs/open-source/features/openai_compatibility.mdx index a25f1082a..c430e8b7f 100644 --- a/docs/open-source/features/openai_compatibility.mdx +++ b/docs/open-source/features/openai_compatibility.mdx @@ -1,94 +1,147 @@ --- title: OpenAI Compatibility -description: 'Integrate Mem0 using OpenAI-compatible client APIs' +description: Use Mem0 with the same chat-completions flow you already built for OpenAI. +icon: "message-bot" --- -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. +Mem0 mirrors the OpenAI client interface so you can plug memories into existing chat-completion code with minimal changes. Point your OpenAI-compatible client at Mem0, keep the same request shape, and gain persistent memory between calls. -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. + + **You’ll use this when…** + - Your app already relies on OpenAI chat completions and you want Mem0 to feel familiar. + - You need to reuse existing middleware that expects OpenAI-compatible responses. + - You plan to switch between Mem0 Platform and the self-hosted client without rewriting code. + -Mem0 supports several language models (LLMs) through integration with various [providers](https://litellm.vercel.app/docs/providers). +## Feature -## Use Mem0 Platform +- **Drop-in client:** `client.chat.completions.create(...)` works the same as OpenAI’s method signatures. +- **Shared parameters:** Mem0 accepts `messages`, `model`, and optional memory-scoping fields (`user_id`, `agent_id`, `run_id`). +- **Memory-aware responses:** Each call saves relevant facts so future prompts automatically reflect past conversations. +- **OSS parity:** Use the same API surface whether you call the hosted proxy or the OSS configuration. + + + Run one request with `user_id` set. If the next call references that ID and its reply uses the stored memory, compatibility is confirmed. + + +--- + +## Configure it + +### Call the managed Mem0 proxy ```python from mem0.proxy.main import Mem0 client = Mem0(api_key="m0-xxx") -# First interaction: Storing user preferences messages = [ - { - "role": "user", - "content": "I love Indian food but I cannot eat pizza since I'm allergic to cheese." - }, -] -user_id = "alice" -chat_completion = client.chat.completions.create( - messages=messages, - model="gpt-4.1-nano-2025-04-14", - user_id=user_id -) -# Memory saved after this will look like: "Loves Indian food. Allergic to cheese and cannot eat pizza." - -# Second interaction: Leveraging stored memory -messages = [ - { - "role": "user", - "content": "Suggest restaurants in San Francisco to eat.", - } + {"role": "user", "content": "I love Indian food but I cannot eat pizza since I'm allergic to cheese."} ] chat_completion = client.chat.completions.create( messages=messages, model="gpt-4.1-nano-2025-04-14", - user_id=user_id + user_id="alice" ) -print(chat_completion.choices[0].message.content) -# Answer: You might enjoy Indian restaurants in San Francisco, such as Amber India, Dosa, or Curry Up Now, which offer delicious options without cheese. ``` -In this example, you can see how the second response is tailored based on the information provided in the first interaction. Mem0 remembers the user's preference for Indian food and their cheese allergy, using this information to provide more relevant and personalized restaurant suggestions in San Francisco. + + Reuse the same identifiers your OpenAI client already sends so you can switch between providers without branching logic. + -## Use Mem0 OSS +### Use the OpenAI-compatible OSS client ```python +from mem0.proxy.main import Mem0 + config = { "vector_store": { "provider": "qdrant", "config": { "host": "localhost", - "port": 6333, + "port": 6333 } - }, + } } client = Mem0(config=config) chat_completion = client.chat.completions.create( - messages=[ - { - "role": "user", - "content": "What's the capital of France?", - } - ], - model="gpt-4.1-nano-2025-04-14", + messages=[{"role": "user", "content": "What's the capital of France?"}], + model="gpt-4.1-nano-2025-04-14" ) ``` -## Mem0 Params for Chat Completion +## See it in action -- `user_id` (Optional[str]): Identifier for the user. +### Memory-aware restaurant recommendation -- `agent_id` (Optional[str]): Identifier for the agent. +```python +from mem0.proxy.main import Mem0 -- `run_id` (Optional[str]): Identifier for the run. +client = Mem0(api_key="m0-xxx") -- `metadata` (Optional[dict]): Additional metadata to be stored with the memory. +# Store preferences +client.chat.completions.create( + messages=[{"role": "user", "content": "I love Indian food but I'm allergic to cheese."}], + model="gpt-4.1-nano-2025-04-14", + user_id="alice" +) -- `filters` (Optional[dict]): Filters to apply when searching for relevant memories. +# Later conversation reuses the memory +response = client.chat.completions.create( + messages=[{"role": "user", "content": "Suggest dinner options in San Francisco."}], + model="gpt-4.1-nano-2025-04-14", + user_id="alice" +) -- `limit` (Optional[int]): Maximum number of relevant memories to retrieve. Default is 10. +print(response.choices[0].message.content) +``` + + The second response should call out Indian restaurants and avoid cheese, proving Mem0 recalled the stored preference. + -Other parameters are similar to OpenAI's API, making it easy to integrate Mem0 into your existing applications. +--- + +## Verify the feature is working + +- Compare responses from Mem0 vs. OpenAI for identical prompts—both should return the same structure (`choices`, `usage`, etc.). +- Inspect stored memories after each request to confirm the fact extraction captured the right details. +- Test switching between hosted (`Mem0(api_key=...)`) and OSS configurations to ensure both respect the same request body. + +--- + +## Best practices + +1. **Scope context intentionally:** Pass identifiers only when you want conversations to persist; skip them for one-off calls. +2. **Log memory usage:** Inspect `response.metadata.memories` (if enabled) to see which facts the model recalled. +3. **Reuse middleware:** Point your existing OpenAI client wrappers to the Mem0 proxy URL to avoid code drift. +4. **Handle fallbacks:** Keep a code path for plain OpenAI calls in case Mem0 is unavailable, then resync memory later. + +--- + +## Parameter reference + +| Parameter | Type | Purpose | +| --- | --- | --- | +| `user_id` | `str` | Associates the conversation with a user so memories persist. | +| `agent_id` | `str` | Optional agent or bot identifier for multi-agent scenarios. | +| `run_id` | `str` | Optional session/run identifier for short-lived flows. | +| `metadata` | `dict` | Store extra fields alongside each memory entry. | +| `filters` | `dict` | Restrict retrieval to specific memories while responding. | +| `limit` | `int` | Cap how many memories Mem0 pulls into the context (default 10). | + +Other request fields mirror OpenAI’s chat completion API. + +--- + + + + Review LLM options that support OpenAI-compatible calls in Mem0. + + + See a full workflow that layers Mem0 memories on top of tool-calling agents. + + diff --git a/docs/open-source/features/overview.mdx b/docs/open-source/features/overview.mdx index 5d4cd25d6..dfef5cdbf 100644 --- a/docs/open-source/features/overview.mdx +++ b/docs/open-source/features/overview.mdx @@ -1,56 +1,69 @@ --- -title: Overview -description: 'Build powerful AI applications with self-improving memory using Mem0 open-source' +title: "Overview" +description: "Self-hosting features that extend Mem0 beyond basic memory storage" +icon: "list" --- -## Welcome to Mem0 Open Source +# Self-Hosting Features Overview -Mem0 is a self-improving memory layer for LLM applications that enables personalized AI experiences while saving costs and delighting users. The open-source version gives you complete control over your memory infrastructure. +Mem0 Open Source ships with capabilities that adapt memory behavior for production workloads—async operations, graph relationships, multimodal inputs, and fine-tuned retrieval. Configure these features with code or YAML to match your application's needs. -## Why Choose Mem0 Open Source? + + Start with the Python quickstart to validate basic memory operations, then enable the features below when you need them. + -Mem0 open-source provides a powerful, flexible foundation for AI memory management with these key advantages: +## Choose your path -1. **Complete Control**: Deploy and manage your own memory infrastructure with full customization capabilities. Perfect for organizations that need data sovereignty and custom integrations. + + + Store entity relationships for multi-hop recall. + + + Query with logical operators and nested conditions. + + + Boost search relevance with specialized models. + + + Non-blocking operations for high-throughput apps. + + + Process images, audio, and video memories. + + + Tailor how facts are extracted from text. + + -2. **Flexible Architecture**: Choose from multiple vector databases (Pinecone, Qdrant, Weaviate, Chroma, PGVector), graph stores (Neo4j, Memgraph), and embedding models to fit your specific needs. + + + Control memory refinement with custom instructions. + + + HTTP endpoints for language-agnostic integrations. + + + Drop-in replacement for OpenAI chat endpoints. + + -3. **Advanced Memory Organization**: Organize memories using `user_id`, `agent_id`, and `run_id` parameters for sophisticated multi-agent, multi-session applications with precise context control. + + Looking for managed features instead? Compare self-hosting vs managed in the Platform vs OSS guide. + -4. **Rich Integration Ecosystem**: Seamlessly integrate with popular frameworks like LangChain, LlamaIndex, AutoGen, CrewAI, and Vercel AI SDK. +## Keep going -## Core Features - -### Memory Management -- **Synchronous & Asynchronous Operations**: Choose between sync and async memory operations based on your application needs -- **Smart Memory Retrieval**: Intelligent search and retrieval with semantic understanding -- **Advanced Reranking**: Improve search relevance with Zero Entropy, LLM-based, or custom reranking models -- **Memory Persistence**: Long-term storage with automatic optimization and cleanup - -### Advanced Organization -- **User Context**: Organize memories by user for personalized experiences -- **Agent Isolation**: Separate memories by AI agent for specialized knowledge domains -- **Session Tracking**: Use run IDs to maintain context across different conversation sessions - -### Flexible Storage -- **Vector Databases**: Support for Pinecone, Qdrant, Weaviate, Chroma, and PGVector -- **Graph Stores**: Neo4j and Memgraph integration for relationship-based memory -- **Embedding Models**: Multiple embedding providers for optimal performance - -## Getting Started - -Choose your preferred approach: - -- **[Python Quickstart](../python-quickstart)**: Get started with Python SDK -- **[Node.js Quickstart](../node-quickstart)**: Use Mem0 with Node.js/TypeScript -- **[Examples](/examples)**: Explore real-world use cases and implementations - -## Next Steps - -- Explore [specific features](./async-memory) in detail -- Learn about [graph memory](./graph-memory) capabilities -- Set up [vector databases](/components/vectordbs/overview) and [LLM integrations](/components/llms/overview) -- Check out our [examples](/examples) for practical implementations -- Join our [Discord community](https://mem0.dev/DiD) for support - -We're excited to see what you'll build with Mem0 open-source. + + + + diff --git a/docs/open-source/features/reranker-search.mdx b/docs/open-source/features/reranker-search.mdx index ec8abc5ae..fbae84182 100644 --- a/docs/open-source/features/reranker-search.mdx +++ b/docs/open-source/features/reranker-search.mdx @@ -1,26 +1,58 @@ --- title: Reranker-Enhanced Search -description: 'Improve search relevance with reranking models in Mem0 1.0.0 ' +description: Boost relevance by reordering vector hits with reranking models. +icon: "ranking-star" --- - -**Mem0 1.0.0+** supports reranker-enhanced search, letting specialized models reorder vector hits so you deliver the most relevant memories. +Reranker-enhanced search adds a second scoring pass after vector retrieval so Mem0 can return the most relevant memories first. Enable it when keyword similarity alone misses nuance or when you need the highest-confidence context for an agent decision. + + + **You’ll use this when…** + - Queries are nuanced and require semantic understanding beyond vector distance. + - Large memory collections produce too many near matches to review manually. + - You want consistent scoring across providers by delegating ranking to a dedicated model. -## Overview + + Reranking raises latency and, for hosted models, API spend. Benchmark with production traffic and define a fallback path for latency-sensitive requests. + -Rerankers are specialized models that improve the quality of search results by reordering initially retrieved memories. They work as a second-stage ranking system that analyzes the semantic relationship between your query and retrieved memories to provide more relevant results. + + All configuration snippets translate directly to the TypeScript SDK—swap dictionaries for objects while keeping the same keys (`provider`, `config`, `rerank` flags). + -## How Reranking Works +--- -1. **Initial Vector Search**: Retrieves candidate memories using vector similarity -2. **Reranking**: Specialized model analyzes query-memory relationships -3. **Reordering**: Results are reordered based on semantic relevance -4. **Enhanced Results**: Final results with improved relevance scores +## Feature anatomy -## Configuration +- **Initial vector search:** Retrieve candidate memories by similarity. +- **Reranker pass:** A specialized model scores each candidate against the original query. +- **Reordered results:** Mem0 sorts responses using the reranker’s scores before returning them. +- **Optional fallbacks:** Toggle reranking per request or disable it entirely if performance or cost becomes a concern. -### Basic Setup + + + - **[Cohere](/components/rerankers/models/cohere)** – Multilingual hosted reranker with API-based scoring. + - **[Sentence Transformer](/components/rerankers/models/sentence_transformer)** – Local Hugging Face cross-encoders for GPU or CPU. + - **[Hugging Face](/components/rerankers/models/huggingface)** – Bring any hosted or on-prem reranker model ID. + - **[LLM Reranker](/components/rerankers/models/llm_reranker)** – Use your preferred LLM (OpenAI, etc.) for prompt-driven scoring. + - **[Zero Entropy](/components/rerankers/models/zero_entropy)** – High-quality neural reranking tuned for retrieval tasks. + + + | Provider | Latency | Quality | Cost | Local deploy | + | --- | --- | --- | --- | --- | + | Cohere | Medium | High | API cost | ❌ | + | Sentence Transformer | Low | Good | Free | ✅ | + | Hugging Face | Low–Medium | Variable | Free | ✅ | + | LLM Reranker | High | Very high | API cost | Depends | + + + +--- + +## Configure it + +### Basic setup ```python from mem0 import Memory @@ -38,50 +70,43 @@ config = { m = Memory.from_config(config) ``` -### Supported Providers + + Confirm `results["results"][0]["score"]` reflects the reranker output—if the field is missing, the reranker was not applied. + -Mem0 supports multiple reranking providers. See the complete documentation for each: + + Set `top_k` to the smallest candidate pool that still captures relevant hits. Smaller pools keep reranking costs down. + -- **[Cohere](../../components/rerankers/models/cohere)**: Enterprise-grade with multilingual support -- **[Sentence Transformer](../../components/rerankers/models/sentence_transformer)**: Local HuggingFace models -- **[Hugging Face](../../components/rerankers/models/huggingface)**: Custom models from HuggingFace -- **[LLM Reranker](../../components/rerankers/models/llm_reranker)**: Use any LLM for flexible scoring -- **[Zero Entropy](../../components/rerankers/models/zero_entropy)**: State-of-the-art neural reranking - -#### Cohere Reranker +### Provider-specific options ```python +# Cohere reranker config = { "reranker": { "provider": "cohere", "config": { "model": "rerank-english-v3.0", "api_key": "your-cohere-api-key", - "top_k": 10, # Number of results to rerank + "top_k": 10, "return_documents": True } } } -``` -#### Sentence Transformer Reranker - -```python +# Sentence Transformer reranker config = { "reranker": { "provider": "sentence_transformer", "config": { "model": "cross-encoder/ms-marco-MiniLM-L-6-v2", - "device": "cuda", # Use GPU if available + "device": "cuda", "max_length": 512 } } } -``` -#### Hugging Face Reranker - -```python +# Hugging Face reranker config = { "reranker": { "provider": "huggingface", @@ -92,11 +117,8 @@ config = { } } } -``` -#### LLM-based Reranker - -```python +# LLM-based reranker config = { "reranker": { "provider": "llm_reranker", @@ -114,70 +136,11 @@ config = { } ``` -## Usage Examples + + Keep authentication keys in environment variables when you plug these configs into production projects. + -### Basic Reranked Search - -```python -# Reranking is enabled by default when configured -results = m.search( - "What are my food preferences?", - user_id="alice" -) - -# Results are automatically reranked for better relevance -for result in results["results"]: - print(f"Memory: {result['memory']}") - print(f"Score: {result['score']}") -``` - - -Expect each result to include both the base vector score and an updated rerank score so you can compare quality improvements. - - -### Controlling Reranking - -```python -# Enable reranking explicitly -results_with_rerank = m.search( - "What movies do I like?", - user_id="alice", - rerank=True -) - -# Disable reranking for this search -results_without_rerank = m.search( - "What movies do I like?", - user_id="alice", - rerank=False -) - -# Compare the difference in results -print("With reranking:", len(results_with_rerank["results"])) -print("Without reranking:", len(results_without_rerank["results"])) -``` - -### Combining with Filters - -```python -# Reranking works with metadata filtering -results = m.search( - "important work tasks", - user_id="alice", - filters={ - "AND": [ - {"category": "work"}, - {"priority": {"gte": 7}} - ] - }, - rerank=True, - limit=20 -) -``` - -## Advanced Configuration - -### Complete Configuration Example +### Full stack example ```python config = { @@ -216,120 +179,165 @@ config = { m = Memory.from_config(config) ``` -### Async Support + + A quick search should now return results with both vector and reranker scores, letting you compare improvements immediately. + + +### Async support ```python from mem0 import AsyncMemory -# Reranking works with async operations async_memory = AsyncMemory.from_config(config) async def search_with_rerank(): - results = await async_memory.search( + return await async_memory.search( "What are my preferences?", user_id="alice", rerank=True ) - return results -# Use in async context import asyncio results = asyncio.run(search_with_rerank()) ``` -## Performance Considerations + + Inspect the async response to confirm reranking still applies; the scores should match the synchronous implementation. + -### When to Use Reranking - -✅ **Good Use Cases:** -- Complex semantic queries -- Domain-specific searches -- When precision is more important than speed -- Large memory collections -- Ambiguous or nuanced queries - -❌ **Avoid When:** -- Simple keyword matching -- Real-time applications with strict latency requirements -- Small memory collections -- High-frequency searches where cost matters - -### Performance Optimization +### Tune performance and cost ```python -# Optimize reranking performance +# GPU-friendly local reranker configuration config = { "reranker": { "provider": "sentence_transformer", "config": { "model": "cross-encoder/ms-marco-MiniLM-L-6-v2", - "device": "cuda", # Use GPU - "batch_size": 32, # Process in batches - "top_k": 10, # Limit candidates - "max_length": 256 # Reduce if appropriate - } - } -} -``` - -### Cost Management - -```python -# For API-based rerankers like Cohere -config = { - "reranker": { - "provider": "cohere", - "config": { - "model": "rerank-english-v3.0", - "api_key": "your-cohere-api-key", - "top_k": 5, # Reduce to control API costs + "device": "cuda", + "batch_size": 32, + "top_k": 10, + "max_length": 256 } } } -# Use reranking selectively +# Smart toggle for hosted rerankers def smart_search(query, user_id, use_rerank=None): - # Automatically decide when to use reranking if use_rerank is None: - use_rerank = len(query.split()) > 3 # Complex queries only - + use_rerank = len(query.split()) > 3 return m.search(query, user_id=user_id, rerank=use_rerank) ``` -## Error Handling + + Use heuristics (query length, user tier) to decide when to rerank so high-signal queries benefit without taxing every request. + + +### Handle failures gracefully ```python try: - results = m.search( - "test query", - user_id="alice", - rerank=True - ) -except Exception as e: - print(f"Reranking failed: {e}") - # Gracefully fall back to vector search - results = m.search( - "test query", - user_id="alice", - rerank=False - ) + results = m.search("test query", user_id="alice", rerank=True) +except Exception as exc: + print(f"Reranking failed: {exc}") + results = m.search("test query", user_id="alice", rerank=False) ``` -## Reranker Comparison + + Always fall back to vector-only search—dropped queries introduce bigger accuracy issues than slightly less relevant ordering. + -| Provider | Latency | Quality | Cost | Local Deploy | -|----------|---------|---------|------|--------------| -| Cohere | Medium | High | API Cost | ❌ | -| Sentence Transformer | Low | Good | Free | ✅ | -| Hugging Face | Low-Medium | Variable | Free | ✅ | -| LLM Reranker | High | Very High | API Cost | Depends | - -## Real-world Examples - -### Customer Support +### Migrate from v0.x + +```python +# Before: basic vector search +results = m.search("query", user_id="alice") + +# After: same API with reranking enabled via config +config = { + "reranker": { + "provider": "sentence_transformer", + "config": { + "model": "cross-encoder/ms-marco-MiniLM-L-6-v2" + } + } +} + +m = Memory.from_config(config) +results = m.search("query", user_id="alice") +``` + +--- + +## See it in action + +### Basic reranked search + +```python +results = m.search( + "What are my food preferences?", + user_id="alice" +) + +for result in results["results"]: + print(f"Memory: {result['memory']}") + print(f"Score: {result['score']}") +``` + + + Expect each result to list the reranker-adjusted score so you can compare ordering against baseline vector results. + + +### Toggle reranking per request + +```python +results_with_rerank = m.search( + "What movies do I like?", + user_id="alice", + rerank=True +) + +results_without_rerank = m.search( + "What movies do I like?", + user_id="alice", + rerank=False +) +``` + + + Log the reranked vs. non-reranked lists during rollout so stakeholders can see the improvement before enforcing it everywhere. + + + + You should see the same memories in both lists, but the reranked response will reorder them based on semantic relevance. + + +### Combine with metadata filters + +```python +results = m.search( + "important work tasks", + user_id="alice", + filters={ + "AND": [ + {"category": "work"}, + {"priority": {"gte": 7}} + ] + }, + rerank=True, + limit=20 +) +``` + + + Verify filtered reranked searches still respect every metadata clause—reranking only reorders candidates, it never bypasses filters. + + +### Real-world playbooks + +#### Customer support ```python -# Improve support ticket relevance config = { "reranker": { "provider": "cohere", @@ -342,7 +350,6 @@ config = { m = Memory.from_config(config) -# Find relevant support cases results = m.search( "customer having login issues with mobile app", agent_id="support_bot", @@ -351,10 +358,13 @@ results = m.search( ) ``` -### Content Recommendation + + Top results should highlight tickets matching the login issue context so agents can respond faster. + + +#### Content recommendation ```python -# Better content matching results = m.search( "science fiction books with space exploration themes", user_id="reader123", @@ -368,10 +378,13 @@ for result in results["results"]: print(f"Relevance: {result['score']:.3f}") ``` -### Personal Assistant + + Expect high-scoring recommendations that match both the requested theme and any metadata limits you applied. + + +#### Personal assistant ```python -# Enhanced personal queries results = m.search( "What restaurants did I enjoy last month that had good vegetarian options?", user_id="foodie_user", @@ -386,58 +399,40 @@ results = m.search( ) ``` -## Migration Guide + + Reuse this pattern for other lifestyle queries—swap the filters and prompt text without changing the rerank configuration. + -### From v0.x (No Reranking) + + Each workflow keeps the same `m.search(...)` signature, so you can template these queries across agents with only the prompt and filters changing. + -```python -# v0.x - basic vector search -results = m.search("query", user_id="alice") -``` +--- -### To v1.0.0 (With Reranking) +## Verify the feature is working -```python -# Add reranker configuration -config = { - "reranker": { - "provider": "sentence_transformer", - "config": { - "model": "cross-encoder/ms-marco-MiniLM-L-6-v2" - } - } -} +- Inspect result payloads for both `score` (vector) and reranker scores; mismatched fields indicate the reranker didn’t execute. +- Track latency before and after enabling reranking to ensure SLAs hold. +- Review provider logs or dashboards for throttling or quota warnings. +- Run A/B comparisons (rerank on/off) to validate improved relevance before defaulting to reranked responses. -m = Memory.from_config(config) +--- -# Same search API, better results -results = m.search("query", user_id="alice") # Automatically reranked -``` +## Best practices -## Best Practices +1. **Start local:** Try Sentence Transformer models to prove value before paying for hosted APIs. +2. **Monitor latency:** Add metrics around reranker duration so you notice regressions quickly. +3. **Control spend:** Use `top_k` and selective toggles to cap hosted reranker costs. +4. **Keep a fallback:** Always catch reranker failures and continue with vector-only ordering. +5. **Experiment often:** Swap providers or models to find the best fit for your domain and language mix. -1. **Start Simple**: Begin with Sentence Transformers for local deployment -2. **Monitor Performance**: Track both relevance improvements and latency -3. **Cost Awareness**: Use API-based rerankers judiciously -4. **Selective Usage**: Apply reranking where it provides the most value -5. **Fallback Strategy**: Always handle reranking failures gracefully -6. **Test Different Models**: Experiment to find the best fit for your domain - - -Reranker-enhanced search significantly improves result relevance. Start with a local model and upgrade to API-based solutions as your needs grow. - +--- - - + + Review provider fields, defaults, and environment variables before going live. + + + Extend scoring with prompt-tuned LLM rerankers for niche workflows. + diff --git a/docs/open-source/features/rest-api.mdx b/docs/open-source/features/rest-api.mdx index 72c6f97a5..3a77cb839 100644 --- a/docs/open-source/features/rest-api.mdx +++ b/docs/open-source/features/rest-api.mdx @@ -1,113 +1,155 @@ --- title: REST API Server -description: 'Reach every Mem0 capability through a FastAPI-powered REST server' +description: Reach every Mem0 OSS capability through a FastAPI-powered REST layer. +icon: "code" --- -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. +The Mem0 REST API server exposes every OSS memory operation over HTTP. Run it alongside your stack to add, search, update, and delete memories from any language that speaks REST. - - - + + **You’ll use this when…** + - Your services already talk to REST APIs and you want Mem0 to match that style. + - Teams on languages without the Mem0 SDK still need access to memories. + - You plan to explore or debug endpoints through the built-in OpenAPI page at `/docs`. + -## Features + + Add your own authentication and HTTPS before exposing the server to anything beyond your internal network. The default image does not include auth. + -- **Create memories**: Create memories based on messages for a user, agent, or run. -- **Retrieve memories**: Get all memories for a given user, agent, or run. -- **Search memories**: Search stored memories based on a query. -- **Update memories**: Update an existing memory. -- **Delete memories**: Delete a specific memory or all memories for a user, agent, or run. -- **Reset memories**: Reset all memories for a user, agent, or run. -- **OpenAPI Documentation**: Accessible via `/docs` endpoint. +--- -## Running Locally +## Feature + +- **CRUD endpoints:** Create, retrieve, search, update, delete, and reset memories by `user_id`, `agent_id`, or `run_id`. +- **Status health check:** Access base routes to confirm the server is online. +- **OpenAPI explorer:** Visit `/docs` for interactive testing and schema reference. + +--- + +## Configure it + +### Run with Docker Compose (development) - - The Development Docker Compose comes pre-configured with postgres pgvector, neo4j and a `server/history/history.db` volume for the history database. + +1. Create `server/.env` with your keys: - The only required environment variable to run the server is `OPENAI_API_KEY`. +```bash +OPENAI_API_KEY=your-openai-api-key +``` - 1. Create a `.env` file in the `server/` directory and set your environment variables. For example: +2. Start the stack: - ```txt - OPENAI_API_KEY=your-openai-api-key - ``` +```bash +cd server +docker compose up +``` - 2. Run the Docker container using Docker Compose: - - ```bash - cd server - docker compose up - ``` - - 3. Access the API at http://localhost:8888. - - 4. Making changes to the server code or the library code will automatically reload the server. - - - - - 1. Create a `.env` file in the current directory and set your environment variables. For example: - - ```txt - OPENAI_API_KEY=your-openai-api-key - ``` - - 2. Either pull the docker image from docker hub or build the docker image locally. - - - - - ```bash - docker pull mem0/mem0-api-server - ``` - - - - - - ```bash - docker build -t mem0-api-server . - ``` - - - - - 3. Run the Docker container: - - ``` bash - docker run -p 8000:8000 mem0-api-server --env-file .env - ``` - - 4. Access the API at http://localhost:8000. - - - - - - 1. Create a `.env` file in the current directory and set your environment variables. For example: - - ```txt - OPENAI_API_KEY=your-openai-api-key - ``` - - 2. Install dependencies: - - ```bash - pip install -r requirements.txt - ``` - - 3. Start the FastAPI server: - - ```bash - uvicorn main:app --reload - ``` - - 4. Access the API at http://localhost:8000. - - +3. Reach the API at `http://localhost:8888`. Edits to the server or library auto-reload. + -## Usage +### Run with Docker -Once the server is running (locally or via Docker), you can interact with it using any REST client or through your preferred programming language (e.g., Go, Java, etc.). You can test out the APIs using the OpenAPI documentation at [http://localhost:8000/docs](http://localhost:8000/docs) endpoint. + + +```bash +docker pull mem0/mem0-api-server +``` + + +```bash +docker build -t mem0-api-server . +``` + + + +1. Create a `.env` file with `OPENAI_API_KEY`. +2. Run the container: + +```bash +docker run -p 8000:8000 --env-file .env mem0-api-server +``` + +3. Visit `http://localhost:8000`. + +### Run directly (no Docker) + +```bash +pip install -r requirements.txt +uvicorn main:app --reload +``` + + + Use a process manager such as `systemd`, Supervisor, or PM2 when deploying the FastAPI server for production resilience. + + + + The REST server reads the same configuration you use locally, so you can point it at your preferred LLM, vector store, graph backend, and reranker without changing code. + + +--- + +## See it in action + +### Create and search memories via HTTP + +```bash +curl -X POST http://localhost:8000/memories \ + -H "Content-Type: application/json" \ + -d '{ + "messages": [ + {"role": "user", "content": "I love fresh vegetable pizza."} + ], + "user_id": "alice" + }' +``` + + + Expect a JSON response containing the new memory IDs and events (`ADD`, etc.). + + +```bash +curl "http://localhost:8000/memories/search?user_id=alice&query=vegetable" +``` + +### Explore with OpenAPI docs + +1. Navigate to `http://localhost:8000/docs`. +2. Pick an endpoint (e.g., `POST /memories/search`). +3. Fill in parameters and click **Execute** to try requests in-browser. + + + Export the generated `curl` snippets from the OpenAPI UI to bootstrap integration tests. + + +--- + +## Verify the feature is working + +- Hit the root route and `/docs` to confirm the server is reachable. +- Run a full cycle: `POST /memories` → `GET /memories/{id}` → `DELETE /memories/{id}`. +- Watch server logs for import errors or provider misconfigurations during startup. +- Confirm environment variables (API keys, vector store credentials) load correctly when containers restart. + +--- + +## Best practices + +1. **Add authentication:** Protect endpoints with API gateways, proxies, or custom FastAPI middleware. +2. **Use HTTPS:** Terminate TLS at your load balancer or reverse proxy. +3. **Monitor uptime:** Track request rates, latency, and error codes per endpoint. +4. **Version configs:** Keep environment files and Docker Compose definitions in source control. +5. **Limit exposure:** Bind to private networks unless you explicitly need public access. + +--- + + + + Fine-tune LLMs, vector stores, and graph backends that power the REST server. + + + See how services call the REST endpoints as part of an automation pipeline. + + diff --git a/docs/open-source/node-quickstart.mdx b/docs/open-source/node-quickstart.mdx index c495981a1..7df12047c 100644 --- a/docs/open-source/node-quickstart.mdx +++ b/docs/open-source/node-quickstart.mdx @@ -1,342 +1,177 @@ --- title: Node SDK Quickstart -description: 'Get started with Mem0 quickly!' -icon: "node" -iconType: "solid" +description: "Store and search Mem0 memories from a TypeScript or JavaScript app in minutes." +icon: "js" --- -> Welcome to the Mem0 quickstart guide. This guide will help you get up and running with Mem0 in no time. +Spin up Mem0 with the Node SDK in just a few steps. You’ll install the package, initialize the client, add a memory, and confirm retrieval with a single search. -## Installation +## Prerequisites -To install Mem0, you can use npm. Run the following command in your terminal: +- Node.js 18 or higher +- (Optional) OpenAI API key stored in your environment when you want to customize providers +## Install and run your first memory + + + ```bash npm install mem0ai ``` + -## Basic Usage - -### Initialize Mem0 - - - -```typescript -import { Memory } from 'mem0ai/oss'; + +```ts +import { Memory } from "mem0ai/oss"; const memory = new Memory(); ``` - - -If you want to run Mem0 in production, initialize using the following method: + -```typescript -import { Memory } from 'mem0ai/oss'; - -const memory = new Memory({ - version: 'v1.1', - embedder: { - provider: 'openai', - config: { - apiKey: process.env.OPENAI_API_KEY || '', - model: 'text-embedding-3-small', - }, - }, - vectorStore: { - provider: 'memory', - config: { - collectionName: 'memories', - dimension: 1536, - }, - }, - llm: { - provider: 'openai', - config: { - apiKey: process.env.OPENAI_API_KEY || '', - model: 'gpt-4-turbo-preview', - }, - }, - historyDbPath: 'memory.db', - }); -``` - - - - -### Store a Memory - - -```typescript Code + +```ts 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 thriller movies but I love sci-fi movies."}, - {"role": "assistant", "content": "Got it! I'll avoid thriller recommendations and suggest sci-fi movies in the future."} -] + { 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 thriller movies but I love sci-fi movies." }, + { role: "assistant", content: "Got it! I'll avoid thriller recommendations and suggest sci-fi movies in the future." } +]; await memory.add(messages, { userId: "alice", metadata: { category: "movie_recommendations" } }); ``` + -```json Output + +```ts +const results = await memory.search("What do you know about me?", { userId: "alice" }); +console.log(results); +``` + +**Output** +```json { "results": [ { "id": "892db2ae-06d9-49e5-8b3e-585ef9b85b8e", "memory": "User is planning to watch a movie tonight.", - "metadata": { - "category": "movie_recommendations" - } - }, - { - "id": "cbb1fe73-0bf1-4067-8c1f-63aa53e7b1a4", - "memory": "User is not a big fan of thriller movies.", - "metadata": { - "category": "movie_recommendations" - } - }, - { - "id": "475bde34-21e6-42ab-8bef-0ab84474f156", - "memory": "User loves sci-fi movies.", - "metadata": { - "category": "movie_recommendations" - } - } - ] -} -``` - - -### Retrieve Memories - - -```typescript Code -// Get all memories -const allMemories = await memory.getAll({ userId: "alice" }); -console.log(allMemories) -``` - -```json Output -{ - "results": [ - { - "id": "892db2ae-06d9-49e5-8b3e-585ef9b85b8e", - "memory": "User is planning to watch a movie tonight.", - "hash": "1a271c007316c94377175ee80e746a19", - "createdAt": "2025-02-27T16:33:20.557Z", - "updatedAt": "2025-02-27T16:33:27.051Z", - "metadata": { - "category": "movie_recommendations" - }, - "userId": "alice" - }, - { - "id": "475bde34-21e6-42ab-8bef-0ab84474f156", - "memory": "User loves sci-fi movies.", - "hash": "285d07801ae42054732314853e9eadd7", - "createdAt": "2025-02-27T16:33:20.560Z", - "updatedAt": undefined, - "metadata": { - "category": "movie_recommendations" - }, - "userId": "alice" - }, - { - "id": "cbb1fe73-0bf1-4067-8c1f-63aa53e7b1a4", - "memory": "User is not a big fan of thriller movies.", - "hash": "285d07801ae42054732314853e9eadd7", - "createdAt": "2025-02-27T16:33:20.560Z", - "updatedAt": undefined, - "metadata": { - "category": "movie_recommendations" - }, - "userId": "alice" - } - ] -} -``` - - - -
- - -```typescript Code -// Get a single memory by ID -const singleMemory = await memory.get('892db2ae-06d9-49e5-8b3e-585ef9b85b8e'); -console.log(singleMemory); -``` - -```json Output -{ - "id": "892db2ae-06d9-49e5-8b3e-585ef9b85b8e", - "memory": "User is planning to watch a movie tonight.", - "hash": "1a271c007316c94377175ee80e746a19", - "createdAt": "2025-02-27T16:33:20.557Z", - "updatedAt": undefined, - "metadata": { - "category": "movie_recommendations" - }, - "userId": "alice" -} -``` - - -### Search Memories - - -```typescript Code -const result = await memory.search('What do you know about me?', { userId: "alice" }); -console.log(result); -``` - -```json Output -{ - "results": [ - { - "id": "892db2ae-06d9-49e5-8b3e-585ef9b85b8e", - "memory": "User is planning to watch a movie tonight.", - "hash": "1a271c007316c94377175ee80e746a19", - "createdAt": "2025-02-27T16:33:20.557Z", - "updatedAt": undefined, "score": 0.38920719231944799, "metadata": { "category": "movie_recommendations" }, "userId": "alice" - }, - { - "id": "475bde34-21e6-42ab-8bef-0ab84474f156", - "memory": "User loves sci-fi movies.", - "hash": "285d07801ae42054732314853e9eadd7", - "createdAt": "2025-02-27T16:33:20.560Z", - "updatedAt": undefined, - "score": 0.36869761478135689, - "metadata": { - "category": "movie_recommendations" - }, - "userId": "alice" - }, - { - "id": "cbb1fe73-0bf1-4067-8c1f-63aa53e7b1a4", - "memory": "User is not a big fan of thriller movies.", - "hash": "285d07801ae42054732314853e9eadd7", - "createdAt": "2025-02-27T16:33:20.560Z", - "updatedAt": undefined, - "score": 0.33855272141248272, - "metadata": { - "category": "movie_recommendations" - }, - "userId": "alice" } ] } ``` - + +
-### Update a Memory + +By default the Node SDK uses local-friendly settings (OpenAI `gpt-4.1-nano-2025-04-14`, `text-embedding-3-small`, in-memory vector store, and SQLite history). Swap components by passing a config as shown below. + + +## Configure for production + +```ts +import { Memory } from "mem0ai/oss"; + +const memory = new Memory({ + version: "v1.1", + embedder: { + provider: "openai", + config: { + apiKey: process.env.OPENAI_API_KEY || "", + model: "text-embedding-3-small" + } + }, + vectorStore: { + provider: "memory", + config: { + collectionName: "memories", + dimension: 1536 + } + }, + llm: { + provider: "openai", + config: { + apiKey: process.env.OPENAI_API_KEY || "", + model: "gpt-4-turbo-preview" + } + }, + historyDbPath: "memory.db" +}); +``` + +## Manage memories (optional) -```typescript Code -const result = await memory.update( - '892db2ae-06d9-49e5-8b3e-585ef9b85b8e', - 'I love India, it is my favorite country.' -); +```ts Get all memories +const allMemories = await memory.getAll({ userId: "alice" }); +console.log(allMemories); +``` + +```ts Get one memory +const singleMemory = await memory.get("892db2ae-06d9-49e5-8b3e-585ef9b85b8e"); +console.log(singleMemory); +``` + +```ts Search memories +const result = await memory.search("What do you know about me?", { userId: "alice" }); console.log(result); ``` -```json Output -{ - "message": "Memory updated successfully!" -} +```ts Update a memory +const updateResult = await memory.update( + "892db2ae-06d9-49e5-8b3e-585ef9b85b8e", + "I love India, it is my favorite country." +); +console.log(updateResult); ``` -### Memory History - - -```typescript Code -const history = await memory.history('892db2ae-06d9-49e5-8b3e-585ef9b85b8e'); +```ts +// Audit history +const history = await memory.history("892db2ae-06d9-49e5-8b3e-585ef9b85b8e"); console.log(history); -``` -```json Output -[ - { - "id": 39, - "memoryId": "892db2ae-06d9-49e5-8b3e-585ef9b85b8e", - "previousValue": "User is planning to watch a movie tonight.", - "newValue": "I love India, it is my favorite country.", - "action": "UPDATE", - "createdAt": "2025-02-27T16:33:20.557Z", - "updatedAt": "2025-02-27T16:33:27.051Z", - "isDeleted": 0 - }, - { - "id": 37, - "memoryId": "892db2ae-06d9-49e5-8b3e-585ef9b85b8e", - "previousValue": null, - "newValue": "User is planning to watch a movie tonight.", - "action": "ADD", - "createdAt": "2025-02-27T16:33:20.557Z", - "updatedAt": null, - "isDeleted": 0 - } -] -``` - - -### Delete Memory - -```typescript -// Delete a memory by id -await memory.delete('892db2ae-06d9-49e5-8b3e-585ef9b85b8e'); - -// Delete all memories for a user +// Delete specific or scoped memories +await memory.delete("892db2ae-06d9-49e5-8b3e-585ef9b85b8e"); await memory.deleteAll({ userId: "alice" }); + +// Reset everything +await memory.reset(); ``` -### Reset Memory +## Use a custom history store -```typescript -await memory.reset(); // Reset all memories -``` - -### History Store - -The Mem0 TypeScript SDK supports history stores to run in serverless environments. - -We recommend using Supabase as a history store for serverless environments, or disabling the history store to run in serverless environments. +The Node SDK supports Supabase (or other providers) when you need serverless-friendly history storage. -```typescript Supabase -import { Memory } from 'mem0ai/oss'; +```ts Supabase provider +import { Memory } from "mem0ai/oss"; const memory = new Memory({ historyStore: { - provider: 'supabase', + provider: "supabase", config: { - supabaseUrl: process.env.SUPABASE_URL || '', - supabaseKey: process.env.SUPABASE_KEY || '', - tableName: 'memory_history', - }, - }, + supabaseUrl: process.env.SUPABASE_URL || "", + supabaseKey: process.env.SUPABASE_KEY || "", + tableName: "memory_history" + } + } }); ``` -```typescript Disable History -import { Memory } from 'mem0ai/oss'; +```ts Disable history +import { Memory } from "mem0ai/oss"; const memory = new Memory({ - disableHistory: true, + disableHistory: true }); ``` -Mem0 uses SQLite as a default history store. - -#### Create Memory History Table in Supabase - -You may need to create a memory history table in Supabase to store the history of memories. Use the following SQL command in `SQL Editor` on the Supabase project dashboard to create a memory history table: +Create the Supabase table with: ```sql create table memory_history ( @@ -351,105 +186,113 @@ create table memory_history ( ); ``` -## Configuration Parameters +## Configuration parameters -Mem0 offers extensive configuration options to customize its behavior according to your needs. These configurations span different components like vector stores, language models, embedders, and graph stores. +Mem0 offers granular configuration across vector stores, LLMs, embedders, and history stores. - -| Parameter | Description | Default | -|-------------|---------------------------------|-------------| -| `provider` | Vector store provider (e.g., "memory") | "memory" | -| `host` | Host address | "localhost" | -| `port` | Port number | undefined | - - - -| Parameter | Description | Provider | -|-----------------------|-----------------------------------------------|-------------------| -| `provider` | LLM provider (e.g., "openai", "anthropic") | All | -| `model` | Model to use | All | -| `temperature` | Temperature of the model | All | -| `apiKey` | API key to use | All | -| `maxTokens` | Tokens to generate | All | -| `topP` | Probability threshold for nucleus sampling | All | -| `topK` | Number of highest probability tokens to keep | All | -| `openaiBaseUrl` | Base URL for OpenAI API | OpenAI | - - - -| Parameter | Description | Default | -|-------------|---------------------------------|-------------| -| `provider` | Graph store provider (e.g., "neo4j") | "neo4j" | -| `url` | Connection URL | env.NEO4J_URL | -| `username` | Authentication username | env.NEO4J_USERNAME | -| `password` | Authentication password | env.NEO4J_PASSWORD | - - - -| Parameter | Description | Default | -|-------------|---------------------------------|------------------------------| -| `provider` | Embedding provider | "openai" | -| `model` | Embedding model to use | "text-embedding-3-small" | -| `apiKey` | API key for embedding service | None | - - - -| Parameter | Description | Default | -|------------------|--------------------------------------|----------------------------| -| `historyDbPath` | Path to the history database | "{mem0_dir}/history.db" | -| `version` | API version | "v1.0" | -| `customPrompt` | Custom prompt for memory processing | None | - - - -| Parameter | Description | Default | -|------------------|--------------------------------------|----------------------------| -| `provider` | History store provider | "sqlite" | -| `config` | History store configuration | None (Defaults to SQLite) | -| `disableHistory` | Disable history store | false | - - - -```typescript + +| Parameter | Description | Default | +| --- | --- | --- | +| `provider` | Vector store provider (e.g., `"memory"`) | `"memory"` | +| `host` | Host address | `"localhost"` | +| `port` | Port number | `undefined` | + + +| Parameter | Description | Provider | +| --- | --- | --- | +| `provider` | LLM provider (e.g., `"openai"`, `"anthropic"`) | All | +| `model` | Model to use | All | +| `temperature` | Temperature value | All | +| `apiKey` | API key | All | +| `maxTokens` | Max tokens to generate | All | +| `topP` | Probability threshold | All | +| `topK` | Token count to keep | All | +| `openaiBaseUrl` | Base URL override | OpenAI | + + +| Parameter | Description | Default | +| --- | --- | --- | +| `provider` | Graph store provider (e.g., `"neo4j"`) | `"neo4j"` | +| `url` | Connection URL | `process.env.NEO4J_URL` | +| `username` | Username | `process.env.NEO4J_USERNAME` | +| `password` | Password | `process.env.NEO4J_PASSWORD` | + + +| Parameter | Description | Default | +| --- | --- | --- | +| `provider` | Embedding provider | `"openai"` | +| `model` | Embedding model | `"text-embedding-3-small"` | +| `apiKey` | API key | `undefined` | + + +| Parameter | Description | Default | +| --- | --- | --- | +| `historyDbPath` | Path to history database | `"{mem0_dir}/history.db"` | +| `version` | API version | `"v1.0"` | +| `customPrompt` | Custom processing prompt | `undefined` | + + +| Parameter | Description | Default | +| --- | --- | --- | +| `provider` | History provider | `"sqlite"` | +| `config` | Provider configuration | `undefined` | +| `disableHistory` | Disable history store | `false` | + + +```ts const config = { - version: 'v1.1', - embedder: { - provider: 'openai', - config: { - apiKey: process.env.OPENAI_API_KEY || '', - model: 'text-embedding-3-small', - }, - }, - vectorStore: { - provider: 'memory', - config: { - collectionName: 'memories', - dimension: 1536, - }, - }, - llm: { - provider: 'openai', - config: { - apiKey: process.env.OPENAI_API_KEY || '', - model: 'gpt-4-turbo-preview', - }, - }, - historyStore: { - provider: 'supabase', - config: { - supabaseUrl: process.env.SUPABASE_URL || '', - supabaseKey: process.env.SUPABASE_KEY || '', - tableName: 'memories', - }, - }, - disableHistory: false, // This is false by default - customPrompt: "I'm a virtual assistant. I'm here to help you with your queries.", + version: "v1.1", + embedder: { + provider: "openai", + config: { + apiKey: process.env.OPENAI_API_KEY || "", + model: "text-embedding-3-small" } + }, + vectorStore: { + provider: "memory", + config: { + collectionName: "memories", + dimension: 1536 + } + }, + llm: { + provider: "openai", + config: { + apiKey: process.env.OPENAI_API_KEY || "", + model: "gpt-4-turbo-preview" + } + }, + historyStore: { + provider: "supabase", + config: { + supabaseUrl: process.env.SUPABASE_URL || "", + supabaseKey: process.env.SUPABASE_KEY || "", + tableName: "memories" + } + }, + disableHistory: false, + customPrompt: "I'm a virtual assistant. I'm here to help you with your queries." +}; ``` - + -If you have any questions, please feel free to reach out to us using one of the following methods: +## What's next? - \ No newline at end of file + + + Review CRUD patterns, filters, and advanced retrieval across the OSS stack. + + + Swap in your preferred LLM, vector store, and history provider for production use. + + + See a full Node-based workflow that layers Mem0 memories onto tool-calling agents. + + + +If you have any questions, please feel free to reach out: + + diff --git a/docs/open-source/overview.mdx b/docs/open-source/overview.mdx index 6ac8ea0fd..2118cd5e5 100644 --- a/docs/open-source/overview.mdx +++ b/docs/open-source/overview.mdx @@ -1,8 +1,7 @@ --- title: "Overview" -icon: "code-branch" -iconType: "solid" description: "Self-host Mem0 with full control over your infrastructure and data" +icon: "house" --- # Mem0 Open Source Overview @@ -27,31 +26,31 @@ Mem0 Open Source delivers the same adaptive memory engine as the platform, but p - Bootstrap the CLI, run dockerized dependencies, and verify the add/search loop. + Bootstrap CLI and verify add/search loop. - Install the TypeScript SDK, wire environment variables, and run the starter script. + Install TypeScript SDK and run starter script. - Choose your LLM, embedder, vector store, and reranker with YAML or code. + LLM, embedder, vector store, reranker setup. - Add relationship-aware recall across providers like Neo4j, Memgraph, or Kùzu. + Relationship-aware recall with Neo4j, Memgraph. - Optimize search quality with hybrid retrieval and reranker depth controls. + Hybrid retrieval and reranker controls. - Follow the reference deployment to persist memories and expose REST endpoints. + Reference deployment with REST endpoints. - Call the REST endpoints for async add/search flows and project automation. + Async add/search flows and automation. diff --git a/docs/open-source/python-quickstart.mdx b/docs/open-source/python-quickstart.mdx index 2a4a4c852..c4e20e28c 100644 --- a/docs/open-source/python-quickstart.mdx +++ b/docs/open-source/python-quickstart.mdx @@ -1,8 +1,7 @@ --- title: Python SDK Quickstart description: "Get started with Mem0 quickly!" -icon: "python" -iconType: "solid" +icon: "snake" --- Get started with Mem0's Python SDK in under 5 minutes. This guide shows you how to install Mem0 and store your first memory. diff --git a/docs/platform/features/platform-overview.mdx b/docs/platform/features/platform-overview.mdx index e17fa8bad..a4b32cbfa 100644 --- a/docs/platform/features/platform-overview.mdx +++ b/docs/platform/features/platform-overview.mdx @@ -1,40 +1,47 @@ --- -description: "See how Mem0 Platform features evolve from baseline filters to graph-powered retrieval." -icon: "sparkles" title: Overview +description: "See how Mem0 Platform features evolve from baseline filters to graph-powered retrieval." +icon: "list" --- Mem0 Platform features help managed deployments scale from basic filtering to graph-powered retrieval and data governance. Use this page to pick the right feature lane for your team. - New to the platform? Start with the Platform quickstart, then dive into the journeys below. + New to the platform? Start with the Platform quickstart, + then dive into the journeys below. ## Choose your path - - Control which memories surface with field-level filtering and async defaults. + + Field-level filtering with async defaults. - Stream add/search requests without blocking your agents. + Non-blocking add/search requests for agents. - Layer relationships on top of vectors for richer recalls. + Relationship-aware recall across entities. - - Combine metadata filtering, rerankers, and per-request toggles. + + Metadata filters, rerankers, and toggles. - Handle imports, exports, timestamps, and expirations at scale. + Imports, exports, timestamps, and expirations. - Wire webhook callbacks, feedback loops, and multi-agent chat. + Webhooks, feedback loops, and multi-agent chat. - Self-hosting instead? Jump to the OSS feature overview for equivalent capabilities. + Self-hosting instead? Jump to the{" "} + OSS feature overview for equivalent + capabilities. ## Keep going diff --git a/docs/platform/overview.mdx b/docs/platform/overview.mdx index c8b35cdf3..37df07cb4 100644 --- a/docs/platform/overview.mdx +++ b/docs/platform/overview.mdx @@ -38,31 +38,31 @@ Mem0 is the memory engine that keeps conversations contextual so users never rep - Create a project, export an API key, and ship your first memory in minutes. + Create project and ship first memory. - Learn how user, agent, and session memories behave across the platform. + User, agent, and session memory behavior. - See how add/search/update/delete work together with verification steps. + Add, search, update, and delete workflows. - Browse graph memory, async clients, and rerankers before turning them on. + Graph memory, async clients, and rerankers. - Layer metadata filters, rerankers, and per-request toggles onto your flows. + Metadata filters and per-request toggles. - Wire Mem0 into LangChain, CrewAI, Vercel AI SDK, and other partner tools. + LangChain, CrewAI, Vercel AI SDK. - Track memory activity, adjust settings, and manage workspaces from one place. + Track activity and manage workspaces.