|
4 | 4 | from openai.types.responses import ResponseCustomToolCall |
5 | 5 |
|
6 | 6 | from agents import Agent, CustomTool, RunConfig, RunContextWrapper |
7 | | -from agents.items import ToolCallOutputItem |
| 7 | +from agents.items import ToolApprovalItem, ToolCallOutputItem |
8 | 8 | from agents.lifecycle import RunHooks |
9 | 9 | from agents.run_internal.run_steps import ToolRunCustom |
10 | 10 | from agents.run_internal.tool_actions import CustomToolAction |
| 11 | +from agents.tool import CustomToolOnApprovalFunctionResult |
11 | 12 | from agents.tool_context import ToolContext |
12 | 13 |
|
13 | 14 |
|
@@ -47,3 +48,47 @@ async def invoke(ctx: ToolContext[Any], raw_input: str) -> str: |
47 | 48 | "call_id": "call_custom", |
48 | 49 | "output": "HELLO", |
49 | 50 | } |
| 51 | + |
| 52 | + |
| 53 | +@pytest.mark.asyncio |
| 54 | +async def test_custom_tool_on_approval_callback_auto_rejects_with_reason() -> None: |
| 55 | + async def invoke(_ctx: ToolContext[Any], _raw_input: str) -> str: |
| 56 | + raise AssertionError("rejected custom tool should not execute") |
| 57 | + |
| 58 | + async def on_approval( |
| 59 | + _context: RunContextWrapper[Any], _approval_item: ToolApprovalItem |
| 60 | + ) -> CustomToolOnApprovalFunctionResult: |
| 61 | + return {"approve": False, "reason": "Not allowed"} |
| 62 | + |
| 63 | + tool = CustomTool( |
| 64 | + name="raw_editor", |
| 65 | + description="Edit raw text.", |
| 66 | + on_invoke_tool=invoke, |
| 67 | + format={"type": "text"}, |
| 68 | + needs_approval=True, |
| 69 | + on_approval=on_approval, |
| 70 | + ) |
| 71 | + agent = Agent(name="custom-agent", tools=[tool]) |
| 72 | + tool_call = ResponseCustomToolCall( |
| 73 | + type="custom_tool_call", |
| 74 | + name="raw_editor", |
| 75 | + call_id="call_custom", |
| 76 | + input="hello", |
| 77 | + ) |
| 78 | + |
| 79 | + result = await CustomToolAction.execute( |
| 80 | + agent=agent, |
| 81 | + call=ToolRunCustom(tool_call=tool_call, custom_tool=tool), |
| 82 | + hooks=RunHooks[Any](), |
| 83 | + context_wrapper=RunContextWrapper(context=None), |
| 84 | + config=RunConfig(), |
| 85 | + ) |
| 86 | + |
| 87 | + assert isinstance(result, ToolCallOutputItem) |
| 88 | + assert result.output == "Not allowed" |
| 89 | + raw_item = cast(dict[str, Any], result.raw_item) |
| 90 | + assert raw_item == { |
| 91 | + "type": "custom_tool_call_output", |
| 92 | + "call_id": "call_custom", |
| 93 | + "output": "Not allowed", |
| 94 | + } |
0 commit comments