Skip to content

feat(tools): run sync tools in a thread to avoid event loop blocking #820

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 3 commits into
base: main
Choose a base branch
from
Open
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
18 changes: 15 additions & 3 deletions src/agents/tool.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
from __future__ import annotations

import asyncio
import inspect
import json
from collections.abc import Awaitable
Expand Down Expand Up @@ -30,7 +31,6 @@
from .util._types import MaybeAwaitable

if TYPE_CHECKING:

from .agent import Agent

ToolParams = ParamSpec("ToolParams")
Expand Down Expand Up @@ -302,6 +302,7 @@ def function_tool(
failure_error_function: ToolErrorFunction | None = None,
strict_mode: bool = True,
is_enabled: bool | Callable[[RunContextWrapper[Any], Agent[Any]], MaybeAwaitable[bool]] = True,
run_in_thread: bool = False,
) -> FunctionTool:
"""Overload for usage as @function_tool (no parentheses)."""
...
Expand All @@ -317,6 +318,7 @@ def function_tool(
failure_error_function: ToolErrorFunction | None = None,
strict_mode: bool = True,
is_enabled: bool | Callable[[RunContextWrapper[Any], Agent[Any]], MaybeAwaitable[bool]] = True,
run_in_thread: bool = False,
) -> Callable[[ToolFunction[...]], FunctionTool]:
"""Overload for usage as @function_tool(...)."""
...
Expand All @@ -332,6 +334,7 @@ def function_tool(
failure_error_function: ToolErrorFunction | None = default_tool_error_function,
strict_mode: bool = True,
is_enabled: bool | Callable[[RunContextWrapper[Any], Agent[Any]], MaybeAwaitable[bool]] = True,
run_in_thread: bool = False,
) -> FunctionTool | Callable[[ToolFunction[...]], FunctionTool]:
"""
Decorator to create a FunctionTool from a function. By default, we will:
Expand Down Expand Up @@ -363,6 +366,9 @@ def function_tool(
is_enabled: Whether the tool is enabled. Can be a bool or a callable that takes the run
context and agent and returns whether the tool is enabled. Disabled tools are hidden
from the LLM at runtime.
run_in_thread: Whether to run the tool in a thread. This only applies to non-async functions.
If True, the tool will be run in a thread, which can be useful to avoid blocking the
main thread.
"""

def _create_function_tool(the_func: ToolFunction[...]) -> FunctionTool:
Expand Down Expand Up @@ -413,9 +419,15 @@ async def _on_invoke_tool_impl(ctx: ToolContext[Any], input: str) -> Any:
result = await the_func(*args, **kwargs_dict)
else:
if schema.takes_context:
result = the_func(ctx, *args, **kwargs_dict)
if run_in_thread:
result = await asyncio.to_thread(the_func, ctx, *args, **kwargs_dict)
else:
result = the_func(ctx, *args, **kwargs_dict)
else:
result = the_func(*args, **kwargs_dict)
if run_in_thread:
result = await asyncio.to_thread(the_func, *args, **kwargs_dict)
else:
result = the_func(*args, **kwargs_dict)

if _debug.DONT_LOG_TOOL_DATA:
logger.debug(f"Tool {schema.name} completed.")
Expand Down