Build and run agents you can see, understand and trust.
Python agentchatbotlarge-language-modelsllmllm-agentmcpmulti-agentmulti-modalreact-agentrealtime-agentvoice-agentvoice-assistant
feat(memory): add reme long-term memory implementation (#865)
jinliyl4d105b7afe5a
diff --git a/docs/tutorial/en/src/task_long_term_memory.py b/docs/tutorial/en/src/task_long_term_memory.pyindex 817f9dd46..d543c49b0 100644--- a/docs/tutorial/en/src/task_long_term_memory.py+++ b/docs/tutorial/en/src/task_long_term_memory.py@@ -141,6 +141,328 @@ async def retrieve_preferences():asyncio.run(retrieve_preferences())+# %%+# Using ReMe Long-Term Memory+# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~+#+# .. note:: We provide an example of using ReMe long-term memory in the GitHub repository under the ``examples/long_term_memory/reme`` directory.+#++from agentscope.memory import ReMePersonalLongTermMemory++# Create ReMe personal long-term memory instance+reme_long_term_memory = ReMePersonalLongTermMemory(+ agent_name="Friday",+ user_name="user_123",+ model=DashScopeChatModel(+ model_name="qwen3-max",+ api_key=os.environ.get("DASHSCOPE_API_KEY"),+ stream=False,+ ),+ embedding_model=DashScopeTextEmbedding(+ model_name="text-embedding-v4",+ api_key=os.environ.get("DASHSCOPE_API_KEY"),+ dimensions=1024,+ ),+)++# %%+# The ``ReMePersonalLongTermMemory`` class provides four main methods for long-term memory operations.+# They include ``record_to_memory`` and ``retrieve_from_memory`` for tool calls,+# as well as ``record`` and ``retrieve`` for direct calls.+#+# As an example, we use ``record_to_memory`` to record user preferences.+#+++async def test_record_to_memory():+ """Test record_to_memory tool function interface"""+ async with reme_long_term_memory:+ result = await reme_long_term_memory.record_to_memory(+ thinking="The user is sharing their travel preferences and habits",+ content=[+ "I prefer to stay in homestays when traveling to Hangzhou",+ "I like to visit the West Lake in the morning",+ "I enjoy drinking Longjing tea",+ ],+ )+ # Extract result text+ result_text = " ".join(+ block.get("text", "")+ for block in result.content+ if block.get("type") == "text"+ )+ print(f"Recording result: {result_text}")+++# %%+# output+#+# .. code-block:: console+#+# Recording result: Successfully recorded 3 memory/memories to personal memory.+#+++# %%+# Then we use ``retrieve_from_memory`` to retrieve related memories.+#+++async def test_retrieve_from_memory():+ """Test retrieve_from_memory tool function interface"""+ async with reme_long_term_memory:+ # First record some content+ await reme_long_term_memory.record_to_memory(+ thinking="User is sharing travel preferences",+ content=[+ "I prefer to stay in homestays when traveling to Hangzhou",+ ],+ )++ # Then retrieve+ result = await reme_long_term_memory.retrieve_from_memory(+ keywords=["Hangzhou travel", "tea preference"],+ )+ retrieved_text = " ".join(+ block.get("text", "")+ for block in result.content+ if block.get("type") == "text"+ )+ print(f"Retrieved memories: {retrieved_text}")+++# %%+# output+#+# .. code-block:: console+#+# Retrieved memories: Keyword 'Hangzhou travel':+# user prefers to stay in homestays when traveling to Hangzhou+#+# Keyword 'tea preference':+# user prefers to stay in homestays when traveling to Hangzhou+#++# %%+# Besides the tool function interface, we can also use the ``record`` method to directly record message conversations.+++async def test_record_direct():+ """Test record direct recording method"""+ async with reme_long_term_memory:+ await reme_long_term_memory.record(+ msgs=[+ Msg(+ role="user",+ content="I work as a software engineer and prefer remote work",+ name="user",+ ),+ Msg(+ role="assistant",+ content="Understood! You're a software engineer who values remote work flexibility.",+ name="assistant",+ ),+ Msg(+ role="user",+ content="I usually start my day at 9 AM with a cup of coffee",+ name="user",+ ),+ ],+ )+ print("Successfully recorded conversation messages")+++# %%+# output+#+# .. code-block:: console+#+# Successfully recorded conversation messages+#++# %%+# Similarly, we use the ``retrieve`` method to retrieve related memories.+#+++async def test_retrieve_direct():+ """Test retrieve direct retrieval method"""+ async with reme_long_term_memory:+ # First record some content+ await reme_long_term_memory.record(+ msgs=[+ Msg(+ role="user",+ content="I work as a software engineer and prefer remote work",+ name="user",+ ),+ ],+ )++ # Then retrieve+ memories = await reme_long_term_memory.retrieve(+ msg=Msg(+ role="user",+ content="What do you know about my work preferences?",+ name="user",+ ),+ )+ print(+ f"Retrieved memories: {memories if memories else 'No memories found'}",+ )+++# %%+# output+#+# .. code-block:: console+#+# Retrieved memories: user works as a software engineer and prefers remote work++# %%+# Integration with ReAct Agent+# ----------------------------------------+# In AgentScope, the ``ReActAgent`` class receives a ``long_term_memory``+# parameter in its constructor, as well as a ``long_term_memory_mode`` parameter.+#+# If ``long_term_memory_mode`` is set to ``agent_control`` or ``both``,+# ``record_to_memory`` and ``retrieve_from_memory`` tool functions will be+# registered, allowing the agent to autonomously manage long-term memory through tool calls.+#+# .. note:: To achieve the best results, the ``"agent_control"`` mode may require+# additional instructions in the system prompt.+#+++# Create ReAct agent with long-term memory (agent_control mode)+async def test_react_agent_with_reme():+ """Test ReActAgent integration with ReMe personal memory"""+ async with reme_long_term_memory:+ agent_with_reme = ReActAgent(+ name="Friday",+ sys_prompt=(+ "You are a helpful assistant named Friday with long-term memory capabilities. "+ "\n\n## Memory Management Guidelines:\n"+ "1. **Recording Memories**: When users share personal information, preferences, "+ "habits, or facts about themselves, ALWAYS record them using `record_to_memory` "+ "for future reference.\n"+ "\n2. **Retrieving Memories**: BEFORE answering questions about the user's preferences, "+ "past information, or personal details, you MUST FIRST call `retrieve_from_memory` "+ "to check if you have any relevant stored information. Do NOT rely solely on the "+ "current conversation context.\n"+ "\n3. **When to Retrieve**: Call `retrieve_from_memory` when:\n"+ " - User asks questions like 'what do I like?', 'what are my preferences?', "+ "'what do you know about me?'\n"+ " - User asks about their past behaviors, habits, or preferences\n"+ " - User refers to information they mentioned before\n"+ " - You need context about the user to provide personalized responses\n"+ "\nAlways check your memory first before claiming you don't know something about the user."+ ),+ model=DashScopeChatModel(+ model_name="qwen3-max",+ api_key=os.environ.get("DASHSCOPE_API_KEY"),+ stream=False,+ ),+ formatter=DashScopeChatFormatter(),+ toolkit=Toolkit(),+ memory=InMemoryMemory(),+ long_term_memory=reme_long_term_memory,+ long_term_memory_mode="agent_control", # Use agent_control mode+ )++ # User shares preferences+ msg = Msg(+ role="user",+ content="When I travel to Hangzhou, I prefer to stay in a homestay",+ name="user",+ )+ response = await agent_with_reme(msg)+ print(f"Agent response: {response.get_text_content()}")++ # Clear short-term memory to test long-term memory+ await agent_with_reme.memory.clear()++ # Query preferences+ msg2 = Msg(+ role="user",+ content="what preference do I have?",+ name="user",+ )+ response2 = await agent_with_reme(msg2)+ print(f"Agent response: {response2.get_text_content()}")+++# %%+# output+#+# .. code-block:: console+#+# system: {+# "type": "tool_result",+# "id": "call_7de95a3382e241309b16cb9e",+# "name": "retrieve_from_memory",+# "output": [+# {+# "type": "text",+# "text": "Keyword 'preference':\nuser prefers to stay in a homestay when traveling to Hangzhou"+# }+# ]+# }+# Friday: Based on what I know, you prefer to stay in a homestay when traveling to Hangzhou. Let me know if there's anything else you'd like me to remember or clarify!+# Agent response: Based on what I know, you prefer to stay in a homestay when traveling to Hangzhou. Let me know if there's anything else you'd like me to remember or clarify!+#++# %%+# Then we clear the short-term memory and ask the agent about the user's preferences.+#+++async def retrieve_reme_preferences():+ """Retrieve user preferences from long-term memory"""+ async with reme_long_term_memory:+ # Create agent (reusing for demonstration completeness)+ agent_with_reme = ReActAgent(+ name="Friday",+ sys_prompt="You are an assistant with long-term memory capabilities.",+ model=DashScopeChatModel(+ api_key=os.environ.get("DASHSCOPE_API_KEY"),+ model_name="qwen3-max",+ stream=False,+ ),+ formatter=DashScopeChatFormatter(),+ toolkit=Toolkit(),+ memory=InMemoryMemory(),+ long_term_memory=reme_long_term_memory,+ long_term_memory_mode="agent_control",+ )++ # Clear short-term memory+ await agent_with_reme.memory.clear()+ # The agent will remember previous conversations+ msg2 = Msg("user", "What are my preferences? Answer briefly.", "user")+ await agent_with_reme(msg2)+++# %%+# output+#+# .. code-block:: console+#+# system: {+# "type": "tool_result",+# "id": "call_e7d354e450684ceca331a8d9",+# "name": "retrieve_from_memory",+# "output": [+# {+# "type": "text",+# "text": "No memories found for the given keywords."+# }+# ]+# }+# Friday: I don't have any recorded information about your preferences yet. Let me know what you like or need, and I can remember it for future reference!+#+# %%# Customizing Long-Term Memory# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~@@ -163,8 +485,17 @@ asyncio.run(retrieve_preferences())# - - For ``"static_control"`` mode, you must implement the ``record`` and ``retrieve`` methods.# - For ``"agent_control"`` mode, the ``record_to_memory`` and ``retrieve_from_memory`` methods must be implemented.# * - ``Mem0LongTermMemory``-# - \-+# - | ``record``+# | ``retrieve``+# | ``record_to_memory``+# | ``retrieve_from_memory``# - Long-term memory implementation based on the mem0 library, supporting vector storage and retrieval.+# * - ``ReMePersonalLongTermMemory``+# - | ``record``+# | ``retrieve``+# | ``record_to_memory``+# | ``retrieve_from_memory``+# - Personal memory implementation based on the ReMe framework, providing powerful memory management and retrieval capabilities.###diff --git a/docs/tutorial/zh_CN/src/task_long_term_memory.py b/docs/tutorial/zh_CN/src/task_long_term_memory.pyindex 16fdf0726..e6040de37 100644--- a/docs/tutorial/zh_CN/src/task_long_term_memory.py+++ b/docs/tutorial/zh_CN/src/task_long_term_memory.py@@ -129,6 +129,317 @@ async def retrieve_preferences():asyncio.run(retrieve_preferences())+# %%+# 使用 ReMe 个人长期记忆+# ~~~~~~~~~~~~~~~~~~~~~~~~+#+# .. note:: 在 GitHub 仓库的 ``examples/long_term_memory/reme`` 目录下我们提供了 ReMe 长期记忆的使用示例。+#++from agentscope.memory import ReMePersonalLongTermMemory++# 创建 ReMe 个人长期记忆实例+reme_long_term_memory = ReMePersonalLongTermMemory(+ agent_name="Friday",+ user_name="user_123",+ model=DashScopeChatModel(+ model_name="qwen3-max",+ api_key=os.environ.get("DASHSCOPE_API_KEY"),+ stream=False,+ ),+ embedding_model=DashScopeTextEmbedding(+ model_name="text-embedding-v4",+ api_key=os.environ.get("DASHSCOPE_API_KEY"),+ dimensions=1024,+ ),+)++# %%+# ``ReMePersonalLongTermMemory`` 类提供了四个操作长期记忆的方法。+# 它们分别是用于工具调用的 ``record_to_memory`` 和 ``retrieve_from_memory``,+# 以及用于直接调用的 ``record`` 和 ``retrieve``。+#+# 例如下面的例子中,我们使用 ``record_to_memory`` 记录用户偏好。+#+++async def test_record_to_memory():+ """测试 record_to_memory 工具函数接口"""+ async with reme_long_term_memory:+ result = await reme_long_term_memory.record_to_memory(+ thinking="用户正在分享他们的旅行偏好和习惯",+ content=[+ "我去杭州旅行时喜欢住民宿",+ "我喜欢早上去西湖游玩",+ "我喜欢喝龙井茶",+ ],+ )+ # 提取结果文本+ result_text = " ".join(+ block.get("text", "")+ for block in result.content+ if block.get("type") == "text"+ )+ print(f"记录结果: {result_text}")+++# %%+# 输出+#+# .. code-block:: console+#+# 记录结果: Successfully recorded 3 memory/memories to personal memory.+#+++# %%+# 然后我们使用 ``retrieve_from_memory`` 检索相关记忆。+#+++async def test_retrieve_from_memory():+ """测试 retrieve_from_memory 工具函数接口"""+ async with reme_long_term_memory:+ # 先记录一些内容+ await reme_long_term_memory.record_to_memory(+ thinking="用户正在分享旅行偏好",+ content=["我去杭州旅行时喜欢住民宿"],+ )++ # 然后检索+ result = await reme_long_term_memory.retrieve_from_memory(+ keywords=["杭州旅行", "茶偏好"],+ )+ retrieved_text = " ".join(+ block.get("text", "")+ for block in result.content+ if block.get("type") == "text"+ )+ print(f"检索到的记忆: {retrieved_text}")+++# %%+# 输出+#+# .. code-block:: console+#+# 检索到的记忆: Keyword 'Hangzhou travel':+# user prefers to stay in homestays when traveling to Hangzhou+#+# Keyword 'tea preference':+# user prefers to stay in homestays when traveling to Hangzhou+#++# %%+# 除了工具函数接口,我们也可以使用 ``record`` 方法直接记录消息对话。+#+++async def test_record_direct():+ """测试 record 直接记录方法"""+ async with reme_long_term_memory:+ await reme_long_term_memory.record(+ msgs=[+ Msg(+ role="user",+ content="我是一名软件工程师,喜欢远程工作",+ name="user",+ ),+ Msg(+ role="assistant",+ content="明白了!您是一名重视远程工作灵活性的软件工程师。",+ name="assistant",+ ),+ Msg(+ role="user",+ content="我通常早上9点开始工作,会先喝一杯咖啡",+ name="user",+ ),+ ],+ )+ print("成功记录了对话消息")+++# %%+# 输出+#+# .. code-block:: console+#+# 成功记录了对话消息+#++# %%+# 类似地,我们使用 ``retrieve`` 方法检索相关记忆。+#+++async def test_retrieve_direct():+ """测试 retrieve 直接检索方法"""+ async with reme_long_term_memory:+ # 先记录一些内容+ await reme_long_term_memory.record(+ msgs=[+ Msg(+ role="user",+ content="我是一名软件工程师,喜欢远程工作",+ name="user",+ ),+ ],+ )++ # 然后检索+ memories = await reme_long_term_memory.retrieve(+ msg=Msg(+ role="user",+ content="你知道我的工作偏好吗?",+ name="user",+ ),+ )+ print(f"检索到的记忆: {memories if memories else '未找到相关记忆'}")+++# %%+# 输出+#+# .. code-block:: console+#+# 检索到的记忆: user works as a software engineer and prefers remote work++# %%+# 与 ReAct 智能体集成+# ----------------------------------------+# AgentScope 中的 ``ReActAgent`` 在构造函数中包含 ``long_term_memory`` 和 ``long_term_memory_mode`` 两个参数。+#+# 当 ``long_term_memory_mode`` 设置为 ``"agent_control"`` 或 ``both`` 时,在 ``ReActAgent`` 的构造函数中将+# 注册 ``record_to_memory`` 和 ``retrieve_from_memory`` 工具函数,使智能体能够自主的管理长期记忆。+#+# .. note:: 为了达到最好的效果,``"agent_control"`` 模式可能还需要在系统提示(system prompt)中添加相应的说明。+#+++# 创建带有长期记忆的 ReAct 智能体(agent_control 模式)+async def test_react_agent_with_reme():+ """测试 ReActAgent 与 ReMe 个人记忆的集成"""+ async with reme_long_term_memory:+ agent_with_reme = ReActAgent(+ name="Friday",+ sys_prompt=(+ "你是一个名为 Friday 的助手,具有长期记忆能力。"+ "\n\n## 记忆管理指南:\n"+ "1. **记录记忆**:当用户分享个人信息、偏好、习惯或关于自己的事实时,"+ "始终使用 `record_to_memory` 记录这些信息以供将来参考。\n"+ "\n2. **检索记忆**:在回答关于用户偏好、过去信息或个人详细信息的问题之前,"+ "你必须首先调用 `retrieve_from_memory` 来检查是否有任何相关的存储信息。"+ "不要仅依赖当前对话上下文。\n"+ "\n3. **何时检索**:在以下情况下调用 `retrieve_from_memory`:\n"+ " - 用户问类似'我喜欢什么?'、'我的偏好是什么?'、"+ "'你对我了解多少?'的问题\n"+ " - 用户询问他们过去的行为、习惯或偏好\n"+ " - 用户提到他们之前提到的信息\n"+ " - 你需要关于用户的上下文来提供个性化的响应\n"+ "\n在声称不了解用户的某些信息之前,始终先检查你的记忆。"+ ),+ model=DashScopeChatModel(+ model_name="qwen3-max",+ api_key=os.environ.get("DASHSCOPE_API_KEY"),+ stream=False,+ ),+ formatter=DashScopeChatFormatter(),+ toolkit=Toolkit(),+ memory=InMemoryMemory(),+ long_term_memory=reme_long_term_memory,+ long_term_memory_mode="agent_control", # 使用 agent_control 模式+ )++ # 用户分享偏好+ msg = Msg(+ role="user",+ content="我去杭州旅行时,喜欢住民宿",+ name="user",+ )+ response = await agent_with_reme(msg)+ print(f"智能体响应: {response.get_text_content()}")++ # 清空短期记忆以测试长期记忆+ await agent_with_reme.memory.clear()++ # 查询偏好+ msg2 = Msg(role="user", content="我有什么偏好?", name="user")+ response2 = await agent_with_reme(msg2)+ print(f"智能体响应: {response2.get_text_content()}")+++# %%+# 输出+#+# .. code-block:: console+#+# system: {+# "type": "tool_result",+# "id": "call_7de95a3382e241309b16cb9e",+# "name": "retrieve_from_memory",+# "output": [+# {+# "type": "text",+# "text": "Keyword 'preference':\nuser prefers to stay in a homestay when traveling to Hangzhou"+# }+# ]+# }+# Friday: Based on what I know, you prefer to stay in a homestay when traveling to Hangzhou. Let me know if there's anything else you'd like me to remember or clarify!+# Agent response: Based on what I know, you prefer to stay in a homestay when traveling to Hangzhou. Let me know if there's anything else you'd like me to remember or clarify!+#++# %%+# 然后我们清空智能体的短期记忆,以避免造成干扰,并测试智能体是否会记住之前的对话。+#+++async def retrieve_reme_preferences():+ """从长期记忆中检索用户偏好"""+ async with reme_long_term_memory:+ # 创建智能体(这里可以复用之前创建的智能体,为了示例完整性重新创建)+ agent_with_reme = ReActAgent(+ name="Friday",+ sys_prompt="你是一个具有长期记忆功能的助手。",+ model=DashScopeChatModel(+ api_key=os.environ.get("DASHSCOPE_API_KEY"),+ model_name="qwen3-max",+ stream=False,+ ),+ formatter=DashScopeChatFormatter(),+ toolkit=Toolkit(),+ memory=InMemoryMemory(),+ long_term_memory=reme_long_term_memory,+ long_term_memory_mode="agent_control",+ )++ # 我们清空智能体的短期记忆,以避免造成干扰+ await agent_with_reme.memory.clear()++ # 测试智能体是否会记住之前的对话+ msg2 = Msg("user", "我有什么偏好?简要的回答我", "user")+ await agent_with_reme(msg2)+++# %%+# 输出+#+# .. code-block:: console+#+# system: {+# "type": "tool_result",+# "id": "call_e7d354e450684ceca331a8d9",+# "name": "retrieve_from_memory",+# "output": [+# {+# "type": "text",+# "text": "No memories found for the given keywords."+# }+# ]+# }+# Friday: I don't have any recorded information about your preferences yet. Let me know what you like or need, and I can remember it for future reference!+#+# %%# 自定义长期记忆# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~@@ -147,11 +458,20 @@ asyncio.run(retrieve_preferences())# | ``retrieve``# | ``record_to_memory``# | ``retrieve_from_memory``-# - - 如果想支持 “static_control” 模式,必须实现 ``record`` 和 ``retrieve`` 方法。-# - 想要支持 “agent_control” 模式,必须实现 ``record_to_memory`` 和 ``retrieve_from_memory`` 方法。+# - - 如果想支持 "static_control" 模式,必须实现 ``record`` 和 ``retrieve`` 方法。+# - 想要支持 "agent_control" 模式,必须实现 ``record_to_memory`` 和 ``retrieve_from_memory`` 方法。# * - ``Mem0LongTermMemory``-# - \-+# - | ``record``+# | ``retrieve``+# | ``record_to_memory``+# | ``retrieve_from_memory``# - 基于 mem0 库的长期记忆实现,支持向量存储和检索。+# * - ``ReMePersonalLongTermMemory``+# - | ``record``+# | ``retrieve``+# | ``record_to_memory``+# | ``retrieve_from_memory``+# - 基于 ReMe 框架的个人记忆实现,提供强大的记忆管理和检索功能。### 进一步阅读diff --git a/examples/functionality/long_term_memory/reme/README.md b/examples/functionality/long_term_memory/reme/README.mdnew file mode 100644index 000000000..e69f61951--- /dev/null+++ b/examples/functionality/long_term_memory/reme/README.md@@ -0,0 +1,609 @@+# ReMe Long-Term Memory in AgentScope++This example demonstrates how to:++- Use ReMe (Reflection Memory) to provide three specialized types of persistent memory storage for AgentScope agents+- Record and retrieve personal information, task execution trajectories, and tool usage patterns across sessions+- Integrate long-term memory with ReActAgent for context-aware conversations and continuous learning+- Configure DashScope embedding models and vector stores for efficient memory management++## Overview++ReMe (Reflection Memory) provides three types of long-term memory for intelligent agents:++1. **Personal Memory** (`ReMePersonalLongTermMemory`) - Records and retrieves persistent personal information, preferences, and facts about users+2. **Task Memory** (`ReMeTaskLongTermMemory`) - Learns from task execution trajectories and retrieves relevant past experiences for similar tasks+3. **Tool Memory** (`ReMeToolLongTermMemory`) - Records tool execution results and generates usage guidelines to improve tool calling++## Prerequisites++- Python 3.12 or higher+- DashScope API key from Alibaba Cloud (for the examples)++## QuickStart++### Installation++```bash+# Install agentscope from source+cd {PATH_TO_AGENTSCOPE}+pip install -e .++# Install required dependencies+pip install reme-ai python-dotenv+```++### Setup++Set up your API key:++```bash+export DASHSCOPE_API_KEY='YOUR_API_KEY'+```++Or create a `.env` file:++```bash+DASHSCOPE_API_KEY=YOUR_API_KEY+```++### Run Examples++```bash+# Personal Memory Example - 5 core interfaces+python personal_memory_example.py++# Task Memory Example - 5 core interfaces+python task_memory_example.py++# Tool Memory Example - Complete workflow with ReActAgent+python tool_memory_example.py+```++> **Note**: The examples use DashScope models by default. To use OpenAI or other models, modify the model initialization in the example code accordingly.++## Key Features++- **Three Specialized Memory Types**: Personal, Task, and Tool memory for different use cases+- **Dual Interface Design**: Both tool functions (for agent calling) and direct methods (for programmatic use)+- **Vector-based Retrieval**: Efficient semantic search using embedding models and vector stores+- **Async-first Architecture**: Full async/await support for non-blocking operations+- **ReActAgent Integration**: Seamless integration with AgentScope's ReActAgent and Toolkit+- **Automatic Context Management**: Uses async context managers for proper resource handling++## Core Concepts++### Memory Types and Their Use Cases++| Memory Type | Purpose | When to Use |+|------------|---------|-------------|+| **Personal Memory** | Store user preferences, habits, and personal facts | User profiles, personalized assistants, long-term user context |+| **Task Memory** | Learn from task execution trajectories | Problem-solving, debugging, repeated workflows, learning from past successes |+| **Tool Memory** | Record tool usage patterns and generate guidelines | Tool-using agents, improving tool call accuracy, avoiding past errors |++### Interface Design++**Personal Memory** and **Task Memory** provide **5 core interfaces**:++1. **`record_to_memory()`** - Tool function for agents to record memories (returns `ToolResponse`)+2. **`retrieve_from_memory()`** - Tool function for agents to retrieve memories (returns `ToolResponse`)+3. **`record()`** - Direct method for programmatic recording (returns `None`)+4. **`retrieve()`** - Direct method for programmatic retrieval (returns `str`)+5. **ReActAgent Integration** - Use memory with `long_term_memory` and `long_term_memory_mode` parameters++**Tool Memory** provides **2 core interfaces** (no tool functions):++1. **`record()`** - Direct method for recording tool execution results (returns `None`)+2. **`retrieve()`** - Direct method for retrieving tool usage guidelines (returns `str`)++## Usage Examples++### 1. Personal Memory++**Use Case**: Record and retrieve user preferences, habits, and personal information.++```python+import asyncio+import os+from agentscope.memory import ReMePersonalLongTermMemory+from agentscope.embedding import DashScopeTextEmbedding+from agentscope.message import Msg+from agentscope.model import DashScopeChatModel+++async def main():+ # Initialize personal memory+ personal_memory = ReMePersonalLongTermMemory(+ agent_name="Friday",+ user_name="user_123",+ model=DashScopeChatModel(+ model_name="qwen3-max",+ api_key=os.environ.get("DASHSCOPE_API_KEY"),+ stream=False,+ ),+ embedding_model=DashScopeTextEmbedding(+ model_name="text-embedding-v4",+ api_key=os.environ.get("DASHSCOPE_API_KEY"),+ dimensions=1024,+ ),+ )++ # Use async context manager (required!)+ async with personal_memory:+ # Interface 1: record_to_memory (tool function)+ result = await personal_memory.record_to_memory(+ thinking="User sharing travel preferences",+ content=[+ "I prefer to stay in homestays when traveling to Hangzhou",+ "I like to visit the West Lake in the morning",+ "I enjoy drinking Longjing tea",+ ],+ )++ # Interface 2: retrieve_from_memory (tool function)+ result = await personal_memory.retrieve_from_memory(+ keywords=["Hangzhou travel", "tea preference"],+ )++ # Interface 3: record (direct method)+ await personal_memory.record(+ msgs=[+ Msg(role="user", content="I work as a software engineer", name="user"),+ Msg(role="assistant", content="Got it!", name="assistant"),+ ],+ )++ # Interface 4: retrieve (direct method)+ memories = await personal_memory.retrieve(+ msg=Msg(role="user", content="What do you know about my work?", name="user"),+ )+ print(memories)+++asyncio.run(main())+```++**Integration with ReActAgent** (Interface 5):++```python+from agentscope.agent import ReActAgent+from agentscope.formatter import DashScopeChatFormatter+from agentscope.memory import InMemoryMemory+from agentscope.tool import Toolkit++async def use_with_agent():+ personal_memory = ReMePersonalLongTermMemory(...)++ async with personal_memory:+ agent = ReActAgent(+ name="Friday",+ sys_prompt="You are Friday with long-term memory. Always record user information and retrieve memories when needed.",+ model=DashScopeChatModel(...),+ formatter=DashScopeChatFormatter(),+ toolkit=Toolkit(),+ memory=InMemoryMemory(),+ long_term_memory=personal_memory, # Attach personal memory+ long_term_memory_mode="both", # Enable both record and retrieve tools+ )++ # Agent can now use record_to_memory and retrieve_from_memory as tools+ msg = Msg(role="user", content="I prefer staying in homestays", name="user")+ response = await agent(msg)+```++### 2. Task Memory++**Use Case**: Learn from task execution trajectories and retrieve relevant experiences.++```python+from agentscope.memory import ReMeTaskLongTermMemory+++async def main():+ # Initialize task memory+ task_memory = ReMeTaskLongTermMemory(+ agent_name="TaskAssistant",+ user_name="task_workspace_123", # Acts as workspace_id+ model=DashScopeChatModel(...),+ embedding_model=DashScopeTextEmbedding(...),+ )++ async with task_memory:+ # Interface 1: record_to_memory with score+ result = await task_memory.record_to_memory(+ thinking="Recording successful debugging approach",+ content=[+ "For API 404 errors: Check route definition, verify URL path, ensure correct port",+ "Always use linter to catch typos in route paths",+ ],+ score=0.95, # High score for successful trajectory+ )++ # Interface 2: retrieve_from_memory+ result = await task_memory.retrieve_from_memory(+ keywords=["debugging", "API errors"],+ )++ # Interface 3: record with score in direct method+ await task_memory.record(+ msgs=[+ Msg(role="user", content="I'm getting a 404 error", name="user"),+ Msg(role="assistant", content="Let's check the route path...", name="assistant"),+ Msg(role="user", content="Found the typo!", name="user"),+ ],+ score=0.95, # Optional score for this trajectory+ )++ # Interface 4: retrieve (direct method)+ experiences = await task_memory.retrieve(+ msg=Msg(role="user", content="How to debug API errors?", name="user"),+ )+ print(experiences)+++asyncio.run(main())+```++**Integration with ReActAgent** (Interface 5):++```python+async def use_with_agent():+ task_memory = ReMeTaskLongTermMemory(...)++ async with task_memory:+ agent = ReActAgent(+ name="TaskAssistant",+ sys_prompt="You are a task assistant. Record solutions and retrieve past experiences before solving problems.",+ model=DashScopeChatModel(...),+ formatter=DashScopeChatFormatter(),+ toolkit=Toolkit(),+ memory=InMemoryMemory(),+ long_term_memory=task_memory,+ long_term_memory_mode="both",+ )++ # Agent learns from task executions over time+ msg = Msg(role="user", content="How should I optimize database queries?", name="user")+ response = await agent(msg)+```++### 3. Tool Memory++**Use Case**: Record tool execution results and generate usage guidelines for better tool calling.++**Complete Workflow**:++```python+import json+from datetime import datetime+from agentscope.memory import ReMeToolLongTermMemory+from agentscope.tool import Toolkit, ToolResponse+from agentscope.message import Msg, TextBlock+++# Step 1: Define tools+async def web_search(query: str, max_results: int = 5) -> ToolResponse:+ """Search the web for information."""+ result = f"Found {max_results} results for query: '{query}'"+ return ToolResponse(content=[TextBlock(type="text", text=result)])+++async def main():+ # Initialize tool memory+ tool_memory = ReMeToolLongTermMemory(+ agent_name="ToolBot",+ user_name="tool_workspace_demo",+ model=DashScopeChatModel(...),+ embedding_model=DashScopeTextEmbedding(...),+ )++ async with tool_memory:+ # Step 2: Record tool execution history (accepts JSON strings in msgs)+ tool_result = {+ "create_time": datetime.now().strftime("%Y-%m-%d %H:%M:%S"),+ "tool_name": "web_search",+ "input": {"query": "Python asyncio tutorial", "max_results": 10},+ "output": "Found 10 results for query: 'Python asyncio tutorial'",+ "token_cost": 150,+ "success": True,+ "time_cost": 2.3+ }++ # Interface 1: record (accepts JSON strings in message content)+ await tool_memory.record(+ msgs=[Msg(role="assistant", content=json.dumps(tool_result), name="assistant")],+ )++ # Step 3: Retrieve tool guidelines+ # Interface 2: retrieve returns summarized guidelines+ guidelines = await tool_memory.retrieve(+ msg=Msg(role="user", content="web_search", name="user"),+ )++ # Step 4: Inject guidelines into agent system prompt+ toolkit = Toolkit()+ toolkit.register_tool_function(web_search)++ base_prompt = "You are ToolBot, a helpful AI assistant."+ enhanced_prompt = f"{base_prompt}\n\n# Tool Guidelines:\n{guidelines}"++ agent = ReActAgent(+ name="ToolBot",+ sys_prompt=enhanced_prompt, # Guidelines enhance tool usage+ model=DashScopeChatModel(...),+ formatter=DashScopeChatFormatter(),+ toolkit=toolkit,+ memory=InMemoryMemory(),+ )++ # Agent now uses tools with learned guidelines+ msg = Msg(role="user", content="Search for Python design patterns", name="user")+ response = await agent(msg)+++asyncio.run(main())+```++> **Note**: Tool Memory does NOT provide `record_to_memory()` and `retrieve_from_memory()` tool functions. It only provides direct `record()` and `retrieve()` methods. Tool Memory is designed to be used programmatically to enhance agent system prompts, not as agent-callable tools.++## API Reference++### Common Parameters++All memory types share these initialization parameters:++```python+ReMePersonalLongTermMemory(+ agent_name: str, # Name of the agent using this memory+ user_name: str, # User identifier (acts as workspace_id in ReMe)+ model: ModelWrapper, # LLM for summarization and processing+ embedding_model: EmbeddingWrapper, # Embedding model for vector retrieval+ vector_store_dir: str = "./memory_vector_store", # Storage location+)+```++### Interface Specifications++#### Personal Memory++| Interface | Type | Signature | Returns | Description |+|-----------|------|-----------|---------|-------------|+| `record_to_memory` | Tool Function | `(thinking: str, content: list[str])` | `ToolResponse` | Record personal information with reasoning |+| `retrieve_from_memory` | Tool Function | `(keywords: list[str], limit: int = 3)` | `ToolResponse` | Retrieve memories by keywords |+| `record` | Direct Method | `(msgs: list[Msg])` | `None` | Record message conversations |+| `retrieve` | Direct Method | `(msg: Msg, top_k: int = 3)` | `str` | Query-based retrieval |++**Parameters**:+- `thinking`: Reasoning about what to record+- `content`: List of strings to remember+- `keywords`: Search keywords+- `limit`: Results per keyword (tool function, default: 3)+- `top_k`: Total results to retrieve (direct method, default: 3)++#### Task Memory++| Interface | Type | Signature | Returns | Description |+|-----------|------|-----------|---------|-------------|+| `record_to_memory` | Tool Function | `(thinking: str, content: list[str], score: float = 1.0)` | `ToolResponse` | Record task trajectory with score |+| `retrieve_from_memory` | Tool Function | `(keywords: list[str], top_k: int = 5)` | `ToolResponse` | Retrieve experiences by keywords |+| `record` | Direct Method | `(msgs: list[Msg], score: float = 1.0)` | `None` | Record message conversations with score |+| `retrieve` | Direct Method | `(msg: Msg, top_k: int = 5)` | `str` | Query-based experience retrieval |++**Parameters**:+- `thinking`: Reasoning about the task execution+- `content`: Task execution information and insights+- `score`: Success score for the trajectory (0.0-1.0, default: 1.0)+- `keywords`: Search keywords (e.g., task type, domain)+- `top_k`: Number of results to retrieve (default: 5)++#### Tool Memory++| Interface | Type | Signature | Returns | Description |+|-----------|------|-----------|---------|-------------|+| `record` | Direct Method | `(msgs: list[Msg])` | `None` | Record tool results as messages (JSON format) |+| `retrieve` | Direct Method | `(msg: Msg)` | `str` | Retrieve guidelines for tools |++**Parameters**:+- `msgs`: List of messages where `content` contains JSON strings with tool execution metadata:+ - `create_time`: Timestamp (`"%Y-%m-%d %H:%M:%S"`)+ - `tool_name`: Tool identifier+ - `input`: Parameters used (dict)+ - `output`: Execution result (str)+ - `token_cost`: Token usage (int)+ - `success`: Execution status (bool)+ - `time_cost`: Duration in seconds (float)+- `msg`: Message containing tool name to retrieve guidelines for+- **Note**: Tool Memory does NOT provide tool functions (`record_to_memory` and `retrieve_from_memory`). It only provides direct methods for programmatic use.++### ReActAgent Integration Modes++When attaching **Personal Memory** or **Task Memory** to ReActAgent, use the `long_term_memory_mode` parameter:++```python+agent = ReActAgent(+ name="Assistant",+ long_term_memory=memory, # ReMePersonalLongTermMemory or ReMeTaskLongTermMemory+ long_term_memory_mode="both", # Options: "record", "retrieve", "both"+ # ... other parameters+)+```++**Modes**:+- `"record"`: Only adds `record_to_memory` tool to agent+- `"retrieve"`: Only adds `retrieve_from_memory` tool to agent+- `"both"`: Adds both tools (recommended for most use cases)++> **Note**: Tool Memory does NOT support ReActAgent integration with tool functions. Use Tool Memory programmatically to enhance system prompts as shown in the Tool Memory example.++### Async Context Manager (Required!)++All ReMe memory types **must** be used with async context managers:++```python+async with long_term_memory:+ # All memory operations must be within this context+ await long_term_memory.record(msgs=[...])+ result = await long_term_memory.retrieve(msg=...)+```++This ensures:+- Proper initialization of the ReMe backend+- Resource cleanup after operations+- Vector store connection management++### Custom Configuration++```python+from agentscope.memory import ReMePersonalLongTermMemory++# Custom storage location and models+memory = ReMePersonalLongTermMemory(+ agent_name="Friday",+ user_name="user_123",+ model=your_custom_model, # Any AgentScope-compatible LLM+ embedding_model=your_embedding, # Any AgentScope-compatible embedding model+ vector_store_dir="./custom_path", # Custom storage directory+)+```++## Example Files Overview++### `personal_memory_example.py`++Demonstrates **5 core interfaces** for personal memory:++1. **`record_to_memory()`** - Record user preferences using tool function+2. **`retrieve_from_memory()`** - Search memories by keywords using tool function+3. **`record()`** - Direct recording of message conversations+4. **`retrieve()`** - Direct query-based retrieval+5. **ReActAgent Integration** - Agent autonomously uses memory tools++**Key Features**:+- Recording travel preferences, work habits, and personal information+- Keyword-based and query-based retrieval+- System prompt guidelines for agent memory usage+- Automatic memory tool calling by ReActAgent++### `task_memory_example.py`++Demonstrates **5 core interfaces** for task memory:++1. **`record_to_memory()`** - Record task experiences with scores+2. **`retrieve_from_memory()`** - Retrieve relevant experiences by keywords+3. **`record()`** - Direct recording with trajectory scores+4. **`retrieve()`** - Direct experience retrieval+5. **ReActAgent Integration** - Agent learns from past task executions++**Key Features**:+- Recording project planning, debugging, and development experiences+- Score-based trajectory evaluation (0.0-1.0)+- Learning from successful and failed attempts+- Continuous improvement through experience retrieval++### `tool_memory_example.py`++Demonstrates the **complete workflow** for tool memory:++1. **Mock tools** - Define and register tools to Toolkit+2. **Record tool history** - Store execution results with metadata using `record()`+3. **Retrieve guidelines** - Get summarized usage guidelines using `retrieve()`+4. **Enhance agent prompt** - Inject guidelines into system prompt+5. **Use ReActAgent** - Agent uses tools with learned guidelines++**Key Features**:+- JSON-formatted tool execution recording via direct `record()` method+- Automatic guideline generation through summarization+- Multi-tool guideline retrieval via direct `retrieve()` method+- System prompt enhancement for better tool usage+- **Note**: Tool Memory does NOT provide agent-callable tool functions++## Architecture++### Inheritance Hierarchy++```+ReMeLongTermMemoryBase (abstract base)+├── ReMePersonalLongTermMemory+├── ReMeTaskLongTermMemory+└── ReMeToolLongTermMemory+```++**`ReMeLongTermMemoryBase`** provides:+- Integration with ReMe library's `ReMeApp`+- Async context manager implementation+- Common interface definitions+- Vector store and embedding management++### Memory Storage++- **Location**: `./memory_vector_store/` (configurable)+- **Isolation**: Each `user_name` maintains separate storage+- **Persistence**: Memories persist across sessions+- **Format**: Vector embeddings with metadata++## Best Practices++### 1. System Prompt Design++For agents with long-term memory, clearly specify when to record and retrieve:++```python+sys_prompt = """+You are an assistant with long-term memory.++Recording Guidelines:+- Record when users share personal information, preferences, or important facts+- Record successful task execution approaches and solutions+- Record tool execution results with detailed metadata++Retrieval Guidelines:+- ALWAYS retrieve before answering questions about past information+- Retrieve when dealing with similar tasks to past executions+- Check tool guidelines before using tools+"""+```++### 2. Score Assignment (Task Memory)++Use meaningful scores to prioritize experiences:++```python+# Successful trajectory+await task_memory.record_to_memory(..., score=0.95)++# Partially successful+await task_memory.record_to_memory(..., score=0.6)++# Failed trajectory (still useful to learn from)+await task_memory.record_to_memory(..., score=0.2)+```++### 3. Tool Memory Workflow++Follow this pattern for tool memory:++```+1. Execute tool → 2. Record result → 3. Trigger summarization → 4. Retrieve guidelines → 5. Use in agent+```++## Troubleshooting++### Common Issues++**Issue**: `RuntimeError: Memory not initialized`+- **Solution**: Always use `async with memory:` context manager++**Issue**: No memories retrieved+- **Solution**: Ensure you've recorded memories first and check `user_name` matches++**Issue**: Tool memory not generating guidelines+- **Solution**: Record multiple tool executions to trigger summarization++**Issue**: Agent not using memory tools+- **Solution**: Check `long_term_memory_mode="both"` and verify system prompt encourages memory usage++## References++- [ReMe Library](https://github.com/modelscope/ReMe) - Core memory implementation+- [AgentScope Documentation](https://github.com/modelscope/agentscope) - Framework documentation+- [DashScope API](https://dashscope.aliyun.com/) - Model API for examplesdiff --git a/examples/functionality/long_term_memory/reme/personal_memory_example.py b/examples/functionality/long_term_memory/reme/personal_memory_example.pynew file mode 100644index 000000000..a99b72a5c--- /dev/null+++ b/examples/functionality/long_term_memory/reme/personal_memory_example.py@@ -0,0 +1,289 @@+# -*- coding: utf-8 -*-+"""Personal memory example demonstrating ReMe personal memory.++This module provides examples of how to use the ReMePersonalMemory+class.++The example demonstrates 5 core interfaces:+1. record_to_memory - Tool function for explicit memory recording+2. retrieve_from_memory - Tool function for keyword-based retrieval+3. record - Direct method for recording message conversations+4. retrieve - Direct method for query-based retrieval+5. ReActAgent integration - Using personal memory with ReActAgent+"""++import asyncio+import os+from dotenv import load_dotenv++from agentscope.agent import ReActAgent+from agentscope.embedding import DashScopeTextEmbedding+from agentscope.formatter import DashScopeChatFormatter+from agentscope.memory import InMemoryMemory+from agentscope.memory import ReMePersonalLongTermMemory+from agentscope.message import Msg+from agentscope.model import DashScopeChatModel+from agentscope.tool import ToolResponse, Toolkit++load_dotenv()+++async def test_record_to_memory(+ memory: ReMePersonalLongTermMemory,+) -> None:+ """Test the record_to_memory tool function interface."""+ print("Interface 1: record_to_memory (Tool Function)")+ print("-" * 70)+ print("Purpose: Explicit memory recording with structured content")+ print("Test case: Recording user's travel preferences...")++ result: ToolResponse = await memory.record_to_memory(+ thinking=("The user is sharing their travel preferences and habits"),+ content=[+ "I prefer to stay in homestays when traveling to Hangzhou",+ "I like to visit the West Lake in the morning",+ "I enjoy drinking Longjing tea",+ ],+ )+ result_text = " ".join(+ block.get("text", "")+ for block in result.content+ if block.get("type") == "text"+ )+ print(f"✓ Result: {result_text}")+ print(+ f"✓ Status: {'Success' if 'Success' in result_text else 'Failed'}",+ )+ print()+++async def test_retrieve_from_memory(+ memory: ReMePersonalLongTermMemory,+) -> None:+ """Test the retrieve_from_memory tool function interface."""+ print("Interface 2: retrieve_from_memory (Tool Function)")+ print("-" * 70)+ print("Purpose: Keyword-based memory retrieval")+ print()++ result = await memory.retrieve_from_memory(+ keywords=["Hangzhou travel", "tea preference"],+ )+ retrieved_text = " ".join(+ block.get("text", "")+ for block in result.content+ if block.get("type") == "text"+ )+ print("✓ Retrieved memories:")+ print(f"{retrieved_text}")+ print()+++async def test_record_direct(memory: ReMePersonalLongTermMemory) -> None:+ """Test the direct record method interface."""+ print("Interface 3: record (Direct Recording)")+ print("-" * 70)+ print("Purpose: Direct recording of message conversations")+ print()+ print("Test case: Recording work preferences and habits...")++ try:+ await memory.record(+ msgs=[+ Msg(+ role="user",+ content=(+ "I work as a software engineer and prefer "+ "remote work"+ ),+ name="user",+ ),+ Msg(+ role="assistant",+ content=(+ "Understood! You're a software engineer who "+ "values remote work flexibility."+ ),+ name="assistant",+ ),+ Msg(+ role="user",+ content=(+ "I usually start my day at 9 AM with a "+ "cup of coffee"+ ),+ name="user",+ ),+ ],+ )+ print("✓ Status: Successfully recorded conversation messages")+ print(+ "✓ Messages recorded: 3 messages (user-assistant dialogue)",+ )+ except Exception as e:+ print(f"✗ Status: Failed - {str(e)}")+ print()+++async def test_retrieve_direct(memory: ReMePersonalLongTermMemory) -> None:+ """Test the direct retrieve method interface."""+ print("Interface 4: retrieve (Direct Retrieval)")+ print("-" * 70)+ print("Purpose: Query-based memory retrieval using messages")+ print()+ print(+ "Test case: Querying 'What do you know about my "+ "work preferences?'...",+ )++ memories = await memory.retrieve(+ msg=Msg(+ role="user",+ content="What do you know about my work preferences?",+ name="user",+ ),+ )+ print("✓ Retrieved memories:")+ print(f"{memories if memories else 'No memories found'}")+ status = (+ "Success - Found memories"+ if memories+ else "No relevant memories found"+ )+ print(f"✓ Status: {status}")+ print()+++async def test_react_agent_with_memory(+ memory: ReMePersonalLongTermMemory,+) -> None:+ """Test ReActAgent integration with personal memory."""+ print("Interface 5: ReActAgent with Personal Memory")+ print("-" * 70)+ print(+ "Purpose: Demonstrate how ReActAgent uses personal memory tools",+ )+ print()+ print("Test case: Agent-driven memory recording and retrieval...")++ toolkit = Toolkit()+ agent = ReActAgent(+ name="Friday",+ sys_prompt=(+ "You are a helpful assistant named Friday with long-term "+ "memory capabilities. "+ "\n\n## Memory Management Guidelines:\n"+ "1. **Recording Memories**: When users share personal "+ "information, preferences, "+ "habits, or facts about themselves, ALWAYS record them "+ "using `record_to_memory` "+ "for future reference.\n"+ "\n2. **Retrieving Memories**: BEFORE answering questions "+ "about the user's preferences, "+ "past information, or personal details, you MUST FIRST "+ "call `retrieve_from_memory` "+ "to check if you have any relevant stored information. "+ "Do NOT rely solely on the "+ "current conversation context.\n"+ "\n3. **When to Retrieve**: Call `retrieve_from_memory` "+ "when:\n"+ " - User asks questions like 'what do I like?', "+ "'what are my preferences?', "+ "'what do you know about me?'\n"+ " - User asks about their past behaviors, habits, or "+ "preferences\n"+ " - User refers to information they mentioned before\n"+ " - You need context about the user to provide "+ "personalized responses\n"+ "\nAlways check your memory first before claiming you "+ "don't know something about the user."+ ),+ model=DashScopeChatModel(+ model_name="qwen3-max",+ api_key=os.environ.get("DASHSCOPE_API_KEY"),+ stream=False,+ ),+ formatter=DashScopeChatFormatter(),+ toolkit=toolkit,+ memory=InMemoryMemory(),+ long_term_memory=memory,+ long_term_memory_mode="both",+ )++ await agent.memory.clear()++ print(+ "→ User: 'When I travel to Hangzhou, I prefer to stay in "+ "a homestay'",+ )+ msg = Msg(+ role="user",+ content=(+ "When I travel to Hangzhou, I prefer to stay in " "a homestay"+ ),+ name="user",+ )+ msg = await agent(msg)+ print(f"✓ Agent response: {msg.get_text_content()}\n")++ print("→ User: 'what preference do I have?'")+ msg = Msg(+ role="user",+ content="what preference do I have?",+ name="user",+ )+ msg = await agent(msg)+ print(f"✓ Agent response: {msg.get_text_content()}\n")++ print(+ "✓ Status: Successfully demonstrated ReActAgent with "+ "personal memory",+ )+ print()+++async def main() -> None:+ """Demonstrate the 5 core interfaces of ReMePersonalMemory.++ This example shows how to use:+ 1. record_to_memory - Tool function for explicit memory recording+ 2. retrieve_from_memory - Tool function for keyword-based retrieval+ 3. record - Direct method for recording message conversations+ 4. retrieve - Direct method for query-based retrieval+ 5. ReActAgent integration - Using personal memory with ReActAgent+ """+ long_term_memory = ReMePersonalLongTermMemory(+ agent_name="Friday",+ user_name="user_123",+ model=DashScopeChatModel(+ model_name="qwen3-max",+ api_key=os.environ.get("DASHSCOPE_API_KEY"),+ stream=False,+ ),+ embedding_model=DashScopeTextEmbedding(+ model_name="text-embedding-v4",+ api_key=os.environ.get("DASHSCOPE_API_KEY"),+ dimensions=1024,+ ),+ )++ print("=" * 70)+ print("ReMePersonalMemory - Testing 5 Core Interfaces")+ print("=" * 70)+ print()++ # Use async context manager to ensure proper initialization+ async with long_term_memory:+ # await test_record_to_memory(long_term_memory)+ # await test_retrieve_from_memory(long_term_memory)+ # await test_record_direct(long_term_memory)+ # await test_retrieve_direct(long_term_memory)+ await test_react_agent_with_memory(long_term_memory)++ print("=" * 70)+ print("Testing Complete: All 5 Core Interfaces Verified!")+ print("=" * 70)+++if __name__ == "__main__":+ asyncio.run(main())diff --git a/examples/functionality/long_term_memory/reme/task_memory_example.py b/examples/functionality/long_term_memory/reme/task_memory_example.pynew file mode 100644index 000000000..06bf0ee7f--- /dev/null+++ b/examples/functionality/long_term_memory/reme/task_memory_example.py@@ -0,0 +1,336 @@+# -*- coding: utf-8 -*-+"""Task memory example demonstrating ReMe task memory.++This module provides examples of how to use the ReMeTaskMemory class+using the ReMe library.++The example demonstrates 5 core interfaces:+1. record_to_memory - Tool function for recording task information+2. retrieve_from_memory - Tool function for keyword-based retrieval+3. record - Direct method for recording message conversations+ with scores+4. retrieve - Direct method for retrieving task experiences+5. ReActAgent integration - Using task memory with ReActAgent+"""++import asyncio+import os+from dotenv import load_dotenv++from agentscope.agent import ReActAgent+from agentscope.embedding import DashScopeTextEmbedding+from agentscope.formatter import DashScopeChatFormatter+from agentscope.memory import InMemoryMemory+from agentscope.memory import ReMeTaskLongTermMemory+from agentscope.message import Msg+from agentscope.model import DashScopeChatModel+from agentscope.tool import ToolResponse, Toolkit++load_dotenv()+++async def test_record_to_memory(memory: ReMeTaskLongTermMemory) -> None:+ """Test the record_to_memory tool function interface."""+ print("Interface 1: record_to_memory (Tool Function)")+ print("-" * 70)+ print(+ "Purpose: Record task execution information with thinking and content",+ )+ print()+ print("Test case: Recording project planning task information...")++ result: ToolResponse = await memory.record_to_memory(+ thinking=(+ "Recording project planning best practices and "+ "development approach"+ ),+ content=[+ "For web application projects, break down into phases: "+ "Requirements gathering, Design, Development, Testing, "+ "Deployment",+ "Development phase recommendations: Frontend (React), "+ "Backend (FastAPI), Database (PostgreSQL), Agile "+ "methodology with 2-week sprints",+ "Dependency management: Use npm for frontend and pip for "+ "Python backend, maintain requirements.txt and "+ "package.json files",+ ],+ score=0.9, # Optional: score for this trajectory (1.0)+ )+ result_text = " ".join(+ block.get("text", "")+ for block in result.content+ if block.get("type") == "text"+ )+ print(f"✓ Result: {result_text}")+ print(+ f"✓ Status: {'Success' if 'Success' in result_text else 'Failed'}",+ )+ print()+++async def test_retrieve_from_memory(+ memory: ReMeTaskLongTermMemory,+) -> None:+ """Test the retrieve_from_memory tool function interface."""+ print("Interface 2: retrieve_from_memory (Tool Function)")+ print("-" * 70)+ print("Purpose: Keyword-based retrieval of task experiences")+ print()+ print(+ "Test case: Searching with keywords 'project planning', "+ "'development phase'...",+ )++ result = await memory.retrieve_from_memory(+ keywords=["project planning", "development phase"],+ )+ retrieved_text = " ".join(+ block.get("text", "")+ for block in result.content+ if block.get("type") == "text"+ )+ print("✓ Retrieved experiences:")+ print(f"{retrieved_text}")+ has_experiences = (+ retrieved_text and "No task experiences found" not in retrieved_text+ )+ status = (+ "Success - Found experiences"+ if has_experiences+ else "No relevant experiences found"+ )+ print(f"✓ Status: {status}")+ print()+++async def test_record_direct(memory: ReMeTaskLongTermMemory) -> None:+ """Test the direct record method interface."""+ print("Interface 3: record (Direct Recording)")+ print("-" * 70)+ print("Purpose: Direct recording of message conversations with scores")+ print()+ print("Test case: Recording debugging task conversation...")++ try:+ await memory.record(+ msgs=[+ Msg(+ role="user",+ content="I'm getting a 404 error on my API endpoint",+ name="user",+ ),+ Msg(+ role="assistant",+ content=(+ "Let's troubleshoot: 1) Check if the route is "+ "properly defined, 2) Verify the URL path, "+ "3) Ensure the server is running on the correct "+ "port"+ ),+ name="assistant",+ ),+ Msg(+ role="user",+ content="Found it! The route path had a typo.",+ name="user",+ ),+ Msg(+ role="assistant",+ content=(+ "Great! Always double-check route paths and use "+ "a linter to catch typos early."+ ),+ name="assistant",+ ),+ ],+ score=0.95, # Optional: score (default: 1.0)+ )+ print("✓ Status: Successfully recorded debugging trajectory")+ print("✓ Messages recorded: 4 messages with score 0.95")+ except Exception as e:+ print(f"✗ Status: Failed - {str(e)}")+ print()+++async def test_retrieve_direct(memory: ReMeTaskLongTermMemory) -> None:+ """Test the direct retrieve method interface."""+ print("Interface 4: retrieve (Direct Retrieval)")+ print("-" * 70)+ print("Purpose: Query-based retrieval using messages")+ print()+ print("Test case: Querying 'How to debug API errors?'...")++ memories = await memory.retrieve(+ msg=Msg(+ role="user",+ content=(+ "How should I approach debugging API errors in my "+ "application?"+ ),+ name="user",+ ),+ )+ print("✓ Retrieved experiences:")+ print(f"{memories if memories else 'No experiences found'}")+ status = (+ "Success - Found experiences"+ if memories+ else "No relevant experiences found"+ )+ print(f"✓ Status: {status}")+ print()+++async def test_react_agent_with_memory(+ memory: ReMeTaskLongTermMemory,+) -> None:+ """Test ReActAgent integration with task memory."""+ print("Interface 5: ReActAgent with Task Memory")+ print("-" * 70)+ print(+ "Purpose: Demonstrate how ReActAgent uses task memory tools",+ )+ print()+ print(+ "Test case: Agent-driven task experience recording and "+ "retrieval...",+ )++ toolkit = Toolkit()+ agent = ReActAgent(+ name="TaskAssistant",+ sys_prompt=(+ "You are a helpful task assistant named TaskAssistant "+ "with long-term task memory. "+ "\n\n## Task Memory Management Guidelines:\n"+ "1. **Recording Task Experiences**: When you provide "+ "technical solutions, solve problems, "+ "or complete tasks, ALWAYS record the key insights using "+ "`record_to_memory`. Include:\n"+ " - Specific techniques and approaches used\n"+ " - Best practices and implementation details\n"+ " - Lessons learned and important considerations\n"+ " - Step-by-step procedures that worked well\n"+ "\n2. **Retrieving Past Experiences**: BEFORE solving a "+ "problem or answering technical "+ "questions, you MUST FIRST call `retrieve_from_memory` "+ "to check if you have relevant "+ "past experiences. This helps you:\n"+ " - Avoid repeating past mistakes\n"+ " - Leverage proven solutions\n"+ " - Provide more accurate and tested approaches\n"+ "\n3. **When to Retrieve**: Always retrieve when:\n"+ " - Asked about technical topics or problem-solving "+ "approaches\n"+ " - Asked to provide recommendations or best practices\n"+ " - Dealing with tasks similar to ones you may have "+ "handled before\n"+ " - User explicitly asks 'what do you know about...?' "+ "or 'have you seen this before?'\n"+ "\nAlways check your task memory first to provide the "+ "most informed responses."+ ),+ model=DashScopeChatModel(+ model_name="qwen3-max",+ api_key=os.environ.get("DASHSCOPE_API_KEY"),+ stream=False,+ ),+ formatter=DashScopeChatFormatter(),+ toolkit=toolkit,+ memory=InMemoryMemory(),+ long_term_memory=memory,+ long_term_memory_mode="both",+ )++ await agent.memory.clear()++ print(+ "→ User: 'Here are some database optimization techniques "+ "I learned'",+ )+ msg = Msg(+ role="user",+ content=(+ "I just learned some valuable database optimization "+ "techniques for slow queries: "+ "1) Add indexes on foreign keys and WHERE clause columns "+ "to speed up joins and filtering. "+ "2) Use table partitioning to divide large tables by "+ "date or category for faster queries. "+ "3) Implement query result caching with Redis to avoid "+ "repeated database hits. "+ "4) Optimize JOIN order - put smallest tables first to "+ "reduce intermediate result sets. "+ "5) Use EXPLAIN ANALYZE to identify bottlenecks and "+ "missing indexes. "+ "Please record these optimization techniques for future "+ "reference."+ ),+ name="user",+ )+ msg = await agent(msg)+ print(f"✓ Agent response: {msg.get_text_content()}\n")++ print(+ "→ User: 'What do you know about database optimization?'",+ )+ msg = Msg(+ role="user",+ content=(+ "What do you know about database optimization? "+ "Can you retrieve any past experiences?"+ ),+ name="user",+ )+ msg = await agent(msg)+ print(f"✓ Agent response: {msg.get_text_content()}\n")++ print()+++async def main() -> None:+ """Demonstrate the 5 core interfaces of ReMeTaskMemory.++ This example shows how to use:+ 1. record_to_memory - Tool function for recording task information+ 2. retrieve_from_memory - Tool function for keyword-based retrieval+ 3. record - Direct method for recording message conversations with scores+ 4. retrieve - Direct method for retrieving task experiences+ 5. ReActAgent integration - Using task memory with ReActAgent+ """+ long_term_memory = ReMeTaskLongTermMemory(+ agent_name="TaskAssistant",+ user_name="task_workspace_123",+ model=DashScopeChatModel(+ model_name="qwen3-max",+ api_key=os.environ.get("DASHSCOPE_API_KEY"),+ stream=False,+ ),+ embedding_model=DashScopeTextEmbedding(+ model_name="text-embedding-v4",+ api_key=os.environ.get("DASHSCOPE_API_KEY"),+ dimensions=1024,+ ),+ )++ print("=" * 70)+ print("ReMeTaskMemory - Testing 5 Core Interfaces")+ print("=" * 70)+ print()++ # Use async context manager to ensure proper initialization+ async with long_term_memory:+ # await test_record_to_memory(long_term_memory)+ # await test_retrieve_from_memory(long_term_memory)+ # await test_record_direct(long_term_memory)+ # await test_retrieve_direct(long_term_memory)+ await test_react_agent_with_memory(long_term_memory)++ print("=" * 70)+ print("Testing Complete: All 5 Core Interfaces Verified!")+ print("=" * 70)+++if __name__ == "__main__":+ asyncio.run(main())diff --git a/examples/functionality/long_term_memory/reme/tool_memory_example.py b/examples/functionality/long_term_memory/reme/tool_memory_example.pynew file mode 100644index 000000000..543e8c936--- /dev/null+++ b/examples/functionality/long_term_memory/reme/tool_memory_example.py@@ -0,0 +1,430 @@+# -*- coding: utf-8 -*-+"""Tool memory example demonstrating ReMe tool memory with ReActAgent.++This module demonstrates the complete workflow:+1. Mock a tool function and register it to Toolkit+2. Record tool execution results to tool memory using record()+3. Retrieve tool usage guidelines using retrieve()+4. Inject guidelines into ReActAgent's system prompt+5. Use ReActAgent with tool memory++This workflow helps LLMs learn from past tool usage patterns and+improve their tool calling decisions over time.+"""++import asyncio+import json+import os+from datetime import datetime+from dotenv import load_dotenv++from agentscope.agent import ReActAgent+from agentscope.embedding import DashScopeTextEmbedding+from agentscope.formatter import DashScopeChatFormatter+from agentscope.memory import InMemoryMemory+from agentscope.memory import ReMeToolLongTermMemory+from agentscope.message import Msg+from agentscope.message import TextBlock+from agentscope.model import DashScopeChatModel+from agentscope.tool import Toolkit, ToolResponse++load_dotenv()+++# ============================================================================+# Step 1: Mock tool functions+# ============================================================================+++async def web_search(query: str, max_results: int = 5) -> ToolResponse:+ """Search the web for information.++ Args:+ query: The search query string+ max_results: Maximum number of results to return++ Returns:+ ToolResponse containing search results+ """+ # Simulate web search+ result = f"Found {max_results} results for query: '{query}'"+ return ToolResponse(+ content=[+ TextBlock(+ type="text",+ text=result,+ ),+ ],+ )+++async def calculate(expression: str) -> ToolResponse:+ """Calculate a mathematical expression.++ Args:+ expression: Mathematical expression to evaluate++ Returns:+ ToolResponse containing calculation result+ """+ try:+ # Simple calculation (in real scenario, use safer evaluation)+ result = eval(expression) # noqa: S307+ return ToolResponse(+ content=[+ TextBlock(+ type="text",+ text=f"Result: {result}",+ ),+ ],+ )+ except Exception as e:+ return ToolResponse(+ content=[+ TextBlock(+ type="text",+ text=f"Error calculating '{expression}': {str(e)}",+ ),+ ],+ )+++# ============================================================================+# Step 2: Record tool execution history to tool memory+# ============================================================================+++async def record_tool_history(+ tool_memory: ReMeToolLongTermMemory,+) -> None:+ """Record historical tool execution results to tool memory.++ This simulates past tool usage that the agent can learn from.+ """+ print("=" * 70)+ print("Step 1: Recording Tool Execution History to Memory")+ print("=" * 70)+ print()++ # Record successful web_search examples+ web_search_histories = [+ {+ "create_time": datetime.now().strftime("%Y-%m-%d %H:%M:%S"),+ "tool_name": "web_search",+ "input": {+ "query": "Python asyncio tutorial",+ "max_results": 10,+ },+ "output": (+ "Found 10 results for query: 'Python asyncio tutorial'"+ ),+ "token_cost": 150,+ "success": True,+ "time_cost": 2.3,+ },+ {+ "create_time": datetime.now().strftime("%Y-%m-%d %H:%M:%S"),+ "tool_name": "web_search",+ "input": {+ "query": "machine learning basics",+ "max_results": 5,+ },+ "output": ("Found 5 results for query: 'machine learning basics'"),+ "token_cost": 120,+ "success": True,+ "time_cost": 1.8,+ },+ ]++ # Record failed web_search example (empty query)+ web_search_fail = {+ "create_time": datetime.now().strftime("%Y-%m-%d %H:%M:%S"),+ "tool_name": "web_search",+ "input": {+ "query": "",+ "max_results": 5,+ },+ "output": "Error: Query cannot be empty",+ "token_cost": 20,+ "success": False,+ "time_cost": 0.1,+ }++ # Record calculate examples+ calculate_histories = [+ {+ "create_time": datetime.now().strftime("%Y-%m-%d %H:%M:%S"),+ "tool_name": "calculate",+ "input": {+ "expression": "2 + 2",+ },+ "output": "Result: 4",+ "token_cost": 30,+ "success": True,+ "time_cost": 0.05,+ },+ {+ "create_time": datetime.now().strftime("%Y-%m-%d %H:%M:%S"),+ "tool_name": "calculate",+ "input": {+ "expression": "10 * 5 + 3",+ },+ "output": "Result: 53",+ "token_cost": 30,+ "success": True,+ "time_cost": 0.05,+ },+ ]++ # Record all histories+ all_histories = (+ web_search_histories + [web_search_fail] + calculate_histories+ )++ print(f"Recording {len(all_histories)} tool execution histories...")+ await tool_memory.record(+ msgs=[+ Msg(+ role="assistant",+ content=json.dumps(history),+ name="assistant",+ )+ for history in all_histories+ ],+ )+ print(f"✓ Successfully recorded {len(all_histories)} tool executions")+ print()+++# ============================================================================+# Step 3: Retrieve tool guidelines and create enhanced system prompt+# ============================================================================+++async def retrieve_tool_guidelines(+ tool_memory: ReMeToolLongTermMemory,+ tool_names: list[str],+) -> str:+ """Retrieve tool usage guidelines from memory.++ Args:+ tool_memory: The ReMeToolMemory instance+ tool_names: List of tool names to retrieve guidelines for++ Returns:+ Combined guidelines text to be added to system prompt+ """+ print("=" * 70)+ print("Step 2: Retrieving Tool Usage Guidelines from Memory")+ print("=" * 70)+ print()++ all_guidelines = []++ for tool_name in tool_names:+ print(f"Retrieving guidelines for '{tool_name}'...")+ guidelines = await tool_memory.retrieve(+ msg=Msg(+ role="user",+ content=tool_name,+ name="user",+ ),+ )++ if guidelines:+ all_guidelines.append(+ f"## Guidelines for {tool_name}:\n{guidelines}",+ )+ print(f"✓ Retrieved guidelines for '{tool_name}'")+ print(f" Preview: {guidelines}")+ else:+ print(+ f"✓ No guidelines found for '{tool_name}' " "(first time use)",+ )+ print()++ if all_guidelines:+ combined_guidelines = "\n\n".join(all_guidelines)+ guidelines_prompt = f"""+# Tool Usage Guidelines (from past experience)++{combined_guidelines}++Please follow these guidelines when using the tools.+"""+ return guidelines_prompt+ else:+ return ""+++# ============================================================================+# Step 4: Use ReActAgent with tool memory+# ============================================================================+++async def use_react_agent_with_tool_memory(+ toolkit: Toolkit,+ tool_guidelines: str,+) -> None:+ """Create and use ReActAgent with tool memory guidelines.++ Args:+ toolkit: The Toolkit with registered tools+ tool_guidelines: Retrieved tool usage guidelines+ """+ print("=" * 70)+ print("Step 3: Using ReActAgent with Tool Memory")+ print("=" * 70)+ print()++ # Create enhanced system prompt with tool guidelines+ base_sys_prompt = (+ "You are a helpful AI assistant named ToolBot.\n"+ "You have access to various tools to help users complete "+ "their tasks.\n"+ "Please use the tools appropriately based on the user's "+ "requests."+ )++ if tool_guidelines:+ sys_prompt = f"{base_sys_prompt}\n{tool_guidelines}"+ print(+ "✓ System prompt enhanced with tool memory guidelines",+ )+ else:+ sys_prompt = base_sys_prompt+ print(+ "✓ Using base system prompt (no guidelines available)",+ )++ print()++ # Create ReActAgent+ agent = ReActAgent(+ name="ToolBot",+ sys_prompt=sys_prompt,+ model=DashScopeChatModel(+ model_name="qwen-max",+ api_key=os.environ.get("DASHSCOPE_API_KEY"),+ stream=False,+ ),+ formatter=DashScopeChatFormatter(),+ toolkit=toolkit,+ memory=InMemoryMemory(),+ max_iters=5,+ )++ print("✓ ReActAgent created successfully")+ print()++ # Test queries+ test_queries = [+ "Search the web for 'Python design patterns'",+ "Calculate 15 * 7 + 23",+ ]++ print("-" * 70)+ print("Testing ReActAgent with tool memory...")+ print("-" * 70)+ print()++ for i, query in enumerate(test_queries, 1):+ print(f"Query {i}: {query}")+ print("-" * 70)++ msg = Msg(+ role="user",+ content=query,+ name="user",+ )++ response = await agent(msg)+ print(f"Response: {response.get_text_content()}")+ print()+ print()+++async def main() -> None:+ """Demonstrate the workflow of using ReMeToolMemory with ReActAgent.++ This example shows:+ 1. Create mock tools and register them to Toolkit+ 2. Record historical tool execution results to tool memory+ 3. Retrieve tool usage guidelines from memory+ 4. Inject guidelines into ReActAgent's system prompt+ 5. Use ReActAgent to complete tasks with tool memory+ """+ print("=" * 70)+ print("ReMeToolMemory + ReActAgent Integration Example")+ print("=" * 70)+ print()+ print("This workflow demonstrates:")+ print("1. Mock tools → Register to Toolkit")+ print("2. Record tool execution history → Tool Memory")+ print("3. Retrieve guidelines → Enhance system prompt")+ print("4. Use ReActAgent with tool memory")+ print()++ # Initialize tool memory+ tool_memory = ReMeToolLongTermMemory(+ agent_name="ToolBot",+ user_name="tool_workspace_demo",+ model=DashScopeChatModel(+ model_name="qwen-max",+ api_key=os.environ.get("DASHSCOPE_API_KEY"),+ stream=False,+ ),+ embedding_model=DashScopeTextEmbedding(+ model_name="text-embedding-v4",+ api_key=os.environ.get("DASHSCOPE_API_KEY"),+ dimensions=1024,+ ),+ )++ # Create and register tools to toolkit+ toolkit = Toolkit()+ toolkit.register_tool_function(web_search)+ toolkit.register_tool_function(calculate)+ print()++ # Use async context manager for tool memory+ async with tool_memory:+ # Step 1: Record historical tool executions to memory+ await record_tool_history(tool_memory)++ # Step 2: Retrieve tool usage guidelines+ tool_names = ["web_search", "calculate"]+ tool_guidelines = await retrieve_tool_guidelines(+ tool_memory,+ tool_names,+ )++ # Step 3: Use ReActAgent with enhanced system prompt+ await use_react_agent_with_tool_memory(+ toolkit,+ tool_guidelines,+ )++ print("=" * 70)+ print("Workflow Complete!")+ print("=" * 70)+ print()+ print("Summary:")+ print("✓ Mock tools created and registered to Toolkit")+ print("✓ Historical tool executions recorded to tool memory")+ print("✓ Tool usage guidelines retrieved from memory")+ print("✓ ReActAgent system prompt enhanced with guidelines")+ print(+ "✓ ReActAgent successfully used tools with memory guidance",+ )+ print()+ print("Benefits:")+ print("- Agent learns from past tool usage patterns")+ print("- Reduced errors by following proven guidelines")+ print("- Better tool parameter selection")+ print("- Improved success rate over time")+ print("=" * 70)+++if __name__ == "__main__":+ asyncio.run(main())diff --git a/pyproject.toml b/pyproject.tomlindex 24635a5ce..a70537163 100644--- a/pyproject.toml+++ b/pyproject.toml@@ -68,6 +68,8 @@ dev = ["myst_parser","matplotlib","pymilvus[milvus_lite]",+ # Long-term memory+ "reme-ai>=0.1.10.7; python_full_version >= '3.12'",][project.urls]diff --git a/src/agentscope/memory/__init__.py b/src/agentscope/memory/__init__.pyindex 696d4cb19..f779a7957 100644--- a/src/agentscope/memory/__init__.py+++ b/src/agentscope/memory/__init__.py@@ -1,15 +1,22 @@# -*- coding: utf-8 -*-"""The memory module."""-from ._memory_base import MemoryBasefrom ._in_memory_memory import InMemoryMemoryfrom ._long_term_memory_base import LongTermMemoryBasefrom ._mem0_long_term_memory import Mem0LongTermMemory-+from ._memory_base import MemoryBase+from ._reme import (+ ReMePersonalLongTermMemory,+ ReMeTaskLongTermMemory,+ ReMeToolLongTermMemory,+)__all__ = ["MemoryBase","InMemoryMemory","LongTermMemoryBase","Mem0LongTermMemory",+ "ReMePersonalLongTermMemory",+ "ReMeTaskLongTermMemory",+ "ReMeToolLongTermMemory",]diff --git a/src/agentscope/memory/_reme/__init__.py b/src/agentscope/memory/_reme/__init__.pynew file mode 100644index 000000000..c89565dfb--- /dev/null+++ b/src/agentscope/memory/_reme/__init__.py@@ -0,0 +1,12 @@+# -*- coding: utf-8 -*-+"""The reme memory module."""++from ._reme_personal_long_term_memory import ReMePersonalLongTermMemory+from ._reme_task_long_term_memory import ReMeTaskLongTermMemory+from ._reme_tool_long_term_memory import ReMeToolLongTermMemory++__all__ = [+ "ReMePersonalLongTermMemory",+ "ReMeTaskLongTermMemory",+ "ReMeToolLongTermMemory",+]diff --git a/src/agentscope/memory/_reme/_reme_long_term_memory_base.py b/src/agentscope/memory/_reme/_reme_long_term_memory_base.pynew file mode 100644index 000000000..ca4e4de3f--- /dev/null+++ b/src/agentscope/memory/_reme/_reme_long_term_memory_base.py@@ -0,0 +1,374 @@+# -*- coding: utf-8 -*-+"""Base long-term memory implementation using ReMe library.++This module provides a base class for long-term memory implementations+that integrate with the ReMe library. ReMe enables agents to maintain+persistent, searchable memories across sessions and contexts.++The module handles the integration between AgentScope's memory system and+the ReMe library, including:+- Model configuration and API credential management+- Context lifecycle management (async context managers)+- Graceful handling of missing dependencies+- Error handling with helpful installation instructions++Key Features:+- Supports both DashScope and OpenAI model providers+- Automatic extraction of API credentials and endpoints+- Flexible configuration via config files or kwargs+- Safe fallback behavior when reme_ai is not installed++Dependencies:+ The ReMe library is an optional dependency that must be installed:++ .. code-block:: bash++ pip install reme-ai++ Python 3.12 or greater is required to use ReMe.+ For more information, visit: https://github.com/modelscope/reMe++Subclasses:+ This base class is extended by specific memory type implementations:+ - ReMeToolLongTermMemory: For tool execution patterns and guidelines+ - ReMeTaskLongTermMemory: For task execution experiences and learnings+ - ReMePersonalLongTermMemory: For user preferences and personal information++Example:+ .. code-block:: python++ from agentscope.models import OpenAIChatModel+ from agentscope.embedding import OpenAITextEmbedding+ from agentscope.memory._reme import ReMeToolLongTermMemory++ # Initialize models+ model = OpenAIChatModel(model_name="gpt-4", api_key="...")+ embedding = OpenAITextEmbedding(+ model_name="text-embedding-3-small", api_key="...")++ # Create memory instance+ memory = ReMeToolLongTermMemory(+ agent_name="my_agent",+ user_name="user_123",+ model=model,+ embedding_model=embedding+ )++ # Use memory in async context+ async with memory:+ # Record tool execution+ await memory.record_to_memory(+ thinking="This tool worked well for data processing",+ content=['{"tool_name": "process_data", "success": true, ...}']+ )++ # Retrieve tool guidelines+ result = await memory.retrieve_from_memory(+ keywords=["process_data"]+ )++"""+from abc import ABCMeta+from typing import Any++from .._long_term_memory_base import LongTermMemoryBase+from ...embedding import (+ DashScopeTextEmbedding,+ OpenAITextEmbedding,+)+from ...model import (+ DashScopeChatModel,+ OpenAIChatModel,+)+++class ReMeLongTermMemoryBase(LongTermMemoryBase, metaclass=ABCMeta):+ """Base class for ReMe-based long-term memory implementations.++ This class provides the foundation for integrating AgentScope with the ReMe+ library, enabling agents to maintain and retrieve long-term memories across+ different contexts.++ The ReMe library must be installed separately:+ pip install reme-ai++ Requirements:+ Python 3.12 or greater is required to use ReMe.++ If the library is not installed, a warning will be issued during+ initialization,+ and runtime errors with installation instructions will be raised+ when attempting+ to use memory operations.+ """++ def __init__(+ self,+ agent_name: str | None = None,+ user_name: str | None = None,+ run_name: str | None = None,+ model: DashScopeChatModel | OpenAIChatModel | None = None,+ embedding_model: (+ DashScopeTextEmbedding | OpenAITextEmbedding | None+ ) = None,+ reme_config_path: str | None = None,+ **kwargs: Any,+ ) -> None:+ """Initialize the ReMe-based long-term memory.++ This constructor sets up the connection to the ReMe+ library and configures+ the necessary models for memory operations. The ReMe app+ will be initialized+ with the provided model configurations.++ Args:+ agent_name (`str | None`, optional):+ Name identifier for the agent. Used for organizing+ memories by agent.+ user_name (`str | None`, optional):+ Unique identifier for the user or workspace. This maps+ to workspace_id in ReMe and helps isolate memories across+ different users/workspaces.+ run_name (`str | None`, optional):+ Name identifier for the current execution run or session.+ model (`DashScopeChatModel | OpenAIChatModel | None`, optional):+ The chat model to use for memory operations. The model's+ API credentials and endpoint will be extracted and+ passed to ReMe.+ embedding_model (`DashScopeTextEmbedding | OpenAITextEmbedding | \+ None`, optional):+ The embedding model to use for semantic memory retrieval.+ The model's API credentials and endpoint will be+ extracted and passed to ReMe.+ reme_config_path (`str | None`, optional):+ Path to a custom ReMe configuration file. If not provided, ReMe+ will use its default configuration.+ **kwargs (`Any`):+ Additional keyword arguments to pass to the+ ReMeApp constructor.+ These can include custom ReMe configuration parameters.++ Raises:+ `ValueError`:+ If the provided model is not a DashScopeChatModel or+ OpenAIChatModel, or if the embedding_model is not a+ DashScopeTextEmbedding or OpenAITextEmbedding.++ Note:+ If the reme_ai library is not installed, a warning will be+ issued and self.app will be set to None. Subsequent memory+ operations will raise RuntimeError with installation+ instructions.++ Example:+ .. code-block:: python++ from agentscope.models import OpenAIChatModel+ from agentscope.embedding import OpenAITextEmbedding+ from agentscope.memory._reme import ReMeToolLongTermMemory++ # Initialize models+ model = OpenAIChatModel(+ model_name="gpt-4",+ api_key="your-api-key"+ )+ embedding = OpenAITextEmbedding(+ model_name="text-embedding-3-small",+ api_key="your-api-key"+ )++ # Create memory instance+ memory = ReMeToolLongTermMemory(+ agent_name="my_agent",+ user_name="user_123",+ run_name="session_001",+ model=model,+ embedding_model=embedding+ )++ # Use with async context manager+ async with memory:+ # Memory operations...+ pass++ """+ super().__init__()++ # Store agent and workspace identifiers+ self.agent_name = agent_name+ # Maps to ReMe's workspace_id concept+ self.workspace_id = user_name+ self.run_name = run_name++ # Build configuration arguments for ReMeApp+ # These will be passed as command-line style config overrides+ config_args = []++ # Extract LLM API credentials based on model type+ # DashScope uses a fixed endpoint, OpenAI can have custom base_url+ if isinstance(model, DashScopeChatModel):+ llm_api_base = "https://dashscope.aliyuncs.com/compatible-mode/v1"+ llm_api_key = model.api_key++ elif isinstance(model, OpenAIChatModel):+ llm_api_base = str(getattr(model.client, "base_url", None))+ llm_api_key = str(getattr(model.client, "api_key", None))++ else:+ raise ValueError(+ f"model must be a DashScopeChatModel or "+ f"OpenAIChatModel instance. "+ f"Got {type(model).__name__} instead.",+ )++ # Extract model name and add to config if provided+ llm_model_name = model.model_name++ if llm_model_name:+ config_args.append(f"llm.default.model_name={llm_model_name}")++ # Extract embedding model API credentials based on type+ # Similar to LLM, DashScope uses fixed endpoint,+ # OpenAI can be customized+ if isinstance(embedding_model, DashScopeTextEmbedding):+ embedding_api_base = (+ "https://dashscope.aliyuncs.com/compatible-mode/v1"+ )+ embedding_api_key = embedding_model.api_key++ elif isinstance(embedding_model, OpenAITextEmbedding):+ embedding_api_base = getattr(+ embedding_model.client,+ "base_url",+ None,+ )+ embedding_api_key = getattr(+ embedding_model.client,+ "api_key",+ None,+ )++ else:+ raise ValueError(+ "embedding_model must be a DashScopeTextEmbedding or "+ "OpenAITextEmbedding instance. "+ f"Got {type(embedding_model).__name__} instead.",+ )++ # Extract embedding model name and add to config if provided+ embedding_model_name = embedding_model.model_name++ if embedding_model_name:+ config_args.append(+ f"embedding_model.default.model_name={embedding_model_name}",+ )++ # Attempt to import and initialize ReMe+ # If import fails, set app to None and issue a warning+ # This allows the class to be instantiated even without+ # reme_ai installed+ try:+ from reme_ai import ReMeApp+ except ImportError as e:+ raise ImportError(+ "The 'reme_ai' library is required for ReMe-based "+ "long-term memory. Please install it by `pip install reme-ai`,"+ "and visit: https://github.com/modelscope/reMe for more "+ "information.",+ ) from e++ # Initialize ReMe with extracted configurations+ self.app = ReMeApp(+ *config_args, # Config overrides as positional args+ llm_api_key=llm_api_key,+ llm_api_base=llm_api_base,+ embedding_api_key=embedding_api_key,+ embedding_api_base=embedding_api_base,+ # Optional custom config file+ config_path=reme_config_path,+ # Additional ReMe-specific configurations+ **kwargs,+ )++ # Track if the app context is active (started via __aenter__)+ self._app_started = False++ async def __aenter__(self) -> "ReMeLongTermMemoryBase":+ """Async context manager entry point.++ This method is called when entering an async context+ (using 'async with'). It initializes the ReMe app context if+ available, enabling memory operations within the context block.++ Returns:+ `ReMeLongTermMemoryBase`:+ The memory instance itself, allowing it to be used in+ the context.++ Example:+ .. code-block:: python++ memory = ReMeToolLongTermMemory(+ agent_name="my_agent",+ model=model,+ embedding_model=embedding+ )++ async with memory:+ # Memory operations can be performed here+ await memory.record_to_memory(+ thinking="Recording tool usage",+ content=[...]+ )++ """+ if self.app is not None:+ await self.app.__aenter__()+ self._app_started = True+ return self++ async def __aexit__(+ self,+ exc_type: Any,+ exc_val: Any,+ exc_tb: Any,+ ) -> None:+ """Async context manager exit point.++ This method is called when exiting an async context (at the end+ of 'async with' block or when an exception occurs). It properly+ cleans up the ReMe app context and resources.++ Args:+ exc_type (`Any`):+ The type of exception that occurred, if any. None if no+ exception.+ exc_val (`Any`):+ The exception instance that occurred, if any. None if no+ exception.+ exc_tb (`Any`):+ The traceback object for the exception, if any. None if+ no exception.++ .. note:: This method will gracefully handle the case where self.app+ is None (reme_ai not installed) by skipping the cleanup but still+ marking the app as stopped. It will also always set _app_started+ to False, ensuring the memory state is properly reset.++ Example:+ .. code-block:: python++ async with memory:+ try:+ # Memory operations+ await memory.record_to_memory(...)+ except Exception as e:+ # __aexit__ will be called even if an exception occurs+ print(f"Error: {e}")+ # __aexit__ has been called and resources are cleaned up++ """+ if self.app is not None:+ await self.app.__aexit__(exc_type, exc_val, exc_tb)+ self._app_started = Falsediff --git a/src/agentscope/memory/_reme/_reme_personal_long_term_memory.py b/src/agentscope/memory/_reme/_reme_personal_long_term_memory.pynew file mode 100644index 000000000..d76006364--- /dev/null+++ b/src/agentscope/memory/_reme/_reme_personal_long_term_memory.py@@ -0,0 +1,410 @@+# -*- coding: utf-8 -*-+"""Personal memory implementation using ReMe library.++This module provides a personal memory implementation that integrates+with the ReMe library to provide persistent personal memory storage and+retrieval capabilities for AgentScope agents.++Requirements:+ Python 3.12 or greater is required to use ReMe.+"""+from typing import Any++from ._reme_long_term_memory_base import ReMeLongTermMemoryBase+from ..._logging import logger+from ...message import Msg, TextBlock+from ...tool import ToolResponse+++class ReMePersonalLongTermMemory(ReMeLongTermMemoryBase):+ """Personal memory implementation using ReMe library.++ Requirements:+ Python 3.12 or greater is required to use ReMe.+ """++ async def record_to_memory(+ self,+ thinking: str,+ content: list[str],+ **kwargs: Any,+ ) -> ToolResponse:+ """Record important user information to long-term memory.++ Record important user information to long-term memory for future+ reference.++ Use this function to save user's personal information,+ preferences, habits, and facts that you may need in future+ conversations. This enables you to provide personalized and+ contextually relevant responses.++ When to record:++ - User shares personal preferences (e.g., "I prefer homestays+ when traveling")+ - User mentions habits or routines (e.g., "I start work at 9 AM")+ - User states likes/dislikes (e.g., "I enjoy drinking green tea")+ - User provides personal facts (e.g., "I work as a software+ engineer")++ What to record: Be specific and structured. Include who, when,+ where, what, why, and how when relevant.++ Args:+ thinking (`str`):+ Your reasoning about why this information is worth+ recording and how it might be useful later.+ content (`list[str]`):+ List of specific facts to remember. Each string should be+ a clear, standalone piece of information. Examples:+ ["User prefers homestays in Hangzhou", "User likes+ visiting West Lake in the morning"].+ **kwargs (`Any`):+ Additional keyword arguments for the recording operation.++ Returns:+ `ToolResponse`:+ Confirmation message indicating successful memory+ recording.+ """+ logger.info(+ "[ReMePersonalMemory] Entering record_to_memory - "+ "thinking: %s, content: %s, kwargs: %s",+ thinking,+ content,+ kwargs,+ )++ if not self._app_started:+ raise RuntimeError(+ "ReMeApp context not started. "+ "Please use 'async with' to initialize the app.",+ )++ try:+ # Prepare messages for personal memory recording+ messages = []++ # Add thinking as a user message if provided+ if thinking:+ messages.append(+ {+ "role": "user",+ "content": thinking,+ },+ )++ # Add content items as user messages+ for item in content:+ messages.append(+ {+ "role": "user",+ "content": item,+ },+ )+ # Add a simple assistant acknowledgment+ messages.append(+ {+ "role": "assistant",+ "content": (+ "I understand and will remember this "+ "information."+ ),+ },+ )++ result = await self.app.async_execute(+ name="summary_personal_memory",+ workspace_id=self.workspace_id,+ trajectories=[+ {+ "messages": messages,+ },+ ],+ **kwargs,+ )++ # Extract metadata about stored memories if available+ metadata = result.get("metadata", {})+ memory_list = metadata.get("memory_list", [])++ if memory_list:+ summary_text = (+ f"Successfully recorded {len(memory_list)} "+ f"memory/memories to personal memory."+ )+ else:+ summary_text = "Memory recording completed."++ return ToolResponse(+ content=[+ TextBlock(+ type="text",+ text=summary_text,+ ),+ ],+ metadata={"result": result},+ )++ except Exception as e:+ logger.exception("Error recording memory: %s", str(e))+ return ToolResponse(+ content=[+ TextBlock(+ type="text",+ text=f"Error recording memory: {str(e)}",+ ),+ ],+ )++ async def retrieve_from_memory(+ self,+ keywords: list[str],+ **kwargs: Any,+ ) -> ToolResponse:+ """Search and retrieve relevant information from long-term memory.++ .. note:: You should call this function BEFORE answering+ questions about the user's preferences, past information, or+ personal details. This ensures you provide accurate information+ based on stored memories rather than guessing.++ Use this when:++ - User asks "what do I like?", "what are my preferences?",+ "what do you know about me?"+ - User asks about their past behaviors, habits, or stated+ preferences+ - User refers to information they shared in previous+ conversations+ - You need to personalize responses based on user's history++ Args:+ keywords (`list[str]`):+ Keywords to search for in memory. Be specific and use+ multiple keywords for better results. Examples:+ ["travel preferences", "Hangzhou"], ["work habits",+ "morning routine"], ["food preferences", "tea"].+ **kwargs (`Any`):+ Additional keyword arguments for the retrieval operation.++ Returns:+ `ToolResponse`:+ Retrieved memories matching the keywords. If no memories+ found, you'll receive a message indicating that.+ """+ logger.info(+ "[ReMePersonalMemory] Entering retrieve_from_memory - "+ "keywords: %s, kwargs: %s",+ keywords,+ kwargs,+ )++ if not self._app_started:+ raise RuntimeError(+ "ReMeApp context not started. "+ "Please use 'async with' to initialize the app.",+ )++ try:+ results = []++ # Search for each keyword+ limit = kwargs.get("limit", 3)+ for keyword in keywords:+ result = await self.app.async_execute(+ name="retrieve_personal_memory",+ workspace_id=self.workspace_id,+ query=keyword,+ top_k=limit,+ **kwargs,+ )++ # Extract the answer from the result+ answer = result.get("answer", "")+ if answer:+ results.append(f"Keyword '{keyword}':\n{answer}")++ # Combine all results+ if results:+ combined_text = "\n\n".join(results)+ else:+ combined_text = "No memories found for the given keywords."++ return ToolResponse(+ content=[+ TextBlock(+ type="text",+ text=combined_text,+ ),+ ],+ )++ except Exception as e:+ logger.exception("Error retrieving memory: %s", str(e))+ return ToolResponse(+ content=[+ TextBlock(+ type="text",+ text=f"Error retrieving memory: {str(e)}",+ ),+ ],+ )++ async def record(+ self,+ msgs: list[Msg | None],+ **kwargs: Any,+ ) -> None:+ """Record the content to the long-term memory.++ This method converts AgentScope messages to ReMe's format and+ records them using the personal memory flow.++ Args:+ msgs (`list[Msg | None]`):+ The messages to record to memory.+ **kwargs (`Any`):+ Additional keyword arguments for the mem0 recording.+ """+ if isinstance(msgs, Msg):+ msgs = [msgs]++ # Filter out None+ msg_list = [_ for _ in msgs if _]+ if not msg_list:+ return++ if not all(isinstance(_, Msg) for _ in msg_list):+ raise TypeError(+ "The input messages must be a list of Msg objects.",+ )++ if not self._app_started:+ raise RuntimeError(+ "ReMeApp context not started. "+ "Please use 'async with' to initialize the app.",+ )++ try:+ # Convert AgentScope messages to ReMe format+ messages = []+ for msg in msg_list:+ # Extract content as string+ if isinstance(msg.content, str):+ content_str = msg.content+ elif isinstance(msg.content, list):+ # Join content blocks into a single string+ content_parts = []+ for block in msg.content:+ if isinstance(block, dict) and "text" in block:+ content_parts.append(block["text"])+ elif isinstance(block, dict) and "thinking" in block:+ content_parts.append(block["thinking"])+ content_str = "\n".join(content_parts)+ else:+ content_str = str(msg.content)++ messages.append(+ {+ "role": msg.role,+ "content": content_str,+ },+ )++ await self.app.async_execute(+ name="summary_personal_memory",+ workspace_id=self.workspace_id,+ trajectories=[+ {+ "messages": messages,+ },+ ],+ **kwargs,+ )++ except Exception as e:+ # Log the error but don't raise to maintain compatibility+ logger.exception("Error recording messages to memory: %s", str(e))+ import warnings++ warnings.warn(f"Error recording messages to memory: {str(e)}")++ async def retrieve(+ self,+ msg: Msg | list[Msg] | None,+ **kwargs: Any,+ ) -> str:+ """Retrieve the content from the long-term memory.++ Args:+ 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.+ **kwargs (`Any`):+ Additional keyword arguments.++ Returns:+ `str`:+ The retrieved memory as a string.+ """+ if msg is None:+ return ""++ if isinstance(msg, Msg):+ msg = [msg]++ if not isinstance(msg, list) or not all(+ isinstance(_, Msg) for _ in msg+ ):+ raise TypeError(+ "The input message must be a Msg or a list of Msg objects.",+ )++ if not self._app_started:+ raise RuntimeError(+ "ReMeApp context not started. "+ "Please use 'async with' to initialize the app.",+ )++ try:+ # Only use the last message's content for retrieval+ last_msg = msg[-1]+ query = ""++ if isinstance(last_msg.content, str):+ query = last_msg.content+ elif isinstance(last_msg.content, list):+ # Extract text from content blocks+ content_parts = []+ for block in last_msg.content:+ if isinstance(block, dict) and "text" in block:+ content_parts.append(block["text"])+ elif isinstance(block, dict) and "thinking" in block:+ content_parts.append(block["thinking"])+ query = "\n".join(content_parts)++ if not query:+ return ""++ # Retrieve using the query from the last message+ # Extract top_k from kwargs if available, default to 3+ top_k = kwargs.get("top_k", 3)+ result = await self.app.async_execute(+ name="retrieve_personal_memory",+ workspace_id=self.workspace_id,+ query=query,+ top_k=top_k,+ **kwargs,+ )++ return result.get("answer", "")++ except Exception as e:+ logger.exception("Error retrieving memory: %s", str(e))+ import warnings++ warnings.warn(f"Error retrieving memory: {str(e)}")+ return ""diff --git a/src/agentscope/memory/_reme/_reme_task_long_term_memory.py b/src/agentscope/memory/_reme/_reme_task_long_term_memory.pynew file mode 100644index 000000000..78b458af3--- /dev/null+++ b/src/agentscope/memory/_reme/_reme_task_long_term_memory.py@@ -0,0 +1,429 @@+# -*- coding: utf-8 -*-+"""Task memory implementation using ReMe library.++This module provides a task memory implementation that integrates+with the ReMe library to learn from execution trajectories and+retrieve relevant task experiences.++Requirements:+ Python 3.12 or greater is required to use ReMe.+"""+from typing import Any++from ._reme_long_term_memory_base import ReMeLongTermMemoryBase+from ..._logging import logger+from ...message import Msg, TextBlock+from ...tool import ToolResponse+++class ReMeTaskLongTermMemory(ReMeLongTermMemoryBase):+ """Task memory implementation using ReMe library.++ Task memory learns from execution trajectories and provides+ retrieval of relevant task experiences.++ Requirements:+ Python 3.12 or greater is required to use ReMe.+ """++ async def record_to_memory(+ self,+ thinking: str,+ content: list[str],+ **kwargs: Any,+ ) -> ToolResponse:+ """Record task execution experiences and learnings.++ Record task execution experiences and learnings to long-term+ memory.++ Use this function to save valuable task-related knowledge that+ can help with future similar tasks. This enables learning from+ experience and improving over time.++ When to record:++ - After solving technical problems or completing tasks+ - When discovering useful techniques or approaches+ - After implementing solutions with specific steps+ - When learning best practices or important lessons++ What to record: Be detailed and actionable. Include:++ - Task description and context+ - Step-by-step execution details+ - Specific techniques and methods used+ - Results, outcomes, and effectiveness+ - Lessons learned and considerations++ Args:+ thinking (`str`):+ Your reasoning about why this task experience is valuable+ and what makes it worth remembering for future reference.+ content (`list[str]`):+ List of specific task insights to remember. Each string+ should be a clear, actionable piece of information.+ Examples: ["Add indexes on WHERE clause columns to speed+ up queries", "Use EXPLAIN ANALYZE to identify missing+ indexes"].+ **kwargs (`Any`):+ Additional keyword arguments. Can include 'score' (float)+ to indicate the quality/success of this approach+ (default: 1.0).++ Returns:+ `ToolResponse`:+ Confirmation message indicating successful memory+ recording.+ """+ logger.info(+ "[ReMeTaskMemory] Entering record_to_memory - "+ "thinking: %s, content: %s, kwargs: %s",+ thinking,+ content,+ kwargs,+ )++ if not self._app_started:+ raise RuntimeError(+ "ReMeApp context not started. "+ "Please use 'async with' to initialize the app.",+ )++ try:+ # Prepare messages for task memory recording+ messages = []++ # Add thinking as a user message if provided+ if thinking:+ messages.append(+ {+ "role": "user",+ "content": thinking,+ },+ )++ # Add content items as user-assistant pairs+ for item in content:+ messages.append(+ {+ "role": "user",+ "content": item,+ },+ )+ # Add a simple assistant acknowledgment+ messages.append(+ {+ "role": "assistant",+ "content": "Task information recorded.",+ },+ )++ result = await self.app.async_execute(+ name="summary_task_memory",+ workspace_id=self.workspace_id,+ trajectories=[+ {+ "messages": messages,+ "score": kwargs.pop("score", 1.0),+ },+ ],+ **kwargs,+ )++ # Extract metadata if available+ summary_text = (+ f"Successfully recorded {len(content)} task memory/memories."+ )++ return ToolResponse(+ content=[+ TextBlock(+ type="text",+ text=summary_text,+ ),+ ],+ metadata={"result": result},+ )++ except Exception as e:+ logger.exception("Error recording task memory: %s", str(e))+ return ToolResponse(+ content=[+ TextBlock(+ type="text",+ text=f"Error recording task memory: {str(e)}",+ ),+ ],+ )++ async def retrieve_from_memory(+ self,+ keywords: list[str],+ **kwargs: Any,+ ) -> ToolResponse:+ """Search and retrieve relevant task experiences.++ Search and retrieve relevant task experiences from long-term+ memory.++ IMPORTANT: You should call this function BEFORE attempting to+ solve problems or answer technical questions. This ensures you+ leverage experiences and proven solutions rather than+ starting from scratch.++ Use this when:+ - Asked to solve a technical problem or implement a solution+ - Asked for recommendations, best practices, or approaches+ - Asked "what do you know about...?" or "have you seen this+ before?"+ - Dealing with tasks that may be similar to experiences+ - Need to recall specific techniques or methods++ Benefits of retrieving first:+ - Learn from past successes and mistakes+ - Provide more accurate, battle-tested solutions+ - Avoid reinventing the wheel+ - Give consistent, informed recommendations++ Args:+ keywords (`list[str]`):+ Keywords describing the task or problem domain. Be+ specific and use technical terms. Examples:+ ["database optimization", "slow queries"], ["API design",+ "rate limiting"], ["code refactoring", "Python"].+ **kwargs (`Any`):+ Additional keyword arguments. Can include 'top_k' (int)+ to specify number of experiences to retrieve+ (default: 3).++ Returns:+ `ToolResponse`:+ Retrieved task experiences and learnings. If no relevant+ experiences found, you'll receive a message indicating+ that.+ """+ logger.info(+ "[ReMeTaskMemory] Entering retrieve_from_memory - "+ "keywords: %s, kwargs: %s",+ keywords,+ kwargs,+ )++ if not self._app_started:+ raise RuntimeError(+ "ReMeApp context not started. "+ "Please use 'async with' to initialize the app.",+ )++ try:+ results = []++ # Search for each keyword+ top_k = kwargs.get("top_k", 3)+ for keyword in keywords:+ result = await self.app.async_execute(+ name="retrieve_task_memory",+ workspace_id=self.workspace_id,+ query=keyword,+ top_k=top_k,+ **kwargs,+ )++ # Extract the answer from the result+ answer = result.get("answer", "")+ if answer:+ results.append(f"Keyword '{keyword}':\n{answer}")++ # Combine all results+ if results:+ combined_text = "\n\n".join(results)+ else:+ combined_text = (+ "No task experiences found for the given keywords."+ )++ return ToolResponse(+ content=[+ TextBlock(+ type="text",+ text=combined_text,+ ),+ ],+ )++ except Exception as e:+ logger.exception("Error retrieving task memory: %s", str(e))+ return ToolResponse(+ content=[+ TextBlock(+ type="text",+ text=f"Error retrieving task memory: {str(e)}",+ ),+ ],+ )++ async def record(+ self,+ msgs: list[Msg | None],+ **kwargs: Any,+ ) -> None:+ """Record the content to the task memory.++ This method converts AgentScope messages to ReMe's format and+ records them as a task execution trajectory.++ Args:+ msgs (`list[Msg | None]`):+ The messages to record to memory.+ **kwargs (`Any`):+ Additional keyword arguments for the recording.+ Can include 'score' (float) for trajectory scoring+ (default: 1.0).+ """+ if isinstance(msgs, Msg):+ msgs = [msgs]++ # Filter out None+ msg_list = [_ for _ in msgs if _]+ if not msg_list:+ return++ if not all(isinstance(_, Msg) for _ in msg_list):+ raise TypeError(+ "The input messages must be a list of Msg objects.",+ )++ if not self._app_started:+ raise RuntimeError(+ "ReMeApp context not started. "+ "Please use 'async with' to initialize the app.",+ )++ try:+ # Convert AgentScope messages to ReMe format+ messages = []+ for msg in msg_list:+ # Extract content as string+ if isinstance(msg.content, str):+ content_str = msg.content+ elif isinstance(msg.content, list):+ # Join content blocks into a single string+ content_parts = []+ for block in msg.content:+ if isinstance(block, dict) and "text" in block:+ content_parts.append(block["text"])+ elif isinstance(block, dict) and "thinking" in block:+ content_parts.append(block["thinking"])+ content_str = "\n".join(content_parts)+ else:+ content_str = str(msg.content)++ messages.append(+ {+ "role": msg.role,+ "content": content_str,+ },+ )++ # Extract score from kwargs if provided, default to 1.0+ score = kwargs.pop("score", 1.0)++ await self.app.async_execute(+ name="summary_task_memory",+ workspace_id=self.workspace_id,+ trajectories=[+ {+ "messages": messages,+ "score": score,+ },+ ],+ **kwargs,+ )++ except Exception as e:+ # Log the error but don't raise to maintain compatibility+ logger.exception(+ "Error recording messages to task memory: %s",+ str(e),+ )+ import warnings++ warnings.warn(+ f"Error recording messages to task memory: {str(e)}",+ )++ async def retrieve(+ self,+ msg: Msg | list[Msg] | None,+ **kwargs: Any,+ ) -> str:+ """Retrieve relevant task experiences from memory.++ Args:+ msg (`Msg | list[Msg] | None`):+ The message to search for relevant task experiences.+ **kwargs (`Any`):+ Additional keyword arguments.++ Returns:+ `str`:+ The retrieved task experiences as a string.+ """+ if msg is None:+ return ""++ if isinstance(msg, Msg):+ msg = [msg]++ if not isinstance(msg, list) or not all(+ isinstance(_, Msg) for _ in msg+ ):+ raise TypeError(+ "The input message must be a Msg or a list of Msg objects.",+ )++ if not self._app_started:+ raise RuntimeError(+ "ReMeApp context not started. "+ "Please use 'async with' to initialize the app.",+ )++ try:+ # Only use the last message's content for retrieval+ last_msg = msg[-1]+ query = ""++ if isinstance(last_msg.content, str):+ query = last_msg.content+ elif isinstance(last_msg.content, list):+ # Extract text from content blocks+ content_parts = []+ for block in last_msg.content:+ if isinstance(block, dict) and "text" in block:+ content_parts.append(block["text"])+ elif isinstance(block, dict) and "thinking" in block:+ content_parts.append(block["thinking"])+ query = "\n".join(content_parts)++ if not query:+ return ""++ # Retrieve using the query from the last message+ top_k = kwargs.get("top_k", 3)+ result = await self.app.async_execute(+ name="retrieve_task_memory",+ workspace_id=self.workspace_id,+ query=query,+ top_k=top_k,+ **kwargs,+ )++ return result.get("answer", "")++ except Exception as e:+ logger.exception("Error retrieving task memory: %s", str(e))+ import warnings++ warnings.warn(f"Error retrieving task memory: {str(e)}")+ return ""diff --git a/src/agentscope/memory/_reme/_reme_tool_long_term_memory.py b/src/agentscope/memory/_reme/_reme_tool_long_term_memory.pynew file mode 100644index 000000000..e44408ce2--- /dev/null+++ b/src/agentscope/memory/_reme/_reme_tool_long_term_memory.py@@ -0,0 +1,534 @@+# -*- coding: utf-8 -*-+"""Tool memory implementation using ReMe library.++This module provides a tool memory implementation that integrates+with the ReMe library to record tool execution results and retrieve+tool usage guidelines.++Requirements:+ Python 3.12 or greater is required to use ReMe.+"""+from typing import Any++from ._reme_long_term_memory_base import ReMeLongTermMemoryBase+from ..._logging import logger+from ...message import Msg, TextBlock+from ...tool import ToolResponse+++class ReMeToolLongTermMemory(ReMeLongTermMemoryBase):+ """Tool memory implementation using ReMe library.++ Tool memory records tool execution results and generates usage+ guidelines from the execution history.++ Requirements:+ Python 3.12 or greater is required to use ReMe.+ """++ async def record_to_memory(+ self,+ thinking: str,+ content: list[str],+ **kwargs: Any,+ ) -> ToolResponse:+ """Record tool execution results to build tool usage patterns.++ Record tool execution results to build a knowledge base of tool+ usage patterns.++ Use this function after successfully using tools to capture+ execution details, results, and performance metrics. Over time,+ this builds comprehensive usage guidelines and best practices+ for each tool.++ When to record:++ - After successfully executing any tool+ - After tool failures (to learn what doesn't work)+ - When discovering effective parameter combinations+ - After noteworthy tool usage patterns++ What to record: Each tool execution should include complete+ execution details.++ Args:+ thinking (`str`):+ Your reasoning about why this tool execution is worth+ recording. Mention what worked well, what could be+ improved, or lessons learned.+ content (`list[str]`):+ List of JSON strings, each representing a tool execution.+ Each JSON must have these fields:+ - create_time: Timestamp in format "YYYY-MM-DD HH:MM:SS"+ - tool_name: Name of the tool executed+ - input: Input parameters as a dict+ - output: Tool's output as a string+ - token_cost: Token cost (integer)+ - success: Whether execution succeeded (boolean)+ - time_cost: Execution time in seconds (float)++ Example: '{"create_time": "2024-01-01 10:00:00",+ "tool_name": "search", "input": {"query": "Python"},+ "output": "Found 10 results", "token_cost": 100,+ "success": true, "time_cost": 1.2}'+ **kwargs (`Any`):+ Additional keyword arguments for the recording operation.++ Returns:+ `ToolResponse`:+ Confirmation message with number of executions recorded+ and guidelines generated.+ """+ logger.info(+ "[ReMeToolMemory] Entering record_to_memory - "+ "thinking: %s, content: %s, kwargs: %s",+ thinking,+ content,+ kwargs,+ )++ if not self._app_started:+ raise RuntimeError(+ "ReMeApp context not started. "+ "Please use 'async with' to initialize the app.",+ )++ try:+ import json++ # Parse each content item as a tool_call_result+ tool_call_results = []+ tool_names_set = set()++ for item in content:+ try:+ # Parse JSON string to dict+ tool_call_result = json.loads(item)+ tool_call_results.append(tool_call_result)++ # Track tool names for summary+ if "tool_name" in tool_call_result:+ tool_names_set.add(tool_call_result["tool_name"])++ except json.JSONDecodeError as e:+ # Skip invalid JSON items+ import warnings++ warnings.warn(+ f"Failed to parse tool call result JSON: {item}. "+ f"Error: {str(e)}",+ )+ continue++ if not tool_call_results:+ return ToolResponse(+ content=[+ TextBlock(+ type="text",+ text="No valid tool call results to record.",+ ),+ ],+ )++ # First, add the tool call results+ await self.app.async_execute(+ name="add_tool_call_result",+ workspace_id=self.workspace_id,+ tool_call_results=tool_call_results,+ **kwargs,+ )++ # Then, summarize the tool memory for the affected tools+ if tool_names_set:+ tool_names_list = list(tool_names_set)+ await self.app.async_execute(+ name="summary_tool_memory",+ workspace_id=self.workspace_id,+ tool_names=tool_names_list,+ **kwargs,+ )++ num_results = len(tool_call_results)+ summary_text = (+ f"Successfully recorded {num_results} tool execution "+ f"result{'s' if num_results > 1 else ''} and generated "+ f"usage guidelines."+ )++ return ToolResponse(+ content=[+ TextBlock(+ type="text",+ text=summary_text,+ ),+ ],+ )++ except Exception as e:+ logger.exception("Error recording tool memory: %s", str(e))+ return ToolResponse(+ content=[+ TextBlock(+ type="text",+ text=f"Error recording tool memory: {str(e)}",+ ),+ ],+ )++ async def retrieve_from_memory(+ self,+ keywords: list[str],+ **kwargs: Any,+ ) -> ToolResponse:+ """Retrieve usage guidelines and best practices for tools.++ Retrieve usage guidelines and best practices for specific tools.++ .. note:: You should call this function BEFORE using a tool,+ especially if you're uncertain about its proper usage or want to+ follow established best practices. This retrieves synthesized+ guidelines based on past tool executions.++ Use this when:++ - About to use a tool and want to know the best practices+ - Uncertain about tool parameters or usage patterns+ - Want to learn from past successful/failed tool executions+ - User asks "how should I use this tool?" or "what's the best+ way to..."+ - Need to understand tool performance characteristics or+ limitations++ Benefits of retrieving first:++ - Learn from accumulated tool usage experience+ - Avoid common mistakes and pitfalls+ - Use optimal parameter combinations+ - Understand tool performance and cost characteristics+ - Follow established best practices++ Args:+ keywords (`list[str]`):+ List of tool names to retrieve guidelines for. Use the+ exact tool names. Examples: ["search"],+ ["database_query", "cache_get"], ["api_call"].+ **kwargs (`Any`):+ Additional keyword arguments for the retrieval operation.++ Returns:+ `ToolResponse`:+ Retrieved usage guidelines and best practices for the+ specified tools. If no guidelines exist yet, you'll+ receive a message indicating that.+ """+ logger.info(+ "[ReMeToolMemory] Entering retrieve_from_memory - "+ "keywords: %s, kwargs: %s",+ keywords,+ kwargs,+ )++ if not self._app_started:+ raise RuntimeError(+ "ReMeApp context not started. "+ "Please use 'async with' to initialize the app.",+ )++ try:+ # Join all tool names with comma+ tool_names = ",".join(keywords)++ # Retrieve tool guidelines for all tools at once+ result = await self.app.async_execute(+ name="retrieve_tool_memory",+ workspace_id=self.workspace_id,+ tool_names=tool_names,+ **kwargs,+ )++ # Extract the answer from the result+ answer = result.get("answer", "")+ if answer:+ combined_text = answer+ else:+ combined_text = f"No tool guidelines found for: {tool_names}"++ return ToolResponse(+ content=[+ TextBlock(+ type="text",+ text=combined_text,+ ),+ ],+ )++ except Exception as e:+ logger.exception("Error retrieving tool memory: %s", str(e))+ return ToolResponse(+ content=[+ TextBlock(+ type="text",+ text=f"Error retrieving tool memory: {str(e)}",+ ),+ ],+ )++ def _extract_content_from_messages(self, msg_list: list[Msg]) -> list[str]:+ """Extract content strings from messages.++ Args:+ msg_list (`list[Msg]`):+ List of messages to extract content from.++ Returns:+ `list[str]`:+ List of extracted content strings.+ """+ content_list = []+ for msg in msg_list:+ if isinstance(msg.content, str):+ content_list.append(msg.content)+ elif isinstance(msg.content, list):+ content_list.extend(+ self._extract_text_from_blocks(msg.content),+ )+ return content_list++ def _extract_text_from_blocks(self, blocks: list) -> list[str]:+ """Extract text from content blocks.++ Args:+ blocks (`list`):+ List of content blocks.++ Returns:+ `list[str]`:+ List of extracted text strings.+ """+ texts = []+ for block in blocks:+ if isinstance(block, dict) and block.get("type") == "text":+ texts.append(block.get("text", ""))+ elif isinstance(block, str):+ texts.append(block)+ return texts++ def _parse_tool_call_results(+ self,+ content_list: list[str],+ ) -> tuple[list[dict], set[str]]:+ """Parse JSON content strings into tool call results.++ Args:+ content_list (`list[str]`):+ List of JSON strings to parse.++ Returns:+ `tuple[list[dict], set[str]]`:+ Tuple of (tool_call_results, tool_names_set).+ """+ import json+ import warnings++ tool_call_results = []+ tool_names_set = set()++ for item in content_list:+ try:+ tool_call_result = json.loads(item)+ tool_call_results.append(tool_call_result)+ if "tool_name" in tool_call_result:+ tool_names_set.add(tool_call_result["tool_name"])+ except json.JSONDecodeError as e:+ warnings.warn(+ f"Failed to parse tool call result JSON: {item}. "+ f"Error: {str(e)}",+ )++ return tool_call_results, tool_names_set++ async def record(+ self,+ msgs: list[Msg | None],+ **kwargs: Any,+ ) -> None:+ """Record the content to the tool memory.++ This method extracts content from messages and treats them as+ JSON strings representing tool_call_results, similar to+ record_to_memory.++ Args:+ msgs (`list[Msg | None]`):+ The messages to record to memory. Each message's content+ should be a JSON string or list of JSON strings+ representing tool_call_results.+ **kwargs (`Any`):+ Additional keyword arguments for the recording.+ """+ if isinstance(msgs, Msg):+ msgs = [msgs]++ # Filter out None+ msg_list = [_ for _ in msgs if _]+ if not msg_list:+ return++ if not all(isinstance(_, Msg) for _ in msg_list):+ raise TypeError(+ "The input messages must be a list of Msg objects.",+ )++ if not self._app_started:+ raise RuntimeError(+ "ReMeApp context not started. "+ "Please use 'async with' to initialize the app.",+ )++ try:+ # Extract content from messages and parse as tool_call_results+ content_list = self._extract_content_from_messages(msg_list)+ if not content_list:+ return++ # Parse each content item as a tool_call_result+ tool_call_results, tool_names_set = self._parse_tool_call_results(+ content_list,+ )+ if not tool_call_results:+ return++ # First, add the tool call results+ await self.app.async_execute(+ name="add_tool_call_result",+ workspace_id=self.workspace_id,+ tool_call_results=tool_call_results,+ **kwargs,+ )++ # Then, summarize the tool memory for the affected tools+ if tool_names_set:+ tool_names_list = list(tool_names_set)+ await self.app.async_execute(+ name="summary_tool_memory",+ workspace_id=self.workspace_id,+ tool_names=tool_names_list,+ **kwargs,+ )++ except Exception as e:+ # Log the error but don't raise to maintain compatibility+ logger.exception(+ "Error recording tool messages to memory: %s",+ str(e),+ )+ import warnings++ warnings.warn(+ f"Error recording tool messages to memory: {str(e)}",+ )++ def _extract_tool_names_from_message(self, msg: Msg) -> str:+ """Extract tool names from a message.++ Args:+ msg (`Msg`):+ Message to extract tool names from.++ Returns:+ `str`:+ Extracted tool names as a string.+ """+ if isinstance(msg.content, str):+ return msg.content++ if isinstance(msg.content, list):+ content_parts = []+ for block in msg.content:+ if isinstance(block, dict) and "text" in block:+ content_parts.append(block["text"])+ return " ".join(content_parts)++ return ""++ def _format_retrieve_result(self, result: Any) -> str:+ """Format the retrieve result into a string.++ Args:+ result (`Any`):+ Result from the retrieve operation.++ Returns:+ `str`:+ Formatted result string.+ """+ if isinstance(result, dict) and "answer" in result:+ return result["answer"]+ if isinstance(result, str):+ return result+ return str(result)++ async def retrieve(+ self,+ msg: Msg | list[Msg] | None,+ **kwargs: Any,+ ) -> str:+ """Retrieve tool guidelines from memory.++ Retrieve tool guidelines from memory based on message content.++ Args:+ msg (`Msg | list[Msg] | None`):+ The message containing tool names or queries to+ retrieve guidelines for.+ **kwargs (`Any`):+ Additional keyword arguments.++ Returns:+ `str`:+ The retrieved tool guidelines as a string.+ """+ if msg is None:+ return ""++ if isinstance(msg, Msg):+ msg = [msg]++ if not isinstance(msg, list) or not all(+ isinstance(_, Msg) for _ in msg+ ):+ raise TypeError(+ "The input message must be a Msg or a list of Msg objects.",+ )++ if not self._app_started:+ raise RuntimeError(+ "ReMeApp context not started. "+ "Please use 'async with' to initialize the app.",+ )++ try:+ # Extract tool names from the last message+ last_msg = msg[-1]+ tool_names = self._extract_tool_names_from_message(last_msg)++ if not tool_names:+ return ""++ # Retrieve tool guidelines+ result = await self.app.async_execute(+ name="retrieve_tool_memory",+ workspace_id=self.workspace_id,+ tool_names=tool_names,+ **kwargs,+ )++ return self._format_retrieve_result(result)++ except Exception as e:+ logger.exception("Error retrieving tool guidelines: %s", str(e))+ import warnings++ warnings.warn(f"Error retrieving tool guidelines: {str(e)}")+ return ""diff --git a/tests/memory_reme_test.py b/tests/memory_reme_test.pynew file mode 100644index 000000000..b6325cc4f--- /dev/null+++ b/tests/memory_reme_test.py@@ -0,0 +1,766 @@+# -*- coding: utf-8 -*-+# flake8: noqa: E501+# pylint: disable=C0301,W0212+"""Unit tests for ReMeMemory classes (Personal, Tool, Task)."""+import os+import sys+import unittest+from typing import Any+from unittest.async_case import IsolatedAsyncioTestCase+from unittest.mock import patch, AsyncMock, MagicMock++# Check Python version before importing reme dependencies+PYTHON_VERSION = sys.version_info+SKIP_REME_TESTS = PYTHON_VERSION < (3, 12)++if not SKIP_REME_TESTS:+ from agentscope.embedding import DashScopeTextEmbedding+ from agentscope.memory import (+ ReMePersonalLongTermMemory,+ ReMeToolLongTermMemory,+ ReMeTaskLongTermMemory,+ )+ from agentscope.message import Msg+ from agentscope.model import DashScopeChatModel+ from agentscope.tool import ToolResponse++# Get memory type from environment variable or command line argument+# Options: "personal", "tool", "task"+MEMORY_TYPE = os.environ.get("REME_MEMORY_TYPE", "personal").lower()+if not SKIP_REME_TESTS:+ print(f"MEMORY_TYPE: {MEMORY_TYPE}")+else:+ print(+ f"Skipping ReMeMemory tests: Python {PYTHON_VERSION.major}.{PYTHON_VERSION.minor} < 3.12",+ )+++ SKIP_REME_TESTS,+ f"ReMeMemory requires Python 3.12+, current version is {PYTHON_VERSION.major}.{PYTHON_VERSION.minor}",+)+class TestReMeMemory(IsolatedAsyncioTestCase):+ """Test cases for ReMeMemory (dynamically tests Personal, Tool, or Task memory)."""++ def setUp(self) -> None:+ """Set up test fixtures."""+ # Mock the model and embedding model to pass isinstance checks+ self.mock_model = MagicMock(spec=DashScopeChatModel)+ self.mock_model.model_name = "qwen3-max"+ self.mock_model.api_key = "test_api_key"++ self.mock_embedding_model = MagicMock(spec=DashScopeTextEmbedding)+ self.mock_embedding_model.model_name = "text-embedding-v4"+ self.mock_embedding_model.api_key = "test_embedding_key"++ # Set the memory class based on MEMORY_TYPE+ self.memory_type = MEMORY_TYPE+ if self.memory_type == "tool":+ self.memory_class = ReMeToolLongTermMemory+ self.summary_operation = "add_tool_call_result"+ elif self.memory_type == "task":+ self.memory_class = ReMeTaskLongTermMemory+ self.summary_operation = "summary_task_memory"+ else: # default to personal+ self.memory_class = ReMePersonalLongTermMemory+ self.summary_operation = "summary_personal_memory"++ print(f"\n=== Testing {self.memory_class.__name__} ===")++ def _create_memory_instance(self) -> Any:+ """Create a ReMeMemory instance with mocked dependencies."""+ with patch("reme_ai.ReMeApp"):+ memory = self.memory_class(+ agent_name="TestAgent",+ user_name="test_user",+ model=self.mock_model,+ embedding_model=self.mock_embedding_model,+ )+ # Mock the app attribute+ memory.app = AsyncMock()+ memory._app_started = True+ memory.workspace_id = "test_workspace_123"+ return memory++ async def test_init_with_default_params(self) -> None:+ """Test initialization with default parameters."""+ with patch("reme_ai.ReMeApp"):+ memory = self.memory_class(+ agent_name="Friday",+ user_name="user_123",+ model=self.mock_model,+ embedding_model=self.mock_embedding_model,+ )+ self.assertEqual(memory.agent_name, "Friday")+ self.assertEqual(memory.workspace_id, "user_123")+ self.assertIsNotNone(memory.app)++ async def test_record_to_memory_success(self) -> None:+ """Test successful memory recording via record_to_memory tool."""+ memory = self._create_memory_instance()++ # Prepare test data based on memory type+ mock_result: dict = {}+ if self.memory_type == "tool":+ # Tool memory expects JSON strings with tool_call_result format+ import json++ content = [+ json.dumps(+ {+ "create_time": "2025-01-01T12:00:00",+ "tool_name": "search_web",+ "input": {"query": "Hangzhou travel"},+ "output": "Found 10 results",+ "token_cost": 100,+ "success": True,+ "time_cost": 1.5,+ },+ ),+ json.dumps(+ {+ "create_time": "2025-01-01T12:01:00",+ "tool_name": "book_hotel",+ "input": {"location": "Hangzhou"},+ "output": "Booking confirmed",+ "token_cost": 150,+ "success": True,+ "time_cost": 2.0,+ },+ ),+ ]+ expected_count = 2+ mock_result = {"status": "success"}+ elif self.memory_type == "task":+ # Task memory expects task execution information+ content = [+ "Task: Plan Hangzhou trip",+ "Step 1: Research destinations",+ "Step 2: Book accommodations",+ ]+ expected_count = 3+ mock_result = {"status": "success"}+ else: # personal+ # Personal memory expects natural language content+ content = [+ "I prefer to stay in homestays when traveling to Hangzhou",+ "I like to visit the West Lake in the morning",+ "I enjoy drinking Longjing tea",+ ]+ expected_count = 3+ mock_result = {+ "metadata": {+ "memory_list": [+ {"content": "Prefer homestays in Hangzhou"},+ {"content": "Visit West Lake in morning"},+ {"content": "Enjoy Longjing tea"},+ ],+ },+ }++ memory.app.async_execute = AsyncMock(return_value=mock_result)++ # Test recording+ result = await memory.record_to_memory(+ thinking="Recording important information",+ content=content,+ )++ # Verify result+ self.assertIsInstance(result, ToolResponse)+ self.assertGreater(len(result.content), 0)+ text_content = result.content[0].get("text", "")++ # Verify success message contains the expected count+ if self.memory_type == "tool":+ self.assertIn(+ "Successfully recorded 2 tool execution",+ text_content,+ )+ else:+ self.assertIn(+ f"Successfully recorded {expected_count}",+ text_content,+ )++ # Verify app.async_execute was called+ memory.app.async_execute.assert_called()+ self.assertEqual(+ memory.app.async_execute.call_args[1]["workspace_id"],+ "test_workspace_123",+ )++ async def test_record_to_memory_app_not_started(self) -> None:+ """Test record_to_memory when app context is not started."""+ memory = self._create_memory_instance()+ memory._app_started = False++ # Should raise RuntimeError when app is not started+ with self.assertRaises(RuntimeError) as context:+ await memory.record_to_memory(+ thinking="Test thinking",+ content=["Test content"],+ )++ self.assertIn("ReMeApp context not started", str(context.exception))++ async def test_record_to_memory_error_handling(self) -> None:+ """Test error handling in record_to_memory."""+ memory = self._create_memory_instance()++ # Tool memory has different behavior - it validates JSON first+ if self.memory_type == "tool":+ # For tool memory, test with invalid JSON that triggers the "No valid tool call results" path+ result = await memory.record_to_memory(+ thinking="Test thinking",+ content=["Test content"], # Invalid JSON+ )++ self.assertIsInstance(result, ToolResponse)+ text_content = result.content[0].get("text", "")+ self.assertIn("No valid tool call results to record", text_content)+ else:+ # For task and personal memory, test with connection error+ memory.app.async_execute = AsyncMock(+ side_effect=Exception("Connection error"),+ )++ result = await memory.record_to_memory(+ thinking="Test thinking",+ content=["Test content"],+ )++ self.assertIsInstance(result, ToolResponse)+ text_content = result.content[0].get("text", "")++ # Different memory types have different error messages+ if self.memory_type == "task":+ self.assertIn("Error recording task memory", text_content)+ else: # personal+ self.assertIn("Error recording memory", text_content)++ self.assertIn("Connection error", text_content)++ async def test_retrieve_from_memory_success(self) -> None:+ """Test successful memory retrieval via retrieve_from_memory tool."""+ memory = self._create_memory_instance()++ # Mock the app.async_execute response based on memory type+ if self.memory_type == "tool":+ # Tool memory expects tool_names parameter and returns tool guidelines+ def mock_retrieve(**kwargs: Any) -> dict:+ tool_names = kwargs.get("tool_names", "")+ if "search_web" in tool_names or "book_hotel" in tool_names:+ return {+ "answer": "Tool usage guidelines for search_web and book_hotel.",+ }+ return {"answer": ""}++ memory.app.async_execute = AsyncMock(side_effect=mock_retrieve)++ # Test retrieval with tool names+ result = await memory.retrieve_from_memory(+ keywords=["search_web", "book_hotel"],+ )++ # Verify result+ self.assertIsInstance(result, ToolResponse)+ text_content = result.content[0].get("text", "")+ self.assertIn("Tool usage guidelines", text_content)++ # Tool memory combines all keywords into one call+ self.assertEqual(memory.app.async_execute.call_count, 1)++ elif self.memory_type == "task":+ # Task memory expects query parameter and returns task experiences+ def mock_retrieve(**kwargs: Any) -> dict:+ query = kwargs.get("query", "")+ if "Hangzhou" in query:+ return {+ "answer": "Task experience: Planning a trip to Hangzhou requires research and booking.",+ }+ elif "travel" in query:+ return {+ "answer": "Task experience: Travel planning involves multiple steps.",+ }+ return {"answer": ""}++ memory.app.async_execute = AsyncMock(side_effect=mock_retrieve)++ # Test retrieval+ result = await memory.retrieve_from_memory(+ keywords=["Hangzhou trip", "travel planning"],+ )++ # Verify result+ self.assertIsInstance(result, ToolResponse)+ text_content = result.content[0].get("text", "")+ self.assertIn("Keyword 'Hangzhou trip'", text_content)+ self.assertIn("Task experience", text_content)++ # Task memory calls once per keyword+ self.assertEqual(memory.app.async_execute.call_count, 2)++ else: # personal+ # Personal memory expects query parameter and returns personal preferences+ def mock_retrieve(**kwargs: Any) -> dict:+ keyword = kwargs.get("query", "")+ if "Hangzhou" in keyword:+ return {+ "answer": "User prefers homestays in Hangzhou and visits West Lake in the morning.",+ }+ elif "tea" in keyword:+ return {+ "answer": "User enjoys drinking Longjing tea.",+ }+ return {"answer": ""}++ memory.app.async_execute = AsyncMock(side_effect=mock_retrieve)++ # Test retrieval+ result = await memory.retrieve_from_memory(+ keywords=["Hangzhou travel", "tea preference"],+ )++ # Verify result+ self.assertIsInstance(result, ToolResponse)+ text_content = result.content[0].get("text", "")+ self.assertIn("Keyword 'Hangzhou travel'", text_content)+ self.assertIn("homestays", text_content)+ self.assertIn("Keyword 'tea preference'", text_content)+ self.assertIn("Longjing tea", text_content)++ # Personal memory calls once per keyword+ self.assertEqual(memory.app.async_execute.call_count, 2)++ async def test_retrieve_from_memory_no_results(self) -> None:+ """Test retrieve_from_memory when no memories are found."""+ memory = self._create_memory_instance()++ # Mock empty response+ memory.app.async_execute = AsyncMock(return_value={"answer": ""})++ result = await memory.retrieve_from_memory(+ keywords=["nonexistent keyword"],+ )++ self.assertIsInstance(result, ToolResponse)+ text_content = result.content[0].get("text", "")++ # Different memory types have different "not found" messages+ if self.memory_type == "tool":+ self.assertIn("No tool guidelines found", text_content)+ elif self.memory_type == "task":+ self.assertIn("No task experiences found", text_content)+ else: # personal+ self.assertIn("No memories found", text_content)++ async def test_retrieve_from_memory_app_not_started(self) -> None:+ """Test retrieve_from_memory when app context is not started."""+ memory = self._create_memory_instance()+ memory._app_started = False++ # Should raise RuntimeError when app is not started+ with self.assertRaises(RuntimeError) as context:+ await memory.retrieve_from_memory(+ keywords=["test"],+ )++ self.assertIn("ReMeApp context not started", str(context.exception))++ async def test_record_direct_method_success(self) -> None:+ """Test direct record method with message list."""+ memory = self._create_memory_instance()++ # Mock successful recording+ memory.app.async_execute = AsyncMock(+ return_value={"status": "success"},+ )++ # Prepare messages based on memory type+ if self.memory_type == "tool":+ # Tool memory expects JSON strings with tool call results+ import json++ msgs = [+ Msg(+ role="user",+ content=json.dumps(+ {+ "create_time": "2025-01-01T12:00:00",+ "tool_name": "search",+ "input": {"query": "test"},+ "output": "result",+ "token_cost": 100,+ "success": True,+ "time_cost": 1.0,+ },+ ),+ name="user",+ ),+ ]+ else:+ # Task and Personal memory work with regular messages+ msgs = [+ Msg(+ role="user",+ content="I work as a software engineer",+ name="user",+ ),+ Msg(+ role="assistant",+ content="Understood!",+ name="assistant",+ ),+ Msg(+ role="user",+ content="I prefer remote work",+ name="user",+ ),+ ]++ # Should not raise any exception+ await memory.record(msgs)++ # Verify app.async_execute was called+ memory.app.async_execute.assert_called()+ call_args = memory.app.async_execute.call_args[1]+ self.assertEqual(call_args["workspace_id"], "test_workspace_123")++ async def test_record_direct_with_single_message(self) -> None:+ """Test direct record method with a single message."""+ memory = self._create_memory_instance()++ memory.app.async_execute = AsyncMock(+ return_value={"status": "success"},+ )++ # Tool memory requires JSON-formatted tool call results+ if self.memory_type == "tool":+ import json++ msg = Msg(+ role="user",+ content=json.dumps(+ {+ "create_time": "2025-01-01T12:00:00",+ "tool_name": "test_tool",+ "input": {"param": "value"},+ "output": "result",+ "token_cost": 10,+ "success": True,+ "time_cost": 0.1,+ },+ ),+ name="user",+ )+ else:+ msg = Msg(+ role="user",+ content="Single message test",+ name="user",+ )++ # Should handle single message+ await memory.record(msg)++ # Tool memory calls async_execute twice (add + summarize)+ if self.memory_type == "tool":+ self.assertEqual(memory.app.async_execute.call_count, 2)+ else:+ memory.app.async_execute.assert_called_once()++ async def test_record_direct_with_empty_list(self) -> None:+ """Test direct record method with empty message list."""+ memory = self._create_memory_instance()++ memory.app.async_execute = AsyncMock()++ # Should return early without calling app+ await memory.record([])++ memory.app.async_execute.assert_not_called()++ async def test_record_direct_filters_none_messages(self) -> None:+ """Test that record method filters out None messages."""+ memory = self._create_memory_instance()++ memory.app.async_execute = AsyncMock(+ return_value={"status": "success"},+ )++ # Tool memory requires JSON-formatted tool call results+ if self.memory_type == "tool":+ import json++ msgs = [+ Msg(+ role="user",+ content=json.dumps(+ {+ "create_time": "2025-01-01T12:00:00",+ "tool_name": "tool1",+ "input": {},+ "output": "result1",+ "token_cost": 10,+ "success": True,+ "time_cost": 0.1,+ },+ ),+ name="user",+ ),+ None,+ Msg(+ role="assistant",+ content=json.dumps(+ {+ "create_time": "2025-01-01T12:01:00",+ "tool_name": "tool2",+ "input": {},+ "output": "result2",+ "token_cost": 20,+ "success": True,+ "time_cost": 0.2,+ },+ ),+ name="assistant",+ ),+ None,+ ]+ else:+ msgs = [+ Msg(role="user", content="Valid message", name="user"),+ None,+ Msg(+ role="assistant",+ content="Another valid",+ name="assistant",+ ),+ None,+ ]++ await memory.record(msgs)++ # Tool memory calls async_execute twice (add + summarize)+ if self.memory_type == "tool":+ self.assertEqual(memory.app.async_execute.call_count, 2)+ else:+ # Should still be called with filtered messages+ memory.app.async_execute.assert_called_once()++ async def test_record_direct_app_not_started(self) -> None:+ """Test record method when app is not started."""+ memory = self._create_memory_instance()+ memory._app_started = False++ msgs = [Msg(role="user", content="Test", name="user")]++ # Should raise RuntimeError when app is not started+ with self.assertRaises(RuntimeError) as context:+ await memory.record(msgs)++ self.assertIn("ReMeApp context not started", str(context.exception))++ async def test_retrieve_direct_method_success(self) -> None:+ """Test direct retrieve method with message."""+ memory = self._create_memory_instance()++ # Prepare test data based on memory type+ if self.memory_type == "tool":+ mock_response = {+ "answer": "Tool guidelines for search and analysis tools.",+ }+ expected_content = "Tool guidelines"+ expected_operation = "retrieve_tool_memory"+ elif self.memory_type == "task":+ mock_response = {+ "answer": "Task experience with work-related projects.",+ }+ expected_content = "Task experience"+ expected_operation = "retrieve_task_memory"+ else: # personal+ mock_response = {+ "answer": "You are a software engineer who prefers remote work.",+ }+ expected_content = "software engineer"+ expected_operation = "retrieve_personal_memory"++ # Mock the retrieval response+ memory.app.async_execute = AsyncMock(return_value=mock_response)++ msg = Msg(+ role="user",+ content="What do you know about my work preferences?",+ name="user",+ )++ result = await memory.retrieve(msg)++ # Verify result+ self.assertIsInstance(result, str)+ self.assertIn(expected_content, result)++ # Verify app.async_execute was called+ memory.app.async_execute.assert_called_once()+ call_args = memory.app.async_execute.call_args[1]+ self.assertEqual(call_args["name"], expected_operation)++ async def test_retrieve_direct_with_message_list(self) -> None:+ """Test direct retrieve method with list of messages."""+ memory = self._create_memory_instance()++ memory.app.async_execute = AsyncMock(+ return_value={"answer": "Test answer"},+ )++ msgs = [+ Msg(role="user", content="First message", name="user"),+ Msg(role="user", content="Last message for query", name="user"),+ ]++ result = await memory.retrieve(msgs)++ self.assertIsInstance(result, str)+ # Should use the last message's content+ call_args = memory.app.async_execute.call_args[1]++ # Tool memory uses tool_names parameter, others use query+ if self.memory_type == "tool":+ # Tool memory extracts tool names from content+ self.assertIn("tool_names", call_args)+ else:+ self.assertIn("Last message for query", call_args["query"])++ async def test_retrieve_direct_with_none_message(self) -> None:+ """Test direct retrieve method with None message."""+ memory = self._create_memory_instance()++ result = await memory.retrieve(None)++ # Should return empty string+ self.assertEqual(result, "")++ async def test_retrieve_direct_invalid_input(self) -> None:+ """Test direct retrieve method with invalid input."""+ memory = self._create_memory_instance()++ # Should raise TypeError for invalid input+ with self.assertRaises(TypeError) as context:+ await memory.retrieve("invalid string input")++ self.assertIn("must be a Msg or a list of Msg", str(context.exception))++ async def test_retrieve_direct_app_not_started(self) -> None:+ """Test retrieve method when app is not started."""+ memory = self._create_memory_instance()+ memory._app_started = False++ msg = Msg(role="user", content="Test", name="user")++ # Should raise RuntimeError+ with self.assertRaises(RuntimeError) as context:+ await memory.retrieve(msg)++ self.assertIn("ReMeApp context not started", str(context.exception))++ async def test_context_manager_usage(self) -> None:+ """Test using ReMeMemory as async context manager."""+ with patch("reme_ai.ReMeApp") as MockReMeApp:+ mock_app = AsyncMock()+ mock_app.__aenter__ = AsyncMock(return_value=mock_app)+ mock_app.__aexit__ = AsyncMock(return_value=None)+ MockReMeApp.return_value = mock_app++ memory = self.memory_class(+ agent_name="TestAgent",+ user_name="test_user",+ model=self.mock_model,+ embedding_model=self.mock_embedding_model,+ )++ # Use as context manager+ async with memory as mem:+ self.assertIsNotNone(mem)+ # The app should be started+ self.assertTrue(hasattr(mem, "app"))++ async def test_integration_record_and_retrieve(self) -> None:+ """Test integration of recording and retrieving memories."""+ memory = self._create_memory_instance()++ # Prepare test data based on memory type+ if self.memory_type == "tool":+ import json++ content = [+ json.dumps(+ {+ "create_time": "2025-01-01T12:00:00",+ "tool_name": "python_executor",+ "input": {"code": "print('hello')"},+ "output": "hello",+ "token_cost": 50,+ "success": True,+ "time_cost": 0.5,+ },+ ),+ ]+ keywords = ["python_executor"]+ expected_text = "Tool usage guidelines"+ elif self.memory_type == "task":+ content = ["Task: Execute Python code successfully"]+ keywords = ["Python execution"]+ expected_text = "Task experience"+ else: # personal+ content = ["I like Python programming"]+ keywords = ["programming preferences"]+ expected_text = "Python programming"++ # Mock record response+ memory.app.async_execute = AsyncMock(+ return_value={+ "metadata": {"memory_list": [{"content": "test"}]},+ },+ )++ # Record some memories+ record_result = await memory.record_to_memory(+ thinking="Recording preferences",+ content=content,+ )++ self.assertIn(+ "Successfully recorded",+ record_result.content[0]["text"],+ )++ # Mock retrieve response+ if self.memory_type == "tool":+ memory.app.async_execute = AsyncMock(+ return_value={+ "answer": "Tool usage guidelines for python_executor.",+ },+ )+ elif self.memory_type == "task":+ memory.app.async_execute = AsyncMock(+ return_value={+ "answer": "Task experience: Execute Python code successfully.",+ },+ )+ else: # personal+ memory.app.async_execute = AsyncMock(+ return_value={+ "answer": "You like Python programming.",+ },+ )++ # Retrieve the memories+ retrieve_result = await memory.retrieve_from_memory(+ keywords=keywords,+ )++ self.assertIn(expected_text, retrieve_result.content[0]["text"])+++if __name__ == "__main__":+ unittest.main()