diff --git a/examples/decisions/README.md b/examples/decisions/README.md index a19c08ea8e..b77b1476d4 100644 --- a/examples/decisions/README.md +++ b/examples/decisions/README.md @@ -1,4 +1,123 @@ -# Decisions API recipes +# Decisions in the Python Agents SDK + +## Ask a typed question + +Set `Agent.decisions` once. Each call sends only the question, explicit input and requested output schema. This example makes paid requests when invoked. + +```python +from typing import Literal + +from pydantic import BaseModel + +from agents import Agent, AgentHooks, OpenAIDecisions, Runner +from agents.decorators import tool +from agents.tool_context import ToolContext + + +class Ticket(BaseModel): + urgent: bool + team: Literal["billing", "support"] + + +@tool +async def classify(ctx: ToolContext[None], report: str) -> str: + return await ctx.decide("Which team?", input=report, choices=["billing", "support"]) + + +async def check(run, proposal): + ready = await proposal.decide("Does the reply include a next step?", input=proposal.output) + return "finish" if ready else "continue" + + +async def answer_ticket(text: str): + async with OpenAIDecisions() as provider: + agent = Agent( + name="Help", + decisions=provider, + tools=[classify], + hooks=AgentHooks(final_output_policy=check), + ) + ticket = await agent.decide("Classify this request.", input=text, output_type=Ticket) + reply = await Runner.run(agent, text, max_turns=3) + return ticket, reply.final_output +``` + +Without `choices` or `output_type`, the result is a boolean. The built-in provider uses a probability threshold of 0.5. Choose one output form per call. Supported types include finite scalar choices, required nested records, integers spanning up to 255 values and floats with integer bounds up to 9 apart. Unsupported schemas fail before dispatch. Input can be text or model input items. The SDK adds no conversation history or instructions. + +Within one run, a handoff target inherits the root provider unless it declares its own. Nested runs, including agents as tools, start with their own provider. Within a function tool, a model input filter or a final output policy, call `decide` on the live `ToolContext`, `CallModelData` or `ProposedFinalOutput` respectively. Use `provider=...` for a single call or implement `DecisionProvider.get_decision` for another backend. An answer grants no permissions. + +Use `async with OpenAIDecisions()` or call `aclose()` for the default client. With `OpenAIDecisions(client=client)`, the caller owns the client. The built-in adapter needs an OpenAI client version with Decisions support and disables retries. Decision calls and tokens are outside Runner usage and budgets. With tracing enabled, the `decision.usage` span records available metadata without the question, input or answer. Missing usage is unknown. + +## 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, configure a provider on the source agent. This function makes paid calls when invoked. + +```python +from openai import AsyncOpenAI + +from agents import Agent, OpenAIDecisions, Runner +from agents.decisions import decision_handoff + + +async def answer(client: AsyncOpenAI, text: str): + source = Agent( + name="Triage", + instructions="Transfer requests that need a specialist.", + decisions=OpenAIDecisions(client=client), + ) + targets = { + "billing": Agent(name="Billing", instructions="Help with invoices."), + "account": Agent(name="Account", instructions="Help with account settings."), + } + route = decision_handoff( + source, + question="Which team can help?", + targets=targets, + ) + source.handoffs.append(route) + return await Runner.run(source, text) +``` + +Use a client with Decisions support. The caller owns its lifetime. Give each clone its own handoff list and selector. For one fixed target, use an ordinary `handoff(target)`. + +- **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. 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.** 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. 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) +``` + +Use a separate specialist instance for each label and ordinary handoff. A saved specialist identifies one route. Loading and resuming recheck each selected label on the active handoff path, including ordinary descendants and pending agent tools. Returning to an earlier agent ends the branch below it. Missing bindings or denied access stop the resume before dispatch. Decisions does not run again. Review each pending call in `state.get_interruptions()`, then approve or reject it and resume with `await Runner.run(source, state)`. + +Keep the graph and grants current. If selection fails after a tool has run, keep the updated `RunState` and inspect completed results before retrying. + +### Evaluate routing separately + +Compare ordinary and Decisions handoffs on held-out labels with the same specialists. Record wrong transfers, refusals, end-task outcomes, latency and any available usage. The offline comparison cannot establish which route is better for your workload. + +## 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..88c4b2ed73 --- /dev/null +++ b/examples/decisions/compare_handoffs.py @@ -0,0 +1,103 @@ +"""Compare two scripted handoff paths on labeled fixtures without making API calls.""" + +import asyncio +import json +from time import perf_counter + +import httpx2 +from openai import AsyncOpenAI + +from agents import Agent, RunConfig, Runner, handoff +from agents.decisions import OpenAIDecisions, 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"), +) + + +async def compare() -> None: + predictions = {text: predicted for text, _, _, _, predicted in CASES} + calls = 0 + + def respond(request: httpx2.Request) -> httpx2.Response: + nonlocal calls + calls += 1 + choice = predictions[json.loads(request.content)["input"]] + return httpx2.Response( + 200, + json={ + "answers": [ + { + "type": "choice", + "name": "decision", + "choice": choice, + "confidence": 1.0, + "probabilities": [ + {"value": c["value"], "probability": float(c["value"] == choice)} + for c in json.loads(request.content)["questions"][0]["choices"] + ], + } + ] + }, + ) + + async with AsyncOpenAI( + api_key="synthetic", + base_url="https://fixture.invalid/v1", + http_client=httpx2.AsyncClient(transport=httpx2.MockTransport(respond), trust_env=False), + ) as client: + for path in ("primary", "decisions"): + calls = 0 + 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: + source.decisions = OpenAIDecisions(client=client) + route = decision_handoff( + source, 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": calls, + "estimated_cost": None, + "fallback": None, + } + ) + ) + + +if __name__ == "__main__": + asyncio.run(compare()) diff --git a/src/agents/__init__.py b/src/agents/__init__.py index 8f83c32b78..27845e1447 100644 --- a/src/agents/__init__.py +++ b/src/agents/__init__.py @@ -19,6 +19,13 @@ from .agent_output import AgentOutputSchema, AgentOutputSchemaBase from .apply_diff import apply_diff from .computer import AsyncComputer, Button, Computer, Environment +from .decisions import ( + DecisionError, + DecisionProvider, + DecisionRequest, + DecisionResponse, + OpenAIDecisions, +) from .editor import ApplyPatchEditor, ApplyPatchOperation, ApplyPatchResult from .exceptions import ( AgentsException, @@ -380,6 +387,11 @@ def enable_verbose_stdout_logging() -> None: __all__ = [ + "DecisionError", + "DecisionProvider", + "DecisionRequest", + "DecisionResponse", + "OpenAIDecisions", "Agent", "AgentBase", "AgentToolStreamEvent", diff --git a/src/agents/_decision_schema.py b/src/agents/_decision_schema.py new file mode 100644 index 0000000000..f0433f3a48 --- /dev/null +++ b/src/agents/_decision_schema.py @@ -0,0 +1,237 @@ +"""The bounded subset of JSON Schema expressible as Decisions questions.""" + +from __future__ import annotations + +import json +import math +from dataclasses import dataclass +from typing import Any + + +def _key(value: Any) -> tuple[type, Any]: + if type(value) not in (str, bool, int, float, type(None)) or ( + type(value) is float and not math.isfinite(value) + ): + raise ValueError("Expected a finite JSON scalar") + return (int if type(value) is float else type(value)), value + + +def _number(value: Any, low: float, high: float) -> float: + if type(value) not in (int, float) or not low <= value <= high: + raise ValueError("Invalid decision number") + return float(value) + + +def _choices(node: dict[str, Any]) -> list[Any]: + keys = set(node) - {"title", "description", "type", "$defs"} + kind = node.get("type") + if keys == {"anyOf"} and kind is None: + values = [v for branch in node["anyOf"] for v in _choices(branch)] + if not 1 <= len(values) <= 255 or len({_key(v) for v in values}) != len(values): + raise ValueError("Expected distinct finite choices") + return values + if not keys and kind == "null": + return [None] + if not keys and kind == "boolean": + return [True, False] + if keys in ({"enum"}, {"const"}): + values = node.get("enum", [node.get("const")]) + if ( + not isinstance(values, list) + or not 1 <= len(values) <= 255 + or len({_key(v) for v in values}) != len(values) + ): + raise ValueError("Expected distinct finite choices") + types = { + "string": (str,), + "boolean": (bool,), + "null": (type(None),), + "integer": (int,), + "number": (int, float), + } + if kind is not None and any(type(v) not in types.get(kind, ()) for v in values): + raise ValueError("Incompatible Decisions choice type") + return list(values) + raise ValueError("Expected a finite scalar schema") + + +@dataclass +class _Leaf: + kind: str + values: list[Any] + minimum: int = 0 + width: int = 0 + + def validate(self, value: Any) -> None: + if self.kind == "choice": + if _key(value) not in {_key(item) for item in self.values}: + raise ValueError("Unknown choice") + elif self.kind == "boolean": + if type(value) is not bool: + raise ValueError("Expected a boolean") + else: + _number(value, self.minimum, self.minimum + self.width) + + def decode(self, question: dict[str, Any], answer: dict[str, Any]) -> Any: + if question["type"] == "predicate": + p = _number(answer["probability"], 0, 1) + return p >= 0.5 if self.kind == "boolean" else p + _number(answer["confidence"], 0, 1) + wire = ( + [v["value"] for v in question["choices"]] + if self.kind == "choice" + else list(range(self.width + 1)) + ) + entries = answer["probabilities"] + if not isinstance(entries, list) or len(entries) != len(wire): + raise ValueError("Invalid probability list") + remaining = {_key(v) for v in wire} + total = 0.0 + for entry in entries: + remaining.remove(_key(entry["value"])) + total += _number(entry["probability"], 0, 1) + if ( + self.kind == "score" + and entry["label"] != question["levels"][entry["value"]]["label"] + ): + raise ValueError("Invalid score level") + if abs(total - 1.0) > 1e-5: + raise ValueError("Invalid probability total") + if self.kind == "choice": + return self.values[[_key(v) for v in wire].index(_key(answer["choice"]))] + return self.minimum + _number(answer["score"], 0, self.width) + + +class _Plan: + def __init__(self, question: str, schema: dict[str, Any]): + self.questions: list[dict[str, Any]] = [] + self.leaves: dict[tuple[str, ...], _Leaf] = {} + self.records: dict[tuple[str, ...], set[str]] = {} + definitions = schema.get("$defs", {}) + visited = 0 + + def bounded(value: Any, depth: int) -> None: + nonlocal visited + visited += 1 + if depth > 32 or visited > 10000: + raise ValueError("Decisions schema is too large") + if isinstance(value, (dict, list)): + for item in value.values() if isinstance(value, dict) else value: + bounded(item, depth + 1) + + bounded(schema, 0) + visited = 0 + + def visit(node: dict[str, Any], path: tuple[str, ...], depth: int) -> None: + nonlocal visited + visited += 1 + if depth > 32 or visited > 10000 or not isinstance(node, dict): + raise ValueError("Unsupported Decisions output schema") + keys = set(node) - {"title", "description", "type", "$defs"} + kind = node.get("type") + if keys == {"$ref"} and kind is None: + ref = node["$ref"] + if ( + not isinstance(ref, str) + or not ref.startswith("#/$defs/") + or ref[8:] not in definitions + ): + raise ValueError("Unsupported Decisions reference") + visit(definitions[ref[8:]], path, depth + 1) + return + if kind == "object" and keys <= {"properties", "required", "additionalProperties"}: + fields = node.get("properties", {}) + required = node.get("required", []) + if ( + not fields + or node.get("additionalProperties", False) is not False + or len(fields) != len(required) + or set(fields) != set(required) + ): + raise ValueError("Decisions records require fixed, required fields") + self.records[path] = set(fields) + for name, field_schema in fields.items(): + visit(field_schema, (*path, name), depth + 1) + return + if keys in ({"enum"}, {"const"}, {"anyOf"}) or (kind == "null" and not keys): + leaf = _Leaf("choice", _choices(node)) + elif kind == "boolean" and not keys: + leaf = _Leaf("boolean", []) + elif kind in ("integer", "number") and keys == {"minimum", "maximum"}: + lo, hi = node["minimum"], node["maximum"] + if any( + type(v) not in (int, float) or not abs(v) <= 2**53 - 1 or int(v) != v + for v in (lo, hi) + ) or not 0 < hi - lo <= (254 if kind == "integer" else 9): + raise ValueError("Unsupported Decisions bounds") + if kind == "integer": + leaf = _Leaf("choice", list(range(int(lo), int(hi) + 1))) + else: + leaf = _Leaf( + "probability" if (lo, hi) == (0, 1) else "score", [], int(lo), int(hi - lo) + ) + else: + raise ValueError("Unsupported Decisions output schema") + self.leaves[path] = leaf + if len(leaf.values) == 1: + return + if len(self.questions) >= 400: + raise ValueError("Decisions supports at most 400 questions") + instructions = question + if path: + instructions += "\nField " + json.dumps(path) + if node.get("description"): + instructions += "\n" + node["description"] + q: dict[str, Any] = { + "name": f"field_{len(self.questions) + 1}" if path else "decision", + "instructions": instructions, + } + if leaf.kind == "choice": + plain = all(type(v) in (bool, str) for v in leaf.values) + q.update( + type="choice", + choices=[ + {"value": v} + if plain + else {"value": f"value_{i}", "description": json.dumps(v)} + for i, v in enumerate(leaf.values) + ], + ) + elif leaf.kind == "score": + q.update( + type="score", + levels=[{"label": str(leaf.minimum + i)} for i in range(leaf.width + 1)], + ) + else: + q["type"] = "predicate" + self.questions.append(q) + + visit(schema, (), 0) + + def validate(self, value: Any) -> None: + def check(item: Any, path: tuple[str, ...]) -> None: + if path in self.records: + if type(item) is not dict or item.keys() != self.records[path]: + raise ValueError("Invalid decision record") + for name, child in item.items(): + check(child, (*path, name)) + else: + self.leaves[path].validate(item) + + check(value, ()) + + def choice(self, value: Any) -> Any: + return next(v for v in self.leaves[()].values if _key(v) == _key(value)) + + def decode(self, answers: list[Any]) -> Any: + result: dict[str, Any] = {} + pairs = iter(zip(self.questions, answers, strict=True)) + for path, leaf in self.leaves.items(): + value = leaf.values[0] if len(leaf.values) == 1 else leaf.decode(*next(pairs)) + if not path: + return value + node = result + for part in path[:-1]: + node = node.setdefault(part, {}) + node[path[-1]] = value + return result diff --git a/src/agents/_decision_types.py b/src/agents/_decision_types.py new file mode 100644 index 0000000000..6cca6f0614 --- /dev/null +++ b/src/agents/_decision_types.py @@ -0,0 +1,102 @@ +from __future__ import annotations + +from collections.abc import Sequence +from dataclasses import dataclass, field +from typing import Any, Protocol, TypeVar, overload, runtime_checkable + +from .exceptions import _data_redacted_error_boundary +from .usage import Usage + +DecisionInput = str | Sequence[dict[str, Any]] +_T = TypeVar("_T") + + +@dataclass(frozen=True, kw_only=True) +class DecisionRequest: + """A question, explicit evidence and the JSON schema of the requested value.""" + + question: str = field(repr=False) + input: DecisionInput = field(repr=False) + output_schema: dict[str, Any] = field(repr=False) + + +@dataclass(frozen=True, kw_only=True) +class DecisionResponse: + """A JSON value and optional metadata. Missing usage is unknown.""" + + value: Any = field(repr=False) + usage: Usage | None = None + request_id: str | None = None + model: str | None = None + + +@runtime_checkable +class DecisionProvider(Protocol): + """Answer one decision without changing the conversation or executing tools.""" + + async def get_decision(self, request: DecisionRequest) -> DecisionResponse: ... + + +class _Decider: + @overload + async def decide( + self, + question: str, + *, + input: DecisionInput, + provider: DecisionProvider | None = None, + choices: None = None, + output_type: None = None, + ) -> bool: ... + + @overload + async def decide( + self, + question: str, + *, + input: DecisionInput, + provider: DecisionProvider | None = None, + choices: Sequence[_T], + output_type: None = None, + ) -> _T: ... + + @overload + async def decide( + self, + question: str, + *, + input: DecisionInput, + provider: DecisionProvider | None = None, + choices: None = None, + output_type: type[_T], + ) -> _T: ... + + @overload + async def decide( + self, + question: str, + *, + input: DecisionInput, + provider: DecisionProvider | None = None, + choices: None = None, + output_type: Any, + ) -> Any: ... + + @_data_redacted_error_boundary + async def decide( + self, + question: str, + *, + input: DecisionInput, + provider: DecisionProvider | None = None, + choices: Sequence[Any] | None = None, + output_type: Any = None, + ) -> Any: + """Answer from explicit input only. Omit choices and output_type for a boolean. + + A tool, request filter or final output policy may use its live context. A provider + override applies to this call only. Decision usage is separate from run usage. + """ + from .decisions import _decide + + return await _decide(self, question, input, provider, choices, output_type) diff --git a/src/agents/_run_state_agent_identity.py b/src/agents/_run_state_agent_identity.py index d4505959fa..fbaabe1269 100644 --- a/src/agents/_run_state_agent_identity.py +++ b/src/agents/_run_state_agent_identity.py @@ -4,17 +4,21 @@ 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 from ._tool_identity import get_function_tool_namespace, get_function_tool_qualified_name from .agent import Agent +from .exceptions import UserError 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,8 +30,66 @@ ShellTool, ) +_DECISION_PREFIX = "decision:" -def _iter_agent_graph(initial_agent: Agent[Any]) -> Iterator[Agent[Any]]: + +_PATH_PREFIX = "decision:path:" + + +def _is_decision_identity(value: object) -> bool: + return isinstance(value, str) and ( + value.startswith(_PATH_PREFIX) + or 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] + + +# Only accepted transfers belong here. Filters can erase every model-facing receipt. +_DecisionPath = tuple[tuple[Agent[Any], tuple[_DecisionHandoff[Any], str] | None], ...] + + +def _path_key(key: str, selected: bool) -> str: + # Ordinary names and protected identities belong to different domains. + return hashlib.sha256( + ("selected:" if selected else "ordinary:").encode() + key.encode() + ).hexdigest() + + +def _encode_decision_path(path: _DecisionPath, keys: Mapping[int, str]) -> str: + return _PATH_PREFIX + ".".join( + _path_key(keys[id(agent)], selection is not None) for agent, selection in path + ) + + +def _decode_decision_path( + identity: str, agents: Mapping[str, Agent[Any]], root: Agent[Any] +) -> _DecisionPath: + if not identity.startswith(_PATH_PREFIX): + return () + keys = identity[len(_PATH_PREFIX) :].split(".") + bindings = _decision_bindings(root) + lookup = {_path_key(key, id(agent) in bindings): agent for key, agent in agents.items()} + if len(keys) != len(set(keys)) or any(key not in lookup for key in keys): + return () + path = tuple((lookup[key], bindings.get(id(lookup[key]))) for key in keys) + return path if any(binding for _, binding in path) else () + + +def _ordinary_target(route: Any) -> Any: + ref = getattr(route, "_agent_ref", None) + return ref() if callable(ref) else getattr(route, "agent", route) + + +def _iter_agent_graph( + initial_agent: Agent[Any], *, include_tools: bool = True, include_decisions: bool = True +) -> Iterator[Agent[Any]]: """Yield agents reachable from the starting agent in breadth-first order.""" queue: deque[Agent[Any]] = deque([initial_agent]) seen_agent_ids: set[int] = set() @@ -41,6 +103,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 include_decisions and 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 @@ -92,6 +158,8 @@ def _iter_agent_graph(initial_agent: Agent[Any]) -> Iterator[Agent[Any]]: if handoff_agent is not None and handoff_agent_name: queue.append(cast(Agent[Any], handoff_agent)) + if not include_tools: + continue # Include agent-as-tool instances so nested approvals can be restored. tools = getattr(current, "tools", None) if tools: @@ -489,6 +557,38 @@ def _has_ambiguous_hook_identities(initial_agent: Agent[Any]) -> bool: ) +def _decision_bindings(root: Agent[Any]) -> dict[int, tuple[_DecisionHandoff[Any], str]]: + """Require a unique incoming route for each protected checkpoint identity.""" + bindings: dict[int, tuple[_DecisionHandoff[Any], str]] = {} + ordinary = {id(root)} + for source in _iter_agent_graph(root): + for route in source.handoffs: + if isinstance(route, _DecisionHandoff): + if route._source is not source: + continue + names = ( + h.tool_name if isinstance(h, Handoff) else Handoff.default_tool_name(h) + for h in source.handoffs + ) + if sum(name == route.tool_name for name in names) != 1: + raise UserError("Give each decision handoff a unique tool_name on its source.") + for label, (target, _) in route._roster.items(): + if id(target) in bindings: + raise UserError("Create a separate specialist for each decision label.") + bindings[id(target)] = (route, label) + else: + ordinary.add(id(_ordinary_target(route))) + for tool in source.tools: + if getattr(tool, "_is_agent_tool", False): + ordinary.add(id(getattr(tool, "_agent_instance", None))) + if ordinary.intersection(bindings): + raise UserError( + "A decision specialist cannot also be a root, agent tool or ordinary handoff " + "target. Create a separate specialist for each route." + ) + return bindings + + 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 +632,20 @@ 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 = _decision_bindings(initial_agent) + if bindings: + source_keys = {id(agent): key for key, agent in agent_identity_map.items()} + for key, target in list(agent_identity_map.items()): + if id(target) in bindings: + route, label = bindings[id(target)] + edge = (source_keys[id(route._source)], route.tool_name, label) + data = _stable_identity_text([key, [edge]]) + 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/agent.py b/src/agents/agent.py index 0243d79d07..2ced1d287d 100644 --- a/src/agents/agent.py +++ b/src/agents/agent.py @@ -10,13 +10,14 @@ from dataclasses import dataclass, field from functools import wraps from itertools import chain -from typing import TYPE_CHECKING, Any, Generic, Literal, TypeAlias, cast +from typing import TYPE_CHECKING, Annotated, Any, Generic, Literal, TypeAlias, cast from openai.types.responses.response_prompt_param import ResponsePromptParam -from pydantic import BaseModel, TypeAdapter, ValidationError +from pydantic import BaseModel, Field, TypeAdapter, ValidationError from typing_extensions import NotRequired, TypedDict from . import _debug +from ._decision_types import DecisionProvider, _Decider from ._tool_identity import get_tool_approval_item_call_id from .agent_output import AgentOutputSchemaBase from .agent_tool_input import ( @@ -91,7 +92,7 @@ class ContinueWithFeedback: @dataclass(frozen=True) -class ProposedFinalOutput(Generic[TContext]): +class ProposedFinalOutput(_Decider, Generic[TContext]): """A proposed final output from one SDK model turn. Treat its contents as read-only.""" agent: Agent[TContext] @@ -340,18 +341,8 @@ async def _check_tool_enabled(tool: Tool) -> bool: @dataclass -class Agent(AgentBase, Generic[TContext]): - """An agent is an AI model configured with instructions, tools, guardrails, handoffs and more. - - We strongly recommend passing `instructions`, which is the "system prompt" for the agent. In - addition, you can pass `handoff_description`, which is a human-readable description of the - agent, used when the agent is used inside tools/handoffs. - - Agents are generic on the context type. The context is a (mutable) object you create. It is - passed to tool functions, handoffs, guardrails, etc. - - See `AgentBase` for base parameters that are shared with `RealtimeAgent`s. - """ +class _AgentFields(AgentBase, Generic[TContext]): + """Fields shared by the released Agent and SandboxAgent constructors.""" instructions: ( str @@ -444,6 +435,26 @@ class Agent(AgentBase, Generic[TContext]): """Whether to reset the tool choice to the default value after a tool has been called. Defaults to True. This ensures that the agent doesn't enter an infinite loop of tool usage.""" + +@dataclass +class Agent(_AgentFields[TContext], _Decider): + """An agent is an AI model configured with instructions, tools, guardrails, handoffs and more. + + We strongly recommend passing `instructions`, which is the "system prompt" for the agent. In + addition, you can pass `handoff_description`, which is a human-readable description of the + agent, used when the agent is used inside tools/handoffs. + + Agents are generic on the context type. The context is a (mutable) object you create. It is + passed to tool functions, handoffs, guardrails, etc. + + See `AgentBase` for base parameters that are shared with `RealtimeAgent`s. + """ + + decisions: Annotated[DecisionProvider | None, Field(exclude=True)] = field( + default=None, kw_only=True, repr=False, compare=False + ) + """Borrowed provider for typed decisions on this agent and its callbacks.""" + if TYPE_CHECKING: def __init__( @@ -475,6 +486,8 @@ def __init__( | ToolsToFinalOutputFunction ) = "run_llm_again", reset_tool_choice: bool = True, + *, + decisions: DecisionProvider | None = None, ) -> None: ... def __post_init__(self): @@ -994,6 +1007,9 @@ def _nested_approvals_status( resume_state._context.usage = context.usage if run_result is None: + from .decisions import _delegate_decisions + + _delegate_decisions(self, context, nested_context) if on_stream is not None: stream_handler = on_stream run_result_streaming = Runner.run_streamed( diff --git a/src/agents/decisions.py b/src/agents/decisions.py new file mode 100644 index 0000000000..b8e1f52786 --- /dev/null +++ b/src/agents/decisions.py @@ -0,0 +1,582 @@ +"""Typed Decisions and specialist handoffs.""" + +from __future__ import annotations + +import asyncio +import json +import math +from collections.abc import AsyncIterator, Callable, Mapping, Sequence +from contextlib import asynccontextmanager +from contextvars import ContextVar +from copy import deepcopy +from typing import Any, Literal, TypeVar, cast + +from openai import AsyncOpenAI +from pydantic import BaseModel, ConfigDict, Field, TypeAdapter + +from . import _debug +from ._decision_schema import _Plan +from ._decision_types import DecisionInput, DecisionProvider, DecisionRequest, DecisionResponse +from ._public_agent import get_public_agent +from ._redaction import current_redactor +from ._run_state_agent_identity import _decision_bindings, _DecisionHandoff, _iter_agent_graph +from .agent import Agent +from .exceptions import UserError, _data_redacted_error_boundary, _mark_error_data_redacted +from .handoffs import Handoff, HandoffInputFilter +from .run_context import RunContextWrapper +from .usage import Usage + +__all__ = [ + "DecisionError", + "DecisionInput", + "DecisionProvider", + "DecisionRequest", + "DecisionResponse", + "OpenAIDecisions", + "decision_handoff", +] + +_T = TypeVar("_T") +_CHOICE_COUNTS = range(2, 256) + + +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, + ): + if reason not in ("refusal", "invalid_response"): + raise ValueError("Unknown decision failure") + super().__init__("Decision refused" if reason == "refusal" else "Invalid decision response") + self.reason = reason + metadata = _metadata(request_id, model, usage) + self.request_id: str | None = metadata["request_id"] + self.model: str | None = metadata["model"] + self.usage: Usage | None = metadata["usage"] + + +def _usage(value: Any) -> Usage | None: + if not isinstance(value, (dict, Usage)): + return None + + def count(name: str) -> Any: + return value.get(name) if isinstance(value, dict) else getattr(value, name) + + inp, out, total = (count(k) for k in ("input_tokens", "output_tokens", "total_tokens")) + if any(type(n) is not int or n < 0 for n in (inp, out, total)) or inp + out != total: + return None + usage = Usage(requests=1, input_tokens=inp, output_tokens=out, total_tokens=total) + for field, key, bound in ( + ("input_tokens_details", "cached_tokens", inp), + ("input_tokens_details", "cache_write_tokens", inp), + ("output_tokens_details", "reasoning_tokens", out), + ): + details = count(field) + n = details.get(key, 0) if isinstance(details, dict) else getattr(details, key, 0) + if type(n) is not int or not 0 <= n <= bound: + return None + setattr(getattr(usage, field), key, n) + return usage + + +def _metadata(request_id: Any, model: Any, usage: Any) -> dict[str, Any]: + def identifier(v: Any) -> str | None: + return ( + v + if current_redactor() is None and type(v) is str and len(v) <= 256 and v.isprintable() + else None + ) + + return { + "request_id": identifier(request_id), + "model": identifier(model), + "usage": _usage(usage), + } + + +def _read_answer(raw: Any, plan: _Plan) -> DecisionResponse | DecisionError: + request_id = raw.headers.get("x-request-id") + metadata = _metadata(request_id, None, None) + try: + data = raw.http_response.json() + metadata = _metadata(request_id, data.get("model"), data.get("usage")) + answers = data["answers"] + if not isinstance(answers, list) or len(answers) != len(plan.questions): + return DecisionError("invalid_response", **metadata) + for question, answer in zip(plan.questions, answers, strict=True): + if answer["name"] != question["name"]: + return DecisionError("invalid_response", **metadata) + if answer["type"] == "refusal": + return DecisionError("refusal", **metadata) + if answer["type"] != question["type"]: + return DecisionError("invalid_response", **metadata) + return DecisionResponse(value=plan.decode(answers), **metadata) + except (ValueError, KeyError, AttributeError, TypeError, RecursionError, OverflowError): + return DecisionError("invalid_response", **metadata) + + +def _evidence(question: str, input: DecisionInput) -> DecisionInput: + if not isinstance(question, str) or not question.strip(): + raise ValueError("A nonblank question is required.") + if not isinstance(input, str): + if ( + not isinstance(input, Sequence) + or isinstance(input, (bytes, bytearray)) + or any(not isinstance(v, dict) for v in input) + ): + raise TypeError("Decision input must be text or a sequence of input items.") + input = json.loads(json.dumps(list(input), allow_nan=False)) + return input + + +class OpenAIDecisions: + """Use the generated Decisions service without retries. Only owned clients are closed.""" + + def __init__(self, *, client: AsyncOpenAI | None = None): + if client is not None and not isinstance(client, AsyncOpenAI): + raise TypeError("Expected an AsyncOpenAI client.") + if not getattr(AsyncOpenAI, "decisions", None): + raise ValueError("Install an OpenAI client with Decisions support.") + self._client = client + self._owned = client is None + self._closed = False + + async def __aenter__(self) -> OpenAIDecisions: + if self._closed: + raise RuntimeError("Decisions provider is closed") + return self + + async def __aexit__(self, *args: Any) -> None: + await self.aclose() + + async def aclose(self) -> None: + self._closed = True + if self._owned and self._client is not None: + await self._client.close() + + async def get_decision(self, request: DecisionRequest) -> DecisionResponse: + if self._closed: + raise RuntimeError("Decisions provider is closed") + evidence = _evidence(request.question, request.input) + plan = _Plan(request.question, request.output_schema) + if not plan.questions: + return DecisionResponse(value=plan.decode([]), usage=Usage()) + if self._client is None: + self._client = AsyncOpenAI() + resource = self._client.with_options(max_retries=0).decisions + response = _read_answer( + await resource.with_raw_response.create( + model="gpt-6-luna", + input=cast(Any, evidence), + questions=cast(Any, plan.questions), + ), + plan, + ) + if isinstance(response, DecisionError): + raise response + return response + + +def _provider(value: Any) -> DecisionProvider: + if value is None: + raise ValueError("Configure Agent.decisions or supply a decision provider.") + if not callable(getattr(value, "get_decision", None)): + raise TypeError("Expected a DecisionProvider with get_decision().") + return cast(DecisionProvider, value) + + +class _DecisionRun: + """Snapshot this run's handoff graph. Nested runners capture a separate root.""" + + def __init__(self, root: Agent[Any], tracing_disabled: bool, context: object): + parent = _run.get() + scope = _scope.get() + self.parents: tuple[_DecisionRun, ...] = () + if parent and scope and scope.delegate: + agent, owner = scope.delegate + if agent is root and owner is context: + scope.delegate = None + self.parents = (parent, *parent.parents) + self.root: Agent[Any] | None = root + self.tracing_disabled = tracing_disabled + self.providers: dict[int, tuple[Agent[Any], DecisionProvider | None]] = {} + self.scopes: set[_Scope] = set() + self.live = True + for agent in _iter_agent_graph(root, include_tools=False): + provider = getattr(agent, "decisions", None) + if provider is None: + provider = getattr(root, "decisions", None) + if any(isinstance(h, _DecisionHandoff) and h._source is agent for h in agent.handoffs): + _provider(provider) + self.providers[id(agent)] = agent, provider + + @asynccontextmanager + async def bind(self) -> AsyncIterator[None]: + token = _run.set(self) + callback = _scope.set(None) + try: + yield + finally: + self.live = False + _scope.reset(callback) + _run.reset(token) + self.root = None + self.providers.clear() + scopes = tuple(self.scopes) + for scope in scopes: + scope.live = False + scope.cancel(tuple(scope.pending)) + interrupted = False + for scope in scopes: + try: + await scope.close(tuple(scope.pending)) + except asyncio.CancelledError: + interrupted = True + if interrupted: + raise asyncio.CancelledError + + +_run: ContextVar[_DecisionRun | None] = ContextVar("decision_run", default=None) + + +def _record_transfer( + context: RunContextWrapper[Any], + source: Agent[Any], + target: Agent[Any], + handoff: Handoff[Any, Any], +) -> None: + path = context._decision_path + if not path: + if not isinstance(handoff, _DecisionHandoff) and not _decision_bindings(source): + return + path = ((source, None),) + if path[-1][0] is not source: + raise UserError("Decision specialist unavailable. Check the original route.") + # An ordinary checkpoint omits earlier hops. The invocation still owns its root. + run = _run.get() + if run is not None and target is run.root: + context._decision_path = () + return + for index, (agent, _) in enumerate(path): + if agent is target: + context._decision_path = path[: index + 1] + return + selection = None + if isinstance(handoff, _DecisionHandoff): + label = next(k for k, (agent, _) in handoff._roster.items() if agent is target) + selection = (handoff, label) + context._decision_path = (*path, (target, selection)) + + +def _selected(agent: Any) -> DecisionProvider | None: + run = _run.get() + if run is None: + return getattr(agent, "decisions", None) + entry = run.providers.get(id(agent)) + return entry[1] if entry is not None and entry[0] is agent else None + + +class _Scope: + def __init__(self, owner: object, provider: DecisionProvider | None): + self.delegate: tuple[Agent[Any], object] | None = None + self.owner = owner + self.provider = provider + self.loop = asyncio.get_running_loop() + self.live = True + self.pending: dict[asyncio.Task[Any], bool] = {} + + def check(self, owner: object) -> None: + if ( + not self.live + or self.owner is not owner + or self.loop is not asyncio.get_running_loop() + or _scope.get() is not self + ): + raise RuntimeError("Decisions require the exact live callback context.") + + def cancel(self, tasks: tuple[asyncio.Task[Any], ...]) -> None: + for t in tasks: + if not t.done() and not self.pending[t]: + self.pending[t] = True + t.cancel() + + async def close(self, tasks: tuple[asyncio.Task[Any], ...]) -> None: + self.cancel(tasks) + interrupted = False + for t in tasks: + while not t.done(): + try: + await asyncio.wait((t,)) + except asyncio.CancelledError: + interrupted = True + if not t.cancelled(): + t.exception() + self.pending.pop(t, None) + if interrupted: + raise asyncio.CancelledError + + +_scope: ContextVar[_Scope | None] = ContextVar("decision_callback", default=None) + + +def _delegate_decisions(agent: Agent[Any], owner: object, context: object) -> None: + # Only the nested Runner created by Agent.as_tool shares cancellation ownership. + scope = _scope.get() + if scope is not None and scope.owner is owner: + scope.delegate = (agent, context) + + +@asynccontextmanager +async def _bind_decisions(owner: object, agent: Any) -> AsyncIterator[None]: + scope = _Scope(owner, _selected(agent)) + run = _run.get() + runs = (run, *run.parents) if run is not None else () + for active in runs: + scope.live = scope.live and active.live + active.scopes.add(scope) + token = _scope.set(scope) + try: + yield + finally: + scope.live = False + _scope.reset(token) + try: + await scope.close(tuple(scope.pending)) + finally: + for active in runs: + active.scopes.discard(scope) + + +def _record(response: DecisionResponse | DecisionError) -> None: + from .tracing import custom_span, get_current_trace + + run = _run.get() + if (run is not None and run.tracing_disabled) or get_current_trace() is None: + return + try: + metadata = _metadata(response.request_id, response.model, response.usage) + usage = metadata["usage"] + metadata["usage_known"] = usage is not None + metadata["usage"] = ( + None + if usage is None + else {k: getattr(usage, k) for k in ("input_tokens", "output_tokens", "total_tokens")} + ) + metadata["outcome"] = ( + response.reason if isinstance(response, DecisionError) else "completed" + ) + with custom_span("decision.usage", data=metadata): + pass + except Exception: + pass + + +def _validate(response: Any, plan: _Plan, adapter: TypeAdapter[Any] | None) -> Any: + if not isinstance(response, DecisionResponse): + return DecisionError("invalid_response") + try: + plan.validate(response.value) + if adapter is None: + return plan.choice(response.value) + return adapter.validate_json(json.dumps(response.value, allow_nan=False), strict=True) + except (ValueError, TypeError, RecursionError, OverflowError): + return DecisionError( + "invalid_response", **_metadata(response.request_id, response.model, response.usage) + ) + + +async def _decide( + owner: object, + question: str, + input: DecisionInput, + provider: DecisionProvider | None, + choices: Sequence[Any] | None, + output_type: Any, + *, + timeout: float | None = None, +) -> Any: + scope = _scope.get() + if isinstance(owner, Agent): + default = owner.decisions + scope = None + else: + if scope is None: + raise RuntimeError("Decisions require the exact live callback context.") + scope.check(owner) + default = scope.provider + selected = _provider(default if provider is None else provider) + input = _evidence(question, input) + adapter: TypeAdapter[Any] | None = None + if choices is not None: + if output_type is not None: + raise ValueError("choices and output_type are mutually exclusive") + if ( + not isinstance(choices, Sequence) + or isinstance(choices, (str, bytes, bytearray)) + or not 1 <= len(choices) <= 255 + ): + raise ValueError("Expected 1 to 255 distinct choices") + schema = {"enum": list(choices)} + else: + adapter = TypeAdapter(bool if output_type is None else output_type) + schema = adapter.json_schema() + plan = _Plan(question, schema) + request = DecisionRequest(question=question, input=input, output_schema=deepcopy(schema)) + + work = scope or _Scope(owner, selected) + deadline = None if timeout is None else work.loop.time() + timeout + task = asyncio.create_task(selected.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 (deadline is not None and work.loop.time() >= deadline): + raise asyncio.TimeoutError("Decision timed out") + if task.cancelled(): + raise RuntimeError("Decisions request was cancelled") + try: + response = task.result() + value = _validate(response, plan, adapter) + _record(value if isinstance(value, DecisionError) else response) + del response + except DecisionError as error: + _record(error) + if timeout is None: + _mark_error_data_redacted(error) + raise + finally: + await work.close((task,)) + del task + if isinstance(value, DecisionError): + if timeout is None: + _mark_error_data_redacted(value) + raise value + return value + + +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], + *, + 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, + 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. + The primary model supplies the routing evidence. The optional input_filter + changes the selected specialist's history only, after the Decisions request. + Supply fresh context_override on protected reload. Resuming rechecks the + selected grant without another request. Use separate specialist instances + for different labels or ordinary handoffs. + """ + 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") + 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()} + + if len(roster) < 2 or (len(roster) > 255 and is_available is None): + raise ValueError( + "Decisions requires 2 to 255 available labels. Use handoff(target) for one." + ) + if any(agent is source or not name.strip() for agent, name in roster.values()) or len( + {id(agent) for agent, _ in roster.values()} + ) != len(roster): + raise ValueError("Create a separate named specialist for each decision label.") + + 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 available_choices(ctx: RunContextWrapper[_T]) -> list[str]: + labels = [label for label in roster if admitted(ctx, label)] + if len(labels) not in _CHOICE_COUNTS: + return [] + return labels + + def enabled(ctx: RunContextWrapper[_T], agent: Any) -> bool: + return get_public_agent(agent) is source and bool(available_choices(ctx)) + + 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() + + @_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(): + raise ValueError("Decision handoff is unavailable") + async with _bind_decisions(route, source): + answer = await _decide(route, question, evidence, None, choices, None, timeout=timeout) + if not authorized(ctx, answer): + raise ValueError("Selected specialist is unavailable") + return roster[answer][0] + + route: _DecisionHandoff[_T] = _DecisionHandoff( + tool_name=tool_name, + 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, + ) + route._source = source + route._roster = roster + route._can_restore = authorized + return route diff --git a/src/agents/run.py b/src/agents/run.py index eaf6137691..cb033430d3 100644 --- a/src/agents/run.py +++ b/src/agents/run.py @@ -19,6 +19,7 @@ ) from .agent import Agent from .agent_tool_state import set_agent_tool_state_scope +from .decisions import _DecisionRun from .exceptions import ( AgentsException, InputGuardrailTripwireTriggered, @@ -605,6 +606,10 @@ def _prepare_private_input( config: RunConfig, options: RunOptions[TContext], ) -> str | list[TResponseInputItem] | RunState[TContext]: + from ._run_state_agent_identity import _decision_bindings + + if not isinstance(input, RunState): + _decision_bindings(agent) if current_redactor() is None: if isinstance(input, RunState) and input._requires_redaction: error = UserError("Continuing this run requires RunConfig.redact_text.") @@ -693,8 +698,12 @@ async def run( if isinstance(input, RunState) and input._current_agent is not None else starting_agent ) + decisions = _DecisionRun( + starting_agent, run_config.tracing_disabled, kwargs.get("context") + ) with agent_tool_configuration_run(configuration_agent): - result = await self._run_impl(starting_agent, input, **kwargs) + async with decisions.bind(): + result = await self._run_impl(starting_agent, input, **kwargs) require_clean_final_output( result.final_output, result.input, result.new_items ) @@ -777,6 +786,7 @@ async def _run_impl( run_state=run_state, context=context, ) + await run_state._check_pending_specialists(starting_agent, context_wrapper) context_wrapper._resolve_function_approval_owners(starting_agent) validate_resume_policy(run_state, context_wrapper, run_config) await validate_resumed_agent_tools( @@ -2824,6 +2834,9 @@ def run_streamed( if run_config.tracing_disabled else contextlib.nullcontext(), ): + decisions = _DecisionRun( + starting_agent, run_config.tracing_disabled, kwargs.get("context") + ) input = _prepare_private_input(starting_agent, input, run_config, kwargs) budget = _prepare_budget( run_config, starting_agent, input if isinstance(input, RunState) else None @@ -3058,6 +3071,10 @@ def run_streamed( # Kick off the actual agent loop in the background and return the streamed result object. async def run_loop() -> None: + async with decisions.bind(): + await stream() + + async def stream() -> None: with ( redaction_scope(run_config.redact_text), operation_tracing_scope( @@ -3069,6 +3086,8 @@ async def run_loop() -> None: else contextlib.nullcontext(), ): try: + if run_state is not None and is_resumed_state: + await run_state._check_pending_specialists(starting_agent, context_wrapper) if is_resumed_state and run_state is not None: await validate_resumed_agent_tools( run_state, diff --git a/src/agents/run_config.py b/src/agents/run_config.py index 7e465aa021..2ff9b447bd 100644 --- a/src/agents/run_config.py +++ b/src/agents/run_config.py @@ -16,6 +16,7 @@ coerce_dataclass_config, coerce_pydantic_config, ) +from ._decision_types import _Decider from .guardrail import InputGuardrail, OutputGuardrail from .handoffs import HandoffHistoryMapper, HandoffInputFilter from .items import TResponseInputItem @@ -93,7 +94,7 @@ class ModelSelectionData(Generic[TContext]): @dataclass -class CallModelData(Generic[TContext]): +class CallModelData(_Decider, Generic[TContext]): """Data passed to `RunConfig.call_model_input_filter` prior to model call.""" model_data: ModelInputData diff --git a/src/agents/run_context.py b/src/agents/run_context.py index 6e5592aca6..30f227fe1f 100644 --- a/src/agents/run_context.py +++ b/src/agents/run_context.py @@ -43,6 +43,7 @@ from .usage import Usage if TYPE_CHECKING: + from ._run_state_agent_identity import _DecisionPath from .items import ToolApprovalItem, TResponseInputItem from .run_internal.tool_declarations import PreparedTool else: @@ -221,12 +222,14 @@ class RunContextWrapper(Generic[TContext]): ) # Runtime-only state. RunState owns its portable representation. + _decision_path = cast("_DecisionPath", ()) _budget = cast("_BudgetState | None", None) def _for_new_root(self, budget: _BudgetState | None) -> RunContextWrapper[TContext]: - if budget is None and self._budget is None: + if budget is None and self._budget is None and not self._decision_path: return self root = copy.copy(self) + root._decision_path = () root._budget = budget return root diff --git a/src/agents/run_internal/turn_preparation.py b/src/agents/run_internal/turn_preparation.py index efe13b1a35..a04bfd03f0 100644 --- a/src/agents/run_internal/turn_preparation.py +++ b/src/agents/run_internal/turn_preparation.py @@ -78,8 +78,12 @@ async def maybe_filter_model_input( agent=agent, context=context_wrapper.context, ) - maybe_updated = run_config.call_model_input_filter(filter_payload) - updated = await maybe_updated if inspect.isawaitable(maybe_updated) else maybe_updated + from .._public_agent import get_public_agent + from ..decisions import _bind_decisions + + async with _bind_decisions(filter_payload, get_public_agent(agent)): + maybe_updated = run_config.call_model_input_filter(filter_payload) + updated = await maybe_updated if inspect.isawaitable(maybe_updated) else maybe_updated if not isinstance(updated, ModelInputData): raise UserError("call_model_input_filter must return a ModelInputData instance") return updated diff --git a/src/agents/run_internal/turn_resolution.py b/src/agents/run_internal/turn_resolution.py index 82258e84ae..23549ad573 100644 --- a/src/agents/run_internal/turn_resolution.py +++ b/src/agents/run_internal/turn_resolution.py @@ -485,8 +485,11 @@ async def execute_final_output( # Isolate even synchronous cancellation from cancellation of the owning run. async def decide() -> Literal["continue", "finish"] | ContinueWithFeedback: - value = policy(context_wrapper, proposal) - return await value if inspect.isawaitable(value) else value + from ..decisions import _bind_decisions + + async with _bind_decisions(proposal, public_agent): + value = policy(context_wrapper, proposal) + return await value if inspect.isawaitable(value) else value def on_policy_failure(error: BaseException) -> None: if isinstance(error, asyncio.CancelledError): @@ -718,6 +721,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 @@ -760,6 +764,9 @@ def nest_history( source_agent=public_agent, target_agent=new_agent, ) + from ..decisions import _record_transfer + + _record_transfer(context_wrapper, public_agent, new_agent, handoff) new_step_items.append(handoff_output) if handoff_output_committer is not None: _register_tool_call_items(context_wrapper, [handoff_output]) diff --git a/src/agents/run_state.py b/src/agents/run_state.py index a93830a250..232740bff7 100644 --- a/src/agents/run_state.py +++ b/src/agents/run_state.py @@ -48,10 +48,16 @@ _build_agent_identity_keys_by_id, _build_agent_identity_map, _build_agent_map, + _decision_bindings, + _DecisionPath, + _decode_decision_path, + _encode_decision_path, _get_ambiguous_agent_ids, _has_ambiguous_hook_identities, _has_legacy_hook_identity_ambiguity, + _is_decision_identity, _iter_agent_graph, + _ordinary_target, ) from ._tool_identity import ( FunctionToolLookupKey, @@ -1006,6 +1012,109 @@ class RunState(Generic[TContext, TAgent]): reproduce, and it is cleared only once that turn is fully persisted. """ + def _check_specialist( + self, + root: Agent[Any], + context: RunContextWrapper[Any] | None, + *, + restore_error: RunStateValidationErrorFactory | None = None, + ) -> bool: + path = self._context._decision_path if self._context else () + bindings = _decision_bindings(root) + if not path and not bindings: + return False + + def unavailable() -> Exception: + return (restore_error or _default_run_state_validation_error)( + "Decision specialist unavailable. Check the roster and context_override.", UserError + ) + + # An ordinary checkpoint may restart at a later source. It cannot establish + # a protected selection. Only a committed path carries those identities. + start = path[0][0] if path else self._current_agent + if start is not root and not any( + agent is start + for agent in _iter_agent_graph(root, include_tools=False, include_decisions=False) + ): + raise unavailable() + if not path: + return False + if path[-1][0] is not self._current_agent: + raise unavailable() + previous = None + protected = False + for agent, selection in path: + binding = bindings.get(id(agent)) + if selection is None: + if binding is not None or ( + previous is not None + and not any(_ordinary_target(route) is agent for route in previous.handoffs) + ): + raise unavailable() + else: + route, label = selection + if ( + binding is None + or route is not binding[0] + or label != binding[1] + or route._source is not previous + or ( + (restore_error is not None or context is not None) + and not route._can_restore(context, label) + ) + ): + raise unavailable() + protected = True + previous = agent + return protected + + async def _check_pending_specialists( + self, root: Agent[Any], context: RunContextWrapper[Any] + ) -> bool: + from ._tool_identity import ( + get_function_tool_lookup_key_for_call, + get_function_tool_lookup_keys, + ) + from .agent_tool_state import get_agent_tool_resume_state, peek_agent_tool_run_result + from .tool import FunctionTool, _function_tool_enabled + + protected = self._check_specialist(root, context) + for action in getattr(self._last_processed_response, "functions", ()): + delegate = action.function_tool + if not delegate._is_agent_tool: + continue + result = peek_agent_tool_run_result( + action.tool_call, scope_id=self._agent_tool_state_scope_id + ) + child = get_agent_tool_resume_state(result) + if child is None and result is not None and result.interruptions: + child = result.to_state() + if child is None or child._starting_agent is None: + continue + owner = copy.copy(child._context or context) + owner.context, owner.usage = context.context, context.usage + if not await child._check_pending_specialists(child._starting_agent, owner): + continue + key = get_function_tool_lookup_key_for_call(action.tool_call) + agent = self._current_agent + bindings = ( + [ + tool + for tool in agent.tools + if isinstance(tool, FunctionTool) + and key in get_function_tool_lookup_keys(tool) + and await _function_tool_enabled(tool, context, agent) + ] + if agent is not None + else [] + ) + if len(bindings) != 1 or bindings[0]._agent_instance is not child._starting_agent: + raise UserError( + "A pending decision specialist requires the same enabled agent tool." + ) + protected = True + return protected + def __init__( self, context: RunContextWrapper[TContext], @@ -2089,6 +2198,15 @@ def _serialize_snapshot( cast(Agent[Any], self._current_agent), agent_identity_keys_by_id=agent_identity_keys_by_id, ) + if ( + self._starting_agent is not None + and self._context._decision_path + and self._check_specialist(self._starting_agent, None) + ): + assert agent_identity_keys_by_id is not None + current_agent_entry["identity"] = _encode_decision_path( + self._context._decision_path, agent_identity_keys_by_id + ) generated_items = self._merge_generated_items_with_processed() result = { @@ -2712,6 +2830,8 @@ def _validate_pending_approvals( response = state.get("last_processed_response") if not isinstance(response, dict): response = {} + if nested and _has_pending_specialist(state): + required_children.add(id(state)) approvals = response.get("native_approvals") if approvals: # Only the root session has a claimed checkpoint. A nested state cannot @@ -3371,11 +3491,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, @@ -3402,10 +3539,17 @@ 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, required_children=required_children, @@ -3414,7 +3558,7 @@ async def _restore_pending_nested_agent_tool_runs( except _BudgetCheckpointError: raise except Exception: - if strict_context: + if strict_context or specialist: raise logger.warning( "Failed to deserialize nested agent run state for tool call %s.", @@ -3442,6 +3586,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, defer_mcp_discovery: bool = False, @@ -3785,6 +3930,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, @@ -3994,6 +4140,18 @@ def _resolve_agent_from_data( if resolved is not None: return resolved resolved = agent_map.get(agent_name) + if ( + resolved is not None + and agent_identity_map + and any( + agent is resolved and _is_decision_identity(key) + for key, agent in agent_identity_map.items() + ) + ): + # A specialist name alone cannot establish the original route and label. + raise validation_error_factory( + "Decision specialist unavailable. Check the roster and context_override.", UserError + ) return resolved if resolved is not None else fallback_agent return fallback_agent @@ -4485,12 +4643,26 @@ async def _build_run_state_from_json( agent_map = _build_agent_map(initial_agent) current_agent_data = state_json["current_agent"] - current_agent = _resolve_agent_from_data( - current_agent_data, - agent_map, - agent_identity_map=agent_identity_map, - validation_error_factory=validation_error_factory, + identity = ( + current_agent_data.get("identity") if isinstance(current_agent_data, Mapping) else None ) + path: _DecisionPath = () + current_agent: Agent[Any] | None + if isinstance(identity, str) and _is_decision_identity(identity): + path = _decode_decision_path(identity, agent_identity_map, initial_agent) + if not path or current_agent_data.get("name") != path[-1][0].name: + raise validation_error_factory( + "Run state references an agent identity that is not present in the restored graph", + UserError, + ) + current_agent = path[-1][0] + else: + current_agent = _resolve_agent_from_data( + current_agent_data, + agent_map, + agent_identity_map=agent_identity_map, + validation_error_factory=validation_error_factory, + ) if current_agent is None: raise validation_error_factory("Run state agent not found in agent map", UserError) @@ -4563,6 +4735,7 @@ 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", {})) + context._decision_path = path saved_invocations = context_data.get("tool_invocations", {}) if ( (schema_major, schema_minor) < (1, 23) @@ -4686,6 +4859,11 @@ async def _build_run_state_from_json( [dict(item) if isinstance(item, Mapping) else item for item in pending_input_raw], ) state._model_responses = _deserialize_model_responses(state_json.get("model_responses", [])) + state._check_specialist( + initial_agent, + context if context_override is not None else None, + restore_error=validation_error_factory, + ) serialized_generated_items = state_json.get("generated_items", []) state._generated_items, generated_source_indexes = _deserialize_items_with_source_indexes( serialized_generated_items, @@ -4714,6 +4892,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, defer_mcp_discovery=state._requires_redaction, @@ -5892,6 +6071,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/src/agents/sandbox/sandbox_agent.py b/src/agents/sandbox/sandbox_agent.py index 2021c5f109..eaec4d8142 100644 --- a/src/agents/sandbox/sandbox_agent.py +++ b/src/agents/sandbox/sandbox_agent.py @@ -6,7 +6,7 @@ from .._config_coercion import coerce_pydantic_config from .._public_agent import get_public_agent -from ..agent import Agent +from ..agent import Agent, _AgentFields from ..run_context import RunContextWrapper, TContext from .capabilities import Capability from .capabilities.capabilities import Capabilities @@ -14,6 +14,7 @@ from .types import User if TYPE_CHECKING: + from .._decision_types import DecisionProvider from ..agent import MCPConfig, StopAtTools, ToolsToFinalOutputFunction from ..agent_output import AgentOutputSchemaBase from ..guardrail import InputGuardrail, OutputGuardrail @@ -28,12 +29,8 @@ @dataclass -class SandboxAgent(Agent[TContext]): - """An `Agent` with sandbox-specific configuration. - - Runtime transport details such as the sandbox client, client options, and live session are - provided at run time through `RunConfig(sandbox=...)`, not stored on the agent itself. - """ +class _SandboxFields(_AgentFields[TContext]): + """Sandbox fields in released dataclass order.""" default_manifest: Manifest | None = None """Default sandbox manifest for new sessions created by `Runner` sandbox execution. @@ -65,6 +62,17 @@ class SandboxAgent(Agent[TContext]): default=(), init=False, repr=False, compare=False ) + +# Dataclasses collect bases in reverse MRO. Keep the sandbox fields before +# newer keyword-only Agent options while retaining Agent behavior. +@dataclass +class SandboxAgent(Agent[TContext], _SandboxFields[TContext]): + """An `Agent` with sandbox-specific configuration. + + Runtime transport details such as the sandbox client, client options, and live session are + provided at run time through `RunConfig(sandbox=...)`, not stored on the agent itself. + """ + if TYPE_CHECKING: def __init__( @@ -107,6 +115,8 @@ def __init__( ) = None, capabilities: Sequence[Capability] = ..., run_as: User | dict[str, Any] | str | None = None, + *, + decisions: DecisionProvider | None = None, ) -> None: ... async def get_all_tools(self, run_context: RunContextWrapper[TContext]) -> list[Tool]: diff --git a/src/agents/tool.py b/src/agents/tool.py index 61e1374b0f..0e9fc60f79 100644 --- a/src/agents/tool.py +++ b/src/agents/tool.py @@ -2364,15 +2364,24 @@ async def _invoke_function_tool_with_metadata( """Invoke a function tool and identify default SDK-generated timeout outputs.""" _consume_function_tool_default_failure(context) invoke_context = _get_function_tool_invoke_context(function_tool, context) + + async def invoke() -> Any: + from ._public_agent import get_public_agent + from .decisions import _bind_decisions + + async with _bind_decisions( + invoke_context, get_public_agent(context.agent) if context.agent else None + ): + return await function_tool.on_invoke_tool(cast(Any, invoke_context), arguments) + timeout_seconds = function_tool.timeout_seconds if timeout_seconds is None: - output = await function_tool.on_invoke_tool(cast(Any, invoke_context), arguments) + output = await invoke() return _FunctionToolInvocationResult( output, is_sdk_generated_error=_consume_function_tool_default_failure(context), ) - invoke = functools.partial(function_tool.on_invoke_tool, cast(Any, invoke_context), arguments) tool_task: asyncio.Future[Any] = asyncio.ensure_future( _protect_selected_task(invoke) if context._edit_text is not None else invoke() ) diff --git a/src/agents/tool_context.py b/src/agents/tool_context.py index 4a9d9a0694..59e4860434 100644 --- a/src/agents/tool_context.py +++ b/src/agents/tool_context.py @@ -5,6 +5,7 @@ from openai.types.responses import ResponseFunctionToolCall +from ._decision_types import _Decider from ._tool_identity import get_tool_call_namespace, tool_trace_name from ._tool_invocation import tool_invocation_identity_and_scope from .agent_tool_state import ( @@ -43,7 +44,7 @@ def _assert_must_pass_tool_arguments() -> str: @dataclass(eq=False) -class ToolContext(RunContextWrapper[TContext]): +class ToolContext(RunContextWrapper[TContext], _Decider): """The context of a tool call.""" tool_name: str = field(default_factory=_assert_must_pass_tool_name) diff --git a/tests/test_decisions.py b/tests/test_decisions.py new file mode 100644 index 0000000000..3b7171dc9d --- /dev/null +++ b/tests/test_decisions.py @@ -0,0 +1,1135 @@ +"""Decisions at the explicit-input, client, callback and Runner boundaries.""" + +import asyncio +import json +from dataclasses import replace +from types import SimpleNamespace +from typing import Any + +import httpx2 +import pytest +from openai import AsyncOpenAI + +from agents import ( + Agent, + RunConfig, + RunContextWrapper, + RunHooks, + Runner, + RunState, + SQLiteSession, + handoff, +) +from agents.decisions import DecisionError, OpenAIDecisions, decision_handoff +from agents.decorators import tool +from agents.exceptions import UserError +from agents.extensions.handoff_filters import remove_all_tools +from agents.testing import ModelStep, ScriptedModel, assistant_message, function_call + +CONFIG = RunConfig(tracing_disabled=True) + + +class Peer: + """Offline transport for the generated Decisions resource.""" + + def __init__(self, value="blue"): + if not hasattr(AsyncOpenAI, "decisions"): + pytest.skip("This client has no Decisions resource.") + self.requests = [] + self.value = value + self.client = AsyncOpenAI( + api_key="synthetic", + base_url="https://fixture.invalid/v1", + http_client=httpx2.AsyncClient( + transport=httpx2.MockTransport(self.respond), trust_env=False + ), + ) + + async def respond(self, request): + assert request.url.path == "/v1/decisions" + self.requests.append(json.loads(request.content)) + if self.value == "transport": + return httpx2.Response(500, json={}) + answer: dict[str, Any] = { + "name": "decision", + "type": "choice", + "choice": self.value, + "confidence": 1.0, + "probabilities": [ + {"value": c["value"], "probability": float(c["value"] == self.value)} + for c in self.requests[-1]["questions"][0]["choices"] + ], + } + if self.value == "refusal": + answer = {"name": "decision", "type": "refusal", "refusal": "private"} + return httpx2.Response( + 200, + headers={"x-request-id": "request"}, + json={ + "model": "fixture", + "answers": [answer], + "usage": { + "input_tokens": 5, + "output_tokens": 2, + "total_tokens": 7, + "input_tokens_details": {"cached_tokens": 0, "cache_write_tokens": 0}, + "output_tokens_details": {"reasoning_tokens": 0}, + }, + }, + ) + + +class BlockingPeer(Peer): + """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() + 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: + # 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() + return await super().respond(request) + + +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) + + +def test_openai_single_target_suggests_ordinary_handoff(): + source = source_agent() + with pytest.raises(ValueError, match=r"handoff\(target\)"): + source.decisions = OpenAIDecisions(client=Peer().client) + decision_handoff(source, 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 = Peer("blue") + if routed: + source = source_agent() + source.decisions = OpenAIDecisions(client=provider.client) + route = decision_handoff( + source, + question="Which?", + targets={"blue": target, "red": Agent(name="Red")}, + 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")]]) + source = Agent(name="Source", model=model) + targets = {str(i): Agent(name=str(i)) for i in range(max(2, count))} + client = Peer().client + source.decisions = OpenAIDecisions(client=client) + route = decision_handoff( + source, + question="Which?", + targets=targets, + is_available=lambda ctx, label: int(label) < count, + ) + source.handoffs.append(route) + await run(source, False) + assert model.calls[0].handoffs == ([route] if 2 <= count <= 255 else []) + + +@pytest.mark.parametrize("stream", [False, True]) +async def test_openai_handoff_revoked_after_catalog_skips_provider(stream, monkeypatch): + source = source_agent() + targets = {"blue": Agent(name="Blue", model=ScriptedModel()), "red": Agent(name="Red")} + + class Hooks(RunHooks): + async def on_llm_end(self, context, agent, response): + del targets["red"] + + provider = Peer() + source.decisions = OpenAIDecisions(client=provider.client) + source.handoffs.append(decision_handoff(source, question="Which?", targets=targets)) + with pytest.raises(ValueError, match="unavailable"): + await run(source, stream, hooks=Hooks()) + assert not provider.requests + assert isinstance(source.model, ScriptedModel) + assert len(source.model.calls) == 1 and source.model.calls[0].handoffs + + +@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 = Peer("blue") + targets = {"red": red, "blue": blue} + source.decisions = OpenAIDecisions(client=provider.client) + route = decision_handoff( + source, + question="Which?", + targets=targets, + is_available=lambda ctx, label: label == "red" or 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 == 0 + 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]["questions"][0]["choices"] == [{"value": "red"}, {"value": "blue"}] + + +async def test_restore_rebuilt_roster_binds_label_and_agent_without_reselection(): + provider = Peer("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.decisions = OpenAIDecisions(client=provider.client) + source.handoffs.append( + decision_handoff( + source, question="Which?", targets={label: target, "red": Agent(name="Red")} + ) + ) + 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", + "timeout_before_dispatch", + "cancel", + ], +) +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.decisions = OpenAIDecisions(client=provider.client) + source.handoffs.append( + decision_handoff( + source, + timeout=0.01 if timeout else 30, + question="Which?", + targets=targets, + is_available=lambda ctx, label: ctx.context["allowed"], + ) + ) + task = asyncio.create_task(run(source, False, context=context)) + try: + if not timeout: + 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 timeout: + error = asyncio.TimeoutError + else: + task.cancel() + error = asyncio.CancelledError + if error in (ValueError, DecisionError): + provider.release.set() + with pytest.raises(error): + await task + 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: + 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 = Peer("blue") + source.decisions = OpenAIDecisions(client=provider.client) + source.handoffs.append( + decision_handoff( + source, + question="Which?", + targets={"blue": Agent(name="Blue"), "red": Agent(name="Red")}, + ) + ) + with pytest.raises(ValueError, match="routing input"): + await run(source, False) + 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) + + provider = Peer("refusal" if failure == "refusal" else "unknown") + + source.decisions = OpenAIDecisions(client=provider.client) + handoff = decision_handoff( + source, question="Which?", targets={"blue": Agent(name="Blue"), "red": Agent(name="Red")} + ) + 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 == "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)) + + +async def test_immediate_stream_cancellation_drains_late_selection(): + source = source_agent() + model = ScriptedModel() + provider = BlockingPeer() + source.decisions = OpenAIDecisions(client=provider.client) + source.handoffs.append( + decision_handoff( + source, + question="Which?", + targets={"blue": Agent(name="Blue", model=model), "red": Agent(name="Red")}, + ) + ) + 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 + + +@pytest.mark.parametrize("stream", [False, True]) +async def test_primary_can_answer_without_selection_and_clones_need_their_own_route(stream): + provider = Peer("blue") + model = ScriptedModel( + [ + [assistant_message("direct")], + [assistant_message("direct")], + [function_call("select_specialist", {"input": "evidence"}, call_id="clone")], + [function_call("select_specialist", {"input": "evidence"}, call_id="transfer")], + ] + ) + source = Agent(name="Source", model=model) + original = Agent(name="Blue", model=ScriptedModel([[assistant_message("original")]])) + source.decisions = OpenAIDecisions(client=provider.client) + route = decision_handoff( + source, question="Which?", targets={"blue": original, "red": Agent(name="Red")} + ) + source.handoffs.append(route) + shallow = source.clone() + assert shallow.handoffs is source.handoffs + for agent in (source, shallow): + assert (await run(agent, stream)).final_output == "direct" + assert len(model.calls[0].handoffs) == 1 and not model.calls[1].handoffs + assert not provider.requests + + clone = source.clone(handoffs=[]) + alternate = Agent(name="Blue", model=ScriptedModel([[assistant_message("alternate")]])) + clone.decisions = OpenAIDecisions(client=provider.client) + clone.handoffs.append( + decision_handoff( + clone, question="Which?", targets={"blue": alternate, "red": Agent(name="Red")} + ) + ) + assert source.handoffs == [route] + assert (await run(clone, stream)).last_agent is alternate + assert (await run(source, stream)).last_agent is original + assert len(provider.requests) == 2 + + +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 = Peer("unknown") + source.decisions = OpenAIDecisions(client=provider.client) + route = decision_handoff( + source, question="Which?", targets={"blue": Agent(name="Blue"), "red": Agent(name="Red")} + ) + 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 == 0 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", "timeout_before_dispatch", "refusal", "invalid"] +) +async def test_selection_failure_keeps_completed_tool_receipt( + stream, approve_first, failure, monkeypatch +): + effects = [] + + before_dispatch = failure == "timeout_before_dispatch" + timeout = before_dispatch or failure == "timeout" + + class Failing(BlockingPeer): + async def respond(self, request): + effects.append("select") + if timeout: + return await super().respond(request) + 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: + 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.decisions = OpenAIDecisions(client=peer.client) + source.handoffs.append( + decision_handoff( + source, + timeout=0.01 if timeout else 30, + question="Which?", + targets={"blue": Agent(name="Blue", model=specialist), "red": Agent(name="Red")}, + ) + ) + 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: 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": + assert str(caught.value) == "Decisions request was cancelled" + 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" + 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() + + +@pytest.mark.parametrize("stream", [False, True]) +async def test_nested_specialist_uses_fresh_context_and_owns_approval(stream): + effects = [] + provider = Peer("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")]]), + ) + source.decisions = OpenAIDecisions(client=provider.client) + route = decision_handoff( + source, + question="Which?", + targets={"blue": target, "red": Agent(name="Red")}, + is_available=lambda ctx, label: label == "red" or 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 + + +@pytest.mark.parametrize("stream", [False, True]) +@pytest.mark.parametrize("mode", ["memory", "loaded", "session"]) +@pytest.mark.parametrize("nested", [False, True]) +async def test_resume_rechecks_only_selected_grant_before_any_effect(stream, mode, nested): + from agents.memory.resumable_session import ResumableSession + from tests.memory.test_resumable_session import MemoryStore + + effects = [] + + @tool(needs_approval=True) + def record() -> str: + effects.append("record") + return "done" + + source = source_agent() + blue = Agent( + name="Blue", + model=ScriptedModel([[function_call("record", {}, call_id="effect")]]), + tools=[record], + tool_use_behavior="stop_on_first_tool", + ) + targets = {"blue": blue, "red": Agent(name="Red")} + peer = Peer() + grants = {"blue", "red"} + source.decisions = OpenAIDecisions(client=peer.client) + route = decision_handoff( + source, question="Which?", targets=targets, is_available=lambda ctx, label: label in grants + ) + source.handoffs.append(route) + root = source + if nested: + delegate = source.as_tool("ask", "Ask") + sibling = Agent(name="Other").as_tool("ask", "Other", is_enabled=False) + root = Agent( + name="Manager", + model=ScriptedModel( + [ + [function_call("ask", {"input": "work"}, call_id="child")], + [assistant_message("done")], + ] + ), + tools=[delegate, sibling], + ) + store = MemoryStore() + session = await ResumableSession.create(store) if mode == "session" else None + state = (await run(root, stream, context={}, session=session)).to_state() + if session: + state = await session.load_state(root, context_override={}) + elif mode == "loaded": + state = await RunState.from_string(root, state.to_string(), context_override={}) + grants.clear() + state.approve(state.get_interruptions()[0]) + before = store.records.copy() + with pytest.raises(UserError, match="specialist unavailable"): + await run(root, stream, state) + grants.add("blue") + source.handoffs.clear() + with pytest.raises(UserError): + await run(root, stream, state) + assert not effects and store.records == before + source.handoffs.append(route) + if nested: + for enabled, other in [(False, False), (True, True), (False, True)]: + delegate.is_enabled, sibling.is_enabled = enabled, other + with pytest.raises(UserError, match="same enabled agent tool"): + await run(root, stream, state) + assert not effects and store.records == before and len(peer.requests) == 1 + delegate.is_enabled, sibling.is_enabled = True, False + assert (await run(root, stream, state)).final_output == "done" + assert effects == ["record"] and len(peer.requests) == 1 + + +@pytest.mark.parametrize("stream", [False, True]) +@pytest.mark.parametrize("other", ["plain", "handoff", "decision"]) +async def test_shared_specialist_rejected_before_primary_inference(stream, other): + source = source_agent() + peer = Peer() + blue = Agent(name="Blue") + + def route(name): + source.decisions = OpenAIDecisions(client=peer.client) + return decision_handoff( + source, + question="Which?", + tool_name=name, + targets={"blue": blue, "red": Agent(name="Red")}, + ) + + source.handoffs.append(route("select_specialist")) + source.handoffs.append( + blue if other == "plain" else handoff(blue) if other == "handoff" else route("second") + ) + with pytest.raises(UserError, match="separate specialist"): + await run(source, stream) + assert isinstance(source.model, ScriptedModel) + assert not source.model.calls and not peer.requests + + +def test_invalid_permanent_configuration(monkeypatch): + client = Peer().client + blue = Agent(name="Blue") + targets = {"blue": blue, "red": Agent(name="Red")} + + def build(roster=targets): + source = source_agent() + source.decisions = OpenAIDecisions(client=client) + return decision_handoff(source, question="Which?", targets=roster) + + with pytest.raises(ValueError, match="separate"): + build(roster={"a": blue, "b": blue}) + with pytest.raises(ValueError, match="255"): + build(roster={str(i): Agent(name=str(i)) for i in range(256)}) + monkeypatch.setattr(AsyncOpenAI, "decisions", None, raising=False) + with pytest.raises(ValueError, match="Decisions support"): + build() + + +async def test_transport_error_has_no_retry(): + from openai import InternalServerError + + peer = Peer("transport") + source = source_agent() + source.decisions = OpenAIDecisions(client=peer.client) + source.handoffs.append( + decision_handoff( + source, question="Which?", targets={"a": Agent(name="A"), "b": Agent(name="B")} + ) + ) + with pytest.raises(InternalServerError): + await run(source, False) + assert len(peer.requests) == 1 + + +@pytest.mark.parametrize("stream", [False, True]) +async def test_selector_names_must_be_unique_before_inference(stream): + source = source_agent() + peer = Peer() + for _ in range(2): + source.decisions = OpenAIDecisions(client=peer.client) + source.handoffs.append( + decision_handoff( + source, + question="Which?", + targets={"blue": Agent(name="Blue"), "red": Agent(name="Red")}, + ) + ) + with pytest.raises(UserError, match="unique tool_name"): + await run(source, stream) + assert isinstance(source.model, ScriptedModel) + assert not source.model.calls and not peer.requests + + +@pytest.mark.parametrize("stream", [False, True]) +async def test_inconsistent_distribution_cannot_transfer(stream): + class Inconsistent(Peer): + async def respond(self, request): + data = (await super().respond(request)).json() + for entry in data["answers"][0]["probabilities"]: + entry["probability"] = 0.9 + return httpx2.Response(200, json=data) + + peer = Inconsistent() + source = source_agent() + model = ScriptedModel() + source.decisions = OpenAIDecisions(client=peer.client) + source.handoffs.append( + decision_handoff( + source, + question="Which?", + targets={label: Agent(name=label, model=model) for label in ("blue", "red")}, + ) + ) + with pytest.raises(DecisionError) as caught: + await run(source, stream) + assert caught.value.reason == "invalid_response" + assert len(peer.requests) == 1 and not model.calls + + +@pytest.mark.parametrize("stream", [False, True]) +@pytest.mark.parametrize("loaded", [False, True]) +@pytest.mark.parametrize("nested", [False, True]) +@pytest.mark.parametrize("filtered", [False, True]) +async def test_descendant_pause_rechecks_each_selected_grant(stream, loaded, nested, filtered): + history_filter = remove_all_tools if filtered else None + effects = [] + + @tool(needs_approval=True) + def record() -> str: + effects.append("record") + return "done" + + peer = Peer() + requests = [] + + def scripted(name, args, call_id): + model = ScriptedModel([[function_call(name, args, call_id=call_id)]]) + requests.append(model) + return model + + leaf = Agent( + name="leaf", + tools=[record], + model=scripted("record", {}, "effect"), + tool_use_behavior="stop_on_first_tool", + ) + specialist = Agent( + name="specialist", + handoffs=[handoff(leaf, input_filter=history_filter)], + model=scripted("transfer_to_leaf", {}, "ordinary"), + ) + first = Agent( + name="first", + decisions=OpenAIDecisions(client=peer.client), + model=scripted("select_specialist", {"input": "evidence"}, "first"), + ) + second = Agent( + name="second", model=scripted("select_specialist", {"input": "evidence"}, "second") + ) + for source, selected in [(first, second), (second, specialist)]: + + def grant(ctx, label, key=source.name): + return ( + ctx.context.get(key, False) if label == "blue" else ctx.context.get("other", False) + ) + + other = Agent(name="other_" + source.name, handoffs=[leaf]) + source.handoffs.append( + decision_handoff( + source, + question="Which?", + targets={"blue": selected, "red": other}, + is_available=grant, + input_filter=history_filter, + ) + ) + first.handoffs.append(leaf) + root = first + if nested: + root = Agent( + name="manager", + tools=[first.as_tool("ask", "Ask")], + model=ScriptedModel( + [ + [function_call("ask", {"input": "work"}, call_id="child")], + [assistant_message("done")], + ] + ), + ) + current = {"first": True, "second": True, "other": True} + state = (await run(root, stream, context=current)).to_state() + if loaded: + saved = state.to_string() + route = first.handoffs.pop(0) + with pytest.raises(UserError): + await RunState.from_string(root, saved, context_override=current) + first.handoffs.insert(0, route) + with pytest.raises(UserError, match="unavailable"): + await RunState.from_string(root, saved) + with pytest.raises(UserError, match="unavailable"): + await RunState.from_string(root, saved, context_override={"second": True}) + current = current.copy() + state = await RunState.from_string(root, saved, context_override=current) + state.approve(state.get_interruptions()[0]) + current["other"] = False + route = first.handoffs.pop(0) + with pytest.raises(UserError, match="unavailable"): + await run(root, stream, state) + first.handoffs.insert(0, route) + for key in ("first", "second"): + current[key] = False + with pytest.raises(UserError, match="unavailable"): + await run(root, stream, state) + assert not effects and all(len(model.calls) == 1 for model in requests) + assert len(peer.requests) == 2 + current[key] = True + assert (await run(root, stream, state)).final_output == "done" + assert effects == ["record"] and len(peer.requests) == 2 + + +@pytest.mark.asyncio +async def test_return_to_source_ends_the_specialist_grant(): + @tool(needs_approval=True) + def record() -> str: + return "done" + + peer = Peer() + source = Agent( + name="source", + decisions=OpenAIDecisions(client=peer.client), + model=ScriptedModel( + [ + [function_call("select_specialist", {"input": "work"}, call_id="choose")], + [function_call("record", {}, call_id="record")], + ] + ), + tools=[record], + tool_use_behavior="stop_on_first_tool", + ) + specialist = Agent( + name="specialist", + handoffs=[source], + model=ScriptedModel([[function_call("transfer_to_source", {}, call_id="back")]]), + ) + source.handoffs.append( + decision_handoff( + source, + question="Which?", + targets={"blue": specialist, "red": Agent(name="other")}, + is_available=lambda ctx, label: ctx.context["grant"], + ) + ) + state = (await run(source, False, context={"grant": True})).to_state() + saved = state.to_json() + restored = await RunState.from_json(source, saved, context_override={"grant": False}) + restored.approve(restored.get_interruptions()[0]) + assert (await run(source, False, restored)).final_output == "done" + assert len(peer.requests) == 1 + selected = next(i for i in saved["session_items"] if i["type"] == "handoff_output_item") + del selected["target_agent"]["identity"] + with pytest.raises(UserError, match="unavailable"): + await RunState.from_json(source, saved, context_override={"grant": True}) + + +@pytest.mark.asyncio +async def test_shared_descendant_ordinary_path_does_not_require_a_specialist_grant(): + @tool(needs_approval=True) + def record() -> str: + return "done" + + peer = Peer() + leaf = Agent( + name="leaf", + tools=[record], + tool_use_behavior="stop_on_first_tool", + model=ScriptedModel([[function_call("record", {}, call_id="effect")]]), + ) + source = Agent( + name="source", + decisions=OpenAIDecisions(client=peer.client), + handoffs=[handoff(leaf, input_filter=remove_all_tools)], + model=ScriptedModel([[function_call("transfer_to_leaf", {}, call_id="ordinary")]]), + ) + source.handoffs.append( + decision_handoff( + source, + question="Which?", + targets={"blue": Agent(name="specialist", handoffs=[leaf]), "red": Agent(name="other")}, + is_available=lambda ctx, label: False, + ) + ) + saved = (await run(source, False)).to_state().to_json() + assert saved["current_agent"] == {"name": "leaf"} + state = await RunState.from_json(source, saved) + state.approve(state.get_interruptions()[0]) + assert (await run(source, False, state)).final_output == "done" + assert not peer.requests + saved["current_agent"]["identity"] = "decision:path:invalid" + with pytest.raises(UserError, match="agent identity"): + await RunState.from_json(source, saved) + + +@pytest.mark.asyncio +@pytest.mark.parametrize("stream", [False, True]) +async def test_return_to_root_after_reloading_an_ordinary_checkpoint(stream): + effects = [] + + @tool(needs_approval=True) + def record(step: str) -> str: + effects.append(step) + return step + + peer = Peer() + chooser = Agent( + name="chooser", + tools=[record], + model=ScriptedModel( + [ + [function_call("record", {"step": "first"}, call_id="first")], + [function_call("select_specialist", {"input": "work"}, call_id="choose")], + ] + ), + ) + root = Agent( + name="root", + decisions=OpenAIDecisions(client=peer.client), + handoffs=[handoff(chooser, input_filter=remove_all_tools)], + tools=[record], + tool_use_behavior="stop_on_first_tool", + model=ScriptedModel( + [ + [function_call("transfer_to_chooser", {}, call_id="start")], + [function_call("record", {"step": "last"}, call_id="last")], + ] + ), + ) + specialist = Agent( + name="specialist", + handoffs=[root], + model=ScriptedModel([[function_call("transfer_to_root", {}, call_id="back")]]), + ) + chooser.handoffs.append( + decision_handoff( + chooser, + question="Which?", + targets={"blue": specialist, "red": Agent(name="other")}, + is_available=lambda ctx, label: ctx.context["grant"], + ) + ) + context = {"grant": True} + first = (await run(root, stream, context=context)).to_state() + reopened = await RunState.from_string(root, first.to_string(), context_override=context) + reopened.approve(reopened.get_interruptions()[0]) + last = (await run(root, stream, reopened)).to_state() + assert effects == ["first"] + assert last.to_json()["current_agent"] == {"name": "root"} + last.approve(last.get_interruptions()[0]) + context["grant"] = False + assert (await run(root, stream, last)).final_output == "last" + assert effects == ["first", "last"] and len(peer.requests) == 1 diff --git a/tests/test_typed_decisions.py b/tests/test_typed_decisions.py new file mode 100644 index 0000000000..7703e93da9 --- /dev/null +++ b/tests/test_typed_decisions.py @@ -0,0 +1,520 @@ +"""Typed Decisions, callback ownership and separate usage, without service calls.""" + +import asyncio +import json +from contextlib import nullcontext +from copy import copy +from typing import Annotated, Any, Literal + +import httpx2 +import pytest +from openai import AsyncOpenAI +from pydantic import BaseModel, Field, create_model + +from agents import ( + Agent, + AgentHooks, + DecisionError, + DecisionRequest, + DecisionResponse, + OpenAIDecisions, + RunBudget, + RunConfig, + Runner, + function_tool, +) +from agents.testing import ScriptedModel, assistant_message, function_call +from agents.tool_context import ToolContext +from agents.usage import Usage + + +class Provider: + def __init__(self, value): + self.value = value + self.calls = [] + + async def get_decision(self, request: DecisionRequest) -> DecisionResponse: + self.calls.append(request) + return DecisionResponse(value=self.value, usage=Usage(input_tokens=99, total_tokens=99)) + + +class Queue(BaseModel): + team: Literal["account", "orders"] + urgent: bool + + +class Ticket(BaseModel): + queue: Queue + probability: Annotated[float, Field(ge=0, le=1)] + priority: Annotated[int, Field(ge=0, le=3)] + rating: Annotated[float, Field(ge=-1, le=1)] + + +async def test_real_client_structured_record_and_borrowed_lifetime(): + if not hasattr(AsyncOpenAI, "decisions"): + pytest.skip("This client has no Decisions resource.") + sent = [] + + def respond(req): + data = json.loads(req.content) + sent.append(data) + answers = [] + for q in data["questions"]: + answer = {"name": q["name"], "type": q["type"]} + if q["type"] == "predicate": + answer["probability"] = 0.75 + elif q["type"] == "choice": + values = [c["value"] for c in q["choices"]] + answer.update( + choice=values[1], + confidence=1, + probabilities=[ + {"value": v, "probability": float(i == 1)} for i, v in enumerate(values) + ], + ) + else: + answer.update( + score=1.5, + confidence=0.5, + probabilities=[ + {"label": level["label"], "value": i, "probability": 0.5 if i else 0} + for i, level in enumerate(q["levels"]) + ], + ) + answers.append(answer) + return httpx2.Response(200, json={"answers": answers}) + + async with AsyncOpenAI( + api_key="synthetic", + base_url="https://fixture.invalid/v1", + http_client=httpx2.AsyncClient(transport=httpx2.MockTransport(respond), trust_env=False), + ) as client: + async with OpenAIDecisions(client=client) as provider: + agent = Agent(name="Queue", decisions=provider) + ticket = await agent.decide("Classify", input="order", output_type=Ticket) + assert ticket == Ticket( + queue=Queue(team="orders", urgent=True), probability=0.75, priority=1, rating=0.5 + ) + assert await agent.decide("Urgent?", input="order") is True + assert await agent.decide("Team?", input="order", choices=["only"]) == "only" + assert len(sent) == 2 and all(d["input"] == "order" for d in sent) + assert not client.is_closed() + with pytest.raises(RuntimeError, match="closed"): + await agent.decide("Urgent?", input="") + + +async def test_private_validation_preserves_types_and_rejects_unsupported_before_dispatch(): + provider = Provider(1) + a = Agent(name="check", decisions=provider) + assert a.clone().decisions is provider + fields: dict[str, Any] = {f"k{i}": (bool, ...) for i in range(401)} + for typ in ( + str, + float, + list[bool], + dict[str, bool], + int, + create_model("TooMany", **fields), + ): + with pytest.raises(ValueError): + await a.decide("Classify", input="", output_type=typ) + for choices in ([], [1, 1.0], [True, True], [float("nan")], list(range(256))): + with pytest.raises(ValueError): + await a.decide("Classify", input="", choices=choices) + assert not provider.calls + with pytest.raises(DecisionError) as error: + await a.decide("Allow?", input="private") + assert error.value.usage is not None + assert error.value.reason == "invalid_response" and error.value.usage.total_tokens == 99 + assert await a.decide("Which?", input="", choices=[True, 1]) is provider.value + assert await a.decide("Allow?", input="", provider=Provider(False)) is False + with pytest.raises(DecisionError): + await a.decide( + "Classify", + input="", + output_type=Queue, + provider=Provider({"team": "orders", "urgent": "true"}), + ) + + class Changed: + async def get_decision(self, request): + request.output_schema["enum"].append("other") + return DecisionResponse(value="other") + + with pytest.raises(DecisionError): + await a.decide("Which?", input="", choices=["a", "b"], provider=Changed()) + + +async def finish(agent, stream, **kwargs): + if stream: + result = Runner.run_streamed(agent, "history", **kwargs) + async for _ in result.stream_events(): + pass + return result + return await Runner.run(agent, "history", **kwargs) + + +@pytest.mark.parametrize("stream", [False, True]) +@pytest.mark.parametrize("own", [False, True]) +async def test_exact_tool_and_proposal_owners_after_handoff(stream, own, monkeypatch): + import agents.tracing + + spans = [] + + def span(name, *, data): + spans.append(data) + return nullcontext() + + monkeypatch.setattr(agents.tracing, "custom_span", span) + root, child = Provider(True), Provider(True) + saved = [] + + @function_tool(failure_error_function=None) + async def verify(ctx: ToolContext[None]) -> bool: + saved.append(ctx) + target.decisions = Provider(False) + with pytest.raises(RuntimeError, match="live"): + await copy(ctx).decide("Wrong?", input="") + return await ctx.decide("Check?", input="tool") + + async def policy(run, proposal): + assert not hasattr(run, "decide") + with pytest.raises(RuntimeError, match="live"): + await saved[0].decide("Again?", input="") + saved.append(proposal) + assert await proposal.decide("Ready?", input=proposal.output) + return "finish" + + target = Agent( + name="next", + decisions=child if own else None, + tools=[verify], + hooks=AgentHooks(final_output_policy=policy), + model=ScriptedModel( + [[function_call("verify", {}, call_id="verify")], [assistant_message("done")]] + ), + ) + first = Agent( + name="first", + decisions=root, + handoffs=[target], + model=ScriptedModel([[function_call("transfer_to_next", {}, call_id="transfer_to_next")]]), + ) + result = await finish( + first, + stream, + run_config=RunConfig(tracing_disabled=own, budget=RunBudget(max_model_calls=3)), + ) + assert result.final_output == "done" and result.context_wrapper.usage.total_tokens == 0 + assert [call.input for call in (child if own else root).calls] == ["tool", "done"] + assert not (root if own else child).calls + assert len(spans) == (0 if own else 2) + assert all(s["usage"]["total_tokens"] == 99 and "input" not in s for s in spans) + with pytest.raises(RuntimeError, match="live"): + await saved[-1].decide("Again?", input="") + + +@pytest.mark.parametrize("stream", [False, True]) +async def test_agent_as_tool_has_its_own_grant(stream): + root = Provider(True) + + async def policy(run, proposal): + with pytest.raises(ValueError, match="Configure"): + await proposal.decide("Use parent?", input="") + return "finish" + + child = Agent( + name="child", + model=ScriptedModel([[assistant_message("reply")]]), + hooks=AgentHooks(final_output_policy=policy), + ) + parent = Agent( + name="parent", + decisions=root, + tools=[child.as_tool(tool_name="ask", tool_description="Ask", failure_error_function=None)], + model=ScriptedModel( + [[function_call("ask", {"input": "query"}, call_id="ask")], [assistant_message("done")]] + ), + ) + assert ( + await finish(parent, stream, run_config=RunConfig(tracing_disabled=True)) + ).final_output == "done" + assert not root.calls + + +@pytest.mark.parametrize("stream", [False, True]) +@pytest.mark.parametrize("route", ["direct", "tool", "policy", "handoff"]) +async def test_cancelled_tool_joins_decision_cleanup(stream, route): + from agents.decisions import decision_handoff + + entered, cleaning, release = asyncio.Event(), asyncio.Event(), asyncio.Event() + + class Blocking: + async def get_decision(self, request): + entered.set() + try: + await asyncio.Event().wait() + finally: + cleaning.set() + await release.wait() + return DecisionResponse(value=True) + + @function_tool + async def check(ctx: ToolContext[None]) -> bool: + return await ctx.decide("OK?", input="") + + agent = Agent( + name="check", + decisions=Blocking(), + model=ScriptedModel([[function_call("check", {}, call_id="check")]]), + tools=[check], + ) + if route == "policy": + + async def policy(run, proposal): + await proposal.decide("Ready?", input="") + return "finish" + + agent.hooks = AgentHooks(final_output_policy=policy) + agent.model = ScriptedModel([[assistant_message("done")]]) + if route == "handoff": + selector = decision_handoff( + agent, question="Which?", targets={"a": Agent(name="a"), "b": Agent(name="b")} + ) + agent.handoffs = [selector] + agent.model = ScriptedModel( + [[function_call(selector.tool_name, {"input": "question"}, call_id="select")]] + ) + if route != "direct": + agent = Agent( + name="parent", + tools=[agent.as_tool(tool_name="ask", tool_description="Ask")], + model=ScriptedModel([[function_call("ask", {"input": "question"}, call_id="ask")]]), + ) + config = RunConfig(tracing_disabled=True) + if stream: + result = Runner.run_streamed(agent, "input", run_config=config) + + async def drain(): + async for _ in result.stream_events(): + pass + + task = asyncio.create_task(drain()) + cancel = result.cancel + else: + task = asyncio.create_task(Runner.run(agent, "input", run_config=config)) + cancel = task.cancel + try: + await asyncio.wait_for(entered.wait(), 5) + cancel() + await asyncio.wait_for(cleaning.wait(), 5) + done, _ = await asyncio.wait((task,), timeout=0.35) + assert not done + finally: + release.set() + await asyncio.wait_for(asyncio.gather(task, return_exceptions=True), 5) + + +@pytest.mark.parametrize("stream", [False, True]) +async def test_concurrent_runs_and_detached_callback_requests(stream): + class Pending: + def __init__(self): + self.entered = asyncio.Event() + self.drained = asyncio.Event() + + async def get_decision(self, request): + self.entered.set() + try: + await asyncio.Event().wait() + finally: + self.drained.set() + return DecisionResponse(value=True) + + async def single(value): + pending = Pending() + detached = [] + + async def check(run, proposal): + detached.append( + asyncio.create_task(proposal.decide("Later?", input="", provider=pending)) + ) + await pending.entered.wait() + assert await proposal.decide("OK?", input="") is value + return "finish" + + agent = Agent( + name="same", + decisions=Provider(value), + hooks=AgentHooks(final_output_policy=check), + model=ScriptedModel([[assistant_message("done")]]), + ) + await finish(agent, stream, run_config=RunConfig(tracing_disabled=True)) + assert pending.drained.is_set() + with pytest.raises(asyncio.CancelledError): + await detached[0] + + await asyncio.wait_for(asyncio.gather(single(True), single(False)), 5) + + +@pytest.mark.parametrize("kind", ["score", "choice"]) +@pytest.mark.parametrize("total", [0.4, 1.000001, 1.4]) +async def test_service_distribution_must_sum_to_one(kind, total): + if not hasattr(AsyncOpenAI, "decisions"): + pytest.skip("This client has no Decisions resource.") + + def respond(req): + q = json.loads(req.content)["questions"][0] + answer = {"type": kind, "name": q["name"], "confidence": 0.5} + if kind == "choice": + answer.update( + choice="a", + probabilities=[{"value": v, "probability": total / 2} for v in ("a", "b")], + ) + else: + answer.update( + score=0.5, + probabilities=[ + {"value": i, "label": level["label"], "probability": total / 2} + for i, level in enumerate(q["levels"]) + ], + ) + return httpx2.Response(200, json={"answers": [answer]}) + + async with AsyncOpenAI( + api_key="synthetic", + base_url="https://fixture.invalid/v1", + http_client=httpx2.AsyncClient(transport=httpx2.MockTransport(respond), trust_env=False), + ) as client: + agent = Agent(name="Check", decisions=OpenAIDecisions(client=client)) + typ = Literal["a", "b"] if kind == "choice" else Annotated[float, Field(ge=1, le=2)] + value = agent.decide("Which?", input="", output_type=typ) + if total == 1.000001: + assert await value == ("a" if kind == "choice" else 1.5) + else: + with pytest.raises(DecisionError) as error: + await value + assert error.value.reason == "invalid_response" + + +async def test_decision_span_reports_the_validated_outcome_once(monkeypatch): + import agents.tracing + + spans = [] + + def capture(name, *, data): + assert name == "decision.usage" + spans.append(data) + return nullcontext() + + monkeypatch.setattr(agents.tracing, "custom_span", capture) + + class Refuses: + async def get_decision(self, request): + raise DecisionError("refusal", usage=Usage(input_tokens=1, total_tokens=1)) + + a = Agent(name="checker", decisions=Provider(True)) + with agents.tracing.trace("check"): + assert await a.decide("Secret question?", input="evidence") is True + with pytest.raises(DecisionError): + await a.decide("Secret question?", input="evidence", provider=Provider("secret value")) + with pytest.raises(DecisionError): + await a.decide("Secret question?", input="evidence", provider=Refuses()) + assert [s["outcome"] for s in spans] == ["completed", "invalid_response", "refusal"] + assert [s["usage"]["total_tokens"] for s in spans] == [99, 99, 1] + assert "secret" not in repr(spans).lower() and "evidence" not in repr(spans) + + +async def test_decide_is_async_and_gather_handles_invalid_calls(): + import inspect + + from agents import ProposedFinalOutput + + assert all( + inspect.iscoroutinefunction(cls.decide) for cls in (Agent, ToolContext, ProposedFinalOutput) + ) + a = Agent(name="check", decisions=Provider(True)) + ok, invalid = await asyncio.gather( + a.decide("Pass?", input=""), a.decide("", input=""), return_exceptions=True + ) + assert ok is True and isinstance(invalid, ValueError) + + +@pytest.mark.parametrize("stream", [False, True]) +async def test_request_filter_uses_inherited_provider_on_fresh_owner(stream): + provider = Provider(True) + model = ScriptedModel([[assistant_message("done")]]) + target = Agent(name="next", model=model) + first = Agent( + name="first", + decisions=provider, + handoffs=[target], + model=ScriptedModel([[function_call("transfer_to_next", {}, call_id="transfer")]]), + ) + saved = [] + + async def prepare(data): + if data.agent is first: + saved.append(data.decide("Later?", input="")) + else: + with pytest.raises(RuntimeError, match="live"): + await saved.pop() + if await data.decide("Include instructions?", input="new user"): + data.model_data.instructions = "Explain the next step." + saved.append(data.decide("After exit?", input="")) + return data.model_data + + await finish( + first, stream, run_config=RunConfig(tracing_disabled=True, call_model_input_filter=prepare) + ) + assert model.calls[0].system_instructions == "Explain the next step." + with pytest.raises(RuntimeError, match="live"): + await saved.pop() + assert [call.input for call in provider.calls] == ["new user"] + + +@pytest.mark.asyncio +async def test_sandbox_provider_preserves_released_fields_and_survives_preparation(): + from dataclasses import dataclass, fields, replace + + from agents.sandbox import SandboxAgent, SandboxRunConfig + from agents.testing import scripted_sandbox_session + + @dataclass + class Worker(SandboxAgent): + def __post_init__(self): + super().__post_init__() + + provider = Provider(True) + + async def finish(run, proposal): + assert await proposal.decide("Ready?", input=proposal.output) + return "finish" + + worker = Worker( + name="Worker", + decisions=provider, + capabilities=[], + model=ScriptedModel([[assistant_message("done")]]), + hooks=AgentHooks(final_output_policy=finish), + ) + assert [f.name for f in fields(SandboxAgent) if f.init][-5:] == [ + "default_manifest", + "base_instructions", + "capabilities", + "run_as", + "decisions", + ] + for agent in (Agent(name="Helper", decisions=provider), worker): + assert fields(agent)[-1].kw_only + assert "decisions=" not in repr(agent) + assert agent.clone().decisions is replace(agent).decisions is provider + assert await worker.decide("Ready?", input="start") + result = await Runner.run( + worker, + "start", + run_config=RunConfig( + tracing_disabled=True, sandbox=SandboxRunConfig(session=scripted_sandbox_session()) + ), + ) + assert result.final_output == "done" + assert len(provider.calls) == 2