|
| 1 | +from __future__ import annotations |
| 2 | + |
| 3 | +import inspect |
| 4 | +from typing import TYPE_CHECKING, Any, Callable, cast, overload |
| 5 | + |
| 6 | +from pydantic import TypeAdapter |
| 7 | +from typing_extensions import TypeVar |
| 8 | + |
| 9 | +from ..exceptions import ModelBehaviorError, UserError |
| 10 | +from ..handoffs import Handoff |
| 11 | +from ..run_context import RunContextWrapper, TContext |
| 12 | +from ..strict_schema import ensure_strict_json_schema |
| 13 | +from ..tracing.spans import SpanError |
| 14 | +from ..util import _error_tracing, _json |
| 15 | +from ..util._types import MaybeAwaitable |
| 16 | + |
| 17 | +if TYPE_CHECKING: |
| 18 | + from ..agent import AgentBase |
| 19 | + from . import RealtimeAgent |
| 20 | + |
| 21 | + |
| 22 | +# The handoff input type is the type of data passed when the agent is called via a handoff. |
| 23 | +THandoffInput = TypeVar("THandoffInput", default=Any) |
| 24 | + |
| 25 | +OnHandoffWithInput = Callable[[RunContextWrapper[Any], THandoffInput], Any] |
| 26 | +OnHandoffWithoutInput = Callable[[RunContextWrapper[Any]], Any] |
| 27 | + |
| 28 | + |
| 29 | +@overload |
| 30 | +def realtime_handoff( |
| 31 | + agent: RealtimeAgent[TContext], |
| 32 | + *, |
| 33 | + tool_name_override: str | None = None, |
| 34 | + tool_description_override: str | None = None, |
| 35 | + is_enabled: bool |
| 36 | + | Callable[[RunContextWrapper[Any], RealtimeAgent[Any]], MaybeAwaitable[bool]] = True, |
| 37 | +) -> Handoff[TContext, RealtimeAgent[TContext]]: ... |
| 38 | + |
| 39 | + |
| 40 | +@overload |
| 41 | +def realtime_handoff( |
| 42 | + agent: RealtimeAgent[TContext], |
| 43 | + *, |
| 44 | + on_handoff: OnHandoffWithInput[THandoffInput], |
| 45 | + input_type: type[THandoffInput], |
| 46 | + tool_description_override: str | None = None, |
| 47 | + tool_name_override: str | None = None, |
| 48 | + is_enabled: bool |
| 49 | + | Callable[[RunContextWrapper[Any], RealtimeAgent[Any]], MaybeAwaitable[bool]] = True, |
| 50 | +) -> Handoff[TContext, RealtimeAgent[TContext]]: ... |
| 51 | + |
| 52 | + |
| 53 | +@overload |
| 54 | +def realtime_handoff( |
| 55 | + agent: RealtimeAgent[TContext], |
| 56 | + *, |
| 57 | + on_handoff: OnHandoffWithoutInput, |
| 58 | + tool_description_override: str | None = None, |
| 59 | + tool_name_override: str | None = None, |
| 60 | + is_enabled: bool |
| 61 | + | Callable[[RunContextWrapper[Any], RealtimeAgent[Any]], MaybeAwaitable[bool]] = True, |
| 62 | +) -> Handoff[TContext, RealtimeAgent[TContext]]: ... |
| 63 | + |
| 64 | + |
| 65 | +def realtime_handoff( |
| 66 | + agent: RealtimeAgent[TContext], |
| 67 | + tool_name_override: str | None = None, |
| 68 | + tool_description_override: str | None = None, |
| 69 | + on_handoff: OnHandoffWithInput[THandoffInput] | OnHandoffWithoutInput | None = None, |
| 70 | + input_type: type[THandoffInput] | None = None, |
| 71 | + is_enabled: bool |
| 72 | + | Callable[[RunContextWrapper[Any], RealtimeAgent[Any]], MaybeAwaitable[bool]] = True, |
| 73 | +) -> Handoff[TContext, RealtimeAgent[TContext]]: |
| 74 | + """Create a handoff from a RealtimeAgent. |
| 75 | +
|
| 76 | + Args: |
| 77 | + agent: The RealtimeAgent to handoff to, or a function that returns a RealtimeAgent. |
| 78 | + tool_name_override: Optional override for the name of the tool that represents the handoff. |
| 79 | + tool_description_override: Optional override for the description of the tool that |
| 80 | + represents the handoff. |
| 81 | + on_handoff: A function that runs when the handoff is invoked. |
| 82 | + input_type: the type of the input to the handoff. If provided, the input will be validated |
| 83 | + against this type. Only relevant if you pass a function that takes an input. |
| 84 | + is_enabled: Whether the handoff is enabled. Can be a bool or a callable that takes the run |
| 85 | + context and agent and returns whether the handoff is enabled. Disabled handoffs are |
| 86 | + hidden from the LLM at runtime. |
| 87 | +
|
| 88 | + Note: input_filter is not supported for RealtimeAgent handoffs. |
| 89 | + """ |
| 90 | + assert (on_handoff and input_type) or not (on_handoff and input_type), ( |
| 91 | + "You must provide either both on_handoff and input_type, or neither" |
| 92 | + ) |
| 93 | + type_adapter: TypeAdapter[Any] | None |
| 94 | + if input_type is not None: |
| 95 | + assert callable(on_handoff), "on_handoff must be callable" |
| 96 | + sig = inspect.signature(on_handoff) |
| 97 | + if len(sig.parameters) != 2: |
| 98 | + raise UserError("on_handoff must take two arguments: context and input") |
| 99 | + |
| 100 | + type_adapter = TypeAdapter(input_type) |
| 101 | + input_json_schema = type_adapter.json_schema() |
| 102 | + else: |
| 103 | + type_adapter = None |
| 104 | + input_json_schema = {} |
| 105 | + if on_handoff is not None: |
| 106 | + sig = inspect.signature(on_handoff) |
| 107 | + if len(sig.parameters) != 1: |
| 108 | + raise UserError("on_handoff must take one argument: context") |
| 109 | + |
| 110 | + async def _invoke_handoff( |
| 111 | + ctx: RunContextWrapper[Any], input_json: str | None = None |
| 112 | + ) -> RealtimeAgent[TContext]: |
| 113 | + if input_type is not None and type_adapter is not None: |
| 114 | + if input_json is None: |
| 115 | + _error_tracing.attach_error_to_current_span( |
| 116 | + SpanError( |
| 117 | + message="Handoff function expected non-null input, but got None", |
| 118 | + data={"details": "input_json is None"}, |
| 119 | + ) |
| 120 | + ) |
| 121 | + raise ModelBehaviorError("Handoff function expected non-null input, but got None") |
| 122 | + |
| 123 | + validated_input = _json.validate_json( |
| 124 | + json_str=input_json, |
| 125 | + type_adapter=type_adapter, |
| 126 | + partial=False, |
| 127 | + ) |
| 128 | + input_func = cast(OnHandoffWithInput[THandoffInput], on_handoff) |
| 129 | + if inspect.iscoroutinefunction(input_func): |
| 130 | + await input_func(ctx, validated_input) |
| 131 | + else: |
| 132 | + input_func(ctx, validated_input) |
| 133 | + elif on_handoff is not None: |
| 134 | + no_input_func = cast(OnHandoffWithoutInput, on_handoff) |
| 135 | + if inspect.iscoroutinefunction(no_input_func): |
| 136 | + await no_input_func(ctx) |
| 137 | + else: |
| 138 | + no_input_func(ctx) |
| 139 | + |
| 140 | + return agent |
| 141 | + |
| 142 | + tool_name = tool_name_override or Handoff.default_tool_name(agent) |
| 143 | + tool_description = tool_description_override or Handoff.default_tool_description(agent) |
| 144 | + |
| 145 | + # Always ensure the input JSON schema is in strict mode |
| 146 | + # If there is a need, we can make this configurable in the future |
| 147 | + input_json_schema = ensure_strict_json_schema(input_json_schema) |
| 148 | + |
| 149 | + async def _is_enabled(ctx: RunContextWrapper[Any], agent_base: AgentBase[Any]) -> bool: |
| 150 | + assert callable(is_enabled), "is_enabled must be non-null here" |
| 151 | + assert isinstance(agent_base, RealtimeAgent), "Can't handoff to a non-RealtimeAgent" |
| 152 | + result = is_enabled(ctx, agent_base) |
| 153 | + if inspect.isawaitable(result): |
| 154 | + return await result |
| 155 | + return result |
| 156 | + |
| 157 | + return Handoff( |
| 158 | + tool_name=tool_name, |
| 159 | + tool_description=tool_description, |
| 160 | + input_json_schema=input_json_schema, |
| 161 | + on_invoke_handoff=_invoke_handoff, |
| 162 | + input_filter=None, # Not supported for RealtimeAgent handoffs |
| 163 | + agent_name=agent.name, |
| 164 | + is_enabled=_is_enabled if callable(is_enabled) else is_enabled, |
| 165 | + ) |
0 commit comments