Build and run agents you can see, understand and trust.
Python agentchatbotlarge-language-modelsllmllm-agentmcpmulti-agentmulti-modalreact-agentrealtime-agentvoice-agentvoice-assistant
feat(app): activate the agentic memory within the agent service (#2263)
DavdGao29b592358c2e
diff --git a/examples/agent_service/main.py b/examples/agent_service/main.pyindex 84f8122d6..a41baba1d 100644--- a/examples/agent_service/main.py+++ b/examples/agent_service/main.py@@ -14,8 +14,10 @@ from agentscope.app.rag.knowledge_base_manager import CollectionPerKbManagerfrom agentscope.app.storage import RedisStoragefrom agentscope.app.workspace_manager import LocalWorkspaceManagerfrom agentscope.mcp import MCPClient, StdioMCPConfig, HttpMCPConfig+from agentscope.middleware import AgenticMemoryMiddleware, MiddlewareBasefrom agentscope.permission import PermissionContext, PermissionModefrom agentscope.rag import QdrantStore+from agentscope.workspace import WorkspaceBasedefault_mcps = [MCPClient(@@ -47,6 +49,24 @@ storage = RedisStorage(vector_store = QdrantStore(location=":memory:")++async def longterm_memory_factory(+ user_id: str,+ agent_id: str,+ session_id: str,+ workspace: WorkspaceBase,+) -> list[MiddlewareBase]:+ """Attach Markdown-file long-term memory, stored under the session's+ workspace so it is reachable through whichever backend is bound."""+ del user_id, agent_id, session_id+ return [+ AgenticMemoryMiddleware(+ workdir=workspace.workdir,+ backend=workspace.get_backend(),+ ),+ ]++app = create_app(storage=storage,message_bus=InMemoryMessageBus(),@@ -118,6 +138,9 @@ so anything you want them to see MUST be sent through `TeamSay`.""",),),],+ # Long-term memory. The default PER_AGENT workspace isolation makes+ # the memory survive across sessions of the same agent.+ extra_agent_middlewares=longterm_memory_factory,extra_middlewares=[Middleware(CORSMiddleware,diff --git a/src/agentscope/app/_app.py b/src/agentscope/app/_app.pyindex d96a76ad2..e43afc74c 100644--- a/src/agentscope/app/_app.py+++ b/src/agentscope/app/_app.py@@ -197,14 +197,21 @@ def create_app(extra_middlewares (`list[Middleware] | None`, optional):Additional ASGI middlewares to add to the application.extra_agent_middlewares (`AgentMiddlewareFactory | None`, optional):- An async factory ``(user_id, agent_id, session_id) -> awaitable- of list[MiddlewareBase]`` that produces extra+ An async factory ``(user_id, agent_id, session_id, workspace) ->+ awaitable of list[MiddlewareBase]`` that produces extra:class:`~agentscope.middleware.MiddlewareBase` instances toattach to the agent on each invocation. Called once per agentassembly (i.e. per chat turn / scheduled trigger), so it canreturn user/session-specific middleware (auth, audit logging,- tenant isolation, etc.). The returned middlewares are appended- to the framework-supplied ones (e.g. ``ToolOffloadMiddleware``).+ tenant isolation, etc.). ``workspace`` is the session's+ resolved :class:`~agentscope.workspace.WorkspaceBase`, exposing+ ``workdir`` and ``get_backend()`` for filesystem-backed+ middleware such as+ :class:`~agentscope.middleware.AgenticMemoryMiddleware`.+ Factories written against the older three-argument signature+ keep working — the fourth argument is only passed to factories+ that accept it. The returned middlewares are appended to the+ framework-supplied ones (e.g. ``ToolOffloadMiddleware``).extra_agent_tools (`AgentToolFactory | None`, optional):An async factory ``(user_id, agent_id, session_id) -> awaitableof list[ToolBase]`` that produces extradiff --git a/src/agentscope/app/_service/_chat.py b/src/agentscope/app/_service/_chat.pyindex 9c4db81a3..cb6729571 100644--- a/src/agentscope/app/_service/_chat.py+++ b/src/agentscope/app/_service/_chat.py@@ -12,6 +12,7 @@ that wants them subscribes through the``GET /sessions/{sid}/stream`` SSE endpoint."""import asyncio+import inspectfrom typing import TYPE_CHECKINGfrom fastapi import HTTPException@@ -137,6 +138,9 @@ class ChatService:optional):Async factory invoked at every chat turn to produceuser/session-specific middlewares to attach to the agent.+ Called as ``(user_id, agent_id, session_id, workspace)``,+ falling back to the legacy three-argument call when the+ factory does not accept ``workspace``.extra_agent_tools (`AgentToolFactory | None`, optional):Async factory invoked at every chat turn to produceuser/session-specific tools to register in the toolkit.@@ -169,6 +173,20 @@ optional):self._access = resource_access_serviceself._knowledge_base_manager = knowledge_base_managerself._extra_agent_middlewares = extra_agent_middlewares+ # Probed once (the service is built once per lifespan) so legacy+ # three-argument factories keep working without the per-turn cost.+ self._middlewares_take_workspace = False+ if extra_agent_middlewares is not None:+ try:+ inspect.signature(extra_agent_middlewares).bind(+ "",+ "",+ "",+ None,+ )+ self._middlewares_take_workspace = True+ except (TypeError, ValueError):+ passself._extra_agent_tools = extra_agent_toolsself._channel_dispatcher = channel_dispatcherself._sub_agent_templates = custom_subagent_templates@@ -575,12 +593,11 @@ optional):),]if self._extra_agent_middlewares is not None:+ factory_args: tuple = (user_id, agent_id, session_id)+ if self._middlewares_take_workspace:+ factory_args += (workspace,)middlewares.extend(- await self._extra_agent_middlewares(- user_id,- agent_id,- session_id,- ),+ await self._extra_agent_middlewares(*factory_args),)# ----------------------------------------------------------------diff --git a/src/agentscope/app/_types.py b/src/agentscope/app/_types.pyindex a4180df01..abee28e47 100644--- a/src/agentscope/app/_types.py+++ b/src/agentscope/app/_types.py@@ -11,18 +11,24 @@ from ..middleware import MiddlewareBasefrom ..permission import PermissionContextfrom ..state import TaskContextfrom ..tool import ToolBase+from ..workspace import WorkspaceBaseif TYPE_CHECKING:from ._service._session_projection import SessionProjectionfrom .storage import AgentRecord, SessionRecord-AgentMiddlewareFactory = Callable[- [str, str, str],- Awaitable[list[MiddlewareBase]],-]-# Async factory signature: ``(user_id, agent_id, session_id)`` →-# awaitable of :class:`~agentscope.middleware.MiddlewareBase` instances.+AgentMiddlewareFactory = (+ Callable[[str, str, str], Awaitable[list[MiddlewareBase]]]+ | Callable[+ [str, str, str, WorkspaceBase],+ Awaitable[list[MiddlewareBase]],+ ]+)+# Async factory: ``(user_id, agent_id, session_id, workspace)`` → awaitable+# of :class:`~agentscope.middleware.MiddlewareBase` instances. The legacy+# three-argument form stays supported — ``ChatService`` probes the signature+# and only passes ``workspace`` to factories that accept it.AgentToolFactory = Callable[[str, str, str],diff --git a/tests/service_chat_middleware_factory_test.py b/tests/service_chat_middleware_factory_test.pynew file mode 100644index 000000000..8e53d4bb3--- /dev/null+++ b/tests/service_chat_middleware_factory_test.py@@ -0,0 +1,96 @@+# -*- coding: utf-8 -*-+# pylint: disable=protected-access+"""Back-compat probe for the ``extra_agent_middlewares`` factory.++The factory gained a fourth ``workspace`` argument. ``ChatService`` probes+each factory's signature once at construction so factories written against+the original three-argument shape keep being called with three arguments.+"""+import functools+from unittest import TestCase++from agentscope.app._service._chat import ChatService+++def _probe(factory: object) -> bool:+ """Return whether ``ChatService`` would pass ``workspace`` to+ ``factory``.++ Args:+ factory (`object`):+ The candidate ``extra_agent_middlewares`` factory.++ Returns:+ `bool`:+ ``True`` when the service resolved the four-argument shape.+ """+ service = ChatService(+ storage=None,+ workspace_manager=None,+ scheduler_manager=None,+ background_task_manager=None,+ message_bus=None,+ resource_access_service=None,+ extra_agent_middlewares=factory,+ )+ return service._middlewares_take_workspace+++async def _legacy(user_id: str, agent_id: str, session_id: str) -> list:+ """A factory written before ``workspace`` existed."""+ del user_id, agent_id, session_id+ return []+++async def _with_workspace(+ user_id: str,+ agent_id: str,+ session_id: str,+ workspace: object,+) -> list:+ """A factory that opted into the fourth argument."""+ del user_id, agent_id, session_id, workspace+ return []+++class _CallableLegacy:+ """A callable object using the three-argument shape."""++ async def __call__(self, user_id: str, agent_id: str, sid: str) -> list:+ """Return no middlewares."""+ del user_id, agent_id, sid+ return []+++class ExtraMiddlewareFactoryProbeTest(TestCase):+ """The probe must classify every callable shape correctly."""++ def test_legacy_factory_is_called_without_workspace(self) -> None:+ """A three-argument factory must not receive ``workspace``."""+ self.assertFalse(_probe(_legacy))++ def test_new_factory_receives_workspace(self) -> None:+ """A four-argument factory must receive ``workspace``."""+ self.assertTrue(_probe(_with_workspace))++ def test_no_factory_is_inert(self) -> None:+ """``None`` must not be probed as if it were callable."""+ self.assertFalse(_probe(None))++ def test_var_positional_factory_receives_workspace(self) -> None:+ """``*args`` absorbs the fourth argument, so pass it."""++ async def factory(*args: object) -> list:+ del args+ return []++ self.assertTrue(_probe(factory))++ def test_callable_object_is_probed_on_its_call(self) -> None:+ """``__call__`` is what gets invoked, so it is what is measured."""+ self.assertFalse(_probe(_CallableLegacy()))++ def test_partial_keeps_the_underlying_shape(self) -> None:+ """``functools.partial`` must not be mistaken for a legacy shape."""+ self.assertTrue(_probe(functools.partial(_with_workspace)))+ self.assertFalse(_probe(functools.partial(_legacy)))diff --git a/tests/service_workspace_files_test.py b/tests/service_workspace_files_test.pyindex aeea0414a..a485928f1 100644--- a/tests/service_workspace_files_test.py+++ b/tests/service_workspace_files_test.py@@ -578,11 +578,16 @@ class WorkspaceFileEndpointTests(IsolatedAsyncioTestCase):async def test_tampered_token_raises_401(self) -> None:"""An edited signature must not pass."""token, _ = self._service.sign_download_token("u", "notes.txt")+ # Edit the signature's first character, not its last: a 32-byte+ # digest ends on a base64 char carrying only 4 significant bits,+ # so editing that one can decode back to the same digest.+ expiry, user, signature = token.split(".")+ tampered = ("A" if signature[0] != "A" else "B") + signature[1:]with self.assertRaises(HTTPException) as ctx:await self._read(path="notes.txt",download=True,- token=token[:-1] + ("A" if token[-1] != "A" else "B"),+ token=f"{expiry}.{user}.{tampered}",x_user_id=None,)self.assertEqual(