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
9 changes: 5 additions & 4 deletions python/packages/core/agent_framework/_workflows/_events.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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:
Expand Down Expand Up @@ -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(
Expand Down Expand Up @@ -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,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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
Expand Down Expand Up @@ -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:
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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:
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand All @@ -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."
)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Comment thread
PratikDhanave marked this conversation as resolved.
Resolved
)

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)
Loading