Skip to content

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

fix(middleware): default mem0 search_memory limit to top_k (#3720)

Kiko030126f6e7aba010
diff --git a/src/agentscope/middleware/_longterm_memory/_mem0/_tools.py b/src/agentscope/middleware/_longterm_memory/_mem0/_tools.py
index 633ed891d..5cbad7105 100644
--- a/src/agentscope/middleware/_longterm_memory/_mem0/_tools.py
+++ b/src/agentscope/middleware/_longterm_memory/_mem0/_tools.py
@@ -67,35 +67,54 @@ class _SearchMemoryTool(_Mem0MemoryToolBase):
"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
+ def __init__(
+ self,
+ mw: "Mem0Middleware",
+ ) -> None:
+ """Bind the tool to ``mw`` and build its per-instance schema.
+
+ The advertised ``limit`` default is read from the middleware's
+ ``top_k`` here (rather than a hardcoded constant), so configuring
+ ``top_k`` on the middleware also governs the tool's default.
+
+ Args:
+ mw (`Mem0Middleware`):
+ The middleware whose mem0 client and ``top_k`` this
+ search tool uses.
+ """
+ super().__init__(mw)
+ # Per-instance schema so the default ``limit`` reflects this
+ # middleware's ``top_k`` rather than a hardcoded constant.
+ self.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": mw._top_k,
+ },
+ },
+ "required": ["keywords"],
+ }
+
async def __call__(
self,
keywords: list[str],
- limit: int = 5,
+ limit: int | None = None,
) -> ToolChunk:
"""Retrieve the memory based on the given keywords.
@@ -107,10 +126,13 @@ class _SearchMemoryTool(_Mem0MemoryToolBase):
memory). Each keyword is issued as an independent query
against the memory store; results are merged and
deduplicated.
- limit (int):
+ limit (int | None):
The maximum number of memories to retrieve per keyword.
- Defaults to 5.
+ When omitted, falls back to the middleware's ``top_k``.
"""
+ if limit is None:
+ limit = self._mw._top_k
+
if not keywords:
return _text_chunk("(no keywords supplied — nothing to search)")
diff --git a/tests/mem0_middleware_test.py b/tests/mem0_middleware_test.py
index 086de47f9..86257d95d 100644
--- a/tests/mem0_middleware_test.py
+++ b/tests/mem0_middleware_test.py
@@ -692,6 +692,43 @@ class TestAgentControlMode(IsolatedAsyncioTestCase):
self.assertEqual(fake.search_calls[0]["top_k"], 3)
self.assertEqual(mw._top_k, 9)
+ async def test_search_memory_defaults_to_middleware_top_k(self) -> None:
+ """Omitting ``limit`` must fall back to the middleware's
+ ``top_k``, both in the advertised schema and in the mem0 call.
+
+ The tool used to hardcode ``5``, so a middleware configured
+ with ``top_k=9`` still searched for five memories per keyword.
+ """
+ fake = _FakeAsyncMem0Client(
+ search_return={"results": [{"memory": "found"}]},
+ )
+ mw = Mem0Middleware(
+ client=fake,
+ user_id="alice",
+ mode="agent_control",
+ top_k=9,
+ )
+ agent = await self._agent(mw, system_prompt="base prompt")
+ await agent.reply(UserMsg("user", "hi"))
+
+ search_tool = _find_tool(self.toolkit, "search_memory")
+ await search_tool(keywords=["alice"])
+
+ self.assertEqual(
+ fake.search_calls,
+ [
+ {
+ "query": "alice",
+ "filters": {"user_id": "alice"},
+ "top_k": 9,
+ },
+ ],
+ )
+ self.assertEqual(
+ search_tool.input_schema["properties"]["limit"]["default"],
+ 9,
+ )
+
async def test_tools_auto_allow_permission(self) -> None:
"""Memory tools should be auto-allowed by permission checks."""
mw = Mem0Middleware(