|
| 1 | +from __future__ import annotations |
| 2 | + |
| 3 | +import asyncio |
| 4 | +import json |
| 5 | +import logging |
| 6 | +from typing import Any, Literal |
| 7 | + |
| 8 | +import pytest |
| 9 | + |
| 10 | +import agents._debug as _debug |
| 11 | +from agents import Agent, RunConfig, RunContextWrapper, Runner, UserError |
| 12 | +from agents.decorators import tool |
| 13 | +from agents.testing import ScriptedModel |
| 14 | +from agents.tool import default_tool_error_function |
| 15 | + |
| 16 | +from .test_responses import get_function_tool_call, get_text_message |
| 17 | +from .testing_processor import SPAN_PROCESSOR_TESTING |
| 18 | + |
| 19 | +SENTINEL = "synthetic-private-tool-detail" |
| 20 | +GENERIC_ERROR = "An error occurred while running the tool. Please try again." |
| 21 | + |
| 22 | + |
| 23 | +@pytest.mark.asyncio |
| 24 | +@pytest.mark.parametrize("streamed", [False, True]) |
| 25 | +@pytest.mark.parametrize("sensitive_tracing", [False, True]) |
| 26 | +@pytest.mark.parametrize("failure", ["sync", "async", "cancel"]) |
| 27 | +async def test_default_failure_keeps_exception_out_of_model_history_and_traces( |
| 28 | + streamed: bool, |
| 29 | + sensitive_tracing: bool, |
| 30 | + failure: Literal["sync", "async", "cancel"], |
| 31 | + caplog: pytest.LogCaptureFixture, |
| 32 | +) -> None: |
| 33 | + def raise_error() -> str: |
| 34 | + try: |
| 35 | + raise RuntimeError(f"cause-{SENTINEL}") |
| 36 | + except RuntimeError as cause: |
| 37 | + error = ValueError(SENTINEL) |
| 38 | + if hasattr(error, "add_note"): |
| 39 | + error.add_note(f"note-{SENTINEL}") |
| 40 | + raise error from cause |
| 41 | + |
| 42 | + async def raise_async_error() -> str: |
| 43 | + if failure == "cancel": |
| 44 | + raise asyncio.CancelledError(SENTINEL) |
| 45 | + return raise_error() |
| 46 | + |
| 47 | + failing_tool = tool(raise_error if failure == "sync" else raise_async_error) |
| 48 | + model = ScriptedModel( |
| 49 | + [ |
| 50 | + [get_function_tool_call(failing_tool.name, "{}", call_id="failure-call")], |
| 51 | + [get_text_message("recovered")], |
| 52 | + ] |
| 53 | + ) |
| 54 | + agent = Agent(name="test", model=model, tools=[failing_tool]) |
| 55 | + config = RunConfig(trace_include_sensitive_data=sensitive_tracing) |
| 56 | + with caplog.at_level(logging.DEBUG, logger="openai.agents"): |
| 57 | + if streamed: |
| 58 | + result = Runner.run_streamed(agent, "start", run_config=config) |
| 59 | + async for _ in result.stream_events(): |
| 60 | + pass |
| 61 | + else: |
| 62 | + result = await Runner.run(agent, "start", run_config=config) |
| 63 | + |
| 64 | + assert result.final_output == "recovered" |
| 65 | + next_input = model.calls[-1].input |
| 66 | + assert isinstance(next_input, list) |
| 67 | + outputs = [item for item in next_input if item.get("type") == "function_call_output"] |
| 68 | + assert len(outputs) == 1 |
| 69 | + assert outputs[0]["output"] == GENERIC_ERROR |
| 70 | + assert SENTINEL not in json.dumps(next_input) |
| 71 | + assert SENTINEL not in json.dumps(result.to_input_list()) |
| 72 | + spans = [span.export() for span in SPAN_PROCESSOR_TESTING.get_ordered_spans()] |
| 73 | + assert spans |
| 74 | + assert SENTINEL not in json.dumps(spans) |
| 75 | + for record in caplog.records: |
| 76 | + assert SENTINEL not in repr(record.__dict__) |
| 77 | + assert record.exc_info is None |
| 78 | + assert record.exc_text is None |
| 79 | + assert SENTINEL not in logging.Formatter().format(record) |
| 80 | + |
| 81 | + |
| 82 | +@pytest.mark.asyncio |
| 83 | +@pytest.mark.parametrize("policy", ["custom", "propagate", "explicit-default"]) |
| 84 | +async def test_explicit_failure_policies_remain_available( |
| 85 | + policy: Literal["custom", "propagate", "explicit-default"], |
| 86 | +) -> None: |
| 87 | + received: list[Exception] = [] |
| 88 | + |
| 89 | + def custom_error(context: RunContextWrapper[Any], error: Exception) -> str: |
| 90 | + received.append(error) |
| 91 | + return "Application-approved feedback" |
| 92 | + |
| 93 | + @tool( |
| 94 | + failure_error_function=( |
| 95 | + custom_error |
| 96 | + if policy == "custom" |
| 97 | + else default_tool_error_function |
| 98 | + if policy == "explicit-default" |
| 99 | + else None |
| 100 | + ) |
| 101 | + ) |
| 102 | + async def failing_tool() -> str: |
| 103 | + raise ValueError(SENTINEL) |
| 104 | + |
| 105 | + model = ScriptedModel( |
| 106 | + [ |
| 107 | + [get_function_tool_call("failing_tool", "{}")], |
| 108 | + [get_text_message("recovered")], |
| 109 | + ] |
| 110 | + ) |
| 111 | + agent = Agent(name="test", model=model, tools=[failing_tool]) |
| 112 | + if policy == "propagate": |
| 113 | + with pytest.raises(UserError, match=SENTINEL) as exc_info: |
| 114 | + await Runner.run(agent, "start") |
| 115 | + assert isinstance(exc_info.value.__cause__, ValueError) |
| 116 | + return |
| 117 | + |
| 118 | + result = await Runner.run(agent, "start") |
| 119 | + assert result.final_output == "recovered" |
| 120 | + next_input = model.calls[-1].input |
| 121 | + assert isinstance(next_input, list) |
| 122 | + output = next(item for item in next_input if item.get("type") == "function_call_output") |
| 123 | + if policy == "custom": |
| 124 | + assert output["output"] == "Application-approved feedback" |
| 125 | + assert len(received) == 1 |
| 126 | + assert str(received[0]) == SENTINEL |
| 127 | + else: |
| 128 | + assert output["output"] == GENERIC_ERROR |
| 129 | + spans = [span.export() for span in SPAN_PROCESSOR_TESTING.get_ordered_spans()] |
| 130 | + assert SENTINEL not in json.dumps(spans) |
| 131 | + |
| 132 | + |
| 133 | +@pytest.mark.asyncio |
| 134 | +async def test_default_failure_does_not_format_the_exception() -> None: |
| 135 | + class UnprintableError(Exception): |
| 136 | + def __str__(self) -> str: |
| 137 | + raise AssertionError("Exception text must not be inspected") |
| 138 | + |
| 139 | + @tool |
| 140 | + async def failing_tool() -> str: |
| 141 | + raise UnprintableError() |
| 142 | + |
| 143 | + model = ScriptedModel( |
| 144 | + [[get_function_tool_call("failing_tool", "{}")], [get_text_message("recovered")]] |
| 145 | + ) |
| 146 | + result = await Runner.run(Agent(name="test", model=model, tools=[failing_tool]), "start") |
| 147 | + assert result.final_output == "recovered" |
| 148 | + |
| 149 | + |
| 150 | +@pytest.mark.asyncio |
| 151 | +async def test_explicit_local_diagnostics_keep_exception_detail( |
| 152 | + monkeypatch: pytest.MonkeyPatch, caplog: pytest.LogCaptureFixture |
| 153 | +) -> None: |
| 154 | + monkeypatch.setattr(_debug, "DONT_LOG_TOOL_DATA", False) |
| 155 | + |
| 156 | + @tool |
| 157 | + async def failing_tool() -> str: |
| 158 | + raise ValueError(SENTINEL) |
| 159 | + |
| 160 | + model = ScriptedModel( |
| 161 | + [[get_function_tool_call("failing_tool", "{}")], [get_text_message("recovered")]] |
| 162 | + ) |
| 163 | + with caplog.at_level(logging.DEBUG, logger="openai.agents"): |
| 164 | + result = await Runner.run(Agent(name="test", model=model, tools=[failing_tool]), "start") |
| 165 | + assert result.final_output == "recovered" |
| 166 | + assert SENTINEL in caplog.text |
| 167 | + assert any(record.exc_info is not None for record in caplog.records) |
| 168 | + assert SENTINEL not in json.dumps(model.calls[-1].input) |
| 169 | + assert SENTINEL not in json.dumps( |
| 170 | + [span.export() for span in SPAN_PROCESSOR_TESTING.get_ordered_spans()] |
| 171 | + ) |
0 commit comments