Build and run agents you can see, understand and trust.
Python agentchatbotlarge-language-modelsllmllm-agentmcpmulti-agentmulti-modalreact-agentrealtime-agentvoice-agentvoice-assistant
feat(middleware): add mem0-backed long-term memory middleware (#1775)
Osier-Yi5be0b16db257
diff --git a/docs/NEWS.md b/docs/NEWS.mdindex 6fb47f2ed..7899a5115 100644--- a/docs/NEWS.md+++ b/docs/NEWS.md@@ -2,5 +2,6 @@<!-- The first 10 items are automatically synced to README.md and README_zh.md via GitHub Actions. --><!-- To update news in READMEs, modify this file and push to trigger the workflow. -->+- **[2026-06] `INTE`:** Mem0 supported. [Example](https://github.com/agentscope-ai/agentscope/tree/main/examples/long_term_memory) | [Docs](https://docs.agentscope.io/v2)- **[2026-06] `FEAT`:** Agent Team supported. [Example](https://github.com/agentscope-ai/agentscope/tree/main/examples/agent_service) | [Docs](https://docs.agentscope.io/v2/deploy/agent-team)- **[2026-05] `RELS`:** AgentScope 2.0 released! [Docs](https://docs.agentscope.io/)\ No newline at end of filediff --git a/docs/NEWS_zh.md b/docs/NEWS_zh.mdindex b8885a620..3d564c838 100644--- a/docs/NEWS_zh.md+++ b/docs/NEWS_zh.md@@ -2,5 +2,6 @@<!-- The first 10 items are automatically synced to README.md and README_zh.md via GitHub Actions. --><!-- To update news in READMEs, modify this file and push to trigger the workflow. -->+- **[2026-06] `集成`:** 集成 Mem0 长期记忆。 [Example](https://github.com/agentscope-ai/agentscope/tree/main/examples/long_term_memory) | [Docs](https://docs.agentscope.io/v2)- **[2026-06] `功能`:** 支持 Agent Team。[样例](https://github.com/agentscope-ai/agentscope/tree/main/examples/agent_service) | [文档](https://docs.agentscope.io/zh/v2/deploy/agent-team)- **[2026-05] `发布`:** AgentScope 2.0 已发布\ No newline at end of filediff --git a/examples/long_term_memory/mem0/README.md b/examples/long_term_memory/mem0/README.mdnew file mode 100644index 000000000..2c102a84d--- /dev/null+++ b/examples/long_term_memory/mem0/README.md@@ -0,0 +1,387 @@+# mem0 middleware example++One runnable demo (`oss_demo.py`) showing the+[mem0](https://github.com/mem0ai/mem0) middleware plugged into an+`agentscope.agent.Agent`. Drives two consecutive agent sessions for+the same `user_id` so mem0's cross-session memory effect is visible,+and prints each middleware contribution (retrieval / tool call /+write-back) inline so you can see when each path fires.++The demo defaults to the **OSS backend** (open-source mem0,+self-hosted via local Qdrant) with mem0 driven by AgentScope's own+DashScope chat + embedding model — no separate OpenAI key needed+by mem0. To run it against the hosted **mem0+Platform** instead, swap the `Mem0Middleware(...)` construction for+the alternative shown inline (look for the+``# For the hosted mem0 Platform, swap …`` comment in `oss_demo.py`)+— the rest of the demo is identical.++## Install++```bash+# mem0 is an optional AgentScope dependency — pull it via the extra:+pip install "agentscope[mem0]" # resolves to mem0ai>=2.0.0,<3.0.0+# (equivalent to `pip install agentscope mem0ai>=2.0.0,<3.0.0`)++export DASHSCOPE_API_KEY=sk-... # OSS path+# Platform path (only if you switch):+# export MEM0_API_KEY=m0-...+# export OPENAI_API_KEY=sk-... # only needed if your agent's chat model is OpenAI+```++## Import path++`Mem0Middleware` is exported from the middleware package:++```python+from agentscope.middleware import Mem0Middleware+from agentscope.tool import Toolkit+```++## Three construction paths++```python+# 1. Models — build a local OSS AsyncMemory wired to your AgentScope+# chat + embedding model. mem0 defaults for everything else.+Mem0Middleware(+ user_id="alice",+ chat_model=my_chat_model,+ embedding_model=my_embedding_model,+ mode="both",+)++# 2. Models + custom mem0_config — same as (1), but start from your+# customized MemoryConfig (custom vector store, history DB,+# reranker, ...). `chat_model` / `embedding_model` always WIN:+# if mem0_config already specifies an .llm or .embedder, it gets+# OVERWRITTEN by the AgentScope adapter built from your model.+# Every other field of mem0_config (vector_store, history_db_path,+# reranker, etc.) is preserved as-is.+Mem0Middleware(+ user_id="alice",+ chat_model=my_chat_model,+ embedding_model=my_embedding_model,+ mem0_config=MemoryConfig(+ vector_store=VectorStoreConfig(+ provider="qdrant",+ config={"host": "my-qdrant", "port": 6333},+ ),+ history_db_path="/data/mem0_history.db",+ ),+ mode="both",+)++# 3. Client — bring your own pre-built mem0 client. Accepts EITHER+# backend: `mem0.AsyncMemory` (open-source / self-hosted) or+# `mem0.AsyncMemoryClient` (hosted Platform). Use this when you+# want full control over the mem0 setup — custom subclass, a+# pre-warmed client shared across many agents, exotic config+# that doesn't fit the `build_mem0_config` helper, etc.+#+# OSS backend (you assemble the AsyncMemory yourself):+Mem0Middleware(+ user_id="alice",+ client=AsyncMemory(), # or AsyncMemory.from_config({...})+ mode="both",+)++# Hosted Platform backend:+Mem0Middleware(+ user_id="alice",+ client=AsyncMemoryClient(api_key="m0-..."),+ mode="both",+)+```++Precedence and validation matrix:++| `client` | `mem0_config` | `chat_model` | `embedding_model` | Behavior |+|:-:|:-:|:-:|:-:|---|+| ✓ | — | — | — | Use `client` as-is. |+| ✓ | any | any | any | Use `client`; the other three are ignored, and a `WARNING` log lists which kwargs got dropped. |+| — | ✓ | — | — | Wrap `mem0_config` in an `AsyncMemory`, no overrides. |+| — | ✓ | ✓ | — | Wrap + override `.llm` with the AgentScope adapter; keep `.embedder` from `mem0_config`. |+| — | ✓ | — | ✓ | Wrap + override `.embedder` only; keep `.llm` from `mem0_config`. |+| — | ✓ | ✓ | ✓ | Wrap + override both `.llm` and `.embedder` (other fields of `mem0_config` preserved). |+| — | — | ✓ | ✓ | Build a fresh `MemoryConfig` (mem0 defaults for vector store / history DB) with the AgentScope adapters wired in. |+| — | — | ✓ | — | ❌ `ValueError` — `chat_model` and `embedding_model` must be passed together when `mem0_config` is omitted. |+| — | — | — | ✓ | ❌ Same. |+| — | — | — | — | ❌ `ValueError` — need one of: `client`, `mem0_config`, or both `chat_model` + `embedding_model`. |++Why the "client wins" and "config override" paths exist:++- **`client` wins** lets one `Mem0Middleware(...)` call+ shape work for both library callers (who pass AgentScope models)+ and production setups (who supply a pre-built `client`). The+ `WARNING` log makes any mismatch visible without crashing.+- **Config override of `mem0_config.llm` / `.embedder`** lets you+ keep one canonical `MemoryConfig` template (custom vector store,+ history DB, reranker, …) and swap just the LLM / embedder per+ call site by passing `chat_model` / `embedding_model`.++## How the middleware controls memory++The `mode` parameter selects one of three patterns. They differ by+**what the LLM sees** and **what fires automatically**:++### `static_control`+The middleware does the work, the agent is unaware. Mirroring+AgentScope 1.x's `ReActAgent._retrieve_from_long_term_memory`:++1. **`on_reply` (pre)** queries mem0 with the latest user message+ and pre-fetches the results.+2. **At `ReplyStartEvent`** — which fires right after the agent has+ ingested the new user input into `state.context` and before the+ reasoning loop starts — the middleware appends an+ `AssistantMsg(name="memory", ...)` to `state.context`. This puts+ the memory note IMMEDIATELY after the user's new message, matching+ v1's placement (it ran right after `self.memory.add(msg)`).+3. **`on_reply` (post)** writes the new `(user, assistant)` exchange+ back to mem0.++The injected memory message **persists** in the agent's context+across turns. Long sessions accumulate one per turn that retrieved+anything; if that becomes a token concern, post-process with+`compress_context` or write your own middleware to pop them.++### `agent_control`+The middleware lists two tools — `search_memory(keywords, limit)` and+`add_memory(thinking, content)` — and otherwise stays out of the way.+Pass them into the agent's toolkit explicitly when constructing the+agent:++```python+mw = Mem0Middleware(..., mode="agent_control")+agent = Agent(+ ...,+ toolkit=Toolkit(tools=await mw.list_tools()),+ middlewares=[mw],+)+```++The system prompt gets a short nudge telling the agent that memory+tools exist; the actual per-tool usage guidance comes through the+standard tool schema. No automatic retrieval or write-back.++### `both` (default)+Both patterns are active simultaneously: memories are auto-retrieved+and appended to the agent's context as an assistant note, AND the+tools (with their system-prompt hint) are exposed for explicit+on-demand search / save. This matches AgentScope 1.x's+`ReActAgent.long_term_memory_mode` default.++## Sharing one middleware across agents++The local OSS mem0 backend uses on-disk Qdrant by default, and Qdrant+takes an **exclusive lock** on the storage folder+(``/tmp/qdrant`` by default). Two ``Mem0Middleware`` instances each+built from ``chat_model`` + ``embedding_model`` would each construct+their own ``AsyncMemory`` → second one crashes on the lock:++```+RuntimeError: Storage folder /tmp/qdrant is already accessed by+another instance of Qdrant client.+```++Fix: build **one** ``Mem0Middleware`` instance and pass it to every+agent that should share the same memory namespace:++```python+mw = Mem0Middleware(+ user_id="alice",+ chat_model=chat_model,+ embedding_model=embedding_model,+ mode="both",+)+agent_a = Agent(+ ...,+ toolkit=Toolkit(tools=await mw.list_tools()),+ middlewares=[mw],+)+agent_b = Agent(+ ...,+ toolkit=Toolkit(tools=await mw.list_tools()),+ middlewares=[mw],+)+```++This is what the demo does. The memory tools receive the live+`AgentState` at call time, and the middleware resolves the active+agent by `state.session_id`, so sharing one middleware across agents+is safe.++If you genuinely need a separate Qdrant store per agent, pass a+``mem0_config`` with a distinct ``vector_store.config.path`` or+``collection_name`` for each one.++### Recommended: run Qdrant in Docker (especially on Windows)++The local on-disk Qdrant works for single-process demos but is+brittle in real deployments — and **outright painful on Windows**,+where the filesystem-lock semantics differ from Unix and the+exclusive-lock failure mode is harder to recover from. For anything+beyond a single-process Linux/macOS sandbox, run Qdrant as a service:++```bash+docker run -p 6333:6333 -p 6334:6334 \+ -v $(pwd)/qdrant_storage:/qdrant/storage \+ qdrant/qdrant+```++Then point mem0 at it instead of the on-disk path:++```python+from mem0.configs.base import MemoryConfig+from mem0.vector_stores.configs import VectorStoreConfig++mem0_cfg = MemoryConfig(+ vector_store=VectorStoreConfig(+ provider="qdrant",+ config={+ "collection_name": "mem0",+ "host": "localhost", # the Docker container+ "port": 6333,+ "embedding_model_dims": 1536,+ },+ ),+)+Mem0Middleware(+ user_id="alice",+ chat_model=chat_model,+ embedding_model=embedding_model,+ mem0_config=mem0_cfg,+)+```++Benefits over on-disk:++- No file-lock contention — multiple Python processes can connect.+- Survives across runs without manual file cleanup.+- Same shape works for remote Qdrant (Qdrant Cloud, your own+ Kubernetes deployment) — just change ``host`` / ``port`` /+ ``api_key``.++## Memory scoping (`user_id` × `agent_id`)++mem0 tags every stored memory with the `user_id` and `agent_id`+filter values passed at `add` time, and searches by AND-matching those+tags. The middleware exposes the agent dimension via the+`scope_search_by_agent` flag (default `True`):++| `scope_search_by_agent` | What `add` tags the memory with | What `search` filters by | Effect |+| --- | --- | --- | --- |+| `True` (default) | `user_id` + `agent_id` | `user_id` + `agent_id` | Strict per-agent silos. Agent A's memories invisible to agent B for the same user. |+| `False` | `user_id` + `agent_id` (unchanged) | `user_id` only | Read-broad, write-narrow. All agents for the same user share a memory pool, but each memory still records which agent wrote it (visible in mem0 metadata). |++`agent_id` defaults to `agent.name`. Override via `agent_id="..."` or+`agent_id=lambda agent: ...` on the middleware constructor.++When to relax `scope_search_by_agent`:++- One user has multiple specialized agents (research / coding /+ scheduling) that should benefit from each other's discoveries about+ the user.+- An agent's `name` might change across deployments but you want the+ memory to persist across name changes.++### A note on agent-centric extraction (currently unreachable)++mem0 v2's extraction prompt+([`ADDITIVE_EXTRACTION_PROMPT`](https://github.com/mem0ai/mem0/blob/main/mem0/configs/prompts.py))+has a conditional suffix that switches framing from user-centric+("User stated X") to **agent-centric** ("Agent was informed of X" /+"Agent recommended Y"). It's gated on+`is_agent_scoped = bool(filters.agent_id) and not filters.user_id` —+i.e. only when `agent_id` is provided *without* `user_id`. The+middleware always passes `user_id` (it's a required constructor arg),+so this agent-centric suffix is unreachable through `Mem0Middleware`+today. In practice that's fine — agent persona / configuration is+usually expressed via system prompt rather than long-term memory.++## Service-mode integration (`agentscope.app`)++The demos above use the **library mode** — you construct `Agent`+yourself and pass `Mem0Middleware` into its `middlewares=[...]`. For+production deployments via `agentscope.app` (the FastAPI service+layer), the `user_id` already flows through the framework from the+`X-User-ID` HTTP header. Hook in through the+[`extra_agent_middlewares`](../../../../src/agentscope/app/_types.py)+factory:++```python+from agentscope.app import create_app+from agentscope.middleware import Mem0Middleware+from agentscope.middleware._longterm_memory._mem0._agentscope_adapter \+ import build_mem0_config+from mem0 import AsyncMemory++# Build the mem0 client ONCE at module scope — local OSS Qdrant+# takes an exclusive lock on its storage folder; per-request+# construction would deadlock under concurrent traffic.+chat_model = ... # shared AgentScope ChatModelBase+emb_model = ... # shared AgentScope EmbeddingModelBase+mem0_client = AsyncMemory(+ config=build_mem0_config(+ chat_model=chat_model,+ embedding_model=emb_model,+ ),+)+++async def long_term_memory_factory(+ user_id: str, # ← from the authenticated X-User-ID header+ agent_id: str,+ session_id: str,+) -> list:+ return [+ Mem0Middleware(+ user_id=user_id,+ client=mem0_client, # shared across all requests+ mode="both",+ ),+ ]+++app = create_app(+ ...,+ extra_agent_middlewares=long_term_memory_factory,+)+```++Key points:++- The factory is `async (user_id, agent_id, session_id) ->+ list[MiddlewareBase]`, called **once per agent assembly**+ (i.e. per chat turn / scheduled trigger). It returns fresh+ `Mem0Middleware` instances each time, but they share a single+ underlying mem0 client.+- `user_id` is the authenticated caller, injected by `agentscope.app`+ via `get_current_user_id` (currently from `X-User-ID` header; will+ become JWT-based when auth lands upstream). You forward it straight+ to `Mem0Middleware(user_id=user_id, ...)` — no resolver callable+ needed.+- For hosted mem0 Platform, swap the `AsyncMemory(config=...)`+ construction for `AsyncMemoryClient(api_key=...)` — same factory+ shape, no Qdrant lock concern.++## Notes on the AgentScope-as-mem0-backend path++When you pass `chat_model` + `embedding_model`, the middleware+internally:++1. Registers `AgentScopeLLM` / `AgentScopeEmbedding` in mem0's factory+ dicts under provider name `"agentscope"`.+2. Substitutes `LlmConfig` / `EmbedderConfig` with subclasses whose+ validator allows `"agentscope"` (mem0's stock validator hardcodes a+ whitelist that doesn't include us). Other providers continue to be+ rejected with mem0's original error.+3. Builds an `AsyncMemory` whose `.llm` and `.embedding_model` route+ through the AgentScope adapters.+4. Bridges mem0's sync API onto AgentScope's async models via a+ persistent background event loop, so async clients (e.g. Ollama's+ `AsyncClient`) keep their connection pool across calls.++Your embedding model's `dimensions` must match the vector store's+expected dim — mem0's default Qdrant expects 1536, which matches+DashScope's `text-embedding-v2` at `dimensions=1536` (the value used+in `oss_demo.py`).diff --git a/examples/long_term_memory/mem0/oss_demo.py b/examples/long_term_memory/mem0/oss_demo.pynew file mode 100644index 000000000..cc2134f35--- /dev/null+++ b/examples/long_term_memory/mem0/oss_demo.py@@ -0,0 +1,327 @@+# -*- coding: utf-8 -*-+"""Mem0 middleware demo (open-source mem0, AgentScope-driven).++Drives two independent agent sessions for the same ``user_id`` so+mem0's cross-session memory effect is visible. Each turn streams+events from ``agent.reply_stream`` and prints the ones that matter:++- ``[mem0 → context (static)]`` — the memory note the middleware+ appended to ``state.context`` (fires at ``ReplyStartEvent``, before+ any tool call, so the output order matches the data flow)+- ``[tool call (agent)]`` — each ``search_memory`` / ``add_memory``+ invocation the agent makes on its own+- ``[assistant]`` — the assistant's reply, concatenated from the+ ``TextBlockDeltaEvent`` stream+- ``[context → mem0 (static)]`` — facts the middleware wrote back+ after the turn++The mode tag (``static`` / ``agent``) on each line tells you which+control path produced it.++Starts each run from a clean mem0 store (for ``user_id``) so the+demo is reproducible.++Requires:+ pip install agentscope mem0ai+ export DASHSCOPE_API_KEY=sk-...+"""+import asyncio+import logging+import os+import shutil++from mem0 import AsyncMemory+from mem0.configs.base import MemoryConfig+from mem0.vector_stores.configs import VectorStoreConfig++from agentscope.agent import Agent+from agentscope.credential import DashScopeCredential+from agentscope.embedding import DashScopeEmbeddingModel+from agentscope.event import (+ ReplyStartEvent,+ TextBlockDeltaEvent,+ ToolCallDeltaEvent,+ ToolCallStartEvent,+ ToolResultEndEvent,+ ToolResultTextDeltaEvent,+)+from agentscope.message import UserMsg+from agentscope.middleware import Mem0Middleware+from agentscope.model import DashScopeChatModel+from agentscope.tool import Toolkit+++MODE = "both" # try "static_control" or "agent_control" too+++# Silence mem0's noisy init warnings (qdrant migration notice, spaCy+# missing, fastembed missing) — they're informational, not actionable.+logging.getLogger("mem0").setLevel(logging.ERROR)+++async def _facts_in_mem0(client: AsyncMemory, user_id: str) -> list[str]:+ """Return mem0's current facts for ``user_id`` as plain strings."""+ res = await client.get_all(filters={"user_id": user_id})+ items = res.get("results", res) if isinstance(res, dict) else res+ out: list[str] = []+ for m in items:+ if isinstance(m, dict):+ text = m.get("memory")+ if isinstance(text, str) and text:+ out.append(text)+ return out+++def _injected_memory_bullets(agent: Agent) -> list[str]:+ """Extract the bullet lines from the memory note the middleware+ appended to ``agent.state.context`` (if any) — strips the section+ header and intro so we see only the actual retrieved facts."""+ for msg in agent.state.context:+ if getattr(msg, "name", None) != "memory":+ continue+ hint_text = "\n".join(+ block.hint for block in msg.get_content_blocks("hint")+ )+ return [+ line[2:].strip()+ for line in hint_text.splitlines()+ if line.startswith("- ")+ ]+ return []+++async def _run_turn(agent: Agent, user_msg: UserMsg) -> str:+ """Drive one reply turn through ``agent.reply_stream`` and print+ each middleware contribution as it happens, in the order it+ happens:++ 1. ``ReplyStartEvent`` fires right after the agent ingests the new+ user input AND the middleware has appended any retrieved memory+ note to ``state.context`` (static path) — so this is the right+ place to surface ``[mem0 → context]``.+ 2. ``ToolCallStartEvent`` / ``ToolResultEndEvent`` bracket each+ ``search_memory`` / ``add_memory`` invocation the agent makes+ on its own (agent path).+ 3. ``TextBlockDeltaEvent`` carries the assistant's streamed reply+ text — concatenating every delta yields the final message+ content (there is no separate "final Msg" reply_stream+ withholds).++ Each printed line is tagged with the mem0 control path that+ produced it (``static`` vs ``agent``) so the demo stays readable+ in any of the three modes.+ """+ pending_args: dict[str, str] = {}+ pending_names: dict[str, str] = {}+ pending_results: dict[str, str] = {}+ text_parts: list[str] = []+ memory_announced = False++ async for ev in agent.reply_stream(inputs=user_msg):+ if isinstance(ev, ReplyStartEvent) and not memory_announced:+ injected = _injected_memory_bullets(agent)+ print(+ f"[mem0 → context (static)] retrieved "+ f"{len(injected)} memory note(s):",+ )+ for b in injected:+ print(f" ← {b}")+ memory_announced = True+ elif isinstance(ev, ToolCallStartEvent):+ pending_names[ev.tool_call_id] = ev.tool_call_name+ pending_args[ev.tool_call_id] = ""+ pending_results[ev.tool_call_id] = ""+ elif isinstance(ev, ToolCallDeltaEvent):+ pending_args[ev.tool_call_id] += ev.delta+ elif isinstance(ev, ToolResultTextDeltaEvent):+ pending_results[ev.tool_call_id] += ev.delta+ elif isinstance(ev, ToolResultEndEvent):+ name = pending_names.pop(ev.tool_call_id, "<unknown>")+ args = pending_args.pop(ev.tool_call_id, "")+ result = pending_results.pop(ev.tool_call_id, "")+ # ev.state is a StrEnum at the type level but pydantic+ # may have deserialized it to a plain str; f-string both+ # cases yields the same value string.+ print(f"[tool call (agent)] {name}({args}) → state={ev.state}")+ for line in result.splitlines() or [""]:+ if line:+ print(f" → {line}")+ elif isinstance(ev, TextBlockDeltaEvent):+ text_parts.append(ev.delta)++ return "".join(text_parts)+++async def main() -> None:+ """Drive two cross-session agent turns and print middleware effects."""+ api_key = os.environ["DASHSCOPE_API_KEY"]+ user_id = "alice"++ # Wipe mem0's local files BEFORE constructing the client so each+ # demo run starts clean. We don't use ``mem0_client.delete_all()``+ # because qdrant-client's local SQLite layer has a race under+ # mem0's parallel ``asyncio.gather`` deletes (sqlite3.InterfaceError).+ qdrant_path = "/tmp/qdrant" # matches the vector_store config below+ history_db = os.path.expanduser("~/.mem0/history.db")+ print("=== resetting mem0 local state ===")+ print(f" rm -rf {qdrant_path}")+ shutil.rmtree(qdrant_path, ignore_errors=True)+ print(f" rm -f {history_db}")+ try:+ os.remove(history_db)+ except FileNotFoundError:+ pass++ # `stream` can be True or False — the AgentScope→mem0 adapter+ # drains an async generator and uses the last chunk (which carries+ # the full accumulated content per AgentScope's streaming contract).+ # The agent's own `reply_stream` still emits per-delta events+ # regardless of this setting, so streaming-mode does not change the+ # demo's printed output shape.+ chat_model = DashScopeChatModel(+ credential=DashScopeCredential(api_key=api_key),+ model="qwen3.7-max",+ stream=False,+ )+ embedding_model = DashScopeEmbeddingModel(+ credential=DashScopeCredential(api_key=api_key),+ model="text-embedding-v4",+ parameters=DashScopeEmbeddingModel.Parameters(+ dimensions=1536, # matches mem0's Qdrant default+ ),+ )++ # Explicit vector-store config (here we just spell out mem0's+ # default local Qdrant — collection ``mem0``, on-disk at+ # ``/tmp/qdrant``, 1536-d vectors). Override any of these for+ # remote Qdrant, alternate collection names, etc. Pass the+ # ``MemoryConfig`` through ``mem0_config=`` and the middleware+ # keeps everything you set, only swapping ``.llm`` and+ # ``.embedder`` to route through your AgentScope models.+ #+ # Recommended for Windows users and any production setup: run+ # Qdrant in Docker and connect over the network instead of using+ # the local on-disk backend. Local on-disk Qdrant takes an+ # exclusive file lock that's brittle on Windows (different+ # filesystem-lock semantics) and breaks under concurrent agent+ # instances. To switch:+ #+ # docker run -p 6333:6333 -p 6334:6334 \\+ # -v $(pwd)/qdrant_storage:/qdrant/storage \\+ # qdrant/qdrant+ #+ # vector_store=VectorStoreConfig(+ # provider="qdrant",+ # config={+ # "collection_name": "mem0",+ # "host": "localhost", # Docker container+ # "port": 6333,+ # "embedding_model_dims": 1536,+ # },+ # )+ #+ # (You'd also drop the ``shutil.rmtree(qdrant_path)`` wipe above —+ # state lives in the Docker volume, not the local filesystem.)+ mem0_cfg = MemoryConfig(+ vector_store=VectorStoreConfig(+ provider="qdrant",+ config={+ "collection_name": "mem0",+ "path": qdrant_path,+ "embedding_model_dims": 1536,+ "on_disk": False,+ },+ ),+ )++ mw = Mem0Middleware(+ user_id=user_id,+ agent_id="datascope_assistant",+ chat_model=chat_model,+ embedding_model=embedding_model,+ mem0_config=mem0_cfg,+ mode=MODE,+ top_k=5,+ )+ # For the hosted mem0 Platform, swap the construction above for:+ #+ # from mem0 import AsyncMemoryClient+ # mw = Mem0Middleware(+ # user_id=user_id,+ # client=AsyncMemoryClient(api_key=os.environ["MEM0_API_KEY"]),+ # mode=MODE,+ # )+ #+ # No local Qdrant / vector_store config needed — extraction and+ # storage all happen in mem0's cloud service.+ # pylint: disable-next=protected-access+ mem0_client: AsyncMemory = mw._client # demo only — peek at the+ # constructed client to inspect mem0 state between turns.++ # =================================================================+ # SESSION 1+ # =================================================================+ print(f"\n=== SESSION 1 (mode={MODE!r}) ===")+ user_msg_1 = (+ "Hi! For any chart, please default to dark mode and use "+ "matplotlib. Also I'm based in Hangzhou."+ )+ print(f"\n[user] {user_msg_1}\n")++ before = await _facts_in_mem0(mem0_client, user_id)++ agent = Agent(+ name="datascope_assistant",+ system_prompt=(+ "You are a helpful data-analysis assistant. Be concise. "+ "If you learn a durable user preference, save it with "+ "the add_memory tool when one is available."+ ),+ model=chat_model,+ toolkit=Toolkit(tools=await mw.list_tools()),+ middlewares=[mw],+ )+ reply_text = await _run_turn(agent, UserMsg("alice", user_msg_1))+ print(f"\n[assistant] {reply_text}")++ after = await _facts_in_mem0(mem0_client, user_id)+ new = [f for f in after if f not in before]+ print(f"\n[context → mem0 (static)] extracted {len(new)} new fact(s):")+ for f in new:+ print(f" + {f}")++ # =================================================================+ # SESSION 2 — fresh Agent, empty chat context. mem0 should bridge.+ # =================================================================+ print(f"\n=== SESSION 2 (fresh agent, mem0 bridges; mode={MODE!r}) ===")+ user_msg_2 = (+ "Plot me a bar chart of monthly sales — pick reasonable "+ "defaults for theme and library."+ )+ print(f"\n[user] {user_msg_2}\n")++ before = await _facts_in_mem0(mem0_client, user_id)++ agent = Agent(+ name="datascope_assistant",+ system_prompt=(+ "You are a helpful data-analysis assistant. Be concise. "+ "If you learn a durable user preference, save it with "+ "the add_memory tool when one is available."+ ),+ model=chat_model,+ toolkit=Toolkit(tools=await mw.list_tools()),+ middlewares=[mw],+ )+ reply_text = await _run_turn(agent, UserMsg("alice", user_msg_2))+ print(f"\n[assistant] {reply_text}")++ after = await _facts_in_mem0(mem0_client, user_id)+ new = [f for f in after if f not in before]+ print(f"\n[context → mem0 (static)] extracted {len(new)} new fact(s):")+ for f in new:+ print(f" + {f}")+++if __name__ == "__main__":+ asyncio.run(main())diff --git a/pyproject.toml b/pyproject.tomlindex 58c233c98..a9e4aa3c0 100644--- a/pyproject.toml+++ b/pyproject.toml@@ -77,6 +77,15 @@ tools = ["ripgrep",]+# ------------ Long-term memory ------------+# Required by `agentscope.middleware._longterm_memory.Mem0Middleware`.+# Pinned to mem0 v2.x because the middleware targets that+# architecture: ADDITIVE_EXTRACTION_PROMPT + AGENT_CONTEXT_SUFFIX+# (replaced v1's USER/AGENT_MEMORY_EXTRACTION_PROMPT split) and the+# v3 phased pipeline in `_add_to_vector_store`. Running on mem0 1.x+# wouldn't crash but the 2-tier add fallback degenerates into a+# wasted LLM call.+mem0 = ["mem0ai>=2.0.0"]# ------------ Full ------------full = ["agentscope[models]",@@ -84,6 +93,7 @@ full = ["agentscope[storage]","agentscope[workspace]","agentscope[tools]",+ "agentscope[mem0]",]# ------------ Development ------------diff --git a/src/agentscope/middleware/__init__.py b/src/agentscope/middleware/__init__.pyindex a15f6b5d6..171d87591 100644--- a/src/agentscope/middleware/__init__.py+++ b/src/agentscope/middleware/__init__.py@@ -2,10 +2,12 @@"""Middleware system for AgentScope agents."""from ._base import MiddlewareBase+from ._longterm_memory import Mem0Middlewarefrom ._tracing import TracingMiddlewarefrom ._tts_middleware import TTSMiddleware__all__ = [+ "Mem0Middleware","MiddlewareBase","TracingMiddleware","TTSMiddleware",diff --git a/src/agentscope/middleware/_longterm_memory/__init__.py b/src/agentscope/middleware/_longterm_memory/__init__.pynew file mode 100644index 000000000..d7d379e4b--- /dev/null+++ b/src/agentscope/middleware/_longterm_memory/__init__.py@@ -0,0 +1,16 @@+# -*- coding: utf-8 -*-+"""Long-term memory middlewares for AgentScope agents.++Currently only the mem0 backend is implemented. Import the public class+from the middleware package::++ from agentscope.middleware import Mem0Middleware++Future backends (e.g. dedicated vector stores, custom user-profile+services) can sit alongside ``_mem0/`` under this package and be+re-exported here.+"""++from ._mem0 import Mem0Middleware++__all__ = ["Mem0Middleware"]diff --git a/src/agentscope/middleware/_longterm_memory/_mem0/__init__.py b/src/agentscope/middleware/_longterm_memory/_mem0/__init__.pynew file mode 100644index 000000000..645e7e6ca--- /dev/null+++ b/src/agentscope/middleware/_longterm_memory/_mem0/__init__.py@@ -0,0 +1,6 @@+# -*- coding: utf-8 -*-+"""mem0-backed long-term memory middleware."""++from ._middleware import Mem0Middleware++__all__ = ["Mem0Middleware"]diff --git a/src/agentscope/middleware/_longterm_memory/_mem0/_agentscope_adapter.py b/src/agentscope/middleware/_longterm_memory/_mem0/_agentscope_adapter.pynew file mode 100644index 000000000..8fedd418d--- /dev/null+++ b/src/agentscope/middleware/_longterm_memory/_mem0/_agentscope_adapter.py@@ -0,0 +1,439 @@+# -*- coding: utf-8 -*-+"""Adapters that let mem0 drive its memory extraction with the user's+existing AgentScope chat / embedding model — instead of building yet+another OpenAI / Anthropic / Ollama client just for mem0.++Two pieces:++- :class:`AgentScopeLLM` — implements ``mem0.llms.base.LLMBase`` by+ delegating to an ``agentscope.model.ChatModelBase`` instance.+- :class:`AgentScopeEmbedding` — implements+ ``mem0.embeddings.base.EmbeddingBase`` by delegating to an+ ``agentscope.embedding.EmbeddingModelBase`` instance.++mem0 calls these synchronously; AgentScope models are async. We bridge+the two with ``asyncio.get_event_loop().run_until_complete()`` which+executes the coroutine on the caller's event loop.++Use :func:`build_mem0_config` to produce a ``MemoryConfig`` wired to+AgentScope models:++ from mem0 import AsyncMemory+ from agentscope.middleware._longterm_memory._mem0._agentscope_adapter \\+ import build_mem0_config++ mem0_client = AsyncMemory(+ config=build_mem0_config(+ chat_model=my_chat_model,+ embedding_model=my_embedding_model,+ ),+ )+"""+from __future__ import annotations++import asyncio+import json+import threading+from collections.abc import AsyncGenerator+from typing import Any, TYPE_CHECKING++from mem0.configs.embeddings.base import BaseEmbedderConfig+from mem0.configs.llms.base import BaseLlmConfig+from mem0.embeddings.base import EmbeddingBase+from mem0.llms.base import LLMBase++from ....embedding import EmbeddingModelBase+from ....message import (+ AssistantMsg,+ Msg,+ SystemMsg,+ UserMsg,+)+from ....model import ChatModelBase++if TYPE_CHECKING:+ from ....model import ChatResponse+++# ----------------------------------------------------------------------+# Sync → async bridge+# ----------------------------------------------------------------------+++class _AsyncBridge:+ """Run async coroutines synchronously on a dedicated, long-lived+ event loop.++ mem0's ``LLMBase.generate_response`` / ``EmbeddingBase.embed`` are+ sync, but AgentScope models are async. The bridge owns one event+ loop running on its own daemon thread and submits coroutines to it+ via ``run_coroutine_threadsafe``, blocking for the result. The loop+ stays alive for the bridge's lifetime, so async clients created+ inside the model are reused and cleaned up against a live loop.+ """++ def __init__(self) -> None:+ self._loop = asyncio.new_event_loop()+ self._thread = threading.Thread(+ target=self._loop.run_forever,+ name="mem0-agentscope-bridge",+ daemon=True,+ )+ self._thread.start()++ def run(self, coro: Any) -> Any:+ """Submit ``coro`` to the bridge loop and block for its result."""+ return asyncio.run_coroutine_threadsafe(coro, self._loop).result()+++# ----------------------------------------------------------------------+# LLM adapter+# ----------------------------------------------------------------------+++class AgentScopeLLM(LLMBase):+ """mem0 ``LLMBase`` backed by an AgentScope ``ChatModelBase``.++ Pass your AgentScope model into ``config["model"]``; mem0's memory+ extraction calls then route through it. Both streaming and+ non-streaming AgentScope models are accepted (streaming responses are+ drained and the final chunk is used).+ """++ def __init__(+ self,+ config: BaseLlmConfig | dict | None = None,+ ) -> None:+ """Initialize the AgentScope LLM for mem0."""+ super().__init__(config)+ if self.config.model is None:+ raise ValueError(+ "AgentScopeLLM requires `model` in the config to be an "+ "AgentScope ChatModelBase instance.",+ )+ if not isinstance(self.config.model, ChatModelBase):+ raise TypeError(+ f"AgentScopeLLM `model` must be a ChatModelBase, got "+ f"{type(self.config.model).__name__}.",+ )+ self._agentscope_model: ChatModelBase = self.config.model+ self._bridge = _AsyncBridge()++ # ----- LLMBase interface -----+ # pylint: disable=unused-argument+ def generate_response(+ self,+ messages: list[dict[str, str]],+ response_format: Any | None = None, # mem0 contract — unused+ tools: list[dict] | None = None,+ tool_choice: str = "auto", # mem0 contract — unused+ ) -> str | dict:+ """mem0 ``LLMBase`` entry — runs the AgentScope chat model+ synchronously and returns str (or dict with tool_calls when+ ``tools`` is given)."""+ as_messages = _convert_messages_to_agentscope(messages)+ if not as_messages:+ raise ValueError(+ "AgentScopeLLM received no usable messages "+ "(empty list or all roles unrecognized).",+ )++ response = self._bridge.run(+ _await_chat(self._agentscope_model, as_messages, tools),+ )+ return _parse_chat_response(response, has_tool=bool(tools))+++async def _await_chat(+ model: ChatModelBase,+ messages: list[Msg],+ tools: list[dict] | None,+) -> "ChatResponse":+ """Call the AgentScope chat model, handling both streaming and+ non-streaming returns."""+ result = await model(messages, tools=tools)+ # Streaming model — drain the generator and keep the final chunk,+ # which carries the complete content per AgentScope's streaming+ # contract. ``isinstance`` (not ``hasattr``) — Pydantic BaseModel+ # raises KeyError instead of AttributeError on missing dunder+ # attrs, which ``hasattr`` does not catch.+ if isinstance(result, AsyncGenerator):+ last = None+ async for chunk in result:+ last = chunk+ if last is None:+ raise RuntimeError(+ "AgentScope streaming model yielded no chunks.",+ )+ return last+ return result+++def _convert_messages_to_agentscope(+ messages: list[dict[str, str]],+) -> list[Msg]:+ """mem0 hands us OpenAI-style ``[{"role", "content"}, ...]`` dicts;+ AgentScope wants ``Msg`` objects."""+ out: list[Msg] = []+ for m in messages:+ role = m.get("role")+ content = m.get("content", "")+ if role == "system":+ out.append(SystemMsg(name="system", content=content))+ elif role == "user":+ out.append(UserMsg(name="user", content=content))+ elif role == "assistant":+ out.append(AssistantMsg(name="assistant", content=content))+ # unknown roles silently dropped — matches v1 behavior+ return out+++def _parse_chat_response(+ response: "ChatResponse",+ has_tool: bool,+) -> str | dict:+ """Flatten an AgentScope ``ChatResponse`` into the str/dict shape+ mem0 expects from ``LLMBase.generate_response``."""+ text_parts: list[str] = []+ thinking_parts: list[str] = []+ tool_parts: list[dict] = []++ for block in response.content or []:+ block_type = getattr(block, "type", None)+ if block_type == "text":+ text_parts.append(block.text or "")+ elif block_type == "thinking":+ thinking_parts.append(f"[Thinking: {block.thinking or ''}]")+ elif block_type == "tool_call":+ # AgentScope 2.0 stores tool args as a JSON string; mem0+ # expects an arguments' dict.+ raw_input = block.input or "{}"+ try:+ arguments = json.loads(raw_input)+ except json.JSONDecodeError:+ arguments = raw_input+ tool_parts.append(+ {"name": block.name, "arguments": arguments},+ )+ # DataBlock and other types are not part of mem0's contract.++ text_out = "\n".join(thinking_parts + text_parts)+ if has_tool:+ return {"content": text_out, "tool_calls": tool_parts}+ return text_out+++# ----------------------------------------------------------------------+# Embedding adapter+# ----------------------------------------------------------------------+++class AgentScopeEmbedding(EmbeddingBase):+ """mem0 ``EmbeddingBase`` backed by an AgentScope+ ``EmbeddingModelBase``."""++ def __init__(+ self,+ config: BaseEmbedderConfig | dict | None = None,+ ) -> None:+ # mem0's EmbeddingBase (unlike LLMBase) does NOT auto-convert+ # dict configs — it stores whatever is passed. Normalize here+ # so callers can use the same dict-config style as the LLM.+ if isinstance(config, dict):+ config = BaseEmbedderConfig(**config)+ super().__init__(config)+ if self.config.model is None:+ raise ValueError(+ "AgentScopeEmbedding requires `model` in the config "+ "to be an AgentScope EmbeddingModelBase instance.",+ )+ if not isinstance(self.config.model, EmbeddingModelBase):+ raise TypeError(+ f"AgentScopeEmbedding `model` must be an "+ f"EmbeddingModelBase, got "+ f"{type(self.config.model).__name__}.",+ )+ self._agentscope_model: EmbeddingModelBase = self.config.model+ self._bridge = _AsyncBridge()++ # ----- EmbeddingBase interface -----+ # pylint: disable=unused-argument+ def embed(+ self,+ text: str | list[str],+ memory_action: str | None = None, # mem0 contract — unused+ ) -> list[float]:+ """mem0 ``EmbeddingBase`` entry — runs the AgentScope embedding+ model synchronously and returns the first vector."""+ text_list = [text] if isinstance(text, str) else list(text)+ response = self._bridge.run(self._agentscope_model(text_list))+ if not response.embeddings:+ raise RuntimeError(+ "AgentScope embedding model returned no embeddings.",+ )+ # AgentScope EmbeddingResponse.embeddings is List[List[float]];+ # mem0 expects a single vector for a single-text call.+ return response.embeddings[0]+++# ----------------------------------------------------------------------+# Build a mem0 MemoryConfig wired to AgentScope models+# ----------------------------------------------------------------------++# The provider name we register under in mem0's factory + config layer.+_AGENTSCOPE_PROVIDER = "agentscope"+++def build_mem0_config(+ *,+ chat_model: ChatModelBase | None = None,+ embedding_model: EmbeddingModelBase | None = None,+ mem0_config: Any | None = None,+) -> Any:+ """Build a ``mem0.configs.base.MemoryConfig`` wired to AgentScope+ chat / embedding models.++ Three calling shapes:++ 1. ``build_mem0_config(chat_model=..., embedding_model=...)``+ — build a fresh config (mem0 defaults for vector_store /+ history_db / reranker etc.) with both LLM and embedder routed+ through AgentScope.+ 2. ``build_mem0_config(mem0_config=cfg, chat_model=...,+ embedding_model=...)`` — start from your customized+ ``MemoryConfig`` and override only ``.llm`` / ``.embedder`` with+ the AgentScope adapters. Use this when you want a non-default+ vector store / history DB / reranker but still want AgentScope+ to drive memory extraction. Either or both of ``chat_model``+ and ``embedding_model`` may be passed — fields you omit keep+ whatever the input config had.+ 3. ``build_mem0_config(mem0_config=cfg)`` — pass-through; the+ AgentScope adapters are registered (cheap) but no fields are+ overridden.++ Why a helper? Two private layers inside mem0 reject anything+ outside its built-in provider list, so plugging in AgentScope+ requires both:++ 1. Adding ``"agentscope"`` to ``LlmFactory.provider_to_class`` /+ ``EmbedderFactory.provider_to_class`` so the factory can+ construct our adapter classes.+ 2. Bypassing the hardcoded provider whitelist in+ ``LlmConfig.validate_config`` / ``EmbedderConfig.validate_config``.+ Done by substituting subclasses whose validator only allows+ ``"agentscope"``. Other provider names are rejected by these+ subclasses, matching the fact that this helper is only for wiring+ the AgentScope adapters.++ Args:+ chat_model:+ The AgentScope ``ChatModelBase`` mem0 should use for memory+ extraction. Required when ``mem0_config`` is not given.+ embedding_model:+ The AgentScope ``EmbeddingModelBase`` mem0 should use to+ embed memories. Its ``dimensions`` must match the vector+ store's expected dim (mem0's default Qdrant expects 1536).+ Required when ``mem0_config`` is not given.+ mem0_config:+ Optional pre-built ``MemoryConfig`` to use as the base.+ When given, only the LLM / embedder slots are overridden+ from ``chat_model`` / ``embedding_model`` — every other+ field (``vector_store``, ``history_db_path``, ``reranker``,+ ``custom_instructions``, ``version``) is preserved.++ Returns:+ A ``MemoryConfig`` ready to pass to ``AsyncMemory(config=...)``+ or ``Memory(config=...)``.+ """+ from mem0.configs.base import MemoryConfig++ _register_agentscope_provider()+ llm_cfg_cls, emb_cfg_cls = _agentscope_config_classes()++ if mem0_config is None:+ if chat_model is None or embedding_model is None:+ raise ValueError(+ "build_mem0_config requires `chat_model` and "+ "`embedding_model` when `mem0_config` is not given.",+ )+ return MemoryConfig(+ llm=llm_cfg_cls(+ provider=_AGENTSCOPE_PROVIDER,+ config={"model": chat_model},+ ),+ embedder=emb_cfg_cls(+ provider=_AGENTSCOPE_PROVIDER,+ config={"model": embedding_model},+ ),+ )++ # Use the user's config as base; partial-override .llm / .embedder+ # only for fields they actually passed. Pydantic v2 doesn't+ # re-validate on attribute assignment, so this sticks.+ if chat_model is not None:+ mem0_config.llm = llm_cfg_cls(+ provider=_AGENTSCOPE_PROVIDER,+ config={"model": chat_model},+ )+ if embedding_model is not None:+ mem0_config.embedder = emb_cfg_cls(+ provider=_AGENTSCOPE_PROVIDER,+ config={"model": embedding_model},+ )+ return mem0_config+++def _register_agentscope_provider() -> None:+ """Plug the AgentScope adapter classes into mem0's factory dicts+ under provider name ``"agentscope"``. Idempotent."""+ from mem0.utils.factory import EmbedderFactory, LlmFactory++ LlmFactory.provider_to_class[_AGENTSCOPE_PROVIDER] = (+ f"{__name__}.AgentScopeLLM",+ BaseLlmConfig,+ )+ EmbedderFactory.provider_to_class[+ _AGENTSCOPE_PROVIDER+ ] = f"{__name__}.AgentScopeEmbedding"+++def _agentscope_config_classes() -> tuple[type, type]:+ """Return ``LlmConfig`` / ``EmbedderConfig`` subclasses whose+ validator allows ``provider="agentscope"`` (and only that — every+ other provider continues to be rejected with the same error mem0+ would have raised)."""+ from pydantic import field_validator++ from mem0.embeddings.configs import EmbedderConfig+ from mem0.llms.configs import LlmConfig++ class _AgentScopeLlmConfig(LlmConfig):+ """``LlmConfig`` subclass that accepts the AgentScope provider."""++ @field_validator("config")+ @classmethod+ def validate_config(cls, v: Any, values: Any) -> Any:+ """Allow ``provider == "agentscope"``; reject everything+ else with mem0's original error."""+ provider = values.data.get("provider")+ if provider == _AGENTSCOPE_PROVIDER:+ return v+ raise ValueError(f"Unsupported LLM provider: {provider}")++ class _AgentScopeEmbedderConfig(EmbedderConfig):+ """``EmbedderConfig`` subclass that accepts the AgentScope+ provider."""++ @field_validator("config")+ @classmethod+ def validate_config(cls, v: Any, values: Any) -> Any:+ """Allow ``provider == "agentscope"``; reject everything+ else with mem0's original error."""+ provider = values.data.get("provider")+ if provider == _AGENTSCOPE_PROVIDER:+ return v+ raise ValueError(+ f"Unsupported embedding provider: {provider}",+ )++ return _AgentScopeLlmConfig, _AgentScopeEmbedderConfigdiff --git a/src/agentscope/middleware/_longterm_memory/_mem0/_middleware.py b/src/agentscope/middleware/_longterm_memory/_mem0/_middleware.pynew file mode 100644index 000000000..5c65f95b0--- /dev/null+++ b/src/agentscope/middleware/_longterm_memory/_mem0/_middleware.py@@ -0,0 +1,741 @@+# -*- coding: utf-8 -*-+"""mem0-backed long-term memory middleware for AgentScope agents.++Works with either ``mem0.AsyncMemory`` (open-source) or+``mem0.AsyncMemoryClient`` (hosted Platform). Both clients converge on+the same call shape:++- ``search(query, filters={"user_id": ..., "agent_id": ...}, top_k=...)``+- ``add(messages, user_id=..., agent_id=...)``++so one middleware class handles both.+"""+from __future__ import annotations++import asyncio+import inspect+from typing import (+ Any,+ AsyncGenerator,+ Callable,+ Literal,+ TYPE_CHECKING,+)+from ..._base import MiddlewareBase+from ...._logging import logger+from ....event import ReplyStartEvent+from ....message import AssistantMsg, HintBlock, Msg+from ._tools import _build_memory_tools+from ._utils import (+ _extract_memory_texts,+ _extract_query_text,+ _mem0_extracted_anything,+)++if TYPE_CHECKING:+ from typing import TypeAlias++ from mem0 import AsyncMemory, AsyncMemoryClient++ from ....agent import Agent+ from ....embedding import EmbeddingModelBase+ from ....model import ChatModelBase+ from ....tool import ToolBase++ # Explicit ``TypeAlias`` annotation tells mypy this is a type+ # alias rather than a plain variable assignment — without it+ # mypy 1.7+ refuses to use ``Mem0AsyncClient`` in annotation+ # positions ("Variable is not valid as a type").+ Mem0AsyncClient: TypeAlias = AsyncMemory | AsyncMemoryClient+++def _looks_async(method: Any) -> bool:+ """Detect "async-callable" methods, including ones wrapped by a+ sync ``@functools.wraps`` decorator that returns the underlying+ coroutine.++ Plain ``inspect.iscoroutinefunction`` is too strict for mem0's+ Platform client: ``AsyncMemoryClient.search`` is ``async def`` but+ decorated by mem0's ``@api_error_handler``, which is a sync wrapper+ that returns the coroutine produced by calling the underlying async+ function. The wrapper itself isn't a coroutine function, so the+ naive check rejects an otherwise-valid client. ``inspect.unwrap``+ walks ``__wrapped__`` (set by ``functools.wraps``) until it finds+ the original async ``func``, which the strict check then accepts.+ """+ if method is None:+ return False+ return inspect.iscoroutinefunction(inspect.unwrap(method))+++DEFAULT_MEMORY_SECTION_HEADER = "## Relevant memories from past conversations"+DEFAULT_MEMORY_SECTION_INTRO = (+ "The following memories about the user may be relevant. "+ "Use them only if they are pertinent to the current request."+)++DEFAULT_TOOL_INSTRUCTIONS = (+ "## Long-term memory\n\n"+ "You have `search_memory` and `add_memory` tools available. Use "+ "them whenever the conversation depends on (search) or contributes "+ "(add) a durable fact about the user — see each tool's own "+ "description for the exact input shape and usage guidance."+)+++class Mem0Middleware(MiddlewareBase):+ """AgentScope middleware that adds long-term memory backed by+ `mem0 <https://github.com/mem0ai/mem0>`_.++ Two construction paths:++ 1. **Models** — pass an AgentScope ``chat_model`` and+ ``embedding_model`` (optionally with a custom ``mem0_config``+ as base for vector store / history DB / etc.). The middleware+ builds an OSS ``AsyncMemory`` internally, wired so mem0's+ memory extraction and embedding both go through your AgentScope+ models.+ 2. **Client** — pass a pre-built ``mem0.AsyncMemory`` /+ ``mem0.AsyncMemoryClient`` when you want full control (e.g.+ hosted Platform, sharing one mem0 across agents). When+ ``client`` is 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],+ )+ """++ def __init__(+ self,+ *,+ 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:+ """Initialize the mem0 middleware.++ 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).+ - **Models + ``mem0_config``** — same but starts from your+ customized ``MemoryConfig``; only ``.llm`` / ``.embedder``+ slots are overridden with the AgentScope adapters, every+ other field (vector store, history DB, reranker, ...) is+ preserved.+ - **Client** — pass a pre-built mem0 client (OSS / Platform /+ custom). When ``client`` is given it takes absolute+ precedence; ``chat_model`` / ``embedding_model`` /+ ``mem0_config`` are ignored, with a warning listing any+ ignored kwargs.++ Args:+ user_id:+ The mem0 ``user_id`` for memory namespacing. Required.+ client:+ 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_model:+ 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_model:+ 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_config:+ 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``.+ mode:+ 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_id:+ 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_k:+ 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).+ threshold:+ Minimum similarity score. ``None`` lets mem0 decide.+ scope_search_by_agent:+ 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_write:+ 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).+ tool_instructions:+ Markdown block appended to the agent's system prompt+ in ``agent_control`` / ``both`` modes, advertising the+ ``search_memory`` / ``add_memory`` tools to the LLM.+ """+ is_empty_user_id = isinstance(user_id, str) and not user_id.strip()+ if user_id is None or is_empty_user_id:+ raise ValueError(+ "Mem0Middleware requires a non-empty `user_id`.",+ )+ if mode not in ("static_control", "agent_control", "both"):+ raise ValueError(+ f"Unknown mode {mode!r}; expected one of "+ f"'static_control', 'agent_control', 'both'.",+ )++ client = self._resolve_client(+ client=client,+ chat_model=chat_model,+ embedding_model=embedding_model,+ mem0_config=mem0_config,+ )+ self._client = client++ self._user_id = user_id+ self._agent_id = agent_id+ self._mode = mode+ self._top_k = top_k+ self._threshold = threshold+ self._scope_search_by_agent = scope_search_by_agent+ self._await_write = await_write+ self._memory_section_header = memory_section_header+ self._memory_section_intro = memory_section_intro+ self._tool_instructions = tool_instructions++ # ------------------------------------------------------------------+ # Hook: on_reply+ # ------------------------------------------------------------------+ async def on_reply(+ self,+ agent: "Agent",+ input_kwargs: dict,+ next_handler: Callable[..., AsyncGenerator],+ ) -> AsyncGenerator:+ user_id = self._user_id+ agent_id = self._agent_id++ # In pure agent_control mode the middleware is a no-op on the+ # reply path — the agent decides when to invoke the memory+ # tools — so just pass through.+ if self._mode == "agent_control":+ async for item in next_handler(**input_kwargs):+ yield item+ return++ # static_control / both, mirroring AgentScope 1.x's ReActAgent:+ # 1. Pre-fetch memories from mem0 using the user's new query.+ # 2. Once the agent has actually ingested the new user input+ # into state.context (signaled by ReplyStartEvent — fires+ # right after _handle_incoming_messages and before the+ # reasoning loop), append the memory note. This places the+ # note IMMEDIATELY AFTER the user message in context, same+ # slot as v1's `_retrieve_from_long_term_memory` (which ran+ # right after `self.memory.add(msg)`).+ # 3. After the reply finishes, write the new exchange back.+ #+ # The memory note persists in state.context across turns. Long+ # sessions will accumulate one per turn that retrieved+ # anything; rely on ``compress_context`` or pop them yourself+ # if that becomes a token concern.+ # user_id / agent_id already resolved + cached above.++ inputs = input_kwargs.get("inputs")+ query_text = _extract_query_text(inputs)++ memories: list[str] = []+ if query_text:+ search_agent_id = agent_id if self._scope_search_by_agent else None+ logger.info(+ "mem0 search started: user_id=%s agent_id=%s chars=%d",+ user_id,+ search_agent_id,+ len(query_text),+ )+ try:+ memories = await self._async_search(+ query_text,+ user_id=user_id,+ agent_id=search_agent_id,+ )+ logger.info(+ "mem0 search finished: user_id=%s agent_id=%s memories=%d",+ user_id,+ search_agent_id,+ len(memories),+ )+ except Exception as e: # noqa: BLE001+ logger.warning(+ "mem0 search failed for user_id=%s: %s",+ user_id,+ e,+ )++ final_msg: Msg | None = None+ injected = False+ try:+ async for item in next_handler(**input_kwargs):+ is_reply_start = isinstance(item, ReplyStartEvent)+ if not injected and memories and is_reply_start:+ agent.state.context.append(+ self._build_memory_message(memories),+ )+ injected = True+ if isinstance(item, Msg) and item.role == "assistant":+ final_msg = item+ yield item+ finally:+ if query_text and final_msg is not None:+ assistant_text = final_msg.get_text_content()+ if assistant_text:+ await self._dispatch_write(+ [+ {"role": "user", "content": query_text},+ {"role": "assistant", "content": assistant_text},+ ],+ user_id=user_id,+ agent_id=agent_id,+ )++ # ------------------------------------------------------------------+ # Hook: on_system_prompt (advertise memory tools to the LLM)+ # ------------------------------------------------------------------+ async def on_system_prompt(+ self,+ agent: "Agent",+ current_prompt: str,+ ) -> str:+ """Append memory-tool instructions to the system prompt.++ Args:+ agent (`Agent`):+ The agent whose system prompt is being transformed.+ current_prompt (`str`):+ The system prompt produced by previous middleware.++ Returns:+ `str`:+ The unchanged prompt in static-control mode, otherwise the+ prompt with memory-tool instructions appended.+ """+ if self._mode == "static_control":+ return current_prompt+ return f"{current_prompt}\n\n{self._tool_instructions}"++ async def list_tools(self) -> list["ToolBase"]:+ """List memory tools provided by this middleware.++ Returns:+ `list[ToolBase]`:+ The ``search_memory`` and ``add_memory`` tools in+ agent-control modes, otherwise an empty list.+ """+ if self._mode == "static_control":+ return []+ return _build_memory_tools(self)++ # ==================================================================+ # mem0 client construction+ # ==================================================================+ @staticmethod+ def _resolve_client(+ *,+ client: "Mem0AsyncClient | None",+ chat_model: "ChatModelBase | None",+ embedding_model: "EmbeddingModelBase | None",+ mem0_config: Any | None,+ ) -> "Mem0AsyncClient":+ """Resolve the constructor's mem0-backend kwargs into a single+ async client.++ ``client=`` takes absolute precedence — if given, the other+ three (``chat_model`` / ``embedding_model`` / ``mem0_config``)+ are ignored (a warning is logged so the mismatch is not+ invisible). Otherwise, the rest are combined by+ :func:`build_mem0_config` into an ``AsyncMemory``.+ """+ if client is not None:+ ignored = [+ name+ for name, value in (+ ("chat_model", chat_model),+ ("embedding_model", embedding_model),+ ("mem0_config", mem0_config),+ )+ if value is not None+ ]+ if ignored:+ logger.warning(+ "Mem0Middleware: `client` was provided, so %s "+ "%s ignored. Pass them via the mem0 client itself "+ "(or omit `client` to let the middleware build one "+ "for you).",+ ", ".join(ignored),+ "is" if len(ignored) == 1 else "are",+ )+ if client is None:+ no_models = chat_model is None and embedding_model is None+ if mem0_config is None and no_models:+ raise ValueError(+ "Mem0Middleware needs one of: a pre-built `client`, "+ "a `mem0_config`, or both `chat_model` and "+ "`embedding_model`.",+ )+ # When no mem0_config is given, models must come as a pair.+ if mem0_config is None and (+ (chat_model is None) ^ (embedding_model is None)+ ):+ raise ValueError(+ "Mem0Middleware: `chat_model` and "+ "`embedding_model` must be passed together when "+ "`mem0_config` is not given.",+ )++ from mem0 import AsyncMemory++ from ._agentscope_adapter import build_mem0_config++ client = AsyncMemory(+ config=build_mem0_config(+ chat_model=chat_model,+ embedding_model=embedding_model,+ mem0_config=mem0_config,+ ),+ )++ if not _looks_async(+ getattr(client, "search", None),+ ) or not _looks_async(getattr(client, "add", None)):+ raise TypeError(+ "Mem0Middleware requires an async mem0 client "+ "(`mem0.AsyncMemory` or `mem0.AsyncMemoryClient`). "+ "The synchronous `Memory` / `MemoryClient` are not "+ "supported.",+ )+ return client++ # ==================================================================+ # mem0 client adapters (OSS + Platform share this call shape)+ # ==================================================================+ async def _async_search(+ self,+ query: str,+ *,+ user_id: str,+ agent_id: str | None,+ top_k: int | None = None,+ ) -> list[str]:+ """Search mem0 and normalize the result into memory strings.++ Args:+ query (`str`):+ Search query text.+ user_id (`str`):+ mem0 ``user_id`` namespace.+ agent_id (`str | None`):+ Optional mem0 ``agent_id`` namespace. ``None`` searches by+ user only.+ top_k (`int | None`, optional):+ Optional per-call result limit. Defaults to the middleware's+ configured ``top_k``.++ Returns:+ `list[str]`:+ Retrieved memory texts extracted from mem0's response.+ """+ filters: dict[str, Any] = {"user_id": user_id}+ if agent_id:+ filters["agent_id"] = agent_id++ kwargs: dict[str, Any] = {+ "filters": filters,+ "top_k": self._top_k if top_k is None else top_k,+ }+ if self._threshold is not None:+ kwargs["threshold"] = self._threshold++ raw = await self._client.search(query, **kwargs)+ return _extract_memory_texts(raw)++ async def _async_add(+ self,+ messages: list[dict[str, str]],+ *,+ user_id: str,+ agent_id: str | None,+ infer: bool = True,+ ) -> dict | None:+ """Add messages to mem0 using the shared async client call shape.++ Args:+ messages (`list[dict[str, str]]`):+ mem0-compatible message dictionaries.+ user_id (`str`):+ mem0 ``user_id`` namespace.+ agent_id (`str | None`):+ Optional mem0 ``agent_id`` namespace.+ infer (`bool`, optional):+ Whether mem0 should run memory extraction. ``False`` asks+ mem0 to store the text directly.++ Returns:+ `dict | None`:+ The raw result returned by mem0.+ """+ kwargs: dict[str, Any] = {"user_id": user_id}+ if agent_id:+ kwargs["agent_id"] = agent_id+ if not infer:+ # mem0 docstring: ``infer=False`` skips the LLM extraction+ # step and stores the message text directly.+ kwargs["infer"] = False++ return await self._client.add(messages, **kwargs)++ async def _async_add_with_fallback(+ self,+ text: str,+ *,+ user_id: str,+ agent_id: str | None,+ ) -> dict | None:+ """Two-tier add strategy: try extraction first; if mem0's+ extraction LLM returns no memories, fall back to ``infer=False``+ and save the raw text. Guarantees that ``add_memory`` always+ persists *something* — matching AgentScope 1.x's+ ``record_to_memory`` "always save" contract.++ Historical note — why this is 2 tiers, not 3+ ---------------------------------------------+ AgentScope 1.x's ``record_to_memory`` had a 3-tier fallback:+ (a) user role → (b) assistant role → (c) assistant + infer=False.+ Tier (b) was meaningful against **old** mem0, which routed+ user-role messages through ``USER_MEMORY_EXTRACTION_PROMPT``+ and assistant-role messages through+ ``AGENT_MEMORY_EXTRACTION_PROMPT`` — two genuinely different+ prompts, so switching role had a real chance of rescuing an+ empty extraction.++ Current mem0 (v2.x) restructured this in+ ``_add_to_vector_store``:++ parsed_messages = parse_messages(messages)+ ...+ is_agent_scoped = bool(filters.get("agent_id")) \\+ and not filters.get("user_id")+ system_prompt = ADDITIVE_EXTRACTION_PROMPT+ if is_agent_scoped:+ system_prompt += AGENT_CONTEXT_SUFFIX++ Prompt selection now depends on the **filters dict**, not on+ the message role. ``ADDITIVE_EXTRACTION_PROMPT`` itself says+ explicitly "You extract from BOTH user and assistant messages"+ (it just changes attribution framing). Since this middleware+ always passes both ``user_id`` and ``agent_id`` (when scoping+ is on), ``is_agent_scoped`` is always False and the same+ ``ADDITIVE_EXTRACTION_PROMPT`` runs regardless of message role.+ Retrying with role="assistant" is a no-op LLM call.++ So tier (b) is dropped. Tier (c) ``infer=False`` is still+ valuable — it bypasses extraction entirely and saves raw+ text, useful when mem0 decides nothing in the input is+ memory-worthy but the caller wants the bytes persisted anyway.+ """+ # 1. Normal path: let mem0's extraction LLM do its job.+ result = await self._async_add(+ [{"role": "user", "content": text, "name": "user"}],+ user_id=user_id,+ agent_id=agent_id,+ )+ if _mem0_extracted_anything(result):+ return result++ # 2. Raw save: extraction returned empty, persist the raw text+ # so the caller's ``add_memory`` invocation isn't silently+ # discarded.+ return await self._async_add(+ [{"role": "user", "content": text, "name": "user"}],+ user_id=user_id,+ agent_id=agent_id,+ infer=False,+ )++ # ==================================================================+ # Helpers+ # ==================================================================+ def _build_memory_message(self, memories: list[str]) -> Msg:+ """Format retrieved ``memories`` as a synthetic hint message.++ The context entry uses an assistant-role ``Msg`` container because+ user messages cannot carry ``HintBlock`` content. Formatters convert+ the ``HintBlock`` itself into a user message before the model call.++ Args:+ memories (`list[str]`):+ Retrieved memory texts to expose to the model.++ Returns:+ `Msg`:+ An assistant-role message containing one ``HintBlock``.+ """+ bullets = "\n".join(f"- {m}" for m in memories)+ content = (+ f"{self._memory_section_header}\n"+ f"{self._memory_section_intro}\n"+ f"{bullets}"+ )+ return AssistantMsg(+ name="memory",+ content=[HintBlock(hint=content)],+ )++ async def _dispatch_write(+ self,+ messages: list[dict[str, str]],+ *,+ user_id: str,+ agent_id: str | None,+ ) -> None:+ """Persist a completed user/assistant exchange to mem0.++ When ``await_write`` is enabled, the add call is awaited inline so+ errors can be logged before reply cleanup completes. Otherwise, to+ write is scheduled as a background task and failures are logged there.++ Args:+ messages (`list[dict[str, str]]`):+ User/assistant message pair to persist.+ user_id (`str`):+ mem0 ``user_id`` namespace.+ agent_id (`str | None`):+ Optional mem0 ``agent_id`` namespace.+ """+ if self._await_write:+ try:+ logger.info(+ "mem0 write started: user_id=%s agent_id=%s messages=%d",+ user_id,+ agent_id,+ len(messages),+ )+ await self._async_add(+ messages,+ user_id=user_id,+ agent_id=agent_id,+ )+ logger.info(+ "mem0 write finished for user_id=%s agent_id=%s",+ user_id,+ agent_id,+ )+ except Exception as e: # noqa: BLE001+ logger.warning(+ "mem0 add failed for user_id=%s: %s",+ user_id,+ e,+ )+ else:++ async def _bg() -> None:+ try:+ logger.info(+ "mem0 background write started for user_id=%s "+ "agent_id=%s messages=%d",+ user_id,+ agent_id,+ len(messages),+ )+ await self._async_add(+ messages,+ user_id=user_id,+ agent_id=agent_id,+ )+ logger.info(+ "mem0 bg write finished: user_id=%s agent_id=%s",+ user_id,+ agent_id,+ )+ except Exception as e: # noqa: BLE001+ logger.warning(+ "mem0 background add failed for user_id=%s: %s",+ user_id,+ e,+ )++ asyncio.create_task(_bg())diff --git a/src/agentscope/middleware/_longterm_memory/_mem0/_tools.py b/src/agentscope/middleware/_longterm_memory/_mem0/_tools.pynew file mode 100644index 000000000..633ed891d--- /dev/null+++ b/src/agentscope/middleware/_longterm_memory/_mem0/_tools.py@@ -0,0 +1,270 @@+# -*- coding: utf-8 -*-+# pylint: disable=protected-access+"""Agent-control tools exposed by the mem0 middleware.++These ``search_memory`` / ``add_memory`` tools are listed by+:class:`Mem0Middleware` when ``mode`` is ``"agent_control"`` or+``"both"``. Callers pass them into the agent's toolkit explicitly.+Each tool reads ``user_id`` / ``agent_id`` directly from the+middleware instance — both are plain strings set at construction+time, so no Agent instance is stored or referenced at call time.++Shape and behavior mirror AgentScope 1.x's+``Mem0LongTermMemory.retrieve_from_memory`` / ``record_to_memory``+(multi-keyword parallel search, fallback write, verbose result+text) — adapted to AgentScope 2.x's tool conventions+(custom ``ToolBase`` implementations; failures return a ``ToolChunk``+with ``state=ERROR`` so the toolkit aggregates it properly).+"""+from __future__ import annotations++import asyncio+from typing import Any, TYPE_CHECKING++from ....message import TextBlock, ToolResultState+from ....permission import PermissionBehavior, PermissionDecision+from ....tool import ToolBase, ToolChunk++if TYPE_CHECKING:+ from ._middleware import Mem0Middleware+++class _Mem0MemoryToolBase(ToolBase):+ """Base class for mem0 tools that auto-allow themselves.++ Middleware-provided memory tools are part of the agent's standard+ capabilities — prompting on every call would defeat the point.+ """++ is_external_tool: bool = False+ is_state_injected: bool = False+ is_mcp: bool = False+ mcp_name: str | None = None++ def __init__(+ self,+ mw: "Mem0Middleware",+ ) -> None:+ self._mw = mw++ async def check_permissions(+ self,+ *_args: Any,+ **_kwargs: Any,+ ) -> PermissionDecision:+ return PermissionDecision(+ behavior=PermissionBehavior.ALLOW,+ message="auto-allowed: mem0 long-term memory tool",+ )+++class _SearchMemoryTool(_Mem0MemoryToolBase):+ """Agent-callable mem0 search tool."""++ name: str = "search_memory"+ description: str = (+ "Retrieve memories based on short, targeted search keywords. "+ "Each keyword is issued as an independent query; results are merged "+ "and deduplicated."+ )+ input_schema: dict[str, Any] = {+ "type": "object",+ "properties": {+ "keywords": {+ "type": "array",+ "items": {"type": "string"},+ "description": (+ "Short, targeted search phrases such as a person's name, "+ "a specific date, a location, or a phrase describing what "+ "to retrieve from memory."+ ),+ },+ "limit": {+ "type": "integer",+ "description": (+ "Maximum number of memories to retrieve per keyword."+ ),+ "default": 5,+ },+ },+ "required": ["keywords"],+ }+ is_concurrency_safe: bool = True+ is_read_only: bool = True++ async def __call__(+ self,+ keywords: list[str],+ limit: int = 5,+ ) -> ToolChunk:+ """Retrieve the memory based on the given keywords.++ Args:+ keywords (list[str]):+ Short, targeted search phrases (for example, a person's+ name, a specific date, a location, or a phrase+ describing something you want to retrieve from the+ memory). Each keyword is issued as an independent query+ against the memory store; results are merged and+ deduplicated.+ limit (int):+ The maximum number of memories to retrieve per keyword.+ Defaults to 5.+ """+ if not keywords:+ return _text_chunk("(no keywords supplied — nothing to search)")++ user_id = self._mw._user_id+ agent_id = self._mw._agent_id+ search_agent_id = agent_id if self._mw._scope_search_by_agent else None++ # Match v1: each keyword is an independent search, run them in+ # parallel and merge.+ try:+ per_keyword = await asyncio.gather(+ *[+ self._mw._async_search(+ kw,+ user_id=user_id,+ agent_id=search_agent_id,+ top_k=limit,+ )+ for kw in keywords+ ],+ )+ except Exception as e: # noqa: BLE001+ return _error_chunk(f"Error retrieving memory: {e}")++ seen: set[str] = set()+ merged: list[str] = []+ for results in per_keyword:+ for r in results:+ if r not in seen:+ seen.add(r)+ merged.append(r)++ if not merged:+ return _text_chunk("(no relevant memories found)")+ return _text_chunk("\n".join(f"- {m}" for m in merged))+++class _AddMemoryTool(_Mem0MemoryToolBase):+ """Agent-callable mem0 write tool."""++ name: str = "add_memory"+ description: str = (+ "Record important, durable information that may be useful later. "+ "Only the provided content is persisted; thinking is retained in the "+ "tool result for auditability."+ )+ input_schema: dict[str, Any] = {+ "type": "object",+ "properties": {+ "thinking": {+ "type": "string",+ "description": (+ "Reasoning about why this information is worth "+ "remembering. This is not persisted to mem0."+ ),+ },+ "content": {+ "type": "array",+ "items": {"type": "string"},+ "description": (+ "Specific facts to remember. Each item should be a "+ "complete, standalone sentence."+ ),+ },+ },+ "required": ["thinking", "content"],+ }+ is_concurrency_safe: bool = False+ is_read_only: bool = False++ async def __call__(+ self,+ thinking: str,+ content: list[str],+ ) -> ToolChunk:+ """Use this function to record important information that you+ may need later. The target content should be specific and+ concise, e.g. who, when, where, do what, why, how, etc.++ Do NOT pass back content that appears earlier in the+ conversation history as a previous ``search_memory`` tool+ result — those facts are already in the store, re-adding them+ wastes an extraction call.++ Args:+ thinking (str):+ Your reasoning about why this is worth remembering.+ Stays in the agent transcript but is NOT persisted to+ the memory store — only ``content`` is. Use it to+ force yourself to think before writing.+ content (list[str]):+ The content to remember, as a list of strings (one+ item per fact). Each item should be a complete,+ standalone sentence — only this is sent to mem0 for+ extraction.+ """+ if not content:+ return _error_chunk("`content` is empty — nothing to record.")++ user_id = self._mw._user_id+ agent_id = self._mw._agent_id++ # Only the user-facing content goes into mem0. ``thinking`` is+ # the agent's internal rationale — meta about the agent's+ # decision, not a fact about the user — so feeding it to+ # mem0's extraction LLM would muddy the stored memories with+ # agent self-narration. We keep it in the tool response so the+ # decision is auditable in the transcript.+ text = "\n".join(content)++ try:+ result = await self._mw._async_add_with_fallback(+ text,+ user_id=user_id,+ agent_id=agent_id,+ )+ except Exception as e: # noqa: BLE001+ return _error_chunk(f"Error recording memory: {e}")++ rationale = f" (rationale: {thinking})" if thinking else ""+ return _text_chunk(+ f"Successfully recorded to memory{rationale} → {result}",+ )+++def _build_memory_tools(+ mw: "Mem0Middleware",+) -> list[ToolBase]:+ """Return the ``search_memory`` / ``add_memory`` tools bound to+ ``mw``.++ The tool classes intentionally reach into ``mw``'s private state+ (``_resolve_user_id`` / ``_async_search`` / ...) —+ we live in the same package and ``mw`` is the natural place for+ that state.+ """+ return [+ _SearchMemoryTool(mw),+ _AddMemoryTool(mw),+ ]+++def _text_chunk(message: str) -> ToolChunk:+ """Wrap a text message as a normal tool chunk."""+ return ToolChunk(+ content=[TextBlock(type="text", text=message)],+ )+++def _error_chunk(message: str) -> ToolChunk:+ """Wrap an error message as a ``ToolChunk(state=ERROR)`` so the+ toolkit aggregates it as a failed tool call — the agent sees the+ message and can decide whether to retry or move on."""+ return ToolChunk(+ content=[TextBlock(type="text", text=message)],+ state=ToolResultState.ERROR,+ )diff --git a/src/agentscope/middleware/_longterm_memory/_mem0/_utils.py b/src/agentscope/middleware/_longterm_memory/_mem0/_utils.pynew file mode 100644index 000000000..2291f34ac--- /dev/null+++ b/src/agentscope/middleware/_longterm_memory/_mem0/_utils.py@@ -0,0 +1,76 @@+# -*- coding: utf-8 -*-+"""Pure helper functions for the mem0 middleware.++These are stateless adapters that translate between AgentScope and+mem0 data shapes. Keeping them out of the middleware class makes them+trivial to unit-test in isolation.+"""+from __future__ import annotations++from typing import Any++from ....event import ExternalExecutionResultEvent, UserConfirmResultEvent+from ....message import Msg+++def _extract_query_text(inputs: Any) -> str | None:+ """Pull a single text query out of the agent inputs.++ Returns ``None`` for resumption events or empty/non-user inputs,+ in which case the middleware skips both retrieval and write-back.+ """+ if inputs is None:+ return None+ if isinstance(+ inputs,+ (ExternalExecutionResultEvent, UserConfirmResultEvent),+ ):+ return None++ msgs = inputs if isinstance(inputs, list) else [inputs]+ texts: list[str] = []+ for m in msgs:+ if not isinstance(m, Msg) or m.role != "user":+ continue+ text = m.get_text_content()+ if text:+ texts.append(text)+ return "\n".join(texts) if texts else None+++def _mem0_extracted_anything(raw: Any) -> bool:+ """Did mem0's add() actually extract any memories from the input?++ mem0 returns ``{"results": [...]}``; an empty list means its LLM+ extractor decided nothing was worth storing. The+ ``_async_add_with_fallback`` strategy uses this to decide whether+ to try another role / disable inference.+ """+ if not isinstance(raw, dict):+ return False+ results = raw.get("results")+ return isinstance(results, list) and len(results) > 0+++def _extract_memory_texts(raw: Any) -> list[str]:+ """Flatten a mem0 search response into a list of memory strings.++ Tolerates the common shapes:+ - ``{"results": [{"memory": str, ...}, ...]}`` (current OSS / Platform)+ - ``[{"memory": str, ...}, ...]`` (legacy / variations)+ - ``{"results": [str, ...]}`` (defensive fallback)+ """+ if raw is None:+ return []+ results = raw.get("results", raw) if isinstance(raw, dict) else raw+ if not isinstance(results, list):+ return []+ out: list[str] = []+ for item in results:+ if isinstance(item, str):+ out.append(item)+ elif isinstance(item, dict):+ text = item.get("memory") or item.get("text")+ if text:+ out.append(str(text))+ return outdiff --git a/tests/mem0_agentscope_adapter_test.py b/tests/mem0_agentscope_adapter_test.pynew file mode 100644index 000000000..9ff67d416--- /dev/null+++ b/tests/mem0_agentscope_adapter_test.py@@ -0,0 +1,461 @@+# -*- coding: utf-8 -*-+# pylint: disable=wrong-import-order+"""Unit tests for the AgentScope ↔ mem0 adapters.++Verifies that ``AgentScopeLLM`` / ``AgentScopeEmbedding`` correctly+translate between mem0's sync OpenAI-style contract and AgentScope's+async ``Msg`` / ``ContentBlock`` / ``EmbeddingResponse`` shapes, and+that ``register_with_mem0`` plugs them into mem0's factories.+"""+import asyncio+import json+import unittest+from typing import Any++from agentscope.credential import DashScopeCredential+from agentscope.embedding import EmbeddingModelBase, EmbeddingResponse+from agentscope.message import (+ Msg,+ TextBlock,+ ThinkingBlock,+ ToolCallBlock,+)+from agentscope.middleware._longterm_memory._mem0._agentscope_adapter import (+ AgentScopeEmbedding,+ AgentScopeLLM,+ _convert_messages_to_agentscope,+ _parse_chat_response,+ build_mem0_config,+)+from agentscope.model import ChatResponse+from utils import MockModel+++# ----------------------------------------------------------------------+# Pure helpers+# ----------------------------------------------------------------------+++class TestConvertMessages(unittest.TestCase):+ """Tests for converting mem0 dict messages into AgentScope messages."""++ def test_three_roles_map_to_correct_role(self) -> None:+ """System, user, and assistant roles should be preserved."""+ msgs = _convert_messages_to_agentscope(+ [+ {"role": "system", "content": "you are helpful"},+ {"role": "user", "content": "hi"},+ {"role": "assistant", "content": "hello"},+ ],+ )+ self.assertEqual(+ [m.role for m in msgs],+ ["system", "user", "assistant"],+ )+ self.assertTrue(all(isinstance(m, Msg) for m in msgs))+ self.assertEqual(msgs[1].get_text_content(), "hi")++ def test_unknown_role_dropped(self) -> None:+ """Unsupported message roles should be skipped."""+ msgs = _convert_messages_to_agentscope(+ [+ {"role": "tool", "content": "noise"},+ {"role": "user", "content": "real"},+ ],+ )+ self.assertEqual(len(msgs), 1)+ self.assertEqual(msgs[0].role, "user")+++class TestParseChatResponse(unittest.TestCase):+ """Tests for converting AgentScope chat responses into mem0 output."""++ def _resp(self, blocks: list) -> ChatResponse:+ """Build a final chat response from content blocks."""+ return ChatResponse(content=blocks, is_last=True)++ def test_text_only_returns_string(self) -> None:+ """Plain text responses should become plain strings."""+ resp = self._resp([TextBlock(type="text", text="answer")])+ self.assertEqual(_parse_chat_response(resp, has_tool=False), "answer")++ def test_thinking_prefixed_to_text(self) -> None:+ """Thinking blocks should be preserved before visible text."""+ resp = self._resp(+ [+ ThinkingBlock(type="thinking", thinking="hmm"),+ TextBlock(type="text", text="final"),+ ],+ )+ out = _parse_chat_response(resp, has_tool=False)+ self.assertIn("hmm", out)+ self.assertIn("final", out)+ # thinking comes first to mirror v1 order+ self.assertLess(out.index("hmm"), out.index("final"))++ def test_tool_call_with_json_string_input(self) -> None:+ """v2 stores ToolCallBlock.input as a JSON string — adapter+ must parse it back to a dict for mem0."""+ resp = self._resp(+ [+ TextBlock(type="text", text="calling tool"),+ ToolCallBlock(+ type="tool_call",+ id="call_1",+ name="lookup",+ input=json.dumps({"q": "alice"}),+ ),+ ],+ )+ out = _parse_chat_response(resp, has_tool=True)+ self.assertEqual(out["content"], "calling tool")+ self.assertEqual(+ out["tool_calls"],+ [{"name": "lookup", "arguments": {"q": "alice"}}],+ )++ def test_tool_call_with_malformed_input_keeps_raw(self) -> None:+ """Malformed JSON tool inputs should remain as raw strings."""+ resp = self._resp(+ [+ ToolCallBlock(+ type="tool_call",+ id="call_2",+ name="lookup",+ input="not json",+ ),+ ],+ )+ out = _parse_chat_response(resp, has_tool=True)+ self.assertEqual(out["tool_calls"][0]["arguments"], "not json")++ def test_empty_content(self) -> None:+ """Empty responses should convert to the empty mem0 shapes."""+ resp = self._resp([])+ self.assertEqual(_parse_chat_response(resp, has_tool=False), "")+ self.assertEqual(+ _parse_chat_response(resp, has_tool=True),+ {"content": "", "tool_calls": []},+ )+++# ----------------------------------------------------------------------+# AgentScopeLLM end-to-end (fake AgentScope model on caller event loop)+# ----------------------------------------------------------------------+++class _CurrentEventLoopTestCase(unittest.TestCase):+ """Provides a current event loop for the adapter's sync bridge."""++ _event_loop: asyncio.AbstractEventLoop+ _previous_event_loop: asyncio.AbstractEventLoop | None++ def setUp(self) -> None:+ """Install a fresh event loop for each sync-bridge test."""+ super().setUp()+ try:+ self._previous_event_loop = asyncio.get_event_loop()+ except RuntimeError:+ self._previous_event_loop = None+ self._event_loop = asyncio.new_event_loop()+ asyncio.set_event_loop(self._event_loop)++ def tearDown(self) -> None:+ """Restore the previous event loop after each test."""+ asyncio.set_event_loop(self._previous_event_loop)+ self._event_loop.close()+ super().tearDown()+++class _RecordingMockChatModel(MockModel):+ """Captures the ``messages`` arg so we can assert the v2 Msg+ objects mem0's dict messages were converted into."""++ def __init__(self, *args: Any, **kwargs: Any) -> None:+ """Initialize the recording model."""+ super().__init__(*args, **kwargs)+ self.received_messages: list[list[Msg]] = []++ async def _call_api(self, *args: Any, **kwargs: Any) -> Any:+ """Record delivered messages before delegating to MockModel."""+ self.received_messages.append(list(kwargs.get("messages") or []))+ return await super()._call_api(*args, **kwargs)+++class TestAgentScopeLLM(_CurrentEventLoopTestCase):+ """End-to-end tests for the mem0 LLM adapter."""++ def test_constructor_rejects_non_chatmodel(self) -> None:+ """The LLM adapter should reject non-AgentScope chat models."""+ with self.assertRaises(TypeError):+ AgentScopeLLM(config={"model": object()})++ def test_constructor_requires_model(self) -> None:+ """The LLM adapter should require a model config entry."""+ with self.assertRaises(ValueError):+ AgentScopeLLM(config={})++ def test_generate_response_routes_through_agentscope_model(self) -> None:+ """mem0 generation should call the wrapped AgentScope model."""+ model = _RecordingMockChatModel()+ model.set_responses(+ [+ ChatResponse(+ content=[TextBlock(type="text", text="from agentscope")],+ is_last=True,+ ),+ ],+ )+ llm = AgentScopeLLM(config={"model": model})++ result = llm.generate_response(+ [+ {"role": "system", "content": "sys"},+ {"role": "user", "content": "hello"},+ ],+ )+ self.assertEqual(result, "from agentscope")+ # The dict messages were converted to Msg objects with the+ # correct roles preserved.+ delivered = model.received_messages[0]+ self.assertEqual([m.role for m in delivered], ["system", "user"])++ def test_generate_response_with_tools(self) -> None:+ """Tool-call responses should be converted to mem0's tool shape."""+ model = _RecordingMockChatModel()+ model.set_responses(+ [+ ChatResponse(+ content=[+ ToolCallBlock(+ type="tool_call",+ id="call_3",+ name="search",+ input=json.dumps({"q": "x"}),+ ),+ ],+ is_last=True,+ ),+ ],+ )+ llm = AgentScopeLLM(config={"model": model})++ result = llm.generate_response(+ [{"role": "user", "content": "find x"}],+ tools=[{"name": "search"}],+ )+ self.assertIsInstance(result, dict)+ self.assertEqual(+ result["tool_calls"],+ [{"name": "search", "arguments": {"q": "x"}}],+ )++ def test_streaming_response_drained_to_last_chunk(self) -> None:+ """When the AgentScope model streams, the adapter must+ consume all chunks and use the last (which carries the+ complete content per AgentScope's streaming contract)."""+ model = _RecordingMockChatModel()+ # MockModel.set_responses with a list-of-list triggers stream mode+ model.set_responses(+ [+ [+ ChatResponse(+ content=[TextBlock(type="text", text="part 1")],+ is_last=False,+ ),+ ChatResponse(+ content=[TextBlock(type="text", text="final")],+ is_last=True,+ ),+ ],+ ],+ )+ llm = AgentScopeLLM(config={"model": model})+ result = llm.generate_response(+ [{"role": "user", "content": "stream"}],+ )+ self.assertEqual(result, "final")++ def test_empty_messages_raises(self) -> None:+ """Dropping all unsupported messages should raise ValueError."""+ llm = AgentScopeLLM(config={"model": _RecordingMockChatModel()})+ with self.assertRaises(ValueError):+ llm.generate_response([{"role": "tool", "content": "ignored"}])+++# ----------------------------------------------------------------------+# AgentScopeEmbedding+# ----------------------------------------------------------------------+++class _FakeEmbeddingModel(EmbeddingModelBase):+ """Minimal embedding model that records requested texts."""++ def __init__(self) -> None:+ """Initialize the fake embedding model."""+ super().__init__(+ credential=DashScopeCredential(api_key="fake"),+ model="fake-embed",+ parameters=self.Parameters(dimensions=3),+ context_size=8192,+ batch_size=10,+ max_retries=0,+ retry_delay=0.0,+ )+ self.received: list[list[str]] = []++ async def _call_api(+ self,+ inputs: list[str],+ **kwargs: Any,+ ) -> EmbeddingResponse:+ """Return a fixed vector for every input text."""+ self.received.append(list(inputs))+ return EmbeddingResponse(+ embeddings=[[0.1, 0.2, 0.3] for _ in inputs],+ source="api",+ )+++class TestAgentScopeEmbedding(_CurrentEventLoopTestCase):+ """Tests for the mem0 embedding adapter."""++ def test_constructor_validation(self) -> None:+ """The embedding adapter should validate model config."""+ with self.assertRaises(ValueError):+ AgentScopeEmbedding(config={})+ with self.assertRaises(TypeError):+ AgentScopeEmbedding(config={"model": object()})++ def test_embed_single_string(self) -> None:+ """Single-string inputs should be wrapped before model calls."""+ model = _FakeEmbeddingModel()+ emb = AgentScopeEmbedding(config={"model": model})+ result = emb.embed("hello")+ self.assertEqual(result, [0.1, 0.2, 0.3])+ # The string was wrapped into a list before reaching the model.+ self.assertEqual(model.received, [["hello"]])++ def test_embed_list_of_strings_returns_first(self) -> None:+ """mem0's contract is that ``embed`` returns ONE vector. We+ return the first."""+ model = _FakeEmbeddingModel()+ emb = AgentScopeEmbedding(config={"model": model})+ result = emb.embed(["a", "b"])+ self.assertEqual(result, [0.1, 0.2, 0.3])+ self.assertEqual(model.received, [["a", "b"]])+++# ----------------------------------------------------------------------+# Factory registration+# ----------------------------------------------------------------------+++class TestBuildMem0Config(unittest.TestCase):+ """``build_mem0_config`` must bypass mem0's hardcoded provider+ whitelist and emit a config that names the AgentScope adapter."""++ def test_models_only_produces_fresh_config(self) -> None:+ """Models-only construction should create AgentScope providers."""+ chat = MockModel()+ emb = _FakeEmbeddingModel()+ cfg = build_mem0_config(chat_model=chat, embedding_model=emb)++ self.assertEqual(cfg.llm.provider, "agentscope")+ self.assertEqual(cfg.embedder.provider, "agentscope")+ self.assertIs(cfg.llm.config["model"], chat)+ self.assertIs(cfg.embedder.config["model"], emb)++ def test_models_only_requires_both(self) -> None:+ """Models-only construction should require chat and embedding."""+ with self.assertRaises(ValueError):+ build_mem0_config(chat_model=MockModel())+ with self.assertRaises(ValueError):+ build_mem0_config(embedding_model=_FakeEmbeddingModel())+ with self.assertRaises(ValueError):+ build_mem0_config()++ def test_base_config_with_both_models_preserves_other_fields(+ self,+ ) -> None:+ """When a ``mem0_config`` base is given, vector_store /+ history_db / etc. should survive — only .llm and .embedder+ are rewired to the AgentScope adapters."""+ from mem0.configs.base import MemoryConfig++ base = MemoryConfig(history_db_path="/tmp/custom_history.db")+ original_vs = base.vector_store++ chat = MockModel()+ emb = _FakeEmbeddingModel()+ cfg = build_mem0_config(+ chat_model=chat,+ embedding_model=emb,+ mem0_config=base,+ )++ self.assertEqual(cfg.llm.provider, "agentscope")+ self.assertIs(cfg.llm.config["model"], chat)+ self.assertEqual(cfg.embedder.provider, "agentscope")+ self.assertIs(cfg.embedder.config["model"], emb)+ # Non-llm/embedder fields preserved.+ self.assertEqual(cfg.history_db_path, "/tmp/custom_history.db")+ self.assertIs(cfg.vector_store, original_vs)++ def test_base_config_with_only_chat_model_partial_override(+ self,+ ) -> None:+ """Partial override: chat_model alone replaces .llm but+ leaves .embedder untouched (whatever the base config had)."""+ from mem0.configs.base import MemoryConfig++ base = MemoryConfig() # base has the default openai embedder+ original_embedder = base.embedder++ cfg = build_mem0_config(+ chat_model=MockModel(),+ mem0_config=base,+ )+ self.assertEqual(cfg.llm.provider, "agentscope")+ # Embedder unchanged from base — still mem0's openai default.+ self.assertIs(cfg.embedder, original_embedder)++ def test_base_config_alone_is_pass_through(self) -> None:+ """``mem0_config=base`` with no models is just a pass-through —+ registration still happens (cheap) but no fields change."""+ from mem0.configs.base import MemoryConfig++ base = MemoryConfig()+ cfg = build_mem0_config(mem0_config=base)+ self.assertIs(cfg, base)++ def test_registers_adapter_in_factory(self) -> None:+ """The helper side-effect: mem0's factory dicts now know how+ to resolve provider='agentscope'."""+ from mem0.utils.factory import EmbedderFactory, LlmFactory++ build_mem0_config(+ chat_model=MockModel(),+ embedding_model=_FakeEmbeddingModel(),+ )+ self.assertIn("agentscope", LlmFactory.provider_to_class)+ self.assertIn("agentscope", EmbedderFactory.provider_to_class)++ def test_naive_from_config_path_still_rejected(self) -> None:+ """Sanity check: confirm WHY the helper exists — calling+ ``MemoryConfig`` with ``provider='agentscope'`` directly DOES+ raise, which is the failure ``build_mem0_config`` works around."""+ from mem0.configs.base import MemoryConfig+ from pydantic import ValidationError++ with self.assertRaises(ValidationError):+ MemoryConfig(+ llm={+ "provider": "agentscope",+ "config": {"model": MockModel()},+ },+ embedder={+ "provider": "agentscope",+ "config": {"model": _FakeEmbeddingModel()},+ },+ )diff --git a/tests/mem0_middleware_test.py b/tests/mem0_middleware_test.pynew file mode 100644index 000000000..086de47f9--- /dev/null+++ b/tests/mem0_middleware_test.py@@ -0,0 +1,891 @@+# -*- coding: utf-8 -*-+# pylint: disable=protected-access,unused-argument+"""Unit tests for Mem0Middleware.++The mem0 client itself is mocked — we only exercise the AgentScope hook+wiring (retrieve-before / write-after, system-prompt injection,+list_tools exposure) and the small adapter that translates between+AgentScope and mem0. The OSS ``Memory`` and Platform ``MemoryClient``+share the same call shape (``search(query, filters=..., top_k=...)``+and ``add(messages, user_id=..., agent_id=...)``) so one mock covers+both.++``protected-access`` is disabled because tests legitimately reach into+middleware internals (``mw._client``, ``mw._async_search``, ``mw._top_k``) to+inspect what the public API just did.+"""+from unittest.async_case import IsolatedAsyncioTestCase+from unittest.mock import AsyncMock, MagicMock+from typing import Any++from utils import MockModel++from agentscope.agent import Agent+from agentscope.event import (+ ExternalExecutionResultEvent,+ UserConfirmResultEvent,+)+from agentscope.message import HintBlock, Msg, TextBlock, UserMsg+from agentscope.middleware import Mem0Middleware+from agentscope.middleware._longterm_memory._mem0._utils import (+ _extract_memory_texts,+ _extract_query_text,+)+from agentscope.model import ChatResponse+from agentscope.tool import Toolkit+++# ----------------------------------------------------------------------+# Test helpers+# ----------------------------------------------------------------------+++class RecordingMockModel(MockModel):+ """MockModel that captures the ``messages`` of every _call_api call."""++ def __init__(self, *args: Any, **kwargs: Any) -> None:+ """Initialize the recording mock model."""+ super().__init__(*args, **kwargs)+ self.calls: list[list[Msg]] = []++ async def _call_api(+ self,+ *args: Any,+ **kwargs: Any,+ ) -> Any:+ """Record messages before delegating to MockModel."""+ messages = kwargs.get("messages")+ if messages is None and len(args) >= 2:+ messages = args[1]+ self.calls.append(list(messages or []))+ return await super()._call_api(*args, **kwargs)++ @property+ def last_call_messages(self) -> list[Msg]:+ """Return the most recent model-call messages."""+ return self.calls[-1]+++class _FakeAsyncMem0Client:+ """Stands in for any of mem0's four client variants.++ All four expose compatible ``search(query, filters=..., top_k=...)``+ and ``add(messages, user_id=..., agent_id=...)`` shapes, so a single+ fake suffices.+ """++ def __init__(self, search_return: Any = None) -> None:+ """Initialize the fake mem0 client."""+ self.search_return = search_return or {"results": []}+ self.search_calls: list[dict] = []+ self.add_calls: list[dict] = []++ async def search(self, query: str, **kwargs: Any) -> Any:+ """Record a mem0 search call and return the configured result."""+ self.search_calls.append({"query": query, **kwargs})+ return self.search_return++ async def add(self, messages: list[dict], **kwargs: Any) -> None:+ """Record a mem0 add call."""+ self.add_calls.append({"messages": messages, **kwargs})+++def _single_response(text: str) -> ChatResponse:+ """Build a final single-text chat response."""+ return ChatResponse(+ content=[TextBlock(type="text", text=text)],+ is_last=True,+ )+++def _all_tool_names(toolkit: Toolkit) -> list[str]:+ """Flatten every registered tool's name across every group."""+ return [t.name for g in toolkit.tool_groups for t in g.tools]+++def _find_tool(toolkit: Toolkit, name: str) -> Any:+ """Look a tool up by name across every group on the toolkit."""+ for g in toolkit.tool_groups:+ for t in g.tools:+ if t.name == name:+ return t+ raise LookupError(f"tool {name!r} not found in any group")+++def _find_group(toolkit: Toolkit, name: str) -> Any:+ """Look a tool group up by name on the toolkit."""+ for g in toolkit.tool_groups:+ if g.name == name:+ return g+ raise LookupError(f"tool group {name!r} not found")+++def _chunk_text(chunk: Any) -> str:+ """Return the first text block from a tool chunk."""+ return chunk.content[0].text+++# ----------------------------------------------------------------------+# Unit tests for module-level helpers+# ----------------------------------------------------------------------+++class TestExtractQueryText(IsolatedAsyncioTestCase):+ """Tests for extracting the query text from incoming inputs."""++ def test_none_and_empty(self) -> None:+ """None and empty inputs should not produce a query."""+ self.assertIsNone(_extract_query_text(None))+ self.assertIsNone(_extract_query_text([]))++ def test_single_user_msg(self) -> None:+ """A single user message should become its text content."""+ msg = UserMsg("user", "hello world")+ self.assertEqual(_extract_query_text(msg), "hello world")++ def test_list_of_user_msgs_joined(self) -> None:+ """Multiple user messages should be joined by newlines."""+ msgs = [UserMsg("user", "first"), UserMsg("user", "second")]+ self.assertEqual(_extract_query_text(msgs), "first\nsecond")++ def test_resumption_events_return_none(self) -> None:+ """HITL resumption events should not trigger memory IO."""+ self.assertIsNone(+ _extract_query_text(+ UserConfirmResultEvent(+ reply_id="reply",+ confirm_results=[],+ ),+ ),+ )+ self.assertIsNone(+ _extract_query_text(+ ExternalExecutionResultEvent(+ reply_id="reply",+ execution_results=[],+ ),+ ),+ )+++class TestExtractMemoryTexts(IsolatedAsyncioTestCase):+ """Tests for normalizing mem0 search responses into text lists."""++ def test_dict_with_results(self) -> None:+ """Dictionary responses with result dicts should be flattened."""+ raw = {"results": [{"memory": "a"}, {"memory": "b"}]}+ self.assertEqual(_extract_memory_texts(raw), ["a", "b"])++ def test_plain_list_of_dicts(self) -> None:+ """Plain list responses should also be supported."""+ self.assertEqual(+ _extract_memory_texts([{"memory": "only"}]),+ ["only"],+ )++ def test_plain_list_of_strings(self) -> None:+ """String results should pass through unchanged."""+ self.assertEqual(+ _extract_memory_texts({"results": ["x", "y"]}),+ ["x", "y"],+ )++ def test_none_and_garbage(self) -> None:+ """Malformed mem0 outputs should normalize to an empty list."""+ self.assertEqual(_extract_memory_texts(None), [])+ self.assertEqual(_extract_memory_texts({"results": "nope"}), [])+++# ----------------------------------------------------------------------+# Constructor validation+# ----------------------------------------------------------------------+++class TestConstructorValidation(IsolatedAsyncioTestCase):+ """Tests for Mem0Middleware constructor validation."""++ def test_missing_user_id_raises(self) -> None:+ """Empty user IDs should be rejected."""+ with self.assertRaises(ValueError):+ Mem0Middleware(client=MagicMock(), user_id="")+ with self.assertRaises(ValueError):+ Mem0Middleware(client=MagicMock(), user_id=" ")++ def test_unknown_mode_raises(self) -> None:+ """Unknown control modes should be rejected."""+ with self.assertRaises(ValueError):+ Mem0Middleware(+ client=MagicMock(),+ user_id="alice",+ mode="garbage", # type: ignore[arg-type]+ )++ def test_neither_client_nor_models_nor_config_raises(self) -> None:+ """At least one backend construction path should be provided."""+ with self.assertRaises(ValueError) as ctx:+ Mem0Middleware(user_id="alice")+ self.assertIn("client", str(ctx.exception))+ self.assertIn("mem0_config", str(ctx.exception))+ self.assertIn("chat_model", str(ctx.exception))++ def test_client_wins_over_other_backend_kwargs_with_warning(+ self,+ ) -> None:+ """``client`` is the escape hatch — when given, the other+ backend kwargs are ignored. A warning is logged so the+ mismatch is not invisible."""+ fake_client = _FakeAsyncMem0Client()+ with self.assertLogs(+ "as", # the project-wide logger name+ level="WARNING",+ ) as captured:+ mw = Mem0Middleware(+ user_id="alice",+ client=fake_client,+ chat_model=MagicMock(), # ignored+ embedding_model=MagicMock(), # ignored+ mem0_config=MagicMock(), # ignored+ )++ # The fake client wired through unchanged — no AgentScope-+ # adapter construction machinery ran.+ self.assertIs(mw._client, fake_client)++ # Warning mentions all three ignored kwargs.+ joined = "\n".join(captured.output)+ self.assertIn("chat_model", joined)+ self.assertIn("embedding_model", joined)+ self.assertIn("mem0_config", joined)++ def test_client_alone_does_not_warn(self) -> None:+ """Sanity: pure client-only path stays quiet."""+ fake_client = _FakeAsyncMem0Client()+ with self.assertNoLogs("as", level="WARNING"):+ Mem0Middleware(user_id="alice", client=fake_client)++ def test_only_one_of_chat_or_embedding_without_config_raises(+ self,+ ) -> None:+ """Models-only construction requires both chat and embedding."""+ with self.assertRaises(ValueError):+ Mem0Middleware(user_id="alice", chat_model=MagicMock())+ with self.assertRaises(ValueError):+ Mem0Middleware(user_id="alice", embedding_model=MagicMock())+++# ----------------------------------------------------------------------+# Static-control mode (default)+# ----------------------------------------------------------------------+++class TestStaticControlMode(IsolatedAsyncioTestCase):+ """Default mode: retrieve-before / inject / write-after, no tools."""++ async def asyncSetUp(self) -> None:+ """Create a fresh recording model and empty toolkit."""+ self.model = RecordingMockModel(context_size=100_000)+ self.toolkit = Toolkit()++ def _agent(+ self,+ middleware: Mem0Middleware,+ response_text: str = "ok",+ ) -> Agent:+ """Build a test agent using ``middleware`` and one response."""+ self.model.set_responses([_single_response(response_text)])+ return Agent(+ name="agent_under_test",+ system_prompt="base system prompt",+ model=self.model,+ toolkit=self.toolkit,+ middlewares=[middleware],+ )++ async def test_retrieve_inject_write(self) -> None:+ """Static control should search, inject, reply, then write."""+ fake = _FakeAsyncMem0Client(+ search_return={"results": [{"memory": "alice loves coffee"}]},+ )+ mw = Mem0Middleware(+ client=fake,+ user_id="alice",+ agent_id="agent_under_test",+ mode="static_control",+ )++ agent = self._agent(mw, response_text="hi alice")+ reply = await agent.reply(UserMsg("user", "remind me what I like"))++ # 1. search called with unified call shape (filters dict, top_k)+ self.assertEqual(len(fake.search_calls), 1)+ self.assertEqual(+ fake.search_calls[0]["query"],+ "remind me what I like",+ )+ self.assertEqual(+ fake.search_calls[0]["filters"],+ {"user_id": "alice", "agent_id": "agent_under_test"},+ )+ self.assertEqual(fake.search_calls[0]["top_k"], 5)++ # 2. write called post-turn with user+assistant pair+ self.assertEqual(len(fake.add_calls), 1)+ self.assertEqual(+ fake.add_calls[0]["messages"],+ [+ {"role": "user", "content": "remind me what I like"},+ {"role": "assistant", "content": "hi alice"},+ ],+ )+ self.assertEqual(fake.add_calls[0]["user_id"], "alice")+ self.assertEqual(fake.add_calls[0]["agent_id"], "agent_under_test")++ # 3. system prompt is unchanged — static_control mode does NOT+ # add tool instructions (those only fire in agent_control /+ # both modes via on_system_prompt).+ sys_msg = self.model.last_call_messages[0]+ self.assertEqual(sys_msg.role, "system")+ self.assertEqual(sys_msg.get_text_content(), "base system prompt")++ # 4. memory appended to the agent's persistent context as an+ # assistant-role hint note named "memory". Formatters convert+ # HintBlock content into a user message before provider calls.+ memory_msgs = []+ for msg in agent.state.context:+ if getattr(msg, "name", None) == "memory":+ memory_msgs.append(msg)+ self.assertEqual(len(memory_msgs), 1)+ self.assertEqual(memory_msgs[0].role, "assistant")+ memory_hints = memory_msgs[0].get_content_blocks("hint")+ self.assertEqual(len(memory_hints), 1)+ self.assertIsInstance(memory_hints[0], HintBlock)+ memory_text = memory_hints[0].hint+ self.assertIn("Relevant memories", memory_text)+ self.assertIn("alice loves coffee", memory_text)+ # The model saw it on its first call as well.+ delivered = [+ m+ for m in self.model.last_call_messages+ if getattr(m, "name", None) == "memory"+ ]+ self.assertEqual(len(delivered), 1)++ # 5. no agent-control tools registered (in any group)+ all_names = _all_tool_names(self.toolkit)+ self.assertNotIn("search_memory", all_names)+ self.assertNotIn("add_memory", all_names)++ self.assertEqual(reply.get_text_content(), "hi alice")++ async def test_memory_message_lands_after_user_message(self) -> None:+ """Mirroring AgentScope 1.x's ReActAgent placement: the memory+ note is inserted right AFTER the new user input lands in the+ agent context, not before."""+ fake = _FakeAsyncMem0Client(+ search_return={"results": [{"memory": "saved fact"}]},+ )+ mw = Mem0Middleware(+ client=fake,+ user_id="alice",+ mode="static_control",+ )+ agent = self._agent(mw, response_text="answer")+ await agent.reply(UserMsg("user", "tell me what you know"))++ # context order should be: [...prior history..., USER_MSG,+ # MEMORY_NOTE, ASSISTANT_REPLY (added by the agent loop)]+ roles_and_names = [+ (m.role, getattr(m, "name", None)) for m in agent.state.context+ ]+ user_idx = next(+ i+ for i, (r, n) in enumerate(roles_and_names)+ if r == "user" and n != "memory"+ )+ memory_idx = next(+ i for i, (_, n) in enumerate(roles_and_names) if n == "memory"+ )+ self.assertGreater(+ memory_idx,+ user_idx,+ f"memory note at {memory_idx} should come after user msg "+ f"at {user_idx}: {roles_and_names}",+ )++ async def test_no_memories_no_injection(self) -> None:+ """Empty search results should not add a memory hint message."""+ fake = _FakeAsyncMem0Client(search_return={"results": []})+ mw = Mem0Middleware(+ client=fake,+ user_id="alice",+ mode="static_control",+ )++ agent = self._agent(mw)+ await agent.reply(UserMsg("user", "hi"))++ # System prompt unchanged, no synthetic memory msg present.+ msgs = self.model.last_call_messages+ self.assertEqual(msgs[0].get_text_content(), "base system prompt")+ for m in msgs:+ self.assertNotEqual(getattr(m, "name", None), "memory")+ self.assertEqual(len(fake.search_calls), 1)++ async def test_search_failure_does_not_break_reply(self) -> None:+ """Search errors should be logged but not block the reply."""+ fake = _FakeAsyncMem0Client()+ fake.search = AsyncMock(side_effect=RuntimeError("mem0 down"))+ mw = Mem0Middleware(+ client=fake,+ user_id="alice",+ mode="static_control",+ )++ agent = self._agent(mw, response_text="still works")+ reply = await agent.reply(UserMsg("user", "ping"))++ self.assertEqual(reply.get_text_content(), "still works")+ # Write still happened — a failed search must not block writes.+ self.assertEqual(len(fake.add_calls), 1)++ async def test_scope_search_by_agent_false_drops_agent_id(+ self,+ ) -> None:+ """Unscoped search should omit agent_id from mem0 filters."""+ fake = _FakeAsyncMem0Client()+ mw = Mem0Middleware(+ client=fake,+ user_id="alice",+ agent_id="agent_under_test",+ mode="static_control",+ scope_search_by_agent=False,+ )+ agent = self._agent(mw)+ await agent.reply(UserMsg("user", "hi"))++ self.assertNotIn("agent_id", fake.search_calls[0]["filters"])+ # Write still tags both for future scoped queries.+ self.assertEqual(fake.add_calls[0]["agent_id"], "agent_under_test")++ async def test_sync_client_rejected(self) -> None:+ """Sync mem0 clients (``Memory`` / ``MemoryClient``) must be+ rejected at construction time — only async clients are+ supported."""++ class SyncFake:+ """Fake sync mem0 client used to verify rejection."""++ def search(self, query: str, **kwargs: Any) -> Any:+ """Return an empty synchronous search result."""+ return {"results": []}++ def add(self, messages: list, **kwargs: Any) -> None:+ """No-op synchronous add method."""+ return None++ with self.assertRaises(TypeError) as ctx:+ Mem0Middleware(client=SyncFake(), user_id="alice")+ self.assertIn("AsyncMemory", str(ctx.exception))++ async def test_async_method_wrapped_by_sync_decorator_accepted(+ self,+ ) -> None:+ """mem0's hosted ``AsyncMemoryClient`` decorates its async+ methods with ``@api_error_handler`` — a sync wrapper that+ returns the coroutine produced by calling the underlying+ ``async def func``. ``inspect.iscoroutinefunction(wrapper)``+ is False, so the naive check would reject the client; we use+ ``inspect.unwrap`` to peel through ``@functools.wraps`` and+ find the real async function. This test simulates that+ pattern and asserts the wrapped-but-async client is accepted.+ """+ from functools import wraps++ def sync_wraps_async(func: Any) -> Any:+ """Wrap an async function in a sync functools wrapper."""++ @wraps(func)+ def wrapper(*args: Any, **kwargs: Any) -> Any:+ """Return the coroutine created by the wrapped function."""+ return func(*args, **kwargs)++ return wrapper++ class WrappedFake:+ """Fake client whose async methods are sync-wrapped."""++ @sync_wraps_async+ async def search(self, query: str, **kwargs: Any) -> Any:+ """Return an empty async search result."""+ return {"results": []}++ @sync_wraps_async+ async def add(self, messages: list, **kwargs: Any) -> None:+ """No-op async add method."""+ return None++ # Should NOT raise — the unwrap+iscoroutinefunction check sees+ # through the sync wrapper.+ mw = Mem0Middleware(client=WrappedFake(), user_id="alice")+ self.assertIsInstance(mw._client, WrappedFake)+++# ----------------------------------------------------------------------+# Agent-control mode+# ----------------------------------------------------------------------+++class TestAgentControlMode(IsolatedAsyncioTestCase):+ """Tools are listed, but no automatic memory hook behavior."""++ async def asyncSetUp(self) -> None:+ """Create a fresh recording model and empty toolkit."""+ self.model = RecordingMockModel(context_size=100_000)+ self.toolkit = Toolkit()++ async def _agent(+ self,+ middleware: Mem0Middleware,+ *,+ name: str = "a",+ system_prompt: str = "p",+ responses: list[str] | None = None,+ ) -> Agent:+ """Build an agent with tools explicitly listed by middleware."""+ self.model.set_responses(+ [_single_response(r) for r in (responses or ["ok"])],+ )+ self.toolkit = Toolkit(tools=await middleware.list_tools())+ return Agent(+ name=name,+ system_prompt=system_prompt,+ model=self.model,+ toolkit=self.toolkit,+ middlewares=[middleware],+ )++ async def test_tools_listed_and_hint_in_prompt(self) -> None:+ """Agent-control mode should expose tools and prompt guidance."""+ fake = _FakeAsyncMem0Client(+ search_return={"results": [{"memory": "found"}]},+ )+ mw = Mem0Middleware(+ client=fake,+ user_id="alice",+ mode="agent_control",+ )+ agent = await self._agent(+ mw,+ system_prompt="base prompt",+ )+ await agent.reply(UserMsg("user", "hello"))++ # Tools are listed by the middleware and explicitly passed into+ # the toolkit by the caller.+ basic = _find_group(self.toolkit, "basic")+ names = [t.name for t in basic.tools]+ self.assertIn("search_memory", names)+ self.assertIn("add_memory", names)++ # No automatic search/add ran.+ self.assertEqual(fake.search_calls, [])+ self.assertEqual(fake.add_calls, [])++ # System prompt got a short nudge mentioning the tools — the+ # per-tool guidance comes via the standard tool schema, not+ # this nudge.+ msgs = self.model.last_call_messages+ prompt_text = msgs[0].get_text_content()+ self.assertIn("base prompt", prompt_text)+ self.assertIn("Long-term memory", prompt_text)+ self.assertIn("search_memory", prompt_text)+ self.assertIn("add_memory", prompt_text)+ # No synthetic memory message was injected in agent_control mode.+ for m in msgs:+ self.assertNotEqual(getattr(m, "name", None), "memory")++ async def test_middleware_does_not_mutate_toolkit(self) -> None:+ """Middleware should not register tools unless caller does so."""+ fake = _FakeAsyncMem0Client()+ mw = Mem0Middleware(+ client=fake,+ user_id="alice",+ mode="agent_control",+ )+ self.model.set_responses([_single_response("ok")])+ toolkit = Toolkit()+ agent = Agent(+ name="a",+ system_prompt="base prompt",+ model=self.model,+ toolkit=toolkit,+ middlewares=[mw],+ )+ await agent.reply(UserMsg("user", "hello"))++ self.assertNotIn("search_memory", _all_tool_names(toolkit))+ self.assertNotIn("add_memory", _all_tool_names(toolkit))++ async def test_search_memory_tool_invokes_mem0(self) -> None:+ """The search_memory tool should query mem0 per keyword."""+ fake = _FakeAsyncMem0Client(+ search_return={+ "results": [+ {"memory": "first fact"},+ {"memory": "second fact"},+ ],+ },+ )+ mw = Mem0Middleware(+ client=fake,+ user_id="alice",+ agent_id="a",+ mode="agent_control",+ )+ agent = await self._agent(+ mw,+ system_prompt="base prompt",+ )+ # Trigger middleware tool registration by issuing a reply.+ await agent.reply(UserMsg("user", "hi"))++ search_tool = _find_tool(self.toolkit, "search_memory")++ # Exercise the tool directly. The signature mirrors+ # AgentScope 1.x: a LIST of keywords, each issued as an+ # independent parallel search.+ result = await search_tool(+ keywords=["what does alice like?", "alice preferences"],+ limit=3,+ )+ result_text = _chunk_text(result)+ self.assertIn("first fact", result_text)+ self.assertIn("second fact", result_text)++ # Each keyword produces one mem0 call; both share user/agent+ # filter and per-keyword limit.+ self.assertEqual(len(fake.search_calls), 2)+ for call in fake.search_calls:+ self.assertEqual(+ call["filters"],+ {"user_id": "alice", "agent_id": "a"},+ )+ self.assertEqual(call["top_k"], 3)++ async def test_async_search_accepts_per_call_top_k(self) -> None:+ """Per-call search limits should not mutate middleware state."""+ fake = _FakeAsyncMem0Client()+ mw = Mem0Middleware(+ client=fake,+ user_id="alice",+ mode="agent_control",+ top_k=9,+ )++ await mw._async_search(+ "q",+ user_id="alice",+ agent_id="a",+ top_k=3,+ )++ self.assertEqual(fake.search_calls[0]["top_k"], 3)+ self.assertEqual(mw._top_k, 9)++ async def test_tools_auto_allow_permission(self) -> None:+ """Memory tools should be auto-allowed by permission checks."""+ mw = Mem0Middleware(+ client=_FakeAsyncMem0Client(),+ user_id="alice",+ mode="agent_control",+ )+ agent = await self._agent(mw)+ await agent.reply(UserMsg("user", "hi"))++ from agentscope.permission import PermissionBehavior++ search_tool = _find_tool(self.toolkit, "search_memory")+ add_tool = _find_tool(self.toolkit, "add_memory")+ decision_search = await search_tool.check_permissions({}, None)+ decision_add = await add_tool.check_permissions({}, None)+ self.assertEqual(decision_search.behavior, PermissionBehavior.ALLOW)+ self.assertEqual(decision_add.behavior, PermissionBehavior.ALLOW)++ async def test_search_memory_dedupes_across_keywords(self) -> None:+ """When two keywords return overlapping memories, the tool+ merges and dedupes."""+ fake = _FakeAsyncMem0Client(+ search_return={+ "results": [{"memory": "shared"}, {"memory": "unique"}],+ },+ )+ mw = Mem0Middleware(client=fake, user_id="alice", mode="agent_control")+ agent = await self._agent(mw)+ await agent.reply(UserMsg("user", "hi"))+ search_tool = _find_tool(self.toolkit, "search_memory")++ result = await search_tool(+ keywords=["kw1", "kw2"],+ limit=5,+ )+ result_text = _chunk_text(result)+ # "shared" appears once even though both keywords returned it.+ self.assertEqual(result_text.count("shared"), 1)+ self.assertEqual(result_text.count("unique"), 1)++ async def test_search_memory_failure_returns_error_chunk(self) -> None:+ """mem0 raising during search produces a ToolChunk with+ state=ERROR so the toolkit marks the call as failed."""+ from agentscope.message import ToolResultState+ from agentscope.tool import ToolChunk++ fake = _FakeAsyncMem0Client()+ fake.search = AsyncMock(side_effect=RuntimeError("mem0 down"))+ mw = Mem0Middleware(client=fake, user_id="alice", mode="agent_control")+ agent = await self._agent(mw)+ await agent.reply(UserMsg("user", "hi"))+ search_tool = _find_tool(self.toolkit, "search_memory")++ result = await search_tool(+ keywords=["q"],+ limit=5,+ )+ self.assertIsInstance(result, ToolChunk)+ self.assertEqual(result.state, ToolResultState.ERROR)+ self.assertIn("mem0 down", result.content[0].text)++ async def test_add_memory_two_tier_fallback(self) -> None:+ """When mem0's extraction LLM returns no memories, the tool+ falls back to ``infer=False`` and saves raw text so the+ caller's ``add_memory`` invocation isn't silently dropped.++ Two tiers, not three — v1's tier-2 role switch (user →+ assistant) was a no-op against current mem0 (v2.x), which+ picks the extraction prompt based on the filter dict, not the+ message role. See the docstring of+ ``Mem0Middleware._async_add_with_fallback`` for the full+ rationale."""++ class CountingFake:+ """Fake mem0 client that triggers add fallback once."""++ def __init__(self) -> None:+ """Initialize call tracking and empty search behavior."""+ self.add_calls: list[dict] = []+ self.search = AsyncMock(return_value={"results": []})++ async def add(+ self,+ messages: list[dict],+ **kwargs: Any,+ ) -> dict:+ """Return empty extraction first, then a saved memory."""+ self.add_calls.append({"messages": messages, **kwargs})+ # First attempt: extracted nothing → triggers fallback.+ # Second attempt (with infer=False): succeeds.+ if len(self.add_calls) < 2:+ return {"results": []}+ return {"results": [{"id": "m1", "memory": "saved"}]}++ fake = CountingFake()+ mw = Mem0Middleware(client=fake, user_id="alice", mode="agent_control")+ agent = await self._agent(mw)+ await agent.reply(UserMsg("user", "hi"))+ add_tool = _find_tool(self.toolkit, "add_memory")++ result = await add_tool(+ thinking="my reasoning",+ content=["fact one"],+ )+ self.assertIn("Successfully recorded", _chunk_text(result))++ # Exactly 2 calls — the role-switch tier from v1 is gone.+ self.assertEqual(len(fake.add_calls), 2)+ # Both calls use the user role (no more switching).+ self.assertEqual(fake.add_calls[0]["messages"][0]["role"], "user")+ self.assertEqual(fake.add_calls[1]["messages"][0]["role"], "user")+ # First call uses default inference; second explicitly disables it.+ self.assertNotIn("infer", fake.add_calls[0])+ self.assertFalse(fake.add_calls[1]["infer"])++ async def test_add_memory_does_not_persist_thinking(self) -> None:+ """``thinking`` is the agent's rationale — it appears in the+ tool's return text (auditable in the transcript) but is NOT+ sent to mem0, so the stored memory stays clean of agent+ self-narration."""+ fake = _FakeAsyncMem0Client()+ # First attempt extracts something → no fallback.+ fake.add = AsyncMock(+ return_value={"results": [{"id": "m1", "memory": "saved"}]},+ )+ mw = Mem0Middleware(client=fake, user_id="alice", mode="agent_control")+ agent = await self._agent(mw)+ await agent.reply(UserMsg("user", "hi"))+ add_tool = _find_tool(self.toolkit, "add_memory")++ thinking = "user said X because Y"+ fact = "likes coffee"+ result = await add_tool(+ thinking=thinking,+ content=[fact],+ )+ result_text = _chunk_text(result)++ # mem0 only saw the fact, NOT the rationale.+ sent = fake.add.call_args.args[0][0]["content"]+ self.assertIn(fact, sent)+ self.assertNotIn(thinking, sent)++ # ...but the tool return text DOES echo the rationale, so the+ # decision is auditable in the agent transcript.+ self.assertIn(thinking, result_text)+++# ----------------------------------------------------------------------+# Both mode — hooks + tools together+# ----------------------------------------------------------------------+++class TestBothMode(IsolatedAsyncioTestCase):+ """Tests for combined static-control and agent-control behavior."""++ async def test_memory_msg_and_tool_hint_both_present(self) -> None:+ """Both mode should inject memory and expose memory tools."""+ model = RecordingMockModel(context_size=100_000)+ fake = _FakeAsyncMem0Client(+ search_return={"results": [{"memory": "auto-injected"}]},+ )+ mw = Mem0Middleware(client=fake, user_id="alice", mode="both")+ toolkit = Toolkit(tools=await mw.list_tools())+ model.set_responses([_single_response("ok")])+ agent = Agent(+ name="a",+ system_prompt="base",+ model=model,+ toolkit=toolkit,+ middlewares=[mw],+ )+ await agent.reply(UserMsg("user", "hi"))++ # Static hooks ran.+ self.assertEqual(len(fake.search_calls), 1)+ self.assertEqual(len(fake.add_calls), 1)++ msgs = model.last_call_messages++ # System prompt has the tool nudge (from on_system_prompt).+ prompt_text = msgs[0].get_text_content()+ self.assertIn("Long-term memory", prompt_text)+ self.assertIn("search_memory", prompt_text)++ # Memory injected as a synthetic HintBlock Msg.+ memory_msgs = [m for m in msgs if getattr(m, "name", None) == "memory"]+ self.assertEqual(len(memory_msgs), 1)+ memory_hints = memory_msgs[0].get_content_blocks("hint")+ self.assertEqual(len(memory_hints), 1)+ self.assertIn("auto-injected", memory_hints[0].hint)++ # Tools exposed.+ names = _all_tool_names(toolkit)+ self.assertIn("search_memory", names)+ self.assertIn("add_memory", names)