Build and run agents you can see, understand and trust.
Python agentchatbotlarge-language-modelsllmllm-agentmcpmulti-agentmulti-modalreact-agentrealtime-agentvoice-agentvoice-assistant
fix: Fix the bug in mem0 integration (#854)
Osier-Yic0f2affb50dd
diff --git a/examples/functionality/long_term_memory/mem0/README.md b/examples/functionality/long_term_memory/mem0/README.mdindex d21e25b9c..aff85ab74 100644--- a/examples/functionality/long_term_memory/mem0/README.md+++ b/examples/functionality/long_term_memory/mem0/README.md@@ -1,325 +1,158 @@- # Mem0LongTermMemory+ # Mem0 Long-Term Memory in AgentScope-## Overview+This example demonstrates how to-**Note**: We are working on merging Mem0LongTermMemory into the main AgentScope repository.+- use Mem0LongTermMemory to provide persistent semantic memory storage for AgentScope agents,+- record and retrieve conversation history and user preferences across sessions,+- integrate long-term memory with ReAct agents for context-aware conversations, and+- configure DashScope embedding models and Qdrant vector store for memory management.-Mem0LongTermMemory is a long-term memory implementation built on top of the mem0 library, designed to provide persistent, semantic memory storage for AgentScope agents. It enables agents to record, store, and retrieve conversation history, reasoning processes, and contextual information across sessions, supporting advanced memory management and knowledge retention.--This example demonstrates how to use Mem0LongTermMemory to create persistent memory systems that can store and retrieve information based on semantic similarity, enabling agents to maintain context and learn from past interactions.--## Core Features--### Persistent Memory Storage-- **Vector-based Storage**: Uses Qdrant vector database for efficient semantic search and retrieval-- **Configurable Backends**: Support for multiple embedding models (OpenAI, DashScope) and vector stores-- **Async Operations**: Full async support for non-blocking memory operations--### Semantic Memory Management-- **Content Recording**: Store conversation messages, tool usage, and reasoning processes-- **Thinking Integration**: Record agent thinking processes alongside content for better context-- **Flexible Input Formats**: Support for strings, Msg objects, and dictionaries--### Agent Integration-- **Direct AgentScope Integration**: Seamless integration with AgentScope's ReActAgent-- **Memory Modes**: Support for agent_control, dev_control, and both modes-- **Tool Response Format**: Returns structured ToolResponse objects for easy integration+## Prerequisites-## File Structure+- Python 3.10 or higher+- DashScope API key from Alibaba Cloud-```-memory_by_mem0/-├── README.md # This documentation file-├── long_term_memory_by_mem0.py # Core Mem0LongTermMemory implementation-├── memory_example.py # Standalone examples demonstrating memory operations-├── conversation_agent_with_longterm_mem.py # Interactive conversation example with ReActAgent-└── utils.py # AgentScope integration utilities for mem0-```-## Prerequisites+## QuickStart-### Clone the AgentScope Repository-This example depends on AgentScope. Please clone the full repository.+Install agentscope and ensure you have a valid DashScope API key in your environment variables.-### Install Dependencies-**Recommended**: Python 3.10++> Note: The example is built with DashScope chat model and embedding model. If you want to use OpenAI models instead,+> modify the model initialization in the example code accordingly.-Install the following dependencies:```bash+# Install agentscope from source+cd {PATH_TO_AGENTSCOPE}+pip install -e .+# Install dependenciespip install mem0ai```-### API Keys-By default, the example uses DashScope/OpenAI for embedding and LLM. Set your API key:+Set up your API key:```bashexport DASHSCOPE_API_KEY='YOUR_API_KEY'-export DASHSCOPE_API_BASE_URL='YOUR_API_BASE_URL'-export DASHSCOPE_MODEL_4_MEMORY='USED_MODEL_NAME'-export DASHSCOPE_EMBEDDING_MODEL='text-embedding-v2'```-## How It Works--### 1. Configuration-The memory system uses a `MemoryConfig` that specifies:-- **Embedder**: Configuration for embedding models (OpenAI, DashScope)-- **LLM**: Configuration for language models used in memory processing-- **Vector Store**: Configuration for vector database (Qdrant with on-disk storage as default)--### 2. Memory Structure-- **Mem0LongTermMemory**: Inherits from `LongTermMemoryBase` and maintains an async memory server-- **Single AsyncMemory Instance**: Uses one AsyncMemory instance for all storage and retrieval operations-- **Agent/User Context**: Maintains separate memory spaces for different agent-user combinations--### 3. Memory Recording Flow-1. **Input Processing**: Formats various input types (strings, Msg objects, dictionaries) into standardized format-2. **Content Combination**: Merges thinking processes with content for comprehensive memory storage-3. **Vector Storage**: Stores processed content with metadata in the vector database-4. **Response Formatting**: Returns structured ToolResponse objects for easy integration--### 4. Memory Retrieval Flow-1. **Semantic Search**: Performs vector similarity search in the memory database-2. **Response Formatting**: Returns retrieved memories in structured format--## Usage Examples--### Basic Usage--Run the standalone memory examples to see the complete memory operations:+Run the example:```bash-python ./memory_example.py+python memory_example.py```+The example will:+1. Initialize a Mem0LongTermMemory instance with DashScope models and Qdrant vector store+2. Record a basic conversation to long-term memory+3. Retrieve memories using semantic search+4. Demonstrate ReAct agent integration with long-term memory for storing and retrieving user preferences-### Example Scenarios--The example demonstrates several typical use cases:--1. **Basic Conversation Recording**: Store simple user-agent conversations-2. **Tool Usage and Results**: Record tool usage with thinking processes-3. **Multi-step Reasoning**: Store complex reasoning processes step by step-4. **Error Handling**: Record error scenarios and recovery strategies-5. **User Preferences**: Store user preferences and contextual information+## Key Features-## API Reference--### Mem0LongTermMemory Class--#### Main Methods--**`__init__(agent_name=None, user_name=None, run_name=None, model=None, embedding_model=None, vector_store_config=None, mem0_config=None, default_memory_type=None, **kwargs)`**-- Initialize the memory instance with agent, user, and run context-- `agent_name` (str, optional): The name of the agent-- `user_name` (str, optional): The name of the user-- `run_name` (str, optional): The name of the run/session-- `model` (ChatModelBase, optional): The model to use for the long-term memory-- `embedding_model` (EmbeddingModelBase, optional): The embedding model to use-- `vector_store_config` (VectorStoreConfig, optional): Vector store configuration-- `mem0_config` (MemoryConfig, optional): Complete mem0 configuration-- `default_memory_type` (str, optional): Default memory type for storage--**Note**:-1. At least one of `agent_name`, `user_name`, or `run_name` is required.-2. During memory recording, these parameters become metadata for the stored memories.-3. During memory retrieval, only memories with matching metadata values will be returned.--**`record_to_memory(thinking, content, memory_type=None, **kwargs)`**-- Record content with thinking process-- `thinking` (str): Your thinking and reasoning about what to record-- `content` (list[str]): The content to remember, which is a list of strings-- `memory_type` (str, optional): The type of memory to use. Default is None, to create a semantic memory. "procedural_memory" is explicitly used for procedural memories-- Returns: ToolResponse with success/error status--**`retrieve_from_memory(keywords, **kwargs)`**-- Retrieve memories based on keywords-- `keywords` (list[str]): Keywords to search for in the memory, which should be specific and concise, e.g. the person's name, the date, the location, etc.-- `limit_per_search` (int): Number of memories to retrieve per search (default: 5)-- Returns: ToolResponse with retrieved memories--#### Internal Methods--**`record(msgs, **kwargs)`**-- Record message sequences to memory-- `msgs` (Sequence[Msg | None]): Messages to record--**`_record_all(content, thinking=None, memory_type=None, infer=True, **kwargs)`**-- Record content with comprehensive processing-- `content` (list[str] | list[Msg] | list[dict]): The content to remember, which is a list of strings or Msg objects or dict objects-- `thinking` (str, optional): Your thinking and reasoning about what to record, if not provided, the content will be used as the thinking-- `memory_type` (str, optional): The type of memory to use. Default is None, to create a semantic memory. "procedural_memory" is explicitly used for procedural memories-- `infer` (bool): Whether to infer memory type (default: True)-- Handles various input formats and thinking integration--**`retrieve(msg, **kwargs)`**-- Retrieve memories based on message content-- `msg` (Msg | list[Msg] | None): The message to search for in the memory, which should be specific and concise, e.g. the person's name, the date, the location, etc.-- `limit_per_search` (int): Number of results per search (default: 5)-- Returns: list[str] - A list of retrieved memory strings+- **Vector-based Storage**: Uses Qdrant vector database for efficient semantic search and retrieval+- **Flexible Configuration**: Support for multiple embedding models (OpenAI, DashScope) and vector stores+- **Async Operations**: Full async support for non-blocking memory operations+- **ReAct Agent Integration**: Seamless integration with AgentScope's ReActAgent and tool system-### Configuration+## Basic Usage+### Initialize Memory-#### Direct Model Configuration```python-# Initialize with AgentScope models directly+import os+from agentscope.memory import Mem0LongTermMemory+from agentscope.model import DashScopeChatModel+from agentscope.embedding import DashScopeTextEmbedding+from mem0.vector_stores.configs import VectorStoreConfig++# Initialize with DashScope models and Qdrant vector storelong_term_memory = Mem0LongTermMemory(agent_name="Friday",user_name="user_123",- model=OpenAIChatModel(- model_name="gpt-4",- api_key="your_api_key",- base_url="your_base_url"+ model=DashScopeChatModel(+ model_name="qwen-max-latest",+ api_key=os.environ.get("DASHSCOPE_API_KEY")+ ),+ embedding_model=DashScopeTextEmbedding(+ model_name="text-embedding-v3",+ api_key=os.environ.get("DASHSCOPE_API_KEY"),+ dimensions=1024),- embedding_model=OpenAITextEmbedding(- model_name="text-embedding-3-small",- api_key="your_api_key",- base_url="your_base_url"+ vector_store_config=VectorStoreConfig(+ provider="qdrant",+ config={+ "on_disk": True,+ "path": "./qdrant_data", # Your customized storage path+ "embedding_model_dims": 1024+ }))```+> **Important**: If you change to a different embedding model or modify `embedding_model_dims`, you must either set a new storage path or delete the existing database files. Otherwise, a dimension mismatch error will occur.--## Customization & Extension--### Backend Replacement-Easily customize embedding, LLM, or vector store by modifying the configuration:--```python-# Example: Using different embedding model-embedder=EmbedderConfig(- provider="dashscope",- config={- "model": "text-embedding-v1",- "api_key": "your_dashscope_key"- }-)-```--### Memory Config Replacement-Mem0LongTermMemory supports directly receiving memory configurations defined in mem0, allowing users to easily adopt various memory configurations and backends supported by mem0. This provides flexibility to use different embedding models, LLMs, and vector stores without modifying the core implementation.+### Integrate with ReAct Agent```python-# Example: Using a complete mem0 MemoryConfig-from mem0.configs.base import MemoryConfig-from mem0.embeddings.configs import EmbedderConfig-from mem0.llms.configs import LlmConfig-from mem0.vector_stores.configs import VectorStoreConfig--# Create a custom mem0 configuration-mem0_config = MemoryConfig(- embedder=EmbedderConfig(- provider="openai",- config={- "model": "text-embedding-3-small",- "api_key": "your_openai_key"- }+from agentscope.agent import ReActAgent+from agentscope.formatter import DashScopeChatFormatter+from agentscope.memory import InMemoryMemory+from agentscope.tool import Toolkit++# Create a ReAct agent with long-term memory+toolkit = Toolkit()+agent = ReActAgent(+ name="Friday",+ sys_prompt=(+ "You are a helpful assistant named Friday. "+ "If you think there is relevant information about "+ "the user's preferences, you can record it to long-term "+ "memory using the tool `record_to_memory`. "+ "If you need to retrieve information from long-term "+ "memory, use the tool `retrieve_from_memory`."),- llm=LlmConfig(- provider="openai",- config={- "model": "gpt-4",- "api_key": "your_openai_key"- }+ model=DashScopeChatModel(+ model_name="qwen-max-latest",+ api_key=os.environ.get("DASHSCOPE_API_KEY")),- vector_store=VectorStoreConfig(- provider="qdrant",- config={- "on_disk": True,- "path": "./memory_data"- }- )+ formatter=DashScopeChatFormatter(),+ toolkit=toolkit,+ memory=InMemoryMemory(),+ long_term_memory=long_term_memory,+ long_term_memory_mode="both")-# Initialize with the custom mem0 configuration-long_term_memory = Mem0LongTermMemory(- agent_name="Friday",- user_name="user_123",- mem0_config=mem0_config+# Use the agent+msg = Msg(+ role="user",+ content="When I travel to Hangzhou, I prefer to stay in a homestay",+ name="user")+response = await agent(msg)```-**Note**: In Mem0LongTermMemory, if the `model`, `embedding_model`, or `vector_store_config` parameters are not None, they will override the corresponding configurations in `mem0_config`. This allows for flexible configuration where you can use a base mem0 configuration and selectively override specific components.--### AgentScope Integration-The implementation includes custom AgentScope providers for mem0:--- **AgentScopeLLM**: Integrates AgentScope ChatModelBase with mem0-- **AgentScopeEmbedding**: Integrates AgentScope EmbeddingModelBase with mem0+## Advanced Configuration-These providers handle the conversion between mem0's expected format and AgentScope's message/response formats.--### Memory Type Customization-Add custom memory types for different use cases:+You can customize the mem0 config by directly set :```python-# Example: Procedural memory-await memory.record_to_memory(- content=["Step 1: Analyze input", "Step 2: Process data"],- thinking="This is a procedural workflow for data processing",- memory_type="procedural_memory"+long_term_memory = Mem0LongTermMemory(+ agent_name="Friday",+ user_name="user_123",+ mem0_config=your_mem0_config # Pass your custom mem0 configuration)```+For more configuration options, refer to the [mem0 documentation](https://github.com/mem0ai/mem0).-## Best Practices--### Memory Recording-1. **Be Specific**: Record specific, actionable information rather than general statements-2. **Include Context**: Always include relevant context and reasoning when recording-3. **Use Thinking**: Leverage the thinking parameter to explain why information is important-4. **Structured Content**: Use structured formats for complex information--### Memory Retrieval-1. **Specific Keywords**: Use specific, relevant keywords for better search results-2. **Appropriate Limits**: Set reasonable limits based on your use case-3. **Context Awareness**: Consider the current context when retrieving memories-4. **Error Handling**: Always handle potential retrieval errors gracefully--### Performance Optimization-1. **Batch Operations**: Group related memory operations when possible-2. **Efficient Queries**: Use specific keywords to reduce search scope-3. **Memory Cleanup**: Periodically clean up irrelevant or outdated memories-4. **Configuration Tuning**: Optimize vector store and embedding configurations+## What's in the Example-## Troubleshooting+The `memory_example.py` file demonstrates:-### Common Issues--**Memory Not Found**-- Check if the memory was properly recorded-- Verify agent_id and user_id consistency-- Ensure vector store is properly configured--**Poor Search Results**-- Use more specific keywords-- Check embedding model configuration-- Verify content was properly formatted during recording--**Performance Issues**-- Optimize vector store configuration-- Reduce search limits-- Consider using on-disk storage for large datasets--**AgentScope Integration Issues**-- Ensure AgentScope models are properly configured-- Check that the custom providers are registered correctly-- Verify message format compatibility--### Debug Mode-Enable debug logging to troubleshoot issues:--```python-import logging-logging.basicConfig(level=logging.DEBUG)-```+1. **Basic Memory Recording**: Recording user conversations to long-term memory+2. **Memory Retrieval**: Searching for stored memories using semantic similarity+3. **ReAct Agent Integration**: Using long-term memory with ReAct agents to store and retrieve user preferences automatically## Reference- [mem0 Documentation](https://github.com/mem0ai/mem0)-- [AgentScope Documentation](https://github.com/agentscope-ai/agentscope)-- [Qdrant Vector Database](https://qdrant.tech/)--For further customization or integration, please refer to the full implementation in the `long_term_memory_by_mem0.py` file and the mem0 official documentation.\ No newline at end of file+- [Qdrant Vector Database](https://qdrant.tech/)\ No newline at end of filediff --git a/examples/functionality/long_term_memory/mem0/memory_example.py b/examples/functionality/long_term_memory/mem0/memory_example.pyindex 00688ecd2..f711d0282 100644--- a/examples/functionality/long_term_memory/mem0/memory_example.py+++ b/examples/functionality/long_term_memory/mem0/memory_example.py@@ -9,6 +9,7 @@ import asyncioimport osfrom dotenv import load_dotenv+from mem0.vector_stores.configs import VectorStoreConfigfrom agentscope.memory import Mem0LongTermMemoryfrom agentscope.agent import ReActAgent@@ -19,6 +20,7 @@ from agentscope.message import Msgfrom agentscope.model import DashScopeChatModelfrom agentscope.tool import Toolkit+load_dotenv()@@ -34,10 +36,18 @@ async def main() -> None:stream=False,),embedding_model=DashScopeTextEmbedding(- model_name="text-embedding-v2",+ model_name="text-embedding-v3",api_key=os.environ.get("DASHSCOPE_API_KEY"),+ dimensions=1024,+ ),+ vector_store_config=VectorStoreConfig(+ provider="qdrant",+ config={+ "on_disk": True,+ "path": "../memory/qdrant_data", # Specify custom path+ "embedding_model_dims": 1024,+ },),- on_disk=False,)print("=== Long Term Memory Examples with mem0 ===\n")@@ -92,7 +102,14 @@ async def main() -> None:toolkit = Toolkit()agent = ReActAgent(name="Friday",- sys_prompt="You are a helpful assistant named Friday.",+ sys_prompt=(+ "You are a helpful assistant named Friday. "+ "If you think there is relevant information about "+ "user's preference, you can record it to the long term "+ "memory by tool call `record_to_memory`. "+ "If you need to retrieve information from the long term "+ "memory, you can use the tool call `retrieve_from_memory`."+ ),model=DashScopeChatModel(model_name="qwen-max-latest",api_key=os.environ.get("DASHSCOPE_API_KEY"),@@ -117,6 +134,13 @@ async def main() -> None:msg = Msg(role="user", content="what preference do I have?", name="user")msg = await agent(msg)print(f"ReActAgent response: {msg.get_text_content()}\n")+ msg = Msg(+ role="user",+ content="I prefer to visit the West Lake",+ name="user",+ )+ msg = await agent(msg)+ print(f"ReActAgent response: {msg.get_text_content()}\n")if __name__ == "__main__":diff --git a/src/agentscope/memory/_mem0_long_term_memory.py b/src/agentscope/memory/_mem0_long_term_memory.pyindex 367b11366..fba472de6 100644--- a/src/agentscope/memory/_mem0_long_term_memory.py+++ b/src/agentscope/memory/_mem0_long_term_memory.py@@ -99,9 +99,14 @@ class Mem0LongTermMemory(LongTermMemoryBase):required.2. During memory recording, these parameters become metadatafor the stored memories.- 3. During memory retrieval, only memories with matching+ 3. **Important**: mem0 will extract memories from messages+ containing role of "user" by default. If you want to+ extract memories from messages containing role of+ "assistant", you need to provide `agent_name`.+ 4. During memory retrieval, only memories with matchingmetadata values will be returned.+model (`ChatModelBase | None`, optional):The chat model to use for the long-term memory. Ifmem0_config is provided, this will override the LLM@@ -265,20 +270,97 @@ class Mem0LongTermMemory(LongTermMemoryBase):content (`list[str]`):The content to remember, which is a list of strings."""+ # Multi-strategy recording approach to ensure content persistence:+ #+ # This method employs a three-tier fallback strategy to maximize+ # successful memory recording:+ #+ # 1. Primary: Record as "user" role message+ # - This is the default approach for capturing user-related+ # content+ # - Mem0 extracts and infers memories from messages containing+ # role of "user"+ #+ # 2. Fallback (if agent_id exists): Record as "assistant" role+ # message+ # - Triggered when primary recording yields no results+ # - In this case, mem0 will use the AGENT_MEMORY_EXTRACTION_PROMPT+ # in mem0/mem0/configs/prompts.py to extract memories from+ # messages containing role of "assistant", if agent_id is+ # provided, otherwise it will use the+ # USER_MEMORY_EXTRACTION_PROMPT in mem0/mem0/configs/prompts.py+ # to extract memories.+ #+ # 3. Last resort: Record as "assistant" with infer=False+ # - Used when both previous attempts yield no results+ # - Bypasses mem0's inference mechanism, which means no+ # inference is performed, mem0 will only record the content+ # as is.+ #+ # This graduated approach ensures that even if mem0's inference fails+ # to extract meaningful memories, the raw content is still preserved.+try:if thinking:content = [thinking] + content+ # Strategy 1: Record as user message firstresults = await self._mem0_record([{- "role": "assistant",+ "role": "user","content": "\n".join(content),- "name": "assistant",+ "name": "user",},],**kwargs,)++ # Strategy 2: Fallback to assistant message. In this case, if+ # agent_id is provided, mem0 will use the+ # AGENT_MEMORY_EXTRACTION_PROMPT in mem0/mem0/configs/prompts.py+ # to extract memories from messages containing role of+ # "assistant". If agent_id is not provided, mem0 will still use+ # the USER_MEMORY_EXTRACTION_PROMPT in+ # mem0/mem0/configs/prompts.py to extract memories.+ if (+ results+ and isinstance(results, dict)+ and "results" in results+ and len(results["results"]) == 0+ ):+ results = await self._mem0_record(+ [+ {+ "role": "assistant",+ "content": "\n".join(content),+ "name": "assistant",+ },+ ],+ **kwargs,+ )++ # Strategy 3: Last resort - direct recording without inference.+ # In this case, mem0 will not use any prompts to extract+ # memories, it will only record the content as is.+ if (+ results+ and isinstance(results, dict)+ and "results" in results+ and len(results["results"]) == 0+ ):+ results = await self._mem0_record(+ [+ {+ "role": "assistant",+ "content": "\n".join(content),+ "name": "assistant",+ },+ ],+ infer=False,+ **kwargs,+ )+return ToolResponse(content=[TextBlock(