diff --git a/examples/agent_patterns/estimated_spend.py b/examples/agent_patterns/estimated_spend.py new file mode 100644 index 0000000000..d93b93c6d1 --- /dev/null +++ b/examples/agent_patterns/estimated_spend.py @@ -0,0 +1,170 @@ +"""Estimate reported token spend in application code, without SDK pricing callbacks. + +Run offline with ``python -m examples.agent_patterns.estimated_spend``. +The rates below are fictional dollars per million tokens, not provider prices. +Each job makes one tool-free model call in a separate Runner run. +The application chooses the model and its rates before that run. +This does not implement per-turn model selection inside a run. + +The application stops before the next run after reaching its estimate threshold +or receiving unknown usage. A completed request can exceed the threshold. +This is not a billing cap. Retries, failed requests, hidden native work, tool +charges, caching discounts, and other clients can make actual charges differ. +Exceptions propagate. Reconcile their potentially unreported charges before resuming. +""" + +from __future__ import annotations + +import asyncio +from collections.abc import Mapping, Sequence +from dataclasses import dataclass +from decimal import Decimal +from typing import Any, Literal + +from agents import Agent, ModelSettings, RunConfig, Runner +from agents.models.interface import Model, ModelProvider +from agents.testing import ModelStep, ScriptedModel, assistant_message +from agents.usage import Usage + + +@dataclass(frozen=True) +class Rates: + input_per_million: Decimal + output_per_million: Decimal + + +def estimate_usd(raw_usage: Mapping[str, Any] | None, rates: Rates) -> Decimal | None: + """Estimate Responses-shaped usage. Missing or invalid counts mean unknown, never zero. + + Other provider schemas need their own explicit mapping. + All input tokens use the supplied input rate. + Output includes reasoning tokens without counting them again. + """ + if raw_usage is None: + return None + input_tokens = raw_usage.get("input_tokens") + output_tokens = raw_usage.get("output_tokens") + if ( + type(input_tokens) is not int + or type(output_tokens) is not int + or input_tokens < 0 + or output_tokens < 0 + ): + return None + return ( + Decimal(input_tokens) * rates.input_per_million + + Decimal(output_tokens) * rates.output_per_million + ) / Decimal(1_000_000) + + +@dataclass(frozen=True) +class BatchEstimate: + known_usd: Decimal + outputs: list[Any] + stopped: Literal["completed", "threshold", "unknown_usage"] + + +async def run_batch( + jobs: Sequence[tuple[str, str]], + *, + provider: ModelProvider, + rates: Mapping[str, Rates], + stop_at_usd: Decimal, +) -> BatchEstimate: + """Stop admission of the next job using only estimates from completed responses. + + Model names and rates belong to this application. + Provider aliases or routing changes require matching rate updates. + Keep each run tool-free. Adding a model_selector override also requires + tracking the effective model for pricing. + The caller owns the provider and closes it after the batch. + """ + known_usd = Decimal(0) + outputs: list[Any] = [] + for model_name, prompt in jobs: + if known_usd >= stop_at_usd: + return BatchEstimate(known_usd, outputs, "threshold") + model_rates = rates[model_name] + result = await Runner.run( + Agent( + name="Single answer", + model=model_name, + model_settings=ModelSettings(preserve_raw_usage=True), + ), + prompt, + max_turns=1, + run_config=RunConfig(model_provider=provider, tracing_disabled=True), + ) + outputs.append(result.final_output) + estimates = [ + estimate_usd(response.raw_usage, model_rates) for response in result.raw_responses + ] + known_usd += sum((value for value in estimates if value is not None), Decimal(0)) + if not estimates or any(value is None for value in estimates): + return BatchEstimate(known_usd, outputs, "unknown_usage") + return BatchEstimate(known_usd, outputs, "completed") + + +class DemoProvider(ModelProvider): + """Supply deterministic offline responses through the public testing API.""" + + def __init__(self, models: dict[str, Model]): + self.models = models + + def get_model(self, model_name: str | None) -> Model: + assert model_name is not None + return self.models[model_name] + + +async def main() -> None: + rates = { + "economy": Rates(Decimal("1"), Decimal("2")), + "review": Rates(Decimal("3"), Decimal("6")), + } + provider = DemoProvider( + { + name: ScriptedModel( + [ + ModelStep( + output=[assistant_message(f"Answer from {name}")], + usage=Usage( + requests=1, input_tokens=1000, output_tokens=500, total_tokens=1500 + ), + raw_usage={"input_tokens": 1000, "output_tokens": 500}, + ) + ] + ) + for name in rates + } + ) + unknown_provider = DemoProvider( + {"economy": ScriptedModel([[assistant_message("No usage reported")]])} + ) + try: + result = await run_batch( + [ + ("economy", "Draft an answer"), + ("review", "Review it"), + ("economy", "Another answer"), + ], + provider=provider, + rates=rates, + stop_at_usd=Decimal("0.005"), + ) + print( + f"Known estimate: ${result.known_usd}. Answers: {len(result.outputs)}. Stop: {result.stopped}." + ) + unknown = await run_batch( + [("economy", "Usage unavailable"), ("review", "Do not start")], + provider=unknown_provider, + rates=rates, + stop_at_usd=Decimal("0.005"), + ) + print(f"Known subtotal: ${unknown.known_usd}. Total unknown. Stop: {unknown.stopped}.") + finally: + await provider.aclose() + await unknown_provider.aclose() + + +if __name__ == "__main__": + asyncio.run(main()) diff --git a/examples/agent_patterns/restricted_delegation.py b/examples/agent_patterns/restricted_delegation.py new file mode 100644 index 0000000000..d8e35f4382 --- /dev/null +++ b/examples/agent_patterns/restricted_delegation.py @@ -0,0 +1,105 @@ +"""Restricted SDK delegation with a shared action budget and a separate deadline. + +Run this deterministic example without credentials or network access. Replace the +ScriptedModel instances with production models after retaining the same restrictions. +The tool-start count includes the delegate wrapper and the child's lookup handler. +The deadline cancels the owned Runner task; it is not a token or billing limit. + +The parent grants lookup so the catalog reader can use it. Any other agent sharing +this budget could also use its own lookup handler. To deny all SDK function tools +in another child, pass run_config={"budget": RunBudget(allowed_tools=())} to that +child's as_tool call. The parent keeps its own grants. +""" + +import asyncio + +from openai.types.responses import ( + ResponseFunctionToolCall, + ResponseOutputMessage, + ResponseOutputText, +) + +from agents import Agent, RunBudget, RunConfig, Runner, set_trace_provider +from agents.decorators import tool +from agents.testing import ScriptedModel +from agents.tracing.provider import DefaultTraceProvider + + +def message(text: str) -> ResponseOutputMessage: + return ResponseOutputMessage( + id="answer", + type="message", + role="assistant", + status="completed", + content=[ResponseOutputText(type="output_text", text=text, annotations=[])], + ) + + +@tool +async def lookup(topic: str) -> str: + """Read one entry from the application's approved catalog.""" + return {"release": "The release is ready for review."}.get(topic, "Unknown topic.") + + +async def main() -> None: + # This standalone example has been using no exporter or network clients. + set_trace_provider(DefaultTraceProvider()) + child = Agent( + name="catalog-reader", + tools=[lookup], + model=ScriptedModel( + [ + [ + ResponseFunctionToolCall( + id="lookup", + call_id="lookup", + type="function_call", + name="lookup", + arguments='{"topic":"release"}', + ) + ], + [message("The release is ready for review.")], + ] + ), + ) + delegate = child.as_tool( + "delegate", "Ask the restricted catalog reader", failure_error_function=None + ) + parent = Agent( + name="coordinator", + tools=[delegate], + model=ScriptedModel( + [ + [ + ResponseFunctionToolCall( + id="child", + call_id="child", + type="function_call", + name="delegate", + arguments='{"input":"Check the release."}', + ) + ], + [message("The release is ready for review.")], + ] + ), + ) + config = RunConfig( + budget=RunBudget( + max_outer_requests=4, + max_tool_starts=2, + max_child_runs=1, + max_delegation_depth=1, + allowed_tools=("delegate", "lookup"), + share_with_children=True, + ), + tracing_disabled=True, + ) + # Deadline expiration cancels and awaits this owned run, including its SDK children. + result = await asyncio.wait_for( + Runner.run(parent, "Check the release.", run_config=config), timeout=5 + ) + print(result.final_output) + + +if __name__ == "__main__": + asyncio.run(main()) diff --git a/src/agents/agent.py b/src/agents/agent.py index fb1f7c3697..696143bb1d 100644 --- a/src/agents/agent.py +++ b/src/agents/agent.py @@ -810,7 +810,11 @@ async def _run_agent_impl(context: ToolContext, input_json: str) -> Any: resolved_run_config = run_config if resolved_run_config is None and isinstance(context, ToolContext): resolved_run_config = context.run_config - if resolved_run_config is not None and resolved_run_config.budget is not None: + if ( + resolved_run_config is not None + and resolved_run_config.budget is not None + and not resolved_run_config.budget._controlled_children + ): resolved_run_config = copy.copy(resolved_run_config) resolved_run_config.budget = None tool_state_scope_id = get_agent_tool_state_scope(context) @@ -827,6 +831,8 @@ async def _run_agent_impl(context: ToolContext, input_json: str) -> Any: agent=context.agent, run_config=resolved_run_config, ) + if context._budget is not None and context._budget.controlled_children: + nested_context._budget = context._budget set_agent_tool_state_scope(nested_context, tool_state_scope_id) if should_capture_tool_input: nested_context.tool_input = params_data diff --git a/src/agents/models/openai_responses.py b/src/agents/models/openai_responses.py index 048b2715a2..7937b497c1 100644 --- a/src/agents/models/openai_responses.py +++ b/src/agents/models/openai_responses.py @@ -127,7 +127,6 @@ if TYPE_CHECKING: from ..model_settings import ModelSettings - _USER_AGENT = f"Agents/Python {__version__}" _HEADERS = {"User-Agent": _USER_AGENT} diff --git a/src/agents/run.py b/src/agents/run.py index 69ca620066..f2d9e14f40 100644 --- a/src/agents/run.py +++ b/src/agents/run.py @@ -55,7 +55,7 @@ from .memory.resumable_session import ResumableSession from .models._run_context import ModelToolHooks from .result import RunResult, RunResultStreaming -from .run_budget import _check_resume, _prepare_budget +from .run_budget import _check_resume, _parent_budget, _prepare_budget from .run_config import ( DEFAULT_MAX_TURNS, CallModelData, @@ -343,7 +343,7 @@ async def run( Only the first agent's input guardrails are run. Args: - control: A fresh input handle for corrections during this run. + control: A fresh handle for sending user text to the next scheduled request. starting_agent: The starting agent to run. input: The initial input to the agent. You can pass a single string for a user message, or a list of input items. @@ -369,7 +369,6 @@ async def run( other model providers don't write to the Conversation object, so you'll end up having partial conversations stored. session: A session for automatic conversation history management. - control: A fresh handle for sending user text to the next scheduled request. Returns: A run result containing all the inputs, guardrail results and the output of @@ -561,7 +560,7 @@ def run_streamed( Only the first agent's input guardrails are run. Args: - control: A fresh input handle for corrections during this run. + control: A fresh handle for sending user text to the next scheduled request. starting_agent: The starting agent to run. input: The initial input to the agent. You can pass a single string for a user message, or a list of input items. @@ -580,7 +579,6 @@ def run_streamed( ``previous_response_id`` is supplied yet. conversation_id: The ID of the stored conversation, if any. session: A session for automatic conversation history management. - control: A fresh handle for sending user text to the next scheduled request. Returns: A result object that contains data about the run, as well as a method to @@ -748,7 +746,8 @@ async def _run_impl( run_state: RunState[TContext] | None = ( cast(RunState[TContext], input) if is_resumed_state else None ) - budget = _prepare_budget(run_config, starting_agent, run_state) + parent_budget = _parent_budget(context) + budget = _prepare_budget(run_config, starting_agent, run_state, parent_budget) resolved_reasoning_item_id_policy: ReasoningItemIdPolicy | None = ( run_config.reasoning_item_id_policy if run_config.reasoning_item_id_policy is not None @@ -792,7 +791,12 @@ async def _run_impl( ) context_wrapper._resolve_function_approval_owners(starting_agent) validate_resume_policy(run_state, context_wrapper, run_config) - await _check_resume(run_state, run_config.budget, context_wrapper) + await _check_resume( + run_state, + run_config.budget, + context_wrapper, + parent_budget, + ) context = context_wrapper.context reject_unrecoverable_terminal_state(run_state) @@ -2843,8 +2847,12 @@ def run_streamed( else contextlib.nullcontext(), ): input = _prepare_private_input(starting_agent, input, run_config, kwargs) + parent_budget = _parent_budget(context) budget = _prepare_budget( - run_config, starting_agent, input if isinstance(input, RunState) else None + run_config, + starting_agent, + input if isinstance(input, RunState) else None, + parent_budget, ) # Handle RunState input is_resumed_state = isinstance(input, RunState) @@ -3089,7 +3097,12 @@ async def run_loop() -> None: ): try: if is_resumed_state and run_state is not None: - await _check_resume(run_state, run_config.budget, context_wrapper) + await _check_resume( + run_state, + run_config.budget, + context_wrapper, + parent_budget, + ) if isinstance(session, ResumableRun): await session.begin( input, diff --git a/src/agents/run_budget.py b/src/agents/run_budget.py index 73c41783a7..2d6bfe9527 100644 --- a/src/agents/run_budget.py +++ b/src/agents/run_budget.py @@ -1,10 +1,12 @@ -"""Limits on logical model calls and observed tokens in a Runner run.""" +"""Limits on model admissions and observed response usage in a Runner run.""" from __future__ import annotations import copy -from dataclasses import dataclass +from collections.abc import Iterable, Mapping +from dataclasses import dataclass, field from typing import TYPE_CHECKING, Any, Literal +from uuid import uuid4 from ._redaction import current_redactor, protected_error from .exceptions import ( @@ -17,14 +19,17 @@ from .usage import Usage if TYPE_CHECKING: + from openai.types.responses.response_prompt_param import ResponsePromptParam + from .agent import Agent from .memory import Session + from .model_settings import ModelSettings from .models.interface import Model from .result import RunResultStreaming from .run_config import RunConfig from .run_context import RunContextWrapper from .run_state import RunState - from .tool import Tool + from .tool import FunctionTool, Tool def _valid_limit(value: object) -> bool: @@ -33,47 +38,113 @@ def _valid_limit(value: object) -> bool: @dataclass(frozen=True, kw_only=True) class RunBudget: - """Limits for one Python Runner root, including handoffs and approval resumes. - - Pass the same limits and missing-usage policy on resume:: + """Limits on logical calls, SDK outer requests, observed tokens and SDK tool starts. + + max_model_calls and max_tokens retain the root accounting of the upstream budget: + completed root responses and compactions count, failed attempts do not. Retries, + approval replies and replay add no model calls. max_turns wins a tie. Pass + max_turns=None when a finite max_model_calls should determine the stopping point. + Native sampling through CodexProvider and hosted orchestration remain unsupported. + + max_outer_requests explicitly bounds Python or Codex outer Runner requests. It + counts the same SDK admissions as max_model_calls, never hidden native samples, + physical sends or billing. Model-call limits take precedence over outer-request + limits, then token limits. A response may exceed a token limit and finish the run. + The next admission stops. Requested tools may still run. + + Set include_failed_attempt_usage=True to count known provider-reported failed + attempts in token observations. It defaults to False. Unreported attempt usage + stays unknown and adds no fabricated tokens. This flag adds no call admissions. + missing_usage="stop" rejects the next admission when an observed total is missing + or negative. Set missing_usage="continue" to count only known totals. + Reported zero remains zero. + + Agent tools have independent budgets by default. share_with_children=True shares + every configured dimension through SDK Agent.as_tool descendants. Explicit child + budgets add local ceilings. Each scope's failed-attempt flag determines its own + observations. An opted-in ancestor counts known child failures even if the child's + local flag is False. Children without an explicit budget inherit the parent policy. + max_child_runs, max_delegation_depth and allowed_tools also enable shared children. + + allowed_tools uses bare SDK function names or namespace.name for namespaced + functions, including agent-tool wrappers. Rename tools or namespaces containing + literal dots before using an allowlist. A grant applies to that name in every + agent sharing the budget. If a parent and child register different handlers + as lookup, allowing lookup covers both. Give handlers with different permissions + distinct names or namespaces, or pass a narrower budget to Agent.as_tool. + Each call must pass the local allowlist and every ancestor's allowlist. + Restricted runs reject opaque prompt IDs, raw tool or prompt overrides, + non-function tools and deferred/tool-search routes. + max_tool_starts counts SDK FunctionTool starts, including Agent.as_tool wrappers. + It rejects uncounted SDK custom, local shell, computer and apply-patch handlers. + Provider-owned tools remain outside this counter. Local MCP tools adapted to + FunctionTool use the normal start boundary. + + Slots reserve after approval and input guardrails, before hooks and invocation, + without awaiting between checks and increments. Rejected approvals, blocked input + guardrails and replay add no starts. Failures or cancellation after reservation + do not refund slots. A paused child resumes without another wrapper reservation. + max_child_runs counts admitted child wrappers. Depth zero forbids delegation. + Shared native delegation guarantees remain unsupported even in SDK-only workspace + mode, which does not prevent native child model requests. + + Configure the run and pass the same policy on approval resume:: from agents import RunBudget, RunConfig config = RunConfig(budget=RunBudget(max_model_calls=3, max_tokens=4000)) - Set one or both limits to integers from zero through 2**53 - 1. Zero - blocks the first call. A response can exceed the token limit and still - finish the run. Limits block the next call. Requested tools may still run. - Since max_turns (default 10) wins a tie, pass max_turns=None to Runner - when a finite max_model_calls should determine when the run stops. - - Each admitted model call counts, including follow-ups and corrections. - Retries, approval replies, replay and session compaction add no calls. - Tokens count completed root responses and compactions, excluding failed attempts. - With a token limit, missing or negative totals block the next call. - Set missing_usage="continue" to count only known totals. A provider - that reports zero for missing usage makes it indistinguishable from zero. - - Agent tools and independent runs need their own budgets. A paused child - requires the same unique, enabled tool and budget on resume. Child errors - follow the tool's error policy. Check completed work before retrying. - Native sampling through CodexProvider and hosted multi-agent orchestration - are unsupported. These limits cannot bound physical sends or billing. - Text redaction can replace RunBudgetError with a generic error. + Portable checkpoints preserve consumption and shared parent binding. + A paused child requires the same unique, + enabled binding and policy. Child errors follow the tool's error policy. Check + completed work before retrying. Text redaction can replace budget errors. """ max_model_calls: int | None = None max_tokens: int | None = None missing_usage: Literal["stop", "continue"] = "stop" + max_tool_starts: int | None = None + share_with_children: bool = False + max_child_runs: int | None = None + max_delegation_depth: int | None = None + allowed_tools: tuple[str, ...] | None = None + max_outer_requests: int | None = None + include_failed_attempt_usage: bool = False + + @property + def _controlled_children(self) -> bool: + return ( + self.share_with_children + or self.max_child_runs is not None + or self.max_delegation_depth is not None + or self.allowed_tools is not None + ) def __post_init__(self) -> None: - limits = (self.max_model_calls, self.max_tokens) - if all(limit is None for limit in limits): + limits = ( + self.max_model_calls, + self.max_tokens, + self.max_tool_starts, + self.max_child_runs, + self.max_delegation_depth, + self.max_outer_requests, + ) + if all(limit is None for limit in limits) and self.allowed_tools is None: raise ValueError("RunBudget requires at least one limit.") if any(limit is not None and not _valid_limit(limit) for limit in limits): raise ValueError("RunBudget limits must be integers from zero through 2**53 - 1.") if self.missing_usage not in ("stop", "continue"): raise ValueError("RunBudget.missing_usage must be 'stop' or 'continue'.") + if not isinstance(self.share_with_children, bool): + raise TypeError("RunBudget.share_with_children must be a bool.") + if not isinstance(self.include_failed_attempt_usage, bool): + raise TypeError("RunBudget.include_failed_attempt_usage must be a bool.") + if self.allowed_tools is not None: + if not isinstance(self.allowed_tools, (tuple, list)) or any( + not isinstance(name, str) or not name for name in self.allowed_tools + ): + raise ValueError("RunBudget.allowed_tools requires non-empty SDK tool names.") + object.__setattr__(self, "allowed_tools", tuple(self.allowed_tools)) class _BudgetCheckpointError(UserError): @@ -81,24 +152,42 @@ class _BudgetCheckpointError(UserError): class RunBudgetError(AgentsException): - """A blocked model call. Check code for the reason and limit for the ceiling. + """A blocked admission, with upstream model-call/token errors unchanged. - For run_budget_exceeded, model_calls takes precedence over tokens. - For run_budget_usage_unavailable, limit is None. + For run_budget_exceeded, model_calls takes precedence over outer_requests, + then tokens. For run_budget_usage_unavailable, limit is None. """ def __init__( self, code: Literal["run_budget_exceeded", "run_budget_usage_unavailable"], *, - limit: Literal["model_calls", "tokens"] | None = None, + limit: Literal[ + "model_calls", + "tokens", + "outer_requests", + "tool_starts", + "child_runs", + "delegation_depth", + "tools", + ] + | None = None, ): self.limit = limit self.code = code if code == "run_budget_usage_unavailable": message = 'Unknown usage. Use missing_usage="continue" to count only known totals.' else: - ceiling = "max_model_calls" if limit == "model_calls" else "max_tokens" + ceilings = { + "model_calls": "max_model_calls", + "tokens": "max_tokens", + "outer_requests": "max_outer_requests", + "tool_starts": "max_tool_starts", + "child_runs": "max_child_runs", + "delegation_depth": "max_delegation_depth", + "tools": "allowed_tools", + } + ceiling = ceilings.get(limit or "tokens", "max_tokens") message = ( f"RunBudget.{ceiling} reached. Check completed work before starting a new run." ) @@ -111,8 +200,65 @@ class _BudgetState: requests: int = 0 tokens: int = 0 unavailable: bool = False + tool_starts: int = 0 + child_runs: int = 0 + depth: int = 0 + identity: str = field(default_factory=lambda: uuid4().hex) + parent: _BudgetState | None = field(default=None, repr=False) + parent_identity: str | None = None + + @property + def controlled_children(self) -> bool: + # Portable checkpoints retain the binding before resume reattaches the live parent. + return self.limits._controlled_children or self.parent_identity is not None + + def lineage(self) -> Iterable[_BudgetState]: + current: _BudgetState | None = self + while current is not None: + yield current + current = current.parent + + def reserve_request(self) -> None: + for budget in self.lineage(): + budget.check() + for budget in self.lineage(): + budget.requests += 1 + + def reserve_tool(self, tool: FunctionTool) -> None: + # Check and reserve without awaiting so sibling tasks cannot oversubscribe. + child = tool._is_agent_tool + for budget in self.lineage(): + limits = budget.limits + if ( + limits.allowed_tools is not None + and _allowlist_tool_name(tool) not in limits.allowed_tools + ): + raise RunBudgetError("run_budget_exceeded", limit="tools") + if limits.max_tool_starts is not None and budget.tool_starts >= limits.max_tool_starts: + raise RunBudgetError("run_budget_exceeded", limit="tool_starts") + if child and limits._controlled_children: + if limits.max_child_runs is not None and budget.child_runs >= limits.max_child_runs: + raise RunBudgetError("run_budget_exceeded", limit="child_runs") + if ( + limits.max_delegation_depth is not None + and self.depth + 1 - budget.depth > limits.max_delegation_depth + ): + raise RunBudgetError("run_budget_exceeded", limit="delegation_depth") + for budget in self.lineage(): + budget.tool_starts += 1 + if child: + budget.child_runs += 1 def observe(self, usage: Usage | None) -> None: + for budget in self.lineage(): + budget._observe_local(usage) + + def observe_failed_attempt(self, usage: Usage | None) -> None: + for budget in self.lineage(): + if budget.limits.include_failed_attempt_usage: + budget._observe_local(usage) + + def _observe_local(self, usage: Usage | None) -> None: if self.limits.max_tokens is None: return if ( @@ -128,14 +274,16 @@ def check(self) -> None: limits = self.limits if limits.max_model_calls is not None and self.requests >= limits.max_model_calls: raise RunBudgetError("run_budget_exceeded", limit="model_calls") + if limits.max_outer_requests is not None and self.requests >= limits.max_outer_requests: + raise RunBudgetError("run_budget_exceeded", limit="outer_requests") if limits.max_tokens is not None and self.tokens >= limits.max_tokens: raise RunBudgetError("run_budget_exceeded", limit="tokens") if self.unavailable and limits.missing_usage == "stop": raise RunBudgetError("run_budget_usage_unavailable") def checkpoint(self) -> dict[str, Any]: - # Schema 1.25 stores logical model calls as requests. - return { + # Preserve the exact schema 1.25 payload for budgets using only upstream fields. + data: dict[str, Any] = { "max_requests": self.limits.max_model_calls, "max_tokens": self.limits.max_tokens, "missing_usage": self.limits.missing_usage, @@ -143,42 +291,120 @@ def checkpoint(self) -> dict[str, Any]: "tokens": self.tokens, "unavailable": self.unavailable, } + limits = self.limits + if ( + limits.max_outer_requests is not None + or limits.include_failed_attempt_usage + or limits.max_tool_starts is not None + or limits._controlled_children + or self.parent is not None + or self.parent_identity is not None + ): + data.update( + { + "max_outer_requests": limits.max_outer_requests, + "include_failed_attempt_usage": limits.include_failed_attempt_usage, + "max_tool_starts": limits.max_tool_starts, + "share_with_children": limits.share_with_children, + "max_child_runs": limits.max_child_runs, + "max_delegation_depth": limits.max_delegation_depth, + "allowed_tools": list(limits.allowed_tools) + if limits.allowed_tools is not None + else None, + "tool_starts": self.tool_starts, + "child_runs": self.child_runs, + "depth": self.depth, + "identity": self.identity, + "parent_identity": self.parent.identity + if self.parent is not None + else self.parent_identity, + } + ) + return data @classmethod def restore(cls, data: Any) -> _BudgetState: - if not isinstance(data, dict) or data.keys() != { + required = { "max_requests", "max_tokens", "missing_usage", "requests", "tokens", "unavailable", - }: + } + extension = { + "max_outer_requests", + "include_failed_attempt_usage", + "max_tool_starts", + "share_with_children", + "max_child_runs", + "max_delegation_depth", + "allowed_tools", + "tool_starts", + "child_runs", + "depth", + "identity", + "parent_identity", + } + if not isinstance(data, dict) or data.keys() not in (required, required | extension): raise _BudgetCheckpointError("Invalid run budget checkpoint.") + counters = ("requests", "tokens") + ( + ("tool_starts", "child_runs", "depth") if "identity" in data else () + ) if ( - any(type(data[k]) is not int or data[k] < 0 for k in ("requests", "tokens")) + any(type(data[key]) is not int or data[key] < 0 for key in counters) or type(data["unavailable"]) is not bool ): raise _BudgetCheckpointError("Invalid run budget consumption.") + if "identity" in data and ( + not isinstance(data["identity"], str) + or not data["identity"] + or ( + data["parent_identity"] is not None and not isinstance(data["parent_identity"], str) + ) + ): + raise _BudgetCheckpointError("Invalid run budget identity.") try: limits = RunBudget( max_model_calls=data["max_requests"], max_tokens=data["max_tokens"], missing_usage=data["missing_usage"], + **{ + key: data[key] + for key in ( + "max_outer_requests", + "include_failed_attempt_usage", + "max_tool_starts", + "share_with_children", + "max_child_runs", + "max_delegation_depth", + "allowed_tools", + ) + if key in data + }, ) - except ValueError: + except (TypeError, ValueError): raise _BudgetCheckpointError("Invalid run budget limits.") from None - return cls(limits, data["requests"], data["tokens"], data["unavailable"]) + result = cls(limits, data["requests"], data["tokens"], data["unavailable"]) + for key in ("tool_starts", "child_runs", "depth", "identity", "parent_identity"): + if key in data: + setattr(result, key, data[key]) + return result -def _check_model(model: object) -> None: +def _check_model(model: object, limits: RunBudget | None = None) -> None: from .extensions.experimental.hosted_multi_agent import OpenAIHostedMultiAgentModel from .models.codex import CodexProvider, _CodexModel if isinstance(model, OpenAIHostedMultiAgentModel): raise UserError("RunBudget cannot isolate root usage in hosted multi-agent runs.") - if isinstance(model, (CodexProvider, _CodexModel)): - raise UserError("RunBudget cannot enforce native sampling limits with CodexProvider.") + if isinstance(model, (CodexProvider, _CodexModel)) and limits is not None: + if limits.max_model_calls is not None or limits.max_tokens is not None: + raise UserError("RunBudget cannot enforce native sampling limits with CodexProvider.") + if limits._controlled_children: + raise UserError( + "RunBudget cannot enforce controlled native delegation with CodexProvider." + ) def _tool_budget(tool: Tool) -> RunBudget | None: @@ -188,21 +414,104 @@ def _tool_budget(tool: Tool) -> RunBudget | None: return config.budget if config is not None else None +def _validate_explicit_tool_authority( + settings: ModelSettings, + prompt: ResponsePromptParam | None, + *, + policy_name: str, +) -> None: + """Reject provider-owned tool definitions hidden behind prompt or raw overrides.""" + if prompt is not None: + raise UserError(f"{policy_name} requires explicit SDK tools, not prompt IDs.") + for overrides in (settings.extra_args, settings.extra_body): + if overrides is None: + continue + if not isinstance(overrides, Mapping) or any( + key in overrides for key in ("tools", "prompt", "extra_body") + ): + raise UserError(f"{policy_name} cannot use raw tool or prompt overrides.") + + +def _allowlist_tool_name(tool: Tool) -> str: + """Encode only identities that have a unique spelling in a string allowlist.""" + from ._tool_identity import get_function_tool_lookup_key_for_tool + from .tool import FunctionTool + + if not isinstance(tool, FunctionTool) or tool.defer_loading: + raise UserError( + "RunBudget.allowed_tools supports only SDK FunctionTool handlers without " + "deferred loading. Custom, shell, computer, apply-patch, hosted and tool-search " + "routes cannot enforce this policy." + ) + key = get_function_tool_lookup_key_for_tool(tool) + if key is None or key[0] == "deferred_top_level" or any("." in part for part in key[1:]): + raise UserError( + "RunBudget.allowed_tools requires non-empty tool names and namespaces without " + "literal dots. Use name or namespace.name for each grant." + ) + return ".".join(key[1:]) + + +def _check_restricted_tools( + budget: _BudgetState | None, + tools: Iterable[Tool], + settings: ModelSettings | None = None, + prompt: ResponsePromptParam | None = None, +) -> None: + from .tool import ( + ApplyPatchTool, + ComputerTool, + CustomTool, + LocalShellTool, + ShellTool, + ) + + if budget is None: + return + tools = list(tools) + restricted = any(owner.limits.allowed_tools is not None for owner in budget.lineage()) + counted = any(owner.limits.max_tool_starts is not None for owner in budget.lineage()) + if restricted: + for tool in tools: + _allowlist_tool_name(tool) + from .model_settings import ModelSettings + + _validate_explicit_tool_authority( + settings if settings is not None else ModelSettings(), + prompt, + policy_name="RunBudget.allowed_tools", + ) + if counted and any( + isinstance(tool, (CustomTool, ComputerTool, ApplyPatchTool, LocalShellTool)) + or isinstance(tool, ShellTool) + and tool.executor is not None + for tool in tools + ): + raise UserError( + "RunBudget.max_tool_starts supports SDK FunctionTool handlers only. " + "wrap local custom, shell, computer or apply-patch execution in a FunctionTool. " + "Provider-owned tool activity is outside this counter." + ) + + async def _admit( budget: _BudgetState | None, model: Model, session: Session | None, + tools: Iterable[Tool], *, streamed_result: RunResultStreaming | None = None, + settings: ModelSettings | None = None, + prompt: ResponsePromptParam | None = None, ) -> None: - if budget is None: - return from .run_internal.resumable_session import ResumableRun, checkpoint_streamed_result try: - _check_model(model) - budget.check() - budget.requests += 1 + if budget is not None: + _check_restricted_tools(budget, tools, settings, prompt) + for owner in budget.lineage(): + _check_model(model, owner.limits) + budget.reserve_request() except (RunBudgetError, UserError) as error: if streamed_result is not None: from .run_internal.guardrails import input_guardrail_tripwire_triggered_for_stream @@ -230,8 +539,19 @@ async def _admit( raise +def _effective_limits( + configured: RunBudget | None, parent: _BudgetState | None +) -> RunBudget | None: + if configured is not None: + return configured + return parent.limits if parent is not None else None + + async def _check_resume( - state: RunState[Any], limits: RunBudget | None, context: RunContextWrapper[Any] + state: RunState[Any], + limits: RunBudget | None, + context: RunContextWrapper[Any], + parent: _BudgetState | None = None, ) -> bool: """Validate pending policies and report whether this subtree owns a budget.""" from ._tool_identity import get_function_tool_lookup_key_for_call, get_function_tool_lookup_keys @@ -239,8 +559,15 @@ async def _check_resume( from .tool import FunctionTool, _function_tool_enabled saved = state._context._budget if state._context is not None else None - if (saved.limits if saved is not None else None) != limits: + if (saved.limits if saved is not None else None) != _effective_limits(limits, parent): raise UserError("Resume requires the same RunBudget limits and missing_usage policy.") + if saved is not None and (saved.parent_identity is not None or parent is not None): + if ( + parent is None + or saved.parent_identity != parent.identity + or saved.depth != parent.depth + 1 + ): + raise UserError("A shared child budget requires its original parent budget.") budgeted = saved is not None for action in getattr(state._last_processed_response, "functions", ()): if not action.function_tool._is_agent_tool: @@ -264,7 +591,8 @@ async def _check_resume( ] policies = (_tool_budget(tool) for tool in bindings) policy = next((value for value in policies if value is not None), None) - if await _check_resume(child, policy, context): + child_parent = saved if saved is not None and saved.controlled_children else None + if await _check_resume(child, policy, context, child_parent): owner = state._context if owner is not None and owner is not context: # Agent.as_tool keeps the nested wrapper but forwards application @@ -281,25 +609,53 @@ async def _check_resume( ): raise UserError("A pending RunBudget requires the same unique enabled agent tool.") budgeted = True + if saved is not None and saved.parent_identity is not None: + saved.parent = parent return budgeted +def _parent_budget(context: object) -> _BudgetState | None: + """Only the invoking tool can supply the live parent, including on resume.""" + from .tool_context import ToolContext + + parent = context._budget if isinstance(context, ToolContext) else None + return parent if parent is not None and parent.controlled_children else None + + def _prepare_budget( - config: RunConfig, agent: Agent[Any], state: RunState[Any] | None + config: RunConfig, + agent: Agent[Any], + state: RunState[Any] | None, + inherited: _BudgetState | None, ) -> _BudgetState | None: from .models.interface import Model - limits = config.budget - if limits is None: - return None + limits = _effective_limits(config.budget, inherited) current = ( state._current_agent if state is not None and state._current_agent is not None else agent ) + if limits is None: + return None model = config.model if config.model is not None else current.model - _check_model(model if isinstance(model, Model) else config.model_provider) + _check_model(model if isinstance(model, Model) else config.model_provider, limits) + if inherited is not None: + for owner in inherited.lineage(): + _check_model(model if isinstance(model, Model) else config.model_provider, owner.limits) if state is not None: assert state._context is not None + # A resumed approval can execute before the next model admission checks the tools. + if limits.allowed_tools is not None or ( + inherited is not None + and any(owner.limits.allowed_tools is not None for owner in inherited.lineage()) + ): + for tool in current.tools: + _allowlist_tool_name(tool) return state._context._budget budget = _BudgetState(limits) + if inherited is not None: + budget.parent = inherited + budget.parent_identity = inherited.identity + budget.depth = inherited.depth + 1 + _check_restricted_tools(budget, current.tools) budget.check() return budget diff --git a/src/agents/run_config.py b/src/agents/run_config.py index 5e2d9bb7df..1085c60f60 100644 --- a/src/agents/run_config.py +++ b/src/agents/run_config.py @@ -694,7 +694,7 @@ class RunConfig: """ budget: RunBudget | None = None - """Optional limits on root model calls and observed tokens.""" + """Optional limits on model calls, reported tokens, SDK tools and delegated work.""" model_selector: ModelSelector | None = None """Choose a model by name before each new Runner request, before the input filter. diff --git a/src/agents/run_internal/model_retry.py b/src/agents/run_internal/model_retry.py index 82ddf6ffeb..d51330abdc 100644 --- a/src/agents/run_internal/model_retry.py +++ b/src/agents/run_internal/model_retry.py @@ -371,9 +371,12 @@ def apply_retry_attempt_usage( @contextmanager -def record_failed_attempt_usage_on_error(run_usage: Usage) -> Iterator[dict[int, Usage]]: +def record_failed_attempt_usage_on_error( + run_usage: Usage, reported_usage: dict[int, Usage] | None = None +) -> Iterator[dict[int, Usage]]: """Keep provider-reported usage when the retry loop exits without a model response.""" - reported_usage: dict[int, Usage] = {} + if reported_usage is None: + reported_usage = {} try: yield reported_usage except BaseException: @@ -656,6 +659,8 @@ async def get_response_with_retry( return response except Exception as error: if isinstance(error, ModelBehaviorError) and error._terminal_usage is not None: + if budget is not None: + budget.observe_failed_attempt(error._terminal_usage) reported_usage[request_attempt] = error._terminal_usage if ( not replay_unsafe_request @@ -735,7 +740,11 @@ async def stream_response_with_retry( failed_retry_attempts_out: list[int] | None = None, replay_unsafe_request: bool = False, preview: ApprovedOutput | None = None, + reported_usage: dict[int, Usage] | None = None, + budget: _BudgetState | None = None, ) -> AsyncGenerator[TResponseStreamEvent, None]: + if reported_usage is None: + reported_usage = {} request_attempt = 1 policy_attempt = 1 failed_policy_attempts = 0 @@ -874,6 +883,10 @@ async def stream_response_with_retry( except _StreamAttemptSkipped as skipped: raise skipped.reason from None except BaseException as error: + if isinstance(error, ModelBehaviorError) and error._terminal_usage is not None: + if budget is not None: + budget.observe_failed_attempt(error._terminal_usage) + reported_usage[request_attempt] = error._terminal_usage if isinstance(error, ModelTimeoutError): # The timed owner has already been cancelled and drained. Do not retain its # task, result queues, or previous event in the public timeout traceback frame. diff --git a/src/agents/run_internal/run_loop.py b/src/agents/run_internal/run_loop.py index b48f2fa0a1..b22e4d857a 100644 --- a/src/agents/run_internal/run_loop.py +++ b/src/agents/run_internal/run_loop.py @@ -2609,6 +2609,7 @@ async def raise_if_input_guardrail_tripwire_known() -> None: redact_model_input(filtered, prompt_config) if isinstance(filtered.input, list): filtered.input = deduplicate_input_items_preferring_latest(filtered.input) + if server_conversation_tracker is not None: server_conversation_tracker.validate_pending_input_filter(filtered.input) logger.debug( @@ -2675,6 +2676,7 @@ async def rewind_model_request() -> None: server_conversation_tracker.rewind_input(filtered.input) stream_failed_retry_attempts: list[int] = [0] + stream_reported_usage: dict[int, Usage] = {} compaction_input_digests = prepare_compaction_model_input( session, context_wrapper, filtered.input @@ -2713,7 +2715,15 @@ async def controlled_stream() -> AsyncIterator[TResponseStreamEvent]: preview.retire() await _close_async_iterator_quietly(stream) - await _admit(context_wrapper._budget, model, session, streamed_result=streamed_result) + await _admit( + context_wrapper._budget, + model, + session, + all_tools, + streamed_result=streamed_result, + settings=model_settings, + prompt=prompt_config, + ) preview = ( streamed_result._approved_output.for_turn(streamed_result.current_turn, model) if streamed_result._approved_output is not None and current_redactor() is None @@ -2729,6 +2739,8 @@ async def controlled_stream() -> AsyncIterator[TResponseStreamEvent]: conversation_id=conversation_id, timeout=model_settings.timeout, failed_retry_attempts_out=stream_failed_retry_attempts, + reported_usage=stream_reported_usage, + budget=context_wrapper._budget, replay_unsafe_request=any( isinstance(tool, ProgrammaticToolCallingTool) for tool in all_tools ), @@ -2753,6 +2765,9 @@ async def controlled_stream() -> AsyncIterator[TResponseStreamEvent]: ), ) ) + stack.enter_context( + record_failed_attempt_usage_on_error(context_wrapper.usage, stream_reported_usage) + ) model_events = await stack.enter_async_context(aclosing(retry_stream)) async for event in model_events: stream_event_count += 1 @@ -2794,6 +2809,10 @@ async def controlled_stream() -> AsyncIterator[TResponseStreamEvent]: maybe_response if isinstance(maybe_response, Response) else None, ) if terminal_error._terminal_usage is not None: + if context_wrapper._budget is not None: + context_wrapper._budget.observe_failed_attempt( + terminal_error._terminal_usage + ) context_wrapper.usage.add(terminal_error._terminal_usage) raise terminal_error elif getattr(event, "type", None) in {"error", "response.error"}: @@ -2813,7 +2832,9 @@ async def controlled_stream() -> AsyncIterator[TResponseStreamEvent]: ) if context_wrapper._budget is not None: context_wrapper._budget.observe(usage) - usage = apply_retry_attempt_usage(usage, stream_failed_retry_attempts[0]) + usage = apply_retry_attempt_usage( + usage, stream_failed_retry_attempts[0], stream_reported_usage + ) final_response = ModelResponse( output=terminal_response.output, usage=usage, @@ -3243,7 +3264,14 @@ async def request_response() -> ModelResponse: prompt=prompt_config, ) - await _admit(context_wrapper._budget, model, session) + await _admit( + context_wrapper._budget, + model, + session, + all_tools, + settings=model_settings, + prompt=prompt_config, + ) new_response = await get_response_with_retry( budget=context_wrapper._budget, get_response=request_response, diff --git a/src/agents/run_internal/tool_execution.py b/src/agents/run_internal/tool_execution.py index 10d87b3176..16be50121a 100644 --- a/src/agents/run_internal/tool_execution.py +++ b/src/agents/run_internal/tool_execution.py @@ -2086,6 +2086,8 @@ async def _execute_single_tool_body( self.schema_bypassed_tool_runs.add(id(task_state.tool_run)) return rejected_message + if not is_nested_continuation and self.context_wrapper._budget is not None: + self.context_wrapper._budget.reserve_tool(func_tool) span.start(mark_as_current=True) if not is_nested_continuation: await gather_with_cancel( diff --git a/src/agents/run_state.py b/src/agents/run_state.py index 61ef87ebbf..e0bc010d49 100644 --- a/src/agents/run_state.py +++ b/src/agents/run_state.py @@ -3193,6 +3193,8 @@ def _serialize_pending_nested_agent_tool_runs( strict_context=strict_context, include_tracing_api_key=include_tracing_api_key, ) + except _BudgetCheckpointError: + raise except Exception: if strict_context: raise diff --git a/src/agents/tool_context.py b/src/agents/tool_context.py index 926f89130f..0c3655868e 100644 --- a/src/agents/tool_context.py +++ b/src/agents/tool_context.py @@ -256,6 +256,7 @@ def from_agent_context( run_config=tool_run_config, **base_values, ) + tool_context._budget = context._budget context._share_tool_state_with(tool_context) set_agent_tool_state_scope(tool_context, get_agent_tool_state_scope(context)) return tool_context diff --git a/tests/test_budget_observed_failures.py b/tests/test_budget_observed_failures.py new file mode 100644 index 0000000000..171de5d5ee --- /dev/null +++ b/tests/test_budget_observed_failures.py @@ -0,0 +1,229 @@ +"""Failed-attempt usage is opt-in while successful observations retain upstream semantics.""" + +import pytest +from openai.types.responses import ResponseFailedEvent + +from agents import ( + Agent, + ModelBehaviorError, + ModelRetrySettings, + ModelSettings, + RunBudget, + RunBudgetError, + RunConfig, + Runner, + Usage, +) +from agents.decorators import tool +from agents.models._response_terminal import response_terminal_failure_error +from agents.retry import RetryDecision +from agents.testing import ModelStep, ScriptedModel +from tests.model_test_helpers import get_response_obj +from tests.test_responses import get_function_tool_call, get_text_message + + +async def execute(agent, budget, streamed): + config = RunConfig( + budget=budget, tracing_disabled=True, tool_not_found_behavior="return_error_to_model" + ) + if not streamed: + return await Runner.run(agent, "go", run_config=config) + result = Runner.run_streamed(agent, "go", run_config=config) + async for _ in result.stream_events(): + pass + return result + + +def failure(tokens): + response = get_response_obj([], usage=Usage(requests=1, total_tokens=tokens)) + return response_terminal_failure_error("response.failed", response) + + +def retry_settings(): + return ModelSettings( + retry=ModelRetrySettings( + max_retries=1, + policy=lambda _: RetryDecision(retry=True, delay=0, approve_unsafe_replay=True), + ) + ) + + +@pytest.mark.asyncio +@pytest.mark.parametrize("streamed", [False, True]) +@pytest.mark.parametrize("include_failed", [False, True], ids=["upstream-default", "opt-in"]) +async def test_failed_100_then_retry_1_applies_selected_usage_policy(streamed, include_failed): + # The adapter's terminal-error producer supplies actual failed-response usage. + model = ScriptedModel( + [ + failure(100), + ModelStep( + output=[get_function_tool_call("lookup")], usage=Usage(requests=1, total_tokens=1) + ), + ModelStep(output=[get_text_message("done")], usage=Usage(requests=1, total_tokens=1)), + ] + ) + effects = [] + + @tool + async def lookup() -> str: + effects.append("lookup") + return "found" + + agent = Agent(name="root", model=model, tools=[lookup], model_settings=retry_settings()) + budget = RunBudget(max_tokens=50, include_failed_attempt_usage=include_failed) + if include_failed: + with pytest.raises(RunBudgetError) as caught: + await execute(agent, budget, streamed) + assert caught.value.limit == "tokens" + data = caught.value.run_data + assert data is not None and data.context_wrapper._budget is not None + assert data.context_wrapper.usage.total_tokens == 101 + assert data.context_wrapper._budget.tokens == 101 + assert data.context_wrapper._budget.requests == 1 + assert len(model.calls) == 2 + else: + result = await execute(agent, budget, streamed) + assert result.final_output == "done" + assert result.context_wrapper._budget is not None + assert result.context_wrapper._budget.tokens == 2 + assert result.context_wrapper._budget.requests == 2 + assert result.context_wrapper.usage.total_tokens == 102 + assert len(model.calls) == 3 + assert effects == ["lookup"] + + +@pytest.mark.asyncio +@pytest.mark.parametrize("streamed", [False, True]) +async def test_known_failure_is_observed_once_before_retry_aggregation(streamed): + model = ScriptedModel( + [ + failure(5), + ModelStep( + output=[get_function_tool_call("unknown")], usage=Usage(requests=1, total_tokens=7) + ), + ModelStep(output=[get_text_message("done")], usage=Usage(requests=1, total_tokens=11)), + ] + ) + result = await execute( + Agent(name="root", model=model, model_settings=retry_settings()), + RunBudget(max_outer_requests=2, max_tokens=30, include_failed_attempt_usage=True), + streamed, + ) + assert result.final_output == "done" + assert result.context_wrapper._budget is not None + assert result.context_wrapper._budget.requests == 2 + assert result.context_wrapper._budget.tokens == 23 + assert result.context_wrapper.usage.total_tokens == 23 + + +@pytest.mark.asyncio +@pytest.mark.parametrize("streamed", [False, True]) +@pytest.mark.parametrize("include_failed", [False, True]) +async def test_terminal_failure_keeps_public_usage_and_opt_in_budget_usage( + streamed, include_failed +): + model = ScriptedModel([failure(9)]) + with pytest.raises(ModelBehaviorError) as caught: + await execute( + Agent(name="root", model=model), + RunBudget(max_tokens=50, include_failed_attempt_usage=include_failed), + streamed, + ) + data = caught.value.run_data + assert data is not None and data.context_wrapper._budget is not None + assert data.context_wrapper._budget.tokens == (9 if include_failed else 0) + assert data.context_wrapper._budget.requests == 1 + assert data.context_wrapper.usage.total_tokens == 9 + + +@pytest.mark.asyncio +@pytest.mark.parametrize("streamed", [False, True]) +@pytest.mark.parametrize("missing", ["stop", "continue"]) +async def test_failure_without_usage_does_not_invent_a_missing_observation(streamed, missing): + model = ScriptedModel( + [ + ModelBehaviorError("unreported failure"), + ModelStep( + output=[get_function_tool_call("unknown")], usage=Usage(requests=1, total_tokens=1) + ), + ModelStep(output=[get_text_message("done")], usage=Usage(requests=1, total_tokens=1)), + ] + ) + result = await execute( + Agent(name="root", model=model, model_settings=retry_settings()), + RunBudget( + max_tokens=3, + max_outer_requests=2, + missing_usage=missing, + include_failed_attempt_usage=True, + ), + streamed, + ) + assert result.final_output == "done" + assert result.context_wrapper._budget is not None + assert result.context_wrapper._budget.tokens == 2 + assert result.context_wrapper._budget.requests == 2 + + +@pytest.mark.asyncio +async def test_terminal_failed_event_is_observed_once_when_opted_in(): + response = get_response_obj([], usage=Usage(requests=1, total_tokens=9)) + model = ScriptedModel( + [ + ModelStep.stream( + [ResponseFailedEvent(type="response.failed", sequence_number=0, response=response)] + ) + ] + ) + with pytest.raises(ModelBehaviorError) as caught: + await execute( + Agent(name="root", model=model), + RunBudget(max_tokens=50, include_failed_attempt_usage=True), + True, + ) + data = caught.value.run_data + assert data is not None and data.context_wrapper._budget is not None + assert data.context_wrapper._budget.tokens == data.context_wrapper.usage.total_tokens == 9 + + +@pytest.mark.asyncio +@pytest.mark.parametrize("streamed", [False, True]) +@pytest.mark.parametrize("include_failed", [False, True]) +async def test_inherited_child_failure_usage_respects_ancestor_opt_in(streamed, include_failed): + child_model = ScriptedModel( + [ + failure(100), + ModelStep(output=[get_text_message("child")], usage=Usage(requests=1, total_tokens=1)), + ] + ) + child = Agent(name="child", model=child_model, model_settings=retry_settings()).as_tool( + "ask", "Ask child", failure_error_function=None + ) + parent_model = ScriptedModel( + [ + ModelStep( + output=[get_function_tool_call("ask", '{"input":"go"}')], + usage=Usage(requests=1, total_tokens=1), + ), + ModelStep(output=[get_text_message("done")], usage=Usage(requests=1, total_tokens=1)), + ] + ) + root = Agent(name="root", model=parent_model, tools=[child]) + budget = RunBudget( + max_tokens=50, share_with_children=True, include_failed_attempt_usage=include_failed + ) + if include_failed: + with pytest.raises(RunBudgetError) as caught: + await execute(root, budget, streamed) + assert caught.value.limit == "tokens" + data = caught.value.run_data + assert data is not None and data.context_wrapper._budget is not None + assert data.context_wrapper._budget.tokens == 102 + assert data.context_wrapper._budget.requests == 2 + assert len(parent_model.calls) == 1 + else: + result = await execute(root, budget, streamed) + assert result.final_output == "done" and result.context_wrapper._budget is not None + assert result.context_wrapper._budget.tokens == 3 + assert len(parent_model.calls) == 2 + assert len(child_model.calls) == 2 diff --git a/tests/test_budget_tool_authority.py b/tests/test_budget_tool_authority.py new file mode 100644 index 0000000000..242e24c12d --- /dev/null +++ b/tests/test_budget_tool_authority.py @@ -0,0 +1,80 @@ +"""Restricted tool budgets reject provider authority hidden behind prompt definitions.""" + +import pytest + +from agents import Agent, ModelSettings, RunBudget, RunConfig, Runner, UserError +from agents.testing import ScriptedModel +from tests.test_responses import get_function_tool_call + + +async def execute(agent, budget, streamed): + config = RunConfig(budget=budget, tracing_disabled=True) + if not streamed: + return await Runner.run(agent, "go", run_config=config) + result = Runner.run_streamed(agent, "go", run_config=config) + async for _ in result.stream_events(): + pass + return result + + +@pytest.mark.asyncio +@pytest.mark.parametrize("streamed", [False, True]) +@pytest.mark.parametrize("inherited", [False, True]) +@pytest.mark.parametrize("surface", ["prompt", "extra_body", "extra_args", "nested_body"]) +async def test_restricted_tool_authority_cannot_come_from_opaque_prompt( + streamed, inherited, surface +): + model = ScriptedModel() + kwargs = {"name": "restricted", "model": model} + if surface == "prompt": + kwargs["prompt"] = {"id": "opaque-prompt"} + else: + overrides = {"prompt": {"id": "opaque-prompt"}} + kwargs["model_settings"] = ModelSettings( + **( + {"extra_args": {"extra_body": overrides}} + if surface == "nested_body" + else {surface: overrides} + ) + ) + restricted = Agent(**kwargs) + if inherited: + delegate = restricted.as_tool("ask", "Ask child", failure_error_function=None) + agent = Agent( + name="parent", + model=ScriptedModel([[get_function_tool_call("ask", '{"input":"go"}')]]), + tools=[delegate], + ) + else: + agent = restricted + with pytest.raises(UserError, match="RunBudget.allowed_tools"): + await execute(agent, RunBudget(allowed_tools=("ask",)), streamed) + assert not model.calls + + +@pytest.mark.asyncio +@pytest.mark.parametrize("streamed", [False, True]) +async def test_responses_prompt_without_local_tools_rejected_before_provider(streamed): + import httpx2 + from openai import AsyncOpenAI + + from agents.models.openai_responses import OpenAIResponsesModel + + requests = [] + + async def handler(request): + requests.append(request) + raise AssertionError("The opaque prompt must not reach the provider.") + + async with AsyncOpenAI( + api_key="synthetic-test-key", + http_client=httpx2.AsyncClient(transport=httpx2.MockTransport(handler)), + ) as client: + agent = Agent( + name="restricted", + model=OpenAIResponsesModel("example", client), + prompt={"id": "opaque-prompt"}, + ) + with pytest.raises(UserError, match="RunBudget.allowed_tools"): + await execute(agent, RunBudget(allowed_tools=()), streamed) + assert not requests diff --git a/tests/test_estimated_spend_example.py b/tests/test_estimated_spend_example.py new file mode 100644 index 0000000000..92183c7a09 --- /dev/null +++ b/tests/test_estimated_spend_example.py @@ -0,0 +1,86 @@ +from decimal import Decimal + +import pytest + +from agents.testing import ModelStep, ScriptedModel, assistant_message +from agents.usage import Usage +from examples.agent_patterns.estimated_spend import DemoProvider, Rates, estimate_usd, run_batch + + +def response(raw_usage): + return ModelStep( + output=[assistant_message("answer")], + usage=Usage(requests=1, input_tokens=1000, output_tokens=500, total_tokens=1500), + raw_usage=raw_usage, + ) + + +async def test_changes_models_and_stops_before_next_run_after_threshold(): + economy = ScriptedModel([response({"input_tokens": 1000, "output_tokens": 500})]) + review = ScriptedModel([response({"input_tokens": 1000, "output_tokens": 500})]) + result = await run_batch( + [("economy", "draft"), ("review", "review"), ("economy", "never start")], + provider=DemoProvider({"economy": economy, "review": review}), + rates={"economy": Rates(Decimal(1), Decimal(2)), "review": Rates(Decimal(3), Decimal(6))}, + stop_at_usd=Decimal("0.005"), + ) + assert result.known_usd == Decimal("0.008") + assert result.outputs == ["answer", "answer"] + assert result.stopped == "threshold" + assert len(economy.calls) == len(review.calls) == 1 + assert not economy.calls[0].tools and not review.calls[0].tools + + +@pytest.mark.parametrize("raw_usage", [None, {}, {"input_tokens": 1000}]) +async def test_missing_usage_stops_even_when_normalized_usage_has_counts(raw_usage): + model = ScriptedModel([response(raw_usage)]) + result = await run_batch( + [("model", "first"), ("model", "never start")], + provider=DemoProvider({"model": model}), + rates={"model": Rates(Decimal(1), Decimal(2))}, + stop_at_usd=Decimal(1), + ) + assert result.stopped == "unknown_usage" + assert result.known_usd == 0 + assert result.outputs == ["answer"] + assert len(model.calls) == 1 + + +async def test_reported_zero_allows_next_job_and_retains_known_subtotal(): + model = ScriptedModel( + [ + response({"input_tokens": 0, "output_tokens": 0}), + response({"input_tokens": 1000, "output_tokens": 500}), + response(None), + ] + ) + result = await run_batch( + [("model", str(index)) for index in range(4)], + provider=DemoProvider({"model": model}), + rates={"model": Rates(Decimal(1), Decimal(2))}, + stop_at_usd=Decimal(1), + ) + assert result.stopped == "unknown_usage" + assert result.known_usd == Decimal("0.002") + assert len(result.outputs) == len(model.calls) == 3 + + +async def test_zero_threshold_starts_no_request(): + model = ScriptedModel([]) + result = await run_batch( + [("model", "never start")], + provider=DemoProvider({"model": model}), + rates={"model": Rates(Decimal(1), Decimal(2))}, + stop_at_usd=Decimal(0), + ) + assert result.stopped == "threshold" + assert result.outputs == [] + assert not model.calls + + +@pytest.mark.parametrize("count", [None, -1, True, "10"]) +def test_invalid_reported_count_remains_unknown(count): + assert ( + estimate_usd({"input_tokens": count, "output_tokens": 10}, Rates(Decimal(1), Decimal(2))) + is None + ) diff --git a/tests/test_shared_run_budget.py b/tests/test_shared_run_budget.py new file mode 100644 index 0000000000..435884c4d9 --- /dev/null +++ b/tests/test_shared_run_budget.py @@ -0,0 +1,941 @@ +"""Observable SDK admission limits across nested runs and approval resumes.""" + +from __future__ import annotations + +import asyncio +from typing import Any + +import pytest + +from agents import ( + Agent, + RunBudget, + RunBudgetError, + RunConfig, + Runner, + RunState, + UserError, + tool_namespace, +) +from agents.decorators import tool +from agents.models.codex import CodexProvider +from agents.testing import ScriptedModel +from tests.test_responses import get_function_tool_call, get_text_message + + +async def execute( + agent, budget, *, streamed=False, input: str | RunState[Any, Agent[Any]] = "begin" +): + config = RunConfig(budget=budget, tracing_disabled=True) + if not streamed: + return await Runner.run(agent, input, run_config=config) + result = Runner.run_streamed(agent, input, run_config=config) + async for _ in result.stream_events(): + pass + return result + + +@pytest.mark.asyncio +@pytest.mark.parametrize("streamed", [False, True]) +async def test_parallel_function_handlers_reserve_one_slot(streamed): + started = [] + + @tool + async def record(value: str) -> str: + started.append(value) + await asyncio.sleep(0) + return value + + model = ScriptedModel( + [ + [ + get_function_tool_call("record", '{"value":"one"}', call_id="one"), + get_function_tool_call("record", '{"value":"two"}', call_id="two"), + ], + ] + ) + with pytest.raises(RunBudgetError) as caught: + await execute( + Agent(name="root", model=model, tools=[record]), + RunBudget(max_tool_starts=1), + streamed=streamed, + ) + assert caught.value.limit == "tool_starts" + assert len(started) <= 1 + + +@pytest.mark.asyncio +@pytest.mark.parametrize("streamed", [False, True]) +async def test_children_compete_for_shared_tool_slot(streamed): + started = [] + + @tool + async def record() -> str: + started.append("record") + return "saved" + + def child(name): + model = ScriptedModel( + [[get_function_tool_call("record", call_id=name)], [get_text_message(name)]] + ) + return Agent(name=name, model=model, tools=[record]).as_tool( + name, "Run child", failure_error_function=None + ) + + parent = Agent( + name="root", + model=ScriptedModel( + [ + [ + get_function_tool_call("left", '{"input":"go"}', call_id="left"), + get_function_tool_call("right", '{"input":"go"}', call_id="right"), + ], + [get_text_message("done")], + ] + ), + tools=[child("left"), child("right")], + ) + with pytest.raises(RunBudgetError): + await execute( + parent, RunBudget(max_tool_starts=3, share_with_children=True), streamed=streamed + ) + assert len(started) <= 1 + + +@pytest.mark.asyncio +async def test_parent_tool_policy_reaches_child(): + started = [] + + @tool + def denied() -> str: + started.append("denied") + return "unsafe" + + nested = Agent( + name="child", model=ScriptedModel([[get_function_tool_call("denied")]]), tools=[denied] + ).as_tool("ask", "Ask child", failure_error_function=None) + parent = Agent( + name="root", + model=ScriptedModel([[get_function_tool_call("ask", '{"input":"go"}')]]), + tools=[nested], + ) + with pytest.raises(RunBudgetError) as caught: + await execute(parent, RunBudget(allowed_tools=("ask",))) + assert caught.value.limit == "tools" + assert not started + + +@pytest.mark.asyncio +@pytest.mark.parametrize("streamed", [False, True]) +@pytest.mark.parametrize("restrict_child", [False, True], ids=["inherited", "child-deny"]) +async def test_child_can_deny_a_name_allowed_in_the_parent(streamed, restrict_child): + started = [] + + @tool(name_override="lookup") + def parent_lookup() -> str: + started.append("parent") + return "public" + + @tool(name_override="lookup") + def child_lookup() -> str: + started.append("child") + return "private" + + child = Agent( + name="child", + model=ScriptedModel( + [ + [get_function_tool_call("lookup", call_id="child-lookup")], + [get_text_message("child done")], + ] + ), + tools=[child_lookup], + ) + delegate = child.as_tool( + "ask", + "Ask child", + run_config={"budget": RunBudget(allowed_tools=())} if restrict_child else None, + failure_error_function=None, + ) + parent = Agent( + name="parent", + model=ScriptedModel( + [ + [get_function_tool_call("lookup", call_id="parent-lookup")], + [get_function_tool_call("ask", '{"input":"go"}', call_id="ask")], + [get_text_message("done")], + ] + ), + tools=[parent_lookup, delegate], + ) + + budget = RunBudget(allowed_tools=("lookup", "ask")) + if restrict_child: + with pytest.raises(RunBudgetError) as caught: + await execute(parent, budget, streamed=streamed) + assert caught.value.limit == "tools" + assert started == ["parent"] + else: + await execute(parent, budget, streamed=streamed) + assert started == ["parent", "child"] + + +@pytest.mark.asyncio +@pytest.mark.parametrize("streamed", [False, True]) +@pytest.mark.parametrize("dotted_parent", [False, True]) +async def test_allowlist_cannot_confuse_bare_and_namespaced_tools(streamed, dotted_parent): + started = [] + + @tool(name_override="crm.lookup") + def bare() -> str: + started.append("bare") + return "bare" + + @tool + def lookup() -> str: + started.append("namespaced") + return "namespaced" + + namespaced = tool_namespace(name="crm", description="CRM", tools=[lookup])[0] + parent_tool, child_tool = (bare, namespaced) if dotted_parent else (namespaced, bare) + child_call = ( + get_function_tool_call("lookup", namespace="crm") + if dotted_parent + else get_function_tool_call("crm.lookup") + ) + child_model = ScriptedModel([[child_call], [get_text_message("child done")]]) + child = Agent(name="child", model=child_model, tools=[child_tool]) + parent_model = ScriptedModel( + [[get_function_tool_call("ask", '{"input":"go"}')], [get_text_message("done")]] + ) + parent = Agent( + name="parent", + model=parent_model, + tools=[ + parent_tool, + child.as_tool( + "ask", + "Ask child", + run_config=RunConfig(budget=RunBudget(max_tool_starts=1)), + failure_error_function=None, + ), + ], + ) + with pytest.raises(UserError, match="RunBudget.allowed_tools"): + await execute(parent, RunBudget(allowed_tools=("ask", "crm.lookup")), streamed=streamed) + assert not started and not child_model.calls + assert len(parent_model.calls) == (0 if dotted_parent else 1) + + +@pytest.mark.asyncio +@pytest.mark.parametrize( + "namespace, name", [(None, "crm.lookup"), ("sales.crm", "lookup"), ("sales", "crm.lookup")] +) +async def test_allowlist_rejects_dots_in_namespace_components_only_when_restricted(namespace, name): + started = [] + + @tool(name_override=name) + def lookup() -> str: + started.append("lookup") + return "ok" + + model = ScriptedModel( + [[get_function_tool_call(name, namespace=namespace)], [get_text_message("done")]] + ) + agent = Agent( + name="worker", + model=model, + tools=tool_namespace(name=namespace, description="CRM", tools=[lookup]) + if namespace + else [lookup], + ) + with pytest.raises(UserError, match="RunBudget.allowed_tools"): + await execute(agent, RunBudget(allowed_tools=("other",))) + assert not model.calls and not started + assert (await execute(agent, RunBudget(max_tool_starts=1))).final_output == "done" + assert started == ["lookup"] + + +@pytest.mark.asyncio +async def test_namespaced_allowlist_survives_nested_approval_and_policy_check(): + started = [] + + @tool(needs_approval=True) + def lookup() -> str: + started.append("child") + return "ok" + + child_model = ScriptedModel( + [[get_function_tool_call("lookup", namespace="crm")], [get_text_message("child done")]] + ) + child = Agent( + name="child", + model=child_model, + tools=tool_namespace(name="crm", description="Child CRM", tools=[lookup]), + ) + parent = Agent( + name="parent", + model=ScriptedModel( + [[get_function_tool_call("ask", '{"input":"go"}')], [get_text_message("done")]] + ), + tools=[ + *tool_namespace(name="crm", description="Parent CRM", tools=[lookup]), + child.as_tool("ask", "Ask child", failure_error_function=None), + ], + ) + budget = RunBudget(allowed_tools=("ask", "crm.lookup")) + paused = (await execute(parent, budget)).to_state() + state = await RunState.from_json(parent, paused.to_json()) + state.approve(state.get_interruptions()[0]) + with pytest.raises(UserError, match="same RunBudget"): + await execute(parent, RunBudget(allowed_tools=("ask", "lookup")), input=state) + + @tool(name_override="crm.lookup") + def ambiguous() -> str: + return "unreachable" + + original = parent.tools[0] + parent.tools[0] = ambiguous + with pytest.raises(UserError, match="RunBudget.allowed_tools"): + await execute(parent, budget, input=state) + parent.tools[0] = original + assert not started and len(child_model.calls) == 1 + assert (await execute(parent, budget, input=state)).final_output == "done" + assert started == ["child"] + + +@pytest.mark.asyncio +@pytest.mark.parametrize("portable", [False, True]) +async def test_approval_resume_keeps_tool_consumption(portable): + started = [] + + @tool + def first() -> str: + started.append("first") + return "saved" + + @tool(needs_approval=True) + def second() -> str: + started.append("second") + return "saved" + + parent = Agent( + name="root", + model=ScriptedModel( + [ + [ + get_function_tool_call("first", call_id="first"), + get_function_tool_call("second", call_id="second"), + ], + [get_text_message("done")], + ] + ), + tools=[first, second], + ) + budget = RunBudget(max_tool_starts=1) + state = (await execute(parent, budget)).to_state() + assert started == ["first"] + if portable: + state = await RunState.from_json(parent, state.to_json()) + state.approve(state.get_interruptions()[0]) + with pytest.raises(RunBudgetError): + await execute(parent, budget, input=state) + assert started == ["first"] + + +@pytest.mark.asyncio +@pytest.mark.parametrize("field", ["max_child_runs", "max_delegation_depth"]) +async def test_zero_delegation_limit_prevents_child_model(field): + child_model = ScriptedModel([[get_text_message("child")]]) + nested = Agent(name="child", model=child_model).as_tool( + "ask", "Ask child", failure_error_function=None + ) + parent = Agent( + name="root", + model=ScriptedModel([[get_function_tool_call("ask", '{"input":"go"}')]]), + tools=[nested], + ) + with pytest.raises(RunBudgetError): + await execute( + parent, + RunBudget(max_child_runs=0) + if field == "max_child_runs" + else RunBudget(max_delegation_depth=0), + ) + assert not child_model.calls + + +@pytest.mark.asyncio +async def test_child_request_budget_cannot_expand_parent(): + child_model = ScriptedModel([[get_text_message("child")]]) + nested = Agent(name="child", model=child_model).as_tool( + "ask", + "Ask child", + run_config=RunConfig(budget=RunBudget(max_outer_requests=100)), + failure_error_function=None, + ) + parent = Agent( + name="root", + model=ScriptedModel([[get_function_tool_call("ask", '{"input":"go"}')]]), + tools=[nested], + ) + with pytest.raises(RunBudgetError) as caught: + await execute(parent, RunBudget(max_outer_requests=1, share_with_children=True)) + assert caught.value.limit == "outer_requests" + assert not child_model.calls + + +@pytest.mark.asyncio +@pytest.mark.parametrize("portable", [False, True]) +@pytest.mark.parametrize("mode", ["default", "configured", "streamed", "grandchild"]) +async def test_shared_budget_rebinds_nested_approval_resume(portable, mode): + started = [] + + @tool(needs_approval=True) + def record() -> str: + started.append("record") + return "saved" + + child_model = ScriptedModel( + [[get_function_tool_call("record", call_id="inner")], [get_text_message("child")]] + ) + child = Agent(name="child", model=child_model, tools=[record]) + if mode == "grandchild": + child = Agent( + name="middle", + model=ScriptedModel( + [ + [get_function_tool_call("delegate", '{"input":"go"}', call_id="middle")], + [get_text_message("middle done")], + ] + ), + tools=[child.as_tool("delegate", "Delegate", failure_error_function=None)], + ) + child_config = RunConfig(tracing_disabled=True) if mode != "default" else None + if mode == "grandchild": + child_config = RunConfig(budget=RunBudget(max_tool_starts=2), tracing_disabled=True) + nested = child.as_tool( + "ask", + "Ask child", + run_config=child_config, + on_stream=(lambda _: None) if mode == "streamed" else None, + failure_error_function=None, + ) + parent = Agent( + name="root", + model=ScriptedModel( + [ + [get_function_tool_call("ask", '{"input":"go"}', call_id="outer")], + [get_text_message("done")], + ] + ), + tools=[nested], + ) + starts = 3 if mode == "grandchild" else 2 + budget = RunBudget( + max_tool_starts=starts, max_outer_requests=2 * starts, share_with_children=True + ) + state = (await execute(parent, budget)).to_state() + if portable: + state = await RunState.from_json(parent, state.to_json()) + state.approve(state.get_interruptions()[0]) + result = await execute(parent, budget, input=state) + assert result.final_output == "done" + assert started == ["record"] + assert result.context_wrapper._budget is not None + assert result.context_wrapper._budget.tool_starts == starts + assert result.context_wrapper._budget.requests == 2 * starts + + +@pytest.mark.asyncio +async def test_native_hidden_usage_budget_rejected_before_execution(): + with pytest.raises(UserError, match="native sampling"): + await Runner.run( + Agent(name="native", model="example"), + "go", + run_config=RunConfig( + model_provider=CodexProvider(), + budget=RunBudget(max_tokens=1), + tracing_disabled=True, + ), + ) + + +@pytest.mark.asyncio +@pytest.mark.parametrize("streamed", [False, True]) +async def test_cancelled_parent_joins_owned_child_handler(streamed): + # Controlled suspension observes the real child tool's cleanup before parent return. + started = asyncio.Event() + cleaned = asyncio.Event() + + @tool + async def wait_forever() -> str: + started.set() + try: + await asyncio.Event().wait() + finally: + await asyncio.sleep(0) + cleaned.set() + return "unreachable" + + child = Agent( + name="child", + model=ScriptedModel([[get_function_tool_call("wait_forever")]]), + tools=[wait_forever], + ) + nested = child.as_tool("ask", "Ask child", failure_error_function=None) + parent = Agent( + name="root", + model=ScriptedModel([[get_function_tool_call("ask", '{"input":"go"}')]]), + tools=[nested], + ) + budget = RunBudget(max_tool_starts=3, share_with_children=True) + if streamed: + result = Runner.run_streamed( + parent, "begin", run_config=RunConfig(budget=budget, tracing_disabled=True) + ) + + async def drain(): + async for _ in result.stream_events(): + pass + + task = asyncio.create_task(drain()) + await asyncio.wait_for(started.wait(), timeout=2) + result.cancel() + await asyncio.wait_for(task, timeout=2) + else: + task = asyncio.create_task(execute(parent, budget)) + await asyncio.wait_for(started.wait(), timeout=2) + task.cancel() + with pytest.raises(asyncio.CancelledError): + await asyncio.wait_for(task, timeout=2) + assert cleaned.is_set() + + +@pytest.mark.asyncio +async def test_rejected_approval_does_not_reserve_start(): + started = [] + + @tool(needs_approval=True) + def first() -> str: + started.append("first") + return "first" + + @tool + def second() -> str: + started.append("second") + return "second" + + parent = Agent( + name="root", + model=ScriptedModel( + [ + [get_function_tool_call("first", call_id="first")], + [get_function_tool_call("second", call_id="second")], + [get_text_message("done")], + ] + ), + tools=[first, second], + ) + budget = RunBudget(max_tool_starts=1) + state = (await execute(parent, budget)).to_state() + state.reject(state.get_interruptions()[0]) + assert (await execute(parent, budget, input=state)).final_output == "done" + assert started == ["second"] + + +@pytest.mark.asyncio +async def test_child_local_tool_limit_remains_in_force(): + started = [] + + @tool + def record() -> str: + started.append("record") + return "saved" + + child = Agent( + name="child", model=ScriptedModel([[get_function_tool_call("record")]]), tools=[record] + ) + nested = child.as_tool( + "ask", + "Ask child", + run_config=RunConfig(budget=RunBudget(max_tool_starts=0)), + failure_error_function=None, + ) + parent = Agent( + name="root", + model=ScriptedModel([[get_function_tool_call("ask", '{"input":"go"}')]]), + tools=[nested], + ) + with pytest.raises(RunBudgetError) as caught: + await execute(parent, RunBudget(max_tool_starts=10, share_with_children=True)) + assert caught.value.limit == "tool_starts" + assert not started + + +@pytest.mark.asyncio +async def test_child_usage_counts_against_parent_token_limit(): + from agents import Usage + from agents.testing import ModelStep + + child_model = ScriptedModel( + [ModelStep(output=[get_text_message("child")], usage=Usage(total_tokens=5))] + ) + nested = Agent(name="child", model=child_model).as_tool( + "ask", "Ask child", failure_error_function=None + ) + parent_model = ScriptedModel( + [ + ModelStep( + output=[get_function_tool_call("ask", '{"input":"go"}')], + usage=Usage(total_tokens=1), + ), + [get_text_message("done")], + ] + ) + with pytest.raises(RunBudgetError) as caught: + await execute( + Agent(name="root", model=parent_model, tools=[nested]), + RunBudget(max_tokens=6, share_with_children=True), + ) + assert caught.value.limit == "tokens" + assert len(parent_model.calls) == 1 + assert len(child_model.calls) == 1 + + +@pytest.mark.asyncio +async def test_grandchild_cannot_escape_ancestor_depth_through_local_budget(): + leaf_model = ScriptedModel([[get_text_message("leaf")]]) + leaf = Agent(name="leaf", model=leaf_model).as_tool( + "leaf", "Run leaf", failure_error_function=None + ) + child = Agent( + name="child", + model=ScriptedModel([[get_function_tool_call("leaf", '{"input":"go"}')]]), + tools=[leaf], + ).as_tool( + "child", + "Run child", + run_config=RunConfig(budget=RunBudget(max_outer_requests=100)), + failure_error_function=None, + ) + root = Agent( + name="root", + model=ScriptedModel([[get_function_tool_call("child", '{"input":"go"}')]]), + tools=[child], + ) + with pytest.raises(RunBudgetError) as caught: + await execute(root, RunBudget(max_delegation_depth=1)) + assert caught.value.limit == "delegation_depth" + assert not leaf_model.calls + + +@pytest.mark.asyncio +async def test_shared_outer_limit_counts_completed_child_before_parent_followup(): + from agents import Usage + from agents.testing import ModelStep + + child_model = ScriptedModel( + [ModelStep(output=[get_text_message("child")], usage=Usage(total_tokens=5))] + ) + nested = Agent(name="child", model=child_model).as_tool( + "ask", "Ask child", failure_error_function=None + ) + parent_model = ScriptedModel( + [ + ModelStep( + output=[get_function_tool_call("ask", '{"input":"go"}')], + usage=Usage(total_tokens=1), + ), + [get_text_message("done")], + ] + ) + with pytest.raises(RunBudgetError) as caught: + await execute( + Agent(name="root", model=parent_model, tools=[nested]), + RunBudget(max_outer_requests=2, share_with_children=True), + ) + assert caught.value.limit == "outer_requests" + assert len(parent_model.calls) == len(child_model.calls) == 1 + + +@pytest.mark.asyncio +@pytest.mark.parametrize("streamed", [False, True]) +async def test_selected_name_obeys_outer_limit_on_adapter_without_model_attribute(streamed): + from agents import ModelProvider, Usage + from agents.testing import ModelStep + + model = ScriptedModel( + [ + ModelStep(output=[get_function_tool_call("record")], usage=Usage(total_tokens=1)), + [get_text_message("done")], + ] + ) + + class Provider(ModelProvider): + def get_model(self, model_name): + assert model_name == "selected" + return model + + @tool + def record() -> str: + return "saved" + + agent = Agent(name="root", model="static", tools=[record]) + config = RunConfig( + model_provider=Provider(), + model_selector=lambda _: "selected", + budget=RunBudget(max_outer_requests=1), + tracing_disabled=True, + ) + with pytest.raises(RunBudgetError): + if streamed: + result = Runner.run_streamed(agent, "go", run_config=config) + async for _ in result.stream_events(): + pass + else: + await Runner.run(agent, "go", run_config=config) + assert len(model.calls) == 1 + assert agent.model == "static" + + +@pytest.mark.asyncio +async def test_shared_child_selection_obeys_ancestor_outer_limit(): + from agents import ModelProvider, Usage + from agents.testing import ModelStep + + child_model = ScriptedModel( + [ModelStep(output=[get_text_message("child")], usage=Usage(total_tokens=1))] + ) + + class Provider(ModelProvider): + def get_model(self, model_name): + assert model_name == "selected-child" + return child_model + + child = Agent(name="child", model="static-child").as_tool( + "ask", + "Ask child", + run_config=RunConfig( + model_provider=Provider(), + model_selector=lambda _: "selected-child", + budget=RunBudget(max_outer_requests=1), + ), + failure_error_function=None, + ) + root = Agent( + name="root", + model=ScriptedModel( + [ + ModelStep( + output=[get_function_tool_call("ask", '{"input":"go"}')], + usage=Usage(total_tokens=1), + ), + [get_text_message("done")], + ] + ), + tools=[child], + ) + with pytest.raises(RunBudgetError): + await execute( + root, + RunBudget(max_outer_requests=2, share_with_children=True), + ) + assert len(child_model.calls) == 1 + assert isinstance(root.model, ScriptedModel) + assert len(root.model.calls) == 1 + + +@pytest.mark.asyncio +async def test_child_rejects_unlisted_hosted_tool_before_model_dispatch(): + from agents import WebSearchTool + + child_model = ScriptedModel([[get_text_message("should not run")]]) + nested = Agent(name="child", model=child_model, tools=[WebSearchTool()]).as_tool( + "ask", "Ask child", failure_error_function=None + ) + root = Agent( + name="root", + model=ScriptedModel([[get_function_tool_call("ask", '{"input":"go"}')]]), + tools=[nested], + ) + with pytest.raises(UserError, match="only SDK FunctionTool"): + await execute(root, RunBudget(allowed_tools=("ask",))) + assert not child_model.calls + + +@pytest.mark.asyncio +async def test_codex_backed_sdk_child_bounds_outer_requests_and_sdk_handlers(tmp_path, monkeypatch): + # This double preserves the native wire boundary without requiring a compiled extension. + import json + import sys + from collections import deque + from types import ModuleType + + from tests.models.test_codex_provider import FakeThread + + first = FakeThread(call={"callId": "record", "tool": "record", "arguments": {}}) + queue = deque([first]) + module = ModuleType("agents.models._codex_native") + + class Manager: + def __init__(self, *args): + pass + + async def start_thread(self, tools, instructions, settings): + thread = queue.popleft() + monkeypatch.setattr( + thread, "model", json.loads(settings)["model"] or "native-default", raising=False + ) + return thread + + async def close(self): + pass + + monkeypatch.setattr(module, "Manager", Manager, raising=False) + monkeypatch.setitem(sys.modules, module.__name__, module) + started = [] + + @tool + def record() -> str: + started.append("record") + return "saved" + + child = Agent(name="native-child", tools=[record]).as_tool( + "ask", + "Ask child", + run_config=RunConfig( + model_provider=CodexProvider(cwd=tmp_path), + budget=RunBudget(max_outer_requests=1, max_tool_starts=1), + ), + failure_error_function=None, + ) + root = Agent( + name="root", + model=ScriptedModel([[get_function_tool_call("ask", '{"input":"go"}')]]), + tools=[child], + ) + with pytest.raises(RunBudgetError) as caught: + await execute(root, RunBudget(max_tool_starts=1)) + assert caught.value.limit == "outer_requests" + assert started == ["record"] + assert first.closed and not queue + + +@pytest.mark.asyncio +async def test_shared_codex_child_rejects_unenforceable_native_delegation(tmp_path): + child = Agent(name="native-child").as_tool( + "ask", + "Ask child", + run_config=RunConfig(model_provider=CodexProvider(cwd=tmp_path)), + failure_error_function=None, + ) + root = Agent( + name="root", + model=ScriptedModel([[get_function_tool_call("ask", '{"input":"go"}')]]), + tools=[child], + ) + with pytest.raises(UserError, match="controlled native delegation"): + await execute(root, RunBudget(max_tool_starts=2, share_with_children=True)) + + +@pytest.mark.asyncio +async def test_tool_start_limit_rejects_uncounted_custom_handler(): + from agents import CustomTool + + async def execute_custom(ctx, value): + pytest.fail("The unsupported handler must not run.") + + model = ScriptedModel([[get_text_message("should not run")]]) + root = Agent( + name="root", + model=model, + tools=[CustomTool(name="raw", description="Raw", on_invoke_tool=execute_custom)], + ) + with pytest.raises(UserError, match="max_tool_starts supports SDK FunctionTool"): + await execute(root, RunBudget(max_tool_starts=1)) + assert not model.calls + + +@pytest.mark.asyncio +@pytest.mark.parametrize("surface", ["extra_body", "extra_args", "deferred"]) +async def test_allowlist_rejects_provider_override_and_deferred_escape(surface): + from agents import ModelSettings + + @tool + def record() -> str: + return "saved" + + if surface == "deferred": + record.defer_loading = True + settings = ModelSettings() + elif surface == "extra_body": + settings = ModelSettings(extra_body={"tools": [{"type": "web_search"}]}) + else: + settings = ModelSettings(extra_args={"tools": [{"type": "web_search"}]}) + model = ScriptedModel([[get_text_message("should not run")]]) + root = Agent(name="root", model=model, tools=[record], model_settings=settings) + with pytest.raises(UserError, match="RunBudget.allowed_tools"): + await execute(root, RunBudget(allowed_tools=("record",))) + assert not model.calls + + +@pytest.mark.asyncio +async def test_upstream_six_key_checkpoint_restores_without_extension_options(): + @tool(needs_approval=True) + def record() -> str: + return "saved" + + model = ScriptedModel([[get_function_tool_call("record")], [get_text_message("done")]]) + root = Agent(name="upstream checkpoint", model=model, tools=[record]) + budget = RunBudget(max_model_calls=2) + saved = (await execute(root, budget)).to_state().to_json() + # These exact names and defaults come from the merged upstream checkpoint contract. + assert saved["context"]["budget"] == { + "max_requests": 2, + "max_tokens": None, + "missing_usage": "stop", + "requests": 1, + "tokens": 0, + "unavailable": False, + } + assert budget.include_failed_attempt_usage is False + restored = await RunState.from_json(root, saved) + restored.approve(restored.get_interruptions()[0]) + result = await execute(root, budget, input=restored) + assert result.final_output == "done" and len(model.calls) == 2 + assert result.context_wrapper._budget is not None + assert result.context_wrapper._budget.requests == 2 + assert result.to_state().to_json()["context"]["budget"]["max_requests"] == 2 + + +@pytest.mark.asyncio +@pytest.mark.parametrize("streamed", [False, True]) +@pytest.mark.parametrize( + "field,ceiling", [("max_model_calls", "model_calls"), ("max_outer_requests", "outer_requests")] +) +async def test_python_outer_option_preserves_upstream_model_call_contract(streamed, field, ceiling): + model = ScriptedModel( + [ + [get_function_tool_call("unknown")], + [get_function_tool_call("unknown")], + [get_text_message("must not run")], + ] + ) + config = RunConfig( + budget=RunBudget(max_model_calls=2) + if field == "max_model_calls" + else RunBudget(max_outer_requests=2), + tracing_disabled=True, + tool_not_found_behavior="return_error_to_model", + ) + root = Agent(name="limited", model=model) + with pytest.raises(RunBudgetError) as caught: + if streamed: + result = Runner.run_streamed(root, "start", run_config=config, max_turns=None) + async for _ in result.stream_events(): + pass + else: + await Runner.run(root, "start", run_config=config, max_turns=None) + assert caught.value.limit == ceiling + assert len(model.calls) == 2