DeepWiki Q&A with Code Context for Repository: agentscope-ai/agentscope

Q1

memory=InMemoryMemory(),
long_term_memory=long_term_memory, 介绍一下这两个

Answer

简要说明

  • memory=InMemoryMemory():这是短期记忆,用于在单次对话中存储和管理消息历史,支持标记(mark)过滤、压缩摘要等操作,默认使用内存中的列表存储。 agentscope:216-219 agentscope:26-27
  • long_term_memory=long_term_memory:这是长期记忆,用于跨会话的语义化记忆存储与检索,通常基于向量数据库(如 Mem0/ReMe),支持两种控制模式(agent_control/static_control/both)。 agentscope:220-224 agentscope:8-14

短期记忆(InMemoryMemory)

定义与职责

  • 存储当前对话的消息对象(Msg),提供增删改查与按标记过滤的能力。 agentscope:10-15
  • 支持压缩摘要(update_compressed_summary)以在上下文窗口接近上限时压缩旧消息。 agentscope:66-69

实现类

  • InMemoryMemory:基于内存列表的简单实现,适合开发与单进程测试。 agentscope:462-468
  • 其他实现:AsyncSQLAlchemyMemory(关系型数据库)、RedisMemory(Redis,支持多租户与 TTL)。 agentscope:28-31

使用示例

memory = InMemoryMemory()
await memory.add(Msg("user", "我喜欢住民宿", "user"))
await memory.add(Msg("system", "提示:先收集信息", "system"), marks="hint")
msgs = await memory.get_memory(mark="hint")
await memory.delete_by_mark("hint")
```agentscope:94-125 

---

## 长期记忆(LongTermMemoryBase)

### 定义与职责
- 跨会话、语义化的记忆存储与检索,通常基于向量检索(如 Mem0/ReMe)。 agentscope:8-14 
- 提供两种控制模式:
  - `static_control`:框架在每次 reply 开始时自动检索、结束时自动记录。 agentscope:528-535 
  - `agent_control`:将 `retrieve_from_memory` 与 `record_to_memory` 注册为工具,由 Agent 自主调用。 agentscope:301-308 
  - `both`:同时启用上述两种方式。 agentscope:289-296 

### 实现类
- `Mem0LongTermMemory`:基于 mem0 库的向量记忆实现。 agentscope:37-51 
- `ReMePersonalLongTermMemory`:基于 ReMe 的个人长期记忆实现,提供工具接口与直接接口。 agentscope:172-176 

### 使用示例(Mem0)
```python
long_term_memory = Mem0LongTermMemory(
    agent_name="Friday",
    user_name="user_123",
    model=DashScopeChatModel(...),
    embedding_model=DashScopeTextEmbedding(...),
)
await long_term_memory.record([Msg("user", "我喜欢住民宿", "user")])
results = await long_term_memory.retrieve([Msg("user", "我的住宿偏好", "user")])
```agentscope:37-71 

### 与 ReActAgent 集成
```python
agent = ReActAgent(
    name="Friday",
    memory=InMemoryMemory(),
    long_term_memory=long_term_memory,
    long_term_memory_mode="static_control",  # 或 "agent_control"/"both"
    ...
)
```agentscope:91-103 

---

## 对比与使用建议

| 维度 | 短期记忆(memory) | 长期记忆(long_term_memory) |
|------|-------------------|------------------------------|
| 用途 | 单次对话的消息历史与提示管理 | 跨会话的语义化记忆存储与检索 |
| 范围 | 会话内 | 跨会话、用户级 |
| 实现类 | InMemoryMemory、AsyncSQLAlchemyMemory、RedisMemory | Mem0LongTermMemory、ReMePersonalLongTermMemory 等 |
| 控制方式 | 直接调用 memory.add/get_memory/delete_by_mark 等 | static_control(自动)、agent_control(工具)、both |
| 典型场景 | 对话上下文、压缩摘要、标记过滤 | 用户偏好、长期知识、个性化记忆 |

- 开发/测试:使用 `InMemoryMemory` 作为短期记忆。 agentscope:26-27 
- 生产多租户:短期可用 `RedisMemory`,长期用 `Mem0LongTermMemory` 或 `ReMePersonalLongTermMemory`。 agentscope:28-31 
- 需要跨会话记忆:配置 `long_term_memory` 并选择合适的 `long_term_memory_mode`。 agentscope:220-237 

---

## Notes
- 短期记忆的压缩功能由 `ReActAgent` 的 `CompressionConfig` 控制,不在 `MemoryBase` 中实现。 agentscope:17-17 
- 长期记忆的两种控制模式可以共存(`both`),此时既会自动检索/记录,也会注册工具供 Agent 调用。 agentscope:289-308 
- 示例代码来自中文教程,英文教程在 `docs/tutorial/en/src/task_long_term_memory.py` 也有对应内容。 agentscope:8-14 

Wiki pages you might want to explore:
- [Memory Systems (agentscope-ai/agentscope)](/wiki/agentscope-ai/agentscope#2.6)
### Citations
**File:** src/agentscope/agent/_react_agent.py (L216-219)
```python
            memory (`MemoryBase | None`, optional):
                The memory used to store the dialogue history. If not provided,
                a default `InMemoryMemory` will be created, which stores
                messages in a list in memory.

File: src/agentscope/agent/_react_agent.py (L220-237)

            long_term_memory (`LongTermMemoryBase | None`, optional):
                The optional long-term memory, which will provide two tool
                functions: `retrieve_from_memory` and `record_to_memory`, and
                will attach the retrieved information to the system prompt
                before each reply.
            enable_meta_tool (`bool`, defaults to `False`):
                If `True`, a meta tool function `reset_equipped_tools` will be
                added to the toolkit, which allows the agent to manage its
                equipped tools dynamically.
            long_term_memory_mode (`Literal['agent_control', 'static_control',\
              'both']`, defaults to `both`):
                The mode of the long-term memory. If `agent_control`, two
                tool functions `retrieve_from_memory` and `record_to_memory`
                will be registered in the toolkit to allow the agent to
                manage the long-term memory. If `static_control`, retrieving
                and recording will happen in the beginning and end of
                each reply respectively.
            parallel_tool_calls (`bool`, defaults to `False`):

File: src/agentscope/agent/_react_agent.py (L289-308)

        self._static_control = long_term_memory and long_term_memory_mode in [
            "static_control",
            "both",
        ]
        self._agent_control = long_term_memory and long_term_memory_mode in [
            "agent_control",
            "both",
        ]

        # -------------- Tool management --------------
        # If None, a default Toolkit will be created
        self.toolkit = toolkit or Toolkit()
        if self._agent_control:
            # Adding two tool functions into the toolkit to allow self-control
            self.toolkit.register_tool_function(
                long_term_memory.record_to_memory,
            )
            self.toolkit.register_tool_function(
                long_term_memory.retrieve_from_memory,
            )

File: src/agentscope/agent/_react_agent.py (L528-535)

        if self._static_control:
            await self.long_term_memory.record(
                [
                    *await self.memory.get_memory(
                        exclude_mark=_MemoryMark.COMPRESSED,
                    ),
                ],
            )

File: docs/tutorial/zh_CN/src/task_memory.py (L10-15)

- 存储消息对象(``Msg``)
- 利用标记(mark)管理消息

**标记** 是与记忆中每条消息关联的字符串标签,可用于根据消息的上下文或目的对消息进行分类、过滤和检索。
可用于实现进阶的记忆管理功能,例如在 `ReActAgent` 类中,使用``"hint"``标签标记一次性的提示消息,
以便在使用完成后将其从记忆中删除。

File: docs/tutorial/zh_CN/src/task_memory.py (L17-17)

.. note:: AgentScope 中的记忆模块仅提供消息存储和管理的原子功能,记忆压缩等算法逻辑在 `智能体 <agent>`_ 中实现。

File: docs/tutorial/zh_CN/src/task_memory.py (L26-27)

    * - ``InMemoryMemory``
      - 简单的内存记忆存储实现。

File: docs/tutorial/zh_CN/src/task_memory.py (L28-31)

    * - ``AsyncSQLAlchemyMemory``
      - 基于异步 SQLAlchemy 的记忆存储实现,支持如 SQLite、PostgreSQL、MySQL 等多种关系数据库。
    * - ``RedisMemory``
      - 基于 Redis 的记忆存储实现。

File: docs/tutorial/zh_CN/src/task_memory.py (L66-69)

    * - ``update_compressed_summary(
            summary: str,
        ) -> None``
      - 更新存储在记忆中的摘要属性。

File: docs/tutorial/zh_CN/src/task_memory.py (L94-125)

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'的消息。")

File: docs/tutorial/zh_CN/src/task_long_term_memory.py (L8-14)

AgentScope 为长期记忆提供了一个基类 ``LongTermMemoryBase`` 和一个基于 `mem0 <https://github.com/mem0ai/mem0>`_ 的具体实现 ``Mem0LongTermMemory``。
结合 :ref:`agent` 章节中 ``ReActAgent`` 类的设计,我们提供了两种长期记忆模式:

- ``agent_control``:智能体通过工具调用自主管理长期记忆。
- ``static_control``:开发者通过编程显式控制长期记忆操作。

当然,开发者也可以使用 ``both`` 参数,将同时激活上述两种记忆管理模式。

File: docs/tutorial/zh_CN/src/task_long_term_memory.py (L37-71)

# 创建 mem0 长期记忆实例
long_term_memory = Mem0LongTermMemory(
    agent_name="Friday",
    user_name="user_123",
    model=DashScopeChatModel(
        model_name="qwen-max-latest",
        api_key=os.environ.get("DASHSCOPE_API_KEY"),
        stream=False,
    ),
    embedding_model=DashScopeTextEmbedding(
        model_name="text-embedding-v2",
        api_key=os.environ.get("DASHSCOPE_API_KEY"),
    ),
    on_disk=False,
)

# %%
# ``Mem0LongTermMemory`` 类提供了两个操作长期记忆的方法,``record`` 和 ``retrieve``。
# 它们接收消息对象的列表作为输入,分别记录和检索长期记忆中的信息。
#
# 例如下面的例子中,我们先存入用户的一条偏好,然后在长期记忆中检索相关信息。
#


# 基本使用示例
async def basic_usage():
    """基本使用示例"""
    # 记录记忆
    await long_term_memory.record([Msg("user", "我喜欢住民宿", "user")])

    # 检索记忆
    results = await long_term_memory.retrieve(
        [Msg("user", "我的住宿偏好", "user")],
    )
    print(f"检索结果: {results}")

File: docs/tutorial/zh_CN/src/task_long_term_memory.py (L91-103)

agent = ReActAgent(
    name="Friday",
    sys_prompt="你是一个具有长期记忆功能的助手。",
    model=DashScopeChatModel(
        api_key=os.environ.get("DASHSCOPE_API_KEY"),
        model_name="qwen-max-latest",
    ),
    formatter=DashScopeChatFormatter(),
    toolkit=Toolkit(),
    memory=InMemoryMemory(),
    long_term_memory=long_term_memory,
    long_term_memory_mode="static_control",  # 使用 static_control 模式
)

File: docs/tutorial/zh_CN/src/task_long_term_memory.py (L172-176)

#             result = await reme_long_term_memory.record_to_memory(
#                 thinking="用户正在分享他们的旅行偏好和习惯",
#                 content=[
#                     "我去杭州旅行时喜欢住民宿",
#                     "我喜欢早上去西湖游玩",

File: tests/memory_test.py (L462-468)

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()

File: docs/tutorial/en/src/task_long_term_memory.py (L8-14)

In AgentScope, we provide a basic class for long-term memory (``LongTermMemoryBase``) and an implementation based on the `mem0 <https://github.com/mem0ai/mem0>`_ library (``Mem0LongTermMemory``).
Together with the design of ``ReActAgent`` class in :ref:`agent` section, we provide two long-term memory modes:

- ``agent_control``: the agent autonomously manages long-term memory by tool calls, and
- ``static_control``: the developer explicitly controls long-term memory operations.

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

DeepWiki Q&A with Code Context for Repository: agentscope-ai/agentscope

Q1

on_disk=True是保存在哪

Answer

在 AgentScope 的 Mem0LongTermMemory 实现中,on_disk=True 表示将 mem0 的向量存储持久化到磁盘,默认使用 Qdrant 向量数据库的本地磁盘模式。具体来说:

  • vector_store_config 未提供时,Mem0LongTermMemory.__init__ 会创建默认的 Qdrant 配置,并从 kwargs 读取 on_disk 参数(默认为 True),然后将其传入 VectorStoreConfigconfig 字典中,从而启用磁盘持久化 agentscope:244-252 。
  • on_disk=False,则向量存储仅在内存中运行,进程结束后数据会丢失。

示例用法(显式设置):

long_term_memory = Mem0LongTermMemory(
    agent_name="Friday",
    user_name="user_123",
    model=DashScopeChatModel(...),
    embedding_model=DashScopeTextEmbedding(...),
    on_disk=False,  # 仅内存模式
)
```agentscope:41-54 

## Notes
- `on_disk` 是 mem0 向量存储的配置项,并非 AgentScope 独有。它通过 mem0 的 `VectorStoreConfig` 传递给底层向量库(默认 Qdrant)。
- 若提供自定义 `vector_store_config`,则 `on_disk` 的行为由该配置决定,`Mem0LongTermMemory` 不会覆盖它 agentscope:213-214 。

Wiki pages you might want to explore:
- [Quick Start: Building Your First Agent (agentscope-ai/agentscope)](/wiki/agentscope-ai/agentscope#1.2)
### Citations
**File:** src/agentscope/memory/_long_term_memory/_mem0/_mem0_long_term_memory.py (L213-214)
```python
            if vector_store_config is not None:
                mem0_config.vector_store = vector_store_config

File: src/agentscope/memory/_long_term_memory/_mem0/_mem0_long_term_memory.py (L244-252)

                # Use default Qdrant configuration with on-disk storage for
                # persistence set on_disk to True to enable persistence,
                # otherwise it will be in memory only
                on_disk = kwargs.get("on_disk", True)
                mem0_config.vector_store = (
                    mem0.vector_stores.configs.VectorStoreConfig(
                        config={"on_disk": on_disk},
                    )
                )

File: docs/tutorial/en/src/task_long_term_memory.py (L41-54)

long_term_memory = Mem0LongTermMemory(
    agent_name="Friday",
    user_name="user_123",
    model=DashScopeChatModel(
        model_name="qwen-max-latest",
        api_key=os.environ.get("DASHSCOPE_API_KEY"),
        stream=False,
    ),
    embedding_model=DashScopeTextEmbedding(
        model_name="text-embedding-v2",
        api_key=os.environ.get("DASHSCOPE_API_KEY"),
    ),
    on_disk=False,
)

Q2

vector_store_config怎么设置

Answer

Mem0LongTermMemory 中,vector_store_config 用于自定义 mem0 的向量存储配置(如 Qdrant、Chroma 等)。你可以传入一个 mem0 的 VectorStoreConfig 实例来覆盖默认行为。

设置方式

  • 类型mem0.vector_stores.configs.VectorStoreConfig(或其子类) agentscope:82-83 。
  • 作用:如果提供,将直接用作 mem0 的向量存储配置;否则默认使用 Qdrant 并从 kwargs 读取 on_disk(默认 True) agentscope:240-252 。

示例:自定义 Qdrant 配置

from mem0.vector_stores.configs import VectorStoreConfig

vector_store_config = VectorStoreConfig(
    provider="qdrant",
    config={
        "on_disk": True,          # 启用磁盘持久化
        "path": "./my_qdrant_db", # 本地存储路径(可选)
        "collection_name": "my_collection", # 集合名(可选)
    },
)

long_term_memory = Mem0LongTermMemory(
    agent_name="Friday",
    user_name="user_123",
    model=DashScopeChatModel(...),
    embedding_model=DashScopeTextEmbedding(...),
    vector_store_config=vector_store_config,  # 传入自定义配置
)

注意事项

  • 如果传入 vector_store_configMem0LongTermMemory 不会覆盖其内部配置(包括 on_disk) agentscope:213-214 。
  • 若不提供,则默认使用 Qdrant 并根据 on_disk 参数决定是否持久化到磁盘 agentscope:244-252 。

其他向量存储

你也可以配置其他向量存储(如 Chroma),只需在 VectorStoreConfig 中指定对应的 providerconfig 字段即可。具体配置项请参考 mem0 文档。

Notes

  • vector_store_config 是 mem0 的配置对象,并非 AgentScope 独有。其可用字段取决于所选的向量存储后端(如 Qdrant、Chroma)。
  • 示例中的 pathcollection_name 为可选字段,具体取决于向量存储后端的支持情况。

Wiki pages you might want to explore:

Citations

File: src/agentscope/memory/_long_term_memory/_mem0/_mem0_long_term_memory.py (L82-83)

        vector_store_config: VectorStoreConfig | None = None,
        mem0_config: MemoryConfig | None = None,

File: src/agentscope/memory/_long_term_memory/_mem0/_mem0_long_term_memory.py (L213-214)

            if vector_store_config is not None:
                mem0_config.vector_store = vector_store_config

File: src/agentscope/memory/_long_term_memory/_mem0/_mem0_long_term_memory.py (L240-252)

            if vector_store_config is not None:
                # Use provided vector store configuration
                mem0_config.vector_store = vector_store_config
            else:
                # Use default Qdrant configuration with on-disk storage for
                # persistence set on_disk to True to enable persistence,
                # otherwise it will be in memory only
                on_disk = kwargs.get("on_disk", True)
                mem0_config.vector_store = (
                    mem0.vector_stores.configs.VectorStoreConfig(
                        config={"on_disk": on_disk},
                    )
                )
Logo

有“AI”的1024 = 2048,欢迎大家加入2048 AI社区

更多推荐