From 5b20dab1473c40a88ad4cc4209cb6d1c66f84d3d Mon Sep 17 00:00:00 2001 From: Mark Stuart Date: Fri, 20 Nov 2026 22:08:50 -0800 Subject: [PATCH 1/4] feat: add typed Decisions and specialist handoffs --- examples/decisions/README.md | 75 ++- examples/decisions/compare_handoffs.py | 77 +++ src/agents/_run_state_agent_identity.py | 49 +- src/agents/decisions.py | 467 +++++++++++++++++ src/agents/run_state.py | 40 +- tests/test_decisions.py | 649 ++++++++++++++++++++++++ 6 files changed, 1354 insertions(+), 3 deletions(-) create mode 100644 examples/decisions/compare_handoffs.py create mode 100644 src/agents/decisions.py create mode 100644 tests/test_decisions.py diff --git a/examples/decisions/README.md b/examples/decisions/README.md index a19c08ea8e..ffb3017651 100644 --- a/examples/decisions/README.md +++ b/examples/decisions/README.md @@ -1,4 +1,77 @@ -# Decisions API recipes +# Decisions in the Python Agents SDK + +## Let the primary model request a specialist + +Use `agents.decisions.decision_handoff` when the primary model should decide **when** to transfer. Decisions chooses **which** specialist from the labels your application currently allows. If the primary model answers directly, there is no Decisions request. + +[Run the offline comparison](compare_handoffs.py) from the repository root without credentials. + +```bash +uv run python examples/decisions/compare_handoffs.py +``` + +The example compares direct and Decisions handoffs on the same three labeled inputs. Both paths use the same scripted specialists and settings. Route accuracy measures the fraction routed correctly. Task completion measures the fraction with the expected final answer. Each row also reports total elapsed time inside Runner and request counts. Estimated cost is unknown (`null`). The predictions include deliberate mistakes. These fixtures check the workflow and scoring. They provide no evidence of live accuracy, latency or cost. + +For live requests, pass a caller-owned `AsyncOpenAI` client and a supported Decisions model. This function makes paid calls when invoked. + +```python +from openai import AsyncOpenAI + +from agents import Agent, Runner +from agents.decisions import OpenAIDecisions, decision_handoff + + +async def answer(client: AsyncOpenAI, decisions_model: str, text: str): + source = Agent(name="Triage", instructions="Transfer requests that need a specialist.") + targets = { + "billing": Agent(name="Billing", instructions="Help with invoices."), + "account": Agent(name="Account", instructions="Help with account settings."), + } + source.handoffs.append( + decision_handoff( + source, + provider=OpenAIDecisions(client, model=decisions_model), + question="Which team can help?", + targets=targets, + timeout=10, + ) + ) + return await Runner.run(source, text) +``` + +- **Evidence.** The model supplies one nonblank `input` string of up to 8,192 UTF-8 bytes. The provider receives that string, the question and the allowed choices. The model can copy sensitive text into the string. The specialist receives the usual handoff history. Set the handoff's `input_filter` when the specialist needs less context. +- **Authority.** The handoff belongs to the source agent. Create a new handoff for a clone. Labels bind to the original agent objects and names. Removing, replacing or renaming a target makes it unavailable. Use a synchronous, side-effect-free `is_available(ctx, label)` to check application permissions. The handoff checks the selected route again before transfer. Runner keeps the run context, call IDs, tool restrictions and approvals. +- **Failures.** Refusals and invalid answers raise `DecisionError`. Revoked routes raise `ValueError`. The provider deadline defaults to 30 seconds. On timeout or cancellation, the SDK waits for provider cleanup and discards late answers. Timeout raises `asyncio.TimeoutError`. If the provider cancels its own request, the SDK raises `RuntimeError`. Transport errors propagate. There is no automatic fallback or retry. To return an error to the primary model, explicitly set the handoff's `failure_error_function`. For immediate stream cancellation, call `result.cancel()` and drain `result.stream_events()`. +- **Scope.** Both Runner modes support specialist selection. Decisions cannot invoke a tool, grant permissions or tell the source to continue. Realtime and dynamic agent factories are outside this integration. +- **One available label.** The handoff still asks the provider to choose. `OpenAIDecisions` requires at least two choices and raises `ValueError` before sending a request. Use a provider that accepts one choice if your roster can narrow to one. The SDK never transfers by default. + +### Resume a specialist after a tool approval + +The handoff registers its targets for `RunState` automatically. Save `result.to_state().to_string()` when the run pauses. Protect the snapshot from edits. Restore only trusted snapshots with the same source, handoff names, labels and specialists. When rebuilding the graph, you authorize the agents, tools and permission checks you supply under those names. + +If you use `is_available`, pass fresh application permissions through `context_override`. The callback should read them from `ctx.context`. Saved permissions alone cannot authorize the active specialist. For a nested `Agent.as_tool()` run, pass the override when restoring the outer run. The nested specialist shares the application context and keeps its own approvals. + +```python +from agents import RunState + +state = await RunState.from_string(source, saved, context_override=current_context) +``` + +Restore checks each Decisions label bound to the active specialist. All must still be available, even after a direct handoff to the same agent. Use separate agents if routes need independent permissions. A missing binding or denied label stops restore. Decisions does not run again. Review each pending tool call in `state.get_interruptions()` before calling `state.approve(item)` or `state.reject(item)`. Resume with `await Runner.run(source, state)`. + +If a handoff fails during approval resume, retain the updated `RunState`. It contains completed tool results that the session may lack. Keep the graph and permissions current through execution. When resuming an in-memory state directly, recheck access yourself. The restore checks run only when loading serialized state. + +## Ask for a value without transferring + +Call `await decide(question, provider=provider, input=evidence)` from `agents.decisions`. Supply nonempty text or a nonempty sequence of finite JSON objects. The call copies them before the first await. It never reads run history. The default result is a boolean. Use `choices` for distinct finite JSON scalars or `output_type` for a Pydantic-compatible type. The SDK validates the returned JSON against the schema and the application parser. + +A trusted `DecisionProvider` implements `async get_decision(request)` and returns `DecisionResult(value, request_id, model, usage)`. Read the validated answer from `result.value`. Both the result and `DecisionError` expose observed metadata. Missing metadata is `None`. Error reasons are `refusal` and `invalid_response`. The handoff adds reported usage to the run. Standalone calls leave accounting to the application. + +`OpenAIDecisions` requires `openai>=3.26.0` with the Decisions resource. It uses a predicate threshold of 0.5 or 2 to 255 string or boolean choices. It rejects other schemas before inference, including a roster narrowed to one label. Use a custom provider for other contracts. The adapter disables client retries and leaves the client open. + +In an async callback, use `async with decision_scope(ctx)` and pass `owner=ctx` to `decide`. Only the exact owner in that live scope can use the bound call. Scope exit cancels and joins outstanding provider work. The application remains responsible for awaiting its own child tasks. + +## Direct client recipes These examples compose the native `AsyncOpenAI.decisions.create()` client with existing Agents SDK APIs. They do not add a Decisions model adapter or a generic risk policy. diff --git a/examples/decisions/compare_handoffs.py b/examples/decisions/compare_handoffs.py new file mode 100644 index 0000000000..4af60fb564 --- /dev/null +++ b/examples/decisions/compare_handoffs.py @@ -0,0 +1,77 @@ +"""Compare two scripted handoff paths on labeled fixtures without making API calls.""" + +import asyncio +import json +from time import perf_counter + +from agents import Agent, RunConfig, Runner, handoff +from agents.decisions import DecisionRequest, DecisionResult, decision_handoff +from agents.testing import ScriptedModel, assistant_message, function_call + +# Each row records the input, expected route, expected answer and two scripted predictions. +CASES = ( + ("Where can I reset my password?", "account", "Open settings.", "account", "account"), + ("Where is my invoice?", "billing", "Open invoices.", "account", "billing"), + ("How do I change my password?", "account", "Open settings.", "account", "billing"), +) + + +class RecordedDecisions: + def __init__(self, routes: dict[str, str]): + self.routes = routes + self.requests = 0 + + async def get_decision(self, request: DecisionRequest) -> DecisionResult[str]: + assert isinstance(request.input, str) + self.requests += 1 + return DecisionResult(self.routes[request.input]) + + +async def compare() -> None: + for path in ("primary", "decisions"): + provider = RecordedDecisions({text: predicted for text, _, _, _, predicted in CASES}) + correct = completed = requests = 0 + seconds = 0.0 + for text, label, expected, primary, _ in CASES: + targets = { + name: Agent[None](name=name, model=ScriptedModel([[assistant_message(answer)]])) + for name, answer in (("account", "Open settings."), ("billing", "Open invoices.")) + } + source = Agent[None](name="Triage") + if path == "primary": + source.handoffs.extend( + handoff(agent, tool_name_override=name) for name, agent in targets.items() + ) + call = function_call(primary, {}, call_id="transfer") + else: + route = decision_handoff( + source, provider=provider, question="Which team can help?", targets=targets + ) + source.handoffs.append(route) + call = function_call(route.tool_name, {"input": text}, call_id="transfer") + source.model = ScriptedModel([[call]]) + start = perf_counter() + result = await Runner.run(source, text, run_config=RunConfig(tracing_disabled=True)) + seconds += perf_counter() - start + correct += result.last_agent is targets[label] + completed += result.final_output == expected + requests += len(result.raw_responses) + print( + json.dumps( + { + "path": path, + "cases": len(CASES), + "route_accuracy": correct / len(CASES), + "task_completion": completed / len(CASES), + "elapsed_seconds": seconds, + "model_requests": requests, + "decision_requests": provider.requests, + "estimated_cost": None, + "fallback": None, + } + ) + ) + + +if __name__ == "__main__": + asyncio.run(compare()) diff --git a/src/agents/_run_state_agent_identity.py b/src/agents/_run_state_agent_identity.py index d4505959fa..80142fac64 100644 --- a/src/agents/_run_state_agent_identity.py +++ b/src/agents/_run_state_agent_identity.py @@ -4,10 +4,12 @@ import asyncio import dataclasses +import hashlib import json +import re import threading from collections import deque -from collections.abc import Iterator, Mapping, Sequence +from collections.abc import Callable, Iterator, Mapping, Sequence from pathlib import Path from typing import Any, cast @@ -15,6 +17,7 @@ from .agent import Agent from .handoffs import Handoff from .logger import logger +from .run_context import RunContextWrapper, TContext from .sandbox.capabilities.capability import Capability from .sandbox.session.base_sandbox_session import BaseSandboxSession from .tool import ( @@ -26,6 +29,23 @@ ShellTool, ) +_DECISION_PREFIX = "decision:" + + +def _is_decision_identity(value: object) -> bool: + return ( + isinstance(value, str) + and re.fullmatch(_DECISION_PREFIX + r"[0-9a-f]{64}", value) is not None + ) + + +class _DecisionHandoff(Handoff[TContext, Agent[TContext]]): + """Static graph edges and the live admission check owned by decision_handoff.""" + + _source: Agent[TContext] + _roster: Mapping[str, tuple[Agent[TContext], str]] + _can_restore: Callable[[RunContextWrapper[TContext] | None, str], bool] + def _iter_agent_graph(initial_agent: Agent[Any]) -> Iterator[Agent[Any]]: """Yield agents reachable from the starting agent in breadth-first order.""" @@ -41,6 +61,10 @@ def _iter_agent_graph(initial_agent: Agent[Any]) -> Iterator[Agent[Any]]: yield current for handoff_item in current.handoffs: + if isinstance(handoff_item, _DecisionHandoff): + if handoff_item._source is current: + queue.extend(agent for agent, _ in handoff_item._roster.values()) + continue handoff_agent: Any | None = None handoff_agent_name: str | None = None @@ -489,6 +513,16 @@ def _has_ambiguous_hook_identities(initial_agent: Agent[Any]) -> bool: ) +def _decision_edges( + agents: Mapping[str, Agent[Any]], +) -> Iterator[tuple[str, _DecisionHandoff[Any], str, Agent[Any]]]: + for key, source in agents.items(): + for route in source.handoffs: + if isinstance(route, _DecisionHandoff) and route._source is source: + for label, (target, _) in route._roster.items(): + yield key, route, label, target + + def _build_agent_identity_map(initial_agent: Agent[Any]) -> dict[str, Agent[Any]]: """Build a stable identity map that preserves duplicate agent names.""" ordered_agents = list(_iter_agent_graph(initial_agent)) @@ -532,6 +566,19 @@ def _build_agent_identity_map(initial_agent: Agent[Any]) -> dict[str, Agent[Any] agent_identity_map[candidate] = duplicate_agent next_index += 1 + # Keep ordinary identities stable. Bind specialist identities to their incoming + # selectors so another edge cannot silently replace a removed selector or label. + bindings: dict[int, list[tuple[str, str, str]]] = {} + for key, route, label, target in _decision_edges(agent_identity_map): + bindings.setdefault(id(target), []).append((key, route.tool_name, label)) + if bindings: + for key, target in list(agent_identity_map.items()): + if id(target) in bindings: + data = _stable_identity_text([key, sorted(bindings[id(target)])]) + identity = _DECISION_PREFIX + hashlib.sha256(data.encode()).hexdigest() + if identity in agent_identity_map: + raise ValueError("Conflicting specialist identity") + agent_identity_map[identity] = agent_identity_map.pop(key) return agent_identity_map diff --git a/src/agents/decisions.py b/src/agents/decisions.py new file mode 100644 index 0000000000..677922d9ae --- /dev/null +++ b/src/agents/decisions.py @@ -0,0 +1,467 @@ +"""Opt-in, explicit-input decisions and specialist handoffs for Runner.""" + +from __future__ import annotations + +import asyncio +import json +import math +from collections.abc import AsyncIterator, Callable, Coroutine, Mapping, Sequence +from contextlib import asynccontextmanager +from contextvars import ContextVar +from copy import deepcopy +from dataclasses import dataclass, field, replace +from typing import Any, Generic, Literal, Protocol, TypeVar, overload + +from openai import AsyncOpenAI +from openai.types.responses.response_usage import ResponseUsage +from pydantic import BaseModel, ConfigDict, Field, JsonValue, TypeAdapter + +from ._public_agent import get_public_agent +from ._run_state_agent_identity import _DecisionHandoff +from .agent import Agent +from .handoffs import Handoff +from .run_context import RunContextWrapper +from .usage import Usage, _response_usage_to_usage + +__all__ = [ + "DecisionError", + "DecisionProvider", + "DecisionRequest", + "DecisionResult", + "OpenAIDecisions", + "decide", + "decision_handoff", + "decision_scope", +] + +_Input = str | Sequence[dict[str, Any]] +_Scalar = str | bool | int | float | None +_S = TypeVar("_S", bound=_Scalar) +_T = TypeVar("_T") +_json: TypeAdapter[JsonValue] = TypeAdapter(JsonValue) + + +@dataclass(frozen=True) +class DecisionRequest: + """One question, explicit evidence and the JSON schema of the application value.""" + + question: str = field(repr=False) + input: _Input = field(repr=False) + output_schema: dict[str, Any] = field(repr=False) + + +@dataclass(frozen=True) +class DecisionResult(Generic[_T]): + """A value with observed metadata. Missing usage is unknown.""" + + value: _T = field(repr=False) + request_id: str | None = None + model: str | None = None + usage: Usage | None = None + + +class DecisionError(ValueError): + """A refused or invalid response. Only metadata is retained.""" + + def __init__( + self, + reason: Literal["refusal", "invalid_response"], + *, + request_id: str | None = None, + model: str | None = None, + usage: Usage | None = None, + ): + super().__init__("Decision refused" if reason == "refusal" else "Invalid decision response") + self.reason = reason + self.request_id = request_id + self.model = model + self.usage = usage + + +class DecisionProvider(Protocol): + """Trusted application code returning JSON or raising DecisionError on refusal.""" + + async def get_decision(self, request: DecisionRequest) -> DecisionResult[Any]: ... + + +@dataclass +class _Scope: + owner: object + loop: asyncio.AbstractEventLoop + live: bool = True + pending: dict[asyncio.Task[Any], bool] = field(default_factory=dict) + + def check(self, owner: object) -> None: + if ( + not self.live + or self.owner is not owner + or _current.get() is not self + or asyncio.get_running_loop() is not self.loop + ): + raise RuntimeError("Decision requires its exact live callback owner") + + async def cancel(self, tasks: Sequence[asyncio.Task[Any]]) -> None: + # A deadline and callback exit can overlap. Cancel each provider only once. + for task in tasks: + if not task.done() and not self.pending[task]: + self.pending[task] = True + task.cancel() + interrupted = False + while any(not task.done() for task in tasks): + try: + await asyncio.wait(tasks) + except asyncio.CancelledError: + interrupted = True + for task in tasks: + if not task.cancelled(): + task.exception() + if interrupted: + raise asyncio.CancelledError + + +_current: ContextVar[_Scope | None] = ContextVar("decision_scope", default=None) + + +@asynccontextmanager +async def decision_scope(owner: object) -> AsyncIterator[None]: + """Bind decisions to a callback owner. Exit revokes and joins outstanding requests.""" + if owner is None: + raise ValueError("A callback owner is required") + scope = _Scope(owner, asyncio.get_running_loop()) + token = _current.set(scope) + try: + yield + finally: + scope.live = False + _current.reset(token) + await scope.cancel(tuple(scope.pending)) + + +def _check_request(question: str, timeout: float) -> None: + if not isinstance(question, str) or not question.strip(): + raise ValueError("A nonblank question is required") + if not math.isfinite(timeout) or timeout <= 0: + raise ValueError("timeout must be finite and positive") + + +def _snapshot(value: Any) -> str: + return json.dumps(_json.validate_python(value, strict=True), allow_nan=False) + + +def _key(value: _Scalar) -> tuple[type, _Scalar]: + # JSON numbers compare by value, independently of booleans. + return (int if type(value) is float else type(value), value) + + +@overload +def decide( + question: str, + *, + provider: DecisionProvider, + input: _Input, + choices: Sequence[_S], + owner: object = None, + timeout: float = 30, +) -> Coroutine[Any, Any, DecisionResult[_S]]: ... + + +@overload +def decide( + question: str, + *, + provider: DecisionProvider, + input: _Input, + output_type: type[_T], + owner: object = None, + timeout: float = 30, +) -> Coroutine[Any, Any, DecisionResult[_T]]: ... + + +@overload +def decide( + question: str, + *, + provider: DecisionProvider, + input: _Input, + owner: object = None, + timeout: float = 30, +) -> Coroutine[Any, Any, DecisionResult[bool]]: ... + + +def decide( + question: str, + *, + provider: DecisionProvider, + input: _Input, + choices: Sequence[_Scalar] | None = None, + output_type: type[Any] | None = None, + owner: object = None, + timeout: float = 30, +) -> Coroutine[Any, Any, DecisionResult[Any]]: + """Capture explicit evidence now. Await once for a validated value and provider metadata. + + Inside decision_scope, pass the same owner. The timeout in seconds covers the + provider request. Caller cancellation waits for cooperative provider cleanup. + Independent cancellation of the provider request raises RuntimeError. + """ + scope = _current.get() + if scope is not None: + scope.check(owner) + elif owner is not None: + raise RuntimeError("Decision requires its exact live callback owner") + _check_request(question, timeout) + if input == "": + raise ValueError("Decision input is required") + if not isinstance(input, str): + if ( + not isinstance(input, Sequence) + or not input + or not all(isinstance(i, dict) for i in input) + ): + raise ValueError("Expected text or a nonempty sequence of JSON objects") + input = json.loads(_snapshot(list(input))) + if choices is not None: + if output_type is not None: + raise ValueError("choices and output_type are mutually exclusive") + if ( + not choices + or isinstance(choices, (str, bytes, bytearray)) + or not isinstance(choices, Sequence) + ): + raise ValueError("Expected a nonempty sequence of choices") + values = list(choices) + if any(type(v) not in (str, int, float, bool, type(None)) for v in values): + raise ValueError("Choices must be JSON scalars") + _snapshot(values) + admitted = {_key(v): v for v in values} + if len(admitted) != len(values): + raise ValueError("Choices must be distinct") + schema: dict[str, Any] = {"enum": values} + + def parse(text: str) -> Any: + return admitted[_key(json.loads(text))] + else: + from jsonschema import Draft202012Validator # type: ignore[import-untyped] + from referencing import Registry + + adapter: TypeAdapter[Any] = TypeAdapter(bool if output_type is None else output_type) + schema = adapter.json_schema() + Draft202012Validator.check_schema(schema) + validator = Draft202012Validator(schema, registry=Registry()) + + def parse(text: str) -> Any: + validator.validate(json.loads(text)) + return adapter.validate_json(text, strict=True) + + request = DecisionRequest(question, input, deepcopy(schema)) + + async def execute() -> DecisionResult[Any]: + if scope is not None: + scope.check(owner) + loop = asyncio.get_running_loop() + work = scope or _Scope(None, loop) + deadline = loop.time() + timeout + task = asyncio.create_task(provider.get_decision(request)) + work.pending[task] = False + try: + await asyncio.wait((task,), timeout=timeout) + if not work.live: + raise asyncio.CancelledError + if not task.done() or loop.time() >= deadline: + raise asyncio.TimeoutError("Decision timed out") + if task.cancelled(): + raise RuntimeError("Decision provider cancelled its request") + result = _validate(task.result(), parse) + finally: + try: + await work.cancel((task,)) + finally: + del work.pending[task] + del task + if isinstance(result, DecisionError): + raise result + return result + + return execute() + + +def _validate( + response: DecisionResult[Any], parse: Callable[[str], Any] +) -> DecisionResult[Any] | DecisionError: + if not isinstance(response, DecisionResult): + return DecisionError("invalid_response") + try: + return replace(response, value=parse(_snapshot(response.value))) + except Exception: + # Keep parser exceptions and raw values out of the raising frame. + return DecisionError( + "invalid_response", + request_id=response.request_id, + model=response.model, + usage=response.usage, + ) + + +class OpenAIDecisions: + """Ask a predicate or string/boolean choice with a caller-owned client and no retries.""" + + def __init__(self, client: AsyncOpenAI, *, model: str): + self._client = client + self._model = model + + async def get_decision(self, request: DecisionRequest) -> DecisionResult[Any]: + schema = request.output_schema + question: dict[str, Any] = {"instructions": request.question, "name": "decision"} + if schema == {"type": "boolean"}: + question["type"] = "predicate" + elif ( + set(schema) == {"enum"} + and 2 <= len(schema["enum"]) <= 255 + and all(type(value) in (bool, str) for value in schema["enum"]) + ): + question.update(type="choice", choices=[{"value": v} for v in schema["enum"]]) + else: + raise ValueError("Expected a predicate or 2 to 255 string or boolean choices") + resource = getattr(self._client.with_options(max_retries=0), "decisions", None) + if resource is None: + raise RuntimeError("The Decisions client requires openai>=3.26.0") + result = _read_answer( + await resource.with_raw_response.create( + model=self._model, input=request.input, questions=[question] + ), + question["type"], + ) + if isinstance(result, DecisionError): + raise result + return result + + +def _read_answer(raw: Any, kind: str) -> DecisionResult[Any] | DecisionError: + metadata: dict[str, Any] = {"request_id": raw.headers.get("x-request-id")} + try: + data = raw.http_response.json() + if isinstance(data.get("model"), str): + metadata["model"] = data["model"] + if data.get("usage") is not None: + usage = ResponseUsage.model_validate(data["usage"], strict=True, extra="ignore") + metadata["usage"] = _response_usage_to_usage(usage) + answers = data["answers"] + if isinstance(answers, list) and len(answers) == 1 and answers[0]["name"] == "decision": + answer = answers[0] + if answer["type"] == "refusal": + return DecisionError("refusal", **metadata) + if answer["type"] == kind: + if kind == "choice": + return DecisionResult(answer["choice"], **metadata) + probability = answer["probability"] + if type(probability) in (int, float) and 0 <= probability <= 1: + return DecisionResult(probability >= 0.5, **metadata) + except (ValueError, KeyError, AttributeError, TypeError, RecursionError): + pass + return DecisionError("invalid_response", **metadata) + + +class _RoutingInput(BaseModel): + model_config = ConfigDict(extra="forbid") + input: str = Field(min_length=1, max_length=8192) + + +def _routing_input(arguments: str) -> str: + try: + value = _RoutingInput.model_validate_json(arguments, strict=True).input + if value.strip() and len(value.encode()) <= 8192: + return value + except ValueError: + pass + raise ValueError("Expected nonblank routing input of at most 8192 UTF-8 bytes") + + +def decision_handoff( + source: Agent[_T], + *, + provider: DecisionProvider, + question: str, + targets: Mapping[str, Agent[_T]], + tool_name: str = "select_specialist", + tool_description: str = "Transfer to a specialist. Supply only evidence needed for routing.", + is_available: Callable[[RunContextWrapper[_T], str], bool] | None = None, + timeout: float = 30, +) -> Handoff[_T, Agent[_T]]: + """Build a handoff for source.handoffs. Decisions chooses a label on a model request. + + Labels bind to concrete agents at construction. Removing or replacing a target + revokes it. A synchronous is_available callback can further restrict each run. + Restoring a specialist from serialized RunState checks its incoming selectors. + Supply a fresh context_override if any of them uses is_available. + """ + _check_request(question, timeout) + if not tool_name.strip() or not targets: + raise ValueError("Expected a handoff name and targets") + if any( + not isinstance(k, str) or not k.strip() or not isinstance(v, Agent) + for k, v in targets.items() + ): + raise ValueError("Expected nonblank labels mapped to agents") + roster = {label: (agent, agent.name) for label, agent in targets.items()} + + def admitted(ctx: RunContextWrapper[_T] | None, label: str) -> bool: + agent, name = roster[label] + return ( + (is_available is None or (ctx is not None and is_available(ctx, label) is True)) + and targets.get(label) is agent + and agent.name == name + ) + + def enabled(ctx: RunContextWrapper[_T], agent: Any) -> bool: + return get_public_agent(agent) is source and any(admitted(ctx, label) for label in roster) + + def attached() -> bool: + return ( + route.tool_name == tool_name + and route.on_invoke_handoff is invoke + and route.is_enabled is enabled + and any(h is route for h in source.handoffs) + ) + + def authorized(ctx: RunContextWrapper[_T] | None, label: str) -> bool: + return admitted(ctx, label) and attached() + + async def invoke(ctx: RunContextWrapper[_T], arguments: str) -> Agent[_T]: + evidence = _routing_input(arguments) + choices = [label for label in roster if admitted(ctx, label)] + if not attached(): + raise ValueError("Decision handoff is unavailable") + if not choices: + raise ValueError("No specialist is available") + async with decision_scope(ctx): + try: + result = await decide( + question, + provider=provider, + input=evidence, + choices=choices, + owner=ctx, + timeout=timeout, + ) + except DecisionError as error: + if error.usage is not None: + ctx.usage.add(error.usage) + raise + if result.usage is not None: + ctx.usage.add(result.usage) + if not authorized(ctx, result.value): + raise ValueError("Selected specialist is unavailable") + return roster[result.value][0] + + route: _DecisionHandoff[_T] = _DecisionHandoff( + tool_name=tool_name, + tool_description=tool_description, + input_json_schema=_RoutingInput.model_json_schema(), + on_invoke_handoff=invoke, + agent_name=tool_name, + is_enabled=enabled, + ) + route._source = source + route._roster = roster + route._can_restore = authorized + return route diff --git a/src/agents/run_state.py b/src/agents/run_state.py index 20c8ce2755..b86a52b09c 100644 --- a/src/agents/run_state.py +++ b/src/agents/run_state.py @@ -42,9 +42,11 @@ _build_agent_identity_keys_by_id, _build_agent_identity_map, _build_agent_map, + _decision_edges, _get_ambiguous_agent_ids, _has_ambiguous_hook_identities, _has_legacy_hook_identity_ambiguity, + _is_decision_identity, _iter_agent_graph, ) from ._tool_identity import ( @@ -3209,11 +3211,28 @@ def _build_handoffs_map(current_agent: Agent[Any]) -> dict[str, Handoff[Any, Age return handoffs_map +def _has_pending_specialist(snapshot: Mapping[str, Any]) -> bool: + """Identify the interrupted branch even when its selector has been removed.""" + agent = snapshot.get("current_agent") + if isinstance(agent, Mapping) and _is_decision_identity(agent.get("identity")): + return True + response = snapshot.get("last_processed_response") + if not isinstance(response, Mapping): + return False + return any( + _has_pending_specialist(nested) + for entry in response.get("functions") or () + if isinstance(entry, Mapping) + and isinstance(nested := entry.get("agent_run_state"), Mapping) + ) + + async def _restore_pending_nested_agent_tool_runs( *, current_agent: Agent[Any], function_actions: Sequence[_DeserializedFunctionAction], scope_id: str | None = None, + specialist_context: RunContextWrapper[Any] | None = None, context_deserializer: ContextDeserializer | None = None, strict_context: bool = False, validation_error_factory: RunStateValidationErrorFactory = _default_run_state_validation_error, @@ -3239,16 +3258,23 @@ async def _restore_pending_nested_agent_tool_runs( if not isinstance(nested_root_agent, Agent): nested_root_agent = current_agent + specialist = _has_pending_specialist(nested_state_data) try: nested_state = await _build_run_state_from_json( initial_agent=nested_root_agent, state_json=dict(nested_state_data), + # Agent.as_tool shares the application value but owns separate approvals. + context_override=( + RunContextWrapper(context=specialist_context.context) + if specialist and specialist_context is not None + else None + ), context_deserializer=context_deserializer, strict_context=strict_context, validation_error_factory=validation_error_factory, ) except Exception: - if strict_context: + if strict_context or specialist: raise logger.warning( "Failed to deserialize nested agent run state for tool call %s.", @@ -3274,6 +3300,7 @@ async def _deserialize_processed_response( *, agent_identity_map: Mapping[str, Agent[Any]] | None = None, scope_id: str | None = None, + specialist_context: RunContextWrapper[Any] | None = None, context_deserializer: ContextDeserializer | None = None, strict_context: bool = False, program_call_ids: Collection[str] = (), @@ -3597,6 +3624,7 @@ def _deserialize_function_actions() -> list[_DeserializedFunctionAction]: await _restore_pending_nested_agent_tool_runs( current_agent=current_agent, function_actions=function_actions, + specialist_context=specialist_context, scope_id=scope_id, context_deserializer=context_deserializer, strict_context=strict_context, @@ -4346,6 +4374,14 @@ async def _build_run_state_from_json( context._restored_unbound_approval_call_ids = set() context._allow_legacy_approval_binding_reconstruction = (schema_major, schema_minor) < (1, 15) context._rebuild_approvals(context_data.get("approvals", {})) + # Saved context alone cannot authorize a callback-gated specialist. + for _, route, label, target in _decision_edges(agent_identity_map): + if target is current_agent and not route._can_restore( + context if context_override is not None else None, label + ): + raise validation_error_factory( + "Decision specialist unavailable. Check the roster and context_override.", UserError + ) saved_invocations = context_data.get("tool_invocations", {}) if ( (schema_major, schema_minor) < (1, 23) @@ -4484,6 +4520,7 @@ async def _build_run_state_from_json( agent_map, agent_identity_map=agent_identity_map, scope_id=state._agent_tool_state_scope_id, + specialist_context=context if context_override is not None else None, context_deserializer=context_deserializer, strict_context=strict_context, program_call_ids=program_call_ids, @@ -5656,6 +5693,7 @@ def _clone_original_input(original_input: str | list[Any]) -> str | list[Any]: f"New snapshots are written as version {CURRENT_SCHEMA_VERSION}." ), "Run state agent not found in agent map", + "Decision specialist unavailable. Check the roster and context_override.", ( "RunState cannot distinguish same-name agents without hook instance state. " "Use unique agent names before starting a persistable run." diff --git a/tests/test_decisions.py b/tests/test_decisions.py new file mode 100644 index 0000000000..e8c1da9ec9 --- /dev/null +++ b/tests/test_decisions.py @@ -0,0 +1,649 @@ +"""Decisions at the explicit-input, client, callback and Runner boundaries.""" + +import asyncio +import json +from typing import Any + +import httpx2 +import pytest +from openai import AsyncOpenAI, InternalServerError +from pydantic import BaseModel, Field, field_validator + +from agents import ( + Agent, + RunConfig, + RunContextWrapper, + RunHooks, + Runner, + RunState, + SQLiteSession, + Usage, + handoff, +) +from agents.decisions import ( + DecisionError, + DecisionRequest, + DecisionResult, + OpenAIDecisions, + decide, + decision_handoff, + decision_scope, +) +from agents.decorators import tool +from agents.exceptions import UserError +from agents.testing import ModelStep, ScriptedModel, assistant_message, function_call + +CONFIG = RunConfig(tracing_disabled=True) + + +class Provider: + """Script the decision boundary independently of the primary model.""" + + def __init__(self, value: Any): + self.value = value + self.requests: list[DecisionRequest] = [] + + async def get_decision(self, request: DecisionRequest) -> DecisionResult[Any]: + self.requests.append(request) + return DecisionResult(self.value, "request", "fixture", Usage(requests=1, total_tokens=7)) + + +class Count(BaseModel): + count: int = Field(json_schema_extra={"minimum": 0}) + + @field_validator("count") + @classmethod + def even(cls, value: int) -> int: + if value % 2: + raise ValueError("private parser details") + return value + + +async def test_explicit_input_and_choices_are_captured_before_await(): + provider = Provider(False) + evidence = [{"values": [1]}] + choices = [0, False, None] + pending = decide("Which?", provider=provider, input=evidence, choices=choices) + evidence[0]["values"].clear() + choices.clear() + result = await pending + assert result.value is False + assert provider.requests[0].input == [{"values": [1]}] + assert provider.requests[0].output_schema == {"enum": [0, False, None]} + assert result.usage is not None + assert (result.request_id, result.model, result.usage.total_tokens) == ("request", "fixture", 7) + assert (await decide("Even?", provider=Provider(True), input="2")).value is True + typed = await decide( + "How many?", provider=Provider({"count": 2}), input="pair", output_type=Count + ) + assert typed.value.count == 2 + + +@pytest.mark.parametrize( + "changes", + [ + {"question": " "}, + {"input": None}, + {"input": ""}, + {"input": []}, + {"input": [{"n": float("inf")}]}, + {"input": [{1: True}]}, + {"choices": []}, + {"choices": [1, 1.0]}, + {"choices": [float("nan")]}, + {"choices": ["x"], "output_type": Count}, + ], +) +async def test_invalid_requests_do_not_reach_provider(changes): + provider = Provider(True) + with pytest.raises(ValueError): + await decide(**{"question": "Which?", "provider": provider, "input": "item", **changes}) + assert not provider.requests + + +@pytest.mark.parametrize("value", [-2, 3, "private", float("nan")]) +async def test_schema_and_parser_failures_keep_only_metadata(value): + class MutableProvider(Provider): + async def get_decision(self, request): + request.output_schema.clear() + return await super().get_decision(request) + + with pytest.raises(DecisionError) as caught: + await decide( + "Count?", provider=MutableProvider({"count": value}), input="pair", output_type=Count + ) + error = caught.value + assert error.reason == "invalid_response" and error.__context__ is None + assert error.usage is not None + assert (error.model, error.request_id, error.usage.total_tokens) == ("fixture", "request", 7) + assert "private" not in repr(error) + + +class BlockingProvider(Provider): + """Control suspension and simulate a provider returning success after cancellation.""" + + def __init__(self): + super().__init__("blue") + self.started = asyncio.Event() + self.release = asyncio.Event() + self.finished = asyncio.Event() + + async def get_decision(self, request): + self.started.set() + try: + await self.release.wait() + except asyncio.CancelledError: + await asyncio.sleep(0) + self.finished.set() + return await super().get_decision(request) + + +async def test_scope_requires_exact_live_owner_and_joins_revoked_work(): + provider = BlockingProvider() + owner = {} + async with decision_scope(owner): + with pytest.raises(RuntimeError, match="owner"): + await decide("Which?", provider=provider, input="item", owner={}) + stale = decide("Which?", provider=provider, input="item", owner=owner) + task = asyncio.create_task( + decide("Which?", provider=provider, input="item", choices=["blue"], owner=owner) + ) + await provider.started.wait() + assert provider.finished.is_set() + with pytest.raises(asyncio.CancelledError): + await task + async with decision_scope(owner): + with pytest.raises(RuntimeError, match="owner"): + await stale + assert len(provider.requests) == 1 + + +@pytest.mark.parametrize("case", ["choice", "predicate", "refusal", "invalid", "transport"]) +async def test_generated_client_without_network(case): + requests = [] + + def respond(req): + requests.append(json.loads(req.content)) + assert req.url.path == "/v1/decisions" + if case == "transport": + return httpx2.Response(500, json={}) + answer = {"name": "decision", "type": case, "choice": "blue", "probability": 0.7} + if case == "invalid": + answer.update(type="choice", choice="private") + return httpx2.Response( + 200, + headers={"x-request-id": "observed"}, + json={ + "answers": [answer], + "model": "fixture", + "usage": { + "input_tokens": 3, + "output_tokens": 1, + "total_tokens": 4, + "input_tokens_details": {"cached_tokens": 0, "cache_write_tokens": 0}, + "output_tokens_details": {"reasoning_tokens": 0}, + }, + }, + ) + + http = httpx2.AsyncClient(transport=httpx2.MockTransport(respond), trust_env=False) + async with AsyncOpenAI( + api_key="synthetic", base_url="https://fixture.invalid/v1", http_client=http + ) as client: + if not hasattr(client, "decisions"): + pytest.skip("Requires the optional Decisions client") + provider = OpenAIDecisions(client, model="fixture") + with pytest.raises(ValueError, match="predicate"): + await decide("How many?", provider=provider, input="item", output_type=Count) + options: dict[str, Any] = {} if case == "predicate" else {"choices": ["red", "blue"]} + pending = decide("Which?", provider=provider, input="item", **options) + if case == "transport": + with pytest.raises(InternalServerError): + await pending + else: + if case in ("refusal", "invalid"): + with pytest.raises(DecisionError) as caught: + await pending + result = caught.value + assert result.reason == ("refusal" if case == "refusal" else "invalid_response") + assert result.__context__ is None and "private" not in repr(result) + else: + result = await pending + assert result.value == (True if case == "predicate" else "blue") + assert result.usage is not None + assert (result.request_id, result.model, result.usage.total_tokens) == ( + "observed", + "fixture", + 4, + ) + assert len(requests) == 1 and requests[0]["input"] == "item" + assert requests[0]["questions"][0]["type"] == ( + "predicate" if case == "predicate" else "choice" + ) + assert not http.is_closed + + +def source_agent(arguments=None): + return Agent( + name="Source", + model=ScriptedModel( + [ + ModelStep( + output=[ + function_call( + "select_specialist", + arguments or {"input": "evidence"}, + call_id="transfer", + ) + ], + response_id="parent", + request_id="original", + ) + ] + ), + ) + + +async def run(source, stream, value="history", **kwargs): + if stream: + result = Runner.run_streamed(source, value, run_config=CONFIG, **kwargs) + async for _ in result.stream_events(): + pass + return result + return await Runner.run(source, value, run_config=CONFIG, **kwargs) + + +@pytest.mark.parametrize("stream", [False, True]) +async def test_runner_preserves_context_call_identity_and_specialist_permissions(stream): + context = {"allowed": "blue"} + transfers, effects = [], [] + + class Hooks(RunHooks): + async def on_handoff(self, context, from_agent, to_agent): + transfers.append((context.context, from_agent, to_agent)) + + @tool(is_enabled=False) + def hidden() -> str: + raise AssertionError + + @tool(needs_approval=True) + def gated() -> str: + effects.append("approved") + return "done" + + model = ScriptedModel([[function_call("gated", {}, call_id="restricted")]]) + blue = Agent( + name="Blue", model=model, tools=[hidden, gated], tool_use_behavior="stop_on_first_tool" + ) + red = Agent(name="Red", model=ScriptedModel()) + source = source_agent() + provider = Provider("blue") + targets = {"red": red, "blue": blue} + route = decision_handoff( + source, + provider=provider, + question="Which?", + targets=targets, + is_available=lambda ctx, label: ctx.context["allowed"] == label, + ) + source.handoffs.append(route) + result = await run( + source, stream, context=context, hooks=Hooks(), auto_previous_response_id=True + ) + assert result.last_agent is blue + assert len(transfers) == 1 + ctx, parent, target = transfers[0] + assert ctx is context and parent is source and target is blue + assert result.raw_responses[0].request_id == "original" + assert model.calls[0].previous_response_id == "parent" + assert [ + i["call_id"] for i in model.calls[0].input if i.get("type") == "function_call_output" + ] == ["transfer"] + assert [t.name for t in model.calls[0].tools] == ["gated"] + assert not effects and len(result.interruptions) == 1 + assert result.context_wrapper.usage.total_tokens == 7 + saved = result.to_state().to_string() + with pytest.raises(UserError): + await RunState.from_string(source, saved) + with pytest.raises(UserError): + await RunState.from_string(source, saved, context_override={"allowed": "red"}) + del targets["blue"] + with pytest.raises(UserError): + await RunState.from_string(source, saved, context_override=context) + targets["blue"] = blue.clone() + with pytest.raises(UserError): + await RunState.from_string(source, saved, context_override=context) + targets["blue"] = blue + source.handoffs[:] = [handoff(blue, is_enabled=False)] + with pytest.raises(UserError): + await RunState.from_string(source, saved, context_override=context) + source.handoffs[:] = [route] + state = await RunState.from_string(source, saved, context_override=context) + state.approve(state.get_interruptions()[0]) + resumed = await Runner.run(source, state, run_config=CONFIG) + assert resumed.final_output == "done" and effects == ["approved"] + assert len(model.calls) == len(provider.requests) == 1 + assert provider.requests[0].input == "evidence" + assert provider.requests[0].output_schema == {"enum": ["blue"]} + + +async def test_restore_rebuilt_roster_binds_label_and_agent_without_reselection(): + provider = Provider("blue") + effects = [] + + @tool(needs_approval=True) + def record() -> str: + effects.append("record") + return "done" + + def build(label): + source = source_agent() + target = Agent( + name="Specialist", + tools=[record], + tool_use_behavior="stop_on_first_tool", + model=ScriptedModel([[function_call("record", {}, call_id="write")]]), + ) + source.handoffs.append( + decision_handoff(source, provider=provider, question="Which?", targets={label: target}) + ) + return source, target + + source, _ = build("blue") + saved = (await run(source, False)).to_state().to_json() + with pytest.raises(UserError, match="agent identity"): + await RunState.from_json(build("green")[0], saved) + restored, target = build("blue") + state = await RunState.from_json(restored, saved) + state.approve(state.get_interruptions()[0]) + result = await Runner.run(restored, state, run_config=CONFIG) + assert result.last_agent is target and result.final_output == "done" + assert effects == ["record"] and len(provider.requests) == 1 + + +@pytest.mark.parametrize( + "case", ["replaced", "removed", "permission", "unknown", "timeout", "cancel"] +) +async def test_no_transfer_after_revocation_failure_or_cancellation(case): + source = source_agent() + model = ScriptedModel([[assistant_message("unexpected")]]) + targets = {"blue": Agent(name="Blue", model=model)} + context = {"allowed": True} + provider = BlockingProvider() + source.handoffs.append( + decision_handoff( + source, + provider=provider, + question="Which?", + targets=targets, + is_available=lambda ctx, label: ctx.context["allowed"], + timeout=0.01 if case == "timeout" else 30, + ) + ) + task = asyncio.create_task(run(source, False, context=context)) + try: + await asyncio.wait_for(provider.started.wait(), 3) + error: type[BaseException] = ValueError + if case == "replaced": + targets["blue"] = targets["blue"].clone() + elif case == "removed": + source.handoffs.clear() + elif case == "permission": + context["allowed"] = False + elif case == "unknown": + provider.value = "unlisted_tool" + error = DecisionError + elif case == "timeout": + error = asyncio.TimeoutError + else: + task.cancel() + error = asyncio.CancelledError + if error in (ValueError, DecisionError): + provider.release.set() + with pytest.raises(error): + await task + assert provider.finished.is_set() and len(provider.requests) == 1 + assert isinstance(source.model, ScriptedModel) + assert not model.calls and len(source.model.calls) == 1 + finally: + provider.release.set() + await asyncio.gather(task, return_exceptions=True) + + +@pytest.mark.parametrize("arguments", [{"input": "a", "grant": True}, {"input": "é" * 4097}]) +async def test_model_cannot_extend_routing_input(arguments): + source = source_agent(arguments) + provider = Provider("blue") + source.handoffs.append( + decision_handoff(source, provider=provider, question="Which?", targets={"blue": source}) + ) + with pytest.raises(ValueError, match="routing input"): + await run(source, False) + assert not provider.requests + + +async def test_immediate_stream_cancellation_drains_late_selection(): + source = source_agent() + model = ScriptedModel() + provider = BlockingProvider() + source.handoffs.append( + decision_handoff( + source, + provider=provider, + question="Which?", + targets={"blue": Agent(name="Blue", model=model)}, + ) + ) + result = Runner.run_streamed(source, "history", run_config=CONFIG) + + async def drain(): + async for _ in result.stream_events(): + pass + + consumer = asyncio.create_task(drain()) + try: + await asyncio.wait_for(provider.started.wait(), 3) + finally: + result.cancel() + await consumer + assert provider.finished.is_set() and not model.calls + assert result.last_agent is source + + +async def test_primary_can_answer_without_selection_and_clones_need_their_own_route(): + provider = Provider("blue") + model = ScriptedModel([[assistant_message("direct")], [assistant_message("direct")]]) + source = Agent(name="Source", model=model) + route = decision_handoff( + source, provider=provider, question="Which?", targets={"blue": Agent(name="Blue")} + ) + source.handoffs.append(route) + for agent in (source, source.clone()): + assert (await run(agent, False)).final_output == "direct" + assert len(model.calls[0].handoffs) == 1 and not model.calls[1].handoffs + assert not provider.requests + + +async def test_scope_exit_during_cancelled_request_joins_without_interrupting_cleanup(): + started = asyncio.Event() + cleaning = asyncio.Event() + release = asyncio.Event() + cleaned = asyncio.Event() + + class SlowCleanup: + async def get_decision(self, request): + started.set() + try: + await asyncio.Event().wait() + finally: + cleaning.set() + await release.wait() + cleaned.set() + + owner = object() + async with decision_scope(owner): + task = asyncio.create_task( + decide("Ready?", provider=SlowCleanup(), input="item", owner=owner) + ) + try: + await started.wait() + task.cancel() + await cleaning.wait() + finally: + asyncio.get_running_loop().call_soon(release.set) + assert cleaned.is_set() + with pytest.raises(asyncio.CancelledError): + await task + + +async def test_explicit_recovery_returns_to_caller_without_transferring(): + model = ScriptedModel( + [ + [function_call("select_specialist", {"input": "evidence"}, call_id="transfer")], + [assistant_message("direct")], + ] + ) + source = Agent(name="Source", model=model) + provider = Provider("unknown") + route = decision_handoff( + source, provider=provider, question="Which?", targets={"blue": Agent(name="Blue")} + ) + route.failure_error_function = lambda ctx, error: "Transfer unavailable" + source.handoffs.append(route) + result = await run(source, False) + assert result.last_agent is source and result.final_output == "direct" + assert result.context_wrapper.usage.total_tokens == 7 and len(provider.requests) == 1 + assert any( + i.get("output") == "Transfer unavailable" and i.get("call_id") == "transfer" + for i in model.calls[1].input + ) + + +@pytest.mark.parametrize("stream", [False, True]) +@pytest.mark.parametrize("approve_first", [False, True]) +@pytest.mark.parametrize("failure", ["cancel", "timeout", "refusal", "invalid"]) +async def test_selection_failure_keeps_completed_tool_receipt(stream, approve_first, failure): + effects = [] + + class Failing: + async def get_decision(self, request): + effects.append("select") + if failure == "refusal": + raise DecisionError("refusal") + if failure == "invalid": + return DecisionResult("unknown") + if failure == "timeout": + await asyncio.Event().wait() + future = asyncio.get_running_loop().create_future() + future.cancel("private details") + return await future + + @tool(needs_approval=approve_first) + def record() -> str: + effects.append("record") + return "recorded" + + source = Agent( + name="Source", + tools=[record], + model=ScriptedModel( + [ + [ + function_call("record", {}, call_id="effect"), + function_call("select_specialist", {"input": "evidence"}, call_id="select"), + ] + ] + ), + ) + specialist = ScriptedModel() + source.handoffs.append( + decision_handoff( + source, + provider=Failing(), + question="Which?", + timeout=0.01 if failure == "timeout" else 30, + targets={"blue": Agent(name="Blue", model=specialist)}, + ) + ) + session = SQLiteSession("receipts") + try: + value: Any = "history" + if approve_first: + paused = await run(source, stream, session=session) + value = paused.to_state() + value.approve(value.get_interruptions()[0]) + error = {"cancel": RuntimeError, "timeout": asyncio.TimeoutError}.get( + failure, DecisionError + ) + with pytest.raises(error) as caught: + await run(source, stream, value, session=session) + if failure == "cancel": + assert str(caught.value) == "Decision provider cancelled its request" + if approve_first: + items = [ + entry["raw_item"] + for entry in value.to_json()["generated_items"] + if entry["type"] != "tool_approval_item" + ] + else: + items = await session.get_items() + receipts = [i for i in items if i.get("call_id") == "effect"] + assert [i["type"] for i in receipts] == ["function_call", "function_call_output"] + assert receipts[-1].get("output") == "recorded" + assert effects == ["record", "select"] and not specialist.calls + finally: + session.close() + + +@pytest.mark.parametrize("stream", [False, True]) +async def test_nested_specialist_uses_fresh_context_and_owns_approval(stream): + effects = [] + provider = Provider("blue") + + @tool(needs_approval=True) + def record(ctx: RunContextWrapper[dict[str, str]]) -> str: + effects.append(ctx.context) + return "recorded" + + source = source_agent() + target = Agent( + name="Blue", + tools=[record], + tool_use_behavior="stop_on_first_tool", + model=ScriptedModel([[function_call("record", {}, call_id="effect")]]), + ) + route = decision_handoff( + source, + provider=provider, + question="Which?", + targets={"blue": target}, + is_available=lambda ctx, label: ctx.context["allowed"] == label, + ) + source.handoffs.append(route) + manager = Agent( + name="Manager", + tools=[source.as_tool(tool_name="ask", tool_description="Ask")], + model=ScriptedModel( + [ + [function_call("ask", {"input": "work"}, call_id="parent")], + [assistant_message("done")], + ] + ), + ) + paused = await run(manager, stream, context={"allowed": "blue"}) + saved = paused.to_state().to_string() + fresh = {"allowed": "blue", "revision": "current"} + with pytest.raises(UserError, match="unavailable"): + await RunState.from_string(manager, saved) + with pytest.raises(UserError, match="unavailable"): + await RunState.from_string(manager, saved, context_override={"allowed": "red"}) + source.handoffs[:] = [target] + with pytest.raises(UserError): + await RunState.from_string(manager, saved, context_override=fresh) + source.handoffs[:] = [route] + state = await RunState.from_string(manager, saved, context_override=fresh) + assert not effects + state.approve(state.get_interruptions()[0]) + done = await run(manager, not stream, state) + assert done.final_output == "done" + assert len(effects) == len(provider.requests) == 1 and effects[0] is fresh From 5b058ba42a7c80ebab1704f9bbdf7def9ae3d28b Mon Sep 17 00:00:00 2001 From: Mark Stuart Date: Sun, 22 Nov 2026 14:24:10 -0800 Subject: [PATCH 2/4] Keep private routing evidence out of handoff error tracebacks --- examples/decisions/README.md | 1 + src/agents/decisions.py | 11 ++++ src/agents/run_internal/turn_resolution.py | 1 + tests/test_decisions.py | 61 ++++++++++++++++++++++ 4 files changed, 74 insertions(+) diff --git a/examples/decisions/README.md b/examples/decisions/README.md index e475056578..2f54e5e868 100644 --- a/examples/decisions/README.md +++ b/examples/decisions/README.md @@ -42,6 +42,7 @@ async def answer(client: AsyncOpenAI, decisions_model: str, text: str): - **Evidence.** The model supplies one nonblank `input` string of up to 8,192 UTF-8 bytes. The provider receives that string, the question and the allowed choices. The model can copy sensitive text into the string. The specialist receives the usual handoff history. Set the handoff's `input_filter` when the specialist needs less context. - **Authority.** The handoff belongs to the source agent. Create a new handoff for a clone. Labels bind to the original agent objects and names. Removing, replacing or renaming a target makes it unavailable. Use a synchronous, side-effect-free `is_available(ctx, label)` to check application permissions. The handoff checks the selected route again before transfer. Runner keeps the run context, call IDs, tool restrictions and approvals. - **Failures.** Refusals and invalid answers raise `DecisionError`. Revoked routes raise `ValueError`. The provider deadline defaults to 30 seconds. On timeout or cancellation, the SDK waits for provider cleanup and discards late answers. Timeout raises `asyncio.TimeoutError`. If the provider cancels its own request, the SDK raises `RuntimeError`. Transport errors propagate. There is no automatic fallback or retry. To return an error to the primary model, explicitly set the handoff's `failure_error_function`. For immediate stream cancellation, call `result.cancel()` and drain `result.stream_events()`. +- **Error privacy.** When either model or tool data logging is disabled, the handoff removes routing traceback frames and exception chains before propagating a failure. Provider errors and metadata can still contain sensitive data. Keep custom error messages and recovery callbacks safe to share. - **Scope.** Both Runner modes support specialist selection. Decisions cannot invoke a tool, grant permissions or tell the source to continue. Realtime and dynamic agent factories are outside this integration. - **Available labels.** With `OpenAIDecisions`, the model sees the handoff only when 2 to 255 labels are available. If the count falls outside that range before invocation, the handoff raises `ValueError` without asking the provider or transferring. A custom provider can select a single available label. The SDK never transfers by default. diff --git a/src/agents/decisions.py b/src/agents/decisions.py index 8904e1f4d1..64c4dae75a 100644 --- a/src/agents/decisions.py +++ b/src/agents/decisions.py @@ -16,9 +16,11 @@ from openai.types.responses.response_usage import ResponseUsage from pydantic import BaseModel, ConfigDict, Field, JsonValue, TypeAdapter +from . import _debug from ._public_agent import get_public_agent from ._run_state_agent_identity import _DecisionHandoff from .agent import Agent +from .exceptions import _data_redacted_error_boundary, _mark_error_data_redacted from .handoffs import Handoff from .run_context import RunContextWrapper from .usage import Usage, _response_usage_to_usage @@ -436,7 +438,16 @@ def attached() -> bool: def authorized(ctx: RunContextWrapper[_T] | None, label: str) -> bool: return admitted(ctx, label) and attached() + @_data_redacted_error_boundary async def invoke(ctx: RunContextWrapper[_T], arguments: str) -> Agent[_T]: + try: + return await select(ctx, arguments) + except (Exception, asyncio.CancelledError) as error: + if _debug.DONT_LOG_MODEL_DATA or _debug.DONT_LOG_TOOL_DATA: + _mark_error_data_redacted(error) + raise + + async def select(ctx: RunContextWrapper[_T], arguments: str) -> Agent[_T]: evidence = _routing_input(arguments) choices = available_choices(ctx) if not choices or not attached(): diff --git a/src/agents/run_internal/turn_resolution.py b/src/agents/run_internal/turn_resolution.py index e847c9bddd..fdc15493da 100644 --- a/src/agents/run_internal/turn_resolution.py +++ b/src/agents/run_internal/turn_resolution.py @@ -621,6 +621,7 @@ def nest_history( raise # A failed invocation is not a transfer. Do not run transfer hooks or filters. span_handoff.set_error(SpanError(message="Handoff invocation failed", data={})) + _detach_data_redacted_error_traceback(error) error_output = handoff.failure_error_function(context_wrapper, error) if inspect.isawaitable(error_output): error_output = await error_output diff --git a/tests/test_decisions.py b/tests/test_decisions.py index 46590d423b..b64fa92029 100644 --- a/tests/test_decisions.py +++ b/tests/test_decisions.py @@ -466,6 +466,67 @@ async def test_model_cannot_extend_routing_input(arguments): assert not provider.requests +@pytest.mark.parametrize("stream", [False, True]) +@pytest.mark.parametrize("failure", ["arguments", "refusal", "invalid_response"]) +@pytest.mark.parametrize("hide_model,hide_tool", [(True, False), (False, True), (False, False)]) +@pytest.mark.parametrize("recover", [False, True]) +async def test_handoff_error_redaction( + monkeypatch, stream, failure, hide_model, hide_tool, recover +): + from agents import _debug + from agents.exceptions import _is_error_data_redacted + from tests.test_error_logging_redaction import _agents_traceback_frame_locals + + monkeypatch.setattr(_debug, "DONT_LOG_MODEL_DATA", hide_model) + monkeypatch.setattr(_debug, "DONT_LOG_TOOL_DATA", hide_tool) + marker = "SYNTHETIC_PRIVATE_ROUTING_EVIDENCE" + arguments = {"input": marker} + if failure == "arguments": + arguments["extra"] = "unknown" + source = source_agent(arguments) + + class RefusingProvider(Provider): + async def get_decision(self, request): + self.requests.append(request) + raise DecisionError("refusal", request_id="observed") from ValueError(request.input) + + provider = RefusingProvider(None) if failure == "refusal" else Provider("unknown") + handoff = decision_handoff( + source, provider=provider, question="Which?", targets={"blue": source} + ) + source.handoffs.append(handoff) + errors: list[Exception] = [] + if recover: + + def report(ctx, error): + if hide_model or hide_tool: + assert error.__traceback__ is None + errors.append(error) + return "Selection failed" + + handoff.failure_error_function = report + assert isinstance(source.model, ScriptedModel) + source.model.enqueue([assistant_message("recovered")]) + assert (await run(source, stream)).final_output == "recovered" + (error,) = errors + else: + with pytest.raises(ValueError) as caught: + await run(source, stream) + error = caught.value + if failure == "arguments": + assert not provider.requests + else: + assert isinstance(error, DecisionError) and error.reason == failure + assert error.request_id == ("observed" if failure == "refusal" else "request") + assert _is_error_data_redacted(error) == (hide_model or hide_tool) + if hide_model or hide_tool: + assert error.__cause__ is error.__context__ is None + assert marker not in str(error) + assert marker not in repr(_agents_traceback_frame_locals(error)) + elif failure == "refusal": + assert marker in str(error.__cause__) + + async def test_immediate_stream_cancellation_drains_late_selection(): source = source_agent() model = ScriptedModel() From 924b4a16cc2e5fc0417b7afb4b5c822a069594f0 Mon Sep 17 00:00:00 2001 From: Mark Stuart Date: Mon, 23 Nov 2026 21:38:51 -0800 Subject: [PATCH 3/4] Support handoff input filters and reject unusable specialist lists --- src/agents/decisions.py | 12 ++++++++++- tests/test_decisions.py | 45 +++++++++++++++++++++++++++++++++++++++++ 2 files changed, 56 insertions(+), 1 deletion(-) diff --git a/src/agents/decisions.py b/src/agents/decisions.py index d38c4c3b7b..fbdebcbb7f 100644 --- a/src/agents/decisions.py +++ b/src/agents/decisions.py @@ -21,7 +21,7 @@ from ._run_state_agent_identity import _DecisionHandoff from .agent import Agent from .exceptions import _data_redacted_error_boundary, _mark_error_data_redacted -from .handoffs import Handoff +from .handoffs import Handoff, HandoffInputFilter from .run_context import RunContextWrapper from .usage import Usage, _response_usage_to_usage @@ -394,12 +394,16 @@ def decision_handoff( tool_description: str = "Transfer to a specialist. Supply only evidence needed for routing.", is_available: Callable[[RunContextWrapper[_T], str], bool] | None = None, timeout: float = 30, + input_filter: HandoffInputFilter | None = None, ) -> Handoff[_T, Agent[_T]]: """Build a handoff for source.handoffs. Decisions chooses a label on a model request. Labels bind to concrete agents at construction. Removing or replacing a target revokes it. A synchronous is_available callback can further restrict each run. OpenAIDecisions requires 2 to 255 available labels to offer or invoke the handoff. + For a single fixed label, use `handoff(target)` or a custom provider. + Pass `input_filter` to filter the selected specialist's history. The provider + has already received the routing evidence when this filter runs. A custom provider may await decide() without access to the run context. Invoke the handoff outside an explicit decision_scope, which requires its owner. Restoring a specialist from serialized RunState checks its incoming selectors. @@ -415,6 +419,11 @@ def decision_handoff( raise ValueError("Expected nonblank labels mapped to agents") roster = {label: (agent, agent.name) for label, agent in targets.items()} + if isinstance(provider, OpenAIDecisions) and len(roster) == 1: + raise ValueError( + "OpenAIDecisions requires at least two labels. Use handoff(target) for one." + ) + def admitted(ctx: RunContextWrapper[_T] | None, label: str) -> bool: agent, name = roster[label] return ( @@ -480,6 +489,7 @@ async def select(ctx: RunContextWrapper[_T], arguments: str) -> Agent[_T]: tool_description=tool_description, input_json_schema=_RoutingInput.model_json_schema(), on_invoke_handoff=invoke, + input_filter=input_filter, agent_name=tool_name, is_enabled=enabled, ) diff --git a/tests/test_decisions.py b/tests/test_decisions.py index a6d368a875..43f0b29e31 100644 --- a/tests/test_decisions.py +++ b/tests/test_decisions.py @@ -2,6 +2,7 @@ import asyncio import json +from dataclasses import replace from typing import Any from unittest.mock import Mock @@ -317,6 +318,50 @@ async def test_handoff_cannot_replace_an_external_decision_owner(): assert not inner.requests +def test_openai_single_target_suggests_ordinary_handoff(): + source = source_agent() + with pytest.raises(ValueError, match=r"handoff\(target\)"): + decision_handoff( + source, + provider=OpenAIDecisions(Mock(spec=AsyncOpenAI), model="fixture"), + question="Which?", + targets={"blue": Agent(name="Blue")}, + ) + assert not source.handoffs + + +@pytest.mark.parametrize("stream", [False, True]) +@pytest.mark.parametrize("routed", [False, True]) +async def test_input_filter_changes_specialist_history_only(stream, routed): + def summary(data): + return replace(data, input_history="summary", input_items=()) + + model = ScriptedModel([[assistant_message("done")]]) + target = Agent(name="Blue", model=model) + provider = Provider("blue") + if routed: + source = source_agent() + route = decision_handoff( + source, + provider=provider, + question="Which?", + targets={"blue": target}, + input_filter=summary, + ) + else: + route = handoff(target, input_filter=summary) + source = Agent( + name="Source", + model=ScriptedModel([[function_call(route.tool_name, {}, call_id="transfer")]]), + ) + assert not source.handoffs + source.handoffs.append(route) + result = await run(source, stream) + assert result.last_agent is target + assert model.calls[0].input == [{"role": "user", "content": "summary"}] + assert [request.input for request in provider.requests] == (["evidence"] if routed else []) + + @pytest.mark.parametrize("count", [0, 1, 2, 255, 256]) async def test_openai_handoff_catalog_uses_permitted_choice_count(count): model = ScriptedModel([[assistant_message("stay")]]) From a34e88f671c7d6d03fb69990a57df2c1888e91fa Mon Sep 17 00:00:00 2001 From: Mark Stuart Date: Tue, 24 Nov 2026 00:23:16 -0800 Subject: [PATCH 4/4] Make Decisions timeout tests independent of client startup time --- tests/test_decisions.py | 106 ++++++++++++++++++++++++++++++---------- 1 file changed, 80 insertions(+), 26 deletions(-) diff --git a/tests/test_decisions.py b/tests/test_decisions.py index 4be9fbd25e..b4119fff73 100644 --- a/tests/test_decisions.py +++ b/tests/test_decisions.py @@ -3,6 +3,7 @@ import asyncio import json from dataclasses import replace +from types import SimpleNamespace from typing import Any import httpx2 @@ -76,11 +77,36 @@ def __init__(self): self.started = asyncio.Event() self.release = asyncio.Event() self.finished = asyncio.Event() + self.request_task: asyncio.Task[Any] | None = None + + def expire_deadline(self, monkeypatch, *, before_dispatch): + async def wait(tasks, *, timeout=None): + if timeout is None: + return await asyncio.wait(tasks) + assert timeout == 0.01 + (self.request_task,) = tasks + if not before_dispatch: + await asyncio.wait_for(self.started.wait(), 3) + return set(), set(tasks) + + # Only the Decisions deadline expires here. Keep real task cancellation and joins. + clock = SimpleNamespace(**vars(asyncio)) + clock.wait = wait + monkeypatch.setattr("agents.decisions.asyncio", clock) + + def check_timeout(self, *, before_dispatch): + assert self.request_task is not None and self.request_task.done() + if before_dispatch: + assert self.request_task.cancelled() + assert not self.started.is_set() and not self.finished.is_set() and not self.requests + else: + assert self.started.is_set() and self.finished.is_set() and len(self.requests) == 1 async def respond(self, request): self.started.set() try: - await self.release.wait() + # Guard a missing cancellation without using elapsed time to trigger the deadline. + await asyncio.wait_for(self.release.wait(), 5) except asyncio.CancelledError: await asyncio.sleep(0) self.finished.set() @@ -320,28 +346,42 @@ def build(label): @pytest.mark.parametrize( - "case", ["replaced", "removed", "permission", "unknown", "timeout", "cancel"] + "case", + [ + "replaced", + "removed", + "permission", + "unknown", + "timeout", + "timeout_before_dispatch", + "cancel", + ], ) -async def test_no_transfer_after_revocation_failure_or_cancellation(case): +async def test_no_transfer_after_revocation_failure_or_cancellation(case, monkeypatch): source = source_agent() model = ScriptedModel([[assistant_message("unexpected")]]) targets = {"blue": Agent(name="Blue", model=model), "red": Agent(name="Red")} context = {"allowed": True} provider = BlockingPeer() + before_dispatch = case == "timeout_before_dispatch" + timeout = before_dispatch or case == "timeout" + if timeout: + provider.expire_deadline(monkeypatch, before_dispatch=before_dispatch) source.handoffs.append( decision_handoff( source, client=provider.client, model="fixture", + timeout=0.01 if timeout else 30, question="Which?", targets=targets, is_available=lambda ctx, label: ctx.context["allowed"], - timeout=0.01 if case == "timeout" else 30, ) ) task = asyncio.create_task(run(source, False, context=context)) try: - await asyncio.wait_for(provider.started.wait(), 3) + if not timeout: + await asyncio.wait_for(provider.started.wait(), 3) error: type[BaseException] = ValueError if case == "replaced": targets["blue"] = targets["blue"].clone() @@ -352,7 +392,7 @@ async def test_no_transfer_after_revocation_failure_or_cancellation(case): elif case == "unknown": provider.value = "unlisted_tool" error = DecisionError - elif case == "timeout": + elif timeout: error = asyncio.TimeoutError else: task.cancel() @@ -361,7 +401,10 @@ async def test_no_transfer_after_revocation_failure_or_cancellation(case): provider.release.set() with pytest.raises(error): await task - assert provider.finished.is_set() and len(provider.requests) == 1 + if timeout: + provider.check_timeout(before_dispatch=before_dispatch) + else: + assert provider.finished.is_set() and len(provider.requests) == 1 assert isinstance(source.model, ScriptedModel) assert not model.calls and len(source.model.calls) == 1 finally: @@ -549,24 +592,32 @@ async def test_explicit_recovery_returns_to_caller_without_transferring(): @pytest.mark.parametrize("stream", [False, True]) @pytest.mark.parametrize("approve_first", [False, True]) -@pytest.mark.parametrize("failure", ["cancel", "timeout", "refusal", "invalid"]) -async def test_selection_failure_keeps_completed_tool_receipt(stream, approve_first, failure): +@pytest.mark.parametrize( + "failure", ["cancel", "timeout", "timeout_before_dispatch", "refusal", "invalid"] +) +async def test_selection_failure_keeps_completed_tool_receipt( + stream, approve_first, failure, monkeypatch +): effects = [] - class Failing(Peer): + before_dispatch = failure == "timeout_before_dispatch" + timeout = before_dispatch or failure == "timeout" + + class Failing(BlockingPeer): async def respond(self, request): effects.append("select") - if failure == "refusal": - self.value = "refusal" - return await super().respond(request) - if failure == "invalid": - self.value = "unknown" + if timeout: return await super().respond(request) - if failure == "timeout": - await asyncio.Event().wait() - future = asyncio.get_running_loop().create_future() - future.cancel("private details") - return await future + if failure == "cancel": + future = asyncio.get_running_loop().create_future() + future.cancel("private details") + return await future + self.value = "refusal" if failure == "refusal" else "unknown" + return await Peer.respond(self, request) + + peer = Failing() + if timeout: + peer.expire_deadline(monkeypatch, before_dispatch=before_dispatch) @tool(needs_approval=approve_first) def record() -> str: @@ -589,10 +640,10 @@ def record() -> str: source.handoffs.append( decision_handoff( source, - client=Failing().client, + client=peer.client, model="fixture", + timeout=0.01 if timeout else 30, question="Which?", - timeout=0.01 if failure == "timeout" else 30, targets={"blue": Agent(name="Blue", model=specialist), "red": Agent(name="Red")}, ) ) @@ -603,9 +654,9 @@ def record() -> str: paused = await run(source, stream, session=session) value = paused.to_state() value.approve(value.get_interruptions()[0]) - error = {"cancel": RuntimeError, "timeout": asyncio.TimeoutError}.get( - failure, DecisionError - ) + error: type[Exception] = RuntimeError if failure == "cancel" else DecisionError + if timeout: + error = asyncio.TimeoutError with pytest.raises(error) as caught: await run(source, stream, value, session=session) if failure == "cancel": @@ -621,7 +672,10 @@ def record() -> str: receipts = [i for i in items if i.get("call_id") == "effect"] assert [i["type"] for i in receipts] == ["function_call", "function_call_output"] assert receipts[-1].get("output") == "recorded" - assert effects == ["record", "select"] and not specialist.calls + if timeout: + peer.check_timeout(before_dispatch=before_dispatch) + assert effects == (["record"] if before_dispatch else ["record", "select"]) + assert not specialist.calls finally: session.close()