Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions docs/guides/tools/function_tool/index.md
Original file line number Diff line number Diff line change
Expand Up @@ -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`:
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -949,6 +949,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.
Expand Down
70 changes: 70 additions & 0 deletions tests/unittests/tools/test_function_tool.py
Original file line number Diff line number Diff line change
Expand Up @@ -263,6 +263,76 @@ 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."""

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"]


def _sync_wrapper(func: Callable[..., Any]) -> Callable[..., Any]:
"""A plain sync decorator, as commonly used for logging or retries."""

Expand Down
Loading