Skip to content
Merged
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
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,7 @@
from __future__ import annotations

import asyncio
import inspect
import json
from collections.abc import AsyncGenerator
from typing import Any
Expand Down Expand Up @@ -96,7 +97,10 @@ async def _execute(_ctx: Any, args_str: str, _name: str = name) -> str:
args = json.loads(args_str) if args_str else {}
except (json.JSONDecodeError, ValueError):
args = {}
res = await handler(args)
# Accept a sync or an async tool handler.
res = handler(args)
if inspect.isawaitable(res):
res = await res
return str(res)

t = FunctionTool(
Expand Down
33 changes: 33 additions & 0 deletions packages/openai-agents/tests/test_handler.py
Original file line number Diff line number Diff line change
Expand Up @@ -561,6 +561,39 @@ async def _bad(args: Any) -> str:
with pytest.raises(RuntimeError, match="handler error"):
await tools[0].on_invoke_tool(MagicMock(), "{}")

async def test_sync_tool_handler_result_is_returned(self) -> None:
def _sync(args: Any) -> dict[str, Any]:
return {"order_id": args["order_id"], "status": "shipped"}

tools = _build_agent_tools(
{"my-tool": {"description": "d"}}, {"my-tool": _sync}
)
out = await tools[0].on_invoke_tool(MagicMock(), '{"order_id": "A19"}')
assert out == str({"order_id": "A19", "status": "shipped"})

async def test_async_tool_handler_result_is_returned(self) -> None:
async def _async(args: Any) -> str:
return f"order {args['order_id']}"

tools = _build_agent_tools(
{"my-tool": {"description": "d"}}, {"my-tool": _async}
)
out = await tools[0].on_invoke_tool(MagicMock(), '{"order_id": "A19"}')
assert out == "order A19"

async def test_sync_tool_handler_returning_awaitable_is_awaited(self) -> None:
async def _inner() -> str:
return "done"

def _sync_wrapper(args: Any) -> Any:
return _inner()

tools = _build_agent_tools(
{"my-tool": {"description": "d"}}, {"my-tool": _sync_wrapper}
)
out = await tools[0].on_invoke_tool(MagicMock(), "{}")
assert out == "done"


# ---------------------------------------------------------------------------
# 搂1.4 Tool execution loop (pre-span-era; restored, not telemetry)
Expand Down
Loading