Skip to content
Open
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
15 changes: 13 additions & 2 deletions src/agents/result.py
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,7 @@
InputGuardrailTripwireTriggered,
MaxTurnsExceeded,
RunErrorDetails,
UserError,
_await_data_redacted_error_boundary,
_detach_data_redacted_error_traceback,
_is_error_data_redacted,
Expand Down Expand Up @@ -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)

Expand Down
9 changes: 9 additions & 0 deletions tests/test_result_cast.py
Original file line number Diff line number Diff line change
Expand Up @@ -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")
Expand Down