Skip to content

Commit be96b7b

Browse files
committed
Handle synchronous generator functions in _invoke_callable
1 parent 96f3c86 commit be96b7b

File tree

2 files changed

+24
-0
lines changed

2 files changed

+24
-0
lines changed

src/google/adk/tools/function_tool.py

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -230,6 +230,13 @@ async def _invoke_callable(
230230
if is_async_gen:
231231
return [item async for item in target(**args_to_call)]
232232

233+
is_sync_gen = inspect.isgeneratorfunction(target) or (
234+
hasattr(target, '__call__')
235+
and inspect.isgeneratorfunction(target.__call__)
236+
)
237+
if is_sync_gen:
238+
return list(target(**args_to_call))
239+
233240
# Functions are callable objects, but not all callable objects are functions
234241
# checking coroutine function is not enough. We also need to check whether
235242
# Callable's __call__ function is a coroutine function

tests/unittests/tools/test_function_tool.py

Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -14,6 +14,7 @@
1414

1515
import collections.abc
1616
from typing import AsyncGenerator
17+
from typing import Generator
1718
from unittest.mock import MagicMock
1819

1920
from google.adk.agents.invocation_context import InvocationContext
@@ -458,3 +459,19 @@ async def streaming_tool(param: str) -> AsyncGenerator[str, None]:
458459

459460
assert isinstance(result, list)
460461
assert result == ["part 1 test", "part 2 test"]
462+
463+
464+
@pytest.mark.asyncio
465+
async def test_run_async_sync_generator():
466+
"""Test that run_async consumes the sync generator and returns a list."""
467+
468+
def sync_generator_tool(param: str) -> Generator[str, None, None]:
469+
yield f"part 1 {param}"
470+
yield f"part 2 {param}"
471+
472+
tool = FunctionTool(sync_generator_tool)
473+
474+
result = await tool.run_async(args={"param": "test"}, tool_context=None)
475+
476+
assert isinstance(result, list)
477+
assert result == ["part 1 test", "part 2 test"]

0 commit comments

Comments
 (0)