Build and run agents you can see, understand and trust.
Python agentchatbotlarge-language-modelsllmllm-agentmcpmulti-agentmulti-modalreact-agentrealtime-agentvoice-agentvoice-assistant
feat(example): add memory compression example (#951) (#951)
Osier-Yia1e681a63b93
diff --git a/examples/memory_with_compression/README.md b/examples/memory_with_compression/README.mdnew file mode 100644index 000000000..2d2d7b0da--- /dev/null+++ b/examples/memory_with_compression/README.md@@ -0,0 +1,317 @@+# MemoryWithCompress++- [ ] TODO: The memory module with compression will be added to the agentscope library in the future.++## Overview++MemoryWithCompress is a memory management system designed for AgentScope's `ReActAgent`. It automatically compresses conversation history when the memory size exceeds a specified token limit, using a Large Language Model (LLM) to create concise summaries that preserve key information. This allows agents to maintain context over long conversations while staying within token constraints.++The system maintains two separate storage mechanisms:+- **`chat_history_storage`**: Stores the complete, unmodified conversation history (uses `MessageStorageBase` interface)+- **`memory_storage`**: Stores messages that may be compressed when token limits are exceeded (uses `MessageStorageBase` interface)++Both storage mechanisms are abstracted through the `MessageStorageBase` interface, allowing for flexible storage backends. By default, `InMemoryMessageStorage` is used for both.++## Core Features++### Automatic Memory Compression+- **Token-based Triggering**: Automatically compresses memory when the total token count exceeds `max_token`+- **LLM-Powered Summarization**: Uses an LLM to intelligently compress conversation history while preserving essential information+- **Structured Output**: Uses Pydantic schemas to ensure consistent compression format++### Dual Storage System+- **Complete History**: Maintains original, unmodified messages in `_chat_history` for reference+- **Compressed Memory**: Stores potentially compressed messages in `_memory` for efficient context management++### Flexible Memory Management+- **Filtering Support**: Provides `filter_func` parameter for custom memory filtering+- **Recent N Retrieval**: Supports retrieving only the most recent N messages+- **State Persistence**: Includes `state_dict()` and `load_state_dict()` methods for saving and loading memory state+- **Storage Abstraction**: Uses `MessageStorageBase` interface for flexible storage backends+- **Compression Triggers**: Supports both token-based and custom trigger functions for compression+- **Compression Timing Control**: Configurable compression on add (`compression_on_add`) and get (`compression_on_get`) operations++## File Structure++```+memory_with_compression/+├── README.md # This documentation file+├── main.py # Example demonstrating MemoryWithCompress usage+├── _memory_with_compress.py # Core MemoryWithCompress implementation+├── _memory_storage.py # Storage abstraction layer (MessageStorageBase, InMemoryMessageStorage)+├── _mc_utils.py # Utility functions (formatting, token counting, compression schema)++```++## Prerequisites++### Clone the AgentScope Repository+This example depends on AgentScope. Please clone the full repository to your local machine.++### Install Dependencies+**Recommended**: Python 3.10+++Install the required dependencies:+```bash+pip install agentscope+```++### API Keys+This example uses DashScope APIs by default. You need to set your API key as an environment variable:+```bash+export DASHSCOPE_API_KEY='YOUR_API_KEY'+```++You can easily switch to other models by modifying the configuration in `main.py`.++## How It Works++### 1. Memory Addition Flow+1. **Message Input**: New messages are added via the async `add()` method+2. **Dual Storage**: Messages are deep-copied and added to both `chat_history_storage` and `memory_storage`+3. **Optional Compression on Add**: If `compression_on_add=True`, compression may be triggered immediately after adding messages++### 2. Memory Retrieval and Compression Flow+When `get_memory()` is called (if `compression_on_get=True`):+1. **Token Counting**: The system calculates the total token count of all messages in `memory_storage`+2. **Compression Check**:+ - First checks if token count exceeds `max_token` (automatic compression)+ - Then checks if `compression_trigger_func` returns `True` (custom trigger)+3. **LLM Compression**: If compression is needed, all messages in `memory_storage` are sent to the LLM with a compression prompt+4. **Structured Output**: The LLM returns a structured response containing the compressed summary+5. **Memory Replacement**: The entire `memory_storage` is updated with the compressed message(s)+6. **Filtering & Selection**: Optional filtering and recent_n selection are applied+7. **Return**: The processed memory is returned++### 3. Compression Process+The compression uses a structured output approach:+- **Prompt**: Instructs the LLM to summarize conversation history while preserving key information+- **Customizable Prompt**: Supports `customized_compression_prompt` parameter for custom prompt templates+- **Schema**: Uses `MemoryCompressionSchema` (Pydantic model) to ensure consistent output format+- **Output Format**: Returns a message with content wrapped in `<compressed_memory>` tags+- **Async Support**: All compression operations are asynchronous++## Usage Examples++### Running the Example+To see `MemoryWithCompress` in action, run the example script:+```bash+python ./main.py+```++### Basic Initialization+Here is a snippet from `main.py` showing how to set up the agent and memory:++```python+from agentscope.agent import ReActAgent+from agentscope.model import DashScopeChatModel+from agentscope.formatter import DashScopeChatFormatter+from agentscope.token import OpenAITokenCounter+from agentscope.message import Msg+from _memory_with_compress import MemoryWithCompress++# 1. Create the model for agent and memory compression+model = DashScopeChatModel(+ api_key=os.environ.get("DASHSCOPE_API_KEY"),+ model_name="qwen-max",+ stream=False,+)++# 2. Optional: Define a custom compression trigger function+async def trigger_compression(msgs: list[Msg]) -> bool:+ # Trigger compression if the number of messages exceeds 2+ # and the last message is from the assistant+ return len(msgs) > 2 and msgs[-1].role == "assistant"++# 3. Initialize MemoryWithCompress+memory_with_compress = MemoryWithCompress(+ model=model,+ formatter=DashScopeChatFormatter(),+ max_token=3000, # Compress when memory exceeds 3000 tokens+ token_counter=OpenAITokenCounter(model_name="qwen-max"),+ compression_trigger_func=trigger_compression, # Optional custom trigger+ compression_on_add=False, # Don't compress on add (default)+ compression_on_get=True, # Compress on get (default)+)++# 4. Initialize ReActAgent with the memory instance+agent = ReActAgent(+ name="Friday",+ sys_prompt="You are a helpful assistant named Friday.",+ model=model,+ formatter=DashScopeChatFormatter(),+ memory=memory_with_compress,+)+```++### Custom Compression Function+You can provide a custom compression function:++```python+async def custom_compress(messages: List[Msg]) -> List[Msg]:+ # Your custom compression logic+ # Must return a List[Msg], not a single Msg+ compressed_content = "..."+ return [Msg("assistant", compressed_content, "assistant")]++memory_with_compress = MemoryWithCompress(+ model=model,+ formatter=formatter,+ max_token=300,+ compress_func=custom_compress,+)+```++### Custom Storage Backend+You can provide custom storage backends by implementing the `MessageStorageBase` interface:++```python+from _memory_storage import MessageStorageBase++class CustomStorage(MessageStorageBase):+ # Implement required methods: start, stop, health, add, delete, clear, get, replace, __aenter__, __aexit__+ ...++memory_with_compress = MemoryWithCompress(+ model=model,+ formatter=formatter,+ max_token=300,+ chat_history_storage=CustomStorage(),+ memory_storage=CustomStorage(),+)+```++## API Reference++### MemoryWithCompress Class++#### `__init__(...)`+Initializes the memory system. Key parameters include:++- `model` (ChatModelBase): The LLM model to use for compression+- `formatter` (FormatterBase): The formatter to use for formatting messages+- `max_token` (int): The maximum token count for `memory_storage`. Default: 28000. Compression is triggered when exceeded+- `chat_history_storage` (MessageStorageBase): Storage backend for complete chat history. Default: `InMemoryMessageStorage()`+- `memory_storage` (MessageStorageBase): Storage backend for compressed memory. Default: `InMemoryMessageStorage()`+- `token_counter` (Optional[TokenCounterBase]): The token counter for counting tokens. Default: None. If None, it will return the character count of the JSON string representation of messages (i.e., len(json.dumps(messages, ensure_ascii=False))).+- `compress_func` (Callable[[List[Msg]], Awaitable[List[Msg]]] | None): Custom compression function. Must be async and return `List[Msg]`. If None, uses the default `_compress_memory` method+- `compression_trigger_func` (Callable[[List[Msg]], Awaitable[bool]] | None): Optional function to trigger compression when token count is below `max_token`. Must be async and return `bool`. If None, compression only occurs when token count exceeds `max_token`+- `compression_on_add` (bool): Whether to check and compress memory when adding messages. Default: False+- `compression_on_get` (bool): Whether to check and compress memory when getting messages. Default: True+- `customized_compression_prompt` (str | None): Optional customized compression prompt template. Should include placeholders: `{max_token}`, `{messages_list_json}`, `{schema_json}`. Default: None (uses default template)++#### Main Methods++**`async add(msgs: Union[Sequence[Msg], Msg, None], compress_func=None, compression_trigger_func=None)`**+- Adds new messages to both `chat_history_storage` and `memory_storage`+- Messages are deep-copied to avoid modifying originals+- Raises `TypeError` if non-Msg objects are provided+- Parameters:+ - `msgs`: Messages to be added+ - `compress_func` (Optional): Override the instance-level compression function for this call+ - `compression_trigger_func` (Optional): Override the instance-level trigger function for this call+- If `compression_on_add=True`, may trigger compression after adding++**`async direct_update_memory(msgs: Union[Sequence[Msg], Msg, None])`**+- Directly updates the `memory_storage` with new messages (does not update `chat_history_storage`)+- Useful for replacing memory content directly++**`async get_memory(recent_n=None, filter_func=None, compress_func=None, compression_trigger_func=None)`**+- Retrieves memory content, automatically compressing if token limit is exceeded (if `compression_on_get=True`)+- Parameters:+ - `recent_n` (Optional[int]): Return only the most recent N messages+ - `filter_func` (Optional[Callable[[int, Msg], bool]]): Custom filter function that takes (index, message) and returns bool+ - `compress_func` (Optional): Override the instance-level compression function for this call+ - `compression_trigger_func` (Optional): Override the instance-level trigger function for this call+- Returns: `list[Msg]` - The memory content (potentially compressed)++**`async delete(indices: Union[Iterable[int], int])`**+- Deletes memory fragments from `memory_storage` (note: does not delete from `chat_history_storage`)+- Indices can be a single int or an iterable of ints++**`async size() -> int`**+- Returns the number of messages in `chat_history_storage`++**`async clear()`**+- Clears all memory from both `chat_history_storage` and `memory_storage`++**`state_dict() -> dict`**+- Returns a dictionary containing the serialized state:+ - `chat_history_storage`: List of message dictionaries from chat history+ - `memory_storage`: List of message dictionaries from memory+ - `max_token`: The max_token setting+- Note: This method handles async operations internally, so it can be called from both sync and async contexts++**`load_state_dict(state_dict: dict, strict: bool = True)`**+- Loads memory state from a dictionary+- Restores `chat_history_storage`, `memory_storage`, and `max_token` settings+- Note: This method handles async operations internally, so it can be called from both sync and async contexts++**`async retrieve(*args, **kwargs)`**+- Not implemented. Use `get_memory()` instead.+- Raises `NotImplementedError`++## Internal Methods++**`async _compress_memory(msgs: List[Msg]) -> List[Msg]`**+- Internal method that compresses messages using the LLM+- Uses structured output with `MemoryCompressionSchema`+- Returns a `List[Msg]` containing the compressed summary (typically a single message)+- Supports both streaming and non-streaming models++**`async _check_length_and_compress(compress_func=None) -> bool`**+- Checks if memory token count exceeds `max_token` and compresses if needed+- Returns `True` if compression was triggered, `False` otherwise++**`async check_and_compress(compress_func=None, compression_trigger_func=None, memory=None) -> tuple[bool, List[Msg]]`**+- Checks if compression is needed based on `compression_trigger_func`+- Returns a tuple: (was_compressed: bool, compressed_memory: List[Msg])+- If `memory` is provided, checks that instead of `memory_storage`++## Utility Functions++The `_mc_utils.py` module provides:++- **`format_msgs(msgs)`**: Formats a list of `Msg` objects into a list of dictionaries+- **`async count_words(token_counter, text)`**: Counts tokens in text (supports both string and list[dict] formats). Must be awaited.+- **`MemoryCompressionSchema`**: Pydantic model for structured compression output+- **`DEFAULT_COMPRESSION_PROMPT_TEMPLATE`**: Default prompt template for compression (includes placeholders: `{max_token}`, `{messages_list_json}`, `{schema_json}`)++## Storage Abstraction++The `_memory_storage.py` module provides:++- **`MessageStorageBase`**: Abstract base class for message storage backends+ - Required async methods: `start()`, `stop()`, `health()`, `add()`, `delete()`, `clear()`, `get()`, `replace()`, `__aenter__()`, `__aexit__()`+- **`InMemoryMessageStorage`**: Default in-memory implementation+ - Stores messages in a simple list+ - Suitable for most use cases++## Best Practices++- **Token Limit Selection**: Choose `max_token` based on your model's context window and typical conversation length+- **Compression Timing**:+ - Set `compression_on_get=True` (default) for compression during retrieval+ - Set `compression_on_add=False` (default) to avoid compression during add operations, as it may not complete before `get_memory()` is called+- **Async Operations**: All main methods are async, so use `await` when calling them+- **State Persistence**: Use `state_dict()` and `load_state_dict()` to save/restore conversation state between sessions+- **Custom Compression**: For domain-specific compression needs, implement a custom `compress_func` (must be async and return `List[Msg]`)+- **Compression Triggers**: Use `compression_trigger_func` for custom compression logic beyond token limits (e.g., compress after N messages, compress on specific conditions)+- **Storage Backends**: Implement custom `MessageStorageBase` subclasses for persistent storage (e.g., database, file system)++## Troubleshooting++- **Compression Not Triggering**:+ - Check that `compression_on_get=True` if you expect compression during retrieval+ - Verify that `max_token` is set appropriately+ - Ensure `get_memory()` is being called (and awaited)+ - If using `compression_trigger_func`, verify it returns `True` when compression should occur+- **Structured Output Errors**: Ensure your model supports structured output (e.g., DashScope models with `structured_model` parameter)+- **Token Counting Issues**: Verify that your `token_counter` is compatible with your model and correctly configured+- **Async/Await Errors**: Remember that most methods are async - use `await` when calling them+- **Storage Issues**: If using custom storage backends, ensure all required methods are properly implemented and async++## Reference++- [AgentScope Documentation](https://github.com/agentscope-ai/agentscope)+- [Pydantic Documentation](https://docs.pydantic.dev/)diff --git a/examples/memory_with_compression/_mc_utils.py b/examples/memory_with_compression/_mc_utils.pynew file mode 100644index 000000000..1f3bd13f4--- /dev/null+++ b/examples/memory_with_compression/_mc_utils.py@@ -0,0 +1,141 @@+# -*- coding: utf-8 -*-+"""Utility functions for memory compression."""+import json+from typing import Any, Sequence, Union++from pydantic import BaseModel, Field++from agentscope.message import Msg+from agentscope.token import TokenCounterBase+++class MemoryCompressionSchema(BaseModel):+ """+ The schema for the memory compression.+ """++ compressed_text: str = Field(..., description="The compressed text")+++class MemoryWithCompressionState(BaseModel):+ """+ The state for the memory with compress memory.+ """++ max_token: int = Field(+ ...,+ description="The maximum token count for memories in memory_storage",+ )+ chat_history_storage: list[dict[str, Any]] = Field(+ ...,+ description=(+ "The chat history storage in the current conversation session"+ ),+ )+ memory_storage: list[dict[str, Any]] = Field(+ ...,+ description=(+ "The compressed messages storage in the current "+ "conversation session"+ ),+ )+++# Default compression prompt template+# Placeholders: {max_token}, {messages_list_json}, {schema_json}+DEFAULT_COMPRESSION_PROMPT_TEMPLATE = (+ "You are a memory compression assistant. Please summarize and "+ "compress the following conversation history into a concise "+ "summary that preserves the key information. \n\n You should "+ "compress the conversation into less than {max_token} "+ "tokens. The summary should be in the following json format:\n\n"+ "{schema_json}"+ "\n\nThe conversation history is:\n\n{messages_list_json}"+)+++def format_msgs(+ msgs: Union[Sequence[Msg], Msg],+) -> list[dict]:+ """Format a list of messages to a list of dicts in order.+ Args:+ msgs (`Union[Sequence[Msg], Msg]`):+ The messages to format. Only `Msg` objects are accepted.++ Raises:+ ValueError: The message type or the content type is invalid.++ Returns:+ `list[dict]`: The formatted messages.+ """+ results = []+ if not isinstance(msgs, Sequence):+ msgs = [msgs]+ for msg in msgs:+ if not isinstance(msg, Msg):+ raise ValueError(f"Invalid message type: {type(msg)}")+ role = msg.role+ content = msg.content+ if isinstance(content, str):+ results.append(+ {+ "role": role,+ "content": content,+ },+ )+ elif isinstance(content, list):+ unit = {+ "role": role,+ "content": [],+ }+ for c in content:+ unit["content"].append(c)++ results.append(unit)+ else:+ raise ValueError(f"Invalid content type: {type(content)}")+ return results+++async def count_words(+ token_counter: TokenCounterBase | None,+ text: str | list[dict],+) -> int:+ """Count the number of tokens using TokenCounter.count interface.++ Args:+ token_counter (TokenCounterBase):+ the token counter to use for counting tokens+ text (str|list[dict]):+ the text to count the number of tokens. If str, can be plain+ text or JSON string.++ Returns:+ int: the number of tokens in the text+ """+ if isinstance(text, list):+ # text is already a list of dicts+ messages = text+ elif isinstance(text, str):+ # text is a string - try to parse as JSON first+ try:+ parsed = json.loads(text)+ if isinstance(parsed, list):+ # It's a JSON array of messages+ messages = parsed+ else:+ # It's a JSON object or other type, wrap it+ messages = [{"role": "user", "content": text}]+ except (json.JSONDecodeError, TypeError):+ # Not valid JSON, treat as plain text+ messages = [{"role": "user", "content": text}]+ else:+ # Fallback: wrap in a message+ messages = [{"role": "user", "content": str(text)}]++ # if token_counter is None, count the number of tokens in the messages+ if token_counter is None:+ return len(json.dumps(messages, ensure_ascii=False))++ # if token_counter is not None, count the number of tokens in the messages+ return await token_counter.count(messages)diff --git a/examples/memory_with_compression/_memory_storage.py b/examples/memory_with_compression/_memory_storage.pynew file mode 100644index 000000000..f604ea0fe--- /dev/null+++ b/examples/memory_with_compression/_memory_storage.py@@ -0,0 +1,273 @@+# -*- coding: utf-8 -*-+"""The memory storage base class."""+from abc import abstractmethod+from typing import Any, Iterable, Optional, Union, cast+from types import TracebackType++from agentscope.message import Msg+++class MessageStorageBase:+ """The message storage base class."""++ @abstractmethod+ async def start(self, **kwargs: Any) -> None:+ """Establish connection to the storage backend.++ This method should be called after initialization to perform+ async setup operations that cannot be done in __init__.+ """++ @abstractmethod+ async def stop(self, **kwargs: Any) -> None:+ """Close the connection and clean up resources.++ This method should be called when the storage is no longer needed+ to properly release resources.+ """++ @abstractmethod+ async def health(self, **kwargs: Any) -> bool:+ """Check the health status of the storage backend.++ Returns:+ bool: True if the storage is healthy and accessible,+ False otherwise.+ """++ @abstractmethod+ async def add(self, messages: list[Msg], **kwargs: Any) -> None:+ """Record the messages into the message storage.++ Args:+ messages (`list[Msg]`):+ The messages to be added to storage+ """++ @abstractmethod+ async def delete(+ self,+ indices: Union[Iterable[int], int, None] = None,+ **kwargs: Any,+ ) -> None:+ """Delete the messages from the message storage.++ Args:+ indices (`Iterable[int] | int | None`, optional):+ The indices of messages to delete. If None, no messages+ are deleted.+ **kwargs (`Any`):+ Additional keyword arguments for storage-specific options.+ """++ @abstractmethod+ async def clear(self, **kwargs: Any) -> None:+ """Clear the messages from the message storage."""++ @abstractmethod+ async def get(+ self,+ recent_n: Optional[int] = None,+ **kwargs: Any,+ ) -> list[Msg]:+ """Get the messages from the memory storage.++ Args:+ recent_n (`Optional[int]`, optional):+ The number of recent messages to retrieve++ Returns:+ `list[Msg]`:+ The list of messages from storage+ """++ @abstractmethod+ async def replace(self, messages: list[Msg], **kwargs: Any) -> None:+ """Update the messages in the message storage.++ Args:+ messages (`list[Msg]`):+ The new messages to replace existing storage content+ """++ @abstractmethod+ async def __aenter__(self) -> "MessageStorageBase":+ """Async context manager entry.++ Returns:+ `MessageStorageBase`:+ The storage instance+ """++ @abstractmethod+ async def __aexit__(+ self,+ exc_type: Optional[type[BaseException]],+ exc_val: Optional[BaseException],+ exc_tb: Optional[TracebackType],+ ) -> bool:+ """Async context manager exit.++ Args:+ exc_type (`Optional[type[BaseException]]`):+ The exception type if an exception occurred+ exc_val (`Optional[BaseException]`):+ The exception value if an exception occurred+ exc_tb (`Optional[TracebackType]`):+ The exception traceback if an exception occurred++ Returns:+ `bool`:+ False to propagate exceptions+ """+++class InMemoryMessageStorage(MessageStorageBase):+ """The in-memory message storage."""++ def __init__(self) -> None:+ """Initialize the in-memory message storage.++ Note: For async setup operations, call start() after initialization.+ """+ self._storage_client: list[Msg] = []+ self._connected: bool = False++ async def start(self, **kwargs: Any) -> None:+ """Establish connection to the storage backend.++ For in-memory storage, this initializes the storage list and+ sets the connection flag. Kept for interface consistency with+ other storage backends that require async connection setup.+ """++ if hasattr(self, "_connected") and self._connected:+ return+ self._storage_client = []+ self._connected = True++ async def stop(self, **kwargs: Any) -> None:+ """Close the connection and clean up resources.++ For in-memory storage, this clears the storage and resets+ the connection flag.+ """+ if hasattr(self, "_connected") and not self._connected:+ return+ self._storage_client = []+ self._connected = False++ async def health(self, **kwargs: Any) -> bool:+ """Check the health status of the storage backend.++ Returns:+ bool: True if the storage is healthy and accessible,+ False otherwise.+ """+ return hasattr(self, "_connected") and self._connected is True++ async def add(self, messages: list[Msg], **kwargs: Any) -> None:+ """Record the messages into the message storage.++ Args:+ messages (`list[Msg]`):+ The messages to be added to storage+ """+ self._storage_client.extend(messages)++ async def delete(+ self,+ indices: Union[Iterable[int], int, None] = None,+ **kwargs: Any,+ ) -> None:+ """Delete the messages from the message storage.++ Args:+ indices (`Iterable[int] | int | None`, optional):+ The indices of messages to delete. If None, no messages+ are deleted.+ **kwargs (`Any`):+ Additional keyword arguments for storage-specific options.+ """+ if indices is None:+ return+ if isinstance(indices, int):+ indices = [indices]+ indices_set = set(indices)+ self._storage_client = [+ msg+ for idx, msg in enumerate(self._storage_client)+ if idx not in indices_set+ ]++ async def clear(self, **kwargs: Any) -> None:+ """Clear the messages from the message storage."""+ self._storage_client = []++ async def get(+ self,+ recent_n: Optional[int] = None,+ **kwargs: Any,+ ) -> list[Msg]:+ """Get the messages from the memory storage.++ Args:+ recent_n (`Optional[int]`, optional):+ The number of recent messages to retrieve. If None,+ returns all messages.++ Returns:+ `list[Msg]`:+ The list of messages from storage+ """+ if recent_n is None:+ return self._storage_client+ # Type narrowing: recent_n is guaranteed to be int at this point+ n = cast(int, recent_n)+ if n > len(self._storage_client):+ return self._storage_client+ # Use positive index to avoid unary minus operator+ start_idx = len(self._storage_client) - n+ return self._storage_client[start_idx:]++ async def replace(self, messages: list[Msg], **kwargs: Any) -> None:+ """Replace the messages in the message storage.++ Args:+ messages (`list[Msg]`):+ The new messages to replace the existing storage content+ """+ self._storage_client = messages++ async def __aenter__(self) -> "InMemoryMessageStorage":+ """Async context manager entry.++ Returns:+ `InMemoryMessageStorage`:+ The storage instance+ """+ await self.start()+ return self++ async def __aexit__(+ self,+ exc_type: Optional[type[BaseException]],+ exc_val: Optional[BaseException],+ exc_tb: Optional[TracebackType],+ ) -> bool:+ """Async context manager exit.++ Args:+ exc_type (`Optional[type[BaseException]]`):+ The exception type if an exception occurred+ exc_val (`Optional[BaseException]`):+ The exception value if an exception occurred+ exc_tb (`Optional[TracebackType]`):+ The exception traceback if an exception occurred++ Returns:+ `bool`:+ False to propagate exceptions+ """+ await self.stop()+ return Falsediff --git a/examples/memory_with_compression/_memory_with_compress.py b/examples/memory_with_compression/_memory_with_compress.pynew file mode 100644index 000000000..d2c8e27fe--- /dev/null+++ b/examples/memory_with_compression/_memory_with_compress.py@@ -0,0 +1,713 @@+# -*- coding: utf-8 -*-+"""The MemoryWithCompress class for memory management with compression."""++import asyncio+import concurrent.futures+import copy+import functools+import json+from typing import (+ Any,+ Awaitable,+ Callable,+ Iterable,+ List,+ Optional,+ Sequence,+ TypeVar,+ Union,+)+from pydantic import ValidationError+from _mc_utils import ( # noqa: E402+ count_words,+ format_msgs,+ DEFAULT_COMPRESSION_PROMPT_TEMPLATE,+ MemoryWithCompressionState,+ MemoryCompressionSchema,+)+from _memory_storage import ( # noqa: E402+ InMemoryMessageStorage,+ MessageStorageBase,+)+from agentscope.formatter import FormatterBase+from agentscope.memory import MemoryBase+from agentscope.message import Msg+from agentscope.model import ChatModelBase+from agentscope.token import TokenCounterBase++T = TypeVar("T")+++def ensure_health(+ func: Callable[..., Awaitable[T]],+) -> Callable[..., Awaitable[T]]:+ """Async decorator that ensures the MemoryWithCompress health check+ passes before method execution.++ Args:+ func (`Callable[..., Awaitable[T]]`):+ The async function to be decorated++ Returns:+ `Callable[..., Awaitable[T]]`:+ The wrapped async function with health check+ """++ @functools.wraps(func)+ async def wrapper(self: Any, *args: Any, **kwargs: Any) -> T:+ await self.check_health()+ return await func(self, *args, **kwargs)++ return wrapper+++class MemoryWithCompress(MemoryBase):+ """+ MemoryWithCompress is a memory manager that stores original messages+ in chat_history_storage and compressed messages in memory_storage in the+ current conversation session.+ The difference between this memory and longterm memory is that this+ memory is used to store the messages in the current conversation session,+ while longterm memory is used to store the important information across+ multiple conversation sessions.+ """++ def __init__(+ self,+ model: ChatModelBase,+ formatter: FormatterBase,+ max_token: int = 28000,+ chat_history_storage: MessageStorageBase = InMemoryMessageStorage(),+ memory_storage: MessageStorageBase = InMemoryMessageStorage(),+ token_counter: Optional[TokenCounterBase] = None,+ compress_func: Callable[[List[Msg]], Awaitable[List[Msg]]]+ | None = None,+ compression_trigger_func: Callable[[List[Msg]], Awaitable[bool]]+ | None = None,+ compression_on_add: bool = False,+ compression_on_get: bool = True,+ customized_compression_prompt: str | None = None,+ ) -> None:+ """Initialize the MemoryWithCompress.++ Args:+ model (`ChatModelBase`):+ the model to use for compression+ formatter (`FormatterBase`):+ the formatter to use for formatting messages+ max_token (`int`):+ the maximum token count for memories in memory_storage.+ If exceeded, MemoryWithCompress will compress the memory.+ chat_history_storage (`MessageStorageBase`):+ the storage to use for chat history, default is+ InMemoryMessageStorage. It is used to store the original+ messages in the current conversation session.+ memory_storage (`MessageStorageBase`):+ the storage to use for memory, default is+ InMemoryMessageStorage. It is used to store the compressed+ messages in the current conversation session.+ token_counter (`Optional[TokenCounterBase]`):+ the token counter to use for counting tokens, default+ is None. If None, it will return the character count of+ the JSON string representation of messages (i.e.,+ len(json.dumps(messages, ensure_ascii=False))).+ compress_func (`Callable[[List[Msg]], Awaitable[List[Msg]]]`):+ the function to compress the memory, it should return+ an Awaitable[List[Msg]] object, the input is the list+ of messages to compress+ compression_trigger_func (+ `Callable[[List[Msg]], Awaitable[bool]]`+ ):+ Optional function to trigger compression when token count+ is below max_token. It receives the list of messages in+ memory_storage as input and returns an Awaitable[bool]. If it+ returns True, compression will be triggered even when+ token count hasn't exceeded max_token. If None (default),+ compression only occurs when token count exceeds max_token.+ compression_on_add (`bool`):+ Whether to check and compress the memory when adding messages.+ If True, the memory will be checked for compression needs and+ compressed if necessary. If False, the memory will not be+ compressed on add. Default is False, because when checking+ memory during add operations, compression may not be finished+ yet, and get_memory will return uncompressed memory.+ compression_on_get (`bool`):+ Whether to check and compress the memory when getting messages.+ If True, the memory will be checked for compression needs and+ compressed if necessary. Default is True.+ customized_compression_prompt (`str | None`):+ Optional customized compression prompt template. If None+ (default), the default compression prompt template will be+ used. If a string is provided, it should be a template+ string with placeholders: {max_token}, {messages_list_json},+ {schema_json}. The template will be formatted with these+ values when generating the prompt.+ """+ super().__init__()++ self.chat_history_storage = chat_history_storage+ self.memory_storage = memory_storage+ self.customized_compression_prompt = customized_compression_prompt++ self.model = model+ self.formatter = formatter+ self.max_token = max_token+ self.token_counter = token_counter+ self.compress_func = (+ compress_func+ if compress_func is not None+ else self._compress_memory+ )+ self.compression_trigger_func = compression_trigger_func+ self.compression_on_add = compression_on_add+ self.compression_on_get = compression_on_get++ async def check_health(self) -> None:+ """+ Check if the memory system is healthy.+ Verifies that storage backends and model are accessible.+ """+ # Check if chat_history_storage is accessible+ if not await self.chat_history_storage.health():+ await self.chat_history_storage.start()+ if not await self.memory_storage.health():+ await self.memory_storage.start()++ @ensure_health+ async def add(+ self,+ msgs: Union[Sequence[Msg], Msg, None],+ compress_func: Callable[[List[Msg]], Awaitable[List[Msg]]]+ | None = None,+ compression_trigger_func: Callable[[List[Msg]], Awaitable[bool]]+ | None = None,+ ) -> None:+ """+ Add new messages to both chat_history_storage and memory_storage.++ Args:+ msgs (`Union[Sequence[Msg], Msg, None]`):+ Messages to be added.+ compress_func (+ `Callable[[List[Msg]], Awaitable[List[Msg]]] | None`+ ):+ the function to compress the memory, it should return+ an Awaitable[List[Msg]] object, the input is the list+ of messages to compress. If None (default), the default+ compress_func will be used. if provided, it will replace+ the self.compress_func in the add call.+ compression_trigger_func (+ `Callable[[List[Msg]], Awaitable[bool]] | None`+ ):+ Optional function to trigger compression when token count+ is below max_token. It receives the list of messages in+ memory_storage as input and returns an Awaitable[bool]. If it+ returns True, compression will be triggered even when+ token count hasn't exceeded max_token. If None (default),+ compression only occurs when token count exceeds max_token.+ If provided, it will replace the self.compression_trigger_func+ in the add call.+ """+ if msgs is None:+ return++ # Convert to list if single message+ if not isinstance(msgs, Sequence):+ msgs = [msgs]++ # Ensure all items are Msg objects+ msg_list: List[Msg] = []+ for msg in msgs:+ if not isinstance(msg, Msg):+ raise TypeError(f"Expected Msg object, got {type(msg)}")+ msg_list.append(msg)++ # Deep copy messages to avoid modifying originals+ deep_copied_msgs: List[Msg] = copy.deepcopy(msg_list)++ # Add to chat_history_storage (original messages)+ await self.chat_history_storage.add(deep_copied_msgs)++ # Add to memory_storage (same messages, will be compressed if needed)+ await self.memory_storage.add(deep_copied_msgs)++ if self.compression_on_add:+ # first check the total token of the memory is greater than+ # max_token and compress it if needed+ compressed = await self._check_length_and_compress(+ compress_func+ if compress_func is not None+ else self.compress_func,+ )+ if not compressed:+ # if the memory is not compressed, check if it needs+ # compression and compress it if needed+ compressed, compressed_memory = await self.check_and_compress(+ compress_func+ if compress_func is not None+ else self.compress_func,+ compression_trigger_func+ if compression_trigger_func is not None+ else self.compression_trigger_func,+ )+ if compressed:+ await self.memory_storage.replace(compressed_memory)++ @ensure_health+ async def direct_update_memory(+ self,+ msgs: Union[Sequence[Msg], Msg, None],+ ) -> None:+ """+ Directly update the memory with new messages.++ Args:+ msgs (`Union[Sequence[Msg], Msg, None]`):+ Messages to be added.++ """+ if msgs is None:+ return+ if not isinstance(msgs, Sequence):+ msgs = [msgs]+ # Ensure all items are Msg objects+ msg_list: List[Msg] = []+ for msg in msgs:+ if not isinstance(msg, Msg):+ raise TypeError(f"Expected Msg object, got {type(msg)}")+ msg_list.append(msg)+ # Deep copy messages to avoid modifying originals+ await self.memory_storage.replace(msg_list)++ @ensure_health+ async def get_memory(+ self,+ recent_n: Optional[int] = None,+ filter_func: Optional[Callable[[int, Msg], bool]] = None,+ compress_func: Callable[[List[Msg]], Awaitable[List[Msg]]]+ | None = None,+ compression_trigger_func: Callable[[List[Msg]], Awaitable[bool]]+ | None = None,+ ) -> list[Msg]:+ """+ Get memory content. If memory_storage token count exceeds max_token,+ compress all messages into a single message.++ Args:+ recent_n (`Optional[int]`):+ The number of memories to return.+ filter_func (`Optional[Callable[[int, Msg], bool]]`):+ The function to filter memories, which takes the index and+ message as input, and returns a boolean value.+ compress_func (+ `Callable[[List[Msg]], Awaitable[List[Msg]]] | None`+ ):+ the function to compress the memory, it should return+ an Awaitable[List[Msg]] object, the input is the list+ of messages to compress. If None (default), the default+ compress_func will be used. if provided, it will replace+ the self.compress_func in the get_memory call.+ compression_trigger_func (+ `Callable[[List[Msg]], Awaitable[bool]] | None`+ ):+ Optional function to trigger compression when token count+ is below max_token. It receives the list of messages in+ memory_storage as input and returns an Awaitable[bool]. If it+ returns True, compression will be triggered even when+ token count hasn't exceeded max_token. If None (default),+ compression only occurs when token count exceeds max_token.+ If None (default), the self.compression_trigger_func will be+ used. if provided, it will replace the+ self.compression_trigger_func in the get_memory call.++ Returns:+ `list[Msg]`:+ The memory content+ """+ if self.compression_on_get:+ # first check the total token of the memory is greater than+ # max_token and compress it if needed+ compressed = await self._check_length_and_compress(compress_func)+ if not compressed:+ # if the memory is not compressed, check if it needs+ # compression and compress it if needed+ compressed, compressed_memory = await self.check_and_compress(+ compress_func,+ compression_trigger_func,+ )+ if compressed:+ await self.memory_storage.replace(compressed_memory)++ # Apply filter if provided+ memories = await self.memory_storage.get()+ if filter_func is not None:+ filtered_memories = [+ msg for i, msg in enumerate(memories) if filter_func(i, msg)+ ]+ else:+ filtered_memories = memories++ # Return recent_n messages if specified+ if recent_n is not None and recent_n > 0:+ # Type assertion: recent_n is guaranteed to be int here+ assert recent_n is not None # For type narrowing+ n: int = recent_n+ if n < len(filtered_memories):+ # pylint: disable=invalid-unary-operand-type+ return filtered_memories[-n:]+ return filtered_memories+ return filtered_memories++ async def _compress_memory(self, msgs: List[Msg]) -> List[Msg]:+ """Compress all messages using LLM.++ Args:+ msgs (`List[Msg]`):+ The list of messages to compress++ Returns:+ `List[Msg]`:+ The compressed messages+ """+ # Format all messages for compression+ messages_list = format_msgs(msgs)++ # Prepare template variables+ messages_list_json = json.dumps(+ messages_list,+ ensure_ascii=False,+ indent=2,+ )+ schema_json = json.dumps(+ MemoryCompressionSchema.model_json_schema(),+ ensure_ascii=False,+ indent=2,+ )++ # Generate compression prompt using template+ prompt_template = (+ self.customized_compression_prompt+ if self.customized_compression_prompt is not None+ else DEFAULT_COMPRESSION_PROMPT_TEMPLATE+ )+ compression_prompt = prompt_template.format(+ max_token=self.max_token,+ messages_list_json=messages_list_json,+ schema_json=schema_json,+ )++ # Call the model to compress+ # Format the message using the formatter+ prompt_msg = Msg("user", compression_prompt, "user")+ formatted_prompt = await self.formatter.format([prompt_msg])++ # Use structured_model parameter (not response_schema)+ res = await self.model(+ formatted_prompt,+ structured_model=MemoryCompressionSchema,+ )++ # Extract structured output from metadata+ # The structured output is stored in res.metadata as a dict+ if self.model.stream:+ structured_data = None+ async for content_chunk in res:+ if content_chunk.metadata:+ structured_data = content_chunk.metadata+ if structured_data:+ # Validate and parse the structured output+ if not isinstance(structured_data, dict):+ raise ValueError(+ f"Expected structured_data to be a dict, "+ f"got {type(structured_data)}: {structured_data}",+ )+ try:+ parsed_schema = MemoryCompressionSchema(**structured_data)+ except ValidationError as e:+ raise ValueError(+ f"Failed to parse memory compression schema "+ f"from stream metadata. "+ f"Metadata: {structured_data}. "+ f"Validation errors: "+ f"{e.errors() if hasattr(e, 'errors') else str(e)}",+ ) from e+ return [+ Msg(+ name="assistant",+ role="assistant",+ content=(+ f"The compression of the previous "+ f"conversation is: "+ f"<compressed_memory>\n"+ f"{parsed_schema.compressed_text}"+ f"\n</compressed_memory>"+ ),+ ),+ ]+ else:+ raise ValueError(+ "No structured output found in stream response",+ )+ else:+ if res.metadata:+ # Validate and parse the structured output+ if not isinstance(res.metadata, dict):+ raise ValueError(+ f"Expected metadata to be a dict, "+ f"got {type(res.metadata)}: {res.metadata}",+ )+ try:+ parsed_schema = MemoryCompressionSchema(**res.metadata)+ except ValidationError as e:+ raise ValueError(+ f"Failed to parse memory compression schema "+ f"from metadata. "+ f"Metadata: {res.metadata}. "+ f"Validation errors: "+ f"{e.errors() if hasattr(e, 'errors') else str(e)}",+ ) from e+ return [+ Msg(+ name="assistant",+ role="assistant",+ content=(+ f"The compression of the previous "+ f"conversation is: "+ f"<compressed_memory>\n"+ f"{parsed_schema.compressed_text}"+ f"\n</compressed_memory>"+ ),+ ),+ ]+ else:+ raise ValueError(+ "No structured output found in response metadata",+ )++ @ensure_health+ async def delete(self, indices: Union[Iterable[int], int]) -> None:+ """+ Delete memory fragments.++ Args:+ indices (`Union[Iterable[int], int]`):+ indices of the memory fragments to delete+ """+ await self.memory_storage.delete(indices)++ @ensure_health+ async def _check_length_and_compress(+ self,+ compress_func: Callable[[List[Msg]], Awaitable[List[Msg]]]+ | None = None,+ ) -> bool:+ """+ Check if the memory needs compression by the provided+ compress_func and compress it if needed. If compress_func is called,+ the self._memory_storage will be replaced with the compressed memory.++ Args:+ compress_func (+ `Callable[[List[Msg]], Awaitable[List[Msg]]] | None`+ ):+ the function to compress the memory, it should return+ an Awaitable[List[Msg]] object, the input is the list+ of messages to compress. If None (default), the+ self.compress_func will be used. if provided, it will replace+ the self.compress_func in the check_length_and_compress call.++ Returns:+ `bool`:+ True if compression was triggered, False otherwise+ """+ is_compressed = False+ if compress_func is None:+ compress_func = self.compress_func+ memory_msgs = await self.memory_storage.get()+ if len(memory_msgs) > 0:+ total_tokens = await count_words(+ self.token_counter,+ format_msgs(memory_msgs),+ )+ if total_tokens > self.max_token:+ await self.memory_storage.replace(+ await compress_func(memory_msgs),+ )+ is_compressed = True+ return is_compressed++ @ensure_health+ async def check_and_compress(+ self,+ compress_func: Callable[[List[Msg]], Awaitable[List[Msg]]]+ | None = None,+ compression_trigger_func: Callable[[List[Msg]], Awaitable[bool]]+ | None = None,+ memory: List[Msg] | None = None,+ ) -> tuple[bool, List[Msg]]:+ """+ Check if the memory needs compression by the provided+ compression_trigger_func and compress it by the provided+ compress_func if needed.++ Args:+ compress_func (+ `Callable[[List[Msg]], Awaitable[List[Msg]]] | None`+ ):+ Optional function to compress the memory, it should return+ an Awaitable[List[Msg]] object, the input is the list+ of messages to compress. If None (default), the+ self.compress_func will be used.+ compression_trigger_func (+ `Callable[[List[Msg]], Awaitable[bool]] | None`+ ):+ Optional function to trigger compression. If None (default),+ the self.compression_trigger_func will be used.+ memory (`List[Msg] | None`):+ The memory to check and compress. If None (default), the+ self.memory_storage will be used.++ Returns:+ `tuple[bool, List[Msg]]`: A tuple containing a boolean value+ indicating if compression was triggered and the+ compressed memory. The boolean value is True if+ compression was triggered, False otherwise. The+ compressed memory is the list of messages that were+ compressed. If compression was not triggered, the+ compressed memory is the same as the input memory.+ """+ # if memory is not provided, use the _memory+ if memory is None:+ memory = await self.memory_storage.get()+ # if compress_func is not provided, use the self.compress_func+ if compress_func is None:+ compress_func = self.compress_func+ # if compression_trigger_func is not provided, use the self.+ # compression_trigger_func+ if compression_trigger_func is None:+ compression_trigger_func = self.compression_trigger_func++ # check if the memory needs compression by compression_trigger_func+ # and compress it if needed.+ # Notice that compression_trigger_func is optional,+ # so if it is not provided, the memory will not be compressed+ # by compression_trigger_func.+ if compression_trigger_func is not None:+ should_compress = await compression_trigger_func(memory)+ else:+ should_compress = False++ if should_compress:+ compressed_memory = await compress_func(memory)+ else:+ compressed_memory = memory+ return should_compress, compressed_memory++ @ensure_health+ async def retrieve(self, *args: Any, **kwargs: Any) -> None:+ """+ Retrieve items from the memory.+ This method is not implemented as get_memory is used instead.+ """+ raise NotImplementedError(+ "Use get_memory() instead of retrieve() for MemoryWithCompress",+ )++ @ensure_health+ async def size(self) -> int:+ """+ Get the size of the memory.++ Returns:+ `int`:+ The number of messages in chat_history_storage+ """+ return len(await self.chat_history_storage.get())++ @ensure_health+ async def clear(self) -> None:+ """+ Clear all memory.+ """+ await self.chat_history_storage.clear()+ await self.memory_storage.clear()++ def state_dict(self) -> MemoryWithCompressionState:+ """+ Get the state dictionary of the memory.++ Returns:+ `MemoryWithCompressionState`:+ The state dictionary containing chat_history_storage and+ memory_storage, and max_token+ """++ async def _get_state_dict() -> MemoryWithCompressionState:+ chat_history_state_dict = [+ _.to_dict() for _ in await self.chat_history_storage.get()+ ]+ memory_state_dict = [+ _.to_dict() for _ in await self.memory_storage.get()+ ]+ return MemoryWithCompressionState(+ max_token=self.max_token,+ chat_history_storage=chat_history_state_dict,+ memory_storage=memory_state_dict,+ )++ try:+ # Try to get the running event loop+ asyncio.get_running_loop()+ # If we're in a running event loop, we need to create a new one+ # in a separate thread or use nest_asyncio+ # For simplicity, we'll create a new event loop+ with concurrent.futures.ThreadPoolExecutor() as executor:+ future = executor.submit(asyncio.run, _get_state_dict())+ return future.result()+ except RuntimeError:+ # No running event loop, safe to use asyncio.run+ return asyncio.run(_get_state_dict())++ def load_state_dict(+ self,+ state_dict: MemoryWithCompressionState,+ strict: bool = True, # pylint: disable=unused-argument+ ) -> None:+ """+ Load the state dictionary of the memory.++ Args:+ state_dict (`MemoryWithCompressionState`):+ The state dictionary to load+ strict (`bool`):+ Whether to strictly enforce that the keys in state_dict+ match the keys returned by state_dict()+ """++ async def _load_state_dict() -> None:+ if state_dict.chat_history_storage:+ await self.chat_history_storage.replace(+ [+ Msg.from_dict(msg)+ for msg in state_dict.chat_history_storage+ ],+ )+ if state_dict.memory_storage:+ await self.memory_storage.replace(+ [Msg.from_dict(msg) for msg in state_dict.memory_storage],+ )+ if state_dict.max_token:+ self.max_token = state_dict.max_token++ try:+ # Try to get the running event loop+ asyncio.get_running_loop()+ # If we're in a running event loop, we need to create a new one+ # in a separate thread or use nest_asyncio+ # For simplicity, we'll create a new event loop+ with concurrent.futures.ThreadPoolExecutor() as executor:+ future = executor.submit(asyncio.run, _load_state_dict())+ future.result()+ except RuntimeError:+ # No running event loop, safe to use asyncio.run+ asyncio.run(_load_state_dict())diff --git a/examples/memory_with_compression/main.py b/examples/memory_with_compression/main.pynew file mode 100644index 000000000..37b012d95--- /dev/null+++ b/examples/memory_with_compression/main.py@@ -0,0 +1,83 @@+# -*- coding: utf-8 -*-+"""The main entry point of the MemoryWithCompress example."""+import asyncio+import os+from _memory_with_compress import MemoryWithCompress+from agentscope.agent import ReActAgent+from agentscope.formatter import DashScopeChatFormatter+from agentscope.message import Msg+from agentscope.model import DashScopeChatModel+from agentscope.tool import Toolkit+from agentscope.token import OpenAITokenCounter+++async def main() -> None:+ """The main entry point of the MemoryWithCompress example."""++ toolkit = Toolkit()++ # Create model for agent and memory compression+ model = DashScopeChatModel(+ api_key=os.environ.get("DASHSCOPE_API_KEY"),+ model_name="qwen-max",+ stream=False,+ )++ async def trigger_compression(msgs: list[Msg]) -> bool:+ # Trigger compression if the number of messages in self._memory+ # exceeds 2 and the last message is from the assistant+ return len(msgs) > 2 and msgs[-1].role == "assistant"++ # Create MemoryWithCompress instance+ # max_token: maximum token count before compression+ memory_with_compress = MemoryWithCompress(+ model=model,+ formatter=DashScopeChatFormatter(),+ max_token=3000, # Set a lower value for testing compression+ token_counter=OpenAITokenCounter(model_name="qwen-max"),+ compression_trigger_func=trigger_compression, # Trigger compression+ # if the number of messages in self._memory exceeds 2+ )++ agent = ReActAgent(+ name="Friday",+ sys_prompt="You are a helpful assistant named Friday.",+ model=model,+ formatter=DashScopeChatFormatter(),+ toolkit=toolkit,+ memory=memory_with_compress,+ )++ query_1 = Msg(+ "user",+ "Please introduce Einstein",+ "user",+ )+ await agent(query_1)+ current_memory = await memory_with_compress.get_memory()+ print(+ f"\n\n\n******************The memory after the first query is: "+ f"******************\n{current_memory}\n\n******************",+ )++ query_2 = Msg(+ "user",+ "What is his most renowned achievement?",+ "user",+ )+ await agent(query_2)+ current_memory = await memory_with_compress.get_memory()+ print(+ f"\n\n\n******************The memory after the second query is: "+ f"******************\n{current_memory}\n\n******************",+ )++ print("The state dictionary of the memory with compression:")++ state_dict = memory_with_compress.state_dict()+ print(state_dict.model_dump_json(indent=4))++ memory_with_compress.load_state_dict(state_dict)+++asyncio.run(main())