Long-Term Memory

In AgentScope, we provide a basic class for long-term memory (LongTermMemoryBase) and an implementation based on the mem0 library (Mem0LongTermMemory). Together with the design of ReActAgent class in Agent section, we provide two long-term memory modes:

  • agent_control: the agent autonomously manages long-term memory by tool calls, and

  • static_control: the developer explicitly controls long-term memory operations.

Developers can also use the both mode, which activates both memory management modes.

Hint

These memory modes are suitable for different usage scenarios. Developers can choose the appropriate mode based on their needs.

Using mem0 Long-Term Memory

Note

We provide an example of using mem0 long-term memory in the GitHub repository under the examples/long_term_memory/mem0 directory.

  1. import os
  2. import asyncio
  3. from agentscope.message import Msg
  4. from agentscope.memory import InMemoryMemory
  5. from agentscope.agent import ReActAgent
  6. from agentscope.formatter import DashScopeChatFormatter
  7. from agentscope.model import DashScopeChatModel
  8. from agentscope.tool import Toolkit
  9. # Create mem0 long-term memory instance
  10. from agentscope.memory import Mem0LongTermMemory
  11. from agentscope.embedding import DashScopeTextEmbedding
  12. long_term_memory = Mem0LongTermMemory(
  13. agent_name="Friday",
  14. user_name="user_123",
  15. model=DashScopeChatModel(
  16. model_name="qwen-max-latest",
  17. api_key=os.environ.get("DASHSCOPE_API_KEY"),
  18. stream=False,
  19. ),
  20. embedding_model=DashScopeTextEmbedding(
  21. model_name="text-embedding-v2",
  22. api_key=os.environ.get("DASHSCOPE_API_KEY"),
  23. ),
  24. on_disk=False,
  25. )

The Mem0LongTermMemory class provides two main methods for long-term memory operations: record and retrieve. They take a list of messages as input and record/retrieve information from long-term memory.

As an example, we first store a user preference and then retrieve related information from long-term memory.

  1. # Basic usage example
  2. async def basic_usage():
  3. """Basic usage example"""
  4. # Record memory
  5. await long_term_memory.record(
  6. [Msg("user", "I like staying in homestays", "user")],
  7. )
  8. # Retrieve memory
  9. results = await long_term_memory.retrieve(
  10. [Msg("user", "My accommodation preferences", "user")],
  11. )
  12. print(f"Retrieval results: {results}")
  13. asyncio.run(basic_usage())
  1. Retrieval results: Likes staying in homestays

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 that specifies the long-term memory mode.

If long_term_memory_mode is set to agent_control or both, two tool functions record_to_memory and retrieve_from_memory will be registered in the agent’s toolkit, 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.

  1. # Create ReAct agent with long-term memory
  2. agent = ReActAgent(
  3. name="Friday",
  4. sys_prompt="You are an assistant with long-term memory capabilities.",
  5. model=DashScopeChatModel(
  6. api_key=os.environ.get("DASHSCOPE_API_KEY"),
  7. model_name="qwen-max-latest",
  8. ),
  9. formatter=DashScopeChatFormatter(),
  10. toolkit=Toolkit(),
  11. memory=InMemoryMemory(),
  12. long_term_memory=long_term_memory,
  13. long_term_memory_mode="static_control", # Use static_control mode
  14. )
  15. async def record_preferences():
  16. """ReAct agent integration example"""
  17. # Conversation example
  18. msg = Msg(
  19. "user",
  20. "When I travel to Hangzhou, I like staying in homestays",
  21. "user",
  22. )
  23. await agent(msg)
  24. asyncio.run(record_preferences())
  1. Friday: When you travel to Hangzhou, staying in homestays can be a wonderful experience. Homestays often provide a more personal and intimate setting, allowing you to immerse yourself in the local culture and lifestyle. You might have the opportunity to interact with the hosts and other travelers, which can enrich your travel experiences. Moreover, homestays are usually more affordable than hotels and can offer unique accommodations that reflect the local charm. Enjoy your stay in Hangzhou's homestays!

Then we clear the short-term memory and ask the agent about the user’s preferences.

  1. async def retrieve_preferences():
  2. """Retrieve user preferences from long-term memory"""
  3. # Clear short-term memory
  4. await agent.memory.clear()
  5. # The agent will remember previous conversations
  6. msg2 = Msg("user", "What are my preferences? Answer briefly.", "user")
  7. await agent(msg2)
  8. asyncio.run(retrieve_preferences())
  1. Friday: You prefer staying in homestays when traveling to Hangzhou.

Customizing Long-Term Memory

AgentScope provides the LongTermMemoryBase base class, which defines the basic

Developers can inherit from LongTermMemoryBase to implement custom long-term memory systems according to their needs:

Long-term memory classes in AgentScope

Class

Abstract Methods

Description

LongTermMemoryBase

record
retrieve
record_to_memory
retrieve_from_memory
  • 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

-

Long-term memory implementation based on the mem0 library, supporting vector storage and retrieval.

Further Reading

Total running time of the script: (0 minutes 31.945 seconds)

Download Jupyter notebook: task_long_term_memory.ipynb

Download Python source code: task_long_term_memory.py

Download zipped: task_long_term_memory.zip

Gallery generated by Sphinx-Gallery