From 0771e37d4025b118d4e0fa1c942f3a8d3ff48b54 Mon Sep 17 00:00:00 2001 From: Showmick Das Date: Mon, 31 Aug 2026 02:48:17 -0400 Subject: [PATCH] fix: handle generic type aliases in final_output_as --- src/agents/result.py | 15 +++++++++++++-- tests/test_result_cast.py | 9 +++++++++ 2 files changed, 22 insertions(+), 2 deletions(-) diff --git a/src/agents/result.py b/src/agents/result.py index 0ceb0d7187..d14decf2d5 100644 --- a/src/agents/result.py +++ b/src/agents/result.py @@ -18,6 +18,7 @@ InputGuardrailTripwireTriggered, MaxTurnsExceeded, RunErrorDetails, + UserError, _await_data_redacted_error_boundary, _detach_data_redacted_error_traceback, _is_error_data_redacted, @@ -424,8 +425,18 @@ def final_output_as(self, cls: type[T], raise_if_incorrect_type: bool = False) - Returns: The final output casted to the given type. """ - if raise_if_incorrect_type and not isinstance(self.final_output, cls): - raise TypeError(f"Final output is not of type {cls.__name__}") + if raise_if_incorrect_type: + try: + is_correct = isinstance(self.final_output, cls) + except TypeError: + type_name = getattr(cls, "__name__", repr(cls)) + raise UserError( + f"final_output_as cannot validate generic type {type_name}. " + "Use raise_if_incorrect_type=False for generic types." + ) from None + if not is_correct: + type_name = getattr(cls, "__name__", repr(cls)) + raise TypeError(f"Final output is not of type {type_name}") return cast(T, self.final_output) diff --git a/tests/test_result_cast.py b/tests/test_result_cast.py index 61631fcea0..80b6aed4fd 100644 --- a/tests/test_result_cast.py +++ b/tests/test_result_cast.py @@ -103,6 +103,15 @@ def test_bad_cast_with_param_raises(): result.final_output_as(int, raise_if_incorrect_type=True) +def test_bad_cast_with_generic_type_raises_user_error(): + """Bad casts with generic types (like list[str]) should raise UserError.""" + from agents.exceptions import UserError + + result = create_run_result(["test"]) + with pytest.raises(UserError, match="Use raise_if_incorrect_type=False for generic types"): + result.final_output_as(list[str], raise_if_incorrect_type=True) + + def test_run_result_release_agents_breaks_strong_refs() -> None: message = _create_message("hello") agent = Agent(name="leak-test-agent")