From 079bb0279a7b41781f86561acf76d66889508134 Mon Sep 17 00:00:00 2001 From: Mark Stuart Date: Fri, 20 Nov 2026 22:02:37 -0800 Subject: [PATCH 1/4] feat: add per-run request, token and estimated cost limits --- src/agents/__init__.py | 3 + src/agents/agent.py | 5 + src/agents/extensions/models/any_llm_model.py | 2 + src/agents/extensions/models/litellm_model.py | 1 + .../openai_responses_compaction_session.py | 10 +- src/agents/models/chatcmpl_stream_handler.py | 6 +- src/agents/models/openai_chatcompletions.py | 1 + src/agents/run.py | 9 +- src/agents/run_budget.py | 328 ++++++++++ src/agents/run_config.py | 9 + src/agents/run_context.py | 16 +- src/agents/run_internal/model_retry.py | 4 + src/agents/run_internal/resumable_session.py | 5 + src/agents/run_internal/run_loop.py | 22 +- src/agents/run_state.py | 21 +- src/agents/usage.py | 35 +- tests/test_run_budget.py | 604 ++++++++++++++++++ 17 files changed, 1063 insertions(+), 18 deletions(-) create mode 100644 src/agents/run_budget.py create mode 100644 tests/test_run_budget.py diff --git a/src/agents/__init__.py b/src/agents/__init__.py index 7e6885c971..fec95ed502 100644 --- a/src/agents/__init__.py +++ b/src/agents/__init__.py @@ -126,6 +126,7 @@ ToolNameCollisionPolicy, ToolNotFoundBehavior, ) +from .run_budget import RunBudget, RunBudgetError from .run_context import AgentHookContext, RunContextWrapper, TContext from .run_error_handlers import ( RunErrorData, @@ -492,6 +493,8 @@ def enable_verbose_stdout_logging() -> None: "RunResult", "RunResultStreaming", "ResponsesWebSocketSession", + "RunBudget", + "RunBudgetError", "RunConfig", "OutputGuardrailBlockedMessageArgs", "OutputGuardrailBlockedMessageFormatter", diff --git a/src/agents/agent.py b/src/agents/agent.py index 48fea87c0d..fdc9971e81 100644 --- a/src/agents/agent.py +++ b/src/agents/agent.py @@ -797,6 +797,9 @@ 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: + resolved_run_config = copy.copy(resolved_run_config) + resolved_run_config.budget = None tool_state_scope_id = get_agent_tool_state_scope(context) if isinstance(context, ToolContext): # Use a fresh ToolContext to avoid sharing approval state with parent runs. @@ -1140,6 +1143,8 @@ async def enqueue_stream_events() -> None: return run_result.final_output + # Keep the live policy with the implementation, which survives tool rebinding. + cast(Any, _run_agent_impl).__agents_run_config__ = run_config run_agent_tool = _build_wrapped_function_tool( name=tool_name_resolved, description=tool_description_resolved, diff --git a/src/agents/extensions/models/any_llm_model.py b/src/agents/extensions/models/any_llm_model.py index b6f07520af..19c5b70b0e 100644 --- a/src/agents/extensions/models/any_llm_model.py +++ b/src/agents/extensions/models/any_llm_model.py @@ -465,6 +465,7 @@ async def _get_response_via_responses( # The request completed, so it counts even when the provider omits usage. else Usage(requests=1) ) + usage._total_missing = response.usage is None or response.usage.total_tokens is None span_response.span_data.usage = model_usage_to_span_usage(usage) @@ -672,6 +673,7 @@ async def _get_response_via_chat( # The request completed, so it counts even when the provider omits usage. else Usage(requests=1) ) + usage._total_missing = response.usage is None or response.usage.total_tokens is None # Some providers signal a filtered non-streaming completion only through # finish_reason="content_filter" and an otherwise empty message. Preserve diff --git a/src/agents/extensions/models/litellm_model.py b/src/agents/extensions/models/litellm_model.py index 4732874f5f..507b2494ca 100644 --- a/src/agents/extensions/models/litellm_model.py +++ b/src/agents/extensions/models/litellm_model.py @@ -325,6 +325,7 @@ async def get_response( # The request completed, so it counts even when the provider omits usage. else Usage(requests=1) ) + usage._total_missing = response_usage is None or response_usage.total_tokens is None else: usage = Usage(requests=1) logger.warning("No usage information returned from Litellm") diff --git a/src/agents/memory/openai_responses_compaction_session.py b/src/agents/memory/openai_responses_compaction_session.py index cc863e5736..ebc40ba2d0 100644 --- a/src/agents/memory/openai_responses_compaction_session.py +++ b/src/agents/memory/openai_responses_compaction_session.py @@ -479,8 +479,14 @@ async def _run_compaction_locked( compacted = await self.client.responses.compact(**compact_kwargs) compacted_usage = getattr(compacted, "usage", None) - if wrapper is not None and compacted_usage is not None: - wrapper.usage.add(_response_usage_to_usage(compacted_usage)) + if wrapper is not None: + usage = ( + _response_usage_to_usage(compacted_usage) if compacted_usage is not None else None + ) + if wrapper._budget is not None: + wrapper._budget.observe(usage) + if usage is not None: + wrapper.usage.add(usage) output_items = _strip_orphaned_assistant_ids( _normalize_compaction_output_items(compacted.output or []) diff --git a/src/agents/models/chatcmpl_stream_handler.py b/src/agents/models/chatcmpl_stream_handler.py index b0c041f9cb..60b138734e 100644 --- a/src/agents/models/chatcmpl_stream_handler.py +++ b/src/agents/models/chatcmpl_stream_handler.py @@ -1369,7 +1369,7 @@ def _build_response_usage(usage: CompletionUsage | None) -> ResponseUsage | None """Convert the streamed provider usage into a Responses usage payload.""" if usage is None: return None - return ResponseUsage( + result = ResponseUsage( input_tokens=usage.prompt_tokens or 0, output_tokens=usage.completion_tokens or 0, total_tokens=usage.total_tokens or 0, @@ -1386,3 +1386,7 @@ def _build_response_usage(usage: CompletionUsage | None) -> ResponseUsage | None cache_write_tokens=_cache_write_tokens(usage.prompt_tokens_details), ), ) + if usage.total_tokens is None: + # Keep the public numeric default without reporting a measured zero. + object.__setattr__(result, "_agents_sdk_total_missing", True) + return result diff --git a/src/agents/models/openai_chatcompletions.py b/src/agents/models/openai_chatcompletions.py index 8528d0ac37..af457c38b5 100644 --- a/src/agents/models/openai_chatcompletions.py +++ b/src/agents/models/openai_chatcompletions.py @@ -320,6 +320,7 @@ async def get_response( # The request completed, so it counts even when the provider omits usage. else Usage(requests=1) ) + usage._total_missing = response.usage is None or response.usage.total_tokens is None # Record the request and token usage on the span before the terminal # branches below, so a ModelBehaviorError raised for a truncated empty diff --git a/src/agents/run.py b/src/agents/run.py index 57ca88bbe2..ed224bc2ba 100644 --- a/src/agents/run.py +++ b/src/agents/run.py @@ -44,6 +44,7 @@ from .memory import Session from .memory.resumable_session import ResumableSession from .result import RunResult, RunResultStreaming +from .run_budget import _prepare_budget from .run_config import ( DEFAULT_MAX_TURNS, CallModelData, @@ -657,6 +658,7 @@ 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, session) resolved_reasoning_item_id_policy: ReasoningItemIdPolicy | None = ( run_config.reasoning_item_id_policy if run_config.reasoning_item_id_policy is not None @@ -716,7 +718,7 @@ async def _run_impl( previous_response_id=previous_response_id, auto_previous_response_id=auto_previous_response_id, ) - context_wrapper = ensure_context_wrapper(context) + context_wrapper = ensure_context_wrapper(context)._for_new_root(budget) if isinstance(session, ResumableRun): await session.begin(input) context_wrapper._resolve_function_approval_owners(starting_agent) @@ -2671,6 +2673,9 @@ def run_streamed( if run_config.tracing_disabled else contextlib.nullcontext(), ): + budget = _prepare_budget( + run_config, starting_agent, input if isinstance(input, RunState) else None, session + ) # Handle RunState input is_resumed_state = isinstance(input, RunState) run_state: RunState[TContext] | None = None @@ -2739,7 +2744,7 @@ def run_streamed( previous_response_id=previous_response_id, auto_previous_response_id=auto_previous_response_id, ) - context_wrapper = ensure_context_wrapper(context) + context_wrapper = ensure_context_wrapper(context)._for_new_root(budget) context_wrapper._resolve_function_approval_owners(starting_agent) set_agent_tool_state_scope(context_wrapper, uuid4().hex) # input_for_state is the same as input_for_result here diff --git a/src/agents/run_budget.py b/src/agents/run_budget.py new file mode 100644 index 0000000000..e98e16ee2d --- /dev/null +++ b/src/agents/run_budget.py @@ -0,0 +1,328 @@ +"""Limits on model admissions and observed response usage in a Runner run.""" + +from __future__ import annotations + +import copy +import inspect +from collections.abc import Callable, Iterable +from dataclasses import dataclass, field, replace +from typing import TYPE_CHECKING, Any, Literal + +from .exceptions import AgentsException, UserError +from .usage import Usage + +if TYPE_CHECKING: + from .agent import Agent + from .memory import Session + from .models.interface import Model + from .run_config import RunConfig + from .run_state import RunState + from .tool import Tool + + +def _valid_limit(value: object) -> bool: + return type(value) is int and 0 <= value <= 2**53 - 1 + + +@dataclass(frozen=True) +class RunBudget: + """Limits for one Python Runner root, including handoffs and approval resumes. + + Set at least one integer limit from zero through 2**53 - 1. Zero blocks the first + admission. A response may finish above a limit. The next admission then fails. + + Each new regular model invocation counts once, including follow-ups and corrections. + Runner and transport retries, compaction, approval replies and replay add no admissions. + Agent tools and other nested runs have independent budgets. Native sampling through + CodexProvider and hosted multi-agent orchestration are unsupported. Independent + Runner calls, guardrails, sandbox memory, and tool-owned clients are outside the + root. These limits cannot bound physical sends or billing. + + Tokens and estimated cost use completed root responses and reported session compactions. + Failed attempts, child responses and cumulative snapshots are excluded. Only usage + visible to the SDK counts. Adapters that replace missing totals with explicit zeros + make those totals indistinguishable from measured zero. Before the next + admission, the synchronous estimator receives each completion's Usage and returns + millionths of a US dollar in the same integer range, or None for an unknown estimate. + Missing or negative totals, a missing estimator or unknown cost block the next admission + when needed by a limit. Set missing_usage="continue" to use only known values. + + Pass the budget to RunConfig(budget=...) on each call, including resume. RunBudgetError + identifies a blocked admission. Estimated-cost budgets support in-memory + continuation only. ResumableSession rejects cost limits anywhere in the agent graph. + A paused child budget requires a unique, enabled binding in its parent's tools. + Keep the tool graph and policies stable during each invocation. + Child budget errors follow the agent tool's error policy. An unhandled tool failure + leaves a durable session active for reconciliation. A new run starts with fresh counters. + """ + + max_requests: int | None = None + max_tokens: int | None = None + max_estimated_cost_micros: int | None = None + estimate_cost_micros: Callable[[Usage], int | None] | None = None + missing_usage: Literal["stop", "continue"] = "stop" + + def __post_init__(self) -> None: + limits = (self.max_requests, self.max_tokens, self.max_estimated_cost_micros) + if all(limit is None for limit in limits): + 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 self.estimate_cost_micros is not None and ( + not callable(self.estimate_cost_micros) + or inspect.iscoroutinefunction(self.estimate_cost_micros) + ): + raise TypeError("RunBudget.estimate_cost_micros must be a synchronous callable.") + + +class _BudgetCheckpointError(UserError): + """A budget failure that must also abort an enclosing agent-tool checkpoint.""" + + +class RunBudgetError(AgentsException): + """A blocked admission. The code identifies the reason.""" + + def __init__( + self, + code: Literal[ + "run_budget_exceeded", "run_budget_usage_unavailable", "run_budget_invalid_estimate" + ], + ): + self.code = code + super().__init__(code) + + +def _estimate(estimator: Callable[[Usage], int | None], usage: Usage) -> int | None: + try: + value = estimator(usage) + if value is None or _valid_limit(value): + return value + if inspect.iscoroutine(value): + value.close() + except Exception: + pass + raise RunBudgetError("run_budget_invalid_estimate") + + +@dataclass +class _BudgetState: + limits: RunBudget + requests: int = 0 + tokens: int = 0 + unavailable: bool = False + cost: int = 0 + pending: list[Usage] = field(default_factory=list) + + def observe(self, usage: Usage | None) -> None: + limits = self.limits + if limits.max_tokens is None and limits.max_estimated_cost_micros is None: + return + if ( + usage is None + or (usage._total_missing and usage.total_tokens == 0) + or usage.total_tokens < 0 + ): + self.unavailable = True + return + self.tokens += usage.total_tokens + if limits.max_estimated_cost_micros is not None: + if limits.estimate_cost_micros is None: + self.unavailable = True + else: + self.pending.append(copy.deepcopy(usage)) + + def check(self) -> None: + limits = self.limits + for count, ceiling in ( + (self.requests, limits.max_requests), + (self.tokens, limits.max_tokens), + (self.cost, limits.max_estimated_cost_micros), + ): + if ceiling is not None and count >= ceiling: + raise RunBudgetError("run_budget_exceeded") + if self.unavailable and limits.missing_usage == "stop": + raise RunBudgetError("run_budget_usage_unavailable") + while self.pending: + assert limits.estimate_cost_micros is not None + assert limits.max_estimated_cost_micros is not None + estimate = _estimate(limits.estimate_cost_micros, self.pending[0]) + self.pending.pop(0) + if estimate is None: + self.unavailable = True + if limits.missing_usage == "stop": + raise RunBudgetError("run_budget_usage_unavailable") + else: + self.cost += estimate + if self.cost >= limits.max_estimated_cost_micros: + raise RunBudgetError("run_budget_exceeded") + + def checkpoint(self) -> dict[str, Any]: + if self.limits.max_estimated_cost_micros is not None: + raise _BudgetCheckpointError("Cannot serialize an estimated-cost budget.") + return { + "max_requests": self.limits.max_requests, + "max_tokens": self.limits.max_tokens, + "missing_usage": self.limits.missing_usage, + "requests": self.requests, + "tokens": self.tokens, + "unavailable": self.unavailable, + } + + @classmethod + def restore(cls, data: Any) -> _BudgetState: + if not isinstance(data, dict) or data.keys() != { + "max_requests", + "max_tokens", + "missing_usage", + "requests", + "tokens", + "unavailable", + }: + raise _BudgetCheckpointError("Invalid run budget checkpoint.") + if ( + any(type(data[k]) is not int or data[k] < 0 for k in ("requests", "tokens")) + or type(data["unavailable"]) is not bool + ): + raise _BudgetCheckpointError("Invalid run budget consumption.") + try: + limits = RunBudget( + max_requests=data["max_requests"], + max_tokens=data["max_tokens"], + missing_usage=data["missing_usage"], + ) + except ValueError: + raise _BudgetCheckpointError("Invalid run budget limits.") from None + return cls(limits, data["requests"], data["tokens"], data["unavailable"]) + + +def _check_model(model: object) -> 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.") + + +def _tool_config(tool: Tool) -> RunConfig | None: + invoker = getattr(tool, "on_invoke_tool", None) + impl = getattr(invoker, "_invoke_tool_impl", None) + return getattr(impl, "__agents_run_config__", None) + + +def _check_portable(limits: RunBudget | None) -> None: + if limits is not None and limits.max_estimated_cost_micros is not None: + raise UserError("ResumableSession cannot checkpoint an estimated-cost budget.") + + +def _check_tools(tools: Iterable[Tool]) -> None: + for tool in tools: + config = _tool_config(tool) + if config is not None: + _check_portable(config.budget) + + +async def _admit( + budget: _BudgetState | None, model: Model, session: Session | None, tools: Iterable[Tool] +) -> None: + from .run_internal.resumable_session import ResumableRun + + try: + if isinstance(session, ResumableRun): + # Include tools resolved dynamically after the initial graph check. + _check_tools(tools) + if budget is not None: + _check_model(model) + budget.check() + budget.requests += 1 + except (RunBudgetError, UserError): + if isinstance(session, ResumableRun): + await session.finish_budget_stop() + raise + + +def _effective_limits(config: RunConfig | None) -> RunBudget | None: + limits = config.budget if config is not None else None + if ( + limits is not None + and limits.max_estimated_cost_micros is None + and limits.estimate_cost_micros is not None + ): + return replace(limits, estimate_cost_micros=None) + return limits + + +def _check_resume(state: RunState[Any], limits: RunBudget | 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 + from .agent_tool_state import get_agent_tool_resume_state, peek_agent_tool_run_result + from .tool import FunctionTool + + saved = state._context._budget if state._context is not None else None + if (saved.limits if saved is not None else None) != limits: + raise UserError("Resume requires the same RunBudget limits and missing_usage policy.") + budgeted = saved is not None + for action in getattr(state._last_processed_response, "functions", ()): + if not action.function_tool._is_agent_tool: + continue + result = peek_agent_tool_run_result( + action.tool_call, scope_id=state._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: + continue + # Turn resolution can rebind a queued call after load_state(). Check + # the current qualified binding without running enablement callbacks. + key = get_function_tool_lookup_key_for_call(action.tool_call) + tools = state._current_agent.tools if state._current_agent is not None else [] + bindings = [ + tool + for tool in tools + if isinstance(tool, FunctionTool) and key in get_function_tool_lookup_keys(tool) + ] + policies = (_effective_limits(_tool_config(tool)) for tool in bindings) + policy = next((value for value in policies if value is not None), None) + if _check_resume(child, policy): + if ( + len(bindings) != 1 + or bindings[0].is_enabled is False + or bindings[0]._agent_instance is not action.function_tool._agent_instance + ): + raise UserError("A pending RunBudget requires the same unique agent tool.") + budgeted = True + return budgeted + + +def _prepare_budget( + config: RunConfig, agent: Agent[Any], state: RunState[Any] | None, session: Session | None +) -> _BudgetState | None: + from .models.interface import Model + from .run_internal.resumable_session import ResumableRun + + limits = _effective_limits(config) + if state is not None: + _check_resume(state, limits) + current = ( + state._current_agent if state is not None and state._current_agent is not None else agent + ) + if isinstance(session, ResumableRun): + from ._run_state_agent_identity import _iter_agent_graph + + _check_portable(limits) + for reachable in _iter_agent_graph(current): + _check_tools(reachable.tools) + 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) + if state is not None: + assert state._context is not None + return state._context._budget + budget = _BudgetState(limits) + budget.check() + return budget diff --git a/src/agents/run_config.py b/src/agents/run_config.py index c65d9cbd75..ffac97aa3a 100644 --- a/src/agents/run_config.py +++ b/src/agents/run_config.py @@ -28,6 +28,7 @@ from .model_settings import ModelSettings, _coerce_model_settings, _declared_model_settings_type from .models.interface import Model, ModelProvider from .models.multi_provider import MultiProvider +from .run_budget import RunBudget from .run_context import TContext from .run_error_handlers import RunErrorHandlers from .tracing import TracingConfig @@ -589,6 +590,9 @@ class RunConfig: output and guardrail ``output_info`` are never passed to the formatter. """ + budget: RunBudget | None = None + """Optional limits on root model admissions and observed response usage.""" + if TYPE_CHECKING: def __init__( @@ -620,9 +624,14 @@ def __init__( output_guardrail_blocked_message: ( str | OutputGuardrailBlockedMessageFormatter | None ) = None, + budget: RunBudget | dict[str, Any] | None = None, ) -> None: ... def __post_init__(self) -> None: + if self.budget is not None: + self.budget = coerce_dataclass_config( + self.budget, RunBudget, parameter_name="run_config.budget" + ) if self.tool_name_collision_policy not in ("warn", "error"): raise ValueError("tool_name_collision_policy must be either 'warn' or 'error'") blocked_message = self.output_guardrail_blocked_message diff --git a/src/agents/run_context.py b/src/agents/run_context.py index 77ae747a8e..480971f8db 100644 --- a/src/agents/run_context.py +++ b/src/agents/run_context.py @@ -5,7 +5,7 @@ import weakref from collections.abc import Callable, Mapping from dataclasses import dataclass, field -from typing import TYPE_CHECKING, Annotated, Any, Generic +from typing import TYPE_CHECKING, Annotated, Any, Generic, cast from uuid import uuid4 from pydantic import ( @@ -39,6 +39,7 @@ tool_output_identity, ) from .exceptions import ModelBehaviorError, UserError +from .run_budget import _BudgetState from .usage import Usage if TYPE_CHECKING: @@ -211,6 +212,16 @@ class RunContextWrapper(Generic[TContext]): repr=False, ) + # Runtime-only state. RunState owns its portable representation. + _budget = cast("_BudgetState | None", None) + + def _for_new_root(self, budget: _BudgetState | None) -> RunContextWrapper[TContext]: + if budget is None and self._budget is None: + return self + root = copy.copy(self) + root._budget = budget + return root + @model_validator(mode="wrap") @classmethod def _restore_converted_tool_state( @@ -286,6 +297,9 @@ def _copy_for_run_state(self) -> RunContextWrapper[TContext]: # checkpoint's tokens land on every other checkpoint and on the result # the checkpoints came from. copied.usage = copy.deepcopy(self.usage) + if self._budget is not None: + copied._budget = copy.copy(self._budget) + copied._budget.pending = copy.deepcopy(self._budget.pending) copied._approvals = copy.deepcopy(self._approvals) copied._tool_invocations = copy.deepcopy(self._tool_invocations) copied._restored_unbound_approval_call_ids = set(self._restored_unbound_approval_call_ids) diff --git a/src/agents/run_internal/model_retry.py b/src/agents/run_internal/model_retry.py index 4f23b729a8..b19f2864a0 100644 --- a/src/agents/run_internal/model_retry.py +++ b/src/agents/run_internal/model_retry.py @@ -35,6 +35,7 @@ _coerce_backoff_settings, retry_policy_retries_safe_transport_errors, ) +from ..run_budget import _BudgetState from ..tracing._model import ModelRetrySpans, model_retry_scope from ..usage import RequestUsage, Usage from ..util._error_tracing import mark_model_timeout_task @@ -606,6 +607,7 @@ async def get_response_with_retry( timeout: float | None = None, replay_unsafe_request: bool = False, reported_usage: dict[int, Usage] | None = None, + budget: _BudgetState | None = None, ) -> ModelResponse: request_attempt = 1 policy_attempt = 1 @@ -639,6 +641,8 @@ async def get_response_with_retry( model_retry_scope(model_spans, request_attempt), ): response = await _await_model_attempt(get_response(), timeout) + if budget is not None: + budget.observe(response.usage) response.usage = apply_retry_attempt_usage( response.usage, request_attempt - 1, reported_usage ) diff --git a/src/agents/run_internal/resumable_session.py b/src/agents/run_internal/resumable_session.py index a55fba5c31..a529aadd2f 100644 --- a/src/agents/run_internal/resumable_session.py +++ b/src/agents/run_internal/resumable_session.py @@ -44,6 +44,11 @@ async def finish(self, result: RunResult | RunResultStreaming) -> None: state._resumable_binding = "detached" result._resumable_binding = await self._source._save_checkpoint(self._items, state) + async def finish_budget_stop(self) -> None: + """Keep completed work when the next request was refused before dispatch.""" + assert self._source is not None + await self._source._save_checkpoint(self._items, None) + def configure_stream(self, result: RunResultStreaming) -> None: queue = _CheckpointEventQueue() result._event_queue = queue diff --git a/src/agents/run_internal/run_loop.py b/src/agents/run_internal/run_loop.py index 659642845a..404a5a14a2 100644 --- a/src/agents/run_internal/run_loop.py +++ b/src/agents/run_internal/run_loop.py @@ -75,6 +75,7 @@ ) from ..models._run_context import ModelToolHooks, model_run_context, model_run_context_stream from ..result import RunResultStreaming +from ..run_budget import _admit from ..run_config import ReasoningItemIdPolicy, RunConfig from ..run_context import AgentHookContext, RunContextWrapper, TContext from ..run_error_handlers import RunErrorHandlers @@ -2667,6 +2668,7 @@ def get_model_stream() -> AsyncIterator[TResponseStreamEvent]: prompt=prompt_config, ) + await _admit(context_wrapper._budget, model, session, all_tools) retry_stream = stream_response_with_retry( get_stream=get_model_stream, rewind=rewind_model_request, @@ -2732,16 +2734,16 @@ def get_model_stream() -> AsyncIterator[TResponseStreamEvent]: # provider usage (common for some Chat Completions / LiteLLM streams). Skipping # apply_retry_attempt_usage here would drop failed-attempt accounting and diverge # from the non-streaming get_response_with_retry path. - usage = apply_retry_attempt_usage( - ( - _response_usage_to_usage(terminal_response.usage) - if terminal_response.usage - # Defaults to zero requests, so adapters that fold several provider - # responses into one and report counts separately are not double-counted. - else Usage(requests=_requests_for_response_without_usage(terminal_response)) - ), - stream_failed_retry_attempts[0], + usage = ( + _response_usage_to_usage(terminal_response.usage) + if terminal_response.usage + # Defaults to zero requests, so adapters that fold several provider + # responses into one and report counts separately are not double-counted. + else Usage(requests=_requests_for_response_without_usage(terminal_response)) ) + if context_wrapper._budget is not None: + context_wrapper._budget.observe(usage) + usage = apply_retry_attempt_usage(usage, stream_failed_retry_attempts[0]) final_response = ModelResponse( output=terminal_response.output, usage=usage, @@ -3121,7 +3123,9 @@ async def rewind_model_request() -> None: ), record_failed_attempt_usage_on_error(context_wrapper.usage) as reported_usage, ): + await _admit(context_wrapper._budget, model, session, all_tools) new_response = await get_response_with_retry( + budget=context_wrapper._budget, get_response=lambda: model.get_response( system_instructions=filtered.instructions, input=filtered.input, diff --git a/src/agents/run_state.py b/src/agents/run_state.py index 20c8ce2755..5bd9412646 100644 --- a/src/agents/run_state.py +++ b/src/agents/run_state.py @@ -110,6 +110,7 @@ log_model_and_tool_data_warning, logger, ) +from .run_budget import _BudgetCheckpointError, _BudgetState from .run_context import RunContextWrapper, _ApprovalRecord, _FunctionToolApprovalKey from .run_internal.items import ( NestedHistoryOwnedItemRef, @@ -312,7 +313,7 @@ def _default_run_state_validation_error( ), "1.23": ( "Binds prepared tool inputs to their original proposals across retries and resume, " - "and records required ResumableSession ownership for paused runs." + "and records ResumableSession ownership and optional root budgets for paused runs." ), } SUPPORTED_SCHEMA_VERSIONS = frozenset(SCHEMA_VERSION_SUMMARIES) @@ -1982,6 +1983,7 @@ def to_json( "Use unique agent names before starting a persistable run." ) + budget = self._context._budget.checkpoint() if self._context._budget is not None else None approvals_dict = self._serialize_approvals() tool_invocations = self._serialize_tool_invocations() hosted_mcp_approvals = self._serialize_hosted_mcp_approvals() @@ -2000,6 +2002,8 @@ def to_json( # Preserve metadata so deserialization can warn when context types were erased. "context_meta": context_meta, } + if budget is not None: + context_entry["budget"] = budget tool_input = self._serialize_tool_input(self._context.tool_input) if tool_input is not None: context_entry["tool_input"] = tool_input @@ -2567,6 +2571,10 @@ def validation_error_factory( validation_error_factory=validation_error_factory, ) except BaseException as error: + if isinstance(error, _BudgetCheckpointError): + error = validation_error_factory( + "Invalid RunBudget checkpoint or schema version.", UserError + ) trusted_error_message = _trusted_run_state_validation_message( error, trusted_validation_errors, @@ -3049,6 +3057,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 @@ -3247,6 +3257,8 @@ async def _restore_pending_nested_agent_tool_runs( strict_context=strict_context, validation_error_factory=validation_error_factory, ) + except _BudgetCheckpointError: + raise except Exception: if strict_context: raise @@ -4280,6 +4292,11 @@ async def _build_run_state_from_json( raise validation_error_factory("Run state agent not found in agent map", UserError) context_data = state_json["context"] + budget = None + if "budget" in context_data: + if (schema_major, schema_minor) < (1, 23): + raise _BudgetCheckpointError("Run budgets require schema 1.23 or later.") + budget = _BudgetState.restore(context_data["budget"]) usage = deserialize_usage(context_data.get("usage", {})) serialized_context: Any = context_data.get("context", _MISSING_CONTEXT_SENTINEL) @@ -4342,6 +4359,7 @@ async def _build_run_state_from_json( "Serialized run state context must be a mapping. Please provide one.", UserError, ) + context = context._for_new_root(budget) context.usage = usage context._restored_unbound_approval_call_ids = set() context._allow_legacy_approval_binding_reconstruction = (schema_major, schema_minor) < (1, 15) @@ -5700,6 +5718,7 @@ def _clone_original_input(original_input: str | list[Any]) -> str | list[Any]: "Run state nested history ownership references a missing input item", "Run state nested history ownership session digest does not match", "Run state nested history ownership input digest does not match", + "Invalid RunBudget checkpoint or schema version.", "RunState tool_invocations must be a mapping.", "RunState tool_invocations contains an invalid call ID.", "RunState tool invocation must be a mapping.", diff --git a/src/agents/usage.py b/src/agents/usage.py index 90157fab16..a55f5f8e50 100644 --- a/src/agents/usage.py +++ b/src/agents/usage.py @@ -8,8 +8,16 @@ from openai.types.completion_usage import CompletionTokensDetails, PromptTokensDetails from openai.types.responses.response_usage import InputTokensDetails, OutputTokensDetails -from pydantic import BeforeValidator, JsonValue, TypeAdapter, ValidationError +from pydantic import ( + BeforeValidator, + JsonValue, + ModelWrapValidatorHandler, + TypeAdapter, + ValidationError, + model_validator, +) from pydantic.dataclasses import dataclass +from pydantic_core import ArgsKwargs _RAW_USAGE_ATTRIBUTE = "_agents_sdk_raw_usage" _NORMALIZED_USAGE_ATTRIBUTE = "_agents_sdk_normalized_usage" @@ -228,6 +236,23 @@ class Usage: cost calculation or context window management. """ + _total_missing = False + + @model_validator(mode="wrap") + @classmethod + def _remember_total_presence( + cls, value: Any, handler: ModelWrapValidatorHandler[Usage] + ) -> Usage: + usage = handler(value) + if isinstance(value, ArgsKwargs): + # total_tokens is the sixth positional field in the released constructor. + usage._total_missing = len(value.args) < 6 and "total_tokens" not in ( + value.kwargs or {} + ) + elif isinstance(value, Mapping): + usage._total_missing = "total_tokens" not in value + return usage + def __post_init__(self) -> None: # Some providers don't populate optional token detail fields # (cached_tokens, cache_write_tokens, reasoning_tokens), and the OpenAI SDK's generated @@ -262,6 +287,7 @@ def add(self, other: Usage) -> None: Args: other: The Usage object to add to this one. """ + self._total_missing = self._total_missing and other._total_missing self.requests += other.requests if other.requests else 0 self.input_tokens += other.input_tokens if other.input_tokens else 0 self.output_tokens += other.output_tokens if other.output_tokens else 0 @@ -370,7 +396,7 @@ def _response_usage_to_usage(response_usage: Any) -> Usage: usage.requests = max(usage.requests, request_count) return usage - return Usage( + usage = Usage( requests=request_count, input_tokens=response_usage.input_tokens or 0, output_tokens=response_usage.output_tokens or 0, @@ -378,6 +404,11 @@ def _response_usage_to_usage(response_usage: Any) -> Usage: input_tokens_details=response_usage.input_tokens_details, output_tokens_details=response_usage.output_tokens_details, ) + usage._total_missing = ( + response_usage.total_tokens is None + or getattr(response_usage, "_agents_sdk_total_missing", False) is True + ) + return usage def _attach_normalized_usage(target: Any, usage: Usage) -> None: diff --git a/tests/test_run_budget.py b/tests/test_run_budget.py new file mode 100644 index 0000000000..d35727b70c --- /dev/null +++ b/tests/test_run_budget.py @@ -0,0 +1,604 @@ +"""Root budget contracts through the public Runner and approval boundaries.""" + +from __future__ import annotations + +from dataclasses import replace +from types import SimpleNamespace +from unittest.mock import AsyncMock, MagicMock + +import httpx +import httpx2 +import pytest +from openai import APIConnectionError, AsyncOpenAI + +from agents import ( + Agent, + MaxTurnsExceeded, + ModelRetrySettings, + ModelSettings, + RunBudget, + RunBudgetError, + RunConfig, + Runner, + RunState, + Usage, + UserError, + retry_policies, + tool_namespace, +) +from agents.decorators import tool +from agents.memory.openai_responses_compaction_session import OpenAIResponsesCompactionSession +from agents.memory.resumable_session import ResumableSession +from agents.models.codex import CodexProvider +from agents.models.openai_responses import OpenAIResponsesModel +from agents.testing import ModelStep, ScriptedModel +from tests.memory.test_openai_responses_compaction_session import SimpleListSession +from tests.memory.test_resumable_session import MemoryStore +from tests.model_test_helpers import get_response_obj +from tests.test_responses import get_function_tool_call, get_handoff_tool_call, get_text_message + + +async def run(agent, budget, streamed=False, input="begin", **kwargs): + config = RunConfig( + budget=budget, tracing_disabled=True, tool_not_found_behavior="return_error_to_model" + ) + if not streamed: + return await Runner.run(agent, input, run_config=config, **kwargs) + result = Runner.run_streamed(agent, input, run_config=config, **kwargs) + async for _ in result.stream_events(): + pass + return result + + +def step(item, total=None): + usage = Usage(requests=1) if total is None else Usage(requests=1, total_tokens=total) + return ModelStep(output=[item], usage=usage) + + +@pytest.mark.parametrize("value", [None, -1, True, 1.5, 2**53]) +def test_invalid_limits(value): + with pytest.raises(ValueError, match="RunBudget"): + RunConfig(budget={"max_tokens": value}) + + +@pytest.mark.parametrize("limit", ["max_requests", "max_tokens", "max_estimated_cost_micros"]) +def test_zero_blocks_sync_dispatch(limit): + model = ScriptedModel() + with pytest.raises(RunBudgetError, match="run_budget_exceeded"): + Runner.run_sync(Agent(name="root", model=model), "begin", run_config={"budget": {limit: 0}}) + assert not model.calls + + +@pytest.mark.asyncio +@pytest.mark.parametrize("streamed", [False, True]) +async def test_retry_counted_once_and_overshoot_can_finish(streamed): + model = ScriptedModel( + [ + APIConnectionError(request=httpx.Request("POST", "https://example.invalid")), + step(get_function_tool_call("unknown"), 2), + step(get_text_message("done"), 20), + ] + ) + retry = ModelRetrySettings( + max_retries=1, policy=retry_policies.network_error(), backoff={"initial_delay": 0} + ) + agent = Agent(name="root", model=model, model_settings=ModelSettings(retry=retry)) + result = await run(agent, RunBudget(max_requests=2, max_tokens=3), streamed, max_turns=2) + assert result.final_output == "done" + assert result.context_wrapper.usage.requests == len(model.calls) == 3 + + +@pytest.mark.asyncio +@pytest.mark.parametrize("streamed", [False, True]) +@pytest.mark.parametrize( + "total,policy,code", + [ + (0, "stop", None), + (None, "stop", "run_budget_usage_unavailable"), + (-1, "stop", "run_budget_usage_unavailable"), + (None, "continue", None), + (10, "stop", "run_budget_exceeded"), + ], +) +async def test_correction_uses_observed_totals(streamed, total, policy, code): + model = ScriptedModel( + [step(get_function_tool_call("unknown"), total), [get_text_message("done")]] + ) + agent = Agent(name="root", model=model) + budget = RunBudget(max_tokens=5, missing_usage=policy) + if code: + with pytest.raises(RunBudgetError, match=code): + await run(agent, budget, streamed) + assert len(model.calls) == 1 + else: + assert (await run(agent, budget, streamed)).final_output == "done" + + +def failing_estimate(usage): + raise RuntimeError("private estimator detail") + + +@pytest.mark.asyncio +@pytest.mark.parametrize( + "estimator,code", + [ + (None, "run_budget_usage_unavailable"), + (lambda u: None, "run_budget_usage_unavailable"), + (lambda u: u.total_tokens * 2, "run_budget_exceeded"), + (lambda u: True, "run_budget_invalid_estimate"), + (lambda u: 2**53, "run_budget_invalid_estimate"), + (failing_estimate, "run_budget_invalid_estimate"), + ], +) +async def test_estimates_fail_distinctly_without_callback_details(estimator, code): + model = ScriptedModel([step(get_function_tool_call("unknown"), 3)]) + budget = RunBudget(max_estimated_cost_micros=6, estimate_cost_micros=estimator) + with pytest.raises(RunBudgetError) as error: + await run(Agent(name="root", model=model), budget) + assert error.value.code == code + assert error.value.__context__ is None + assert len(model.calls) == 1 + + +@pytest.mark.asyncio +async def test_max_turns_still_limits_corrections(): + model = ScriptedModel([[get_function_tool_call("unknown")]]) + with pytest.raises(MaxTurnsExceeded): + await run(Agent(name="root", model=model), RunBudget(max_requests=2), max_turns=1) + assert len(model.calls) == 1 + + +@pytest.mark.asyncio +@pytest.mark.parametrize("streamed", [False, True]) +@pytest.mark.parametrize("portable", [False, True]) +async def test_resume_after_handoff_checks_policy_before_approval(streamed, portable): + effects = [] + + @tool(needs_approval=True) + def record() -> str: + effects.append(1) + return "saved" + + target_model = ScriptedModel([step(get_function_tool_call("record"), 7)]) + target = Agent(name="target", model=target_model, tools=[record]) + model = ScriptedModel([step(get_handoff_tool_call(target), 2)]) + root = Agent(name="root", model=model, handoffs=[target]) + budget = RunBudget(max_requests=4, max_tokens=5) + result = await run(root, budget, streamed) + state = result.to_state() + if portable: + state = await RunState.from_string(root, state.to_string()) + assert state.to_json()["context"]["budget"]["tokens"] == 9 + state.approve(state.get_interruptions()[0]) + for changed in ( + None, + replace(budget, max_tokens=10), + replace(budget, missing_usage="continue"), + ): + with pytest.raises(UserError, match="same RunBudget"): + await run(root, changed, not streamed, state) + assert not effects + with pytest.raises(RunBudgetError, match="exceeded"): + await run(root, budget, not streamed, state) + assert effects == [1] + assert len(model.calls) == len(target_model.calls) == 1 + + +@pytest.mark.asyncio +@pytest.mark.parametrize("streamed", [False, True]) +async def test_durable_approval_stop_preserves_effect_and_idle_budget(streamed): + effects = [] + + @tool(needs_approval=True) + def record() -> str: + effects.append(1) + return "saved" + + store = MemoryStore() + session = await ResumableSession.create(store) + model = ScriptedModel([[get_function_tool_call("record")], [get_text_message("fresh")]]) + root = Agent(name="root", model=model, tools=[record]) + budget = RunBudget(max_requests=1) + for invalid, error in [ + (RunBudget(max_requests=0), RunBudgetError), + (RunBudget(max_estimated_cost_micros=1), UserError), + ]: + with pytest.raises(error): + await run(root, invalid, streamed, session=session) + await run(root, budget, streamed, session=session) + restored = await ResumableSession.resume(store, session.session_id) + state = await restored.load_state(root) + state.approve(state.get_interruptions()[0]) + with pytest.raises(UserError, match="same RunBudget"): + await run(root, replace(budget, missing_usage="continue"), streamed, state) + assert restored.is_paused and not effects + with pytest.raises(RunBudgetError, match="exceeded"): + await run(root, budget, streamed, state) + assert effects == [1] and len(model.calls) == 1 + assert store.checkpoint(session.session_id)["status"] == "ready" + assert (await run(root, budget, streamed, session=restored)).final_output == "fresh" + assert "saved" in str(model.calls[-1].input) + assert effects == [1] + + +@pytest.mark.asyncio +async def test_live_cost_approval_rejects_portable_capture(): + @tool(needs_approval=True) + def record() -> str: + return "saved" + + budget = RunBudget(max_estimated_cost_micros=1, missing_usage="continue") + model = ScriptedModel([step(get_function_tool_call("record"), 1), [get_text_message("done")]]) + root = Agent(name="root", model=model, tools=[record]) + state = (await run(root, budget)).to_state() + with pytest.raises(UserError, match="estimated-cost"): + state.to_string() + state.approve(state.get_interruptions()[0]) + assert (await run(root, budget, input=state)).final_output == "done" + + +@pytest.mark.asyncio +@pytest.mark.parametrize("streamed", [False, True]) +async def test_nested_tool_has_independent_budget_and_usage(streamed): + child_model = ScriptedModel( + [step(get_function_tool_call("unknown"), 50), step(get_text_message("child"), 50)] + ) + child = Agent(name="child", model=child_model) + nested = child.as_tool( + "ask", + "Ask child", + on_stream=(lambda event: None) if streamed else None, + failure_error_function=None, + ) + model = ScriptedModel( + [ + step(get_function_tool_call("ask", '{"input":"ask"}'), 1), + step(get_text_message("done"), 1), + ] + ) + result = await run( + Agent(name="root", model=model, tools=[nested]), + RunBudget(max_requests=2, max_tokens=2), + streamed, + ) + assert result.final_output == "done" + assert len(model.calls) == len(child_model.calls) == 2 + assert result.context_wrapper.usage.total_tokens == 102 + + +@pytest.mark.asyncio +async def test_compaction_charges_tokens_without_an_admission(): + # ScriptedModel does not own the separate session compaction endpoint. + client = MagicMock() + client.responses.compact = AsyncMock( + return_value=SimpleNamespace( + output=[{"type": "compaction", "encrypted_content": "synthetic"}], + usage=Usage(total_tokens=7), + ) + ) + session = OpenAIResponsesCompactionSession( + session_id="example", + underlying_session=SimpleListSession(), + client=client, + should_trigger_compaction=lambda ctx: True, + ) + model = ScriptedModel([step(get_text_message("done"), 2)]) + result = await run( + Agent(name="root", model=model), RunBudget(max_requests=1, max_tokens=3), session=session + ) + checkpoint = result.to_state().to_json()["context"]["budget"] + assert checkpoint["tokens"] == 9 and checkpoint["requests"] == 1 + + +@pytest.mark.asyncio +async def test_native_sampling_rejected_without_dispatch(): + with pytest.raises(UserError, match="native sampling"): + await Runner.run( + Agent(name="root"), + "begin", + run_config=RunConfig(model_provider=CodexProvider(), budget=RunBudget(max_requests=1)), + ) + + +@pytest.mark.asyncio +@pytest.mark.allow_call_model_methods +@pytest.mark.parametrize("total", [None, 0]) +async def test_responses_missing_total_before_normalization(total): + # The Responses adapter normalizes null totals before returning to Runner. + calls = [] + + async def respond(request): + calls.append(request) + item = get_function_tool_call("unknown") if len(calls) == 1 else get_text_message("done") + payload = get_response_obj([item]).model_dump() + payload["usage"] = { + "total_tokens": total, + "input_tokens": 0, + "output_tokens": 0, + "input_tokens_details": {"cached_tokens": 0}, + "output_tokens_details": {"reasoning_tokens": 0}, + } + return httpx2.Response(200, json=payload) + + async with AsyncOpenAI( + api_key="test-key", + base_url="https://example.invalid/v1", + http_client=httpx2.AsyncClient(transport=httpx2.MockTransport(respond)), + ) as client: + root = Agent( + name="root", model=OpenAIResponsesModel(model="synthetic", openai_client=client) + ) + budget = RunBudget(max_tokens=1) + if total is None: + with pytest.raises(RunBudgetError, match="unavailable"): + await run(root, budget) + assert len(calls) == 1 + else: + assert (await run(root, budget)).final_output == "done" + assert len(calls) == 2 + + +@pytest.mark.asyncio +@pytest.mark.parametrize("cost", [False, True]) +async def test_explicit_child_budget_survives_nested_approval(cost): + effects = [] + + @tool(needs_approval=True) + def record() -> str: + effects.append(1) + return "saved" + + child_model = ScriptedModel( + [ + step(get_function_tool_call("record", call_id="inner"), 8), + step(get_text_message("child"), 8), + ] + ) + child = Agent(name="child", model=child_model, tools=[record]) + child_budget = ( + RunBudget(max_estimated_cost_micros=9, estimate_cost_micros=lambda u: u.total_tokens) + if cost + else RunBudget(max_requests=2) + ) + nested = child.as_tool( + "ask", + "Ask child", + run_config=RunConfig(budget=child_budget, tracing_disabled=True), + failure_error_function=None, + ) + model = ScriptedModel( + [ + step(get_function_tool_call("ask", '{"input":"ask"}'), 1), + step(get_text_message("done"), 2), + ] + ) + root = Agent(name="root", model=model, tools=[nested]) + budget = RunBudget(max_requests=2, max_tokens=2) + state = (await run(root, budget)).to_state() + if cost: + with pytest.raises(UserError, match="estimated-cost"): + state.to_string() + else: + state = await RunState.from_string(root, state.to_string()) + state.approve(state.get_interruptions()[0]) + assert (await run(root, budget, True, state)).final_output == "done" + assert len(model.calls) == len(child_model.calls) == 2 + assert effects == [1] + + +@pytest.mark.asyncio +async def test_missing_observation_survives_checkpoint(): + @tool(needs_approval=True) + def record() -> str: + return "saved" + + model = ScriptedModel([[get_function_tool_call("record")]]) + root = Agent(name="root", model=model, tools=[record]) + budget = RunBudget(max_tokens=5) + paused = await run(root, budget) + data = paused.to_state().to_json() + with pytest.raises(UserError): + await RunState.from_json(root, {**data, "$schemaVersion": "1.22"}) + state = await RunState.from_json(root, data) + state.approve(state.get_interruptions()[0]) + with pytest.raises(RunBudgetError, match="unavailable"): + await run(root, budget, input=state) + assert len(model.calls) == 1 + + +@pytest.mark.asyncio +async def test_hosted_child_usage_cannot_be_isolated(): + from agents.extensions.experimental.hosted_multi_agent import OpenAIHostedMultiAgentModel + + root = Agent(name="root", model=OpenAIHostedMultiAgentModel(model="synthetic")) + with pytest.raises(UserError, match="hosted multi-agent"): + await run(root, RunBudget(max_tokens=2)) + + +@pytest.mark.asyncio +@pytest.mark.parametrize("streamed", [False, True]) +async def test_durable_child_policy_checked_before_claim(streamed): + effects = [] + + @tool(needs_approval=True) + def record() -> str: + effects.append(1) + return "saved" + + store = MemoryStore() + session = await ResumableSession.create(store) + inner = ScriptedModel( + [ + step(get_function_tool_call("record", call_id="inner"), 4), + step(get_text_message("child"), 4), + ] + ) + child = Agent(name="child", model=inner, tools=[record]) + config = RunConfig(budget=RunBudget(max_estimated_cost_micros=8), tracing_disabled=True) + nested = child.as_tool("ask", "Ask", run_config=config, failure_error_function=None) + outer = ScriptedModel( + [ + step(get_function_tool_call("ask", '{"input":"check"}'), 1), + step(get_text_message("done"), 1), + ] + ) + root = Agent(name="root", model=outer, tools=[nested]) + with pytest.raises(UserError, match="estimated-cost"): + await run(root, None, streamed, session=session) + assert not outer.calls and not inner.calls + assert store.checkpoint(session.session_id)["status"] == "ready" + budget = RunBudget(max_requests=2, max_tokens=5) + config.budget = budget + await run(root, budget, streamed, session=session) + restored = await ResumableSession.resume(store, session.session_id) + state = await restored.load_state(root) + state.approve(state.get_interruptions()[0]) + for changed in (None, replace(budget, missing_usage="continue"), RunBudget(max_requests=3)): + config.budget = changed + with pytest.raises(UserError, match="same RunBudget"): + await run(root, budget, streamed, state) + assert store.checkpoint(session.session_id)["status"] == "paused" + assert not effects + config.budget = budget + changed_tool = child.as_tool( + "ask", + "Ask", + run_config=RunConfig(budget=RunBudget(max_requests=3), tracing_disabled=True), + failure_error_function=None, + ) + disabled = child.as_tool("ask", "Ask", run_config=config, is_enabled=False) + for replacement in ([changed_tool], [disabled], [nested, changed_tool], []): + root.tools = replacement + with pytest.raises(UserError, match="RunBudget"): + await run(root, budget, streamed, state) + assert store.checkpoint(session.session_id)["status"] == "paused" + assert len(outer.calls) == len(inner.calls) == 1 + assert not effects + other = tool_namespace(name="other", description="Other tools", tools=[changed_tool]) + root.tools = [nested, *other] + assert (await run(root, budget, streamed, state)).final_output == "done" + assert len(outer.calls) == len(inner.calls) == 2 + assert effects == [1] + + +@pytest.mark.asyncio +@pytest.mark.parametrize("streamed", [False, True]) +async def test_failed_resume_keeps_debit_and_tool_receipt(streamed): + effects = [] + + @tool(needs_approval=True) + def save() -> str: + effects.append(1) + return "saved" + + model = ScriptedModel([[get_function_tool_call("save")], RuntimeError("offline")]) + root = Agent(name="root", model=model, tools=[save]) + budget = RunBudget(max_requests=2) + state = (await run(root, budget, streamed)).to_state() + state.approve(state.get_interruptions()[0]) + with pytest.raises(RuntimeError, match="offline"): + await run(root, budget, streamed, state) + restored = await RunState.from_string(root, state.to_string()) + with pytest.raises(RunBudgetError, match="exceeded"): + await run(root, budget, not streamed, restored) + assert len(model.calls) == 2 + assert effects == [1] + + +@pytest.mark.asyncio +@pytest.mark.allow_call_model_methods +@pytest.mark.parametrize("streamed", [False, True]) +@pytest.mark.parametrize( + ("total", "policy"), [("absent", "stop"), (None, "stop"), (0, "stop"), (None, "continue")] +) +async def test_chat_total_presence_survives_normalization(streamed, total, policy): + # Exercise Chat JSON and SSE conversion before the Runner sees normalized usage. + import json + + from agents.models.openai_chatcompletions import OpenAIChatCompletionsModel + + calls = [] + + async def respond(request): + calls.append(request) + usage = {"prompt_tokens": 0, "completion_tokens": 0} + if total != "absent": + usage["total_tokens"] = total + call = { + "id": "c1", + "type": "function", + "function": {"name": "unknown", "arguments": "{}"}, + } + if streamed: + call["index"] = 0 + first = len(calls) == 1 + message = {"tool_calls": [call]} if first else {"content": "done"} + payload = { + "id": "message", + "created": 1, + "model": "synthetic", + "object": "chat.completion.chunk" if streamed else "chat.completion", + "usage": usage, + "choices": [ + { + "index": 0, + "finish_reason": "tool_calls" if first else "stop", + "delta" if streamed else "message": {"role": "assistant", **message}, + } + ], + } + if streamed: + return httpx2.Response( + 200, + content=f"data: {json.dumps(payload)}\n\ndata: [DONE]\n\n", + headers={"content-type": "text/event-stream"}, + ) + return httpx2.Response(200, json=payload) + + async with AsyncOpenAI( + api_key="test-key", + base_url="https://example.invalid/v1", + http_client=httpx2.AsyncClient(transport=httpx2.MockTransport(respond)), + ) as client: + root = Agent( + name="root", model=OpenAIChatCompletionsModel(model="synthetic", openai_client=client) + ) + budget = RunBudget(max_tokens=1, missing_usage=policy) + if total != 0 and policy == "stop": + with pytest.raises(RunBudgetError, match="unavailable"): + await run(root, budget, streamed) + assert len(calls) == 1 + else: + assert (await run(root, budget, streamed)).final_output == "done" + assert len(calls) == 2 + + +@pytest.mark.asyncio +@pytest.mark.parametrize("streamed", [False, True]) +async def test_child_budget_stop_uses_existing_tool_error_policy(streamed): + @tool(needs_approval=True) + def record() -> str: + return "saved" + + store = MemoryStore() + session = await ResumableSession.create(store) + inner = ScriptedModel([[get_function_tool_call("record", call_id="inner")]]) + child = Agent(name="child", model=inner, tools=[record]) + nested = child.as_tool( + "ask", "Ask", run_config=RunConfig(budget=RunBudget(max_requests=1), tracing_disabled=True) + ) + outer = ScriptedModel( + [ + [get_function_tool_call("ask", '{"input":"check"}')], + [get_text_message("done")], + ] + ) + root = Agent(name="root", model=outer, tools=[nested]) + budget = RunBudget(max_requests=2) + await run(root, budget, streamed, session=session) + state = await session.load_state(root) + state.approve(state.get_interruptions()[0]) + assert (await run(root, budget, streamed, state)).final_output == "done" + assert len(inner.calls) == 1 + assert "An error occurred while running the tool" in str(outer.calls[-1].input) + assert store.checkpoint(session.session_id)["status"] == "ready" From e2a1bc4b50e0eae822b9cb8c981e6370e68d995a Mon Sep 17 00:00:00 2001 From: Mark Stuart Date: Sun, 22 Nov 2026 00:56:14 -0800 Subject: [PATCH 2/4] Publish committed stream events before raising a run budget error --- src/agents/run_budget.py | 20 +++++++++---- src/agents/run_internal/run_loop.py | 4 ++- tests/test_run_budget.py | 46 ++++++++++++++++++++++++++++- 3 files changed, 63 insertions(+), 7 deletions(-) diff --git a/src/agents/run_budget.py b/src/agents/run_budget.py index e98e16ee2d..a249e419db 100644 --- a/src/agents/run_budget.py +++ b/src/agents/run_budget.py @@ -8,13 +8,14 @@ from dataclasses import dataclass, field, replace from typing import TYPE_CHECKING, Any, Literal -from .exceptions import AgentsException, UserError +from .exceptions import AgentsException, UserError, _mark_error_to_drain_stream_events from .usage import Usage if TYPE_CHECKING: from .agent import Agent from .memory import Session from .models.interface import Model + from .result import RunResultStreaming from .run_config import RunConfig from .run_state import RunState from .tool import Tool @@ -226,9 +227,14 @@ def _check_tools(tools: Iterable[Tool]) -> None: async def _admit( - budget: _BudgetState | None, model: Model, session: Session | None, tools: Iterable[Tool] + budget: _BudgetState | None, + model: Model, + session: Session | None, + tools: Iterable[Tool], + *, + streamed_result: RunResultStreaming | None = None, ) -> None: - from .run_internal.resumable_session import ResumableRun + from .run_internal.resumable_session import ResumableRun, checkpoint_streamed_result try: if isinstance(session, ResumableRun): @@ -238,9 +244,13 @@ async def _admit( _check_model(model) budget.check() budget.requests += 1 - except (RunBudgetError, UserError): + except (RunBudgetError, UserError) as error: if isinstance(session, ResumableRun): - await session.finish_budget_stop() + if streamed_result is None: + await session.finish_budget_stop() + else: + await checkpoint_streamed_result(streamed_result, interruptions=[]) + _mark_error_to_drain_stream_events(error) raise diff --git a/src/agents/run_internal/run_loop.py b/src/agents/run_internal/run_loop.py index 9f3bf2b784..6c315a689d 100644 --- a/src/agents/run_internal/run_loop.py +++ b/src/agents/run_internal/run_loop.py @@ -2668,7 +2668,9 @@ def get_model_stream() -> AsyncIterator[TResponseStreamEvent]: prompt=prompt_config, ) - await _admit(context_wrapper._budget, model, session, all_tools) + await _admit( + context_wrapper._budget, model, session, all_tools, streamed_result=streamed_result + ) retry_stream = stream_response_with_retry( get_stream=get_model_stream, rewind=rewind_model_request, diff --git a/tests/test_run_budget.py b/tests/test_run_budget.py index d35727b70c..abaf9df653 100644 --- a/tests/test_run_budget.py +++ b/tests/test_run_budget.py @@ -2,6 +2,7 @@ from __future__ import annotations +import asyncio from dataclasses import replace from types import SimpleNamespace from unittest.mock import AsyncMock, MagicMock @@ -28,7 +29,7 @@ ) from agents.decorators import tool from agents.memory.openai_responses_compaction_session import OpenAIResponsesCompactionSession -from agents.memory.resumable_session import ResumableSession +from agents.memory.resumable_session import ResumableSession, ResumableSessionError from agents.models.codex import CodexProvider from agents.models.openai_responses import OpenAIResponsesModel from agents.testing import ModelStep, ScriptedModel @@ -602,3 +603,46 @@ def record() -> str: assert len(inner.calls) == 1 assert "An error occurred while running the tool" in str(outer.calls[-1].input) assert store.checkpoint(session.session_id)["status"] == "ready" + + +@pytest.mark.asyncio +@pytest.mark.parametrize("fail", [False, True]) +async def test_stream_budget_stop_publishes_only_committed_work(fail): + effects = [] + + @tool + def record() -> str: + effects.append(1) + return "saved" + + store = MemoryStore() + session = await ResumableSession.create(store) + store.block_checkpoint = True + store.fail_checkpoint = fail + model = ScriptedModel([[get_text_message("working"), get_function_tool_call("record")]]) + agent = Agent(name="root", model=model, tools=[record]) + result = Runner.run_streamed( + agent, + "begin", + session=session, + run_config=RunConfig(budget=RunBudget(max_requests=1), tracing_disabled=True), + ) + events = [] + + async def consume(): + async for event in result.stream_events(): + if event.type == "run_item_stream_event": + events.append(event.name) + + consumer = asyncio.create_task(consume()) + try: + await asyncio.wait_for(store.saving.wait(), timeout=5) + assert not events + finally: + store.release.set() + with pytest.raises(ResumableSessionError if fail else RunBudgetError): + await asyncio.wait_for(consumer, timeout=5) + assert len(model.calls) == 1 and effects == [1] + assert store.checkpoint(session.session_id)["status"] == ("active" if fail else "ready") + assert result.final_output is None + assert events == ([] if fail else ["message_output_created", "tool_called", "tool_output"]) From 81d7537d42e897e70773d8bd78c42253b6a2eaad Mon Sep 17 00:00:00 2001 From: Mark Stuart Date: Sun, 22 Nov 2026 21:32:11 -0800 Subject: [PATCH 3/4] Drain committed events before reporting a streamed run budget stop --- src/agents/run_budget.py | 34 +++++++++++----- tests/test_run_budget.py | 84 +++++++++++++++++++++++++++++++++++----- 2 files changed, 98 insertions(+), 20 deletions(-) diff --git a/src/agents/run_budget.py b/src/agents/run_budget.py index 14f69b943b..b73d40cdea 100644 --- a/src/agents/run_budget.py +++ b/src/agents/run_budget.py @@ -13,6 +13,7 @@ from ._redaction import current_redactor, protected_error from .exceptions import ( AgentsException, + InputGuardrailTripwireTriggered, UserError, _mark_error_to_drain_stream_events, _raise_data_redacted_error, @@ -340,16 +341,29 @@ async def _admit( budget.check() budget.requests += 1 except (RunBudgetError, UserError) as error: - if isinstance(session, ResumableRun): - if streamed_result is None: - await session.finish_budget_stop() - else: - await checkpoint_streamed_result(streamed_result, interruptions=[]) - if current_redactor() is not None: - safe = protected_error(error) - _mark_error_to_drain_stream_events(safe) - _raise_data_redacted_error(safe) - _mark_error_to_drain_stream_events(error) + if streamed_result is not None: + from .run_internal.guardrails import input_guardrail_tripwire_triggered_for_stream + + # A parallel check can reject the completed turn while its tools run. + await input_guardrail_tripwire_triggered_for_stream( + streamed_result, ignore_cancelled=True + ) + tripwire = streamed_result._triggered_input_guardrail_result + if tripwire is not None: + raise InputGuardrailTripwireTriggered(tripwire) from None + checks = streamed_result._input_guardrails_task + if checks is not None: + if checks.cancelled(): + raise # No verdict to authorize publishing the queued events. + checks.result() + await checkpoint_streamed_result(streamed_result, interruptions=[]) + if current_redactor() is not None: + safe = protected_error(error) + _mark_error_to_drain_stream_events(safe) + _raise_data_redacted_error(safe) + _mark_error_to_drain_stream_events(error) + elif isinstance(session, ResumableRun): + await session.finish_budget_stop() raise diff --git a/tests/test_run_budget.py b/tests/test_run_budget.py index a7ec33106b..1af534b6cf 100644 --- a/tests/test_run_budget.py +++ b/tests/test_run_budget.py @@ -14,6 +14,8 @@ from agents import ( Agent, + GuardrailFunctionOutput, + InputGuardrailTripwireTriggered, MaxTurnsExceeded, ModelProvider, ModelRetrySettings, @@ -25,6 +27,7 @@ RunState, Usage, UserError, + input_guardrail, retry_policies, tool_namespace, ) @@ -655,9 +658,9 @@ def record() -> str: @pytest.mark.asyncio -@pytest.mark.parametrize("fail", [False, True]) +@pytest.mark.parametrize("session_mode", ["none", "ordinary", "durable", "failed_save"]) @pytest.mark.parametrize("protected", [False, True]) -async def test_stream_budget_stop_publishes_only_committed_work(fail, protected): +async def test_stream_budget_stop_publishes_only_committed_work(session_mode, protected): effects = [] @tool @@ -666,9 +669,13 @@ def record() -> str: return "saved" store = MemoryStore() - session = await ResumableSession.create(store) - store.block_checkpoint = True - store.fail_checkpoint = fail + fail = session_mode == "failed_save" + if session_mode in ("durable", "failed_save"): + session = await ResumableSession.create(store) + store.block_checkpoint = True + store.fail_checkpoint = fail + else: + session = SimpleListSession() if session_mode == "ordinary" else None model = ScriptedModel([[get_text_message("working"), get_function_tool_call("record")]]) agent = Agent(name="root", model=model, tools=[record]) result = Runner.run_streamed( @@ -691,25 +698,82 @@ async def consume(): if event.type == "run_item_stream_event": events.append(event.name) + if not isinstance(session, ResumableSession): + # Let the producer finish before the reader checks for errors. + assert result.run_loop_task is not None + _, pending = await asyncio.wait([result.run_loop_task], timeout=5) + assert not pending consumer = asyncio.create_task(consume()) try: - await asyncio.wait_for(store.saving.wait(), timeout=5) - assert not events + if isinstance(session, ResumableSession): + await asyncio.wait_for(store.saving.wait(), timeout=5) + assert not events finally: store.release.set() - with pytest.raises( + expected = ( ResumableSessionError if fail else (RuntimeError if protected else RunBudgetError) - ) as error: + ) + with pytest.raises(expected) as error: await asyncio.wait_for(consumer, timeout=5) if protected and not fail: assert str(error.value) == "Error details are redacted." assert error.value.__context__ is None assert len(model.calls) == 1 and effects == [1] - assert store.checkpoint(session.session_id)["status"] == ("active" if fail else "ready") + if isinstance(session, ResumableSession): + assert store.checkpoint(session.session_id)["status"] == ("active" if fail else "ready") assert result.final_output is None assert events == ([] if fail else ["message_output_created", "tool_called", "tool_output"]) +@pytest.mark.asyncio +@pytest.mark.parametrize("durable", [False, True]) +@pytest.mark.parametrize("verdict", ["accept", "reject", "cancel"]) +async def test_budget_stop_waits_for_parallel_input_verdict(durable, verdict): + ran = asyncio.Event() + + @tool + async def record() -> str: + ran.set() + return "saved" + + @input_guardrail + async def check(ctx, agent, input): + await ran.wait() + if verdict == "cancel": + raise asyncio.CancelledError + return GuardrailFunctionOutput(output_info=None, tripwire_triggered=verdict == "reject") + + store = MemoryStore() + session = await ResumableSession.create(store) if durable else None + model = ScriptedModel([[get_text_message("working"), get_function_tool_call("record")]]) + result = Runner.run_streamed( + Agent(name="root", model=model, tools=[record], input_guardrails=[check]), + "begin", + session=session, + run_config=RunConfig(budget=RunBudget(max_requests=1), tracing_disabled=True), + ) + assert result.run_loop_task is not None + _, pending = await asyncio.wait([result.run_loop_task], timeout=5) + assert not pending + events = [] + with pytest.raises(InputGuardrailTripwireTriggered if verdict == "reject" else RunBudgetError): + async for event in result.stream_events(): + events.append(event) + assert ran.is_set() and len(model.calls) == 1 and result.final_output is None + if verdict != "accept": + assert not events + else: + assert [e.name for e in events if e.type == "run_item_stream_event"] == [ + "message_output_created", + "tool_called", + "tool_output", + ] + if session is not None: + assert store.checkpoint(session.session_id)["status"] == ( + "ready" if verdict == "accept" else "active" + ) + + @pytest.mark.parametrize("value", [True, -0.01, float("nan"), float("inf"), "0.01"]) def test_invalid_dollar_limit(value): with pytest.raises(ValueError, match="max_estimated_cost_usd"): From 035f94267a6f40003306080c4f20ec92438d01ff Mon Sep 17 00:00:00 2001 From: Mark Stuart Date: Mon, 23 Nov 2026 22:11:49 -0800 Subject: [PATCH 4/4] Limit model calls and reported tokens without pricing callbacks --- .../openai_responses_compaction_session.py | 2 +- src/agents/models/openai_responses.py | 2 - src/agents/run.py | 4 +- src/agents/run_budget.py | 272 +++-------- src/agents/run_config.py | 2 +- src/agents/run_context.py | 1 - src/agents/run_internal/model_retry.py | 3 +- src/agents/run_internal/run_loop.py | 23 +- src/agents/run_state.py | 7 +- src/agents/testing/model.py | 2 +- src/agents/usage.py | 1 - tests/test_run_budget.py | 422 ++++-------------- 12 files changed, 167 insertions(+), 574 deletions(-) diff --git a/src/agents/memory/openai_responses_compaction_session.py b/src/agents/memory/openai_responses_compaction_session.py index 2164db9c34..d7a7efe06d 100644 --- a/src/agents/memory/openai_responses_compaction_session.py +++ b/src/agents/memory/openai_responses_compaction_session.py @@ -490,7 +490,7 @@ async def _run_compaction_locked( _response_usage_to_usage(compacted_usage) if compacted_usage is not None else None ) if wrapper._budget is not None: - wrapper._budget.observe(compact_kwargs["model"], usage) + wrapper._budget.observe(usage) if usage is not None: wrapper.usage.add(usage) diff --git a/src/agents/models/openai_responses.py b/src/agents/models/openai_responses.py index f6e183191a..048b2715a2 100644 --- a/src/agents/models/openai_responses.py +++ b/src/agents/models/openai_responses.py @@ -755,8 +755,6 @@ async def get_response( log_model_action_error(logger, message, e) raise - if self._prompt_owns_model(prompt): - usage._reported_model = getattr(response, "model", None) return ModelResponse( output=response.output, usage=usage, diff --git a/src/agents/run.py b/src/agents/run.py index 8418af03b0..5c35a7a50a 100644 --- a/src/agents/run.py +++ b/src/agents/run.py @@ -724,7 +724,7 @@ 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, session) + budget = _prepare_budget(run_config, starting_agent, run_state) resolved_reasoning_item_id_policy: ReasoningItemIdPolicy | None = ( run_config.reasoning_item_id_policy if run_config.reasoning_item_id_policy is not None @@ -2798,7 +2798,7 @@ def run_streamed( ): input = _prepare_private_input(starting_agent, input, run_config, kwargs) budget = _prepare_budget( - run_config, starting_agent, input if isinstance(input, RunState) else None, session + run_config, starting_agent, input if isinstance(input, RunState) else None ) # Handle RunState input is_resumed_state = isinstance(input, RunState) diff --git a/src/agents/run_budget.py b/src/agents/run_budget.py index 5454c6c687..73c41783a7 100644 --- a/src/agents/run_budget.py +++ b/src/agents/run_budget.py @@ -1,13 +1,9 @@ -"""Limits on model admissions and observed response usage in a Runner run.""" +"""Limits on logical model calls and observed tokens in a Runner run.""" from __future__ import annotations import copy -import inspect -import math -from collections.abc import Callable, Iterable, Mapping -from dataclasses import dataclass, field -from fractions import Fraction +from dataclasses import dataclass from typing import TYPE_CHECKING, Any, Literal from ._redaction import current_redactor, protected_error @@ -21,11 +17,8 @@ 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 @@ -38,108 +31,49 @@ def _valid_limit(value: object) -> bool: return type(value) is int and 0 <= value <= 2**53 - 1 -def _usd(value: float) -> Fraction: - # Sum decimal amounts exactly, without rounding each response to a currency unit. - if type(value) is int and value >= 0: - return Fraction(value) - if type(value) is float and math.isfinite(value) and value >= 0: - return Fraction(str(value)) - raise ValueError("RunBudget.max_estimated_cost_usd must be a finite nonnegative int or float.") - - @dataclass(frozen=True, kw_only=True) class RunBudget: """Limits for one Python Runner root, including handoffs and approval resumes. - Set at least one limit. Request and token limits accept integers from zero - through 2**53 - 1. Zero blocks the first - admission. A response may finish above a limit. The next admission then fails. - - Each new regular model invocation counts once, including follow-ups and corrections. - Runner and transport retries, compaction, approval replies and replay add no admissions. - Agent tools and other nested runs have independent budgets. Native sampling through - CodexProvider and hosted multi-agent orchestration are unsupported. Independent - Runner calls, guardrails, sandbox memory, and tool-owned clients are outside the - root. These limits cannot bound physical sends or billing. - - Tokens and estimated cost use completed root responses and reported session compactions. - Failed attempts, child responses and cumulative snapshots are excluded. Only usage - visible to the SDK counts. Adapters that replace missing totals with explicit zeros - make those totals indistinguishable from measured zero. Before the next - admission, the synchronous estimator receives the model name and Usage - for each completion. The name is the resolved adapter's string ``model``, - the selected model string if unavailable, or None. Compactions use their - own request model. OpenAI request body overrides take precedence. When - a stored prompt selects the model, use the reported model if present. These identifiers - describe Runner selections, with no visibility into provider routing. - - A positive cost limit requires an estimator. An estimator requires a cost - limit. Both amounts use finite, nonnegative int or float values in USD. - The Runner sums their decimal representations without rounding to cents. - Missing or negative totals and unknown estimates (None) block the next - admission by default. Set missing_usage="continue" to use only known values. - - This example uses synthetic USD rates per million tokens. Cached tokens - are part of the input count and get the same rate as other input tokens. - The Runner checks the limit before each regular model request. A single - request can take the estimated cost above the $0.01 limit:: - - from agents import RunBudget, Usage - - def estimate(model: str | None, usage: Usage) -> float | None: - if model != "example": - return None - inputs, outputs = usage.input_tokens, usage.output_tokens - if not 0 <= usage.input_tokens_details.cached_tokens <= inputs or outputs < 0: - return None - if inputs + outputs != usage.total_tokens: - return None - return (2 * inputs + 5 * outputs) / 1_000_000 - - budget = RunBudget(max_estimated_cost_usd=0.01, estimate_cost_usd=estimate) - - Pass the budget to RunConfig(budget=...) on each call, including resume. RunBudgetError - identifies a blocked admission. Estimated-cost budgets support in-memory - continuation only. ResumableSession and redact_text require portable checkpoints - and reject cost limits anywhere in the agent graph. Protected runs can replace - budget errors with generic exceptions. - A paused child budget requires a unique, enabled binding in its parent's tools. - Keep the tool graph and policies stable during each invocation. - Child budget errors follow the agent tool's error policy. An unhandled tool failure - leaves a durable session active for reconciliation. A new run starts with fresh counters. + Pass the same limits and missing-usage policy on 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. """ - max_requests: int | None = None + max_model_calls: int | None = None max_tokens: int | None = None - max_estimated_cost_usd: float | None = None - estimate_cost_usd: Callable[[str | None, Usage], float | None] | None = None missing_usage: Literal["stop", "continue"] = "stop" def __post_init__(self) -> None: - limits = (self.max_requests, self.max_tokens) - if self.max_estimated_cost_usd is not None: - _usd(self.max_estimated_cost_usd) - elif all(limit is None for limit in limits): + limits = (self.max_model_calls, self.max_tokens) + if all(limit is None for limit in limits): 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 request and token limits must be integers from zero through 2**53 - 1." - ) + 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 self.max_estimated_cost_usd is None and self.estimate_cost_usd is not None: - raise ValueError("RunBudget.estimate_cost_usd requires max_estimated_cost_usd.") - if ( - self.max_estimated_cost_usd is not None - and self.max_estimated_cost_usd > 0 - and self.estimate_cost_usd is None - ): - raise ValueError("A positive max_estimated_cost_usd requires estimate_cost_usd.") - if self.estimate_cost_usd is not None and ( - not callable(self.estimate_cost_usd) - or inspect.iscoroutinefunction(self.estimate_cost_usd) - ): - raise TypeError("RunBudget.estimate_cost_usd must be a synchronous callable.") class _BudgetCheckpointError(UserError): @@ -147,66 +81,28 @@ class _BudgetCheckpointError(UserError): class RunBudgetError(AgentsException): - """A blocked admission. The code identifies the reason. + """A blocked model call. Check code for the reason and limit for the ceiling. - For run_budget_exceeded, limit identifies the first reached ceiling. - The Runner checks "requests", then "tokens", then "estimated_cost". - For other codes, limit is None. + For run_budget_exceeded, model_calls takes precedence over tokens. + For run_budget_usage_unavailable, limit is None. """ def __init__( self, - code: Literal[ - "run_budget_exceeded", "run_budget_usage_unavailable", "run_budget_invalid_estimate" - ], + code: Literal["run_budget_exceeded", "run_budget_usage_unavailable"], *, - limit: Literal["requests", "tokens", "estimated_cost"] | None = None, + limit: Literal["model_calls", "tokens"] | None = None, ): self.limit = limit self.code = code - super().__init__(code) - - -def _pricing_model( - model: Model, - agent: Agent[Any], - config: RunConfig, - settings: ModelSettings, - prompt: ResponsePromptParam | None, -) -> str | None: - if config.budget is None or config.budget.estimate_cost_usd is None: - return None - from .models.openai_chatcompletions import OpenAIChatCompletionsModel - from .models.openai_responses import OpenAIResponsesModel - - if isinstance(model, (OpenAIResponsesModel, OpenAIChatCompletionsModel)): - body = settings.extra_body - if isinstance(body, Mapping) and "model" in body: - name = body["model"] - return name if isinstance(name, str) else None - - if isinstance(model, OpenAIResponsesModel) and model._prompt_owns_model(prompt): - # A stored prompt can replace the adapter's implicit default. - override = (settings.extra_args or {}).get("model") - return override if isinstance(override, str) else None - name = getattr(model, "model", None) - if isinstance(name, str): - return name - selected = config.model if config.model is not None else agent.model - return selected if isinstance(selected, str) else None - - -def _estimate( - estimator: Callable[[str | None, Usage], float | None], model: str | None, usage: Usage -) -> Fraction | None: - try: - value = estimator(model, usage) - if inspect.iscoroutine(value): - value.close() - return None if value is None else _usd(value) - except Exception: - pass - raise RunBudgetError("run_budget_invalid_estimate") + 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" + message = ( + f"RunBudget.{ceiling} reached. Check completed work before starting a new run." + ) + super().__init__(f"{code}: {message}") @dataclass @@ -215,12 +111,9 @@ class _BudgetState: requests: int = 0 tokens: int = 0 unavailable: bool = False - cost: Fraction = Fraction(0) - pending: list[tuple[str | None, Usage]] = field(default_factory=list) - def observe(self, model: str | None, usage: Usage | None) -> None: - limits = self.limits - if limits.max_tokens is None and limits.max_estimated_cost_usd is None: + def observe(self, usage: Usage | None) -> None: + if self.limits.max_tokens is None: return if ( usage is None @@ -230,45 +123,20 @@ def observe(self, model: str | None, usage: Usage | None) -> None: self.unavailable = True return self.tokens += usage.total_tokens - if limits.estimate_cost_usd is not None: - if model is None and isinstance(usage._reported_model, str): - model = usage._reported_model - self.pending.append((model, copy.deepcopy(usage))) def check(self) -> None: limits = self.limits - if limits.max_requests is not None and self.requests >= limits.max_requests: - raise RunBudgetError("run_budget_exceeded", limit="requests") + 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_tokens is not None and self.tokens >= limits.max_tokens: raise RunBudgetError("run_budget_exceeded", limit="tokens") - ceiling = ( - _usd(limits.max_estimated_cost_usd) - if limits.max_estimated_cost_usd is not None - else None - ) - if ceiling is not None and self.cost >= ceiling: - raise RunBudgetError("run_budget_exceeded", limit="estimated_cost") if self.unavailable and limits.missing_usage == "stop": raise RunBudgetError("run_budget_usage_unavailable") - while self.pending: - assert limits.estimate_cost_usd is not None - assert ceiling is not None - estimate = _estimate(limits.estimate_cost_usd, *self.pending[0]) - self.pending.pop(0) - if estimate is None: - self.unavailable = True - if limits.missing_usage == "stop": - raise RunBudgetError("run_budget_usage_unavailable") - else: - self.cost += estimate - if self.cost >= ceiling: - raise RunBudgetError("run_budget_exceeded", limit="estimated_cost") def checkpoint(self) -> dict[str, Any]: - if self.limits.max_estimated_cost_usd is not None: - raise _BudgetCheckpointError("Cannot serialize an estimated-cost budget.") + # Schema 1.25 stores logical model calls as requests. return { - "max_requests": self.limits.max_requests, + "max_requests": self.limits.max_model_calls, "max_tokens": self.limits.max_tokens, "missing_usage": self.limits.missing_usage, "requests": self.requests, @@ -294,7 +162,7 @@ def restore(cls, data: Any) -> _BudgetState: raise _BudgetCheckpointError("Invalid run budget consumption.") try: limits = RunBudget( - max_requests=data["max_requests"], + max_model_calls=data["max_requests"], max_tokens=data["max_tokens"], missing_usage=data["missing_usage"], ) @@ -320,36 +188,21 @@ def _tool_budget(tool: Tool) -> RunBudget | None: return config.budget if config is not None else None -def _check_portable(limits: RunBudget | None) -> None: - if limits is not None and limits.max_estimated_cost_usd is not None: - raise UserError( - "ResumableSession and redact_text cannot checkpoint an estimated-cost budget." - ) - - -def _check_tools(tools: Iterable[Tool]) -> None: - for tool in tools: - _check_portable(_tool_budget(tool)) - - async def _admit( budget: _BudgetState | None, model: Model, session: Session | None, - tools: Iterable[Tool], *, streamed_result: RunResultStreaming | None = None, ) -> None: + if budget is None: + return from .run_internal.resumable_session import ResumableRun, checkpoint_streamed_result try: - if isinstance(session, ResumableRun) or current_redactor() is not None: - # Include tools resolved dynamically after the initial graph check. - _check_tools(tools) - if budget is not None: - _check_model(model) - budget.check() - budget.requests += 1 + _check_model(model) + budget.check() + budget.requests += 1 except (RunBudgetError, UserError) as error: if streamed_result is not None: from .run_internal.guardrails import input_guardrail_tripwire_triggered_for_stream @@ -432,23 +285,16 @@ async def _check_resume( def _prepare_budget( - config: RunConfig, agent: Agent[Any], state: RunState[Any] | None, session: Session | None + config: RunConfig, agent: Agent[Any], state: RunState[Any] | None ) -> _BudgetState | None: from .models.interface import Model - from .run_internal.resumable_session import ResumableRun limits = config.budget + if limits is None: + return None current = ( state._current_agent if state is not None and state._current_agent is not None else agent ) - if isinstance(session, ResumableRun) or current_redactor() is not None: - from ._run_state_agent_identity import _iter_agent_graph - - _check_portable(limits) - for reachable in _iter_agent_graph(current): - _check_tools(reachable.tools) - 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) if state is not None: diff --git a/src/agents/run_config.py b/src/agents/run_config.py index 24840882f2..b95367ce8b 100644 --- a/src/agents/run_config.py +++ b/src/agents/run_config.py @@ -673,7 +673,7 @@ class RunConfig: """ budget: RunBudget | None = None - """Optional limits on root model admissions and observed response usage.""" + """Optional limits on root model calls and observed tokens.""" if TYPE_CHECKING: diff --git a/src/agents/run_context.py b/src/agents/run_context.py index 789b58f506..c2064604d5 100644 --- a/src/agents/run_context.py +++ b/src/agents/run_context.py @@ -306,7 +306,6 @@ def _copy_for_run_state(self) -> RunContextWrapper[TContext]: copied.usage = copy.deepcopy(self.usage) if self._budget is not None: copied._budget = copy.copy(self._budget) - copied._budget.pending = copy.deepcopy(self._budget.pending) copied._approvals = copy.deepcopy(self._approvals) copied._tool_invocations = copy.deepcopy(self._tool_invocations) copied._restored_unbound_approval_call_ids = set(self._restored_unbound_approval_call_ids) diff --git a/src/agents/run_internal/model_retry.py b/src/agents/run_internal/model_retry.py index 595fb61958..82ddf6ffeb 100644 --- a/src/agents/run_internal/model_retry.py +++ b/src/agents/run_internal/model_retry.py @@ -615,7 +615,6 @@ async def get_response_with_retry( replay_unsafe_request: bool = False, reported_usage: dict[int, Usage] | None = None, budget: _BudgetState | None = None, - pricing_model: str | None = None, ) -> ModelResponse: request_attempt = 1 policy_attempt = 1 @@ -650,7 +649,7 @@ async def get_response_with_retry( ): response = await _await_model_attempt(get_response(), timeout) if budget is not None: - budget.observe(pricing_model, response.usage) + budget.observe(response.usage) response.usage = apply_retry_attempt_usage( response.usage, request_attempt - 1, reported_usage ) diff --git a/src/agents/run_internal/run_loop.py b/src/agents/run_internal/run_loop.py index edf8866dd3..273dab3c8f 100644 --- a/src/agents/run_internal/run_loop.py +++ b/src/agents/run_internal/run_loop.py @@ -79,7 +79,7 @@ ) from ..models._run_context import ModelToolHooks, model_run_context from ..result import RunResultStreaming -from ..run_budget import _admit, _pricing_model +from ..run_budget import _admit from ..run_config import ReasoningItemIdPolicy, RunConfig from ..run_context import AgentHookContext, RunContextWrapper, TContext from ..run_error_handlers import RunErrorHandlers @@ -2674,12 +2674,7 @@ def get_model_stream() -> AsyncIterator[TResponseStreamEvent]: prompt=prompt_config, ) - await _admit( - context_wrapper._budget, model, session, all_tools, streamed_result=streamed_result - ) - pricing_model = _pricing_model( - model, execution_agent, run_config, model_settings, prompt_config - ) + await _admit(context_wrapper._budget, model, session, streamed_result=streamed_result) retry_stream = stream_response_with_retry( get_stream=get_model_stream, preview=( @@ -2777,14 +2772,7 @@ def get_model_stream() -> AsyncIterator[TResponseStreamEvent]: else Usage(requests=_requests_for_response_without_usage(terminal_response)) ) if context_wrapper._budget is not None: - if pricing_model is None and prompt_config is not None: - from ..models.openai_responses import OpenAIResponsesModel - - if isinstance(model, OpenAIResponsesModel) and model._prompt_owns_model( - prompt_config - ): - usage._reported_model = getattr(terminal_response, "model", None) - context_wrapper._budget.observe(pricing_model, usage) + context_wrapper._budget.observe(usage) usage = apply_retry_attempt_usage(usage, stream_failed_retry_attempts[0]) final_response = ModelResponse( output=terminal_response.output, @@ -3186,12 +3174,9 @@ async def rewind_model_request() -> None: ), record_failed_attempt_usage_on_error(context_wrapper.usage) as reported_usage, ): - await _admit(context_wrapper._budget, model, session, all_tools) + await _admit(context_wrapper._budget, model, session) new_response = await get_response_with_retry( budget=context_wrapper._budget, - pricing_model=_pricing_model( - model, execution_agent, run_config, model_settings, prompt_config - ), get_response=lambda: model.get_response( system_instructions=filtered.instructions, input=filtered.input, diff --git a/src/agents/run_state.py b/src/agents/run_state.py index 1d334eeff5..61ef87ebbf 100644 --- a/src/agents/run_state.py +++ b/src/agents/run_state.py @@ -2047,7 +2047,6 @@ def _serialize_snapshot( "Use unique agent names before starting a persistable run." ) - budget = self._context._budget.checkpoint() if self._context._budget is not None else None approvals_dict = self._serialize_approvals() tool_invocations = self._serialize_tool_invocations() hosted_mcp_approvals = self._serialize_hosted_mcp_approvals() @@ -2066,8 +2065,8 @@ def _serialize_snapshot( # Preserve metadata so deserialization can warn when context types were erased. "context_meta": context_meta, } - if budget is not None: - context_entry["budget"] = budget + if self._context._budget is not None: + context_entry["budget"] = self._context._budget.checkpoint() tool_input = self._serialize_tool_input(self._context.tool_input) if tool_input is not None: context_entry["tool_input"] = tool_input @@ -3194,8 +3193,6 @@ 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/testing/model.py b/src/agents/testing/model.py index 0d77f14c89..1605d9157b 100644 --- a/src/agents/testing/model.py +++ b/src/agents/testing/model.py @@ -500,7 +500,7 @@ async def _next_resolved_step(self, call: ModelCall) -> ModelStep: if inspect.isawaitable(result): result = await result step = self._coerce_step(result, 0) - if step.usage == Usage(): + if step.usage._total_missing and step.usage == Usage(): usage = self._default_usage if self._default_usage is not None else Usage(requests=1) else: usage = step.usage diff --git a/src/agents/usage.py b/src/agents/usage.py index 60ce59a09c..506d26b2a1 100644 --- a/src/agents/usage.py +++ b/src/agents/usage.py @@ -239,7 +239,6 @@ class Usage: """ _total_missing = False - _reported_model = cast("str | None", None) @model_validator(mode="wrap") @classmethod diff --git a/tests/test_run_budget.py b/tests/test_run_budget.py index 8e28e362de..583efe2bf5 100644 --- a/tests/test_run_budget.py +++ b/tests/test_run_budget.py @@ -17,7 +17,6 @@ GuardrailFunctionOutput, InputGuardrailTripwireTriggered, MaxTurnsExceeded, - ModelProvider, ModelRetrySettings, ModelSettings, RunBudget, @@ -61,46 +60,26 @@ def step(item, total=None): @pytest.mark.parametrize("value", [None, -1, True, 1.5, 2**53]) -def test_invalid_limits(value): +@pytest.mark.parametrize("field", ["max_model_calls", "max_tokens"]) +def test_invalid_limits(field, value): with pytest.raises(ValueError, match="RunBudget"): - RunConfig(budget={"max_tokens": value}) - - -@pytest.mark.parametrize("policy", ["stop", "continue"]) -def test_cost_limit_and_estimator_must_be_paired(policy): - with pytest.raises(ValueError, match="requires estimate_cost_usd"): - RunBudget(max_estimated_cost_usd=1, missing_usage=policy) - with pytest.raises(ValueError, match="requires max_estimated_cost_usd"): - RunBudget(max_requests=2, estimate_cost_usd=lambda _model, _usage: 1, missing_usage=policy) - - -@pytest.mark.asyncio -@pytest.mark.parametrize("streamed", [False, True]) -async def test_missing_estimator_rejects_dict_before_dispatch(streamed): - model = ScriptedModel() - agent = Agent(name="root", model=model) - config = {"budget": {"max_estimated_cost_usd": 1, "missing_usage": "continue"}} - with pytest.raises(ValueError, match="requires estimate_cost_usd"): - if streamed: - Runner.run_streamed(agent, "begin", run_config=config) - else: - await Runner.run(agent, "begin", run_config=config) - assert not model.calls + RunConfig(budget={field: value}) @pytest.mark.parametrize( "limits,blocked", [ - ({"max_requests": 0}, "requests"), + ({"max_model_calls": 0}, "model_calls"), ({"max_tokens": 0}, "tokens"), - ({"max_estimated_cost_usd": 0}, "estimated_cost"), - ({"max_requests": 0, "max_tokens": 0}, "requests"), + ({"max_model_calls": 0, "max_tokens": 0}, "model_calls"), ], ) def test_zero_blocks_sync_dispatch(limits, blocked): model = ScriptedModel() with pytest.raises(RunBudgetError, match="run_budget_exceeded") as error: Runner.run_sync(Agent(name="root", model=model), "begin", run_config={"budget": limits}) + assert error.value.code == "run_budget_exceeded" + assert f"max_{blocked}" in str(error.value) assert error.value.limit == blocked assert not model.calls @@ -119,7 +98,7 @@ async def test_retry_counted_once_and_overshoot_can_finish(streamed): max_retries=1, policy=retry_policies.network_error(), backoff={"initial_delay": 0} ) agent = Agent(name="root", model=model, model_settings=ModelSettings(retry=retry)) - result = await run(agent, RunBudget(max_requests=2, max_tokens=3), streamed, max_turns=2) + result = await run(agent, RunBudget(max_model_calls=2, max_tokens=3), streamed, max_turns=2) assert result.final_output == "done" assert result.context_wrapper.usage.requests == len(model.calls) == 3 @@ -127,65 +106,54 @@ async def test_retry_counted_once_and_overshoot_can_finish(streamed): @pytest.mark.asyncio @pytest.mark.parametrize("streamed", [False, True]) @pytest.mark.parametrize( - "total,policy,code", + "usage,policy,code", [ - (0, "stop", None), - (None, "stop", "run_budget_usage_unavailable"), - (-1, "stop", "run_budget_usage_unavailable"), - (None, "continue", None), - (10, "stop", "run_budget_exceeded"), + (Usage(total_tokens=0), "stop", None), + (Usage(requests=1, total_tokens=0), "stop", None), + (Usage(), "stop", "run_budget_usage_unavailable"), + (Usage(requests=1), "stop", "run_budget_usage_unavailable"), + (Usage(requests=1, total_tokens=-1), "stop", "run_budget_usage_unavailable"), + (Usage(requests=1), "continue", None), + (Usage(requests=1, total_tokens=10), "stop", "run_budget_exceeded"), ], ) -async def test_correction_uses_observed_totals(streamed, total, policy, code): +async def test_correction_uses_observed_totals(streamed, usage, policy, code): model = ScriptedModel( - [step(get_function_tool_call("unknown"), total), [get_text_message("done")]] + [ + ModelStep(output=[get_function_tool_call("unknown")], usage=usage), + [get_text_message("done")], + ] ) agent = Agent(name="root", model=model) budget = RunBudget(max_tokens=5, missing_usage=policy) if code: with pytest.raises(RunBudgetError, match=code) as error: await run(agent, budget, streamed) + assert error.value.code == code + assert ("max_tokens" if code == "run_budget_exceeded" else "missing_usage") in str( + error.value + ) assert error.value.limit == ("tokens" if code == "run_budget_exceeded" else None) assert len(model.calls) == 1 else: assert (await run(agent, budget, streamed)).final_output == "done" -def failing_estimate(model, usage): - raise RuntimeError("private estimator detail") - - @pytest.mark.asyncio +@pytest.mark.parametrize("streamed", [False, True]) @pytest.mark.parametrize( - "estimator,code", - [ - (lambda _model, u: None, "run_budget_usage_unavailable"), - (lambda _model, u: u.total_tokens * 2, "run_budget_exceeded"), - (lambda _model, u: -0.01, "run_budget_invalid_estimate"), - (lambda _model, u: float("inf"), "run_budget_invalid_estimate"), - (lambda _model, u: "0.01", "run_budget_invalid_estimate"), - (lambda _model, u: True, "run_budget_invalid_estimate"), - (lambda _model, u: float("nan"), "run_budget_invalid_estimate"), - (failing_estimate, "run_budget_invalid_estimate"), - ], + "turns,calls,error", + [(1, 2, MaxTurnsExceeded), (1, 1, MaxTurnsExceeded), (None, 1, RunBudgetError)], ) -@pytest.mark.parametrize("streamed", [False, True]) -async def test_estimates_fail_distinctly_without_callback_details(estimator, code, streamed): - model = ScriptedModel([step(get_function_tool_call("unknown"), 3)]) - budget = RunBudget(max_estimated_cost_usd=6, estimate_cost_usd=estimator) - with pytest.raises(RunBudgetError) as error: - await run(Agent(name="root", model=model), budget, streamed) - assert error.value.limit == ("estimated_cost" if code == "run_budget_exceeded" else None) - assert str(error.value) == error.value.code == code - assert error.value.__context__ is None - assert len(model.calls) == 1 - - -@pytest.mark.asyncio -async def test_max_turns_still_limits_corrections(): +async def test_max_turns_still_limits_corrections(streamed, turns, calls, error): model = ScriptedModel([[get_function_tool_call("unknown")]]) - with pytest.raises(MaxTurnsExceeded): - await run(Agent(name="root", model=model), RunBudget(max_requests=2), max_turns=1) + with pytest.raises(error): + await run( + Agent(name="root", model=model), + RunBudget(max_model_calls=calls), + streamed, + max_turns=turns, + ) assert len(model.calls) == 1 @@ -204,15 +172,24 @@ def record() -> str: target = Agent(name="target", model=target_model, tools=[record]) model = ScriptedModel([step(get_handoff_tool_call(target), 2)]) root = Agent(name="root", model=model, handoffs=[target]) - budget = RunBudget(max_requests=4, max_tokens=5) + budget = RunBudget(max_model_calls=4, max_tokens=5) result = await run(root, budget, streamed) state = result.to_state() if portable: state = await RunState.from_string(root, state.to_string()) - assert state.to_json()["context"]["budget"]["tokens"] == 9 + # Approval records from the original 1.25 writer use these exact wire keys. + assert state.to_json()["context"]["budget"] == { + "max_requests": 4, + "requests": 2, + "max_tokens": 5, + "tokens": 9, + "missing_usage": "stop", + "unavailable": False, + } state.approve(state.get_interruptions()[0]) for changed in ( None, + replace(budget, max_model_calls=5), replace(budget, max_tokens=10), replace(budget, missing_usage="continue"), ): @@ -239,16 +216,9 @@ def record() -> str: session = await ResumableSession.create(store) model = ScriptedModel([[get_function_tool_call("record")], [get_text_message("fresh")]]) root = Agent(name="root", model=model, tools=[record]) - budget = RunBudget(max_requests=1) - for invalid, error in [ - (RunBudget(max_requests=0), RunBudgetError), - ( - RunBudget(max_estimated_cost_usd=1, estimate_cost_usd=lambda _model, _usage: 1), - UserError, - ), - ]: - with pytest.raises(error): - await run(root, invalid, streamed, session=session) + budget = RunBudget(max_model_calls=1) + with pytest.raises(RunBudgetError): + await run(root, RunBudget(max_model_calls=0), streamed, session=session) await run(root, budget, streamed, session=session) restored = await ResumableSession.resume(store, session.session_id) state = await restored.load_state(root) @@ -265,26 +235,6 @@ def record() -> str: assert effects == [1] -@pytest.mark.asyncio -async def test_live_cost_approval_rejects_portable_capture(): - @tool(needs_approval=True) - def record() -> str: - return "saved" - - budget = RunBudget( - max_estimated_cost_usd=1, - estimate_cost_usd=lambda _model, _usage: None, - missing_usage="continue", - ) - model = ScriptedModel([step(get_function_tool_call("record"), 1), [get_text_message("done")]]) - root = Agent(name="root", model=model, tools=[record]) - state = (await run(root, budget)).to_state() - with pytest.raises(UserError, match="estimated-cost"): - state.to_string() - state.approve(state.get_interruptions()[0]) - assert (await run(root, budget, input=state)).final_output == "done" - - @pytest.mark.asyncio @pytest.mark.parametrize("streamed", [False, True]) async def test_nested_tool_has_independent_budget_and_usage(streamed): @@ -306,7 +256,7 @@ async def test_nested_tool_has_independent_budget_and_usage(streamed): ) result = await run( Agent(name="root", model=model, tools=[nested]), - RunBudget(max_requests=2, max_tokens=2), + RunBudget(max_model_calls=2, max_tokens=2), streamed, ) assert result.final_output == "done" @@ -315,7 +265,8 @@ async def test_nested_tool_has_independent_budget_and_usage(streamed): @pytest.mark.asyncio -async def test_compaction_charges_tokens_without_an_admission(): +@pytest.mark.parametrize("streamed", [False, True]) +async def test_compaction_counts_tokens_without_a_model_call(streamed): # ScriptedModel does not own the separate session compaction endpoint. client = MagicMock() client.responses.compact = AsyncMock( @@ -332,20 +283,28 @@ async def test_compaction_charges_tokens_without_an_admission(): ) model = ScriptedModel([step(get_text_message("done"), 2)]) result = await run( - Agent(name="root", model=model), RunBudget(max_requests=1, max_tokens=3), session=session + Agent(name="root", model=model), + RunBudget(max_model_calls=1, max_tokens=3), + streamed, + session=session, ) checkpoint = result.to_state().to_json()["context"]["budget"] assert checkpoint["tokens"] == 9 and checkpoint["requests"] == 1 @pytest.mark.asyncio -async def test_native_sampling_rejected_without_dispatch(): - with pytest.raises(UserError, match="native sampling"): - await Runner.run( - Agent(name="root"), - "begin", - run_config=RunConfig(model_provider=CodexProvider(), budget=RunBudget(max_requests=1)), - ) +@pytest.mark.parametrize("streamed", [False, True]) +async def test_native_sampling_rejected_without_dispatch(streamed): + provider = CodexProvider() + try: + config = RunConfig(model_provider=provider, budget=RunBudget(max_model_calls=1)) + with pytest.raises(UserError, match="native sampling"): + if streamed: + Runner.run_streamed(Agent(name="root"), "begin", run_config=config) + else: + await Runner.run(Agent(name="root"), "begin", run_config=config) + finally: + await provider.aclose() @pytest.mark.asyncio @@ -387,8 +346,7 @@ async def respond(request): @pytest.mark.asyncio -@pytest.mark.parametrize("cost", [False, True]) -async def test_explicit_child_budget_survives_nested_approval(cost): +async def test_explicit_child_budget_survives_nested_approval(): effects = [] @tool(needs_approval=True) @@ -403,11 +361,7 @@ def record() -> str: ] ) child = Agent(name="child", model=child_model, tools=[record]) - child_budget = ( - RunBudget(max_estimated_cost_usd=9, estimate_cost_usd=lambda _model, u: u.total_tokens) - if cost - else RunBudget(max_requests=2) - ) + child_budget = RunBudget(max_model_calls=2) nested = child.as_tool( "ask", "Ask child", @@ -421,13 +375,9 @@ def record() -> str: ] ) root = Agent(name="root", model=model, tools=[nested]) - budget = RunBudget(max_requests=2, max_tokens=2) + budget = RunBudget(max_model_calls=2, max_tokens=2) state = (await run(root, budget)).to_state() - if cost: - with pytest.raises(UserError, match="estimated-cost"): - state.to_string() - else: - state = await RunState.from_string(root, state.to_string()) + state = await RunState.from_string(root, state.to_string()) state.approve(state.get_interruptions()[0]) assert (await run(root, budget, True, state)).final_output == "done" assert len(model.calls) == len(child_model.calls) == 2 @@ -478,7 +428,7 @@ def model(*calls): leaf_model = model(get_function_tool_call("record", call_id="leaf")) leaf = Agent(name="leaf", tools=[record], model=leaf_model) - config = RunConfig(budget=RunBudget(max_requests=2), tracing_disabled=True) + config = RunConfig(budget=RunBudget(max_model_calls=2), tracing_disabled=True) allowed = True async def grant(ctx, agent): @@ -564,12 +514,13 @@ def record() -> str: @pytest.mark.asyncio -async def test_hosted_child_usage_cannot_be_isolated(): +@pytest.mark.parametrize("streamed", [False, True]) +async def test_hosted_child_usage_cannot_be_isolated(streamed): from agents.extensions.experimental.hosted_multi_agent import OpenAIHostedMultiAgentModel root = Agent(name="root", model=OpenAIHostedMultiAgentModel(model="synthetic")) with pytest.raises(UserError, match="hosted multi-agent"): - await run(root, RunBudget(max_tokens=2)) + await run(root, RunBudget(max_tokens=2), streamed) @pytest.mark.asyncio @@ -591,10 +542,8 @@ def record() -> str: ] ) child = Agent(name="child", model=inner, tools=[record]) - config = RunConfig( - budget=RunBudget(max_estimated_cost_usd=8, estimate_cost_usd=lambda _model, _usage: 1), - tracing_disabled=True, - ) + budget = RunBudget(max_model_calls=2, max_tokens=5) + config = RunConfig(budget=budget, tracing_disabled=True) nested = child.as_tool("ask", "Ask", run_config=config, failure_error_function=None) outer = ScriptedModel( [ @@ -603,17 +552,11 @@ def record() -> str: ] ) root = Agent(name="root", model=outer, tools=[nested]) - with pytest.raises(UserError, match="estimated-cost"): - await run(root, None, streamed, session=session) - assert not outer.calls and not inner.calls - assert store.checkpoint(session.session_id)["status"] == "ready" - budget = RunBudget(max_requests=2, max_tokens=5) - config.budget = budget await run(root, budget, streamed, session=session) restored = await ResumableSession.resume(store, session.session_id) state = await restored.load_state(root) state.approve(state.get_interruptions()[0]) - for changed in (None, replace(budget, missing_usage="continue"), RunBudget(max_requests=3)): + for changed in (None, replace(budget, missing_usage="continue"), RunBudget(max_model_calls=3)): config.budget = changed with pytest.raises(UserError, match="same RunBudget"): await run(root, budget, streamed, state) @@ -623,7 +566,7 @@ def record() -> str: changed_tool = child.as_tool( "ask", "Ask", - run_config=RunConfig(budget=RunBudget(max_requests=3), tracing_disabled=True), + run_config=RunConfig(budget=RunBudget(max_model_calls=3), tracing_disabled=True), failure_error_function=None, ) disabled = child.as_tool("ask", "Ask", run_config=config, is_enabled=False) @@ -653,7 +596,7 @@ def save() -> str: model = ScriptedModel([[get_function_tool_call("save")], RuntimeError("offline")]) root = Agent(name="root", model=model, tools=[save]) - budget = RunBudget(max_requests=2) + budget = RunBudget(max_model_calls=2) state = (await run(root, budget, streamed)).to_state() state.approve(state.get_interruptions()[0]) with pytest.raises(RuntimeError, match="offline"): @@ -745,7 +688,9 @@ def record() -> str: inner = ScriptedModel([[get_function_tool_call("record", call_id="inner")]]) child = Agent(name="child", model=inner, tools=[record]) nested = child.as_tool( - "ask", "Ask", run_config=RunConfig(budget=RunBudget(max_requests=1), tracing_disabled=True) + "ask", + "Ask", + run_config=RunConfig(budget=RunBudget(max_model_calls=1), tracing_disabled=True), ) outer = ScriptedModel( [ @@ -754,7 +699,7 @@ def record() -> str: ] ) root = Agent(name="root", model=outer, tools=[nested]) - budget = RunBudget(max_requests=2) + budget = RunBudget(max_model_calls=2) await run(root, budget, streamed, session=session) state = await session.load_state(root) state.approve(state.get_interruptions()[0]) @@ -790,7 +735,7 @@ def record() -> str: "begin", session=session, run_config=RunConfig( - budget=RunBudget(max_requests=1), + budget=RunBudget(max_model_calls=1), tracing_disabled=True, redact_text=(lambda s: s.replace("working", "public")) if protected else None, ), @@ -857,7 +802,7 @@ async def check(ctx, agent, input): Agent(name="root", model=model, tools=[record], input_guardrails=[check]), "begin", session=session, - run_config=RunConfig(budget=RunBudget(max_requests=1), tracing_disabled=True), + run_config=RunConfig(budget=RunBudget(max_model_calls=1), tracing_disabled=True), ) assert result.run_loop_task is not None _, pending = await asyncio.wait([result.run_loop_task], timeout=5) @@ -881,192 +826,17 @@ async def check(ctx, agent, input): ) -@pytest.mark.parametrize("value", [True, -0.01, float("nan"), float("inf"), "0.01"]) -def test_invalid_dollar_limit(value): - with pytest.raises(ValueError, match="max_estimated_cost_usd"): - RunBudget(max_estimated_cost_usd=value, estimate_cost_usd=lambda m, u: 0) - - -@pytest.mark.asyncio -@pytest.mark.parametrize("streamed", [False, True]) -@pytest.mark.parametrize("prices, ceiling", [((0.1, 0.7), 0.8), ((1e-8, 2e-8), 3e-8)]) -async def test_handoff_and_resume_charge_each_model_once(streamed, prices, ceiling): - @tool(needs_approval=True) - def record() -> str: - return "saved" - - class PricedModel(ScriptedModel): - model = "first" - - target_model = PricedModel([step(get_function_tool_call("record"), 7)]) - target_model.model = "second" - target = Agent(name="target", model=target_model, tools=[record]) - model = PricedModel([step(get_handoff_tool_call(target), 2)]) - root = Agent(name="root", model=model, handoffs=[target]) - charged = [] - - def estimate(name, usage): - charged.append((name, usage.total_tokens)) - return {"first": prices[0], "second": prices[1]}[name] - - budget = RunBudget(max_estimated_cost_usd=ceiling, estimate_cost_usd=estimate) - state = (await run(root, budget, streamed)).to_state() - assert charged == [("first", 2)] - state.approve(state.get_interruptions()[0]) - target_model.model = "later" - with pytest.raises(RunBudgetError) as error: - await run(root, budget, not streamed, state) - assert error.value.limit == "estimated_cost" - assert charged == [("first", 2), ("second", 7)] - assert len(model.calls) == len(target_model.calls) == 1 - - @pytest.mark.asyncio -@pytest.mark.parametrize("streamed", [False, True]) -@pytest.mark.parametrize("named", [False, True]) -async def test_override_prices_selected_name_or_none(streamed, named): - model = ScriptedModel([step(get_function_tool_call("unknown"), 1)]) - - class Provider(ModelProvider): - def get_model(self, model_name): - return model - - provider = Provider() - charged = [] - - def estimate(name, usage): - charged.append(name) - return 0.01 if name else None - +async def test_buffered_budget_stop_preserves_error_redaction(): + model = ScriptedModel([[get_function_tool_call("unknown")]]) config = RunConfig( - model="override" if named else model, - model_provider=provider, - budget=RunBudget(max_estimated_cost_usd=0.01, estimate_cost_usd=estimate), + budget=RunBudget(max_model_calls=1), + redact_text=lambda text: text, tool_not_found_behavior="return_error_to_model", tracing_disabled=True, ) - agent = Agent(name="root", model="unused") - with pytest.raises(RunBudgetError) as error: - 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 charged == ["override" if named else None] - assert error.value.code == ("run_budget_exceeded" if named else "run_budget_usage_unavailable") - assert len(model.calls) == 1 - - -@pytest.mark.asyncio -@pytest.mark.parametrize("streamed", [False, True]) -async def test_compaction_uses_its_own_price_before_resume(streamed): - @tool(needs_approval=True) - def record() -> str: - return "saved" - - model = ScriptedModel([step(get_function_tool_call("record"), 1)]) - agent = Agent(name="root", model=model, tools=[record]) - charged = [] - - def estimate(name, usage): - charged.append((name, usage.total_tokens)) - return 0.01 if name is None else 0.02 - - budget = RunBudget(max_estimated_cost_usd=0.03, estimate_cost_usd=estimate) - result = await run(agent, budget, streamed) - client = MagicMock() - client.responses.compact = AsyncMock( - return_value=SimpleNamespace( - output=[{"type": "compaction", "encrypted_content": "synthetic"}], - usage=Usage(total_tokens=7), - ) - ) - history = SimpleListSession() - await history.add_items([{"role": "user", "content": "earlier"}]) - session = OpenAIResponsesCompactionSession( - "example", history, client=client, should_trigger_compaction=lambda ctx: True - ) - await session.run_compaction(wrapper=result.context_wrapper) - state = result.to_state() - state.approve(state.get_interruptions()[0]) - with pytest.raises(RunBudgetError) as error: - await run(agent, budget, streamed, state) - assert error.value.limit == "estimated_cost" - assert charged == [(None, 1), (session.model, 7)] + with pytest.raises(RuntimeError) as error: + await Runner.run(Agent(name="root", model=model), "begin", run_config=config) + assert str(error.value) == "Error details are redacted." + assert error.value.__context__ is None assert len(model.calls) == 1 - - -@pytest.mark.asyncio -@pytest.mark.parametrize("streamed", [False, True]) -async def test_redaction_rejects_nonportable_budget_before_dispatch(streamed): - model = ScriptedModel() - root = Agent(name="root", model=model) - config = RunConfig( - redact_text=lambda text: text, - budget=RunBudget(max_estimated_cost_usd=1, estimate_cost_usd=lambda m, u: 0), - ) - with pytest.raises(RuntimeError, match="redacted"): - if streamed: - Runner.run_streamed(root, "begin", run_config=config) - else: - await Runner.run(root, "begin", run_config=config) - assert not model.calls - - -@pytest.mark.asyncio -@pytest.mark.allow_call_model_methods -@pytest.mark.parametrize("streamed", [False, True]) -@pytest.mark.parametrize("prompt_owned", [False, True]) -async def test_price_uses_openai_request_body_override_or_prompt_response(streamed, prompt_owned): - import json - - sent = [] - priced = [] - - def estimate(name, usage): - priced.append(name) - return 0.01 if name == "selected" else 0 - - def respond(request): - sent.append(json.loads(request.content).get("model")) - item = get_function_tool_call("unknown") if len(sent) == 1 else get_text_message("done") - payload = get_response_obj([item]).model_dump() - payload["model"] = "selected" if prompt_owned else "reported" - payload["usage"] = { - "total_tokens": 1, - "input_tokens": 1, - "output_tokens": 0, - "input_tokens_details": {"cached_tokens": 0}, - "output_tokens_details": {"reasoning_tokens": 0}, - } - if streamed: - event = {"type": "response.completed", "sequence_number": 1, "response": payload} - return httpx2.Response( - 200, - headers={"content-type": "text/event-stream"}, - content=f"data: {json.dumps(event)}\n\ndata: [DONE]\n\n", - ) - return httpx2.Response(200, json=payload) - - async with AsyncOpenAI( - api_key="test-key", - http_client=httpx2.AsyncClient(transport=httpx2.MockTransport(respond)), - ) as client: - agent = Agent( - name="root", - model=OpenAIResponsesModel( - model="base", openai_client=client, model_is_explicit=not prompt_owned - ), - prompt={"id": "fixture"} if prompt_owned else None, - model_settings=ModelSettings( - extra_body=None if prompt_owned else {"model": "selected"} - ), - ) - with pytest.raises(RunBudgetError) as error: - await run( - agent, RunBudget(max_estimated_cost_usd=0.01, estimate_cost_usd=estimate), streamed - ) - assert error.value.limit == "estimated_cost" - assert sent == [None if prompt_owned else "selected"] - assert priced == ["selected"]