diff --git a/src/agents/__init__.py b/src/agents/__init__.py index a72d61f224..ae226a9f56 100644 --- a/src/agents/__init__.py +++ b/src/agents/__init__.py @@ -128,6 +128,7 @@ ToolNameCollisionPolicy, ToolNotFoundBehavior, ) +from .run_budget import RunBudget, RunBudgetError from .run_context import AgentHookContext, RunContextWrapper, TContext from .run_error_handlers import ( RunErrorData, @@ -495,6 +496,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 e1f6cb90df..fb1f7c3697 100644 --- a/src/agents/agent.py +++ b/src/agents/agent.py @@ -810,6 +810,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. @@ -1158,6 +1161,8 @@ async def close_stream() -> 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 cbb549a931..d7a7efe06d 100644 --- a/src/agents/memory/openai_responses_compaction_session.py +++ b/src/agents/memory/openai_responses_compaction_session.py @@ -485,8 +485,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 = redact_items( _strip_orphaned_assistant_ids( 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 332d1c5604..e32377616f 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 ae3a2c2120..5c35a7a50a 100644 --- a/src/agents/run.py +++ b/src/agents/run.py @@ -54,6 +54,7 @@ from .memory.resumable_session import ResumableSession from .models._run_context import ModelToolHooks from .result import RunResult, RunResultStreaming +from .run_budget import _check_resume, _prepare_budget from .run_config import ( DEFAULT_MAX_TURNS, CallModelData, @@ -723,6 +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) resolved_reasoning_item_id_policy: ReasoningItemIdPolicy | None = ( run_config.reasoning_item_id_policy if run_config.reasoning_item_id_policy is not None @@ -766,6 +768,7 @@ async def _run_impl( ) context_wrapper._resolve_function_approval_owners(starting_agent) validate_resume_policy(run_state, context_wrapper, run_config) + await _check_resume(run_state, run_config.budget, context_wrapper) context = context_wrapper.context reject_unrecoverable_terminal_state(run_state) @@ -792,7 +795,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, @@ -2794,6 +2797,9 @@ def run_streamed( else contextlib.nullcontext(), ): input = _prepare_private_input(starting_agent, input, run_config, kwargs) + budget = _prepare_budget( + run_config, starting_agent, input if isinstance(input, RunState) else None + ) # Handle RunState input is_resumed_state = isinstance(input, RunState) run_state: RunState[TContext] | None = None @@ -2863,7 +2869,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 @@ -3034,8 +3040,10 @@ async def run_loop() -> None: if run_config.tracing_disabled else contextlib.nullcontext(), ): - if isinstance(session, ResumableRun): - try: + try: + if is_resumed_state and run_state is not None: + await _check_resume(run_state, run_config.budget, context_wrapper) + if isinstance(session, ResumableRun): await session.begin( input, ModelToolHooks( @@ -3044,10 +3052,10 @@ async def run_loop() -> None: run_config.tool_not_found_behavior, ) session.bind_state(run_state) - except BaseException: - streamed_result.is_complete = True - streamed_result._event_queue.put_nowait(QueueCompleteSentinel()) - raise + except BaseException: + streamed_result.is_complete = True + streamed_result._event_queue.put_nowait(QueueCompleteSentinel()) + raise configuration_agent = ( run_state._current_agent if run_state is not None and run_state._current_agent is not None diff --git a/src/agents/run_budget.py b/src/agents/run_budget.py new file mode 100644 index 0000000000..73c41783a7 --- /dev/null +++ b/src/agents/run_budget.py @@ -0,0 +1,305 @@ +"""Limits on logical model calls and observed tokens in a Runner run.""" + +from __future__ import annotations + +import copy +from dataclasses import dataclass +from typing import TYPE_CHECKING, Any, Literal + +from ._redaction import current_redactor, protected_error +from .exceptions import ( + AgentsException, + InputGuardrailTripwireTriggered, + UserError, + _mark_error_to_drain_stream_events, + _raise_data_redacted_error, +) +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_context import RunContextWrapper + 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, kw_only=True) +class RunBudget: + """Limits for one Python Runner root, including handoffs and approval resumes. + + Pass the same limits and missing-usage policy on resume:: + + 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_model_calls: int | None = None + max_tokens: int | None = None + missing_usage: Literal["stop", "continue"] = "stop" + + def __post_init__(self) -> None: + 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 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'.") + + +class _BudgetCheckpointError(UserError): + """A budget failure that must also abort an enclosing agent-tool checkpoint.""" + + +class RunBudgetError(AgentsException): + """A blocked model call. Check code for the reason and limit for the ceiling. + + 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"], + *, + limit: Literal["model_calls", "tokens"] | None = None, + ): + self.limit = limit + self.code = code + if code == "run_budget_usage_unavailable": + message = 'Unknown usage. Use missing_usage="continue" to count only known totals.' + else: + ceiling = "max_model_calls" if limit == "model_calls" else "max_tokens" + message = ( + f"RunBudget.{ceiling} reached. Check completed work before starting a new run." + ) + super().__init__(f"{code}: {message}") + + +@dataclass +class _BudgetState: + limits: RunBudget + requests: int = 0 + tokens: int = 0 + unavailable: bool = False + + def observe(self, usage: Usage | None) -> None: + if self.limits.max_tokens 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 + + def check(self) -> None: + limits = self.limits + if limits.max_model_calls is not None and self.requests >= limits.max_model_calls: + raise RunBudgetError("run_budget_exceeded", limit="model_calls") + if limits.max_tokens is not None and self.tokens >= limits.max_tokens: + raise RunBudgetError("run_budget_exceeded", limit="tokens") + if self.unavailable and limits.missing_usage == "stop": + raise RunBudgetError("run_budget_usage_unavailable") + + def checkpoint(self) -> dict[str, Any]: + # Schema 1.25 stores logical model calls as requests. + return { + "max_requests": self.limits.max_model_calls, + "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_model_calls=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_budget(tool: Tool) -> RunBudget | None: + invoker = getattr(tool, "on_invoke_tool", None) + impl = getattr(invoker, "_invoke_tool_impl", None) + config = getattr(impl, "__agents_run_config__", None) + return config.budget if config is not None else None + + +async def _admit( + budget: _BudgetState | None, + model: Model, + session: Session | None, + *, + streamed_result: RunResultStreaming | None = None, +) -> None: + if budget is None: + return + from .run_internal.resumable_session import ResumableRun, checkpoint_streamed_result + + try: + _check_model(model) + budget.check() + budget.requests += 1 + except (RunBudgetError, UserError) as 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 + + +async def _check_resume( + state: RunState[Any], limits: RunBudget | None, context: RunContextWrapper[Any] +) -> 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, _function_tool_enabled + + saved = state._context._budget if state._context is not None else None + if (saved.limits if saved is not None else None) != limits: + 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 and grant only for required branches. + 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 = (_tool_budget(tool) for tool in bindings) + policy = next((value for value in policies if value is not None), None) + if await _check_resume(child, policy, context): + owner = state._context + if owner is not None and owner is not context: + # Agent.as_tool keeps the nested wrapper but forwards application + # context and usage. Leave the saved state untouched on refusal. + owner = copy.copy(owner) + owner.context = context.context + owner.usage = context.usage + if ( + len(bindings) != 1 + or bindings[0]._agent_instance is not action.function_tool._agent_instance + or owner is None + or state._current_agent is None + or not await _function_tool_enabled(bindings[0], owner, state._current_agent) + ): + raise UserError("A pending RunBudget requires the same unique enabled agent tool.") + budgeted = True + return budgeted + + +def _prepare_budget( + config: RunConfig, agent: Agent[Any], state: RunState[Any] | None +) -> _BudgetState | None: + from .models.interface import Model + + 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 + ) + 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 0711f22530..b95367ce8b 100644 --- a/src/agents/run_config.py +++ b/src/agents/run_config.py @@ -29,6 +29,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 @@ -671,6 +672,9 @@ class RunConfig: metadata. No redactor is active by default. """ + budget: RunBudget | None = None + """Optional limits on root model calls and observed tokens.""" + if TYPE_CHECKING: def __init__( @@ -703,6 +707,7 @@ def __init__( str | OutputGuardrailBlockedMessageFormatter | None ) = None, redact_text: Callable[[str], str] | None = None, + budget: RunBudget | dict[str, Any] | None = None, ) -> None: ... def __post_init__(self) -> None: @@ -710,6 +715,10 @@ def __post_init__(self) -> None: not callable(self.redact_text) or inspect.iscoroutinefunction(self.redact_text) ): raise TypeError("redact_text must be a synchronous callable or 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 7af842828d..c2064604d5 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: @@ -218,6 +219,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( @@ -293,6 +304,8 @@ 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._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 48c8230973..82ddf6ffeb 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 @@ -613,6 +614,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 @@ -646,6 +648,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 c73a8da0dc..8d612a736f 100644 --- a/src/agents/run_internal/resumable_session.py +++ b/src/agents/run_internal/resumable_session.py @@ -60,6 +60,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 ea9c283ebf..273dab3c8f 100644 --- a/src/agents/run_internal/run_loop.py +++ b/src/agents/run_internal/run_loop.py @@ -79,6 +79,7 @@ ) from ..models._run_context import ModelToolHooks, model_run_context 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 @@ -2673,6 +2674,7 @@ def get_model_stream() -> AsyncIterator[TResponseStreamEvent]: prompt=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=( @@ -2762,16 +2764,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, @@ -3172,7 +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) 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 79823f3802..61ef87ebbf 100644 --- a/src/agents/run_state.py +++ b/src/agents/run_state.py @@ -60,6 +60,7 @@ deserialize_function_tool_lookup_key, get_function_tool_lookup_key, get_function_tool_lookup_key_for_tool, + get_function_tool_lookup_keys, get_function_tool_namespace, get_function_tool_qualified_name, serialize_function_tool_lookup_key, @@ -121,6 +122,7 @@ native_approval_checkpoint, restore_native_approval_call, ) +from .run_budget import _BudgetCheckpointError, _BudgetState from .run_context import RunContextWrapper, _ApprovalRecord, _FunctionToolApprovalKey from .run_internal.items import ( NestedHistoryOwnedItemRef, @@ -258,7 +260,7 @@ def _default_run_state_validation_error( # 3. to_json() always emits CURRENT_SCHEMA_VERSION. # 4. Forward compatibility is intentionally fail-fast (older SDKs reject newer or unsupported # versions). -CURRENT_SCHEMA_VERSION = "1.24" +CURRENT_SCHEMA_VERSION = "1.25" _PROGRAMMATIC_TOOL_CALLING_MIN_SCHEMA_VERSION = "1.13" _HOSTED_MCP_APPROVALS_MIN_SCHEMA_VERSION = "1.14" _CURRENT_RESPONSE_OWNERSHIP_MIN_SCHEMA_VERSION = "1.17" @@ -326,6 +328,7 @@ def _default_run_state_validation_error( "records required ResumableSession ownership, and preserves native approval receipts." ), "1.24": "Requires caller-supplied text redaction when resuming protected RunState snapshots.", + "1.25": "Preserves required Runner budgets and consumption across approval resumes.", } SUPPORTED_SCHEMA_VERSIONS = frozenset(SCHEMA_VERSION_SUMMARIES) @@ -2062,6 +2065,8 @@ def _serialize_snapshot( # Preserve metadata so deserialization can warn when context types were erased. "context_meta": context_meta, } + 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 @@ -2617,8 +2622,8 @@ def validation_error_factory( validation_error_factory=validation_error_factory, ) - if _unsupported_native_approvals(state_json): - raise validation_error_factory(_UNSUPPORTED_NATIVE_APPROVALS, UserError) + required_children: set[int] = set() + _validate_pending_approvals(state_json, validation_error_factory, required_children) from .sandbox._mount_security import sanitize_run_state_sandbox_mount_authority @@ -2638,15 +2643,23 @@ def validation_error_factory( ) state_json["sandbox"] = sanitized_sandbox - return await _build_run_state_from_json( + restored = await _build_run_state_from_json( initial_agent=initial_agent, state_json=state_json, context_override=context_override, context_deserializer=context_deserializer, strict_context=strict_context, + required_children=required_children, validation_error_factory=validation_error_factory, ) + if required_children: + raise validation_error_factory(_REQUIRED_CHILD_MISSING, UserError) + return restored 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, @@ -2674,29 +2687,48 @@ def validation_error_factory( "Run state contains unsupported native tool approvals. " "Check for prior effects before starting a new run with SDK tools." ) +_REQUIRED_CHILD_MISSING = "Cannot restore a required pending agent tool." -def _unsupported_native_approvals(state: dict[str, Any], *, nested: bool = False) -> bool: - """Check nested agent runs before best-effort context restoration can skip a child.""" +def _validate_pending_approvals( + state: dict[str, Any], + validation_error_factory: RunStateValidationErrorFactory, + required_children: set[int], + *, + nested: bool = False, +) -> bool: + """Validate before best-effort child restoration and report whether a budget is required.""" + context = state.get("context") + requires_budget = isinstance(context, dict) and "budget" in context response = state.get("last_processed_response") if not isinstance(response, dict): - return False + response = {} approvals = response.get("native_approvals") if approvals: # Only the root session has a claimed checkpoint. A nested state cannot # authorize an action, even when it contains an otherwise valid receipt. if nested or not isinstance(approvals, list) or len(approvals) != 1: - return True + raise validation_error_factory(_UNSUPPORTED_NATIVE_APPROVALS, UserError) item = approvals[0] if not isinstance(item, dict) or not isinstance(item.get("codex_native_checkpoint"), dict): - return True + raise validation_error_factory(_UNSUPPORTED_NATIVE_APPROVALS, UserError) functions = response.get("functions") if isinstance(functions, list): for entry in functions: child = entry.get("agent_run_state") if isinstance(entry, dict) else None - if isinstance(child, dict) and _unsupported_native_approvals(child, nested=True): - return True - return False + if isinstance(child, dict) and _validate_pending_approvals( + child, validation_error_factory, required_children, nested=True + ): + # Track the exact child snapshot until its pending run is registered. + required_children.add(id(child)) + requires_budget = True + if requires_budget: + version = _validate_run_state_schema_version( + state, validation_error_factory=validation_error_factory + ) + if tuple(map(int, version.split("."))) < (1, 25): + raise _BudgetCheckpointError("Run budgets require schema 1.25 or later.") + return requires_budget def _validate_run_state_json_value(value: object) -> None: @@ -3329,6 +3361,7 @@ async def _restore_pending_nested_agent_tool_runs( context_deserializer: ContextDeserializer | None = None, strict_context: bool = False, validation_error_factory: RunStateValidationErrorFactory = _default_run_state_validation_error, + required_children: set[int] | None = None, ) -> None: """Rehydrate nested agent-as-tool run state into the ephemeral tool-call cache.""" if not function_actions: @@ -3357,8 +3390,11 @@ async def _restore_pending_nested_agent_tool_runs( state_json=dict(nested_state_data), context_deserializer=context_deserializer, strict_context=strict_context, + required_children=required_children, validation_error_factory=validation_error_factory, ) + except _BudgetCheckpointError: + raise except Exception: if strict_context: raise @@ -3376,6 +3412,8 @@ async def _restore_pending_nested_agent_tool_runs( # older pending interruptions after consuming this restored entry. drop_agent_tool_run_result(tool_call, scope_id=scope_id) record_agent_tool_run_result(tool_call, cast(Any, pending_result), scope_id=scope_id) + if required_children: + required_children.discard(id(nested_state_data)) async def _deserialize_processed_response( @@ -3392,6 +3430,7 @@ async def _deserialize_processed_response( program_call_ids: Collection[str] = (), completed_program_call_ids: Collection[str] = (), validation_error_factory: RunStateValidationErrorFactory = _default_run_state_validation_error, + required_children: set[int] | None = None, ) -> ProcessedResponse: """Deserialize a ProcessedResponse from JSON data. @@ -3599,6 +3638,18 @@ def _deserialize_function_actions() -> list[_DeserializedFunctionAction]: ) nested_state_data = entry.get("agent_run_state") + if required_children and id(nested_state_data) in required_children: + if ( + not function_tool._is_agent_tool + or not isinstance(function_tool._agent_instance, Agent) + or sum( + tool_name in get_function_tool_lookup_keys(tool) + for tool in all_tools + if isinstance(tool, FunctionTool) + ) + != 1 + ): + raise validation_error_factory(_REQUIRED_CHILD_MISSING, UserError) deserialized.append( _DeserializedFunctionAction( action=ToolRunFunction( @@ -3719,6 +3770,7 @@ def _deserialize_function_actions() -> list[_DeserializedFunctionAction]: scope_id=scope_id, context_deserializer=context_deserializer, strict_context=strict_context, + required_children=required_children, validation_error_factory=validation_error_factory, ) @@ -4358,6 +4410,7 @@ async def _build_run_state_from_json( context_deserializer: ContextDeserializer | None = None, strict_context: bool = False, validation_error_factory: RunStateValidationErrorFactory = _default_run_state_validation_error, + required_children: set[int] | None = None, ) -> RunState[Any, Agent[Any]]: """Shared helper to rebuild RunState from JSON payload. @@ -4424,6 +4477,7 @@ 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 = _BudgetState.restore(context_data["budget"]) if "budget" in context_data else None usage = deserialize_usage(context_data.get("usage", {})) serialized_context: Any = context_data.get("context", _MISSING_CONTEXT_SENTINEL) @@ -4486,6 +4540,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) @@ -4646,6 +4701,7 @@ async def _build_run_state_from_json( defer_mcp_discovery=state._requires_redaction, program_call_ids=program_call_ids, completed_program_call_ids=completed_program_call_ids, + required_children=required_children, validation_error_factory=validation_error_factory, ) else: @@ -5863,6 +5919,8 @@ 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.", + _REQUIRED_CHILD_MISSING, "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/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 f7947f6fcf..506d26b2a1 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 from ._redaction import require_clean @@ -230,6 +238,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 @@ -264,6 +289,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 @@ -372,7 +398,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, @@ -380,6 +406,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/fixtures/run_state/features/v1_24_requires_declaration.json b/tests/fixtures/run_state/features/v1_24_requires_declaration.json new file mode 100644 index 0000000000..ed00bb7129 --- /dev/null +++ b/tests/fixtures/run_state/features/v1_24_requires_declaration.json @@ -0,0 +1,70 @@ +{ + "$schemaVersion": "1.24", + "auto_previous_response_id": false, + "context": { + "approvals": {}, + "context": {}, + "context_meta": { + "omitted": false, + "original_type": "mapping", + "requires_deserializer": false, + "serialized_via": "mapping" + }, + "tool_invocations": { + "call": { + "approval_scope": "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", + "completed": false, + "executed": false, + "fingerprint": "bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb", + "requires_declaration": true, + "type": "function_call" + } + }, + "usage": { + "input_tokens": 0, + "input_tokens_details": [ + { + "cache_write_tokens": 0, + "cache_write_tokens_details": null, + "cached_tokens": 0 + } + ], + "output_tokens": 0, + "output_tokens_details": [ + { + "reasoning_tokens": 0 + } + ], + "request_usage_entries": [], + "requests": 0, + "total_tokens": 0 + } + }, + "conversation_id": null, + "current_agent": { + "name": "compat-agent" + }, + "current_step": null, + "current_turn": 0, + "current_turn_persisted_item_count": 0, + "generated_items": [], + "generated_prompt_cache_key": null, + "generated_session_item_indexes": [], + "input_guardrail_results": [], + "last_model_response": null, + "last_processed_response": null, + "max_turns": 10, + "model_responses": [], + "nested_history_owned_session_item_refs": [], + "no_active_agent_run": true, + "original_input": "historical input", + "output_guardrail_results": [], + "pending_input": [], + "previous_response_id": null, + "reasoning_item_id_policy": null, + "session_items": [], + "tool_input_guardrail_results": [], + "tool_output_guardrail_results": [], + "tool_use_tracker": {}, + "trace": null +} diff --git a/tests/fixtures/run_state/generate_corpus.py b/tests/fixtures/run_state/generate_corpus.py index 24c6a99428..a6c77f911b 100644 --- a/tests/fixtures/run_state/generate_corpus.py +++ b/tests/fixtures/run_state/generate_corpus.py @@ -47,6 +47,7 @@ RELEASED_1_22_WRITER = "0a74177ed23ffb0c2dba24eda3fb12fb58e3e09d" CODEX_1_22_WRITER = "448ae7a3d9c5ddbfa0656a04a021ffb3f3c16530" RESUMABLE_1_23_WRITER = "d48e3c89ecdb71ad78d9eb90ed97bf632598d51c" +RELEASED_1_24_WRITER = "6463d16ca5b680107df2e37386ed94c1bbb8ff81" GUARDRAIL_1_20_WRITER = "125efa029b4bfd84238bd2c4fd69c3406f802663" LEGACY_CANONICAL_COMPATIBILITY_NOTE = ( @@ -597,6 +598,21 @@ def approval(call_id): "requires_resumable_session", 'state._resumable_binding = "detached"', ), + Scenario( + "1.24", + RELEASED_1_24_WRITER, + "requires_declaration", + """ +from agents.run_context import _ToolInvocationRecord + +state._context._tool_invocations["call"] = _ToolInvocationRecord( + invocation_type="function_call", + approval_scope="a" * 64, + fingerprint="b" * 64, + requires_declaration=True, +) +""", + ), ) @@ -645,6 +661,7 @@ def approval(call_id): Scenario("1.21", RELEASED_1_21_WRITER, "minimal", ""), Scenario("1.22", RELEASED_1_22_WRITER, "minimal", ""), Scenario("1.23", RESUMABLE_1_23_WRITER, "minimal", ""), + Scenario("1.24", RELEASED_1_24_WRITER, "minimal", ""), ) diff --git a/tests/fixtures/run_state/minimal/v1_24.json b/tests/fixtures/run_state/minimal/v1_24.json new file mode 100644 index 0000000000..40bca5ab0c --- /dev/null +++ b/tests/fixtures/run_state/minimal/v1_24.json @@ -0,0 +1,61 @@ +{ + "$schemaVersion": "1.24", + "auto_previous_response_id": false, + "context": { + "approvals": {}, + "context": {}, + "context_meta": { + "omitted": false, + "original_type": "mapping", + "requires_deserializer": false, + "serialized_via": "mapping" + }, + "tool_invocations": {}, + "usage": { + "input_tokens": 0, + "input_tokens_details": [ + { + "cache_write_tokens": 0, + "cache_write_tokens_details": null, + "cached_tokens": 0 + } + ], + "output_tokens": 0, + "output_tokens_details": [ + { + "reasoning_tokens": 0 + } + ], + "request_usage_entries": [], + "requests": 0, + "total_tokens": 0 + } + }, + "conversation_id": null, + "current_agent": { + "name": "compat-agent" + }, + "current_step": null, + "current_turn": 0, + "current_turn_persisted_item_count": 0, + "generated_items": [], + "generated_prompt_cache_key": null, + "generated_session_item_indexes": [], + "input_guardrail_results": [], + "last_model_response": null, + "last_processed_response": null, + "max_turns": 10, + "model_responses": [], + "nested_history_owned_session_item_refs": [], + "no_active_agent_run": true, + "original_input": "historical input", + "output_guardrail_results": [], + "pending_input": [], + "previous_response_id": null, + "reasoning_item_id_policy": null, + "session_items": [], + "tool_input_guardrail_results": [], + "tool_output_guardrail_results": [], + "tool_use_tracker": {}, + "trace": null +} diff --git a/tests/fixtures/run_state/sources.json b/tests/fixtures/run_state/sources.json index a449b59b68..48789451a0 100644 --- a/tests/fixtures/run_state/sources.json +++ b/tests/fixtures/run_state/sources.json @@ -171,6 +171,13 @@ "fixture": "features/v1_23_requires_resumable_session.json", "provenance": "historical_writer", "version": "1.23" + }, + { + "commit": "6463d16ca5b680107df2e37386ed94c1bbb8ff81", + "feature": "requires_declaration", + "fixture": "features/v1_24_requires_declaration.json", + "provenance": "historical_writer", + "version": "1.24" } ], "resume": { @@ -270,6 +277,10 @@ "commit": "d48e3c89ecdb71ad78d9eb90ed97bf632598d51c", "fixture": "minimal/v1_23.json" }, + "1.24": { + "commit": "6463d16ca5b680107df2e37386ed94c1bbb8ff81", + "fixture": "minimal/v1_24.json" + }, "1.3": { "commit": "6814a54711f591712c893f0a8be1cf56c512ae63", "fixture": "minimal/v1_3.json" diff --git a/tests/test_run_budget.py b/tests/test_run_budget.py new file mode 100644 index 0000000000..583efe2bf5 --- /dev/null +++ b/tests/test_run_budget.py @@ -0,0 +1,842 @@ +"""Root budget contracts through the public Runner and approval boundaries.""" + +from __future__ import annotations + +import asyncio +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, + GuardrailFunctionOutput, + InputGuardrailTripwireTriggered, + MaxTurnsExceeded, + ModelRetrySettings, + ModelSettings, + RunBudget, + RunBudgetError, + RunConfig, + Runner, + RunState, + Usage, + UserError, + input_guardrail, + 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, ResumableSessionError +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]) +@pytest.mark.parametrize("field", ["max_model_calls", "max_tokens"]) +def test_invalid_limits(field, value): + with pytest.raises(ValueError, match="RunBudget"): + RunConfig(budget={field: value}) + + +@pytest.mark.parametrize( + "limits,blocked", + [ + ({"max_model_calls": 0}, "model_calls"), + ({"max_tokens": 0}, "tokens"), + ({"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 + + +@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_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 + + +@pytest.mark.asyncio +@pytest.mark.parametrize("streamed", [False, True]) +@pytest.mark.parametrize( + "usage,policy,code", + [ + (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, usage, policy, code): + model = ScriptedModel( + [ + 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" + + +@pytest.mark.asyncio +@pytest.mark.parametrize("streamed", [False, True]) +@pytest.mark.parametrize( + "turns,calls,error", + [(1, 2, MaxTurnsExceeded), (1, 1, MaxTurnsExceeded), (None, 1, RunBudgetError)], +) +async def test_max_turns_still_limits_corrections(streamed, turns, calls, error): + model = ScriptedModel([[get_function_tool_call("unknown")]]) + 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 + + +@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_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()) + # 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"), + ): + 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_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) + 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 +@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_model_calls=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 +@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( + 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_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 +@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 +@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 +async def test_explicit_child_budget_survives_nested_approval(): + 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_model_calls=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_model_calls=2, max_tokens=2) + state = (await run(root, budget)).to_state() + 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_child_budget_requires_supported_schema_on_child_and_parent(): + @tool(needs_approval=True) + def record() -> str: + pytest.fail("Restoring an approval must not execute the tool.") + + child = Agent( + name="child", + model=ScriptedModel([step(get_function_tool_call("record", call_id="inner"), 7)]), + tools=[record], + ) + nested = child.as_tool( + "ask", "Ask", run_config=RunConfig(budget=RunBudget(max_tokens=7), tracing_disabled=True) + ) + parent = Agent( + name="parent", + model=ScriptedModel([step(get_function_tool_call("ask", '{"input":"check"}'), 1)]), + tools=[nested], + ) + state = (await run(parent, None)).to_state() + for downgrade_parent in (True, False): + data = state.to_json() + inner = data["last_processed_response"]["functions"][0]["agent_run_state"] + assert "budget" not in data["context"] and inner["context"]["budget"]["tokens"] == 7 + (data if downgrade_parent else inner)["$schemaVersion"] = "1.24" + with pytest.raises(UserError, match="RunBudget"): + await RunState.from_json(parent, data) + + +@pytest.mark.asyncio +@pytest.mark.parametrize("approved", [False, True]) +async def test_unavailable_budgeted_grandchild_refuses_restore_before_sibling(approved): + effects = [] + + @tool(needs_approval=True) + def record() -> str: + effects.append("record") + return "saved" + + def model(*calls): + return ScriptedModel([ModelStep(output=list(calls)), step(get_text_message("done"), 1)]) + + 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_model_calls=2), tracing_disabled=True) + allowed = True + + async def grant(ctx, agent): + assert agent.name == "middle" + return allowed and ctx.context["allowed"] + + inner = leaf.as_tool("inner", "Delegate", run_config=config, is_enabled=grant) + middle_model = model(get_function_tool_call("inner", '{"input":"go"}', "inner")) + middle = Agent(name="middle", tools=[inner], model=middle_model) + root_model = model( + get_function_tool_call("record", call_id="sibling"), + get_function_tool_call("ask", '{"input":"go"}', "outer"), + ) + root = Agent(name="root", tools=[record, middle.as_tool("ask", "Ask")], model=root_model) + store = MemoryStore() + session = await ResumableSession.create(store) + state = (await run(root, None, session=session, context={"allowed": True})).to_state() + if approved: + for item in state.get_interruptions(): + state.approve(item) + saved = state.to_string() + checks = [] + + def disabled(ctx, agent): + checks.append(agent.name) + return False + + unavailable = leaf.as_tool("inner", "Delegate", run_config=config, is_enabled=disabled) + replacement = Agent(name="other", tools=[record]).as_tool( + "inner", "Delegate", run_config=config + ) + for tools in ( + [], + [unavailable], + [inner, inner], + [replacement], + [replace(record, name="inner")], + ): + middle.tools = list(tools) + with pytest.raises(UserError): + await RunState.from_string(root, saved) + assert checks == ["middle"] + middle.tools = [replace(inner, is_enabled=False)] + with pytest.raises(UserError, match="required pending agent tool"): + await RunState.from_string(root, saved, strict_context=True) + assert not effects + assert len(root_model.calls) == len(middle_model.calls) == len(leaf_model.calls) == 1 + middle.tools = [inner] + pending = await session.load_state(root, context_override={"allowed": False}) + for item in pending.get_interruptions(): + pending.approve(item) + for enabled, context in [(True, None), (False, {"allowed": True}), (True, {"allowed": False})]: + allowed = enabled + with pytest.raises(UserError, match="RunBudget"): + await run(root, None, approved, pending, context=context) + assert store.checkpoint(session.session_id)["status"] == "paused" + assert not effects + assert len(root_model.calls) == len(middle_model.calls) == len(leaf_model.calls) == 1 + result = await run(root, None, approved, pending, context={"allowed": True}) + assert result.final_output == "done" and effects == ["record", "record"] + assert len(root_model.calls) == len(middle_model.calls) == len(leaf_model.calls) == 2 + + +@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() + for version in ("1.22", "1.23", "1.24"): + with pytest.raises(UserError, match="RunBudget"): + await RunState.from_json(root, {**data, "$schemaVersion": version}) + 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 +@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), streamed) + + +@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]) + 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( + [ + step(get_function_tool_call("ask", '{"input":"check"}'), 1), + step(get_text_message("done"), 1), + ] + ) + root = Agent(name="root", model=outer, tools=[nested]) + 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_model_calls=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_model_calls=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_model_calls=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_model_calls=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_model_calls=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" + + +@pytest.mark.asyncio +@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(session_mode, protected): + effects = [] + + @tool + def record() -> str: + effects.append(1) + return "saved" + + store = MemoryStore() + 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( + agent, + "begin", + session=session, + run_config=RunConfig( + budget=RunBudget(max_model_calls=1), + tracing_disabled=True, + redact_text=(lambda s: s.replace("working", "public")) if protected else None, + ), + ) + events = [] + + async def consume(): + async for event in result.stream_events(): + if protected: + assert event.type != "raw_response_event" + assert "working" not in repr(event) + 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: + if isinstance(session, ResumableSession): + await asyncio.wait_for(store.saving.wait(), timeout=5) + assert not events + finally: + store.release.set() + expected = ( + ResumableSessionError if fail else (RuntimeError if protected else RunBudgetError) + ) + 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] + 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_model_calls=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.asyncio +async def test_buffered_budget_stop_preserves_error_redaction(): + model = ScriptedModel([[get_function_tool_call("unknown")]]) + config = RunConfig( + budget=RunBudget(max_model_calls=1), + redact_text=lambda text: text, + tool_not_found_behavior="return_error_to_model", + tracing_disabled=True, + ) + 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 diff --git a/tests/test_run_state.py b/tests/test_run_state.py index f0f6ce29c8..b5f8d617f3 100644 --- a/tests/test_run_state.py +++ b/tests/test_run_state.py @@ -9043,6 +9043,7 @@ def test_supported_schema_versions_match_released_boundary(self): "1.21", "1.22", "1.23", + "1.24", CURRENT_SCHEMA_VERSION, } )