diff --git a/agents/utils/tool_util.py b/agents/utils/tool_util.py index 763fb749e..cbfeb61fe 100644 --- a/agents/utils/tool_util.py +++ b/agents/utils/tool_util.py @@ -11,12 +11,15 @@ async def _execute_single_tool( response = {"type": "tool_result", "tool_use_id": call.id} try: - # Execute the tool directly - result = await tool_dict[call.name].execute(**call.input) - response["content"] = str(result) + tool = tool_dict[call.name] except KeyError: response["content"] = f"Tool '{call.name}' not found" response["is_error"] = True + return response + + try: + result = await tool.execute(**call.input) + response["content"] = str(result) except Exception as e: response["content"] = f"Error executing tool: {str(e)}" response["is_error"] = True diff --git a/tests/agents/test_tool_keyerror_diagnostics.py b/tests/agents/test_tool_keyerror_diagnostics.py new file mode 100644 index 000000000..24a3e39ec --- /dev/null +++ b/tests/agents/test_tool_keyerror_diagnostics.py @@ -0,0 +1,29 @@ +import asyncio +from types import SimpleNamespace +from unittest.mock import AsyncMock + +from utils.tool_util import _execute_single_tool + + +def test_execution_keyerror_is_not_reported_as_missing_tool(): + tool = SimpleNamespace(execute=AsyncMock(side_effect=KeyError("required_field"))) + call = SimpleNamespace(id="call_1", name="example", input={}) + result = asyncio.run(_execute_single_tool(call, {"example": tool})) + assert result["is_error"] is True + assert result["content"] == "Error executing tool: 'required_field'" + assert result["tool_use_id"] == "call_1" + + +def test_missing_tool_keeps_lookup_error(): + call = SimpleNamespace(id="call_1", name="missing", input={}) + result = asyncio.run(_execute_single_tool(call, {})) + assert result["content"] == "Tool 'missing' not found" + assert result["is_error"] is True + + +def test_successful_tool_result(): + tool = SimpleNamespace(execute=AsyncMock(return_value="done")) + call = SimpleNamespace(id="call_1", name="example", input={"value": 1}) + result = asyncio.run(_execute_single_tool(call, {"example": tool})) + assert result == {"type": "tool_result", "tool_use_id": "call_1", "content": "done"} + tool.execute.assert_awaited_once_with(value=1) diff --git a/tests/conftest.py b/tests/conftest.py new file mode 100644 index 000000000..300d79c89 --- /dev/null +++ b/tests/conftest.py @@ -0,0 +1,4 @@ +import sys +from pathlib import Path + +sys.path.insert(0, str(Path(__file__).parent.parent / "agents"))