chore: initial import of standalone agentscope project
Some checks failed
Pre-commit / run (ubuntu-latest) (push) Has been cancelled
Deploy Sphinx documentation to Pages / build_en (ubuntu-latest, 3.10) (push) Has been cancelled
Deploy Sphinx documentation to Pages / build_zh (ubuntu-latest, 3.10) (push) Has been cancelled
Python Unittest Coverage / test (macos-15, 3.10) (push) Has been cancelled
Python Unittest Coverage / test (macos-15, 3.11) (push) Has been cancelled
Python Unittest Coverage / test (macos-15, 3.12) (push) Has been cancelled
Python Unittest Coverage / test (ubuntu-latest, 3.10) (push) Has been cancelled
Python Unittest Coverage / test (ubuntu-latest, 3.11) (push) Has been cancelled
Python Unittest Coverage / test (ubuntu-latest, 3.12) (push) Has been cancelled
Python Unittest Coverage / test (windows-latest, 3.10) (push) Has been cancelled
Python Unittest Coverage / test (windows-latest, 3.11) (push) Has been cancelled
Python Unittest Coverage / test (windows-latest, 3.12) (push) Has been cancelled

This commit is contained in:
2026-03-02 18:21:40 +08:00
commit a842f1861f
561 changed files with 91892 additions and 0 deletions

View File

@@ -0,0 +1,158 @@
# Mem0 Long-Term Memory in AgentScope
This example demonstrates how to
- use Mem0LongTermMemory to provide persistent semantic memory storage for AgentScope agents,
- record and retrieve conversation history and user preferences across sessions,
- integrate long-term memory with ReAct agents for context-aware conversations, and
- configure DashScope embedding models and Qdrant vector store for memory management.
## Prerequisites
- Python 3.10 or higher
- DashScope API key from Alibaba Cloud
## QuickStart
Install agentscope and ensure you have a valid DashScope API key in your environment variables.
> Note: The example is built with DashScope chat model and embedding model. If you want to use OpenAI models instead,
> modify the model initialization in the example code accordingly.
```bash
# Install agentscope from source
cd {PATH_TO_AGENTSCOPE}
pip install -e .
# Install dependencies
pip install mem0ai
```
Set up your API key:
```bash
export DASHSCOPE_API_KEY='YOUR_API_KEY'
```
Run the example:
```bash
python memory_example.py
```
The example will:
1. Initialize a Mem0LongTermMemory instance with DashScope models and Qdrant vector store
2. Record a basic conversation to long-term memory
3. Retrieve memories using semantic search
4. Demonstrate ReAct agent integration with long-term memory for storing and retrieving user preferences
## Key Features
- **Vector-based Storage**: Uses Qdrant vector database for efficient semantic search and retrieval
- **Flexible Configuration**: Support for multiple embedding models (OpenAI, DashScope) and vector stores
- **Async Operations**: Full async support for non-blocking memory operations
- **ReAct Agent Integration**: Seamless integration with AgentScope's ReActAgent and tool system
## Basic Usage
### Initialize Memory
```python
import os
from agentscope.memory import Mem0LongTermMemory
from agentscope.model import DashScopeChatModel
from agentscope.embedding import DashScopeTextEmbedding
from mem0.vector_stores.configs import VectorStoreConfig
# Initialize with DashScope models and Qdrant vector store
long_term_memory = Mem0LongTermMemory(
agent_name="Friday",
user_name="user_123",
model=DashScopeChatModel(
model_name="qwen-max-latest",
api_key=os.environ.get("DASHSCOPE_API_KEY")
),
embedding_model=DashScopeTextEmbedding(
model_name="text-embedding-v3",
api_key=os.environ.get("DASHSCOPE_API_KEY"),
dimensions=1024
),
vector_store_config=VectorStoreConfig(
provider="qdrant",
config={
"on_disk": True,
"path": "./qdrant_data", # Your customized storage path
"embedding_model_dims": 1024
}
)
)
```
> **Important**: If you change to a different embedding model or modify `embedding_model_dims`, you must either set a new storage path or delete the existing database files. Otherwise, a dimension mismatch error will occur.
### Integrate with ReAct Agent
```python
from agentscope.agent import ReActAgent
from agentscope.formatter import DashScopeChatFormatter
from agentscope.memory import InMemoryMemory
from agentscope.tool import Toolkit
# Create a ReAct agent with long-term memory
toolkit = Toolkit()
agent = ReActAgent(
name="Friday",
sys_prompt=(
"You are a helpful assistant named Friday. "
"If you think there is relevant information about "
"the user's preferences, you can record it to long-term "
"memory using the tool `record_to_memory`. "
"If you need to retrieve information from long-term "
"memory, use the tool `retrieve_from_memory`."
),
model=DashScopeChatModel(
model_name="qwen-max-latest",
api_key=os.environ.get("DASHSCOPE_API_KEY")
),
formatter=DashScopeChatFormatter(),
toolkit=toolkit,
memory=InMemoryMemory(),
long_term_memory=long_term_memory,
long_term_memory_mode="both"
)
# Use the agent
msg = Msg(
role="user",
content="When I travel to Hangzhou, I prefer to stay in a homestay",
name="user"
)
response = await agent(msg)
```
## Advanced Configuration
You can customize the mem0 config by directly set :
```python
long_term_memory = Mem0LongTermMemory(
agent_name="Friday",
user_name="user_123",
mem0_config=your_mem0_config # Pass your custom mem0 configuration
)
```
For more configuration options, refer to the [mem0 documentation](https://github.com/mem0ai/mem0).
## What's in the Example
The `memory_example.py` file demonstrates:
1. **Basic Memory Recording**: Recording user conversations to long-term memory
2. **Memory Retrieval**: Searching for stored memories using semantic similarity
3. **ReAct Agent Integration**: Using long-term memory with ReAct agents to store and retrieve user preferences automatically
## Reference
- [mem0 Documentation](https://github.com/mem0ai/mem0)
- [Qdrant Vector Database](https://qdrant.tech/)

View File

@@ -0,0 +1,185 @@
# -*- coding: utf-8 -*-
"""Memory example demonstrating long-term memory functionality with mem0.
This module provides examples of how to use the Mem0LongTermMemory class
for recording and retrieving persistent memories.
"""
import asyncio
import os
from dotenv import load_dotenv
from mem0.vector_stores.configs import VectorStoreConfig
from agentscope.memory import Mem0LongTermMemory
from agentscope.agent import ReActAgent
from agentscope.embedding import DashScopeTextEmbedding
from agentscope.formatter import DashScopeChatFormatter
from agentscope.memory import InMemoryMemory
from agentscope.message import Msg
from agentscope.model import DashScopeChatModel
from agentscope.tool import Toolkit
load_dotenv()
async def main() -> None:
"""Run the memory examples."""
# Initialize long term memory
long_term_memory = Mem0LongTermMemory(
agent_name="Friday",
user_name="user_123",
model=DashScopeChatModel(
model_name="qwen-max-latest",
api_key=os.environ.get("DASHSCOPE_API_KEY"),
stream=False,
),
embedding_model=DashScopeTextEmbedding(
model_name="text-embedding-v3",
api_key=os.environ.get("DASHSCOPE_API_KEY"),
dimensions=1024,
),
vector_store_config=VectorStoreConfig(
provider="qdrant",
config={
"on_disk": True,
"path": "../memory/qdrant_data", # Specify custom path
"embedding_model_dims": 1024,
},
),
)
# If you want to also use graph memory in mem0,
# the following is an example of using Neo4j graph store.
# from mem0.configs.base import MemoryConfig
# from mem0.graphs.configs import GraphStoreConfig
# long_term_memory = Mem0LongTermMemory(
# agent_name="Friday",
# user_name="user_123",
# embedding_model=DashScopeTextEmbedding(
# model_name="text-embedding-v3",
# api_key=os.environ.get("DASHSCOPE_API_KEY"),
# dimensions=1024,
# ),
# model=DashScopeChatModel(
# model_name="qwen-max-latest",
# api_key=os.environ.get("DASHSCOPE_API_KEY"),
# stream=False,
# ),
# vector_store_config=VectorStoreConfig(
# provider="qdrant",
# config={
# "on_disk": True,
# "path": "../memory/qdrant_data", # Specify custom path
# "embedding_model_dims": 1024,
# }),
# mem0_config=MemoryConfig(
# graph_store=GraphStoreConfig(
# provider="neo4j",
# config={
# "url": os.environ.get("NEO4J_URL",
# "neo4j://localhost:7687"),
# "username": os.environ.get("NEO4J_USER", "neo4j"),
# "password": os.environ.get("NEO4J_PASSWORD",
# "12345678"),
# "database": "neo4j",
# },
# ),
# ),
# )
print("=== Long Term Memory Examples with mem0 ===\n")
# Example 1: Basic conversation recording
print("1. Basic Conversation Recording")
print("-" * 40)
results = await long_term_memory.record(
msgs=[
Msg(
role="user",
content="Please help me book a hotel, preferably homestay",
name="user",
),
],
)
print(f"Recorded conversation: {results}\n")
# Example 2: Retrieving memories
print("2. Retrieving Memories")
print("-" * 40)
print("Searching for weather-related memories...")
weather_memories = await long_term_memory.retrieve(
msg=[
Msg(
role="user",
content="What's the weather like today?",
name="user",
),
],
)
print(f"Retrieved weather memories: {weather_memories}\n")
print("Searching for user preference memories...")
preference_memories = await long_term_memory.retrieve(
msg=[
Msg(
role="user",
content=(
"I prefer temperatures in Celsius and wind speed in km/h"
),
name="user",
),
],
)
print(f"Retrieved preference memories: {preference_memories}\n")
# Example 3: ReActAgent with long term memory
print("3. ReActAgent with long term memory")
print("-" * 40)
toolkit = Toolkit()
agent = ReActAgent(
name="Friday",
sys_prompt=(
"You are a helpful assistant named Friday. "
"If you think there is relevant information about "
"user's preference, you can record it to the long term "
"memory by tool call `record_to_memory`. "
"If you need to retrieve information from the long term "
"memory, you can use the tool call `retrieve_from_memory`."
),
model=DashScopeChatModel(
model_name="qwen-max-latest",
api_key=os.environ.get("DASHSCOPE_API_KEY"),
stream=False,
),
formatter=DashScopeChatFormatter(),
toolkit=toolkit,
memory=InMemoryMemory(),
long_term_memory=long_term_memory,
long_term_memory_mode="both",
)
await agent.memory.clear()
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"ReActAgent response: {msg.get_text_content()}\n")
msg = Msg(role="user", content="what preference do I have?", name="user")
msg = await agent(msg)
print(f"ReActAgent response: {msg.get_text_content()}\n")
msg = Msg(
role="user",
content="I prefer to visit the West Lake",
name="user",
)
msg = await agent(msg)
print(f"ReActAgent response: {msg.get_text_content()}\n")
if __name__ == "__main__":
asyncio.run(main())