Skip to content

Build and run agents you can see, understand and trust.

feat(memory): support database memory and memory compression (#1081)

DavdGao7e493404d817
diff --git a/README.md b/README.md
index 1819bec28..4067a7aff 100644
--- a/README.md
+++ b/README.md
@@ -54,6 +54,7 @@
</p>
## 📢 News
+- **[2026-01]** AgentScope integrates [database support](https://doc.agentscope.io/tutorial/task_memory.html) in the memory module now, as well as the [memory compression](https://doc.agentscope.io/tutorial/task_agent.html) feature. Check our [example](https://github.com/agentscope-ai/agentscope/tree/main/examples/functionality/short_term_memory/memory_compression) and [tutorial](https://doc.agentscope.io/tutorial/task_memory.html) for more details.
- **[2025-12]** AgentScope supports [A2A(Agent-to-Agent) protocol](https://doc.agentscope.io/tutorial/task_a2a.html) now! Check our [example](https://github.com/agentscope-ai/agentscope/tree/main/examples/agent/a2a_agent) and [tutorial](https://doc.agentscope.io/tutorial/task_a2a.html) for more details.
- **[2025-12]** AgentScope supports [TTS(Text-to-Speech)](https://doc.agentscope.io/tutorial/task_tts.html) now! Check our [example](https://github.com/agentscope-ai/agentscope/tree/main/examples/functionality/tts) and [tutorial](https://doc.agentscope.io/tutorial/task_tts.html) for more details.
- **[2025-11]** AgentScope supports [Anthropic Agent Skill](https://claude.com/blog/skills) now! Check our [example](https://github.com/agentscope-ai/agentscope/tree/main/examples/functionality/agent_skill) and [tutorial](https://doc.agentscope.io/tutorial/task_agent_skill.html) for more details.
@@ -394,6 +395,7 @@ as_studio
- [Stream Printing Messages](https://github.com/agentscope-ai/agentscope/tree/main/examples/functionality/stream_printing_messages)
- [TTS](https://github.com/agentscope-ai/agentscope/tree/main/examples/functionality/tts)
- [High-code Deployment](https://github.com/agentscope-ai/agentscope/tree/main/examples/deployment/planning_agent)
+ - [Memory Compression](https://github.com/agentscope-ai/agentscope/tree/main/examples/functionality/short_term_memory/memory_compression)
- Agent
- [ReAct Agent](https://github.com/agentscope-ai/agentscope/tree/main/examples/agent/react_agent)
- [Voice Agent](https://github.com/agentscope-ai/agentscope/tree/main/examples/agent/voice_agent)
diff --git a/README_zh.md b/README_zh.md
index 4bd721a2e..c3f8d1f6b 100644
--- a/README_zh.md
+++ b/README_zh.md
@@ -54,6 +54,7 @@
</p>
## 📢 新闻
+- **[2026-01]** AgentScope 已集成[数据库支持](https://doc.agentscope.io/zh_CN/tutorial/task_memory.html) 到记忆模块中,并新增[记忆压缩](https://doc.agentscope.io/zh_CN/tutorial/task_agent.html)功能。欢迎查看我们的[样例](https://github.com/agentscope-ai/agentscope/tree/main/examples/functionality/short_term_memory/memory_compression)和[文档](https://doc.agentscope.io/tutorial/task_memory.html)。
- **[2025-12]** AgentScope 已支持 [A2A(Agent-to-Agent) 通信协议](https://doc.agentscope.io/tutorial/task_a2a.html)!查看 [样例](https://github.com/agentscope-ai/agentscope/tree/main/examples/agent/a2a_agent) 和 [教程](https://doc.agentscope.io/zh_CN/tutorial/task_a2a.html) 了解更多详情。
- **[2025-12]** AgentScope 已支持 [TTS(Text-to-Speech) 模型](https://doc.agentscope.io/zh_CN/tutorial/task_tts.html) !欢迎查看 [样例]() 和 [教程](https://doc.agentscope.io/zh_CN/tutorial/task_tts.html) 了解更多详情。
- **[2025-11]** AgentScope 已支持 [Anthropic Agent Skill](https://claude.com/blog/skills) !欢迎查看 [样例](https://github.com/agentscope-ai/agentscope/tree/main/examples/functionality/agent_skill) 和 [教程](https://doc.agentscope.io/zh_CN/tutorial/task_agent_skill.html) 了解更多详情。
@@ -395,6 +396,7 @@ as_studio
- [流式获取打印消息](https://github.com/agentscope-ai/agentscope/tree/main/examples/functionality/stream_printing_messages)
- [TTS](https://github.com/agentscope-ai/agentscope/tree/main/examples/functionality/tts)
- [高代码部署](https://github.com/agentscope-ai/agentscope/tree/main/examples/deployment/planning_agent)
+ - [记忆压缩](https://github.com/agentscope-ai/agentscope/tree/main/examples/functionality/short_term_memory/memory_compression)
- 智能体
- [ReAct 智能体](https://github.com/agentscope-ai/agentscope/tree/main/examples/agent/react_agent)
- [语音智能体](https://github.com/agentscope-ai/agentscope/tree/main/examples/agent/voice_agent)
diff --git a/docs/tutorial/en/src/task_agent.py b/docs/tutorial/en/src/task_agent.py
index 4a63baa41..3cd18b8b6 100644
--- a/docs/tutorial/en/src/task_agent.py
+++ b/docs/tutorial/en/src/task_agent.py
@@ -20,6 +20,8 @@ In AgentScope, the ``ReActAgent`` class integrates various features into a final
- Reference
* - Support realtime steering
-
+ * - Support memory compression
+ -
* - Support parallel tool calls
-
* - Support structured output
@@ -114,6 +116,124 @@ from agentscope.tool import Toolkit, ToolResponse
# to generate a simple response to the interruption.
#
#
+# Memory Compression
+# ----------------------------------------
+# As conversations grow longer, the token count in memory can exceed model context
+# limits or slow down inference. ``ReActAgent`` provides an automatic memory compression
+# feature to address this issue.
+#
+# **Basic Usage**
+#
+# To enable memory compression, provide a ``CompressionConfig`` instance when initializing
+# the ``ReActAgent``:
+#
+# .. code-block:: python
+#
+# from agentscope.agent import ReActAgent
+# from agentscope.token import CharTokenCounter
+#
+# agent = ReActAgent(
+# name="Assistant",
+# sys_prompt="You are a helpful assistant.",
+# model=model,
+# formatter=formatter,
+# compression_config=ReActAgent.CompressionConfig(
+# enable=True,
+# agent_token_counter=CharTokenCounter(), # The token counter for the agent
+# trigger_threshold=10000, # Trigger compression when exceeding 10000 tokens
+# keep_recent=3, # Keep the most recent 3 messages uncompressed
+# ),
+# )
+#
+# When memory compression is enabled, the agent monitors the token count in its memory.
+# Once it exceeds the ``trigger_threshold``, the agent automatically:
+#
+# 1. Identifies messages that haven't been compressed yet (via ``exclude_mark``)
+# 2. Keeps the most recent ``keep_recent`` messages uncompressed (to preserve recent context)
+# 3. Sends older messages to an LLM to generate a structured summary
+# 4. Marks the compressed messages with ``MemoryMark.COMPRESSED`` (via ``update_messages_mark``)
+# 5. Stores the summary in memory (via ``update_compressed_summary``)
+#
+# .. important:: The compression uses a **marking mechanism** rather than replacing messages. Old messages are marked as compressed and excluded from future retrievals via ``exclude_mark=MemoryMark.COMPRESSED``, while the generated summary is stored separately and retrieved when needed. This approach preserves the original messages and allows flexible memory management. For more details about the mark functionality, please refer to :ref:`memory`.
+#
+# By default, the compressed summary is structured into five key fields:
+#
+# - **task_overview**: The user's core request and success criteria
+# - **current_state**: What has been completed so far, including files and outputs
+# - **important_discoveries**: Technical constraints, decisions, errors, and failed approaches
+# - **next_steps**: Specific actions needed to complete the task
+# - **context_to_preserve**: User preferences, domain details, and promises made
+#
+# **Customizing Compression**
+#
+# You can customize how compression works by specifying ``summary_schema``,
+# ``summary_template``, and ``compression_prompt`` parameters.
+#
+# - **compression_prompt**: Guides the LLM on how to generate the summary
+# - **summary_schema**: Defines the structure of the compressed summary using a Pydantic model
+# - **summary_template**: Formats how the compressed summary is presented back to the agent
+#
+# Here's an example of customizing the compression:
+#
+# .. code-block:: python
+#
+# from pydantic import BaseModel, Field
+#
+# # Define a custom summary structure
+# class CustomSummary(BaseModel):
+# main_topic: str = Field(
+# max_length=200,
+# description="The main topic of the conversation"
+# )
+# key_points: str = Field(
+# max_length=400,
+# description="Important points discussed"
+# )
+# pending_tasks: str = Field(
+# max_length=200,
+# description="Tasks that remain to be done"
+# )
+#
+# # Create agent with custom compression configuration
+# agent = ReActAgent(
+# name="Assistant",
+# sys_prompt="You are a helpful assistant.",
+# model=model,
+# formatter=formatter,
+# compression_config=ReActAgent.CompressionConfig(
+# enable=True,
+# agent_token_counter=CharTokenCounter(),
+# trigger_threshold=10000,
+# keep_recent=3,
+# # Custom schema for structured summary
+# summary_schema=CustomSummary,
+# # Custom prompt to guide compression
+# compression_prompt=(
+# "<system-hint>Please summarize the above conversation "
+# "focusing on the main topic, key discussion points, "
+# "and any pending tasks.</system-hint>"
+# ),
+# # Custom template to format the summary
+# summary_template=(
+# "<system-info>Conversation Summary:\n"
+# "Main Topic: {main_topic}\n\n"
+# "Key Points:\n{key_points}\n\n"
+# "Pending Tasks:\n{pending_tasks}"
+# "</system-info>"
+# ),
+# ),
+# )
+#
+# The ``summary_template`` uses the fields defined in ``summary_schema`` as placeholders
+# (e.g., ``{main_topic}``, ``{key_points}``). After the LLM generates the structured summary,
+# these placeholders will be replaced with the actual values.
+#
+# .. note:: The agent ensures that tool use and tool result pairs are kept together during compression to maintain the integrity of the conversation flow.
+#
+# .. tip:: You can use a smaller, faster model for compression by specifying a different ``compression_model`` and ``compression_formatter`` to reduce costs and latency.
+#
+#
+#
# Parallel Tool Calls
# ----------------------------------------
# ``ReActAgent`` supports parallel tool calls by providing a ``parallel_tool_calls``
diff --git a/docs/tutorial/en/src/task_memory.py b/docs/tutorial/en/src/task_memory.py
index 8585d0bb9..8b9aedb37 100644
--- a/docs/tutorial/en/src/task_memory.py
+++ b/docs/tutorial/en/src/task_memory.py
@@ -5,36 +5,442 @@
Memory
========================
-In AgentScope, the memory is used to store the context of the agent, and retrieve it when needed.
-Specifically, AgentScope provides a memory base class ``MemoryBase`` and an in-memory implementation ``InMemoryMemory`` under ``agentscope.memory`` that can be used directly.
+The memory module in AgentScope is responsible for
-Customize Memory
-~~~~~~~~~~~~~~~~~~~~~~~~
+- storing the messages and
+- managing them with specific marks
+in different storage implementations.
-To customize your own memory, just inherit from ``MemoryBase`` and implement the following methods:
+The **mark** is a string label associated with each message in the memory,
+which can be used to categorize, filter, and retrieve messages based on their
+context or purpose.
-.. list-table::
+It's powerful for high-level memory management in agents. For example,
+In `ReActAgent` class, the hint messages are stored with the
+mark "hint", and the memory compression functionality is also implemented
+based on marks.
+
+.. note:: The memory module only provides storage and management
+ functionalities. The algorithm logic such as compression is implemented in
+ the agent level.
+
+Currently, AgentScope provides the following memory storage implementations:
+
+.. list-table:: The built-in memory storage implementations in AgentScope
+ :header-rows: 1
+
+ * - Memory Class
+ - Description
+ * - ``InMemoryMemory``
+ - A simple in-memory implementation of memory storage.
+ * - ``AsyncSQLAlchemyMemory``
+ - An asynchronous SQLAlchemy-based implementation of memory storage, which supports various databases such as SQLite, PostgreSQL, MySQL, etc.
+ * - ``RedisMemory``
+ - A Redis-based implementation of memory storage.
+
+.. tip:: If you're interested in contributing new memory storage implementations, please refer to the
+ `Contribution Guide <https://github.com/agentscope-ai/agentscope/blob/main/CONTRIBUTING.md#types-of-contributions>`_.
+
+All the above memory classes inherit from the base class ``MemoryBase``, and
+provide the following methods to manage the messages in the memory:
+
+.. list-table:: The methods provided by the memory classes
:header-rows: 1
* - Method
- Description
- * - ``add``
- - Add ``Msg`` objects to the memory
- * - ``delete``
- - Delete items from the memory
- * - ``size``
- - The size of the memory
- * - ``clear``
- - Clear the memory content
- * - ``get_memory``
- - Get the memory content as a list of ``Msg`` objects
- * - ``state_dict``
- - Get the state dictionary of the memory
- * - ``load_state_dict``
- - Load the state dictionary of the memory
-
-Further Reading
-~~~~~~~~~~~~~~~~~~~~~~~~
-
-- :ref:`long-term-memory`
+ * - ``add(
+ memories: Msg | list[Msg] | None,
+ marks: str | list[str] | None = None,
+ ) -> None``
+ - Add ``Msg`` object(s) to the memory storage with the given mark(s) (if provided).
+ * - ``delete(msg_ids: list[str]) -> int``
+ - Delete messages from the memory storage by their IDs.
+ * - ``delete_by_mark(mark: str | list[str]) -> int``
+ - Delete messages from the memory by their marks.
+ * - ``size() -> int``
+ - Get the size of the memory storage.
+ * - ``clear() -> None``
+ - Clear the memory storage.
+ * - ``get_memory(
+ mark: str | None = None,
+ exclude_mark: str | None = None,
+ ) -> list[Msg]``
+ - Get the messages from the memory by mark (if provided). Otherwise, get all messages. If the ``update_compressed_summary`` method is used to store a compressed summary, it will be attached to the head of the returned messages.
+ * - ``update_messages_mark(
+ new_mark: str | None,
+ old_mark: str | None = None,
+ msg_ids: list[str] | None = None,
+ ) -> int``
+ - A unified method to update marks of messages in the storage (add, remove, or change marks).
+ * - ``update_compressed_summary(
+ summary: str,
+ ) -> None``
+ - Update the summary attribute stored in the memory.
"""
+import asyncio
+import json
+
+import fakeredis
+from sqlalchemy.ext.asyncio import create_async_engine
+
+from agentscope.memory import (
+ InMemoryMemory,
+ AsyncSQLAlchemyMemory,
+ RedisMemory,
+)
+from agentscope.message import Msg
+
+
+# %%
+# In-Memory Memory
+# ~~~~~~~~~~~~~~~~~~~~~~~~
+#
+# The in-memory memory provides a simple way to store messages in memory.
+# Together with the :ref:`state` module, it can persist the memory content across
+# different users and sessions.
+
+
+async def in_memory_example():
+ """An example of using InMemoryMemory to store messages in memory."""
+ memory = InMemoryMemory()
+ await memory.add(
+ Msg("Alice", "Generate a report about AgentScope", "user"),
+ )
+
+ # Add a hint message with the mark "hint"
+ await memory.add(
+ [
+ Msg(
+ "system",
+ "<system-hint>Create a plan first to collect information and "
+ "generate the report step by step.</system-hint>",
+ "system",
+ ),
+ ],
+ marks="hint",
+ )
+
+ msgs = await memory.get_memory(mark="hint")
+ print("The messages with mark 'hint':")
+ for msg in msgs:
+ print(f"- {msg}")
+
+ # All the stored messages can be exported and loaded via ``state_dict`` and ``load_state_dict`` methods.
+ state = memory.state_dict()
+ print("The state dict of the memory:")
+ print(json.dumps(state, indent=2))
+
+ # delete messages by mark
+ deleted_count = await memory.delete_by_mark("hint")
+ print(f"Deleted {deleted_count} messages with mark 'hint'.")
+
+ print("The state dict of the memory after deletion:")
+ state = memory.state_dict()
+ print(json.dumps(state, indent=2))
+
+
+asyncio.run(in_memory_example())
+
+# %%
+# Relational Database Memory
+# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+# AgentScope provides a unified interface to work with relational databases via SQLAlchemy, supporting
+#
+# - various databases such as SQLite, PostgreSQL, MySQL, etc.
+# - user and session management, and
+# - connection pooling in the production environment
+#
+# Specifically, here we use a memory backed by SQLite as an example.
+
+
+async def sqlalchemy_example() -> None:
+ """An example of using AsyncSQLAlchemyMemory to store messages in a SQLite database."""
+
+ # Create an async SQLAlchemy engine first
+ engine = create_async_engine("sqlite+aiosqlite:///./test_memory.db")
+
+ # Then create the memory with the engine
+ memory = AsyncSQLAlchemyMemory(
+ engine_or_session=engine,
+ # Optionally specify user_id and session_id
+ user_id="user_1",
+ session_id="session_1",
+ )
+
+ await memory.add(
+ Msg("Alice", "Generate a report about AgentScope", "user"),
+ )
+
+ await memory.add(
+ [
+ Msg(
+ "system",
+ "<system-hint>Create a plan first to collect information and "
+ "generate the report step by step.</system-hint>",
+ "system",
+ ),
+ ],
+ marks="hint",
+ )
+
+ msgs = await memory.get_memory(mark="hint")
+ print("The messages with mark 'hint':")
+ for msg in msgs:
+ print(f"- {msg}")
+
+ # Close the engine when done
+ await memory.close()
+
+
+asyncio.run(sqlalchemy_example())
+
+# %%
+# Optionally, you can also use the ``AsyncSQLAlchemyMemory`` as an async context manager, and the session will be closed automatically when exiting the context.
+
+
+async def sqlalchemy_context_example() -> None:
+ """Example of using AsyncSQLAlchemyMemory as an async context manager."""
+ engine = create_async_engine("sqlite+aiosqlite:///./test_memory.db")
+ async with AsyncSQLAlchemyMemory(
+ engine_or_session=engine,
+ user_id="user_1",
+ session_id="session_1",
+ ) as memory:
+ await memory.add(
+ Msg("Alice", "Generate a report about AgentScope", "user"),
+ )
+
+ msgs = await memory.get_memory()
+ print("All messages in the memory:")
+ for msg in msgs:
+ print(f"- {msg}")
+
+
+asyncio.run(sqlalchemy_context_example())
+
+# %%
+# In production environment e.g. with FastAPI, the connection pooling can be enabled as follows:
+#
+# .. code-block:: python
+# :caption: SQLAlchemy Memory with Connection Pooling in FastAPI
+#
+# from typing import AsyncGenerator
+#
+# from fastapi import FastAPI, Depends
+# from sqlalchemy.ext.asyncio import create_async_engine, async_sessionmaker, AsyncSession
+#
+# from agentscope.agent import ReActAgent
+# from agentscope.pipeline import stream_printing_messages
+#
+#
+# app = FastAPI()
+#
+# # Create an async SQLAlchemy engine with connection pooling
+# engine = create_async_engine(
+# "sqlite+aiosqlite:///./test_memory.db",
+# pool_size=10,
+# max_overflow=20,
+# pool_timeout=30,
+# # ... The other pool settings
+# )
+#
+# # Create a session maker
+# async_session_marker = async_sessionmaker(
+# engine,
+# expire_on_commit=False,
+# autocommit=False,
+# autoflush=False,
+# )
+#
+# async def get_db() -> AsyncGenerator[AsyncSession, None]:
+# async with async_session_marker() as session:
+# try:
+# yield session
+# await session.commit()
+# except Exception:
+# await session.rollback()
+# raise
+# finally:
+# await session.close()
+#
+# @app.post("/chat")
+# async def chat_endpoint(
+# user_id: str,
+# session_id: str,
+# input: str,
+# db_session: AsyncSession = Depends(get_db),
+# ):
+# # Some setup for the agent
+# ...
+#
+# # Create the agent with the SQLAlchemy memory
+# agent = ReActAgent(
+# # ...
+# memory=AsyncSQLAlchemyMemory(
+# engine_or_session=db_session,
+# user_id=user_id,
+# session_id=session_id,
+# ),
+# )
+#
+# # Handle the chat with the agent
+# async for msg, _ in stream_printing_messages(
+# agents=[agent],
+# coroutine_task=agent(Msg("user", input, "user")),
+# ):
+# # yield msg to the client
+# ...
+#
+#
+# NoSQL Database Memory
+# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+# AgentScope also provides memory implementations based on NoSQL databases such as Redis.
+# It also supports user and session management, and connection pooling in the production environment.
+#
+# First, we can initialize the Redis memory as follows:
+
+
+async def redis_memory_example() -> None:
+ """An example of using RedisMemory to store messages in Redis."""
+ # Use fakeredis for in-memory testing without a real Redis server
+ fake_redis = fakeredis.aioredis.FakeRedis(decode_responses=True)
+ # Create the Redis memory
+ memory = RedisMemory(
+ # Using fake redis for demonstration
+ connection_pool=fake_redis.connection_pool,
+ # You can also connect to a real Redis server by specifying host and port
+ # host="localhost",
+ # port=6379,
+ # Optionally specify user_id and session_id
+ user_id="user_1",
+ session_id="session_1",
+ )
+
+ # Add a message to the memory
+ await memory.add(
+ Msg(
+ "Alice",
+ "Generate a report about AgentScope",
+ "user",
+ ),
+ )
+
+ # Add a hint message with the mark "hint"
+ await memory.add(
+ Msg(
+ "system",
+ "<system-hint>Create a plan first to collect information and "
+ "generate the report step by step.</system-hint>",
+ "system",
+ ),
+ marks="hint",
+ )
+
+ # Retrieve messages with the mark "hint"
+ msgs = await memory.get_memory(mark="hint")
+ print("The messages with mark 'hint':")
+ for msg in msgs:
+ print(f"- {msg}")
+
+
+asyncio.run(redis_memory_example())
+
+# %%
+# Similarly, the `RedisMemory` can also be used with connection pooling in the production environment, e.g., with FastAPI.
+#
+# .. code-block:: python
+# :caption: Redis Memory with Connection Pooling in FastAPI
+#
+# from fastapi import FastAPI, HTTPException
+# from redis.asyncio import ConnectionPool
+# from contextlib import asynccontextmanager
+#
+# # Global Redis connection pool
+# redis_pool: ConnectionPool | None = None
+#
+#
+# # Use the lifespan event to manage the Redis connection pool
+# @asynccontextmanager
+# async def lifespan(app: FastAPI):
+# global redis_pool
+# redis_pool = ConnectionPool(
+# host="localhost",
+# port=6379,
+# db=0,
+# password=None,
+# decode_responses=True,
+# max_connections=10,
+# encoding="utf-8",
+# )
+# print("✅ Redis connection established")
+#
+# yield
+#
+# await redis_pool.disconnect()
+# print("✅ Redis connection closed")
+#
+#
+# app = FastAPI(lifespan=lifespan)
+#
+#
+# @app.post("/chat_endpoint")
+# async def chat_endpoint(
+# user_id: str, session_id: str, input: str
+# ): # ✅ 直接使用BaseModel
+# """A chat endpoint"""
+# global redis_pool
+# if redis_pool is None:
+# raise HTTPException(
+# status_code=500,
+# detail="Redis connection pool is not initialized.",
+# )
+#
+# # Create the Redis memory
+# memory = RedisMemory(
+# connection_pool=redis_pool,
+# user_id=user_id,
+# session_id=session_id,
+# )
+#
+# ...
+#
+# # Close the Redis client connection when done
+# client = memory.get_client()
+# await client.aclose()
+#
+#
+#
+# Customizing Memory
+# ~~~~~~~~~~~~~~~~~~~~~~~~
+#
+# To customize your own memory, just inherit from ``MemoryBase`` and implement the following methods:
+#
+# .. list-table::
+# :header-rows: 1
+#
+# * - Method
+# - Description
+# * - ``add``
+# - Add ``Msg`` objects to the memory
+# * - ``delete``
+# - Delete ``Msg`` objects from the memory
+# * - ``delete_by_mark``
+# - Delete ``Msg`` objects from the memory by their marks
+# * - ``size``
+# - The size of the memory
+# * - ``clear``
+# - Clear the memory content
+# * - ``get_memory``
+# - Get the memory content as a list of ``Msg`` objects
+# * - ``update_messages_mark``
+# - Update marks of messages in the memory
+# * - ``state_dict``
+# - Get the state dictionary of the memory
+# * - ``load_state_dict``
+# - Load the state dictionary of the memory
+#
+# Further Reading
+# ~~~~~~~~~~~~~~~~~~~~~~~~
+# - :ref:`agent`
+# - :ref:`long-term-memory`
diff --git a/docs/tutorial/zh_CN/src/task_agent.py b/docs/tutorial/zh_CN/src/task_agent.py
index 19e0c7a0b..ad6041afa 100644
--- a/docs/tutorial/zh_CN/src/task_agent.py
+++ b/docs/tutorial/zh_CN/src/task_agent.py
@@ -19,6 +19,8 @@ ReAct 智能体
- 参考文档
* - 支持实时介入(Realtime Steering)
-
+ * - 支持记忆压缩
+ -
* - 支持并行工具调用
-
* - 支持结构化输出
@@ -105,6 +107,120 @@ from agentscope.tool import Toolkit, ToolResponse
# 开发者可以通过覆盖 ``handle_interrupt`` 函数实现自定义的中断后处理逻辑,例如,调用 LLM 生成对中断的简单响应。
#
#
+# 记忆压缩
+# ----------------------------------------
+# 随着对话的不断增长,记忆中的 token 数量可能会超过模型的上下文限制或导致推理速度变慢。
+# ``ReActAgent`` 提供了自动记忆压缩功能来解决这个问题。
+#
+# **基础用法**
+#
+# 要启用记忆压缩,在初始化 ``ReActAgent`` 时提供一个 ``CompressionConfig`` 实例:
+#
+# .. code-block:: python
+#
+# from agentscope.agent import ReActAgent
+# from agentscope.token import CharTokenCounter
+#
+# agent = ReActAgent(
+# name="助手",
+# sys_prompt="你是一个有用的助手。",
+# model=model,
+# formatter=formatter,
+# compression_config=ReActAgent.CompressionConfig(
+# enable=True,
+# agent_token_counter=CharTokenCounter(), # 智能体的 token 计数器
+# trigger_threshold=10000, # 超过 10000 个 token 时触发压缩
+# keep_recent=3, # 保持最近 3 条消息不被压缩
+# ),
+# )
+#
+# 启用记忆压缩后,智能体会监控其记忆中的 token 数量。
+# 一旦超过 ``trigger_threshold``,智能体会自动:
+#
+# 1. 识别尚未被压缩的消息(通过 ``exclude_mark``)
+# 2. 保持最近 ``keep_recent`` 条消息不被压缩(以保留最近的上下文)
+# 3. 将较早的消息发送给 LLM 生成结构化摘要
+# 4. 使用 ``MemoryMark.COMPRESSED`` 标记已压缩的消息(通过 ``update_messages_mark``)
+# 5. 将摘要存储在记忆中(通过 ``update_compressed_summary``)
+#
+# .. important:: 压缩采用**标记机制**而非替换消息。旧消息被标记为已压缩,并通过 ``exclude_mark=MemoryMark.COMPRESSED`` 在后续检索中被排除,而生成的摘要则单独存储,在需要时检索。这种方式保留了原始消息,允许灵活的记忆管理。关于标记功能的更多详情,请参考 :ref:`memory`。
+#
+# 默认情况下,压缩摘要被结构化为五个关键字段:
+#
+# - **task_overview**:用户的核心请求和成功标准
+# - **current_state**:到目前为止已完成的工作,包括文件和输出
+# - **important_discoveries**:技术约束、决策、错误和失败的尝试
+# - **next_steps**:完成任务所需的具体操作
+# - **context_to_preserve**:用户偏好、领域细节和做出的承诺
+#
+# **自定义压缩**
+#
+# 可以通过指定 ``summary_schema``、``summary_template`` 和 ``compression_prompt`` 参数来自定义压缩的工作方式。
+#
+# - **summary_schema**:使用 Pydantic 模型定义压缩摘要的结构
+# - **compression_prompt**:指导 LLM 如何生成摘要
+# - **summary_template**:格式化压缩摘要如何呈现给智能体
+#
+# 下面是一个自定义压缩的示例:
+#
+# .. code-block:: python
+#
+# from pydantic import BaseModel, Field
+#
+# # 定义自定义摘要结构
+# class CustomSummary(BaseModel):
+# main_topic: str = Field(
+# max_length=200,
+# description="对话的主题"
+# )
+# key_points: str = Field(
+# max_length=400,
+# description="讨论的重要观点"
+# )
+# pending_tasks: str = Field(
+# max_length=200,
+# description="待完成的任务"
+# )
+#
+# # 使用自定义压缩配置创建智能体
+# agent = ReActAgent(
+# name="助手",
+# sys_prompt="你是一个有用的助手。",
+# model=model,
+# formatter=formatter,
+# compression_config=ReActAgent.CompressionConfig(
+# enable=True,
+# agent_token_counter=CharTokenCounter(),
+# trigger_threshold=10000,
+# keep_recent=3,
+# # 结构化摘要的自定义 schema
+# summary_schema=CustomSummary,
+# # 指导压缩的自定义提示
+# compression_prompt=(
+# "<system-hint>请总结上述对话,"
+# "重点关注主题、关键讨论点和待完成任务。</system-hint>"
+# ),
+# # 格式化摘要的自定义模板
+# summary_template=(
+# "<system-info>对话摘要:\n"
+# "主题:{main_topic}\n\n"
+# "关键观点:\n{key_points}\n\n"
+# "待完成任务:\n{pending_tasks}"
+# "</system-info>"
+# ),
+# ),
+# )
+#
+# ``summary_template`` 使用 ``summary_schema`` 中定义的字段作为占位符
+# (例如 ``{main_topic}``、``{key_points}``)。在 LLM 生成结构化摘要后,
+# 这些占位符将被实际值替换。
+#
+# .. note:: 智能体确保工具使用和工具结果对在压缩过程中保持在一起,以维护对话流程的完整性。
+#
+# .. tip:: 可以通过指定不同的 ``compression_model`` 和 ``compression_formatter`` 来使用更小、更快的模型进行压缩,以降低成本和延迟。
+#
+#
+#
# 并行工具调用
# ----------------------------------------
# ``ReActAgent`` 通过在其构造函数中提供 ``parallel_tool_calls`` 参数来支持并行工具调用。
diff --git a/docs/tutorial/zh_CN/src/task_memory.py b/docs/tutorial/zh_CN/src/task_memory.py
index 80253530b..8e8924652 100644
--- a/docs/tutorial/zh_CN/src/task_memory.py
+++ b/docs/tutorial/zh_CN/src/task_memory.py
@@ -5,36 +5,429 @@
记忆
========================
-在 AgentScope 中,记忆(memory)用于存储智能体的上下文,并在需要时检索它。
-具体而言,AgentScope 在 ``agentscope.memory`` 模块下提供了记忆基类 ``MemoryBase`` 和一个可直接使用的基于内存实现 ``InMemoryMemory``。
+AgentScope 中的记忆模块负责:
-自定义记忆
-~~~~~~~~~~~~~~~~~~~~~~~~
+- 存储消息对象(``Msg``)
+- 利用标记(mark)管理消息
-要自定义您自己的记忆,只需继承 ``MemoryBase`` 并实现以下方法:
+**标记** 是与记忆中每条消息关联的字符串标签,可用于根据消息的上下文或目的对消息进行分类、过滤和检索。
+可用于实现进阶的记忆管理功能,例如在 `ReActAgent` 类中,使用``"hint"``标签标记一次性的提示消息,
+以便在使用完成后将其从记忆中删除。
-.. list-table::
+.. note:: AgentScope 中的记忆模块仅提供消息存储和管理的原子功能,记忆压缩等算法逻辑在 `智能体 <agent>`_ 中实现。
+
+目前,AgentScope 提供以下记忆存储实现:
+
+.. list-table:: AgentScope 中的内置记忆类
+ :header-rows: 1
+
+ * - 类
+ - 描述
+ * - ``InMemoryMemory``
+ - 简单的内存记忆存储实现。
+ * - ``AsyncSQLAlchemyMemory``
+ - 基于异步 SQLAlchemy 的记忆存储实现,支持如 SQLite、PostgreSQL、MySQL 等多种关系数据库。
+ * - ``RedisMemory``
+ - 基于 Redis 的记忆存储实现。
+
+.. tip:: 如果您有兴趣贡献新的记忆存储实现,请参考 `贡献指南 <https://github.com/agentscope-ai/agentscope/blob/main/CONTRIBUTING.md#types-of-contributions>`_。
+
+以上所有记忆类均继承自基类 ``MemoryBase``,并提供以下方法来管理记忆中的消息:
+
+.. list-table:: 记忆类提供的方法
:header-rows: 1
* - 方法
- 描述
- * - ``add``
- - 向记忆中添加 ``Msg`` 对象
- * - ``delete``
- - 从记忆中删除项目
- * - ``size``
- - 记忆的大小
- * - ``clear``
- - 清空记忆内容
- * - ``get_memory``
- - 以 ``Msg`` 对象列表的形式获取记忆内容
- * - ``state_dict``
- - 获取记忆的状态字典
- * - ``load_state_dict``
- - 加载记忆的状态字典
-
-进一步阅读
-~~~~~~~~~~~~~~~~~~~~~~~~
-
-- :ref:`long-term-memory`
+ * - ``add(
+ memories: Msg | list[Msg] | None,
+ marks: str | list[str] | None = None,
+ ) -> None``
+ - 将 ``Msg`` 对象添加到记忆存储中,并使用给定的标记(如果提供)。
+ * - ``delete(msg_ids: list[str]) -> int``
+ - 通过ID从记忆存储中删除消息。
+ * - ``delete_by_mark(mark: str | list[str]) -> int``
+ - 通过标记从记忆中删除消息。
+ * - ``size() -> int``
+ - 获取记忆存储的大小。
+ * - ``clear() -> None``
+ - 清空记忆存储。
+ * - ``get_memory(
+ mark: str | None = None,
+ exclude_mark: str | None = None,
+ ) -> list[Msg]``
+ - 通过标记从记忆中获取消息(如果提供)。否则,获取所有消息。如果使用 ``update_compressed_summary`` 方法存储压缩摘要,它将附加到返回消息的头部。
+ * - ``update_messages_mark(
+ new_mark: str | None,
+ old_mark: str | None = None,
+ msg_ids: list[str] | None = None,
+ ) -> int``
+ - 统一的方法,用于更新存储中消息的标记(添加、删除或更改标记)。
+ * - ``update_compressed_summary(
+ summary: str,
+ ) -> None``
+ - 更新存储在记忆中的摘要属性。
"""
+import asyncio
+import json
+
+import fakeredis
+from sqlalchemy.ext.asyncio import create_async_engine
+
+from agentscope.memory import (
+ InMemoryMemory,
+ AsyncSQLAlchemyMemory,
+ RedisMemory,
+)
+from agentscope.message import Msg
+
+
+# %%
+# 内存记忆
+# ~~~~~~~~~~~~~~~~~~~~~~~~
+#
+# 内存记忆提供了一种在内存中存储消息的简单方式。
+# 结合 :ref:`state` 模块,它可以在不同用户和会话之间持久化记忆内容。
+#
+
+
+async def in_memory_example():
+ """使用InMemoryMemory在内存中存储消息的示例。"""
+ memory = InMemoryMemory()
+ await memory.add(
+ Msg("Alice", "生成一份关于AgentScope的报告", "user"),
+ )
+
+ # 添加一条带有标记"hint"的提示消息
+ await memory.add(
+ [
+ Msg(
+ "system",
+ "<system-hint>首先创建一个计划来收集信息,然后逐步生成报告。</system-hint>",
+ "system",
+ ),
+ ],
+ marks="hint",
+ )
+
+ msgs = await memory.get_memory(mark="hint")
+ print("带有标记'hint'的消息:")
+ for msg in msgs:
+ print(f"- {msg}")
+
+ # 所有存储的消息都可以通过 ``state_dict`` 和 ``load_state_dict`` 方法导出和加载。
+ state = memory.state_dict()
+ print("记忆的状态字典:")
+ print(json.dumps(state, indent=2, ensure_ascii=False))
+
+ # 通过标记删除消息
+ deleted_count = await memory.delete_by_mark("hint")
+ print(f"删除了 {deleted_count} 条带有标记'hint'的消息。")
+
+ print("删除后的记忆状态字典:")
+ state = memory.state_dict()
+ print(json.dumps(state, indent=2, ensure_ascii=False))
+
+
+asyncio.run(in_memory_example())
+
+# %%
+# 关系数据库记忆(Relational Database Memory)
+# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+# AgentScope 通过 SQLAlchemy 提供统一的接口来使用关系数据库,支持:
+#
+# - 多种数据库,如 SQLite、PostgreSQL、MySQL 等
+# - 用户和会话管理
+# - 生产环境中的连接池
+#
+# 具体来说,这里我们以SQLite支持的记忆为例。
+
+
+async def sqlalchemy_example() -> None:
+ """使用 AsyncSQLAlchemyMemory 在 SQLite 数据库中存储消息的示例。"""
+
+ # 首先创建一个异步 SQLAlchemy 引擎
+ engine = create_async_engine("sqlite+aiosqlite:///./test_memory.db")
+
+ # 然后使用该引擎创建记忆
+ memory = AsyncSQLAlchemyMemory(
+ engine_or_session=engine,
+ # 可选传入指定user_id和session_id
+ user_id="user_1",
+ session_id="session_1",
+ )
+
+ await memory.add(
+ Msg("Alice", "生成一份关于AgentScope的报告", "user"),
+ )
+
+ await memory.add(
+ [
+ Msg(
+ "system",
+ "<system-hint>首先创建一个计划来收集信息,然后逐步生成报告。</system-hint>",
+ "system",
+ ),
+ ],
+ marks="hint",
+ )
+
+ msgs = await memory.get_memory(mark="hint")
+ print("带有标记'hint'的消息:")
+ for msg in msgs:
+ print(f"- {msg}")
+
+ # 完成后关闭引擎
+ await memory.close()
+
+
+asyncio.run(sqlalchemy_example())
+
+# %%
+# 可选地,您也可以将 ``AsyncSQLAlchemyMemory`` 用作���步上下文管理器,退出上下文时会话将自动关闭。
+
+
+async def sqlalchemy_context_example() -> None:
+ """使用 AsyncSQLAlchemyMemory 作为异步上下文管理器的示例。"""
+ engine = create_async_engine("sqlite+aiosqlite:///./test_memory.db")
+ async with AsyncSQLAlchemyMemory(
+ engine_or_session=engine,
+ user_id="user_1",
+ session_id="session_1",
+ ) as memory:
+ await memory.add(
+ Msg("Alice", "生成一份关于 AgentScope 的报告", "user"),
+ )
+
+ msgs = await memory.get_memory()
+ print("记忆中的所有消息:")
+ for msg in msgs:
+ print(f"- {msg}")
+
+
+asyncio.run(sqlalchemy_context_example())
+
+# %%
+# 在生产环境中,例如使用FastAPI时,可以按如下方式启用连接池:
+#
+# .. code-block:: python
+# :caption: FastAPI中使用连接池的SQLAlchemy记忆
+#
+# from typing import AsyncGenerator
+#
+# from fastapi import FastAPI, Depends
+# from sqlalchemy.ext.asyncio import create_async_engine, async_sessionmaker, AsyncSession
+#
+# from agentscope.agent import ReActAgent
+# from agentscope.pipeline import stream_printing_messages
+#
+#
+# app = FastAPI()
+#
+# # 创建带连接池的异步SQLAlchemy引擎
+# engine = create_async_engine(
+# "sqlite+aiosqlite:///./test_memory.db",
+# pool_size=10,
+# max_overflow=20,
+# pool_timeout=30,
+# # ... 其他连接池设置
+# )
+#
+# # 创建会话制造器
+# async_session_marker = async_sessionmaker(
+# engine,
+# expire_on_commit=False,
+# autocommit=False,
+# autoflush=False,
+# )
+#
+# async def get_db() -> AsyncGenerator[AsyncSession, None]:
+# async with async_session_marker() as session:
+# try:
+# yield session
+# await session.commit()
+# except Exception:
+# await session.rollback()
+# raise
+# finally:
+# await session.close()
+#
+# @app.post("/chat")
+# async def chat_endpoint(
+# user_id: str,
+# session_id: str,
+# input: str,
+# db_session: AsyncSession = Depends(get_db),
+# ):
+# # 智能体的一些设置
+# ...
+#
+# # 使用SQLAlchemy记忆创建智能体
+# agent = ReActAgent(
+# # ...
+# memory=AsyncSQLAlchemyMemory(
+# engine_or_session=db_session,
+# user_id=user_id,
+# session_id=session_id,
+# ),
+# )
+#
+# # 处理与智能体的对话
+# async for msg, _ in stream_printing_messages(
+# agents=[agent],
+# coroutine_task=agent(Msg("user", input, "user")),
+# ):
+# # 将消息返回给客户端
+# ...
+#
+#
+# NoSQL数据库记忆(NoSQL Database Memory)
+# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+# AgentScope还提供基于NoSQL数据库(如Redis)的记忆实现。
+# 它也支持用户和会话管理,以及生产环境中的连接池。
+#
+# 首先,我们可以按如下方式初始化Redis记忆:
+
+
+async def redis_memory_example() -> None:
+ """使用 RedisMemory 在 Redis 中存储消息的示例。"""
+ # 使用fakeredis进行内存测试,无需真实的 Redis 服务器
+ fake_redis = fakeredis.aioredis.FakeRedis(decode_responses=True)
+ # 创建 Redis 记忆
+ memory = RedisMemory(
+ # 使用fake redis进行演示
+ connection_pool=fake_redis.connection_pool,
+ # 也可以通过指定主机和端口连接到真实的Redis服务器
+ # host="localhost",
+ # port=6379,
+ # 可选地指定 user_id 和 session_id
+ user_id="user_1",
+ session_id="session_1",
+ )
+
+ # 向记忆中添加消息
+ await memory.add(
+ Msg(
+ "Alice",
+ "生成一份关于AgentScope的报告",
+ "user",
+ ),
+ )
+
+ # 添加一条带有标记"hint"的提示消息
+ await memory.add(
+ Msg(
+ "system",
+ "<system-hint>首先创建一个计划来收集信息,然后逐步生成报告。</system-hint>",
+ "system",
+ ),
+ marks="hint",
+ )
+
+ # 检索带有标记"hint"的消息
+ msgs = await memory.get_memory(mark="hint")
+ print("带有标记'hint'的消息:")
+ for msg in msgs:
+ print(f"- {msg}")
+
+
+asyncio.run(redis_memory_example())
+
+# %%
+# 同样,`RedisMemory` 也可以在生产环境中使用连接池,例如与FastAPI一起使用。
+#
+# .. code-block:: python
+# :caption: FastAPI中使用连接池的Redis记忆
+#
+# from fastapi import FastAPI, HTTPException
+# from redis.asyncio import ConnectionPool
+# from contextlib import asynccontextmanager
+#
+# # 全局Redis连接池
+# redis_pool: ConnectionPool | None = None
+#
+#
+# # 使用lifespan事件管理Redis连接池
+# @asynccontextmanager
+# async def lifespan(app: FastAPI):
+# global redis_pool
+# redis_pool = ConnectionPool(
+# host="localhost",
+# port=6379,
+# db=0,
+# password=None,
+# decode_responses=True,
+# max_connections=10,
+# encoding="utf-8",
+# )
+# print("✅ Redis连接已建立")
+#
+# yield
+#
+# await redis_pool.disconnect()
+# print("✅ Redis连接已关闭")
+#
+#
+# app = FastAPI(lifespan=lifespan)
+#
+#
+# @app.post("/chat_endpoint")
+# async def chat_endpoint(
+# user_id: str, session_id: str, input: str
+# ):
+# """聊天端点"""
+# global redis_pool
+# if redis_pool is None:
+# raise HTTPException(
+# status_code=500,
+# detail="Redis连接池未初始化。",
+# )
+#
+# # 创建Redis记忆
+# memory = RedisMemory(
+# connection_pool=redis_pool,
+# user_id=user_id,
+# session_id=session_id,
+# )
+#
+# ...
+#
+# # 完成后关闭Redis客户端连接
+# client = memory.get_client()
+# await client.aclose()
+#
+#
+#
+# 自定义记忆(Customizing Memory)
+# ~~~~~~~~~~~~~~~~~~~~~~~~
+#
+# 要自定义您自己的记忆实现,只需从 ``MemoryBase`` 继承并实现以下方法:
+#
+# .. list-table::
+# :header-rows: 1
+#
+# * - 方法
+# - 描述
+# * - ``add``
+# - 向记忆中添加 ``Msg`` 对象
+# * - ``delete``
+# - 从记忆中删除 ``Msg`` 对象
+# * - ``delete_by_mark``
+# - 通过标记从记忆中删除 ``Msg`` 对象
+# * - ``size``
+# - 记忆的大小
+# * - ``clear``
+# - 清空记忆内容
+# * - ``get_memory``
+# - 以 ``Msg`` 对象列表的形式获取记忆内容
+# * - ``update_messages_mark``
+# - 更新记忆中消息的标记
+# * - ``state_dict``
+# - 获取记忆的状态字典
+# * - ``load_state_dict``
+# - 加载记忆的状态字典
+#
+# 延伸阅读
+# ~~~~~~~~~~~~~~~~~~~~~~~~
+# - :ref:`agent`
+# - :ref:`long-term-memory`
diff --git a/examples/functionality/memory/memory_with_compression/_mc_utils.py b/examples/functionality/memory/memory_with_compression/_mc_utils.py
deleted file mode 100644
index 1f3bd13f4..000000000
--- a/examples/functionality/memory/memory_with_compression/_mc_utils.py
+++ /dev/null
@@ -1,141 +0,0 @@
-# -*- 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/functionality/memory/memory_with_compression/_memory_storage.py b/examples/functionality/memory/memory_with_compression/_memory_storage.py
deleted file mode 100644
index f604ea0fe..000000000
--- a/examples/functionality/memory/memory_with_compression/_memory_storage.py
+++ /dev/null
@@ -1,273 +0,0 @@
-# -*- 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 False
diff --git a/examples/functionality/memory/memory_with_compression/_memory_with_compress.py b/examples/functionality/memory/memory_with_compression/_memory_with_compress.py
deleted file mode 100644
index d2c8e27fe..000000000
--- a/examples/functionality/memory/memory_with_compression/_memory_with_compress.py
+++ /dev/null
@@ -1,713 +0,0 @@
-# -*- 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/functionality/memory/memory_with_compression/main.py b/examples/functionality/memory/memory_with_compression/main.py
deleted file mode 100644
index 37b012d95..000000000
--- a/examples/functionality/memory/memory_with_compression/main.py
+++ /dev/null
@@ -1,83 +0,0 @@
-# -*- 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())
diff --git a/examples/functionality/memory/memory_with_compression/README.md b/examples/functionality/short_term_memory/memory_compression/README.md
similarity index 100%
rename from examples/functionality/memory/memory_with_compression/README.md
rename to examples/functionality/short_term_memory/memory_compression/README.md
diff --git a/examples/functionality/short_term_memory/memory_compression/main.py b/examples/functionality/short_term_memory/memory_compression/main.py
new file mode 100644
index 000000000..c6797d342
--- /dev/null
+++ b/examples/functionality/short_term_memory/memory_compression/main.py
@@ -0,0 +1,46 @@
+# -*- coding: utf-8 -*-
+"""The main entry point of the MemoryWithCompress example."""
+import asyncio
+import os
+from agentscope.agent import ReActAgent, UserAgent
+from agentscope.formatter import DashScopeChatFormatter
+from agentscope.model import DashScopeChatModel
+from agentscope.token import CharTokenCounter
+
+
+async def main() -> None:
+ """The main entry point of the MemoryWithCompress example."""
+
+ # Create model for agent and memory compression
+ agent = ReActAgent(
+ name="Friday",
+ sys_prompt="You are a helpful assistant named Friday.",
+ model=DashScopeChatModel(
+ api_key=os.getenv("DASHSCOPE_API_KEY"),
+ model_name="qwen3-max",
+ ),
+ formatter=DashScopeChatFormatter(),
+ compression_config=ReActAgent.CompressionConfig(
+ enable=True,
+ agent_token_counter=CharTokenCounter(),
+ # We set a small trigger threshold for demonstration purposes.
+ trigger_threshold=1000,
+ keep_recent=3,
+ ),
+ )
+ user = UserAgent("User")
+
+ # Simulate a conversation to trigger memory compression
+ msg = None
+ while True:
+ msg = await user(msg)
+ if msg.get_text_content() == "exit":
+ break
+ msg = await agent(msg)
+
+ print("The memory of the agent:")
+ for msg in await agent.memory.get_memory():
+ print(msg.to_dict(), end="\n")
+
+
+asyncio.run(main())
diff --git a/pyproject.toml b/pyproject.toml
index 104b45a74..52f32d72f 100644
--- a/pyproject.toml
+++ b/pyproject.toml
@@ -38,46 +38,103 @@ dependencies = [
"shortuuid",
"tiktoken",
"sounddevice",
+ "sqlalchemy",
"python-frontmatter",
]
[project.optional-dependencies]
-# A2A protocol support
+# ------------ A2A protocol ------------
a2a = [
"a2a-sdk",
"httpx",
+ # TODO: split the card resolvers from the a2a dependency
"nacos-sdk-python>=3.0.0",
]
-full = [
- # Model
- "ollama>=0.5.4",
- "google-genai",
+
+# ------------ Model APIs ------------
+gemini = ["google-genai"]
+ollama = ["ollama>=0.5.4"]
+models = [
+ "agentscope[ollama]",
+ "agentscope[gemini]",
+]
+
+# ------------ Tokenizers ------------
+tokens = [
"Pillow",
"transformers",
"jinja2",
- # Evaluator
- "ray",
- # Long-term memory
+]
+
+# ------------ Memory ------------
+redis_memory = ["redis"]
+
+mem0ai = [
"mem0ai<=0.1.116",
- "packaging",
- "reme-ai>=0.2.0.3",
- # RAG
- "pypdf",
- "python-docx",
- "nltk",
- # The qdrant-client >= 1.16.0 has conflicts with pymilvus, so we fix
- # the version to 1.15.1 here.
- "qdrant-client==1.15.1",
- "mysql-connector-python",
+ "packaging"
+]
+reme = ["reme-ai>=0.2.0.3"]
+memory = [
+ "agentscope[redis_memory]",
+ "agentscope[mem0ai]",
+ "agentscope[reme]",
+]
+
+# ------------ RAG ------------
+# readers
+text-reader = ["nltk"]
+pdf-reader = [
+ "agentscope[text-reader]",
+ # TODO: the latest pypdf has some issues with parsing PDFs
+ # (2026-01-13), so we fix the version here temporarily.
+ "pypdf<=6.5.0",
+]
+docx-reader = [
+ "agentscope[text-reader]",
+ "python-docx"
+]
+readers = [
+ "agentscope[text-reader]",
+ "agentscope[pdf-reader]",
+ "agentscope[docx-reader]",
+]
+
+# vdb
+# The qdrant-client >= 1.16.0 has conflicts with pymilvus, so we fix
+# the version to 1.15.1 here.
+qdrant = ["qdrant-client==1.15.1"]
+milvus = ["pymilvus[milvus_lite]"]
+ali_mysql = ["mysql-connector-python"]
+vdbs = [
+ "agentscope[ali_mysql]",
+ "agentscope[qdrant]",
+ "agentscope[milvus]",
+]
+
+rag = [
+ "agentscope[readers]",
+ "agentscope[vdbs]",
]
+# ------------ Evaluation ------------
+evaluate = ["ray"]
+
+# ------------ Full ------------
+full = [
+ "agentscope[a2a]",
+ "agentscope[models]",
+ "agentscope[tokens]",
+ "agentscope[memory]",
+ "agentscope[rag]",
+ "agentscope[evaluate]",
+]
+
+# ------------ Development ------------
dev = [
# Include full dependencies from local package
"agentscope[full]",
- # A2A protocol support
- "agentscope[a2a]",
# Development tools
"pre-commit",
"pytest",
@@ -86,7 +143,11 @@ dev = [
"furo",
"myst_parser",
"matplotlib",
- "pymilvus[milvus_lite]",
+ # For unittests
+ # For mocking redis in unittests
+ "fakeredis",
+ "aiosqlite",
+ "greenlet",
]
[project.urls]
diff --git a/src/agentscope/agent/_react_agent.py b/src/agentscope/agent/_react_agent.py
index d4a3f5422..c7ac59a70 100644
--- a/src/agentscope/agent/_react_agent.py
+++ b/src/agentscope/agent/_react_agent.py
@@ -1,8 +1,10 @@
# -*- coding: utf-8 -*-
-# pylint: disable=not-an-iterable
+# TODO: simplify the ReActAgent class
+# pylint: disable=not-an-iterable, too-many-lines
# mypy: disable-error-code="list-item"
"""ReAct agent class in agentscope."""
import asyncio
+from enum import Enum
from typing import Type, Any, AsyncGenerator, Literal
from pydantic import BaseModel, ValidationError, Field
@@ -22,6 +24,7 @@ from ..message import (
from ..model import ChatModelBase
from ..rag import KnowledgeBase, Document
from ..plan import PlanNotebook
+from ..token import TokenCounterBase
from ..tool import Toolkit, ToolResponse
from ..tracing import trace_reply
from ..tts import TTSModelBase
@@ -37,6 +40,61 @@ class _QueryRewriteModel(BaseModel):
)
+class SummarySchema(BaseModel):
+ """The compressed memory model, used to generate summary of old memories"""
+
+ task_overview: str = Field(
+ max_length=300,
+ description=(
+ "The user's core request and success criteria.\n"
+ "Any clarifications or constraints they specified"
+ ),
+ )
+ current_state: str = Field(
+ max_length=300,
+ description=(
+ "What has been completed so far.\n"
+ "File created, modified, or analyzed (with paths if relevant).\n"
+ "Key outputs or artifacts produced."
+ ),
+ )
+ important_discoveries: str = Field(
+ max_length=300,
+ description=(
+ "Technical constraints or requirements uncovered.\n"
+ "Decisions made and their rationale.\n"
+ "Errors encountered and how they were resolved.\n"
+ "What approaches were tried that didn't work (and why)"
+ ),
+ )
+ next_steps: str = Field(
+ max_length=200,
+ description=(
+ "Specific actions needed to complete the task.\n"
+ "Any blockers or open questions to resolve.\n"
+ "Priority order if multiple steps remain"
+ ),
+ )
+ context_to_preserve: str = Field(
+ max_length=300,
+ description=(
+ "User preferences or style requirements.\n"
+ "Domain-specific details that aren't obvious.\n"
+ "Any promises made to the user"
+ ),
+ )
+
+
+class _MemoryMark(str, Enum):
+ """The memory marks used in the ReAct agent."""
+
+ HINT = "hint"
+ """Used to mark the hint messages that will be cleared after use."""
+
+ COMPRESSED = "compressed"
+ """Used to mark the compressed messages in the memory."""
+
+
class ReActAgent(ReActAgentBase):
"""A ReAct agent implementation in AgentScope, which supports
@@ -46,6 +104,72 @@ class ReActAgent(ReActAgentBase):
- Structured output generation
"""
+ class CompressionConfig(BaseModel):
+ """The compression related configuration in AgentScope"""
+
+ model_config = {"arbitrary_types_allowed": True}
+ """Allow arbitrary types in the pydantic model."""
+
+ enable: bool
+ """Whether to enable the auto compression feature."""
+
+ agent_token_counter: TokenCounterBase
+ """The token counter for the agent's model, which must be consistent
+ with the model used in the agent."""
+
+ trigger_threshold: int
+ """The token threshold to trigger the compression process. When the
+ total token count in the memory exceeds this threshold, the
+ compression will be activated."""
+
+ keep_recent: int = 3
+ """The number of most recent messages to keep uncompressed in the
+ memory to preserve the recent context."""
+
+ compression_prompt: str = (
+ "<system-hint>You have been working on the task described above "
+ "but have not yet completed it. "
+ "Now write a continuation summary that will allow you to resume "
+ "work efficiently in a future context window where the "
+ "conversation history will be replaced with this summary. "
+ "Your summary should be structured, concise, and actionable."
+ "</system-hint>"
+ )
+ """The prompt used to guide the compression model to generate the
+ compressed summary, which will be wrapped into a user message and
+ attach to the end of the current memory."""
+
+ summary_template: str = (
+ "<system-info>Here is a summary of your previous work\n"
+ "# Task Overview\n"
+ "{task_overview}\n\n"
+ "# Current State\n"
+ "{current_state}\n\n"
+ "# Important Discoveries\n"
+ "{important_discoveries}\n\n"
+ "# Next Steps\n"
+ "{next_steps}\n\n"
+ "# Context to Preserve\n"
+ "{context_to_preserve}"
+ "</system-info>"
+ )
+ """The string template to present the compressed summary to the agent,
+ which will be formatted with the fields from the
+ `compression_summary_model`."""
+
+ summary_schema: Type[BaseModel] = SummarySchema
+ """The structured model used to guide the agent to generate the
+ structured compressed summary."""
+
+ compression_model: ChatModelBase | None = None
+ """The compression model used to generate the compressed summary. If
+ not provided, the agent's model will be used."""
+
+ compression_formatter: FormatterBase | None = None
+ """The corresponding formatter form the compression model, when the
+ `compression_model` is provided, the `compression_formatter` must also
+ be provided."""
+
finish_function_name: str = "generate_response"
"""The name of the function used to generate structured output. Only
registered when structured output model is provided in the reply call."""
@@ -72,6 +196,7 @@ class ReActAgent(ReActAgentBase):
print_hint_msg: bool = False,
max_iters: int = 10,
tts_model: TTSModelBase | None = None,
+ compression_config: CompressionConfig | None = None,
) -> None:
"""Initialize the ReAct agent
@@ -131,6 +256,9 @@ class ReActAgent(ReActAgentBase):
The maximum number of iterations of the reasoning-acting loops.
tts_model (`TTSModelBase | None` optional):
The TTS model used by the agent.
+ compression_config (`CompressionConfig | None`, optional):
+ The compression configuration. If provided, the auto
+ compression will be activated.
"""
super().__init__()
@@ -147,6 +275,7 @@ class ReActAgent(ReActAgentBase):
self.model = model
self.formatter = formatter
self.tts_model = tts_model
+ self.compression_config = compression_config
# -------------- Memory management --------------
# Record the dialogue history in the memory
@@ -224,12 +353,6 @@ class ReActAgent(ReActAgentBase):
# The maximum number of iterations of the reasoning-acting loops
self.max_iters = max_iters
- # The hint messages that will be attached to the prompt to guide the
- # agent's behavior before each reasoning step, and cleared after
- # each reasoning step, meaning the hint messages is one-time use only.
- # We use an InMemoryMemory instance to store the hint messages
- self._reasoning_hint_msgs = InMemoryMemory()
-
# Variables to record the intermediate state
# If required structured output model is provided
@@ -278,6 +401,9 @@ class ReActAgent(ReActAgentBase):
# Retrieve relevant documents from the knowledge base(s) if any
await self._retrieve_from_knowledge(msg)
+ # -------------- Memory compression --------------
+ await self._compress_memory_if_needed()
+
# Control if LLM generates tool calls in each reasoning step
tool_choice: Literal["auto", "none", "required"] | None = None
@@ -356,7 +482,10 @@ class ReActAgent(ReActAgentBase):
"</system-hint>",
"user",
)
- await self._reasoning_hint_msgs.add(msg_hint)
+ await self.memory.add(
+ msg_hint,
+ marks=_MemoryMark.HINT,
+ )
# Just generate text response in the next reasoning step
tool_choice = "none"
@@ -374,7 +503,7 @@ class ReActAgent(ReActAgentBase):
f"required structured output.</system-hint>",
"user",
)
- await self._reasoning_hint_msgs.add(msg_hint)
+ await self.memory.add(msg_hint, marks=_MemoryMark.HINT)
# Require tool call in the next reasoning step
tool_choice = "required"
@@ -400,7 +529,9 @@ class ReActAgent(ReActAgentBase):
await self.long_term_memory.record(
[
*([*msg] if isinstance(msg, list) else [msg]),
- *await self.memory.get_memory(),
+ *await self.memory.get_memory(
+ exclude_mark=_MemoryMark.COMPRESSED,
+ ),
reply_msg,
],
)
@@ -419,19 +550,17 @@ class ReActAgent(ReActAgentBase):
hint_msg = await self.plan_notebook.get_current_hint()
if self.print_hint_msg and hint_msg:
await self.print(hint_msg)
- await self._reasoning_hint_msgs.add(hint_msg)
+ await self.memory.add(hint_msg, marks=_MemoryMark.HINT)
# Convert Msg objects into the required format of the model API
prompt = await self.formatter.format(
msgs=[
Msg("system", self.sys_prompt, "system"),
*await self.memory.get_memory(),
- # The hint messages to guide the agent's behavior, maybe empty
- *await self._reasoning_hint_msgs.get_memory(),
],
)
# Clear the hint messages after use
- await self._reasoning_hint_msgs.clear()
+ await self.memory.delete_by_mark(mark=_MemoryMark.HINT)
res = await self.model(
prompt,
@@ -864,3 +993,127 @@ class ReActAgent(ReActAgentBase):
if self.print_hint_msg:
await self.print(retrieved_msg, True)
await self.memory.add(retrieved_msg)
+
+ async def _compress_memory_if_needed(self) -> None:
+ """Compress the memory content if needed."""
+ if (
+ self.compression_config is None
+ or not self.compression_config.enable
+ ):
+ return
+
+ # Obtain the messages that have not been compressed yet
+ to_compressed_msgs = await self.memory.get_memory(
+ exclude_mark=_MemoryMark.COMPRESSED,
+ )
+
+ # keep the recent n messages uncompressed, note messages with tool
+ # use and result pairs should be kept together
+ n_keep = 0
+ accumulated_tool_call_ids = set()
+ for i in range(len(to_compressed_msgs) - 1, -1, -1):
+ msg = to_compressed_msgs[i]
+ for block in msg.get_content_blocks("tool_result"):
+ accumulated_tool_call_ids.add(block["id"])
+
+ for block in msg.get_content_blocks("tool_use"):
+ if block["id"] in accumulated_tool_call_ids:
+ accumulated_tool_call_ids.remove(block["id"])
+
+ # Handle the tool use/result pairs
+ if len(accumulated_tool_call_ids) == 0:
+ n_keep += 1
+
+ # Break if reach the number of messages to keep
+ if n_keep >= self.compression_config.keep_recent:
+ # Remove the messages that should be kept uncompressed
+ to_compressed_msgs = to_compressed_msgs[:i]
+ break
+
+ # Skip compression if no messages to compress
+ if not to_compressed_msgs:
+ return
+
+ # Calculate the token
+ prompt = await self.formatter.format(
+ [
+ Msg("system", self.sys_prompt, "system"),
+ *to_compressed_msgs,
+ ],
+ )
+ n_tokens = await self.compression_config.agent_token_counter.count(
+ prompt,
+ )
+
+ if n_tokens > self.compression_config.trigger_threshold:
+ logger.info(
+ "Memory compression is triggered (%d > "
+ "threshold %d) for agent %s.",
+ n_tokens,
+ self.compression_config.trigger_threshold,
+ self.name,
+ )
+
+ # The formatter used for compression
+ compression_formatter = (
+ self.compression_config.compression_formatter or self.formatter
+ )
+
+ # Prepare the prompt used to compress the memories
+ compression_prompt = await compression_formatter.format(
+ [
+ Msg("system", self.sys_prompt, "system"),
+ *to_compressed_msgs,
+ Msg(
+ "user",
+ self.compression_config.compression_prompt,
+ "user",
+ ),
+ ],
+ )
+
+ # TODO: What if the compressed messages include multimodal blocks?
+ # Use the specified compression model if provided
+ compression_model = (
+ self.compression_config.compression_model or self.model
+ )
+ res = await compression_model(
+ compression_prompt,
+ structured_model=(self.compression_config.summary_schema),
+ )
+
+ # Obtain the structured output from the model response
+ last_chunk = None
+ if compression_model.stream:
+ async for chunk in res:
+ last_chunk = chunk
+ else:
+ last_chunk = res
+
+ # Format the compressed memory summary
+ if last_chunk.metadata:
+ # Update the compressed summary in the memory storage
+ await self.memory.update_compressed_summary(
+ self.compression_config.summary_template.format(
+ **last_chunk.metadata,
+ ),
+ )
+
+ # Mark the compressed messages in the memory storage
+ await self.memory.update_messages_mark(
+ msg_ids=[_.id for _ in to_compressed_msgs],
+ new_mark=_MemoryMark.COMPRESSED,
+ )
+
+ logger.info(
+ "Finished compressing %d messages in agent %s.",
+ len(to_compressed_msgs),
+ self.name,
+ )
+
+ else:
+ logger.warning(
+ "Failed to obtain compression summary from the model "
+ "structured output in agent %s.",
+ self.name,
+ )
diff --git a/src/agentscope/memory/__init__.py b/src/agentscope/memory/__init__.py
index f779a7957..8af080ba0 100644
--- a/src/agentscope/memory/__init__.py
+++ b/src/agentscope/memory/__init__.py
@@ -1,19 +1,28 @@
# -*- coding: utf-8 -*-
"""The memory module."""
-from ._in_memory_memory import InMemoryMemory
-from ._long_term_memory_base import LongTermMemoryBase
-from ._mem0_long_term_memory import Mem0LongTermMemory
-from ._memory_base import MemoryBase
-from ._reme import (
+from ._working_memory import (
+ MemoryBase,
+ InMemoryMemory,
+ RedisMemory,
+ AsyncSQLAlchemyMemory,
+)
+from ._long_term_memory import (
+ LongTermMemoryBase,
+ Mem0LongTermMemory,
ReMePersonalLongTermMemory,
ReMeTaskLongTermMemory,
ReMeToolLongTermMemory,
)
+
__all__ = [
+ # Working memory
"MemoryBase",
"InMemoryMemory",
+ "RedisMemory",
+ "AsyncSQLAlchemyMemory",
+ # Long-term memory
"LongTermMemoryBase",
"Mem0LongTermMemory",
"ReMePersonalLongTermMemory",
diff --git a/src/agentscope/memory/_in_memory_memory.py b/src/agentscope/memory/_in_memory_memory.py
deleted file mode 100644
index 0d4e0f956..000000000
--- a/src/agentscope/memory/_in_memory_memory.py
+++ /dev/null
@@ -1,122 +0,0 @@
-# -*- coding: utf-8 -*-
-"""The dialogue memory class"""
-
-from typing import Union, Iterable, Any
-
-from ._memory_base import MemoryBase
-from ..message import Msg
-
-
-class InMemoryMemory(MemoryBase):
- """The in-memory memory class for storing messages."""
-
- def __init__(
- self,
- ) -> None:
- """Initialize the in-memory memory object."""
- super().__init__()
- self.content: list[Msg] = []
-
- def state_dict(self) -> dict:
- """Convert the current memory into JSON data format."""
- return {
- "content": [_.to_dict() for _ in self.content],
- }
-
- def load_state_dict(
- self,
- state_dict: dict,
- strict: bool = True,
- ) -> None:
- """Load the memory from JSON data.
-
- Args:
- state_dict (`dict`):
- The state dictionary to load, which should have a "content"
- field.
- strict (`bool`, defaults to `True`):
- If `True`, raises an error if any key in the module is not
- found in the state_dict. If `False`, skips missing keys.
- """
- self.content = []
- for data in state_dict["content"]:
- data.pop("type", None)
- self.content.append(Msg.from_dict(data))
-
- async def size(self) -> int:
- """The size of the memory."""
- return len(self.content)
-
- async def retrieve(self, *args: Any, **kwargs: Any) -> None:
- """Retrieve items from the memory."""
- raise NotImplementedError(
- "The retrieve method is not implemented in "
- f"{self.__class__.__name__} class.",
- )
-
- async def delete(self, index: Union[Iterable, int]) -> None:
- """Delete the specified item by index(es).
-
- Args:
- index (`Union[Iterable, int]`):
- The index to delete.
- """
- if isinstance(index, int):
- index = [index]
-
- invalid_index = [_ for _ in index if 0 > _ or _ >= len(self.content)]
-
- if invalid_index:
- raise IndexError(
- f"The index {invalid_index} does not exist.",
- )
-
- self.content = [
- _ for idx, _ in enumerate(self.content) if idx not in index
- ]
-
- async def add(
- self,
- memories: Union[list[Msg], Msg, None],
- allow_duplicates: bool = False,
- ) -> None:
- """Add message into the memory.
-
- Args:
- memories (`Union[list[Msg], Msg, None]`):
- The message to add.
- allow_duplicates (`bool`, defaults to `False`):
- If allow adding duplicate messages (with the same id) into
- the memory.
- """
- if memories is None:
- return
-
- if isinstance(memories, Msg):
- memories = [memories]
-
- if not isinstance(memories, list):
- raise TypeError(
- f"The memories should be a list of Msg or a single Msg, "
- f"but got {type(memories)}.",
- )
-
- for msg in memories:
- if not isinstance(msg, Msg):
- raise TypeError(
- f"The memories should be a list of Msg or a single Msg, "
- f"but got {type(msg)}.",
- )
-
- if not allow_duplicates:
- existing_ids = [_.id for _ in self.content]
- memories = [_ for _ in memories if _.id not in existing_ids]
- self.content.extend(memories)
-
- async def get_memory(self) -> list[Msg]:
- """Get the memory content."""
- return self.content
-
- async def clear(self) -> None:
- """Clear the memory content."""
- self.content = []
diff --git a/src/agentscope/memory/_long_term_memory/__init__.py b/src/agentscope/memory/_long_term_memory/__init__.py
new file mode 100644
index 000000000..ee099c1d4
--- /dev/null
+++ b/src/agentscope/memory/_long_term_memory/__init__.py
@@ -0,0 +1,18 @@
+# -*- coding: utf-8 -*-
+"""The long-term memory module for AgentScope."""
+
+from ._long_term_memory_base import LongTermMemoryBase
+from ._mem0 import Mem0LongTermMemory
+from ._reme import (
+ ReMePersonalLongTermMemory,
+ ReMeTaskLongTermMemory,
+ ReMeToolLongTermMemory,
+)
+
+__all__ = [
+ "LongTermMemoryBase",
+ "Mem0LongTermMemory",
+ "ReMePersonalLongTermMemory",
+ "ReMeTaskLongTermMemory",
+ "ReMeToolLongTermMemory",
+]
diff --git a/src/agentscope/memory/_long_term_memory_base.py b/src/agentscope/memory/_long_term_memory/_long_term_memory_base.py
similarity index 96%
rename from src/agentscope/memory/_long_term_memory_base.py
rename to src/agentscope/memory/_long_term_memory/_long_term_memory_base.py
index 7114891c4..c02fceb74 100644
--- a/src/agentscope/memory/_long_term_memory_base.py
+++ b/src/agentscope/memory/_long_term_memory/_long_term_memory_base.py
@@ -3,9 +3,9 @@
from typing import Any
-from ..message import Msg
-from ..module import StateModule
-from ..tool import ToolResponse
+from agentscope.message import Msg
+from agentscope.module import StateModule
+from agentscope.tool import ToolResponse
class LongTermMemoryBase(StateModule):
diff --git a/src/agentscope/memory/_long_term_memory/_mem0/__init__.py b/src/agentscope/memory/_long_term_memory/_mem0/__init__.py
new file mode 100644
index 000000000..d29253c5f
--- /dev/null
+++ b/src/agentscope/memory/_long_term_memory/_mem0/__init__.py
@@ -0,0 +1,9 @@
+# -*- coding: utf-8 -*-
+"""The Mem0 long-term memory module for AgentScope."""
+
+from ._mem0_long_term_memory import Mem0LongTermMemory
+
+
+__all__ = [
+ "Mem0LongTermMemory",
+]
diff --git a/src/agentscope/memory/_mem0_long_term_memory.py b/src/agentscope/memory/_long_term_memory/_mem0/_mem0_long_term_memory.py
similarity index 99%
rename from src/agentscope/memory/_mem0_long_term_memory.py
rename to src/agentscope/memory/_long_term_memory/_mem0/_mem0_long_term_memory.py
index c584c9bb8..d8300f943 100644
--- a/src/agentscope/memory/_mem0_long_term_memory.py
+++ b/src/agentscope/memory/_long_term_memory/_mem0/_mem0_long_term_memory.py
@@ -10,14 +10,13 @@ import json
from typing import Any, TYPE_CHECKING
from importlib import metadata
-
from pydantic import field_validator
-from ..embedding import EmbeddingModelBase
-from ._long_term_memory_base import LongTermMemoryBase
-from ..message import Msg, TextBlock
-from ..model import ChatModelBase
-from ..tool import ToolResponse
+from ....embedding import EmbeddingModelBase
+from .._long_term_memory_base import LongTermMemoryBase
+from ....message import Msg, TextBlock
+from ....model import ChatModelBase
+from ....tool import ToolResponse
if TYPE_CHECKING:
diff --git a/src/agentscope/memory/_mem0_utils.py b/src/agentscope/memory/_long_term_memory/_mem0/_mem0_utils.py
similarity index 98%
rename from src/agentscope/memory/_mem0_utils.py
rename to src/agentscope/memory/_long_term_memory/_mem0/_mem0_utils.py
index 2a74af9b1..dbd4e37ea 100644
--- a/src/agentscope/memory/_mem0_utils.py
+++ b/src/agentscope/memory/_long_term_memory/_mem0/_mem0_utils.py
@@ -12,9 +12,8 @@ from mem0.configs.llms.base import BaseLlmConfig
from mem0.embeddings.base import EmbeddingBase
from mem0.llms.base import LLMBase
-
-from ..embedding import EmbeddingModelBase
-from ..model import ChatModelBase, ChatResponse
+from ....embedding import EmbeddingModelBase
+from ....model import ChatModelBase, ChatResponse
class AgentScopeLLM(LLMBase):
diff --git a/src/agentscope/memory/_reme/__init__.py b/src/agentscope/memory/_long_term_memory/_reme/__init__.py
similarity index 100%
rename from src/agentscope/memory/_reme/__init__.py
rename to src/agentscope/memory/_long_term_memory/_reme/__init__.py
diff --git a/src/agentscope/memory/_reme/_reme_long_term_memory_base.py b/src/agentscope/memory/_long_term_memory/_reme/_reme_long_term_memory_base.py
similarity index 98%
rename from src/agentscope/memory/_reme/_reme_long_term_memory_base.py
rename to src/agentscope/memory/_long_term_memory/_reme/_reme_long_term_memory_base.py
index f24b71b01..9abf25879 100644
--- a/src/agentscope/memory/_reme/_reme_long_term_memory_base.py
+++ b/src/agentscope/memory/_long_term_memory/_reme/_reme_long_term_memory_base.py
@@ -70,14 +70,8 @@ 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,
-)
+from ....embedding import DashScopeTextEmbedding, OpenAITextEmbedding
+from ....model import DashScopeChatModel, OpenAIChatModel
class ReMeLongTermMemoryBase(LongTermMemoryBase, metaclass=ABCMeta):
diff --git a/src/agentscope/memory/_reme/_reme_personal_long_term_memory.py b/src/agentscope/memory/_long_term_memory/_reme/_reme_personal_long_term_memory.py
similarity index 99%
rename from src/agentscope/memory/_reme/_reme_personal_long_term_memory.py
rename to src/agentscope/memory/_long_term_memory/_reme/_reme_personal_long_term_memory.py
index b5d5a3ecd..430e321fe 100644
--- a/src/agentscope/memory/_reme/_reme_personal_long_term_memory.py
+++ b/src/agentscope/memory/_long_term_memory/_reme/_reme_personal_long_term_memory.py
@@ -9,9 +9,9 @@ retrieval capabilities for AgentScope agents.
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
+from ...._logging import logger
+from ....message import Msg, TextBlock
+from ....tool import ToolResponse
class ReMePersonalLongTermMemory(ReMeLongTermMemoryBase):
diff --git a/src/agentscope/memory/_reme/_reme_task_long_term_memory.py b/src/agentscope/memory/_long_term_memory/_reme/_reme_task_long_term_memory.py
similarity index 99%
rename from src/agentscope/memory/_reme/_reme_task_long_term_memory.py
rename to src/agentscope/memory/_long_term_memory/_reme/_reme_task_long_term_memory.py
index e309aa6de..7e9b612c2 100644
--- a/src/agentscope/memory/_reme/_reme_task_long_term_memory.py
+++ b/src/agentscope/memory/_long_term_memory/_reme/_reme_task_long_term_memory.py
@@ -9,9 +9,9 @@ retrieve relevant task experiences.
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
+from ...._logging import logger
+from ....message import Msg, TextBlock
+from ....tool import ToolResponse
class ReMeTaskLongTermMemory(ReMeLongTermMemoryBase):
diff --git a/src/agentscope/memory/_reme/_reme_tool_long_term_memory.py b/src/agentscope/memory/_long_term_memory/_reme/_reme_tool_long_term_memory.py
similarity index 99%
rename from src/agentscope/memory/_reme/_reme_tool_long_term_memory.py
rename to src/agentscope/memory/_long_term_memory/_reme/_reme_tool_long_term_memory.py
index e941f6782..ffddb791a 100644
--- a/src/agentscope/memory/_reme/_reme_tool_long_term_memory.py
+++ b/src/agentscope/memory/_long_term_memory/_reme/_reme_tool_long_term_memory.py
@@ -9,9 +9,9 @@ tool usage guidelines.
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
+from ...._logging import logger
+from ....message import Msg, TextBlock
+from ....tool import ToolResponse
class ReMeToolLongTermMemory(ReMeLongTermMemoryBase):
diff --git a/src/agentscope/memory/_memory_base.py b/src/agentscope/memory/_memory_base.py
deleted file mode 100644
index 8173d9fd7..000000000
--- a/src/agentscope/memory/_memory_base.py
+++ /dev/null
@@ -1,44 +0,0 @@
-# -*- coding: utf-8 -*-
-"""The memory base class."""
-
-from abc import abstractmethod
-from typing import Any
-
-from ..message import Msg
-from ..module import StateModule
-
-
-class MemoryBase(StateModule):
- """The base class for memory in agentscope."""
-
- @abstractmethod
- async def add(self, *args: Any, **kwargs: Any) -> None:
- """Add items to the memory."""
-
- @abstractmethod
- async def delete(self, *args: Any, **kwargs: Any) -> None:
- """Delete items from the memory."""
-
- @abstractmethod
- async def retrieve(self, *args: Any, **kwargs: Any) -> None:
- """Retrieve items from the memory."""
-
- @abstractmethod
- async def size(self) -> int:
- """Get the size of the memory."""
-
- @abstractmethod
- async def clear(self) -> None:
- """Clear the memory content."""
-
- @abstractmethod
- async def get_memory(self, *args: Any, **kwargs: Any) -> list[Msg]:
- """Get the memory content."""
-
- @abstractmethod
- def state_dict(self) -> dict:
- """Get the state dictionary of the memory."""
-
- @abstractmethod
- def load_state_dict(self, state_dict: dict, strict: bool = True) -> None:
- """Load the state dictionary of the memory."""
diff --git a/src/agentscope/memory/_working_memory/__init__.py b/src/agentscope/memory/_working_memory/__init__.py
new file mode 100644
index 000000000..a092f0e58
--- /dev/null
+++ b/src/agentscope/memory/_working_memory/__init__.py
@@ -0,0 +1,16 @@
+# -*- coding: utf-8 -*-
+"""The working memory module in AgentScope, which provides various memory
+storage implementations. In AgentScope, such module is responsible for
+storing and managing the short-term memory with specific marks."""
+
+from ._base import MemoryBase
+from ._in_memory_memory import InMemoryMemory
+from ._redis_memory import RedisMemory
+from ._sqlalchemy_memory import AsyncSQLAlchemyMemory
+
+__all__ = [
+ "MemoryBase",
+ "InMemoryMemory",
+ "RedisMemory",
+ "AsyncSQLAlchemyMemory",
+]
diff --git a/src/agentscope/memory/_working_memory/_base.py b/src/agentscope/memory/_working_memory/_base.py
new file mode 100644
index 000000000..8392c3902
--- /dev/null
+++ b/src/agentscope/memory/_working_memory/_base.py
@@ -0,0 +1,168 @@
+# -*- coding: utf-8 -*-
+"""The memory base class."""
+
+from abc import abstractmethod
+from typing import Any
+
+from ...message import Msg
+from ...module import StateModule
+
+
+class MemoryBase(StateModule):
+ """The base class for memory in agentscope."""
+
+ def __init__(self) -> None:
+ """Initialize the memory base."""
+ super().__init__()
+
+ self._compressed_summary: str = ""
+
+ self.register_state("_compressed_summary")
+
+ async def update_compressed_summary(self, summary: str) -> None:
+ """Update the compressed summary of the memory.
+
+ Args:
+ summary (`str`):
+ The new compressed summary.
+ """
+ self._compressed_summary = summary
+
+ @abstractmethod
+ async def add(
+ self,
+ memories: Msg | list[Msg] | None,
+ marks: str | list[str] | None = None,
+ **kwargs: Any,
+ ) -> None:
+ """Add message(s) into the memory storage with the given mark
+ (if provided).
+
+ Args:
+ memories (`Msg | list[Msg] | None`):
+ The message(s) to be added.
+ marks (`str | list[str] | None`, optional):
+ The mark(s) to associate with the message(s). If `None`, no
+ mark is associated.
+ """
+
+ @abstractmethod
+ async def delete(
+ self,
+ msg_ids: list[str],
+ **kwargs: Any,
+ ) -> int:
+ """Remove message(s) from the storage by their IDs.
+
+ Args:
+ msg_ids (`list[str]`):
+ The list of message IDs to be removed.
+
+ Returns:
+ `int`:
+ The number of messages removed.
+ """
+
+ async def delete_by_mark(
+ self,
+ mark: str | list[str],
+ *args: Any,
+ **kwargs: Any,
+ ) -> int:
+ """Remove messages from the memory by their marks.
+
+ Args:
+ mark (`str | list[str]`):
+ The mark(s) of the messages to be removed.
+
+ Raises:
+ `TypeError`:
+ If the provided mark is not a string or a list of strings.
+
+ Returns:
+ `int`:
+ The number of messages removed.
+ """
+ raise NotImplementedError(
+ "The delete_by_mark method is not implemented in "
+ f"{self.__class__.__name__} class.",
+ )
+
+ @abstractmethod
+ async def size(self) -> int:
+ """Get the number of messages in the storage.
+
+ Returns:
+ `int`:
+ The number of messages in the storage.
+ """
+
+ @abstractmethod
+ async def clear(self) -> None:
+ """Clear the memory content."""
+
+ @abstractmethod
+ async def get_memory(
+ self,
+ mark: str | None = None,
+ exclude_mark: str | None = None,
+ prepend_summary: bool = True,
+ **kwargs: Any,
+ ) -> list[Msg]:
+ """Get the messages from the memory by mark (if provided). Otherwise,
+ get all messages.
+
+ .. note:: If `mark` and `exclude_mark` are both provided, the messages
+ will be filtered by both arguments.
+
+ .. note:: `mark` and `exclude_mark` should not overlap.
+
+ Args:
+ mark (`str | None`, optional):
+ The mark to filter messages. If `None`, return all messages.
+ exclude_mark (`str | None`, optional):
+ The mark to exclude messages. If provided, messages with
+ this mark will be excluded from the results.
+ prepend_summary (`bool`, defaults to True):
+ Whether to prepend the compressed summary as a message
+
+ Returns:
+ `list[Msg]`:
+ The list of messages retrieved from the storage.
+ """
+
+ async def update_messages_mark(
+ self,
+ new_mark: str | None,
+ old_mark: str | None = None,
+ msg_ids: list[str] | None = None,
+ ) -> int:
+ """A unified method to update marks of messages in the storage (add,
+ remove, or change marks).
+
+ - If `msg_ids` is provided, the update will be applied to the messages
+ with the specified IDs.
+ - If `old_mark` is provided, the update will be applied to the
+ messages with the specified old mark. Otherwise, the `new_mark` will
+ be added to all messages (or those filtered by `msg_ids`).
+ - If `new_mark` is `None`, the mark will be removed from the messages.
+
+ Args:
+ new_mark (`str | None`, optional):
+ The new mark to set for the messages. If `None`, the mark
+ will be removed.
+ old_mark (`str | None`, optional):
+ The old mark to filter messages. If `None`, this constraint
+ is ignored.
+ msg_ids (`list[str] | None`, optional):
+ The list of message IDs to be updated. If `None`, this
+ constraint is ignored.
+
+ Returns:
+ `int`:
+ The number of messages updated.
+ """
+ raise NotImplementedError(
+ "The update_messages_mark method is not implemented in "
+ f"{self.__class__.__name__} class.",
+ )
diff --git a/src/agentscope/memory/_working_memory/_in_memory_memory.py b/src/agentscope/memory/_working_memory/_in_memory_memory.py
new file mode 100644
index 000000000..489e76990
--- /dev/null
+++ b/src/agentscope/memory/_working_memory/_in_memory_memory.py
@@ -0,0 +1,302 @@
+# -*- coding: utf-8 -*-
+"""The in-memory storage module for memory storage."""
+from copy import deepcopy
+from typing import Any
+
+from ...message import Msg
+from ._base import MemoryBase
+
+
+class InMemoryMemory(MemoryBase):
+ """The in-memory implementation of memory storage."""
+
+ def __init__(self) -> None:
+ """Initialize the in-memory storage."""
+ super().__init__()
+ # Use a list of tuples to store messages along with their marks
+ self.content: list[tuple[Msg, list[str]]] = []
+
+ # Register the state for serialization
+ self.register_state("content")
+
+ async def get_memory(
+ self,
+ mark: str | None = None,
+ exclude_mark: str | None = None,
+ prepend_summary: bool = True,
+ **kwargs: Any,
+ ) -> list[Msg]:
+ """Get the messages from the memory by mark (if provided). Otherwise,
+ get all messages.
+
+ .. note:: If `mark` and `exclude_mark` are both provided, the messages
+ will be filtered by both arguments.
+
+ .. note:: `mark` and `exclude_mark` should not overlap.
+
+ Args:
+ mark (`str | None`, optional):
+ The mark to filter messages. If `None`, return all messages.
+ exclude_mark (`str | None`, optional):
+ The mark to exclude messages. If provided, messages with
+ this mark will be excluded from the results.
+ prepend_summary (`bool`, defaults to True):
+ Whether to prepend the compressed summary as a message
+
+ Raises:
+ `TypeError`:
+ If the provided mark is not a string or None.
+
+ Returns:
+ `list[Msg]`:
+ The list of messages retrieved from the storage.
+ """
+ # Type checks
+ if not (mark is None or isinstance(mark, str)):
+ raise TypeError(
+ f"The mark should be a string or None, but got {type(mark)}.",
+ )
+
+ if not (exclude_mark is None or isinstance(exclude_mark, str)):
+ raise TypeError(
+ f"The exclude_mark should be a string or None, but got "
+ f"{type(exclude_mark)}.",
+ )
+
+ # Filter messages based on mark
+ filtered_content = [
+ (msg, marks)
+ for msg, marks in self.content
+ if mark is None or mark in marks
+ ]
+
+ # Further filter messages based on exclude_mark
+ if exclude_mark is not None:
+ filtered_content = [
+ (msg, marks)
+ for msg, marks in filtered_content
+ if exclude_mark not in marks
+ ]
+
+ if prepend_summary and self._compressed_summary:
+ return [
+ Msg(
+ "user",
+ self._compressed_summary,
+ "user",
+ ),
+ *[msg for msg, _ in filtered_content],
+ ]
+
+ return [msg for msg, _ in filtered_content]
+
+ async def add(
+ self,
+ memories: Msg | list[Msg] | None,
+ marks: str | list[str] | None = None,
+ allow_duplicates: bool = False,
+ **kwargs: Any,
+ ) -> None:
+ """Add message(s) into the memory storage with the given mark
+ (if provided).
+
+ Args:
+ memories (`Msg | list[Msg] | None`):
+ The message(s) to be added.
+ marks (`str | list[str] | None`, optional):
+ The mark(s) to associate with the message(s). If `None`, no
+ mark is associated.
+ allow_duplicates (`bool`, defaults to `False`):
+ Whether to allow duplicate messages in the storage.
+ """
+ if memories is None:
+ return
+
+ if isinstance(memories, Msg):
+ memories = [memories]
+
+ if marks is None:
+ marks = []
+ elif isinstance(marks, str):
+ marks = [marks]
+ elif not isinstance(marks, list) or not all(
+ isinstance(m, str) for m in marks
+ ):
+ raise TypeError(
+ f"The mark should be a string, a list of strings, or None, "
+ f"but got {type(marks)}.",
+ )
+
+ if not allow_duplicates:
+ existing_ids = {msg.id for msg, _ in self.content}
+ memories = [msg for msg in memories if msg.id not in existing_ids]
+
+ for msg in memories:
+ self.content.append((deepcopy(msg), deepcopy(marks)))
+
+ async def delete(
+ self,
+ msg_ids: list[str],
+ **kwargs: Any,
+ ) -> int:
+ """Remove message(s) from the storage by their IDs.
+
+ Args:
+ msg_ids (`list[str]`):
+ The list of message IDs to be removed.
+
+ Returns:
+ `int`:
+ The number of messages removed.
+ """
+ initial_size = len(self.content)
+ self.content = [
+ (msg, marks)
+ for msg, marks in self.content
+ if msg.id not in msg_ids
+ ]
+ return initial_size - len(self.content)
+
+ async def delete_by_mark(
+ self,
+ mark: str | list[str],
+ **kwargs: Any,
+ ) -> int:
+ """Remove messages from the memory by their marks.
+
+ Args:
+ mark (`str | list[str]`):
+ The mark(s) of the messages to be removed.
+
+ Raises:
+ `TypeError`:
+ If the provided mark is not a string or a list of strings.
+
+ Returns:
+ `int`:
+ The number of messages removed.
+ """
+ if isinstance(mark, str):
+ mark = [mark]
+
+ if isinstance(mark, list) and not all(
+ isinstance(m, str) for m in mark
+ ):
+ raise TypeError(
+ f"The mark should be a string or a list of strings, "
+ f"but got {type(mark)} with elements of types "
+ f"{[type(m) for m in mark]}.",
+ )
+
+ initial_size = len(self.content)
+ for m in mark:
+ self.content = [
+ (msg, marks) for msg, marks in self.content if m not in marks
+ ]
+
+ return initial_size - len(self.content)
+
+ async def clear(self) -> None:
+ """Clear all messages from the storage."""
+ self.content.clear()
+
+ async def size(self) -> int:
+ """Get the number of messages in the storage.
+
+ Returns:
+ `int`:
+ The number of messages in the storage.
+ """
+ return len(self.content)
+
+ async def update_messages_mark(
+ self,
+ new_mark: str | None,
+ old_mark: str | None = None,
+ msg_ids: list[str] | None = None,
+ ) -> int:
+ """A unified method to update marks of messages in the storage (add,
+ remove, or change marks).
+
+ - If `msg_ids` is provided, the update will be applied to the messages
+ with the specified IDs.
+ - If `old_mark` is provided, the update will be applied to the
+ messages with the specified old mark. Otherwise, the `new_mark` will
+ be added to all messages (or those filtered by `msg_ids`).
+ - If `new_mark` is `None`, the mark will be removed from the messages.
+
+ Args:
+ new_mark (`str | None`, optional):
+ The new mark to set for the messages. If `None`, the mark
+ will be removed.
+ old_mark (`str | None`, optional):
+ The old mark to filter messages. If `None`, this constraint
+ is ignored.
+ msg_ids (`list[str] | None`, optional):
+ The list of message IDs to be updated. If `None`, this
+ constraint is ignored.
+
+ Returns:
+ `int`:
+ The number of messages updated.
+ """
+ updated_count = 0
+
+ for idx, (msg, marks) in enumerate(self.content):
+ # If msg_ids is provided, skip messages not in the list
+ if msg_ids is not None and msg.id not in msg_ids:
+ continue
+
+ # If old_mark is provided, skip messages that do not have the old
+ # mark
+ if old_mark is not None and old_mark not in marks:
+ continue
+
+ # If new_mark is None, remove the old_mark
+ if new_mark is None:
+ if old_mark in marks:
+ marks.remove(old_mark)
+ updated_count += 1
+
+ else:
+ # If new_mark is provided, add or replace the old_mark
+ if old_mark is not None and old_mark in marks:
+ marks.remove(old_mark)
+ if new_mark not in marks:
+ marks.append(new_mark)
+ updated_count += 1
+
+ self.content[idx] = (msg, marks)
+
+ return updated_count
+
+ def state_dict(self) -> dict:
+ """Get the state dictionary for serialization."""
+ return {
+ "content": [[msg.to_dict(), marks] for msg, marks in self.content],
+ }
+
+ def load_state_dict(self, state_dict: dict, strict: bool = True) -> None:
+ """Load the state dictionary for deserialization."""
+ if strict and "content" not in state_dict:
+ raise KeyError(
+ "The state_dict does not contain 'content' key required for "
+ "InMemoryMemory.",
+ )
+
+ self.content = []
+ for item in state_dict.get("content", []):
+ if isinstance(item, (tuple, list)) and len(item) == 2:
+ msg_dict, marks = item
+ msg = Msg.from_dict(msg_dict)
+ self.content.append((msg, marks))
+
+ elif isinstance(item, dict):
+ # For compatibility with older versions
+ msg = Msg.from_dict(item)
+ self.content.append((msg, []))
+
+ else:
+ raise ValueError(
+ "Invalid item format in state_dict for InMemoryMemory.",
+ )
diff --git a/src/agentscope/memory/_working_memory/_redis_memory.py b/src/agentscope/memory/_working_memory/_redis_memory.py
new file mode 100644
index 000000000..8a3ebd4a4
--- /dev/null
+++ b/src/agentscope/memory/_working_memory/_redis_memory.py
@@ -0,0 +1,591 @@
+# -*- coding: utf-8 -*-
+"""The redis based memory storage implementation."""
+import json
+from typing import Any, TYPE_CHECKING
+
+from ._base import MemoryBase
+from ...message import Msg
+
+if TYPE_CHECKING:
+ from redis.asyncio import ConnectionPool, Redis
+else:
+ ConnectionPool = Any
+ Redis = Any
+
+
+class RedisMemory(MemoryBase):
+ """Redis memory storage implementation, which supports session and user
+ context.
+
+ .. note:: All the operations in this class are within a specific session
+ and user context, identified by `session_id` and `user_id`. Cross-session
+ or cross-user operations are not supported. For example, the
+ `remove_messages` method will only remove messages that belong to the
+ specified `session_id` and `user_id`.
+
+ """
+
+ SESSION_KEY = "user_id:{user_id}:session:{session_id}:messages"
+ """The Redis key pattern to store messages for a specific session."""
+
+ MARK_KEY = "user_id:{user_id}:session:{session_id}:mark:{mark}"
+ """The Redis key pattern to store message ids that belong to a specific
+ mark."""
+
+ MESSAGE_KEY = "user_id:{user_id}:session:{session_id}:msg:{msg_id}"
+ """The Redis key pattern for storing message data."""
+
+ def __init__(
+ self,
+ session_id: str = "default_session",
+ user_id: str = "default_user",
+ host: str = "localhost",
+ port: int = 6379,
+ db: int = 0,
+ password: str | None = None,
+ connection_pool: ConnectionPool | None = None,
+ **kwargs: Any,
+ ) -> None:
+ """Initialize the Redis based storage by connecting to the Redis
+ server. You can provide either the connection parameters or an
+ existing connection pool.
+
+ Args:
+ session_id (`str`, default to `"default_session"`):
+ The session ID for the storage.
+ user_id (`str`, default to `"default_user"`):
+ The user ID for the storage.
+ host (`str`, default to `"localhost"`):
+ The Redis server host.
+ port (`int`, default to `6379`):
+ The Redis server port.
+ db (`int`, default to `0`):
+ The Redis database index.
+ password (`str | None`, optional):
+ The password for the Redis server, if required.
+ connection_pool (`ConnectionPool | None`, optional):
+ An optional Redis connection pool. If provided, it will be used
+ instead of creating a new connection.
+ **kwargs (`Any`):
+ Additional keyword arguments to pass to the Redis client.
+ """
+ try:
+ import redis.asyncio as redis
+ except ImportError as e:
+ raise ImportError(
+ "The 'redis' package is required for RedisStorage. "
+ "Please install it via 'pip install redis[async]'.",
+ ) from e
+
+ super().__init__()
+
+ self.session_id = session_id
+ self.user_id = user_id
+
+ self._client = redis.Redis(
+ host=host,
+ port=port,
+ db=db,
+ password=password,
+ connection_pool=connection_pool,
+ **kwargs,
+ )
+
+ def get_client(self) -> Redis:
+ """Get the underlying Redis client.
+
+ Returns:
+ `Redis`:
+ The Redis client instance.
+ """
+ return self._client
+
+ def _get_session_key(self) -> str:
+ """Get the Redis key for the current session.
+
+ Returns:
+ `str`:
+ The Redis key for storing messages in the current session.
+ """
+ return self.SESSION_KEY.format(
+ user_id=self.user_id,
+ session_id=self.session_id,
+ )
+
+ def _get_mark_key(self, mark: str) -> str:
+ """Get the Redis key for a specific mark.
+
+ Args:
+ mark (`str`):
+ The mark name.
+
+ Returns:
+ `str`:
+ The Redis key for storing message IDs with the given mark.
+ """
+ return self.MARK_KEY.format(
+ user_id=self.user_id,
+ session_id=self.session_id,
+ mark=mark,
+ )
+
+ def _get_mark_pattern(self) -> str:
+ """Get the Redis key pattern for all marks in the current session.
+
+ Returns:
+ `str`:
+ The Redis key pattern for all mark keys.
+ """
+ return self.MARK_KEY.format(
+ user_id=self.user_id,
+ session_id=self.session_id,
+ mark="*",
+ )
+
+ def _get_message_key(self, msg_id: str) -> str:
+ """Get the Redis key for a specific message.
+
+ Args:
+ msg_id (`str`):
+ The message ID.
+
+ Returns:
+ `str`:
+ The Redis key for storing the message data.
+ """
+ return self.MESSAGE_KEY.format(
+ user_id=self.user_id,
+ session_id=self.session_id,
+ msg_id=msg_id,
+ )
+
+ async def get_memory(
+ self,
+ mark: str | None = None,
+ exclude_mark: str | None = None,
+ prepend_summary: bool = True,
+ **kwargs: Any,
+ ) -> list[Msg]:
+ """Get the messages from the memory by mark (if provided). Otherwise,
+ get all messages.
+
+ .. note:: If `mark` and `exclude_mark` are both provided, the messages
+ will be filtered by both arguments.
+
+ .. note:: `mark` and `exclude_mark` should not overlap.
+
+ Args:
+ mark (`str | None`, optional):
+ The mark to filter messages. If `None`, return all messages.
+ exclude_mark (`str | None`, optional):
+ The mark to exclude messages. If provided, messages with
+ this mark will be excluded from the results.
+ prepend_summary (`bool`, defaults to True):
+ Whether to prepend the compressed summary as a message
+
+ Returns:
+ `list[Msg]`:
+ The list of messages retrieved from the storage.
+ """
+ # Type checks
+ if not (mark is None or isinstance(mark, str)):
+ raise TypeError(
+ f"The mark should be a string or None, but got {type(mark)}.",
+ )
+
+ if not (exclude_mark is None or isinstance(exclude_mark, str)):
+ raise TypeError(
+ f"The exclude_mark should be a string or None, but got "
+ f"{type(exclude_mark)}.",
+ )
+
+ if mark is None:
+ # Obtain the message IDs from the session list
+ msg_ids = await self._client.lrange(self._get_session_key(), 0, -1)
+
+ else:
+ # Obtain the message IDs from the mark list
+ msg_ids = await self._client.lrange(
+ self._get_mark_key(mark),
+ 0,
+ -1,
+ )
+
+ # Exclude messages by exclude_mark
+ if exclude_mark:
+ exclude_msg_ids = await self._client.lrange(
+ self._get_mark_key(exclude_mark),
+ 0,
+ -1,
+ )
+ msg_ids = [_ for _ in msg_ids if _ not in exclude_msg_ids]
+
+ # Use mget for batch retrieval to avoid N+1 queries
+ messages: list[Msg] = []
+ if msg_ids:
+ msg_keys = [self._get_message_key(msg_id) for msg_id in msg_ids]
+ msg_data_list = await self._client.mget(msg_keys)
+
+ for msg_data in msg_data_list:
+ if msg_data is not None:
+ if isinstance(msg_data, (bytes, bytearray)):
+ msg_data = msg_data.decode("utf-8")
+ msg_dict = json.loads(msg_data)
+ messages.append(Msg.from_dict(msg_dict))
+
+ if prepend_summary and self._compressed_summary:
+ return [
+ Msg(
+ "user",
+ self._compressed_summary,
+ "user",
+ ),
+ *messages,
+ ]
+
+ return messages
+
+ async def add(
+ self,
+ memories: Msg | list[Msg] | None,
+ marks: str | list[str] | None = None,
+ skip_duplicated: bool = True,
+ **kwargs: Any,
+ ) -> None:
+ """Add message into the storage with the given mark (if provided).
+
+ Args:
+ memories (`Msg | list[Msg]`):
+ The message(s) to be added.
+ marks (`str | list[str] | None`, optional):
+ The mark(s) to associate with the message(s). If `None`, no
+ mark is associated.
+ skip_duplicated (`bool`, defaults to `True`):
+ If `True`, skip messages with duplicate IDs that already exist
+ in the storage. If `False`, allow duplicate message IDs to be
+ added to the session list (though the message data will be
+ overwritten).
+ """
+ if memories is None:
+ return
+
+ if isinstance(memories, Msg):
+ memories = [memories]
+
+ # Normalize marks to a list
+ if marks is None:
+ mark_list = []
+ elif isinstance(marks, str):
+ mark_list = [marks]
+ else:
+ mark_list = marks
+
+ # Filter out existing messages if skip_duplicated is True
+ messages_to_add = memories
+ if skip_duplicated:
+ # Get all existing message IDs in the current session
+ existing_msg_ids = await self._client.lrange(
+ self._get_session_key(),
+ 0,
+ -1,
+ )
+ existing_msg_ids_set = set(existing_msg_ids)
+
+ # Filter out messages that already exist
+ messages_to_add = [
+ m for m in memories if m.id not in existing_msg_ids_set
+ ]
+
+ # If all messages are duplicates, return early
+ if not messages_to_add:
+ return
+
+ # Use pipeline for atomic operations
+ pipe = self._client.pipeline()
+
+ # Push message ids into the session list
+ if messages_to_add:
+ await pipe.rpush(
+ self._get_session_key(),
+ *[m.id for m in messages_to_add],
+ )
+
+ # Store message data and marks
+ for m in messages_to_add:
+ # Record the message data
+ await pipe.set(
+ self._get_message_key(m.id),
+ json.dumps(m.to_dict(), ensure_ascii=False),
+ )
+
+ # Record the marks if provided
+ for mark in mark_list:
+ await pipe.rpush(self._get_mark_key(mark), m.id)
+
+ await pipe.execute()
+
+ async def delete(
+ self,
+ msg_ids: list[str],
+ **kwargs: Any,
+ ) -> int:
+ """Remove message(s) from the storage by their IDs.
+
+ Args:
+ msg_ids (`list[str]`):
+ The list of message IDs to be removed.
+
+ Returns:
+ `int`:
+ The number of messages removed.
+ """
+ if not msg_ids:
+ return 0
+
+ # Get all mark keys once before the pipeline
+ mark_keys = []
+ cursor = 0
+ while True:
+ cursor, keys = await self._client.scan(
+ cursor,
+ match=self._get_mark_pattern(),
+ count=50,
+ )
+ mark_keys.extend(keys)
+ if cursor == 0:
+ break
+
+ pipe = self._client.pipeline()
+ for msg_id in msg_ids:
+ # Remove from the session (0 means remove all occurrences)
+ await pipe.lrem(self._get_session_key(), 0, msg_id)
+
+ # Remove the message data
+ await pipe.delete(self._get_message_key(msg_id))
+
+ # Remove from all marks
+ for mark_key in mark_keys:
+ await pipe.lrem(mark_key, 0, msg_id)
+
+ results = await pipe.execute()
+
+ # Count actual deletions from lrem results (every 3rd result
+ # starting from 0)
+ removed_count = sum(
+ 1
+ for i in range(
+ 0,
+ len(msg_ids) * (2 + len(mark_keys)),
+ 2 + len(mark_keys),
+ )
+ if results[i] > 0
+ )
+
+ return removed_count
+
+ async def delete_by_mark(
+ self,
+ mark: str | list[str],
+ **kwargs: Any,
+ ) -> int:
+ """Remove messages from the storage by their marks.
+
+ Args:
+ mark (`str | list[str]`):
+ The mark(s) of the messages to be removed.
+
+ Returns:
+ `int`:
+ The number of messages removed.
+ """
+ if isinstance(mark, str):
+ mark = [mark]
+
+ total_removed = 0
+
+ for m in mark:
+ mark_key = self._get_mark_key(m)
+ msg_ids = await self._client.lrange(mark_key, 0, -1)
+
+ if not msg_ids:
+ continue
+
+ # Remove messages by IDs
+ removed_count = await self.delete(
+ msg_ids,
+ )
+ total_removed += removed_count
+
+ # Delete the mark list
+ await self._client.delete(mark_key)
+
+ return total_removed
+
+ async def clear(self) -> None:
+ """Clear all messages belong to this session from the storage."""
+ msg_ids = await self._client.lrange(self._get_session_key(), 0, -1)
+
+ # Get all mark keys using SCAN
+ mark_keys = []
+ cursor = 0
+ while True:
+ cursor, keys = await self._client.scan(
+ cursor,
+ match=self._get_mark_pattern(),
+ count=50,
+ )
+ mark_keys.extend(keys)
+ if cursor == 0:
+ break
+
+ pipe = self._client.pipeline()
+
+ for msg_id in msg_ids:
+ # Remove the message data
+ await pipe.delete(self._get_message_key(msg_id))
+
+ # Delete the session list
+ await pipe.delete(self._get_session_key())
+
+ # Delete all mark lists
+ for mark_key in mark_keys:
+ await pipe.delete(mark_key)
+
+ await pipe.execute()
+
+ async def size(self) -> int:
+ """Get the number of messages in the storage.
+
+ Returns:
+ `int`:
+ The number of messages in the storage.
+ """
+ size = await self._client.llen(self._get_session_key())
+ return size
+
+ async def update_messages_mark(
+ self,
+ new_mark: str | None,
+ old_mark: str | None = None,
+ msg_ids: list[str] | None = None,
+ ) -> int:
+ """A unified method to update marks of messages in the storage (add,
+ remove, or change marks).
+
+ - If `msg_ids` is provided, the update will be applied to the messages
+ with the specified IDs.
+ - If `old_mark` is provided, the update will be applied to the
+ messages with the specified old mark. Otherwise, the `new_mark` will
+ be added to all messages (or those filtered by `msg_ids`).
+ - If `new_mark` is `None`, the mark will be removed from the messages.
+
+ Args:
+ new_mark (`str | None`, optional):
+ The new mark to set for the messages. If `None`, the mark
+ will be removed.
+ old_mark (`str | None`, optional):
+ The old mark to filter messages. If `None`, this constraint
+ is ignored.
+ msg_ids (`list[str] | None`, optional):
+ The list of message IDs to be updated. If `None`, this
+ constraint is ignored.
+
+ Returns:
+ `int`:
+ The number of messages updated.
+ """
+ # Determine which message IDs to update
+ if old_mark is not None:
+ # Get message IDs from the old mark list
+ mark_msg_ids = await self._client.lrange(
+ self._get_mark_key(old_mark),
+ 0,
+ -1,
+ )
+ else:
+ # Get all message IDs from the session
+ mark_msg_ids = await self._client.lrange(
+ self._get_session_key(),
+ 0,
+ -1,
+ )
+
+ # Filter by msg_ids if provided
+ if msg_ids is not None:
+ msg_ids_set = set(msg_ids)
+ mark_msg_ids = [mid for mid in mark_msg_ids if mid in msg_ids_set]
+
+ if not mark_msg_ids:
+ return 0
+
+ # Get existing IDs in new_mark list once (if needed)
+ existing_ids_set = set()
+ new_mark_key = None
+ if new_mark is not None:
+ new_mark_key = self._get_mark_key(new_mark)
+ existing_ids = await self._client.lrange(new_mark_key, 0, -1)
+ existing_ids_set = set(existing_ids)
+
+ # Use pipeline for batch operations
+ pipe = self._client.pipeline()
+ updated_count = 0
+
+ for msg_id in mark_msg_ids:
+ # If new_mark is None, remove the old_mark
+ if new_mark is None:
+ if old_mark is not None:
+ await pipe.lrem(
+ self._get_mark_key(old_mark),
+ 0,
+ msg_id,
+ )
+ updated_count += 1
+ else:
+ # Remove from old_mark list if applicable
+ if old_mark is not None:
+ await pipe.lrem(
+ self._get_mark_key(old_mark),
+ 0,
+ msg_id,
+ )
+
+ # Add to new_mark list only if not already present
+ if msg_id not in existing_ids_set and new_mark_key is not None:
+ await pipe.rpush(new_mark_key, msg_id)
+ existing_ids_set.add(msg_id)
+
+ updated_count += 1
+
+ await pipe.execute()
+ return updated_count
+
+ async def close(self) -> None:
+ """Close the Redis client connection."""
+ await self._client.close()
+
+ async def __aenter__(self) -> "RedisMemory":
+ """Enter the async context manager.
+
+ Returns:
+ `RedisMemory`:
+ The memory instance itself.
+ """
+ return self
+
+ async def __aexit__(
+ self,
+ exc_type: type[BaseException] | None,
+ exc_value: BaseException | None,
+ traceback: Any,
+ ) -> None:
+ """Exit the async context manager and close the session.
+
+ Args:
+ exc_type (`type[BaseException] | None`):
+ The exception type if an exception was raised.
+ exc_value (`BaseException | None`):
+ The exception instance if an exception was raised.
+ traceback (`Any`):
+ The traceback object if an exception was raised.
+ """
+ await self.close()
diff --git a/src/agentscope/memory/_working_memory/_sqlalchemy_memory.py b/src/agentscope/memory/_working_memory/_sqlalchemy_memory.py
new file mode 100644
index 000000000..769abb537
--- /dev/null
+++ b/src/agentscope/memory/_working_memory/_sqlalchemy_memory.py
@@ -0,0 +1,873 @@
+# -*- coding: utf-8 -*-
+"""The SQLAlchemy database storage module, which supports storing messages in
+a SQL database using SQLAlchemy ORM (e.g., SQLite, PostgreSQL, MySQL)."""
+from typing import Any
+
+from sqlalchemy import (
+ Column,
+ String,
+ JSON,
+ BigInteger,
+ ForeignKey,
+ select,
+ delete,
+ update,
+ func,
+)
+from sqlalchemy.ext.asyncio import (
+ AsyncEngine,
+ AsyncSession,
+ async_sessionmaker,
+)
+from sqlalchemy.orm import declarative_base, relationship
+
+from ._base import MemoryBase
+from ...message import Msg
+
+Base: Any = declarative_base()
+
+
+class AsyncSQLAlchemyMemory(MemoryBase):
+ """The SQLAlchemy memory storage class for storing messages in a SQL
+ database using SQLAlchemy ORM, such as SQLite, PostgreSQL, MySQL, etc.
+
+ .. note:: All the operations in this class are within a specific session
+ and user context, identified by `session_id` and `user_id`. Cross-session
+ or cross-user operations are not supported. For example, the
+ `remove_messages` method will only remove messages that belong to the
+ specified `session_id` and `user_id`.
+
+ """
+
+ class MessageTable(Base):
+ """The default message table definition."""
+
+ __tablename__ = "message"
+ """The table name"""
+
+ id = Column(String(255), primary_key=True)
+ """The id column, we use the f"{user_id}-{session_id}-{message_id}"
+ as the primary key to ensure uniqueness across users and sessions."""
+
+ msg = Column(JSON, nullable=False)
+ """The message JSON content column"""
+
+ session = relationship(
+ "SessionTable",
+ back_populates="messages",
+ )
+ """The foreign key to the session id relationship"""
+
+ session_id = Column(
+ String(255),
+ ForeignKey("session.id"),
+ nullable=False,
+ )
+ """The foreign key to the session id"""
+
+ index = Column(BigInteger, nullable=False, index=True)
+ """The index column for ordering messages, so that we can retrieve
+ messages in the order they were added."""
+
+ class MessageMarkTable(Base):
+ """The default message mark table definition."""
+
+ __tablename__ = "message_mark"
+ """The table name"""
+
+ msg_id = Column(
+ String(255),
+ ForeignKey("message.id", ondelete="CASCADE"),
+ primary_key=True,
+ )
+ """The message id column"""
+
+ mark = Column(String(255), primary_key=True)
+ """The mark column"""
+
+ class SessionTable(Base):
+ """The default session table definition."""
+
+ __tablename__ = "session"
+ """The table name"""
+
+ id = Column(String(255), primary_key=True)
+ """The session id column"""
+
+ user = relationship("UserTable", back_populates="sessions")
+ """The foreign key to the user id relationship"""
+
+ user_id = Column(String(255), ForeignKey("users.id"), nullable=False)
+ """The foreign key to the user id"""
+
+ messages = relationship("MessageTable", back_populates="session")
+ """The relationship to messages"""
+
+ class UserTable(Base):
+ """The default user table definition."""
+
+ __tablename__ = "users"
+ """The table name"""
+
+ id = Column(String(255), primary_key=True)
+ """The user id column"""
+
+ sessions = relationship("SessionTable", back_populates="user")
+ """The relationship to sessions"""
+
+ def __init__(
+ self,
+ engine_or_session: AsyncEngine | AsyncSession,
+ session_id: str | None = None,
+ user_id: str | None = None,
+ ) -> None:
+ """Initialize the SqlAlchemyDBStorage with a SQLAlchemy session.
+
+ Args:
+ engine_or_session (`AsyncEngine | AsyncSession`):
+ The SQLAlchemy asynchronous engine or session to use for
+ database operations. If you're using a connection pool, maybe
+ you want to pass in an `AsyncSession` instance.
+ session_id (`str | None`, optional):
+ The session ID for the messages. If `None`, a default session
+ ID will be used.
+ user_id (`str | None`, optional):
+ The user ID for the messages. If `None`, a default user ID
+ will be used.
+
+ Raises:
+ `ValueError`:
+ If the `engine` parameter is not an instance of
+ `sqlalchemy.ext.asyncio.AsyncEngine` or `sqlalchemy.
+ ext.asyncio.AsyncSession`.
+ """
+ super().__init__()
+
+ self._db_session: AsyncSession | None = None
+
+ if isinstance(engine_or_session, AsyncEngine):
+ self._session_factory = async_sessionmaker(
+ bind=engine_or_session,
+ expire_on_commit=False,
+ )
+
+ elif isinstance(engine_or_session, AsyncSession):
+ self._session_factory = None
+ self._db_session = engine_or_session
+
+ else:
+ raise ValueError(
+ "The 'engine_or_session' parameter must be an instance of "
+ "sqlalchemy.ext.asyncio.AsyncEngine.",
+ )
+
+ self.session_id = session_id or "default_session"
+ self.user_id = user_id or "default_user"
+
+ # Flag to track if tables and records have been initialized
+ self._initialized = False
+
+ def _make_message_id(self, msg_id: str) -> str:
+ """Generate a composite primary key for a message.
+
+ Args:
+ msg_id (`str`):
+ The original message ID.
+
+ Returns:
+ `str`:
+ The composite primary key in the format
+ "{user_id}-{session_id}-{message_id}".
+ """
+ return f"{self.user_id}-{self.session_id}-{msg_id}"
+
+ @property
+ def session(self) -> AsyncSession:
+ """Get the current database session, creating one if it doesn't exist.
+
+ Returns:
+ `AsyncSession`:
+ The current database session.
+
+ Note:
+ - If an external session was provided, it will be returned as-is
+ - If using internal session factory, a new session will be created
+ if the current one is None or inactive, and _initialized flag
+ will be reset to ensure proper re-initialization
+ """
+ # External session: return as-is (managed by caller)
+ if self._session_factory is None:
+ return self._db_session
+
+ # Internal session: check validity and recreate if needed
+ if self._db_session is None or not self._db_session.is_active:
+ self._db_session = self._session_factory()
+ # Reset initialized flag when creating new session
+ self._initialized = False
+
+ return self._db_session
+
+ async def _create_table(self) -> None:
+ """Create tables in database."""
+ # Skip if already initialized
+ if self._initialized:
+ return
+
+ # Obtain the engine first
+ engine: AsyncEngine = self.session.bind
+
+ async with engine.begin() as conn:
+ await conn.run_sync(Base.metadata.create_all)
+
+ # Track if we need to commit
+ needs_commit = False
+
+ # Create user record if not exists
+ result = await self.session.execute(
+ select(self.UserTable).filter(
+ self.UserTable.id == self.user_id,
+ ),
+ )
+ user_record = result.scalar_one_or_none()
+
+ if user_record is None:
+ user_record = self.UserTable(
+ id=self.user_id,
+ )
+ self.session.add(user_record)
+ needs_commit = True
+
+ # Create session record if not exists
+ result = await self.session.execute(
+ select(self.SessionTable).filter(
+ self.SessionTable.id == self.session_id,
+ ),
+ )
+ session_record = result.scalar_one_or_none()
+
+ if session_record is None:
+ session_record = self.SessionTable(
+ id=self.session_id,
+ user_id=self.user_id,
+ )
+ self.session.add(session_record)
+ needs_commit = True
+
+ # Commit once if any records were added
+ if needs_commit:
+ await self.session.commit()
+
+ # Mark as initialized
+ self._initialized = True
+
+ async def get_memory(
+ self,
+ mark: str | None = None,
+ exclude_mark: str | None = None,
+ prepend_summary: bool = True,
+ **kwargs: Any,
+ ) -> list[Msg]:
+ """Get the messages from the memory by mark (if provided). Otherwise,
+ get all messages.
+
+ .. note:: If `mark` and `exclude_mark` are both provided, the messages
+ will be filtered by both arguments.
+
+ .. note:: `mark` and `exclude_mark` should not overlap.
+
+ Args:
+ mark (`str | None`, optional):
+ The mark to filter messages. If `None`, return all messages.
+ exclude_mark (`str | None`, optional):
+ The mark to exclude messages. If provided, messages with
+ this mark will be excluded from the results.
+ prepend_summary (`bool`, defaults to True):
+ Whether to prepend the compressed summary as a message
+
+ Raises:
+ `TypeError`:
+ If the provided mark is not a string or None.
+
+ Returns:
+ `list[Msg]`:
+ The list of messages retrieved from the storage.
+ """
+ # Type checks
+ if mark is not None and not isinstance(mark, str):
+ raise TypeError(
+ f"The mark should be a string or None, but got {type(mark)}.",
+ )
+
+ if exclude_mark is not None and not isinstance(exclude_mark, str):
+ raise TypeError(
+ f"The exclude_mark should be a string or None, but got "
+ f"{type(exclude_mark)}.",
+ )
+
+ await self._create_table()
+
+ # Step 1: First filter by session_id to narrow down the dataset
+ # This ensures the database uses the session_id index first
+ base_query = select(self.MessageTable).filter(
+ self.MessageTable.session_id == self.session_id,
+ )
+
+ # Step 2: Apply mark filtering if provided
+ if mark:
+ # Join with mark table only on the session-filtered messages
+ base_query = base_query.join(
+ self.MessageMarkTable,
+ self.MessageTable.id == self.MessageMarkTable.msg_id,
+ ).filter(
+ self.MessageMarkTable.mark == mark,
+ )
+
+ # Step 3: Apply exclude_mark filtering if provided
+ if exclude_mark:
+ # Use a subquery to find message IDs with the exclude_mark
+ # within the current session only
+ exclude_subquery = (
+ select(self.MessageMarkTable.msg_id)
+ .filter(
+ self.MessageMarkTable.msg_id.in_(
+ select(self.MessageTable.id).filter(
+ self.MessageTable.session_id == self.session_id,
+ ),
+ ),
+ self.MessageMarkTable.mark == exclude_mark,
+ )
+ .scalar_subquery()
+ )
+ # Exclude messages whose IDs are in the subquery
+ base_query = base_query.filter(
+ self.MessageTable.id.notin_(exclude_subquery),
+ )
+
+ # Step 4: Order by index to maintain message order
+ query = base_query.order_by(self.MessageTable.index)
+
+ result = await self.session.execute(query)
+ results = result.scalars().all()
+
+ msgs = [Msg.from_dict(result.msg) for result in results]
+ if prepend_summary and self._compressed_summary:
+ return [
+ Msg(
+ "user",
+ self._compressed_summary,
+ "user",
+ ),
+ *msgs,
+ ]
+
+ return msgs
+
+ async def add(
+ self,
+ memories: Msg | list[Msg] | None,
+ marks: str | list[str] | None = None,
+ skip_duplicated: bool = True,
+ **kwargs: Any,
+ ) -> None:
+ """Add message into the storage with the given mark (if provided).
+
+ Args:
+ memories (`Msg | list[Msg] | None`):
+ The message(s) to be added.
+ marks (`str | list[str] | None`, optional):
+ The mark(s) to associate with the message(s). If `None`, no
+ mark is associated.
+ skip_duplicated (`bool`, defaults to `True`):
+ If `True`, skip messages with duplicate IDs that already exist
+ in the storage. If `False`, raise an `IntegrityError` when
+ attempting to add a message with an existing ID.
+
+ Raises:
+ `IntegrityError`:
+ If a message with the same ID already exists in the storage
+ and `skip_duplicated` is set to `False`.
+ """
+ if memories is None:
+ return
+
+ # Type checking
+ if isinstance(memories, Msg):
+ memories = [memories]
+ elif not (
+ isinstance(memories, list)
+ and all(isinstance(_, Msg) for _ in memories)
+ ):
+ raise TypeError(
+ "The 'memories' parameter must be a Msg instance or a list of "
+ f"Msg instances, but got {type(memories)}.",
+ )
+
+ if isinstance(marks, str):
+ marks = [marks]
+ elif marks is not None and not (
+ isinstance(marks, list) and all(isinstance(m, str) for m in marks)
+ ):
+ raise TypeError(
+ "The 'marks' parameter must be a string or a list of strings, "
+ f"but got {type(marks)}.",
+ )
+
+ # Create table if not exists
+ await self._create_table()
+
+ # If skip_duplicated is True, filter out existing messages
+ messages_to_add = memories
+ if skip_duplicated:
+ existing_msg_ids = set()
+ result = await self.session.execute(
+ select(self.MessageTable.id).filter(
+ self.MessageTable.id.in_(
+ [self._make_message_id(m.id) for m in memories],
+ ),
+ ),
+ )
+ existing_msg_ids = {row[0] for row in result.fetchall()}
+
+ messages_to_add = [
+ m
+ for m in memories
+ if self._make_message_id(m.id) not in existing_msg_ids
+ ]
+
+ # If all messages are duplicates, return early
+ if not messages_to_add:
+ return
+
+ # Get the starting index once to avoid race conditions
+ start_index = await self._get_next_index()
+
+ # Add messages to message table
+ for i, m in enumerate(messages_to_add):
+ message_record = self.MessageTable(
+ id=self._make_message_id(m.id),
+ msg=m.to_dict(),
+ session_id=self.session_id,
+ index=start_index + i,
+ )
+ self.session.add(message_record)
+
+ # Create mark records if marks are provided (use bulk insert)
+ if marks:
+ mark_records = [
+ {"msg_id": self._make_message_id(msg.id), "mark": mark}
+ for msg in messages_to_add
+ for mark in marks
+ ]
+ if mark_records:
+ if skip_duplicated:
+ # Query existing mark combinations to avoid duplicates
+ result = await self.session.execute(
+ select(
+ self.MessageMarkTable.msg_id,
+ self.MessageMarkTable.mark,
+ ),
+ )
+ existing_marks = {
+ (row[0], row[1]) for row in result.fetchall()
+ }
+
+ # Filter out existing mark combinations
+ mark_records = [
+ r
+ for r in mark_records
+ if (r["msg_id"], r["mark"]) not in existing_marks
+ ]
+
+ if mark_records:
+ await self.session.run_sync(
+ lambda session: session.bulk_insert_mappings(
+ self.MessageMarkTable,
+ mark_records,
+ ),
+ )
+
+ await self.session.commit()
+
+ async def _get_next_index(self) -> int:
+ """Get the next index for a new message in the current session.
+
+ Returns:
+ `int`:
+ The next index value.
+ """
+ result = await self.session.execute(
+ select(self.MessageTable.index)
+ .filter(self.MessageTable.session_id == self.session_id)
+ .order_by(self.MessageTable.index.desc())
+ .limit(1),
+ )
+ max_index = result.scalar_one_or_none()
+ return (max_index + 1) if max_index is not None else 0
+
+ async def size(self) -> int:
+ """Get the size of the messages in the storage."""
+ result = await self.session.execute(
+ select(func.count(self.MessageTable.id)).filter(
+ self.MessageTable.session_id == self.session_id,
+ ),
+ )
+ return result.scalar_one()
+
+ async def clear(self) -> None:
+ """Clear all messages from the storage."""
+ # Delete all marks for messages in this session
+ await self.session.execute(
+ delete(self.MessageMarkTable).where(
+ self.MessageMarkTable.msg_id.in_(
+ select(self.MessageTable.id).filter(
+ self.MessageTable.session_id == self.session_id,
+ ),
+ ),
+ ),
+ )
+
+ # Then delete all messages
+ await self.session.execute(
+ delete(self.MessageTable).filter(
+ self.MessageTable.session_id == self.session_id,
+ ),
+ )
+
+ await self.session.commit()
+
+ async def delete_by_mark(
+ self,
+ mark: str | list[str],
+ **kwargs: Any,
+ ) -> int:
+ """Remove messages from the storage by their marks.
+
+ Args:
+ mark (`str | list[str]`):
+ The mark(s) of the messages to be removed.
+
+ Returns:
+ `int`:
+ The number of messages removed.
+ """
+ if isinstance(mark, str):
+ mark = [mark]
+
+ # First, find message IDs that have the specified marks
+ query = (
+ select(self.MessageTable.id)
+ .join(
+ self.MessageMarkTable,
+ self.MessageTable.id == self.MessageMarkTable.msg_id,
+ )
+ .filter(
+ self.MessageTable.session_id == self.session_id,
+ self.MessageMarkTable.mark.in_(mark),
+ )
+ )
+
+ result = await self.session.execute(query)
+ msg_ids = [row[0] for row in result.all()]
+
+ if not msg_ids:
+ return 0
+
+ # Store the count before deletion
+ deleted_count = len(msg_ids)
+
+ # Delete marks first
+ await self.session.execute(
+ delete(self.MessageMarkTable).filter(
+ self.MessageMarkTable.msg_id.in_(msg_ids),
+ ),
+ )
+
+ # Then delete the messages
+ await self.session.execute(
+ delete(self.MessageTable).filter(
+ self.MessageTable.session_id == self.session_id,
+ self.MessageTable.id.in_(msg_ids),
+ ),
+ )
+
+ await self.session.commit()
+ return deleted_count
+
+ async def delete(
+ self,
+ msg_ids: list[str],
+ **kwargs: Any,
+ ) -> int:
+ """Remove message(s) from the storage by their IDs.
+
+ .. note:: Although MessageMarkTable has CASCADE delete on foreign key,
+ we explicitly delete marks first for reliability across all database
+ engines and configurations. SQLAlchemy's bulk delete bypasses
+ ORM-level cascades, and SQLite requires foreign keys to be
+ explicitly enabled.
+
+ Args:
+ msg_ids (`list[str]`):
+ The list of message IDs to be removed.
+
+ Returns:
+ `int`:
+ The number of messages removed.
+ """
+ # Convert to composite keys
+ composite_ids = [self._make_message_id(msg_id) for msg_id in msg_ids]
+
+ if not composite_ids:
+ return 0
+
+ # Store the count before deletion
+ deleted_count = len(composite_ids)
+
+ # Delete related marks first (explicit cleanup for reliability)
+ await self.session.execute(
+ delete(self.MessageMarkTable).filter(
+ self.MessageMarkTable.msg_id.in_(composite_ids),
+ ),
+ )
+
+ # Then delete the messages
+ await self.session.execute(
+ delete(self.MessageTable).filter(
+ self.MessageTable.session_id == self.session_id,
+ self.MessageTable.id.in_(composite_ids),
+ ),
+ )
+
+ await self.session.commit()
+ return deleted_count
+
+ async def update_messages_mark(
+ self,
+ new_mark: str | None,
+ old_mark: str | None = None,
+ msg_ids: list[str] | None = None,
+ ) -> int:
+ """A unified method to update marks of messages in the storage (add,
+ remove, or change marks).
+
+ - If `msg_ids` is provided, the update will be applied to the messages
+ with the specified IDs.
+ - If `old_mark` is provided, the update will be applied to the
+ messages with the specified old mark. Otherwise, the `new_mark` will
+ be added to all messages (or those filtered by `msg_ids`).
+ - If `new_mark` is `None`, the mark will be removed from the messages.
+
+ Args:
+ new_mark (`str | None`, optional):
+ The new mark to set for the messages. If `None`, the mark
+ will be removed.
+ old_mark (`str | None`, optional):
+ The old mark to filter messages. If `None`, this constraint
+ is ignored.
+ msg_ids (`list[str] | None`, optional):
+ The list of message IDs to be updated. If `None`, this
+ constraint is ignored.
+
+ Returns:
+ `int`:
+ The number of messages updated.
+ """
+
+ # Type checking
+ if new_mark is not None and not isinstance(new_mark, str):
+ raise ValueError(
+ f"The 'new_mark' parameter must be a string or None, "
+ f"but got {type(new_mark)}.",
+ )
+
+ if old_mark is not None and not isinstance(old_mark, str):
+ raise ValueError(
+ f"The 'old_mark' parameter must be a string or None, "
+ f"but got {type(old_mark)}.",
+ )
+
+ if msg_ids is not None and not (
+ isinstance(msg_ids, list)
+ and all(isinstance(_, str) for _ in msg_ids)
+ ):
+ raise ValueError(
+ f"The 'msg_ids' parameter must be a list of strings or None, "
+ f"but got {type(msg_ids)}.",
+ )
+
+ # First obtain the message ids that belong to this session
+ query = select(self.MessageTable).filter(
+ self.MessageTable.session_id == self.session_id,
+ )
+
+ # Filter by msg_ids if provided
+ if msg_ids is not None:
+ # Convert to composite keys
+ composite_ids = [
+ self._make_message_id(msg_id) for msg_id in msg_ids
+ ]
+ query = query.filter(self.MessageTable.id.in_(composite_ids))
+
+ # Filter by old_mark if provided
+ if old_mark is not None:
+ query = query.join(
+ self.MessageMarkTable,
+ self.MessageTable.id == self.MessageMarkTable.msg_id,
+ ).filter(self.MessageMarkTable.mark == old_mark)
+
+ # Obtain the message records
+ result = await self.session.execute(query)
+ msg_ids = [str(_.id) for _ in result.scalars().all()]
+
+ # Return early if no messages found
+ if not msg_ids:
+ return 0
+
+ if new_mark:
+ if old_mark:
+ # Replace old_mark with new_mark
+ return await self._replace_message_mark(
+ msg_ids=msg_ids,
+ old_mark=old_mark,
+ new_mark=new_mark,
+ )
+
+ # Add new_mark to the messages
+ return await self._add_message_mark(
+ msg_ids=msg_ids,
+ mark=new_mark,
+ )
+
+ # Remove all marks from the messages
+ return await self._remove_message_mark(
+ msg_ids=msg_ids,
+ old_mark=old_mark,
+ )
+
+ async def _replace_message_mark(
+ self,
+ msg_ids: list[str],
+ old_mark: str,
+ new_mark: str,
+ ) -> int:
+ """Replace the old mark with the new mark for the given messages by
+ updating records in the message_mark table.
+
+ Args:
+ msg_ids (`list[str]`):
+ The list of message IDs to be updated.
+ old_mark (`str`):
+ The old mark to be replaced.
+ new_mark (`str`):
+ The new mark to be set.
+
+ Returns:
+ `int`:
+ The number of messages updated.
+ """
+
+ await self.session.execute(
+ update(self.MessageMarkTable)
+ .filter(
+ self.MessageMarkTable.msg_id.in_(msg_ids),
+ self.MessageMarkTable.mark == old_mark,
+ )
+ .values(mark=new_mark),
+ )
+ await self.session.commit()
+ return len(msg_ids)
+
+ async def _add_message_mark(self, msg_ids: list[str], mark: str) -> int:
+ """Mark the messages with the given mark by adding records to the
+ message_mark table.
+
+ Args:
+ msg_ids (`list[str]`):
+ The list of message IDs to be marked.
+ mark (`str`):
+ The mark to be added to the messages.
+
+ Returns:
+ `int`:
+ The number of messages marked.
+ """
+ # Use bulk insert for better performance
+ mark_records = [{"msg_id": msg_id, "mark": mark} for msg_id in msg_ids]
+
+ if mark_records:
+ await self.session.run_sync(
+ lambda session: session.bulk_insert_mappings(
+ self.MessageMarkTable,
+ mark_records,
+ ),
+ )
+
+ await self.session.commit()
+ return len(msg_ids)
+
+ async def _remove_message_mark(
+ self,
+ msg_ids: list[str],
+ old_mark: str | None,
+ ) -> int:
+ """Remove marks from the messages by deleting records from the
+ message_mark table.
+
+ Args:
+ msg_ids (`list[str]`):
+ The list of message IDs to be unmarked.
+ old_mark (`str | None`):
+ The old mark to be removed. If `None`, all marks will be
+ removed from the messages.
+
+ Returns:
+ `int`:
+ The number of messages unmarked.
+ """
+ delete_query = delete(self.MessageMarkTable).filter(
+ self.MessageMarkTable.msg_id.in_(msg_ids),
+ )
+
+ if old_mark:
+ delete_query = delete_query.filter(
+ self.MessageMarkTable.mark == old_mark,
+ )
+
+ await self.session.execute(delete_query)
+ await self.session.commit()
+ return len(msg_ids)
+
+ async def close(self) -> None:
+ """Close the database session."""
+ if self._db_session and self._db_session.is_active:
+ await self._db_session.close()
+
+ self._db_session = None
+ self._initialized = False
+
+ async def __aenter__(self) -> "AsyncSQLAlchemyMemory":
+ """Enter the async context manager.
+
+ Returns:
+ `AsyncSQLAlchemyMemory`:
+ The memory instance itself.
+ """
+ return self
+
+ async def __aexit__(
+ self,
+ exc_type: type[BaseException] | None,
+ exc_value: BaseException | None,
+ traceback: Any,
+ ) -> None:
+ """Exit the async context manager and close the session.
+
+ Args:
+ exc_type (`type[BaseException] | None`):
+ The exception type if an exception was raised.
+ exc_value (`BaseException | None`):
+ The exception instance if an exception was raised.
+ traceback (`Any`):
+ The traceback object if an exception was raised.
+ """
+ await self.close()
diff --git a/src/agentscope/token/__init__.py b/src/agentscope/token/__init__.py
index 6c0397fd6..9533441e9 100644
--- a/src/agentscope/token/__init__.py
+++ b/src/agentscope/token/__init__.py
@@ -6,9 +6,12 @@ from ._gemini_token_counter import GeminiTokenCounter
from ._openai_token_counter import OpenAITokenCounter
from ._anthropic_token_counter import AnthropicTokenCounter
from ._huggingface_token_counter import HuggingFaceTokenCounter
+from ._char_token_counter import CharTokenCounter
+
__all__ = [
"TokenCounterBase",
+ "CharTokenCounter",
"GeminiTokenCounter",
"OpenAITokenCounter",
"AnthropicTokenCounter",
diff --git a/src/agentscope/token/_char_token_counter.py b/src/agentscope/token/_char_token_counter.py
new file mode 100644
index 000000000..6d4b227cd
--- /dev/null
+++ b/src/agentscope/token/_char_token_counter.py
@@ -0,0 +1,43 @@
+# -*- coding: utf-8 -*-
+"""A simple character-based token counter implementation."""
+from typing import Any
+
+from ._token_base import TokenCounterBase
+
+
+class CharTokenCounter(TokenCounterBase):
+ """A very simple implementation that counts tokens based on character
+ length.
+
+ .. note:: This counter does not handle multi-modal data well, as base64
+ encoding can significantly increase character count.
+
+ """
+
+ async def count(
+ self,
+ messages: list[dict],
+ tools: list[dict] | None = None,
+ **kwargs: Any,
+ ) -> int:
+ """Count the number of tokens in the messages based on the characters
+
+ Args:
+ messages (`list[dict]`):
+ The list of messages to be counted.
+ tools (`list[dict] | None`, *optional*):
+ The list of tools, not used in this counter.
+
+ Returns:
+ `int`:
+ The total number of tokens counted.
+ """
+ texts = []
+ for msg in messages:
+ texts.append(str(msg))
+
+ if tools:
+ texts.append(str(tools))
+
+ text = "\n".join(texts)
+ return len(text)
diff --git a/src/agentscope/token/_huggingface_token_counter.py b/src/agentscope/token/_huggingface_token_counter.py
index 74350400a..96b3317d6 100644
--- a/src/agentscope/token/_huggingface_token_counter.py
+++ b/src/agentscope/token/_huggingface_token_counter.py
@@ -71,6 +71,7 @@ class HuggingFaceTokenCounter(TokenCounterBase):
The additional keyword arguments that will be passed to the
tokenizer, e.g. `chat_template`, `padding`, etc.
"""
+
tokenized_msgs = self.tokenizer.apply_chat_template(
messages,
add_generation_prompt=False,
diff --git a/tests/memory_compression_test.py b/tests/memory_compression_test.py
new file mode 100644
index 000000000..a4623d39a
--- /dev/null
+++ b/tests/memory_compression_test.py
@@ -0,0 +1,183 @@
+# -*- coding: utf-8 -*-
+# pylint: disable=protected-access
+"""The unittest for memory compression."""
+from typing import Any
+from unittest import IsolatedAsyncioTestCase
+
+from agentscope.agent import ReActAgent
+from agentscope.formatter import FormatterBase
+from agentscope.message import Msg, TextBlock, ToolUseBlock, ToolResultBlock
+from agentscope.model import ChatModelBase, ChatResponse
+from agentscope.token import CharTokenCounter
+
+
+class MockChatModel(ChatModelBase):
+ """A mock chat model for testing purposes."""
+
+ async def __call__(
+ self,
+ messages: list[dict],
+ **kwargs: Any,
+ ) -> ChatResponse:
+ """Mock the model's response."""
+ if [_["id"] for _ in messages[1:-1]] != [str(_) for _ in range(3)]:
+ raise ValueError("Unexpected messages input.")
+
+ if messages[-1]["content"] != (
+ "<system-hint>You have been working on the task described above "
+ "but have not yet completed it. Now write a continuation summary "
+ "that will allow you to resume work efficiently in a future "
+ "context window where the conversation history will be replaced "
+ "with this summary. Your summary should be structured, concise, "
+ "and actionable.</system-hint>"
+ ):
+ raise ValueError("Unexpected final message content.")
+
+ return ChatResponse(
+ content=[],
+ metadata={
+ "task_overview": "This is a compressed summary.",
+ "current_state": "In progress",
+ "important_discoveries": "N/A",
+ "next_steps": "N/A",
+ "context_to_preserve": "N/A",
+ },
+ )
+
+
+class MockFormatter(FormatterBase):
+ """A mock formatter for testing purposes."""
+
+ async def format(self, msgs: list[Msg], **kwargs: Any) -> list[dict]:
+ """Mock the formatting of messages.
+
+ Args:
+ msgs (`list[Msg]`):
+ The list of messages to format.
+
+ Returns:
+ `list[dict]`:
+ The formatted messages.
+ """
+ return [_.to_dict() for _ in msgs]
+
+
+class MemoryCompressionTest(IsolatedAsyncioTestCase):
+ """The unittest for memory compression."""
+
+ async def test_memory_compression(self) -> None:
+ """Test the memory compression functionality."""
+ agent = ReActAgent(
+ name="Friday",
+ sys_prompt="You are a helpful assistant.",
+ model=MockChatModel(model_name="mock-model", stream=False),
+ formatter=MockFormatter(),
+ compression_config=ReActAgent.CompressionConfig(
+ enable=True,
+ trigger_threshold=100,
+ agent_token_counter=CharTokenCounter(),
+ keep_recent=1,
+ ),
+ )
+
+ msgs = [
+ Msg("user", "This is a test message 1.", "user"),
+ Msg("assistant", "This is a test message 2.", "assistant"),
+ Msg("assistant", "This is a test message 3.", "assistant"),
+ Msg(
+ "assistant",
+ [
+ TextBlock(
+ type="text",
+ text="This is a test message 3.",
+ ),
+ ToolUseBlock(
+ id="id1",
+ type="tool_use",
+ name="test_tool",
+ input={"param": "value"},
+ ),
+ ],
+ "assistant",
+ ),
+ Msg(
+ "system",
+ [
+ ToolResultBlock(
+ id="id1",
+ type="tool_result",
+ name="test_tool",
+ output="This is a test tool result.",
+ ),
+ ],
+ "system",
+ ),
+ ]
+ for i, msg in enumerate(msgs):
+ msg.id = str(i)
+
+ # Add mock messages to the agent's memory
+ await agent.memory.add(memories=msgs[0])
+
+ # Manually trigger memory compression
+ await agent._compress_memory_if_needed()
+
+ # The memory shouldn't be compressed yet
+ self.assertEqual(
+ agent.memory._compressed_summary,
+ "",
+ )
+ memory = await agent.memory.get_memory()
+ self.assertListEqual(
+ [_.id for _ in memory],
+ ["0"],
+ )
+
+ # Add more messages to exceed the threshold
+ await agent.memory.add(memories=msgs[1:])
+ await agent._compress_memory_if_needed()
+
+ self.assertEqual(
+ agent.memory._compressed_summary,
+ """<system-info>Here is a summary of your previous work
+# Task Overview
+This is a compressed summary.
+
+# Current State
+In progress
+
+# Important Discoveries
+N/A
+
+# Next Steps
+N/A
+
+# Context to Preserve
+N/A</system-info>""",
+ )
+
+ # Get all the memory including compressed
+ memory = await agent.memory.get_memory()
+ self.assertEqual(
+ [_.id for _ in memory[1:]],
+ [str(_) for _ in range(5)],
+ )
+
+ # Test get the uncompressed memory
+ memory = await agent.memory.get_memory(
+ exclude_mark="compressed",
+ )
+ self.assertEqual(
+ [_.id for _ in memory[1:]],
+ ["3", "4"],
+ )
+
+ # Test the prepend_summary=False option
+ memory = await agent.memory.get_memory(
+ exclude_mark="compressed",
+ prepend_summary=False,
+ )
+ self.assertListEqual(
+ [_.id for _ in memory],
+ ["3", "4"],
+ )
diff --git a/tests/memory_test.py b/tests/memory_test.py
new file mode 100644
index 000000000..a28d22e8d
--- /dev/null
+++ b/tests/memory_test.py
@@ -0,0 +1,570 @@
+# -*- coding: utf-8 -*-
+"""The short-term memory tests."""
+from unittest.async_case import IsolatedAsyncioTestCase
+
+from sqlalchemy.ext.asyncio import create_async_engine
+
+from agentscope.memory import (
+ MemoryBase,
+ InMemoryMemory,
+ AsyncSQLAlchemyMemory,
+ RedisMemory,
+)
+from agentscope.message import Msg
+
+
+class ShortTermMemoryTest(IsolatedAsyncioTestCase):
+ """The short-term memory tests."""
+
+ memory: MemoryBase
+ """The test memory instance."""
+
+ memory_session: MemoryBase
+ """The test memory instance for different session."""
+
+ memory_user: MemoryBase
+ """The test memory instance for different user."""
+
+ async def asyncSetUp(self) -> None:
+ """Set up the memory instance for testing."""
+ self.msgs = [
+ Msg("user", "0", "user"),
+ Msg("user", "1", "user"),
+ Msg("assistant", "2", "assistant"),
+ Msg("system", "3", "system"),
+ Msg("user", "4", "user"),
+ Msg("assistant", "5", "assistant"),
+ Msg("system", "6", "system"),
+ Msg("user", "7", "user"),
+ Msg("assistant", "8", "assistant"),
+ Msg("system", "9", "system"),
+ ]
+ for i, msg in enumerate(self.msgs):
+ msg.id = str(i)
+
+ async def _basic_tests(self) -> None:
+ """Test the basic functionalities of the short-term memory."""
+ # test at the beginning
+ self.assertIsInstance(await self.memory.get_memory(), list)
+ self.assertEqual(
+ len(await self.memory.get_memory()),
+ 0,
+ )
+ self.assertEqual(
+ await self.memory.size(),
+ 0,
+ )
+
+ await self.memory.update_compressed_summary("abc")
+ self.assertEqual(
+ len(await self.memory.get_memory()),
+ 1,
+ )
+
+ await self.memory.update_compressed_summary("")
+ self.assertEqual(
+ len(await self.memory.get_memory()),
+ 0,
+ )
+
+ # test adding messages
+ await self.memory.add(self.msgs[:5])
+ msgs = await self.memory.get_memory()
+ self.assertListEqual(
+ [_.id for _ in msgs],
+ [str(_) for _ in range(5)],
+ )
+
+ # test deleting messages by id
+ await self.memory.delete(msg_ids=["2", "4"])
+ msgs = await self.memory.get_memory()
+ self.assertListEqual(
+ [_.id for _ in msgs],
+ ["0", "1", "3"],
+ )
+ self.assertEqual(
+ await self.memory.size(),
+ 3,
+ )
+
+ # test adding more messages
+ await self.memory.add(self.msgs[5:])
+ msgs = await self.memory.get_memory()
+ self.assertListEqual(
+ [_.id for _ in msgs],
+ [str(_) for _ in [0, 1, 3, 5, 6, 7, 8, 9]],
+ )
+
+ # test clearing memory
+ await self.memory.clear()
+ self.assertEqual(
+ await self.memory.size(),
+ 0,
+ )
+
+ async def _mark_tests(self) -> None:
+ """Test the mark-related functionalities of the short-term memory."""
+ # test getting messages by nonexistent mark
+ await self.memory.add(self.msgs[:5])
+ self.assertListEqual(
+ [_.id for _ in await self.memory.get_memory()],
+ [str(_) for _ in range(5)],
+ )
+ self.assertEqual(
+ len(await self.memory.get_memory(mark="nonexistent")),
+ 0,
+ )
+
+ # test adding marked messages
+ await self.memory.add(
+ self.msgs[5:7],
+ marks=["important", "todo"],
+ )
+ await self.memory.add(self.msgs[7:], marks="important")
+
+ # Test get messages by "important" mark
+ msgs = await self.memory.get_memory(mark="important")
+ self.assertListEqual(
+ [_.id for _ in msgs],
+ [str(_) for _ in range(5, 10)],
+ )
+
+ # Test get messages by "todo" mark
+ msgs = await self.memory.get_memory(mark="todo")
+ self.assertListEqual(
+ [_.id for _ in msgs],
+ [str(_) for _ in range(5, 7)],
+ )
+
+ # Test get messages excluding "todo" mark
+ msgs = await self.memory.get_memory(exclude_mark="todo")
+ self.assertListEqual(
+ [_.id for _ in msgs],
+ [str(_) for _ in [0, 1, 2, 3, 4, 7, 8, 9]],
+ )
+
+ msgs = await self.memory.get_memory(exclude_mark="important")
+ self.assertListEqual(
+ [_.id for _ in msgs],
+ [str(_) for _ in [0, 1, 2, 3, 4]],
+ )
+
+ # add unmarked messages
+ msgs = [
+ Msg("user", "10", "user"),
+ Msg("user", "11", "user"),
+ ]
+ msgs[0].id = "10"
+ msgs[1].id = "11"
+ await self.memory.add(msgs)
+ msgs = await self.memory.get_memory()
+ self.assertListEqual(
+ [_.id for _ in msgs],
+ [str(_) for _ in range(12)],
+ )
+
+ # test marking messages
+ await self.memory.update_messages_mark(
+ msg_ids=["0", "1", "2"],
+ new_mark="review",
+ )
+ msgs = await self.memory.get_memory(mark="review")
+ self.assertListEqual(
+ [_.id for _ in msgs],
+ ["0", "1", "2"],
+ )
+
+ # test adding multiple marks to messages
+ await self.memory.update_messages_mark(
+ msg_ids=["6", "7", "9"],
+ new_mark="unread",
+ )
+ msgs = await self.memory.get_memory(mark="unread")
+ self.assertListEqual(
+ [_.id for _ in msgs],
+ [str(_) for _ in [6, 7, 9]],
+ )
+ msgs = await self.memory.get_memory(mark="important")
+ self.assertListEqual(
+ [_.id for _ in msgs],
+ [str(_) for _ in [5, 6, 7, 8, 9]],
+ )
+
+ # test unmarking messages
+ await self.memory.update_messages_mark(
+ msg_ids=["5", "7"],
+ old_mark="important",
+ new_mark=None,
+ )
+ self.assertListEqual(
+ [_.id for _ in await self.memory.get_memory(mark="important")],
+ [str(_) for _ in [6, 8, 9]],
+ )
+
+ # test updating marks
+ await self.memory.update_messages_mark(
+ msg_ids=["6", "8"],
+ old_mark="important",
+ new_mark="archived",
+ )
+ self.assertListEqual(
+ [_.id for _ in await self.memory.get_memory(mark="important")],
+ ["9"],
+ )
+ self.assertListEqual(
+ [_.id for _ in await self.memory.get_memory(mark="archived")],
+ [str(_) for _ in [6, 8]],
+ )
+
+ # test deleting messages by mark
+ await self.memory.delete_by_mark("important")
+ msgs = await self.memory.get_memory(mark="important")
+ self.assertListEqual(
+ [_.id for _ in msgs],
+ [],
+ )
+ msgs = await self.memory.get_memory()
+ self.assertListEqual(
+ [_.id for _ in msgs],
+ [str(_) for _ in [0, 1, 2, 3, 4, 5, 6, 7, 8, 10, 11]],
+ )
+
+ await self.memory.delete_by_mark(["review", "archived"])
+ msgs = await self.memory.get_memory()
+ self.assertListEqual(
+ [_.id for _ in msgs],
+ [str(_) for _ in [3, 4, 5, 7, 10, 11]],
+ )
+
+ await self.memory.clear()
+ msgs = await self.memory.get_memory()
+ self.assertEqual(
+ len(msgs),
+ 0,
+ )
+
+ async def _multi_tenant_tests(self) -> None:
+ """Test the multi-tenant functionalities of the short-term memory."""
+ await self.memory.add(self.msgs[:8])
+ msgs = await self.memory.get_memory()
+ self.assertEqual(
+ [_.id for _ in msgs],
+ [str(_) for _ in range(8)],
+ )
+
+ # Add some msgs with overlapping ids to different users' memory
+ await self.memory_user.add(self.msgs[3:])
+ self.assertEqual(
+ [_.id for _ in await self.memory_user.get_memory()],
+ [str(_) for _ in [3, 4, 5, 6, 7, 8, 9]],
+ )
+
+ # Mark messages
+ await self.memory.update_messages_mark(
+ new_mark="shared",
+ msg_ids=["5", "6", "7"],
+ )
+
+ # mark messages with same ids with different mark for different users
+ await self.memory_user.update_messages_mark(
+ new_mark="shared_user",
+ msg_ids=["6", "7", "8", "9"],
+ )
+
+ # Test if the marks are isolated between different users
+ msgs = await self.memory.get_memory(
+ mark="shared",
+ )
+ self.assertListEqual(
+ [_.id for _ in msgs],
+ [str(_) for _ in [5, 6, 7]],
+ )
+ msgs = await self.memory.get_memory(
+ mark="shared_user",
+ )
+ self.assertEqual(
+ len(msgs),
+ 0,
+ )
+
+ msgs = await self.memory_user.get_memory(
+ mark="shared_user",
+ )
+ self.assertListEqual(
+ [_.id for _ in msgs],
+ [str(_) for _ in [6, 7, 8, 9]],
+ )
+ msgs = await self.memory_user.get_memory(
+ mark="shared",
+ )
+ self.assertEqual(
+ len(msgs),
+ 0,
+ )
+
+ # Test delete operation is isolated between different sessions
+ await self.memory.delete(
+ msg_ids=["6", "7"],
+ )
+ msgs = await self.memory.get_memory()
+ self.assertListEqual(
+ [_.id for _ in msgs],
+ [str(_) for _ in range(6)],
+ )
+ msgs = await self.memory_user.get_memory()
+ self.assertListEqual(
+ [_.id for _ in msgs],
+ [str(_) for _ in range(3, 10)],
+ )
+
+ # Test delete operation by mark is isolated between different sessions
+ await self.memory_user.delete_by_mark("shared")
+ msgs = await self.memory_user.get_memory()
+ self.assertListEqual(
+ [_.id for _ in msgs],
+ [str(_) for _ in range(3, 10)],
+ )
+ msgs = await self.memory.get_memory()
+ self.assertListEqual(
+ [_.id for _ in msgs],
+ [str(_) for _ in range(6)],
+ )
+
+ # Clean up
+ await self.memory.clear()
+ await self.memory_user.clear()
+
+ async def _multi_session_tests(self) -> None:
+ """Test the multi-session functionalities of the short-term memory."""
+ await self.memory.add(self.msgs[:8])
+ msgs = await self.memory.get_memory()
+ self.assertEqual(
+ [_.id for _ in msgs],
+ [str(_) for _ in range(8)],
+ )
+
+ # Add some msgs with overlapping ids to different session's memory
+ await self.memory_session.add(self.msgs[3:])
+ self.assertEqual(
+ [_.id for _ in await self.memory_session.get_memory()],
+ [str(_) for _ in [3, 4, 5, 6, 7, 8, 9]],
+ )
+
+ # Mark messages in first session
+ await self.memory.update_messages_mark(
+ new_mark="session1_mark",
+ msg_ids=["5", "6", "7"],
+ )
+
+ # mark messages with same ids with different mark for different session
+ await self.memory_session.update_messages_mark(
+ new_mark="session2_mark",
+ msg_ids=["6", "7", "8", "9"],
+ )
+
+ # Test if the marks are isolated between different sessions
+ msgs = await self.memory.get_memory(
+ mark="session1_mark",
+ )
+ self.assertListEqual(
+ [_.id for _ in msgs],
+ [str(_) for _ in [5, 6, 7]],
+ )
+ msgs = await self.memory.get_memory(
+ mark="session2_mark",
+ )
+ self.assertEqual(
+ len(msgs),
+ 0,
+ )
+
+ msgs = await self.memory_session.get_memory(
+ mark="session2_mark",
+ )
+ self.assertListEqual(
+ [_.id for _ in msgs],
+ [str(_) for _ in [6, 7, 8, 9]],
+ )
+ msgs = await self.memory_session.get_memory(
+ mark="session1_mark",
+ )
+ self.assertEqual(
+ len(msgs),
+ 0,
+ )
+
+ # Test delete operation is isolated between different sessions
+ await self.memory.delete(
+ msg_ids=["6", "7"],
+ )
+ msgs = await self.memory.get_memory()
+ self.assertListEqual(
+ [_.id for _ in msgs],
+ [str(_) for _ in range(6)],
+ )
+ msgs = await self.memory_session.get_memory()
+ self.assertListEqual(
+ [_.id for _ in msgs],
+ [str(_) for _ in range(3, 10)],
+ )
+
+ # Test delete operation by mark is isolated between different sessions
+ await self.memory_session.delete_by_mark("session1_mark")
+ msgs = await self.memory_session.get_memory()
+ self.assertListEqual(
+ [_.id for _ in msgs],
+ [str(_) for _ in range(3, 10)],
+ )
+ msgs = await self.memory.get_memory()
+ self.assertListEqual(
+ [_.id for _ in msgs],
+ [str(_) for _ in range(6)],
+ )
+
+ # Clean up
+ await self.memory.clear()
+ await self.memory_session.clear()
+
+ async def _test_add_duplicated_msgs(self) -> None:
+ """Test adding duplicated messages to the memory."""
+ await self.memory.add(self.msgs[:8])
+ await self.memory.add(self.msgs[5:])
+
+ msgs = await self.memory.get_memory()
+ self.assertListEqual(
+ [_.id for _ in msgs],
+ [str(_) for _ in range(10)],
+ )
+
+ await self.memory.clear()
+
+ async def _test_delete_nonexistent_msg(self) -> None:
+ """Test deleting nonexistent messages from the memory."""
+ await self.memory.add(self.msgs[:5])
+ await self.memory.delete(msg_ids=["nonexistent_id"])
+ msgs = await self.memory.get_memory()
+ self.assertListEqual(
+ [_.id for _ in msgs],
+ [str(_) for _ in range(5)],
+ )
+
+ await self.memory.clear()
+
+ async def asyncTearDown(self) -> None:
+ """Clean up after unittests"""
+ await self.memory.clear()
+ # Close the session or connection if applicable
+ if hasattr(self.memory, "close"):
+ await self.memory.close()
+
+
+class InMemoryMemoryTest(ShortTermMemoryTest):
+ """The in-memory short-term memory tests."""
+
+ async def asyncSetUp(self) -> None:
+ """Set up the in-memory memory instance for testing."""
+ await super().asyncSetUp()
+ self.memory = InMemoryMemory()
+
+ async def test_memory(self) -> None:
+ """Test the in-memory memory functionalities."""
+ await self._basic_tests()
+ await self._mark_tests()
+ await self._test_add_duplicated_msgs()
+ await self._test_delete_nonexistent_msg()
+
+
+class AsyncSQLAlchemyMemoryTest(ShortTermMemoryTest):
+ """The SQLAlchemy short-term memory tests."""
+
+ async def asyncSetUp(self) -> None:
+ """Set up the SQLAlchemy memory instance for testing."""
+ await super().asyncSetUp()
+ self.engine = create_async_engine(
+ # in-memory SQLite database for testing
+ url="sqlite+aiosqlite:///:memory:",
+ )
+ self.memory = AsyncSQLAlchemyMemory(
+ session_id="session_1",
+ user_id="user_1",
+ engine_or_session=self.engine,
+ )
+
+ self.memory_session = AsyncSQLAlchemyMemory(
+ session_id="session_2",
+ user_id="user_1",
+ engine_or_session=self.engine,
+ )
+
+ self.memory_user = AsyncSQLAlchemyMemory(
+ session_id="session_2",
+ user_id="user_2",
+ engine_or_session=self.engine,
+ )
+
+ async def test_memory(self) -> None:
+ """Test the SQLAlchemy memory functionalities."""
+ await self._basic_tests()
+ await self._test_add_duplicated_msgs()
+ await self._test_delete_nonexistent_msg()
+ await self._mark_tests()
+ await self._multi_tenant_tests()
+ await self._multi_session_tests()
+
+ async def asyncTearDown(self) -> None:
+ """Clean up after unittests"""
+ await super().asyncTearDown()
+ await self.engine.dispose()
+
+
+class RedisMemoryTest(ShortTermMemoryTest):
+ """The Redis short-term memory tests."""
+
+ memory: RedisMemory
+ """The Redis memory instance."""
+
+ memory_session: RedisMemory
+ """The Redis memory instance for different session."""
+
+ memory_user: RedisMemory
+ """The Redis memory instance for different user."""
+
+ async def asyncSetUp(self) -> None:
+ """Set up the Redis memory instance for testing."""
+ await super().asyncSetUp()
+ try:
+ import fakeredis.aioredis
+ except ImportError:
+ self.skipTest(
+ "fakeredis is not installed. Install it via "
+ "'pip install fakeredis' to run this test.",
+ )
+
+ # Use fakeredis for in-memory testing without a real Redis server
+ fake_redis = fakeredis.aioredis.FakeRedis(decode_responses=True)
+ self.memory = RedisMemory(
+ user_id="user_1",
+ session_id="session_1",
+ connection_pool=fake_redis.connection_pool,
+ )
+
+ self.memory_session = RedisMemory(
+ user_id="user_1",
+ session_id="session_2",
+ connection_pool=fake_redis.connection_pool,
+ )
+
+ self.memory_user = RedisMemory(
+ user_id="user_2",
+ session_id="session_2",
+ connection_pool=fake_redis.connection_pool,
+ )
+
+ async def test_memory(self) -> None:
+ """Test the Redis memory functionalities."""
+ await self._basic_tests()
+ await self._mark_tests()
+ await self._test_add_duplicated_msgs()
+ await self._test_delete_nonexistent_msg()
+ await self._multi_tenant_tests()
+ await self._multi_session_tests()
diff --git a/tests/plan_test.py b/tests/plan_test.py
index 2baf7ad7d..f4aa06059 100644
--- a/tests/plan_test.py
+++ b/tests/plan_test.py
@@ -352,7 +352,6 @@ Subtask at index 2:
"outcome": None,
},
},
- "_reasoning_hint_msgs": {"content": []},
"name": "Friday",
"_sys_prompt": "You are a helpful assistant named Friday. ",
},
diff --git a/tests/token_char_test.py b/tests/token_char_test.py
new file mode 100644
index 000000000..16d247e7c
--- /dev/null
+++ b/tests/token_char_test.py
@@ -0,0 +1,35 @@
+# -*- coding: utf-8 -*-
+"""The unittests for char-based token counter."""
+from unittest.async_case import IsolatedAsyncioTestCase
+
+
+class CharTokenCounterTest(IsolatedAsyncioTestCase):
+ """The unittests for char-based token counter."""
+
+ async def test_count_tokens(self) -> None:
+ """Test the count_tokens method."""
+ from agentscope.token import CharTokenCounter
+
+ counter = CharTokenCounter()
+
+ messages = [
+ {
+ "role": "user",
+ "content": "This is a test string.",
+ },
+ {
+ "id": "1",
+ "name": "test_tool",
+ "type": "tool_use",
+ "input": {
+ "param1": "value1",
+ "param2": "value2",
+ },
+ },
+ ]
+ num_tokens = await counter.count(messages)
+ self.assertEqual(num_tokens, 157)
+
+ messages = []
+ num_tokens = await counter.count(messages)
+ self.assertEqual(num_tokens, 0)