Build and run agents you can see, understand and trust.
Python agentchatbotlarge-language-modelsllmllm-agentmcpmulti-agentmulti-modalreact-agentrealtime-agentvoice-agentvoice-assistant
feat(toolkit): support async func for the `postprocess_func` argument in toolkit (#885)
qbc51b6b83112e1
diff --git a/src/agentscope/tool/_async_wrapper.py b/src/agentscope/tool/_async_wrapper.pyindex 1f127bf80..20edd40a6 100644--- a/src/agentscope/tool/_async_wrapper.py+++ b/src/agentscope/tool/_async_wrapper.py@@ -6,19 +6,30 @@ TODO: handle the exception raised when yielding from async generatorinto a normal ToolResponse instance."""import asyncio-from typing import AsyncGenerator, Generator, Callable+from typing import AsyncGenerator, Generator, Callable, Awaitablefrom ._response import ToolResponsefrom ..message import TextBlock+from .._utils._common import _execute_async_or_sync_funcasync def _postprocess_tool_response(tool_response: ToolResponse,- postprocess_func: Callable[[ToolResponse], ToolResponse | None] | None,+ postprocess_func: (+ Callable[[ToolResponse], ToolResponse | None]+ | Callable[[ToolResponse], Awaitable[ToolResponse | None]]+ )+ | None,) -> ToolResponse:- """Post-process a ToolResponse object with the given function."""+ """Post-process a ToolResponse object with the given function.++ Supports both sync and async postprocess_func.+ """if postprocess_func:- processed_response = postprocess_func(tool_response)+ processed_response = await _execute_async_or_sync_func(+ postprocess_func,+ tool_response,+ )if processed_response:return processed_responsereturn tool_response@@ -26,7 +37,11 @@ async def _postprocess_tool_response(async def _object_wrapper(obj: ToolResponse,- postprocess_func: Callable[[ToolResponse], ToolResponse | None] | None,+ postprocess_func: (+ Callable[[ToolResponse], ToolResponse | None]+ | Callable[[ToolResponse], Awaitable[ToolResponse | None]]+ )+ | None,) -> AsyncGenerator[ToolResponse, None]:"""Wrap a ToolResponse object to an async generator."""yield await _postprocess_tool_response(obj, postprocess_func)@@ -34,7 +49,11 @@ async def _object_wrapper(async def _sync_generator_wrapper(sync_generator: Generator[ToolResponse, None, None],- postprocess_func: Callable[[ToolResponse], ToolResponse | None] | None,+ postprocess_func: (+ Callable[[ToolResponse], ToolResponse | None]+ | Callable[[ToolResponse], Awaitable[ToolResponse | None]]+ )+ | None,) -> AsyncGenerator[ToolResponse, None]:"""Wrap a sync generator to an async generator."""for chunk in sync_generator:@@ -43,7 +62,11 @@ async def _sync_generator_wrapper(async def _async_generator_wrapper(async_func: AsyncGenerator[ToolResponse, None],- postprocess_func: Callable[[ToolResponse], ToolResponse | None] | None,+ postprocess_func: (+ Callable[[ToolResponse], ToolResponse | None]+ | Callable[[ToolResponse], Awaitable[ToolResponse | None]]+ )+ | None,) -> AsyncGenerator[ToolResponse, None]:"""When the function is interrupted during generating the toolresponse, add an interrupted message to the response, and postponediff --git a/src/agentscope/tool/_registered_tool_function.py b/src/agentscope/tool/_registered_tool_function.pyindex 3f9c1dd63..c1438977f 100644--- a/src/agentscope/tool/_registered_tool_function.py+++ b/src/agentscope/tool/_registered_tool_function.py@@ -2,7 +2,7 @@"""The data model for registered tool functions in AgentScope."""from copy import deepcopyfrom dataclasses import field, dataclass-from typing import Callable, Literal, Type+from typing import Callable, Literal, Type, Awaitablefrom pydantic import BaseModel@@ -36,15 +36,22 @@ class RegisteredToolFunction:function, so that we can dynamically adjust the tool function."""mcp_name: str | None = None"""The name of the MCP, if the tool function comes from an MCP server."""- postprocess_func: Callable[- [ToolUseBlock, ToolResponse],- ToolResponse | None,- ] | None = None+ postprocess_func: (+ Callable[+ [ToolUseBlock, ToolResponse],+ ToolResponse | None,+ ]+ | Callable[+ [ToolUseBlock, ToolResponse],+ Awaitable[ToolResponse | None],+ ]+ ) | None = None"""The post-processing function that will be called after the toolfunction is executed, taking the tool call block and tool- response as arguments. If it returns `None`, the tool result will be- returned as is. If it returns a `ToolResponse`, the returned block- will be used as the final tool response."""+ response as arguments. The function can be either sync or async. If it+ returns `None`, the tool result will be returned as is. If it returns a+ `ToolResponse`, the returned block will be used as the final tool+ response."""@propertydef extended_json_schema(self) -> dict:diff --git a/src/agentscope/tool/_toolkit.py b/src/agentscope/tool/_toolkit.pyindex 8fe721523..41ea795f7 100644--- a/src/agentscope/tool/_toolkit.py+++ b/src/agentscope/tool/_toolkit.py@@ -14,6 +14,7 @@ from typing import (Type,Generator,Callable,+ Awaitable,)from pydantic import (@@ -196,13 +197,16 @@ class Toolkit(StateModule):include_long_description: bool = True,include_var_positional: bool = False,include_var_keyword: bool = False,- postprocess_func: Callable[- [- ToolUseBlock,- ToolResponse,- ],- ToolResponse | None,- ]+ postprocess_func: (+ Callable[+ [ToolUseBlock, ToolResponse],+ ToolResponse | None,+ ]+ | Callable[+ [ToolUseBlock, ToolResponse],+ Awaitable[ToolResponse | None],+ ]+ )| None = None,) -> None:"""Register a tool function to the toolkit.@@ -237,14 +241,15 @@ class Toolkit(StateModule):include_var_keyword (`bool`, defaults to `False`):Whether to include the variable keyword arguments (`**kwargs`)in the function schema.- postprocess_func (`Callable[[ToolUseBlock, ToolResponse], \- ToolResponse | None] | None`, optional):+ postprocess_func (`(Callable[[ToolUseBlock, ToolResponse], \+ ToolResponse | None] | Callable[[ToolUseBlock, ToolResponse], \+ Awaitable[ToolResponse | None]]) | None`, optional):A post-processing function that will be called after the toolfunction is executed, taking the tool call block and tool- response as arguments. If it returns `None`, the tool- result will be returned as is. If it returns a- `ToolResponse`, the returned block will be used as the- final tool result.+ response as arguments. The function can be either sync or+ async. If it returns `None`, the tool result will be+ returned as is. If it returns a `ToolResponse`,+ the returned block will be used as the final tool result."""# Arguments checkingif group_name not in self.groups and group_name != "basic":@@ -536,7 +541,12 @@ class Toolkit(StateModule):# Prepare postprocess functionif tool_func.postprocess_func:- partial_postprocess_func = partial(+ # Type: partial wraps the postprocess_func with tool_call bound,+ # reducing it from (ToolUseBlock, ToolResponse) to (ToolResponse)+ partial_postprocess_func: (+ Callable[[ToolResponse], ToolResponse | None]+ | Callable[[ToolResponse], Awaitable[ToolResponse | None]]+ ) | None = partial(tool_func.postprocess_func,tool_call,)@@ -605,13 +615,16 @@ class Toolkit(StateModule):enable_funcs: list[str] | None = None,disable_funcs: list[str] | None = None,preset_kwargs_mapping: dict[str, dict[str, Any]] | None = None,- postprocess_func: Callable[- [- ToolUseBlock,- ToolResponse,- ],- ToolResponse | None,- ]+ postprocess_func: (+ Callable[+ [ToolUseBlock, ToolResponse],+ ToolResponse | None,+ ]+ | Callable[+ [ToolUseBlock, ToolResponse],+ Awaitable[ToolResponse | None],+ ]+ )| None = None,) -> None:"""Register tool functions from an MCP client.@@ -631,14 +644,15 @@ class Toolkit(StateModule):defaults to `None`):The preset keyword arguments mapping, whose keys are the toolfunction names and values are the preset keyword arguments.- postprocess_func (`Callable[[ToolUseBlock, ToolResponse], \- ToolResponse | None] | None`, optional):+ postprocess_func (`(Callable[[ToolUseBlock, ToolResponse], \+ ToolResponse | None] | Callable[[ToolUseBlock, ToolResponse], \+ Awaitable[ToolResponse | None]]) | None`, optional):A post-processing function that will be called after the toolfunction is executed, taking the tool call block and tool- response as arguments. If it returns `None`, the tool- result will be returned as is. If it returns a- `ToolResponse`, the returned block will be used as the- final tool result.+ response as arguments. The function can be either sync or+ async. If it returns `None`, the tool result will be+ returned as is. If it returns a `ToolResponse`,+ the returned block will be used as the final tool result."""if (isinstance(mcp_client, StatefulClientBase)diff --git a/tests/toolkit_test.py b/tests/toolkit_test.pyindex 01556dc06..23edcabd8 100644--- a/tests/toolkit_test.py+++ b/tests/toolkit_test.py@@ -664,7 +664,45 @@ class ToolkitTest(IsolatedAsyncioTestCase):res = await self.toolkit.call_tool_function(tool_use_block)async for chunk in res:- print(chunk)+ self.assertEqual(+ chunk.content,+ [+ TextBlock(type="text", text="arg1: 10, arg2: ['test']"),+ TextBlock(type="text", text="Processed"),+ ],+ )++ async def test_async_postprocess_func(self) -> None:+ """Test async postprocess function."""+ tool_use_block = ToolUseBlock(+ type="tool_use",+ id="123",+ name="sync_func",+ input={"arg1": 10, "arg2": ["test"]},+ )++ async def async_postprocess_func(+ tool_use: ToolUseBlock,+ tool_response: ToolResponse,+ ) -> ToolResponse | None:+ """Postprocess function to modify tool response."""++ self.assertEqual(tool_use, tool_use_block)++ if tool_response.content:+ tool_response.content.append(+ TextBlock(type="text", text="Processed"),+ )+ return tool_response++ self.toolkit.register_tool_function(+ sync_func,+ postprocess_func=async_postprocess_func,+ )++ res = await self.toolkit.call_tool_function(tool_use_block)++ async for chunk in res:self.assertEqual(chunk.content,[