Skip to content

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

fix(tool): await deferred function results (#3135)

fhgffyb768e08f12eb
diff --git a/src/agentscope/tool/_adapters.py b/src/agentscope/tool/_adapters.py
index 67f6e0acf..d62aa6bd8 100644
--- a/src/agentscope/tool/_adapters.py
+++ b/src/agentscope/tool/_adapters.py
@@ -144,10 +144,9 @@ class FunctionTool(ToolBase):
`ToolChunk` or `AsyncGenerator[ToolChunk, None]`:
The normalized result of the function execution.
"""
- if inspect.iscoroutinefunction(self._func):
- result = await self._func(**kwargs)
- else:
- result = self._func(**kwargs)
+ result = self._func(**kwargs)
+ if inspect.isawaitable(result):
+ result = await result
if isinstance(result, AsyncGenerator):
diff --git a/tests/toolkit_test.py b/tests/toolkit_test.py
index bb9d6acc2..0865310e1 100644
--- a/tests/toolkit_test.py
+++ b/tests/toolkit_test.py
@@ -3,7 +3,7 @@
"""Toolkit test case."""
import base64
import json
-from typing import Any, AsyncGenerator, Generator, Literal
+from typing import Any, AsyncGenerator, Awaitable, Generator, Literal
from unittest import TestCase
from unittest.async_case import IsolatedAsyncioTestCase
@@ -494,6 +494,87 @@ class ToolkitTest(IsolatedAsyncioTestCase):
class RegisterFunctionTest(IsolatedAsyncioTestCase):
"""Test registering different functions in the toolkit."""
+ async def test_sync_function_returning_awaitable(self) -> None:
+ """Await the coroutine returned by a sync function."""
+
+ async def finish(value: str) -> ToolChunk:
+ """Create the deferred tool result."""
+ return ToolChunk(content=[TextBlock(text=value)])
+
+ def deferred(value: str) -> Awaitable[ToolChunk]:
+ """Return a coroutine without executing it."""
+ return finish(value)
+
+ toolkit = Toolkit(tools=[FunctionTool(deferred)])
+ results = [
+ item
+ async for item in toolkit.call_tool(
+ ToolCallBlock(
+ id="awaitable",
+ name="deferred",
+ input='{"value": "completed"}',
+ ),
+ AgentState(),
+ )
+ ]
+ self.assertDictEqual(
+ results[-1].model_dump(),
+ {
+ "content": [
+ {
+ "type": "text",
+ "created_at": AnyString(),
+ "finished_at": None,
+ "id": AnyString(),
+ "text": "completed",
+ },
+ ],
+ "state": "success",
+ "metadata": {},
+ "id": "awaitable",
+ },
+ )
+
+ async def test_async_callable_tool(self) -> None:
+ """Await an async callable object."""
+
+ class Deferred:
+ """A callable tool that resolves asynchronously."""
+
+ async def __call__(self, value: str) -> ToolChunk:
+ """Create a tool result asynchronously.
+
+ Args:
+ value (`str`):
+ The text to include in the result.
+
+ Returns:
+ `ToolChunk`:
+ The completed tool result.
+ """
+ return ToolChunk(content=[TextBlock(text=value)])
+
+ tool = FunctionTool(Deferred(), name="deferred")
+ result = await tool.call(value="completed")
+ self.assertDictEqual(
+ result.model_dump(),
+ {
+ "content": [
+ {
+ "type": "text",
+ "created_at": AnyString(),
+ "finished_at": None,
+ "id": AnyString(),
+ "text": "completed",
+ },
+ ],
+ "state": "running",
+ "is_last": True,
+ "metadata": {},
+ "id": AnyString(),
+ },
+ )
+
async def test_sync_non_streaming_function(self) -> None:
"""Test registering a synchronous non-streaming function."""