diff --git a/python/packages/core/agent_framework/_workflows/_events.py b/python/packages/core/agent_framework/_workflows/_events.py index d59dc3b1a82..33b95448019 100644 --- a/python/packages/core/agent_framework/_workflows/_events.py +++ b/python/packages/core/agent_framework/_workflows/_events.py @@ -11,6 +11,7 @@ from contextvars import ContextVar from dataclasses import dataclass from enum import Enum +from types import UnionType from typing import Any, Generic, Literal, cast from ._typing_utils import deserialize_type, serialize_type @@ -236,7 +237,7 @@ def __init__( request_id: str | None = None, source_executor_id: str | None = None, request_type: builtins.type[Any] | None = None, - response_type: builtins.type[Any] | None = None, + response_type: builtins.type[Any] | UnionType | None = None, # SUPERSTEP event fields iteration: int | None = None, ) -> None: @@ -324,7 +325,7 @@ def request_info( request_id: str, source_executor_id: str, request_data: DataT, - response_type: builtins.type[Any], + response_type: builtins.type[Any] | UnionType, ) -> WorkflowEvent[DataT]: """Create a 'request_info' event when an executor requests external information.""" return cls( @@ -416,11 +417,11 @@ def request_type(self) -> builtins.type[Any]: return self._request_type @property - def response_type(self) -> builtins.type[Any]: + def response_type(self) -> builtins.type[Any] | UnionType: """Get response_type for request_info events. Returns: - The response data type as a non-None type object. + The response type as a non-None type object (possibly a union, e.g. ``int | str``). Raises: RuntimeError: If called on an event that is not a request_info event, diff --git a/python/packages/core/agent_framework/_workflows/_functional.py b/python/packages/core/agent_framework/_workflows/_functional.py index 5bf49d7c76c..b8a08952d36 100644 --- a/python/packages/core/agent_framework/_workflows/_functional.py +++ b/python/packages/core/agent_framework/_workflows/_functional.py @@ -51,7 +51,7 @@ from collections.abc import AsyncIterable, Awaitable, Callable, Iterable, Mapping, Sequence from contextvars import Context, ContextVar from copy import deepcopy -from types import CodeType +from types import CodeType, UnionType from typing import Any, Generic, Literal, TypeVar, cast, overload from .._agents import BaseAgent @@ -562,7 +562,7 @@ class WorkflowInterrupted(asyncio.CancelledError): tasks. User code with ``except Exception:`` handlers does not intercept it. """ - def __init__(self, request_id: str, request_data: Any, response_type: type) -> None: + def __init__(self, request_id: str, request_data: Any, response_type: type | UnionType) -> None: self.request_id = request_id self.request_data = request_data self.response_type = response_type @@ -748,7 +748,7 @@ def __init__( async def request_info( self, request_data: Any, - response_type: type, + response_type: type | UnionType, *, request_id: str | None = None, ) -> Any: diff --git a/python/packages/core/agent_framework/_workflows/_request_info_mixin.py b/python/packages/core/agent_framework/_workflows/_request_info_mixin.py index 47a8bd1a8cf..9404f83a12e 100644 --- a/python/packages/core/agent_framework/_workflows/_request_info_mixin.py +++ b/python/packages/core/agent_framework/_workflows/_request_info_mixin.py @@ -30,7 +30,9 @@ class RequestInfoMixin: """Mixin providing common functionality for request info handling.""" - def is_request_supported(self, request_type: builtin_type[Any], response_type: builtin_type[Any]) -> bool: + def is_request_supported( + self, request_type: builtin_type[Any], response_type: builtin_type[Any] | UnionType + ) -> bool: """Check if the executor supports request of the given type and handling a response of the given type. Args: diff --git a/python/packages/core/agent_framework/_workflows/_runner_context.py b/python/packages/core/agent_framework/_workflows/_runner_context.py index edbbfea50c9..205d3bd9538 100644 --- a/python/packages/core/agent_framework/_workflows/_runner_context.py +++ b/python/packages/core/agent_framework/_workflows/_runner_context.py @@ -585,9 +585,17 @@ async def send_request_info_response(self, request_id: str, response: Any) -> No # Validate response type if specified if event.response_type and not is_instance_of(response, event.response_type): + # response_type may be a union/generic (e.g. int | str), which has no usable + # __name__ on Python 3.10/3.11 (AttributeError) and only yields "Union" on 3.12+. + # Use the readable repr for anything that isn't a plain class. + expected = ( + event.response_type.__name__ + if isinstance(event.response_type, type) + else str(event.response_type) + ) raise TypeError( f"Response type mismatch for request_id {request_id}: " - f"expected {event.response_type.__name__}, got {type(response).__name__}" + f"expected {expected}, got {type(response).__name__}" ) source_executor_id = event.source_executor_id diff --git a/python/packages/core/agent_framework/_workflows/_workflow.py b/python/packages/core/agent_framework/_workflows/_workflow.py index cd566778484..053a7df8095 100644 --- a/python/packages/core/agent_framework/_workflows/_workflow.py +++ b/python/packages/core/agent_framework/_workflows/_workflow.py @@ -65,7 +65,7 @@ _MISSING: Any = object() -def _coerce_request_info_response(value: Any, response_type: type, request_id: str) -> Any: +def _coerce_request_info_response(value: Any, response_type: type | types.UnionType, request_id: str) -> Any: """Convert and validate a response supplied for a pending request.""" if response_type is Content and isinstance(value, str): value = Content.from_text(text=value) diff --git a/python/packages/core/agent_framework/_workflows/_workflow_context.py b/python/packages/core/agent_framework/_workflows/_workflow_context.py index 967b1ab789e..9fa52ed31d4 100644 --- a/python/packages/core/agent_framework/_workflows/_workflow_context.py +++ b/python/packages/core/agent_framework/_workflows/_workflow_context.py @@ -401,7 +401,9 @@ async def add_event(self, event: WorkflowEvent[Any]) -> None: return await self._runner_context.add_event(event) - async def request_info(self, request_data: object, response_type: type, *, request_id: str | None = None) -> None: + async def request_info( + self, request_data: object, response_type: type | UnionType, *, request_id: str | None = None + ) -> None: """Request information from outside of the workflow. Calling this method will cause the workflow to emit a request_info event (type='request_info'), carrying the @@ -419,9 +421,11 @@ async def request_info(self, request_data: object, response_type: type, *, reque """ request_type: type = type(request_data) if not self._executor.is_request_supported(request_type, response_type): + # A union response_type (e.g. int | str) has no __name__; show its repr. + response_type_name = response_type.__name__ if isinstance(response_type, type) else str(response_type) logger.warning( f"Executor '{self._executor_id}' requested info of type {request_type.__name__} " - f"with expected response type {response_type.__name__}, but no matching " + f"with expected response type {response_type_name}, but no matching " "response handler is defined. The request will not be ignored but responses will " "not be processed. Please define a response handler using the @response_handler decorator." ) diff --git a/python/packages/core/tests/workflow/test_request_info_event_rehydrate.py b/python/packages/core/tests/workflow/test_request_info_event_rehydrate.py index 449ee736ace..1d2db9c55a2 100644 --- a/python/packages/core/tests/workflow/test_request_info_event_rehydrate.py +++ b/python/packages/core/tests/workflow/test_request_info_event_rehydrate.py @@ -559,3 +559,24 @@ async def test_apply_checkpoint_preserves_streaming_flag() -> None: await target.apply_checkpoint(checkpoint) assert target.is_streaming() is True + + +async def test_send_request_info_response_union_type_mismatch_message() -> None: + """A union response_type must produce a readable TypeError, not crash on __name__. + + ``types.UnionType`` (e.g. ``int | str``) has no ``__name__`` on Python 3.10/3.11 + (AttributeError) and only yields the unhelpful ``"Union"`` on 3.12+. The mismatch + message should name the union itself. + """ + event = WorkflowEvent.request_info( + request_id="union-req", + source_executor_id="gateway", + request_data=MockRequest(), + response_type=int | str, + ) + + runner_context = InProcRunnerContext(InMemoryCheckpointStorage()) + await runner_context.add_request_info_event(event) + + with pytest.raises(TypeError, match=r"expected int \| str, got float"): + await runner_context.send_request_info_response("union-req", 3.14)