类class
agentscope.middlewareMem0Middleware
class Mem0Middleware(MiddlewareBase)
源码Source
agentscope/middleware/_longterm_memory/_mem0/_middleware.py:86–741Mem 0 中间件,在智能体执行流程中提供横切扩展。位于 agentscope.middleware 包,继承自 MiddlewareBase。核心成员包括 on_reply、on_system_prompt、list_tools。
Two construction paths:
- Models — pass an AgentScope
chat_modelandembedding_model(optionally with a custommem0_configas base for vector store / history DB / etc.). The middleware builds an OSSAsyncMemoryinternally, wired so mem0's memory extraction and embedding both go through your AgentScope models. - Client — pass a pre-built
mem0.AsyncMemory/mem0.AsyncMemoryClientwhen you want full control (e.g. hosted Platform, sharing one mem0 across agents). Whenclientis given it takes precedence and the other backend kwargs are ignored.
Three control patterns are available via the mode parameter
("static_control" / "agent_control" / "both"); see
the constructor's mode arg for what each does.
Example (build OSS internally)::
from agentscope.middleware import Mem0Middleware
from agentscope.tool import Toolkit
mw = Mem0Middleware(
user_id="alice",
chat_model=my_chat_model,
embedding_model=my_embedding_model,
mode="both",
)
agent = Agent(
...,
toolkit=Toolkit(tools=await mw.list_tools()),
middlewares=[mw],
)
Example (hosted Platform with pre-built client)::
from agentscope.middleware import Mem0Middleware
from agentscope.tool import Toolkit
from mem0 import AsyncMemoryClient
mw = Mem0Middleware(
user_id="alice",
client=AsyncMemoryClient(api_key="m0-..."),
mode="both",
)
agent = Agent(
...,
toolkit=Toolkit(tools=await mw.list_tools()),
middlewares=[mw],
)
构造器摘要Constructor Summary
| 构造器Constructor | 说明Description |
|---|---|
def __init__(*, user_id: str, client: Mem0AsyncClient | None = None, chat_model: 'ChatModelBase | None' = None, embeddi… | 初始化 `Mem0Middleware` 实例。 Initialize the mem0 middleware. |
方法摘要Method Summary
| 方法Method | 说明Description |
|---|---|
async def on_reply(agent: 'Agent', input_kwargs: dict, next_handler: Callable[..., AsyncGenerator]) -> AsyncGeneratorasync | 拦截并扩展回复流程。 Handles the reply event. |
async def on_system_prompt(agent: 'Agent', current_prompt: str) -> strasync | 拦截并修改系统提示词。 Append memory-tool instructions to the system prompt. |
async def list_tools() -> list['ToolBase']async | 列出当前连接可用的工具。 List memory tools provided by this middleware. |
构造器详情Constructor Detail
Mem0Middleware
def __init__(*, user_id: str, client: Mem0AsyncClient | None = None, chat_model: 'ChatModelBase | None' = None, embedding_model: 'EmbeddingModelBase | None' = None, mem0_config: Any | None = None, mode: Literal['static_control', 'agent_control', 'both'] = 'both', agent_id: str | None = None, top_k: int = 5, threshold: float | None = None, scope_search_by_agent: bool = True, await_write: bool = True, memory_section_header: str = DEFAULT_MEMORY_SECTION_HEADER, memory_section_intro: str = DEFAULT_MEMORY_SECTION_INTRO, tool_instructions: str = DEFAULT_TOOL_INSTRUCTIONS) -> None
初始化 Mem0Middleware 实例。
Three ways to wire up the mem0 backend: - Models only — pass chat_model + embedding_model and the middleware builds a local OSS AsyncMemory wired to them (mem0's default Qdrant for storage).
参数Parameters
| 名称Name | 类型Type | 说明Description |
|---|---|---|
user_idkw | str | 用户标识(类型 `str`)。The mem0 `user_id` for memory namespacing. Required. |
clientkw默认default None | Mem0AsyncClient | None | 客户端(类型 `Mem0AsyncClient | None`)。A pre-built mem0 async client — `mem0.AsyncMemory` (OSS) or `mem0.AsyncMemoryClient` (Platform). Use this when you want full control over the mem0 setup. |
chat_modelkw默认default None | 'ChatModelBase | None' | 聊天模型(类型 `'ChatModelBase | None'`)。The AgentScope chat model mem0 should use for memory extraction. Required if `client` is not given and `mem0_config` does not already supply an LLM. |
embedding_modelkw默认default None | 'EmbeddingModelBase | None' | 向量化模型(类型 `'EmbeddingModelBase | None'`)。The AgentScope embedding model mem0 should use to embed memories. Required if `client` is not given and `mem0_config` does not already supply an embedder. Its `dimensions` must match mem0's vector store (the default Qdrant expects 1536). |
mem0_configkw默认default None | Any | None | mem 0 配置(类型 `Any | None`)。Optional `mem0.configs.base.MemoryConfig` to use as the base — lets you customize vector store / history DB / reranker / etc. while still routing LLM and embedding through AgentScope. Mutually exclusive with `client`. |
modekw默认default 'both' | Literal['static_control', 'agent_control', 'both'] | 模式(类型 `Literal['static_control', 'agent_control', 'both']`)。How the agent interacts with mem0: - `"static_control"`: middleware searches mem0 before each reply, appends the retrieved memories to `agent.state.context` as an `AssistantMsg(name="memory")`, and writes the new exchange back after the reply. The agent never sees mem0 as a tool. - `"agent_control"`: middleware exposes `search_memory` / `add_memory` tools for the agent to invoke on demand, plus a short nudge in the system prompt. No automatic retrieval or write-back. - `"both"`: both patterns at once — auto retrieval AND on-demand tools. Defaults to `"both"` (matching AgentScope 1.x's `ReActAgent.long_term_memory_mode` default). |
agent_idkw默认default None | str | None | 智能体标识(类型 `str | None`)。Optional mem0 `agent_id` for finer-grained namespacing. When `None` (default) mem0 receives no `agent_id` filter and memories are scoped by `user_id` only. |
top_kkw默认default 5 | int | 返回条数(类型 `int`)。Max number of memories retrieved per static-control search. Also serves as the default `top_k` for the `search_memory` tool (the agent can override). |
thresholdkw默认default None | float | None | 阈值(类型 `float | None`)。Minimum similarity score. `None` lets mem0 decide. |
scope_search_by_agentkw默认default True | bool | 范围搜索通过智能体(类型 `bool`)。When `True` (default) search filters include both `user_id` and `agent_id` — memories are scoped to the agent that created them. When `False` search uses `user_id` only, so a user's memories are shared across agents. |
await_writekw默认default True | bool | await 写入(类型 `bool`)。When `True` (default) the post-turn `add` call is awaited inline. When `False` it's fire-and-forget — faster response but exceptions only surface in logs. memory_section_header, memory_section_intro: Strings used when injecting retrieved memories into the model's messages list (`static_control` / `both` modes). |
memory_section_headerkw默认default DEFAULT_MEMORY_SECTION_HEADER | str | 记忆 section 请求头(类型 `str`)。The memory section header. |
memory_section_introkw默认default DEFAULT_MEMORY_SECTION_INTRO | str | 记忆 section intro(类型 `str`)。The memory section intro. |
tool_instructionskw默认default DEFAULT_TOOL_INSTRUCTIONS | str | 工具指令(类型 `str`)。Markdown block appended to the agent's system prompt in `agent_control` / `both` modes, advertising the `search_memory` / `add_memory` tools to the LLM. |
源码Source
agentscope/middleware/_longterm_memory/_mem0/_middleware.py:143–280方法详情Method Detail
on_reply
async def on_reply(agent: 'Agent', input_kwargs: dict, next_handler: Callable[..., AsyncGenerator]) -> AsyncGenerator
async
拦截并扩展回复流程。
Handles the reply event.
参数Parameters
| 名称Name | 类型Type | 说明Description |
|---|---|---|
agent | 'Agent' | 智能体(类型 `'Agent'`)。The agent. |
input_kwargs | dict | 输入关键字参数(类型 `dict`)。The input kwargs. |
next_handler | Callable[..., AsyncGenerator] | 下一个处理器(类型 `Callable[..., AsyncGenerator]`)。The next handler. |
AsyncGenerator
返回AsyncGenerator。Returns async generator.
源码Source
agentscope/middleware/_longterm_memory/_mem0/_middleware.py:285–374on_system_prompt
async def on_system_prompt(agent: 'Agent', current_prompt: str) -> str
async
拦截并修改系统提示词。
Append memory-tool instructions to the system prompt.
参数Parameters
| 名称Name | 类型Type | 说明Description |
|---|---|---|
agent | 'Agent' | 智能体(类型 `'Agent'`)。The agent whose system prompt is being transformed. |
current_prompt | str | 当前提示词(类型 `str`)。The system prompt produced by previous middleware. |
str
返回字符串结果。`str`:
源码Source
agentscope/middleware/_longterm_memory/_mem0/_middleware.py:379–399list_tools
async def list_tools() -> list['ToolBase']
async
列出当前连接可用的工具。
List memory tools provided by this middleware.
list['ToolBase']
返回'ToolBase'列表。`list[ToolBase]`:
源码Source
agentscope/middleware/_longterm_memory/_mem0/_middleware.py:401–411