From 726c20384bd8b2fd074a5a9777962c0c6cccefa3 Mon Sep 17 00:00:00 2001 From: BichengWang Date: Sun, 11 Oct 2026 20:36:44 -0700 Subject: [PATCH] fix(tools): resolve awaitables returned by synchronous wrappers Await results from synchronous FunctionTool callables after inline or thread-pool invocation. This executes wrapped async tools and evaluates wrapped confirmation predicates using their resolved decisions instead of coroutine objects. --- docs/guides/tools/function_tool/index.md | 2 + src/google/adk/tools/function_tool.py | 10 ++- .../tools/test_functions_thread_pool.py | 32 +++++++++ tests/unittests/tools/test_function_tool.py | 71 +++++++++++++++++++ 4 files changed, 113 insertions(+), 2 deletions(-) diff --git a/docs/guides/tools/function_tool/index.md b/docs/guides/tools/function_tool/index.md index 105f203f9cb..7c2d7948624 100644 --- a/docs/guides/tools/function_tool/index.md +++ b/docs/guides/tools/function_tool/index.md @@ -61,6 +61,8 @@ Before invoking the function, `FunctionTool` validates and coerces each annotate `FunctionTool` accepts both synchronous `def` functions and asynchronous `async def` coroutines. Coroutines are awaited on the event loop. Synchronous functions run on the tool thread pool when `RunConfig.tool_thread_pool_config` is configured on the runner, preventing blocking I/O or CPU work inside a synchronous tool from stalling concurrent tool calls. +If a synchronous callable returns an awaitable, such as a coroutine from an async function wrapped by a synchronous decorator, `FunctionTool` awaits it before returning the tool result. With a tool thread pool enabled, the synchronous wrapper runs in a worker thread and its awaitable resolves on the caller's event loop. Exceptions from the awaitable propagate to the caller. The same behavior applies to callable confirmation predicates. + ### Generator tools and isolated sub-branches In standard `Runner.run_async` runs, a synchronous generator or asynchronous generator passed to `FunctionTool` executes as a node on an isolated sub-branch formatted as `{tool_name}@{function_call_id}`. This sub-branch isolates intermediate events from the parent agent's prompt history while still streaming every yielded `Event` to the caller in real time. Intermediate events are never fed back to the model, in the current turn or in later turns; the model only sees the final `FunctionResponse`: diff --git a/src/google/adk/tools/function_tool.py b/src/google/adk/tools/function_tool.py index fafef689e2f..1599bffb8a3 100644 --- a/src/google/adk/tools/function_tool.py +++ b/src/google/adk/tools/function_tool.py @@ -505,8 +505,14 @@ async def _invoke_callable( return await target(**args_to_call) runner = _SYNC_CALLABLE_RUNNER.get() if runner is not None: - return await runner(target, args_to_call) - return target(**args_to_call) + result = await runner(target, args_to_call) + else: + result = target(**args_to_call) + # A sync wrapper can return a coroutine or another awaitable even though + # neither the wrapper nor its __call__ is a coroutine function. + if inspect.isawaitable(result): + return await result + return result def _get_mandatory_args( self, diff --git a/tests/unittests/flows/llm_flows/tools/test_functions_thread_pool.py b/tests/unittests/flows/llm_flows/tools/test_functions_thread_pool.py index c183933a2f9..558e31c9adc 100644 --- a/tests/unittests/flows/llm_flows/tools/test_functions_thread_pool.py +++ b/tests/unittests/flows/llm_flows/tools/test_functions_thread_pool.py @@ -948,6 +948,38 @@ async def async_func() -> dict[str, str]: assert result == {'value': 'main_thread_value'} + async def test_sync_wrapper_awaitable_runs_on_caller_loop(self): + """A worker-created coroutine resolves on the caller's event loop.""" + caller_loop = asyncio.get_running_loop() + wrapper_threads = [] + + async def resolve(value: str) -> str: + assert asyncio.get_running_loop() is caller_loop + await asyncio.sleep(0) + return f'resolved:{value}' + + def wrapped_tool(value: str): + wrapper_threads.append(threading.current_thread().name) + return resolve(value) + + tool = FunctionTool(wrapped_tool) + model = testing_utils.MockModel.create(responses=[]) + agent = Agent(name='test_agent', model=model, tools=[tool]) + invocation_context = await testing_utils.create_invocation_context( + agent=agent, user_content='' + ) + tool_context = ToolContext( + invocation_context=invocation_context, function_call_id='test_id' + ) + + result = await _call_tool_in_thread_pool( + tool, {'value': 'hello'}, tool_context + ) + + assert result == 'resolved:hello' + assert len(wrapper_threads) == 1 + assert wrapper_threads[0].startswith('adk_tool_executor') + @pytest.mark.asyncio async def test_sync_tool_returning_none_runs_exactly_once(self): """Regression test for double invocation of a None-returning sync tool. diff --git a/tests/unittests/tools/test_function_tool.py b/tests/unittests/tools/test_function_tool.py index 972a6c7379d..1aa20de8d86 100644 --- a/tests/unittests/tools/test_function_tool.py +++ b/tests/unittests/tools/test_function_tool.py @@ -257,6 +257,77 @@ async def test_run_async_without_tool_context_sync_func(): assert result == "test_value_1" +@pytest.mark.parametrize("result_kind", ["coroutine", "future"]) +async def test_run_async_resolves_awaitable_from_sync_function(result_kind): + """Synchronous wrappers return their asynchronous result, not an awaitable.""" + import asyncio + + async def resolve(value: str) -> str: + await asyncio.sleep(0) + return f"resolved:{value}" + + def wrapped_tool(value: str): + if result_kind == "future": + future = asyncio.get_running_loop().create_future() + future.set_result(f"resolved:{value}") + return future + return resolve(value) + + result = await FunctionTool(wrapped_tool).run_async( + args={"value": "hello"}, tool_context=MagicMock() + ) + + assert result == "resolved:hello" + + +async def test_run_async_propagates_error_from_sync_wrapped_coroutine(): + """Errors raised while awaiting a wrapped tool still reach the caller.""" + + async def fail(): + raise ValueError("wrapped tool failed") + + def wrapped_tool(): + return fail() + + with pytest.raises(ValueError, match="wrapped tool failed"): + await FunctionTool(wrapped_tool).run_async( + args={}, tool_context=MagicMock() + ) + + +@pytest.mark.parametrize("requires_confirmation", [False, True]) +async def test_sync_wrapped_confirmation_predicate_is_awaited( + requires_confirmation, mock_tool_context +): + """A wrapped async predicate gates execution using its resolved boolean.""" + calls = [] + + def tool(value: str) -> str: + calls.append(value) + return value + + async def decide(value: str) -> bool: + return requires_confirmation + + def wrapped_predicate(value: str): + return decide(value) + + mock_tool_context.tool_confirmation = None + mock_tool_context.function_call_id = "test_function_call_id" + function_tool = FunctionTool(tool, require_confirmation=wrapped_predicate) + + result = await function_tool.run_async( + args={"value": "hello"}, tool_context=mock_tool_context + ) + + if requires_confirmation: + assert "requires confirmation" in result["error"] + assert calls == [] + else: + assert result == "hello" + assert calls == ["hello"] + + @pytest.mark.asyncio async def test_run_async_1_missing_arg_sync_func(): """Test that run_async calls the function with 1 missing arg in signature (synchronous function)."""