diff --git a/examples/model_providers/model_preflight.py b/examples/model_providers/model_preflight.py new file mode 100644 index 0000000000..0d6f3622a0 --- /dev/null +++ b/examples/model_providers/model_preflight.py @@ -0,0 +1,52 @@ +"""Inspect a request without sampling, uploading files or executing tools. + +Run with a model name and optionally --codex. A local check cannot establish +whether the account has access to that model or what host policy permits. +With --codex, the SDK workspace profile blocks native workspace execution by +supplying no execution environments. Native tools may still be advertised, and +native child model requests can still run. Shared child budgets remain unsupported. +""" + +import argparse +import asyncio + +from agents import ModelRequest, ToolExecutionConfig +from agents.decorators import tool +from agents.models.codex import CodexProvider +from agents.models.openai_provider import OpenAIProvider + + +@tool +def inspect_workspace() -> str: + """Return an application-owned workspace summary.""" + return "No pending changes." + + +async def main(name: str, use_codex: bool) -> None: + # The placeholder key is sufficient because this example makes no API request. + provider = CodexProvider() if use_codex else OpenAIProvider(api_key="unused-for-preflight") + try: + model = provider.get_model(name) + report = model.preflight( + ModelRequest( + input="Summarize the workspace.", + tools=[inspect_workspace], + tool_execution=ToolExecutionConfig(workspace_execution="sdk"), + ) + ) + print(report.adapter, report.static_validation) + for route in report.tools: + print(route.name, route.executor) + for check in report.unchecked: + print("Unchecked:", check) + report.raise_for_errors() + finally: + await provider.aclose() + + +if __name__ == "__main__": + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("model") + parser.add_argument("--codex", action="store_true") + args = parser.parse_args() + asyncio.run(main(args.model, args.codex)) diff --git a/src/agents/__init__.py b/src/agents/__init__.py index 03f07bd8c5..17f5dc1143 100644 --- a/src/agents/__init__.py +++ b/src/agents/__init__.py @@ -88,6 +88,7 @@ SessionSettings, is_openai_responses_compaction_aware_session, ) +from .model_preflight import ModelPreflight, ModelRequest, ToolOwnership from .model_settings import ModelSettings from .models.interface import Model, ModelProvider, ModelTracing from .models.multi_provider import MultiProvider @@ -377,6 +378,9 @@ def enable_verbose_stdout_logging() -> None: __all__ = [ + "ModelPreflight", + "ModelRequest", + "ToolOwnership", "Agent", "AgentBase", "AgentToolStreamEvent", diff --git a/src/agents/model_preflight.py b/src/agents/model_preflight.py new file mode 100644 index 0000000000..38220fb5b0 --- /dev/null +++ b/src/agents/model_preflight.py @@ -0,0 +1,144 @@ +"""Static request checks and execution ownership, without sampling or tool discovery.""" + +from __future__ import annotations + +from dataclasses import dataclass, field +from typing import TYPE_CHECKING, Literal, cast + +from openai.types.responses.response_prompt_param import ResponsePromptParam + +from .exceptions import UserError +from .items import TResponseInputItem +from .model_settings import ModelSettings +from .run_budget import _validate_explicit_tool_authority +from .tool import ( + ApplyPatchTool, + ComputerTool, + CustomTool, + FunctionTool, + HostedMCPTool, + LocalShellTool, + ShellTool, + Tool, +) + +if TYPE_CHECKING: + from .handoffs import Handoff + from .run_config import ToolExecutionConfig + + +@dataclass(frozen=True) +class ToolOwnership: + """Who dispatches a tool; SDK ownership does not imply a sandbox or remote isolation.""" + + name: str + executor: Literal["sdk", "native", "provider", "external", "unknown"] + + +@dataclass(frozen=True) +class ModelRequest: + """The effective request to check. Pass resolved tools; this never discovers MCP tools. + + A preflight does not call a selector, run hooks, load a session, read media files, + validate credentials, or query a provider catalog. Runs with model selection or + an explicit SDK workspace/native recovery policy automatically check the actual + request after input filtering, including later turns. Other runs retain their + adapters' existing request validation without an automatic preflight pass. + """ + + input: str | list[TResponseInputItem] + model_settings: ModelSettings = field(default_factory=ModelSettings) + tools: list[Tool] = field(default_factory=list) + handoffs: list[Handoff] = field(default_factory=list) + previous_response_id: str | None = None + conversation_id: str | None = None + prompt: ResponsePromptParam | None = None + tool_execution: ToolExecutionConfig | None = None + resumable: bool = False + + +@dataclass(frozen=True) +class ModelPreflight: + """Request-specific static findings, not a promise of provider or host availability.""" + + adapter: str + static_validation: Literal["passed", "failed", "unknown"] + model_name: str | None = None + tools: tuple[ToolOwnership, ...] = () + errors: tuple[str, ...] = () + unchecked: tuple[str, ...] = () + + def raise_for_errors(self) -> None: + """Reject known incompatibilities without falling back to another adapter.""" + if self.errors: + raise UserError("; ".join(self.errors)) + + +def tool_ownership(tools: list[Tool]) -> tuple[ToolOwnership, ...]: + """Describe SDK dispatch separately from provider and external execution.""" + result = [] + executor: Literal["sdk", "native", "provider", "external", "unknown"] + for tool in tools: + if isinstance(tool, HostedMCPTool) or ( + isinstance(tool, FunctionTool) and tool._mcp_tool_binding is not None + ): + executor = "external" + elif isinstance( + tool, (FunctionTool, CustomTool, ComputerTool, LocalShellTool, ApplyPatchTool) + ): + executor = "sdk" + elif isinstance(tool, ShellTool): + executor = "sdk" if tool.executor is not None else "provider" + else: + executor = "provider" + result.append(ToolOwnership(tool.name, executor)) + return tuple(result) + + +def validate_python_tool_execution(request: ModelRequest) -> None: + """Verify the explicit SDK profile for first-party Python request adapters.""" + execution = request.tool_execution + if execution is None: + return + if execution.require_native_approval_recovery: + raise UserError("Native approval recovery requires CodexProvider and ResumableSession.") + if execution.workspace_execution != "sdk": + return + _validate_explicit_tool_authority( + request.model_settings, request.prompt, policy_name="SDK-only workspace execution" + ) + for tool in request.tools: + if isinstance( + tool, (FunctionTool, CustomTool, ComputerTool, LocalShellTool, ApplyPatchTool) + ): + continue + if isinstance(tool, ShellTool) and tool.executor is not None: + continue + raise UserError( + "SDK-only workspace execution requires SDK callback tools; remove hosted tools." + ) + + +def static_input_copy( + value: str | list[TResponseInputItem], +) -> str | list[TResponseInputItem] | None: + """Copy plain JSON input without iterating user payloads or invoking copy hooks. + + None marks deferred validation: a one-shot iterable or custom object must be + materialized only by the actual adapter. Ordinary JSON null values stay null + inside a successful plain-container copy. + """ + + def copy(value: object) -> object: + if type(value) in (str, int, float, bool, type(None)): + return value + if type(value) is list or type(value) is tuple: + return [copy(item) for item in value] + if type(value) is dict and all(type(key) is str for key in value): + return {key: copy(item) for key, item in value.items()} + raise TypeError + + try: + return cast("str | list[TResponseInputItem]", copy(value)) + except TypeError: + return None diff --git a/src/agents/models/_codex_inputs.py b/src/agents/models/_codex_inputs.py index a5d2dfd471..0f2786069d 100644 --- a/src/agents/models/_codex_inputs.py +++ b/src/agents/models/_codex_inputs.py @@ -22,7 +22,7 @@ from ..tool import ApplyPatchTool, FunctionTool, ShellTool, Tool, ToolSearchTool, WebSearchTool -def _image_content(part: dict[str, Any]) -> dict[str, Any]: +def _image_content(part: dict[str, Any], *, validate_only: bool = False) -> dict[str, Any]: image = part.get("image_url") if isinstance(image, str) and not image.startswith("data:"): parsed = urlparse(image) @@ -36,6 +36,8 @@ def _image_content(part: dict[str, Any]) -> dict[str, Any]: media_type = mimetypes.guess_type(path.name)[0] if media_type not in ("image/png", "image/jpeg", "image/webp", "image/gif"): raise UserError("CodexProvider accepts PNG, JPEG, WebP, and GIF images.") + if validate_only: + return {"type": "input_image", "image_url": image} try: image = f"data:{media_type};base64,{base64.b64encode(path.read_bytes()).decode()}" except (OSError, ValueError) as exc: @@ -73,7 +75,7 @@ def _audio_content(part: dict[str, Any]) -> dict[str, Any]: return {"type": "input_audio", "audio_url": f"data:{media_type};base64,{data}"} -def _user_content(content: Any) -> list[dict[str, Any]]: +def _user_content(content: Any, *, validate_only: bool = False) -> list[dict[str, Any]]: if isinstance(content, str): return [{"type": "input_text", "text": content}] result = [] @@ -83,7 +85,7 @@ def _user_content(content: Any) -> list[dict[str, Any]]: if part["type"] == "input_text": result.append({"type": "input_text", "text": part["text"]}) elif part["type"] == "input_image": - result.append(_image_content(part)) + result.append(_image_content(part, validate_only=validate_only)) elif part["type"] == "input_audio": result.append(_audio_content(part)) else: @@ -96,6 +98,8 @@ def _user_content(content: Any) -> list[dict[str, Any]]: def prepare_codex_history( input: str | list[TResponseInputItem], tools: list[Tool] | None = None, + *, + validate_only: bool = False, ) -> tuple[list[dict[str, Any]], list[dict[str, Any]]]: """Translate SDK replay items and separate the trailing user turn.""" history: list[dict[str, Any]] = [] @@ -184,13 +188,15 @@ def prepare_codex_history( { "type": kind, "call_id": call_id, - "output": output if isinstance(output, str) else _user_content(output), + "output": output + if isinstance(output, str) + else _user_content(output, validate_only=validate_only), } ) elif kind == "message" and item.get("role") in ("user", "assistant", "developer"): role = item["role"] if role in ("user", "developer"): - content = _user_content(item["content"]) + content = _user_content(item["content"], validate_only=validate_only) elif isinstance(item["content"], str): content = [{"type": "output_text", "text": item["content"]}] else: diff --git a/src/agents/models/_openai_shared.py b/src/agents/models/_openai_shared.py index ade8f8fe15..c0c62590af 100644 --- a/src/agents/models/_openai_shared.py +++ b/src/agents/models/_openai_shared.py @@ -85,3 +85,22 @@ def clean_responses_input_item(item: Any) -> Any | None: cleaned.pop("provider_data", None) cleaned.pop("codex_reasoning_summary", None) return cleaned + + +def merge_openai_extra_args( + kwargs: dict[str, Any], + extra_args: dict[str, Any], + *, + method: str, + omitted_types: type | tuple[type, ...], + error_type: type[Exception] = TypeError, +) -> None: + """Allow raw overrides only where the adapter omitted its own argument.""" + duplicates = sorted( + key for key in extra_args if key in kwargs and not isinstance(kwargs[key], omitted_types) + ) + if duplicates: + noun = "argument" if len(duplicates) == 1 else "arguments" + keys = ", ".join(repr(key) for key in duplicates) + raise error_type(f"{method}() got multiple values for keyword {noun} {keys}") + kwargs.update(extra_args) diff --git a/src/agents/models/chatcmpl_converter.py b/src/agents/models/chatcmpl_converter.py index 9bf4c03078..96ea6cdbb0 100644 --- a/src/agents/models/chatcmpl_converter.py +++ b/src/agents/models/chatcmpl_converter.py @@ -565,6 +565,8 @@ def items_to_messages( base_url: str | None = None, should_replay_reasoning_content: ShouldReplayReasoningContent | None = None, strict_feature_validation: bool = False, + *, + warn_on_lossy_tool_output: bool = True, ) -> list[ChatCompletionMessageParam]: """ Convert a sequence of 'Item' objects into a list of ChatCompletionMessageParam. @@ -592,6 +594,8 @@ def items_to_messages( `reasoning_content`. strict_feature_validation: Whether to raise a UserError for Responses-only features that Chat Completions cannot faithfully represent. + warn_on_lossy_tool_output: Disable the placeholder warning during preflight. + Actual request conversion warns when it substitutes the placeholder. Rules: - EasyInputMessage or InputMessage (role=user) => ChatCompletionUserMessageParam @@ -913,11 +917,12 @@ def ensure_assistant_message() -> ChatCompletionAssistantMessageParam: ) if strict_feature_validation: raise UserError(message) - logger.warning( - "%s Replacing the tool output with a placeholder; enable strict " - "feature validation to raise an error instead.", - message, - ) + if warn_on_lossy_tool_output: + logger.warning( + "%s Replacing the tool output with a placeholder; enable " + "strict feature validation to raise an error instead.", + message, + ) tool_result_content = _OMITTED_TOOL_OUTPUT_PLACEHOLDER msg: ChatCompletionToolMessageParam = { "role": "tool", diff --git a/src/agents/models/codex.py b/src/agents/models/codex.py index ed07ea6dfd..ad8698f18e 100644 --- a/src/agents/models/codex.py +++ b/src/agents/models/codex.py @@ -40,9 +40,16 @@ from ..handoffs import Handoff from ..items import ModelResponse, TResponseInputItem, TResponseStreamEvent from ..memory.session import await_session_mutation as _join_close +from ..model_preflight import ( + ModelPreflight, + ModelRequest, + ToolOwnership, + static_input_copy, + tool_ownership, +) from ..model_settings import ModelSettings from ..retry import ModelRetryAdvice, ModelRetryAdviceRequest -from ..tool import ApplyPatchTool, ShellTool, Tool, WebSearchTool +from ..tool import ApplyPatchTool, ShellTool, Tool, ToolSearchTool, WebSearchTool from ..usage import ( Usage, _attach_raw_usage_snapshot, @@ -215,17 +222,62 @@ def _pending_native_call( def _uses_sdk_workspace(tools: list[Tool], bindings: ModelToolHooks | None) -> bool: - settings = bindings.settings if bindings else None + return _sdk_workspace(tools, bindings.settings if bindings else None) + + +def _sdk_workspace(tools: list[Tool], settings: Any) -> bool: return bool( settings - and settings.sdk_only_tool_hooks - and (settings.prepare_tool_input or settings.prepare_tool_output) + and ( + settings.workspace_execution == "sdk" + or ( + settings.sdk_only_tool_hooks + and (settings.prepare_tool_input or settings.prepare_tool_output) + ) + ) ) or any( getattr(tool, "_sdk_sandbox", False) or isinstance(tool, (ShellTool, ApplyPatchTool)) for tool in tools ) +def _request_tool_settings( + tools: list[Tool], dynamic_tools: list[dict[str, Any]], sdk_sandbox: bool +) -> tuple[set[str], dict[str, Any] | None]: + deferred_namespaces = { + tool["name"] + for tool in dynamic_tools + if tool.get("type") == "namespace" + and any(member.get("deferLoading") for member in tool["tools"]) + } + if "functions" in deferred_namespaces: + raise UserError( + "Codex native tool discovery reserves the functions namespace; " + "use another namespace for deferred SDK tools." + ) + web_tools = [tool for tool in tools if isinstance(tool, WebSearchTool)] + if len(web_tools) > 1: + raise UserError("CodexProvider supports one WebSearchTool per request.") + web_request = None + if web_tools: + web = web_tools[0] + if sdk_sandbox: + raise UserError("Expose web search through SDK sandbox tools with CodexProvider.") + if web.image_settings is not None: + raise UserError("CodexProvider does not support web search image settings.") + location = dict(web.user_location) if web.user_location is not None else None + if location is not None and location.pop("type", "approximate") != "approximate": + raise UserError("CodexProvider supports approximate web search locations.") + web_request = { + "external_web_access": web.external_web_access, + "search_context_size": web.search_context_size, + "allowed_domains": web.filters.allowed_domains if web.filters else None, + "user_location": location, + "search_content_types": web.search_content_types, + } + return deferred_namespaces, web_request + + def _settings(settings: ModelSettings) -> tuple[str | None, str | None]: supported = { "timeout", @@ -298,6 +350,77 @@ def __init__(self, name: str | None, provider: CodexProvider) -> None: self._name = name self._provider = provider + def preflight(self, request: ModelRequest) -> ModelPreflight: + """Reuse the Codex adapter's validators without importing or starting native Core.""" + sdk_workspace = _sdk_workspace(request.tools, request.tool_execution) + owners = tuple( + ToolOwnership(tool.name, "native") + if isinstance(tool, (WebSearchTool, ToolSearchTool)) + else owner + for tool, owner in zip(request.tools, tool_ownership(request.tools), strict=True) + ) + if not sdk_workspace: + owners += (ToolOwnership("Codex workspace tools", "native"),) + errors: tuple[str, ...] = () + static_input = static_input_copy(request.input) + try: + if ( + request.previous_response_id is not None + or request.conversation_id is not None + or request.prompt is not None + ): + raise UserError("CodexProvider does not support Responses API state or prompt IDs.") + _settings(request.model_settings) + if static_input is not None: + prepare_codex_history(static_input, request.tools, validate_only=True) + dynamic_tools, identities = prepare_dynamic_tools(request.tools, request.handoffs) + require_sdk_call = request.model_settings.tool_choice == "required" + if require_sdk_call and not identities: + raise UserError( + "CodexProvider tool_choice='required' needs an exposed SDK tool or handoff." + ) + _request_tool_settings(request.tools, dynamic_tools, sdk_workspace) + if request.tool_execution and request.tool_execution.require_native_approval_recovery: + if sdk_workspace: + raise UserError( + "Native approval recovery requires provider-owned workspace tools." + ) + if not request.resumable: + raise UserError("Native approval recovery requires session=ResumableSession.") + if require_sdk_call: + raise UserError( + "Native approval recovery does not support tool_choice='required'. " + "Use tool_choice='auto' to allow native approvals." + ) + except UserError as error: + errors = (str(error),) + return ModelPreflight( + adapter=f"{type(self).__module__}.{type(self).__qualname__}", + static_validation="failed" + if errors + else "passed" + if static_input is not None + else "unknown", + model_name=self._name, + tools=owners, + errors=errors, + unchecked=( + "Model catalog, credentials, and host policy have not been checked.", + "The native runtime checks host policy and execution permissions.", + "The actual request checks local media readability and deferred input.", + "Native approval recovery covers supported unchanged commands and edits only.", + ) + + ( + ( + "Native workspace tools may be advertised, but have no usable " + "execution environment.", + "Native delegation may sample; shared child budgets remain unsupported.", + ) + if sdk_workspace + else () + ), + ) + def get_default_model_settings(self) -> ModelSettings: return ModelSettings() @@ -363,6 +486,20 @@ async def stream_response( conversation_id: str | None, prompt: ResponsePromptParam | None, ) -> AsyncIterator[TResponseStreamEvent]: + bindings = get_model_tool_hooks() + self.preflight( + ModelRequest( + input=input, + model_settings=model_settings, + tools=tools, + handoffs=handoffs, + previous_response_id=previous_response_id, + conversation_id=conversation_id, + prompt=prompt, + tool_execution=bindings.settings if bindings else None, + resumable=bindings.resumable if bindings else False, + ) + ).raise_for_errors() if previous_response_id is not None or conversation_id is not None or prompt is not None: raise UserError("CodexProvider does not support Responses API state or prompt IDs.") effort, summary = _settings(model_settings) @@ -419,37 +556,7 @@ async def stream_response( ], ) ) - deferred_namespaces = { - tool["name"] - for tool in dynamic_tools - if tool.get("type") == "namespace" - and any(member.get("deferLoading") for member in tool["tools"]) - } - if "functions" in deferred_namespaces: - raise UserError( - "Codex native tool discovery reserves the functions namespace; " - "use another namespace for deferred SDK tools." - ) - web_tools = [tool for tool in tools if isinstance(tool, WebSearchTool)] - if len(web_tools) > 1: - raise UserError("CodexProvider supports one WebSearchTool per request.") - web_request = None - if web_tools: - web = web_tools[0] - if sdk_sandbox: - raise UserError("Expose web search through SDK sandbox tools with CodexProvider.") - if web.image_settings is not None: - raise UserError("CodexProvider does not support web search image settings.") - location = dict(web.user_location) if web.user_location is not None else None - if location is not None and location.pop("type", "approximate") != "approximate": - raise UserError("CodexProvider supports approximate web search locations.") - web_request = { - "external_web_access": web.external_web_access, - "search_context_size": web.search_context_size, - "allowed_domains": web.filters.allowed_domains if web.filters else None, - "user_location": location, - "search_content_types": web.search_content_types, - } + deferred_namespaces, web_request = _request_tool_settings(tools, dynamic_tools, sdk_sandbox) settings = { "model": self._name, "reasoning_effort": effort, diff --git a/src/agents/models/interface.py b/src/agents/models/interface.py index 7778fe9e5c..130989e055 100644 --- a/src/agents/models/interface.py +++ b/src/agents/models/interface.py @@ -13,6 +13,7 @@ from ..tool import Tool if TYPE_CHECKING: + from ..model_preflight import ModelPreflight, ModelRequest from ..model_settings import ModelSettings from ..retry import ModelRetryAdvice, ModelRetryAdviceRequest @@ -44,6 +45,28 @@ class Model(abc.ABC): call ID for correlation. """ + def preflight(self, request: ModelRequest) -> ModelPreflight: + """Check known request constraints without sampling, discovery, or network access. + + Third-party adapters may override this method. Unknown compatibility is not + an endorsement. SDK tool ownership describes dispatch, not executor privileges. + """ + from ..model_preflight import ModelPreflight, tool_ownership + + errors: tuple[str, ...] = () + if request.tool_execution and request.tool_execution.require_native_approval_recovery: + errors = ("This adapter cannot guarantee native approval recovery.",) + if request.tool_execution and request.tool_execution.workspace_execution == "sdk": + errors += ("This adapter has not verified SDK-only workspace execution.",) + return ModelPreflight( + adapter=f"{type(self).__module__}.{type(self).__qualname__}", + static_validation="failed" if errors else "unknown", + model_name=getattr(self, "model", None), + tools=tool_ownership(request.tools), + errors=errors, + unchecked=("This adapter does not supply static request validation.",), + ) + def get_default_model_settings(self) -> ModelSettings | None: """Return defaults for this model, or None to retain the agent's implicit defaults. diff --git a/src/agents/models/openai_chatcompletions.py b/src/agents/models/openai_chatcompletions.py index e32377616f..21e35acfb6 100644 --- a/src/agents/models/openai_chatcompletions.py +++ b/src/agents/models/openai_chatcompletions.py @@ -26,6 +26,13 @@ from ..handoffs import Handoff from ..items import ModelResponse, TResponseInputItem, TResponseStreamEvent from ..logger import log_model_action_debug, logger +from ..model_preflight import ( + ModelPreflight, + ModelRequest, + static_input_copy, + tool_ownership, + validate_python_tool_execution, +) from ..retry import ModelRetryAdvice, ModelRetryAdviceRequest from ..tool import Tool from ..tracing._model import chat_model_span @@ -38,6 +45,7 @@ from ..util._error_tracing import model_span_errors from ..util._json import _to_dump_compatible from ._openai_retry import create_with_retry_observation, get_openai_retry_advice +from ._openai_shared import merge_openai_extra_args from ._retry_runtime import should_disable_provider_managed_retries from ._trace import model_config_for_trace, populate_generation_span, record_generation_tools from .chatcmpl_converter import Converter @@ -84,6 +92,87 @@ def _supports_default_prompt_cache_key(self) -> bool: def _tools_require_non_reasoning_mode(self, has_tools: bool) -> bool: return has_tools and self.model in {"gpt-6-sol", "gpt-6-luna"} + def preflight(self, request: ModelRequest) -> ModelPreflight: + """Check the Chat adapter's local conversion without contacting its endpoint.""" + errors: tuple[str, ...] = () + has_replay_callback = self.should_replay_reasoning_content is not None + static_input = ( + static_input_copy(request.input) + if self._strict_feature_validation or not has_replay_callback + else None + ) + unchecked = ["Catalog, files, replay callbacks, and host policy remain unchecked."] + if request.model_settings.extra_args: + unchecked.append("Provider acceptance of extra_args remains unchecked.") + try: + validate_python_tool_execution(request) + if self._strict_feature_validation: + self._handle_unsupported_server_managed_conversation_state( + previous_response_id=request.previous_response_id, + conversation_id=request.conversation_id, + ) + self._handle_unsupported_prompt(request.prompt) + self._handle_unsupported_reasoning_settings(request.model_settings) + elif ( + request.prompt is not None + or request.previous_response_id is not None + or request.conversation_id is not None + ): + unchecked.append( + "Chat Completions does not support Responses state or reusable prompt IDs. " + "Legacy mode ignores them." + ) + if static_input is not None: + self._validate_official_openai_input_content_types(static_input) + Converter.items_to_messages( + static_input, + model=self.model, + base_url=str(self._client.base_url), + # Replay only adds reasoning text. Check the rest of the conversion + # without invoking the caller's predicate or claiming its result. + should_replay_reasoning_content=(lambda _: False) + if has_replay_callback + else None, + strict_feature_validation=self._strict_feature_validation, + warn_on_lossy_tool_output=False, + ) + tool_choice = Converter.convert_tool_choice(request.model_settings.tool_choice) + converted_tools = [Converter.tool_to_openai(tool) for tool in request.tools] + converted_tools.extend( + Converter.convert_handoff_tool(handoff) for handoff in request.handoffs + ) + if request.model_settings.extra_args: + # Messages and headers are always supplied. ModelRequest does not carry + # an output schema or stream mode, and client defaults are deferred. + self._chat_completion_kwargs( + request.model_settings, + converted_messages=[], + converted_tools=converted_tools, + tool_choice=tool_choice, + response_format=omit, + store=request.model_settings.store, + stream_options=None, + stream=False, + extra_headers={}, + error_type=UserError, + ) + except UserError as error: + errors = (str(error),) + return ModelPreflight( + adapter=f"{type(self).__module__}.{type(self).__qualname__}", + static_validation="failed" + if errors + else "passed" + if static_input is not None + and not has_replay_callback + and not request.model_settings.extra_args + else "unknown", + model_name=self.model, + tools=tool_ownership(request.tools), + errors=errors, + unchecked=tuple(unchecked), + ) + def _get_request_settings( self, settings: ModelSettings, @@ -671,13 +760,6 @@ async def _fetch_response( converted_tools = _to_dump_compatible(converted_tools) record_generation_tools(span, tracing, converted_tools) - tools_param = converted_tools if converted_tools else omit - # Chat Completions rejects parallel_tool_calls unless tools are present, so derive it - # from the converted list, which also covers handoff-only turns. - parallel_tool_calls: bool | Omit = ( - self._non_null_or_omit(model_settings.parallel_tool_calls) if converted_tools else omit - ) - if _debug.DONT_LOG_MODEL_DATA: logger.debug("Calling LLM") else: @@ -700,6 +782,79 @@ async def _fetch_response( response_format, ) + store = ChatCmplHelpers.get_store_param(self._get_client(), model_settings) + + stream_options = ChatCmplHelpers.get_stream_options_param( + self._get_client(), model_settings, stream=stream + ) + + create_kwargs, parallel_tool_calls = self._chat_completion_kwargs( + model_settings, + converted_messages=converted_messages, + converted_tools=converted_tools, + tool_choice=tool_choice, + response_format=response_format, + store=store, + stream_options=stream_options, + stream=stream, + extra_headers=self._merge_headers(model_settings), + ) + + client = self._get_client() + ret = await create_with_retry_observation(client, client.chat.completions, create_kwargs) + + if isinstance(ret, ChatCompletion): + return ret + + responses_tool_choice = OpenAIResponsesConverter.convert_tool_choice( + model_settings.tool_choice + ) + if responses_tool_choice is None or responses_tool_choice is omit: + # For Responses API data compatibility with Chat Completions patterns, + # we need to set "none" if tool_choice is absent. + # Without this fix, you'll get the following error: + # pydantic_core._pydantic_core.ValidationError: 4 validation errors for Response + # tool_choice.literal['none','auto','required'] + # Input should be 'none', 'auto' or 'required' + # see also: https://github.com/openai/openai-agents-python/issues/980 + responses_tool_choice = "auto" + + response = Response( + id=FAKE_RESPONSES_ID, + created_at=time.time(), + model=self.model, + object="response", + output=[], + tool_choice=responses_tool_choice, # type: ignore[arg-type] + top_p=model_settings.top_p, + temperature=model_settings.temperature, + tools=[], + parallel_tool_calls=parallel_tool_calls or False, + reasoning=model_settings.reasoning, + ) + return response, ret + + def _chat_completion_kwargs( + self, + model_settings: ModelSettings, + *, + converted_messages: list[Any], + converted_tools: list[Any], + tool_choice: Any, + response_format: Any, + store: bool | None, + stream_options: dict[str, bool] | None, + stream: bool, + extra_headers: dict[str, Any], + error_type: type[Exception] = TypeError, + ) -> tuple[dict[str, Any], bool | Omit]: + tools_param = converted_tools if converted_tools else omit + # Chat Completions rejects parallel_tool_calls unless tools are present, so derive it + # from the converted list, which also covers handoff-only turns. + parallel_tool_calls: bool | Omit = ( + self._non_null_or_omit(model_settings.parallel_tool_calls) if converted_tools else omit + ) + reasoning_effort = ( model_settings.reasoning.effort if model_settings.reasoning is not None else None ) @@ -711,12 +866,6 @@ async def _fetch_response( and "reasoning_effort" not in (model_settings.extra_args or {}) ): reasoning_effort = "none" - store = ChatCmplHelpers.get_store_param(self._get_client(), model_settings) - - stream_options = ChatCmplHelpers.get_stream_options_param( - self._get_client(), model_settings, stream=stream - ) - stream_param: Literal[True] | Omit = True if stream else omit create_kwargs: dict[str, Any] = { @@ -739,7 +888,7 @@ async def _fetch_response( "top_logprobs": self._non_null_or_omit(model_settings.top_logprobs), "prompt_cache_retention": self._non_null_or_omit(model_settings.prompt_cache_retention), "prompt_cache_options": self._non_null_or_omit(model_settings.prompt_cache_options), - "extra_headers": self._merge_headers(model_settings), + "extra_headers": extra_headers, "extra_query": model_settings.extra_query, "extra_body": model_settings.extra_body, "metadata": self._non_null_or_omit(model_settings.metadata), @@ -753,56 +902,14 @@ async def _fetch_response( model_settings.extra_args or {} ): create_kwargs["logprobs"] = True - duplicate_extra_arg_keys = sorted( - key - for key in model_settings.extra_args or {} - if key in create_kwargs and not isinstance(create_kwargs[key], Omit) + merge_openai_extra_args( + create_kwargs, + model_settings.extra_args or {}, + method="chat.completions.create", + omitted_types=Omit, + error_type=error_type, ) - if duplicate_extra_arg_keys: - if len(duplicate_extra_arg_keys) == 1: - key = duplicate_extra_arg_keys[0] - raise TypeError( - f"chat.completions.create() got multiple values for keyword argument '{key}'" - ) - keys = ", ".join(repr(key) for key in duplicate_extra_arg_keys) - raise TypeError( - f"chat.completions.create() got multiple values for keyword arguments {keys}" - ) - create_kwargs.update(model_settings.extra_args or {}) - - client = self._get_client() - ret = await create_with_retry_observation(client, client.chat.completions, create_kwargs) - - if isinstance(ret, ChatCompletion): - return ret - - responses_tool_choice = OpenAIResponsesConverter.convert_tool_choice( - model_settings.tool_choice - ) - if responses_tool_choice is None or responses_tool_choice is omit: - # For Responses API data compatibility with Chat Completions patterns, - # we need to set "none" if tool_choice is absent. - # Without this fix, you'll get the following error: - # pydantic_core._pydantic_core.ValidationError: 4 validation errors for Response - # tool_choice.literal['none','auto','required'] - # Input should be 'none', 'auto' or 'required' - # see also: https://github.com/openai/openai-agents-python/issues/980 - responses_tool_choice = "auto" - - response = Response( - id=FAKE_RESPONSES_ID, - created_at=time.time(), - model=self.model, - object="response", - output=[], - tool_choice=responses_tool_choice, # type: ignore[arg-type] - top_p=model_settings.top_p, - temperature=model_settings.temperature, - tools=[], - parallel_tool_calls=parallel_tool_calls or False, - reasoning=model_settings.reasoning, - ) - return response, ret + return create_kwargs, parallel_tool_calls def _get_client(self) -> AsyncOpenAI: if self._client is None: diff --git a/src/agents/models/openai_responses.py b/src/agents/models/openai_responses.py index 7937b497c1..9ba7a46c46 100644 --- a/src/agents/models/openai_responses.py +++ b/src/agents/models/openai_responses.py @@ -53,6 +53,13 @@ from ..handoffs import Handoff from ..items import ItemHelpers, ModelResponse, TResponseInputItem from ..logger import log_model_action_debug, log_model_action_error, logger +from ..model_preflight import ( + ModelPreflight, + ModelRequest, + static_input_copy, + tool_ownership, + validate_python_tool_execution, +) from ..model_settings import MCPToolChoice from ..retry import ModelRetryAdvice, ModelRetryAdviceRequest, ModelRetryNormalizedError from ..tool import ( @@ -107,7 +114,7 @@ get_openai_retry_advice, record_openai_error_retries, ) -from ._openai_shared import clean_responses_input_item +from ._openai_shared import clean_responses_input_item, merge_openai_extra_args from ._openai_websocket import ( get_openai_websocket_logger, merge_openai_client_websocket_headers, @@ -608,6 +615,77 @@ def _supports_default_prompt_cache_key(self) -> bool: def _prompt_owns_model(self, prompt: ResponsePromptParam | None) -> bool: return prompt is not None and not self._model_is_explicit + def preflight(self, request: ModelRequest) -> ModelPreflight: + """Run local request converters without credentials, catalogs, or file uploads.""" + errors: tuple[str, ...] = () + static_input = static_input_copy(request.input) + static_tools = not any(isinstance(tool, ComputerTool) for tool in request.tools) + unchecked = ["Catalog, files, computer metadata, and host policy remain unchecked."] + if any(isinstance(tool, WebSearchTool) for tool in request.tools): + static_tools = False + unchecked.append( + "Preflight skips web search settings to avoid running caller serializers." + ) + if request.model_settings.extra_args: + unchecked.append("Provider acceptance of extra_args remains unchecked.") + try: + validate_python_tool_execution(request) + effective_model = None if self._prompt_owns_model(request.prompt) else self.model + computer_model = Converter.resolve_computer_tool_model( + request_model=effective_model, + tools=request.tools, + ) + converted_tools = _PreflightConverter.convert_tools( + request.tools, + request.handoffs, + model=computer_model, + allow_opaque_tool_search_surface=request.prompt is not None, + tool_choice=request.model_settings.tool_choice, + ) + if request.model_settings.extra_args: + # Input, include and headers are always supplied. ModelRequest omits + # instructions, output schema and stream mode. Websockets always stream. + kwargs = self._response_create_kwargs( + request.model_settings, + list_input=[], + effective_request_model=effective_model, + converted_tools_payload=converted_tools.tools, + tool_choice=converted_tools.tool_choice, + response_format=omit, + include=[], + system_instructions=None, + previous_response_id=request.previous_response_id, + conversation_id=request.conversation_id, + stream=isinstance(self, OpenAIResponsesWSModel), + prompt=request.prompt, + extra_headers={}, + ) + merge_openai_extra_args( + kwargs, + request.model_settings.extra_args, + method="responses.create", + omitted_types=(Omit, NotGiven), + error_type=UserError, + ) + if static_input is not None: + self._remove_openai_responses_api_incompatible_fields( + ItemHelpers.input_to_new_input_list(static_input) + ) + except UserError as error: + errors = (str(error),) + return ModelPreflight( + adapter=f"{type(self).__module__}.{type(self).__qualname__}", + static_validation="failed" + if errors + else "passed" + if static_input is not None and static_tools and not request.model_settings.extra_args + else "unknown", + model_name=self.model, + tools=tool_ownership(request.tools), + errors=errors, + unchecked=tuple(unchecked), + ) + def _get_request_settings( self, settings: ModelSettings, @@ -1082,25 +1160,7 @@ def _build_response_create_kwargs( ) tool_choice = converted_tools.tool_choice converted_tools_payload = _materialize_responses_tool_params(converted_tools.tools) - parallel_tool_calls: bool | Omit = ( - self._non_null_or_omit(model_settings.parallel_tool_calls) - if prompt is not None or converted_tools_payload - else omit - ) response_format = Converter.get_response_format(output_schema) - model_param: str | ChatModel | Omit = ( - effective_request_model if effective_request_model is not None else omit - ) - should_omit_tools = prompt is not None and len(converted_tools_payload) == 0 - # In prompt-managed tool flows without local tools payload, omit only named tool choices - # that must match an explicit tool list. Keep control literals like "none"/"required". - should_omit_tool_choice = should_omit_tools and isinstance(tool_choice, dict) - tools_param: list[ResponsesToolParam] | Omit = ( - converted_tools_payload if not should_omit_tools else omit - ) - tool_choice_param: response_create_params.ToolChoice | Omit = ( - tool_choice if not should_omit_tool_choice else omit - ) include_set: set[ResponseIncludable] = set(converted_tools.includes) if model_settings.response_include is not None: @@ -1109,6 +1169,22 @@ def _build_response_create_kwargs( include_set.add("message.output_text.logprobs") include: list[ResponseIncludable] = list(include_set) + create_kwargs = self._response_create_kwargs( + model_settings, + list_input=list_input, + effective_request_model=effective_request_model, + converted_tools_payload=converted_tools_payload, + tool_choice=tool_choice, + response_format=response_format, + include=include, + system_instructions=system_instructions, + previous_response_id=previous_response_id, + conversation_id=conversation_id, + stream=stream, + prompt=prompt, + extra_headers=self._merge_headers(model_settings), + ) + if _debug.DONT_LOG_MODEL_DATA or current_redactor() is not None: logger.debug("Calling LLM") else: @@ -1129,7 +1205,7 @@ def _build_response_create_kwargs( input_json, tools_json, stream, - tool_choice_param, + create_kwargs["tool_choice"], response_format, previous_response_id, conversation_id, @@ -1138,9 +1214,51 @@ def _build_response_create_kwargs( extra_args = dict(model_settings.extra_args or {}) if model_settings.top_logprobs is not None: extra_args["top_logprobs"] = model_settings.top_logprobs + merge_openai_extra_args( + create_kwargs, extra_args, method="responses.create", omitted_types=(Omit, NotGiven) + ) + return create_kwargs + + def _response_create_kwargs( + self, + model_settings: ModelSettings, + *, + list_input: list[Any], + effective_request_model: str | None, + converted_tools_payload: list[ResponsesToolParam], + tool_choice: response_create_params.ToolChoice | Omit, + response_format: ResponseTextConfigParam | Omit, + include: list[ResponseIncludable], + system_instructions: str | None, + previous_response_id: str | None, + conversation_id: str | None, + stream: bool, + prompt: ResponsePromptParam | None, + extra_headers: dict[str, Any], + ) -> dict[str, Any]: + parallel_tool_calls: bool | Omit = ( + self._non_null_or_omit(model_settings.parallel_tool_calls) + if prompt is not None or converted_tools_payload + else omit + ) + model_param: str | ChatModel | Omit = ( + effective_request_model if effective_request_model is not None else omit + ) + should_omit_tools = prompt is not None and len(converted_tools_payload) == 0 + # In prompt-managed tool flows without local tools payload, omit only named tool choices + # that must match an explicit tool list. Keep control literals like "none"/"required". + should_omit_tool_choice = should_omit_tools and isinstance(tool_choice, dict) + tools_param: list[ResponsesToolParam] | Omit = ( + converted_tools_payload if not should_omit_tools else omit + ) + tool_choice_param: response_create_params.ToolChoice | Omit = ( + tool_choice if not should_omit_tool_choice else omit + ) + if model_settings.verbosity is not None: - if response_format is not omit: - response_format["verbosity"] = model_settings.verbosity # type: ignore [index] + if isinstance(response_format, dict): + response_format = response_format.copy() + response_format["verbosity"] = model_settings.verbosity else: response_format = {"verbosity": model_settings.verbosity} @@ -1162,7 +1280,7 @@ def _build_response_create_kwargs( "tool_choice": tool_choice_param, "parallel_tool_calls": parallel_tool_calls, "stream": cast(Any, stream_param), - "extra_headers": self._merge_headers(model_settings), + "extra_headers": extra_headers, "extra_query": model_settings.extra_query, "extra_body": model_settings.extra_body, "text": response_format, @@ -1173,20 +1291,6 @@ def _build_response_create_kwargs( "metadata": self._non_null_or_omit(model_settings.metadata), "context_management": self._non_null_or_omit(model_settings.context_management), } - duplicate_extra_arg_keys = sorted( - k - for k in extra_args - if k in create_kwargs and not _is_openai_omitted_value(create_kwargs[k]) - ) - if duplicate_extra_arg_keys: - if len(duplicate_extra_arg_keys) == 1: - key = duplicate_extra_arg_keys[0] - raise TypeError( - f"responses.create() got multiple values for keyword argument '{key}'" - ) - keys = ", ".join(repr(key) for key in duplicate_extra_arg_keys) - raise TypeError(f"responses.create() got multiple values for keyword arguments {keys}") - create_kwargs.update(extra_args) return create_kwargs def _remove_openai_responses_api_incompatible_fields(self, list_input: list[Any]) -> list[Any]: @@ -2472,3 +2576,20 @@ def _convert_handoff_tool(cls, handoff: Handoff) -> ResponsesToolParam: type="function", description=handoff.tool_description, ) + + +class _PreflightConverter(Converter): + @classmethod + def _convert_tool( + cls, tool: Tool, *, use_preview_computer_tool: bool = False + ) -> tuple[ResponsesToolParam, ResponseIncludable | None]: + if isinstance(tool, WebSearchTool): + # Choice resolution needs the tool type. Serializing filters can run caller code. + return {"type": "web_search"}, None + return super()._convert_tool(tool, use_preview_computer_tool=use_preview_computer_tool) + + @classmethod + def _convert_preview_computer_tool(cls, tool: ComputerTool[Any]) -> ResponsesToolParam: + # Only the tool type and presence are needed for static checks. Dispatch + # uses Converter to read the environment and dimensions from the computer. + return _require_responses_tool_param({"type": "computer_use_preview"}) diff --git a/src/agents/run_config.py b/src/agents/run_config.py index 1085c60f60..02da2bf6f6 100644 --- a/src/agents/run_config.py +++ b/src/agents/run_config.py @@ -296,7 +296,30 @@ async def prepare(ctx, declaration): With input or output preparation, the Codex provider disables native workspace tools. """ + workspace_execution: Literal["provider", "sdk"] = field(default="provider", kw_only=True) + """Choose who executes workspace actions. Codex's SDK profile supplies no native + execution environments, even without preparation callbacks. Native workspace tools + can still appear in the model's tool list, but cannot execute workspace actions. + This profile does not prevent native child model requests or make shared child + budgets enforceable. SDK executors retain their own privileges. Other adapters + must explicitly verify their SDK workspace profile. + """ + + require_native_approval_recovery: bool = field(default=False, kw_only=True) + """Require recovery support when native policy asks to approve a command or edit. + + This requires Codex's provider-owned workspace and a resumable session. + Leave tool_choice unset or use "auto". Requiring an SDK tool call disables + native approval recovery. Recovery does not cover unsupported native tools, + network approvals, or edits to the reviewed arguments. Host policy still + decides which operations need approval. + """ + def __post_init__(self) -> None: + if self.workspace_execution not in ("provider", "sdk"): + raise ValueError("tool_execution.workspace_execution must be 'provider' or 'sdk'") + if not isinstance(self.require_native_approval_recovery, bool): + raise ValueError("tool_execution.require_native_approval_recovery must be a bool") if self.max_function_tool_concurrency is not None and ( self.max_function_tool_concurrency < 1 ): diff --git a/src/agents/run_internal/run_loop.py b/src/agents/run_internal/run_loop.py index b22e4d857a..bff87ac53c 100644 --- a/src/agents/run_internal/run_loop.py +++ b/src/agents/run_internal/run_loop.py @@ -73,6 +73,7 @@ logger, ) from ..memory import Session +from ..model_preflight import ModelRequest from ..models._response_terminal import ( response_error_event_failure_error, response_terminal_failure_error, @@ -328,6 +329,14 @@ _STREAM_EVENT_ITEM_OCCURRENCE_KEY = "_agents_stream_event_item_occurrence_key" +def _requires_request_preflight(run_config: RunConfig) -> bool: + settings = run_config.tool_execution + return run_config.model_selector is not None or ( + settings is not None + and (settings.workspace_execution == "sdk" or settings.require_native_approval_recovery) + ) + + def _publish_stream_items( items: list[RunItem], result: RunResultStreaming, emitted: set[str] | None = None ) -> None: @@ -2609,6 +2618,28 @@ async def raise_if_input_guardrail_tripwire_known() -> None: redact_model_input(filtered, prompt_config) if isinstance(filtered.input, list): filtered.input = deduplicate_input_items_preferring_latest(filtered.input) + if _requires_request_preflight(run_config): + model.preflight( + ModelRequest( + input=filtered.input, + model_settings=model_settings, + tools=model_tools, + handoffs=handoffs, + previous_response_id=( + server_conversation_tracker.previous_response_id + if server_conversation_tracker is not None + else None + ), + conversation_id=( + server_conversation_tracker.conversation_id + if server_conversation_tracker is not None + else None + ), + prompt=prompt_config, + tool_execution=run_config.tool_execution, + resumable=isinstance(session, ResumableRun), + ) + ).raise_for_errors() if server_conversation_tracker is not None: server_conversation_tracker.validate_pending_input_filter(filtered.input) @@ -3171,6 +3202,29 @@ async def get_new_response( model_settings = maybe_reset_tool_choice(public_agent, tool_use_tracker, model_settings) validate_prepared_choice(omitted, model_settings.tool_choice, bool(all_tools or handoffs)) + if _requires_request_preflight(run_config): + model.preflight( + ModelRequest( + input=filtered.input, + model_settings=model_settings, + tools=all_tools, + handoffs=handoffs, + previous_response_id=( + server_conversation_tracker.previous_response_id + if server_conversation_tracker is not None + else None + ), + conversation_id=( + server_conversation_tracker.conversation_id + if server_conversation_tracker is not None + else None + ), + prompt=prompt_config, + tool_execution=run_config.tool_execution, + resumable=isinstance(session, ResumableRun), + ) + ).raise_for_errors() + if server_conversation_tracker is not None: server_conversation_tracker.validate_pending_input_filter(filtered.input) server_conversation_tracker.mark_input_as_sent(filtered.input) diff --git a/tests/memory/test_completed_conversation_fork_recipe.py b/tests/memory/test_completed_conversation_fork_recipe.py index 4a762e6872..200ec9653b 100644 --- a/tests/memory/test_completed_conversation_fork_recipe.py +++ b/tests/memory/test_completed_conversation_fork_recipe.py @@ -8,15 +8,71 @@ import pytest -from agents import Agent, RunConfig, Runner, SQLiteSession +from agents import Agent, ModelRequest, RunConfig, Runner, SQLiteSession from agents.decorators import tool from agents.items import TResponseInputItem +from agents.models.codex import CodexProvider from agents.testing import ScriptedModel, assistant_message, function_call from examples.memory.completed_conversation_fork import completed_text_prefix, fork_completed +from tests.models.test_codex_provider import FakeThread, threads as threads CONFIG = RunConfig(tracing_disabled=True) +@pytest.mark.asyncio +@pytest.mark.parametrize("streamed", [False, True]) +async def test_completed_codex_fork_preserves_final_phase_and_diverges(tmp_path, threads, streamed): + queue, _ = threads + original = FakeThread(text="Original") + parent_turn = FakeThread(text="Parent branch") + child_turn = FakeThread(text="Child branch") + queue.extend([original, parent_turn, child_turn]) + provider = CodexProvider(cwd=tmp_path) + config = RunConfig(model_provider=provider, tracing_disabled=True) + agent = Agent(name="Codex assistant") + parent = SQLiteSession("parent", tmp_path / "parent.db") + child = None + + async def run(prompt, session): + if streamed: + result = Runner.run_streamed(agent, prompt, session=session, run_config=config) + async for _ in result.stream_events(): + pass + return result + return await Runner.run(agent, prompt, session=session, run_config=config) + + def validate_destination(items): + provider.get_model(None).preflight( + ModelRequest(input=items + [{"role": "user", "content": "Continue"}]) + ).raise_for_errors() + + try: + await run("Begin", parent) + snapshot = await parent.get_items() + assert snapshot[-1]["phase"] == "final_answer" + child = await fork_completed( + parent, + tmp_path / "child.db", + authorize=lambda session_id, items: session_id == "parent" and items == snapshot, + tools=set(), + validate_destination=validate_destination, + ) + assert await child.get_items() == snapshot + assert (await run("Continue parent", parent)).final_output == "Parent branch" + assert (await run("Continue child", child)).final_output == "Child branch" + assert parent_turn.history[-1]["phase"] == "final_answer" + assert child_turn.history[-1]["phase"] == "final_answer" + assert (await parent.get_items())[-1]["content"][0]["text"] == "Parent branch" + assert (await child.get_items())[-1]["content"][0]["text"] == "Child branch" + assert all(thread.closed for thread in (original, parent_turn, child_turn)) + assert not queue + finally: + parent.close() + if child is not None: + child.close() + await provider.aclose() + + @pytest.mark.asyncio async def test_completed_fork_diverges_without_repeating_the_write(tmp_path: Path) -> None: writes: list[str] = [] diff --git a/tests/models/test_automatic_preflight.py b/tests/models/test_automatic_preflight.py new file mode 100644 index 0000000000..516dcf8fc6 --- /dev/null +++ b/tests/models/test_automatic_preflight.py @@ -0,0 +1,128 @@ +"""Keep default adapter validation ordering while enforcing opted-in request policies.""" + +from unittest.mock import AsyncMock + +import pytest +from openai import AsyncOpenAI + +from agents import Agent, RunConfig, RunHooks, Runner, ToolExecutionConfig, UserError +from agents.models.openai_chatcompletions import OpenAIChatCompletionsModel +from agents.models.openai_provider import OpenAIProvider + + +@pytest.mark.asyncio +@pytest.mark.allow_call_model_methods +@pytest.mark.parametrize("streamed", [False, True]) +@pytest.mark.parametrize("legacy_settings", ["none", "concurrency", "tool-input-hooks"]) +async def test_default_chat_validation_preserves_adapter_error_and_llm_hook_order( + streamed, legacy_settings, monkeypatch +): + events = [] + config = RunConfig(tracing_disabled=True) + if legacy_settings == "concurrency": + config.tool_execution = ToolExecutionConfig(max_function_tool_concurrency=1) + elif legacy_settings == "tool-input-hooks": + + async def prepare_input(context): + raise AssertionError("This model response has no tool calls.") + + config.tool_execution = ToolExecutionConfig( + sdk_only_tool_hooks=True, + prepare_tool_input=prepare_input, + ) + + class Observer(RunHooks): + async def on_llm_start(self, context, agent, system_prompt, input_items): + events.append("llm_start") + + async with AsyncOpenAI(api_key="synthetic-key", base_url="https://api.openai.com/v1") as client: + sampling = AsyncMock(side_effect=AssertionError("Unexpected sampling")) + monkeypatch.setattr(client.chat.completions, "create", sampling) + model = OpenAIChatCompletionsModel("fixture-chat", client, strict_feature_validation=True) + agent = Agent(name="legacy validation", model=model) + with pytest.raises(UserError, match="OpenAIChatCompletionsModel does not support"): + if streamed: + result = Runner.run_streamed( + agent, + "start", + previous_response_id="existing-response", + hooks=Observer(), + run_config=config, + ) + async for _ in result.stream_events(): + pass + else: + await Runner.run( + agent, + "start", + previous_response_id="existing-response", + hooks=Observer(), + run_config=config, + ) + assert events == ["llm_start"] + sampling.assert_not_called() + + +@pytest.mark.asyncio +@pytest.mark.allow_call_model_methods +@pytest.mark.parametrize("streamed", [False, True]) +@pytest.mark.parametrize("policy", ["selector", "sdk-workspace", "native-recovery"]) +async def test_opted_in_request_validation_runs_before_hooks_and_sampling( + streamed, policy, monkeypatch +): + events = [] + + class Observer(RunHooks): + async def on_llm_start(self, context, agent, system_prompt, input_items): + events.append("llm_start") + + async with AsyncOpenAI(api_key="synthetic-key", base_url="https://api.openai.com/v1") as client: + sampling = AsyncMock(side_effect=AssertionError("Unexpected sampling")) + monkeypatch.setattr(client.chat.completions, "create", sampling) + model = OpenAIChatCompletionsModel("fixture-chat", client, strict_feature_validation=True) + config = RunConfig(tracing_disabled=True) + selections = [] + if policy == "selector": + + def select(turn): + selections.append(turn.model_name) + return "fixture-selected" + + config.model_selector = select + config.model_provider = OpenAIProvider( + openai_client=client, + use_responses=False, + strict_feature_validation=True, + ) + elif policy == "sdk-workspace": + config.tool_execution = ToolExecutionConfig(workspace_execution="sdk") + else: + config.tool_execution = ToolExecutionConfig(require_native_approval_recovery=True) + with pytest.raises(UserError, match="server-managed conversation state|CodexProvider"): + if streamed: + result = Runner.run_streamed( + Agent( + name="policy validation", + model="fixture-chat" if policy == "selector" else model, + ), + "start", + previous_response_id="existing-response", + hooks=Observer(), + run_config=config, + ) + async for _ in result.stream_events(): + pass + else: + await Runner.run( + Agent( + name="policy validation", + model="fixture-chat" if policy == "selector" else model, + ), + "start", + previous_response_id="existing-response", + hooks=Observer(), + run_config=config, + ) + assert events == [] + assert selections == (["fixture-chat"] if policy == "selector" else []) + sampling.assert_not_called() diff --git a/tests/models/test_codex_preflight.py b/tests/models/test_codex_preflight.py new file mode 100644 index 0000000000..925d0111e0 --- /dev/null +++ b/tests/models/test_codex_preflight.py @@ -0,0 +1,324 @@ +from pathlib import Path + +import pytest + +from agents import ( + Agent, + ModelRequest, + ModelSettings, + ResumableSession, + RunConfig, + RunHooks, + Runner, + ToolExecutionConfig, + UserError, + WebSearchTool, + function_tool, +) +from agents.models.codex import CodexProvider +from agents.testing import ScriptedModel +from tests.memory.test_resumable_session import MemoryStore + +from .test_codex_pending_approval import ApprovalThread, raw +from .test_codex_provider import FakeThread, native_pair, threads as threads + + +@pytest.mark.parametrize( + "model_request, message", + [ + ( + ModelRequest( + input=[{"role": "user", "content": [{"type": "input_file", "file_id": "file-pdf"}]}] + ), + "only text", + ), + ( + ModelRequest(input="start", model_settings=ModelSettings(tool_choice="editor")), + "tool_choice", + ), + (ModelRequest(input="start", previous_response_id="response-private"), "state or prompt"), + (ModelRequest(input="start", conversation_id="conversation-private"), "state or prompt"), + ( + ModelRequest( + input="start", + tool_execution=ToolExecutionConfig(require_native_approval_recovery=True), + ), + "ResumableSession", + ), + ], +) +def test_codex_preflight_reports_known_incompatibility_without_native_startup( + tmp_path, model_request, message +): + provider = CodexProvider(cwd=tmp_path) + report = provider.get_model("configured").preflight(model_request) + assert report.adapter == "agents.models.codex._CodexModel" + assert report.static_validation == "failed" + with pytest.raises(UserError, match=message): + report.raise_for_errors() + assert provider._manager is None + assert not list(tmp_path.iterdir()) + + +def test_preflight_does_not_read_or_upload_local_images(tmp_path, monkeypatch): + provider = CodexProvider(cwd=tmp_path) + + def unexpected_read(self): + raise AssertionError("Preflight must not read media files.") + + monkeypatch.setattr(Path, "read_bytes", unexpected_read) + report = provider.get_model(None).preflight( + ModelRequest( + input=[ + { + "role": "user", + "content": [{"type": "input_image", "image_url": str(tmp_path / "image.png")}], + } + ] + ) + ) + assert report.static_validation == "passed" + assert any("readability" in check for check in report.unchecked) + assert provider._manager is None + + +def test_third_party_preflight_reports_unknown_and_actual_adapter(): + model = ScriptedModel([]) + report = model.preflight(ModelRequest(input="start")) + assert report.static_validation == "unknown" + assert report.adapter == f"{type(model).__module__}.{type(model).__qualname__}" + assert report.unchecked + report.raise_for_errors() + + +@pytest.mark.asyncio +@pytest.mark.parametrize("streamed", [False, True]) +async def test_runner_rejects_required_native_recovery_before_startup(tmp_path, threads, streamed): + started = [] + + class Observer(RunHooks): + async def on_llm_start(self, *args): + started.append("request") + + provider = CodexProvider(cwd=tmp_path) + config = RunConfig( + model_provider=provider, + tracing_disabled=True, + tool_execution={"require_native_approval_recovery": True}, + ) + with pytest.raises(UserError, match="ResumableSession"): + if streamed: + run = Runner.run_streamed( + Agent(name="worker"), "start", run_config=config, hooks=Observer() + ) + async for _ in run.stream_events(): + pass + else: + await Runner.run(Agent(name="worker"), "start", run_config=config, hooks=Observer()) + assert provider._manager is None + assert not threads[1] and not started + + +@pytest.mark.asyncio +@pytest.mark.parametrize("streamed", [False, True]) +@pytest.mark.parametrize("require_recovery", [False, True]) +async def test_required_sdk_tool_with_resumable_session( + tmp_path, threads, streamed, require_recovery +): + started = [] + + @function_tool + def lookup() -> str: + started.append("tool") + return "found" + + class Observer(RunHooks): + async def on_llm_start(self, *args): + started.append("request") + + thread = FakeThread(call={"callId": "lookup", "tool": "lookup", "arguments": {}}) + threads[0].append(thread) + provider = CodexProvider(cwd=tmp_path) + execution = ToolExecutionConfig(require_native_approval_recovery=require_recovery) + settings = ModelSettings(tool_choice="required") + agent = Agent( + name="worker", + tools=[lookup], + model_settings=settings, + tool_use_behavior="stop_on_first_tool", + ) + config = RunConfig(model_provider=provider, tool_execution=execution, tracing_disabled=True) + session = await ResumableSession.create(MemoryStore()) + report = provider.get_model(None).preflight( + ModelRequest( + input="start", + tools=[lookup], + model_settings=settings, + tool_execution=execution, + resumable=True, + ) + ) + + async def run(): + if streamed: + result = Runner.run_streamed( + agent, "start", run_config=config, hooks=Observer(), session=session + ) + async for _ in result.stream_events(): + pass + return result + return await Runner.run( + agent, "start", run_config=config, hooks=Observer(), session=session + ) + + if require_recovery: + with pytest.raises(UserError, match="tool_choice='required'"): + await run() + assert report.static_validation == "failed" + assert provider._manager is None and not threads[1] and not started + else: + assert report.static_validation == "passed" + assert (await run()).final_output == "found" + assert started == ["request", "tool"] + assert thread.recover_approvals is False + + +@pytest.mark.asyncio +@pytest.mark.parametrize("streamed", [False, True]) +async def test_sdk_workspace_owns_write_without_preparation_hooks(tmp_path, threads, streamed): + queue, _ = threads + effects = [] + + @function_tool + def edit_file() -> str: + (tmp_path / "written.txt").write_text("SDK-owned edit") + effects.append("sdk") + return "edited" + + first = FakeThread(call={"callId": "write", "tool": "edit_file", "arguments": {}}) + second = FakeThread(text="done") + queue.extend([first, second]) + provider = CodexProvider(cwd=tmp_path) + execution = ToolExecutionConfig(workspace_execution="sdk") + model = provider.get_model("configured") + report = model.preflight( + ModelRequest(input="start", tools=[edit_file], tool_execution=execution) + ) + assert report.static_validation == "passed" + assert [(tool.name, tool.executor) for tool in report.tools] == [("edit_file", "sdk")] + assert any("no usable execution environment" in check for check in report.unchecked) + assert any("Native delegation may sample" in check for check in report.unchecked) + native_report = model.preflight(ModelRequest(input="start", tools=[edit_file])) + assert [(tool.name, tool.executor) for tool in native_report.tools] == [ + ("edit_file", "sdk"), + ("Codex workspace tools", "native"), + ] + config = RunConfig(model_provider=provider, tool_execution=execution, tracing_disabled=True) + agent = Agent(name="worker", model="configured", tools=[edit_file]) + if streamed: + result = Runner.run_streamed(agent, "edit", run_config=config) + async for _ in result.stream_events(): + pass + else: + result = await Runner.run(agent, "edit", run_config=config) + assert result.final_output == "done" + assert effects == ["sdk"] + assert (tmp_path / "written.txt").read_text() == "SDK-owned edit" + assert first.settings["sdk_sandbox"] is True and second.settings["sdk_sandbox"] is True + assert first.closed and second.closed + + +@pytest.mark.asyncio +async def test_native_patch_recovery_accepts_resumable_session_and_policy(tmp_path, threads): + call, _ = native_pair("custom_tool_call", "pending", "apply_patch") + pending = ApprovalThread( + events=[ + raw(call), + { + "type": "apply_patch_approval_request", + "call_id": "pending", + "turn_id": "turn_1", + "changes": {}, + }, + {"type": "raw_response_completed"}, + ] + ) + threads[0].append(pending) + provider = CodexProvider(cwd=tmp_path) + execution = ToolExecutionConfig(require_native_approval_recovery=True) + report = provider.get_model(None).preflight( + ModelRequest( + input="edit", + tool_execution=execution, + resumable=True, + ) + ) + assert report.static_validation == "passed" + session = await ResumableSession.create(MemoryStore()) + result = await Runner.run( + Agent(name="worker"), + "edit", + session=session, + run_config=RunConfig( + model_provider=provider, + tool_execution=execution, + tracing_disabled=True, + ), + ) + assert len(result.interruptions) == 1 + assert result.interruptions[0].raw_item.name == "apply_patch" + assert pending.closed + + +@pytest.mark.parametrize( + "overrides", + [ + ['mcp_servers.native.command="worker"'], + ['mcp_servers.native.command="worker"', "mcp_servers.native.enabled=false"], + ], +) +def test_preflight_defers_effective_native_config_to_existing_runtime(tmp_path, overrides): + provider = CodexProvider(cwd=tmp_path, config_overrides=overrides) + report = provider.get_model(None).preflight( + ModelRequest( + input="start", + tool_execution=ToolExecutionConfig(workspace_execution="sdk"), + ) + ) + assert report.static_validation == "passed" + assert any("host policy" in check for check in report.unchecked) + assert provider._manager is None + + +def test_sdk_workspace_rejects_competing_native_web_tool(tmp_path): + report = ( + CodexProvider(cwd=tmp_path) + .get_model(None) + .preflight( + ModelRequest( + input="start", + tools=[WebSearchTool()], + tool_execution=ToolExecutionConfig(workspace_execution="sdk"), + ) + ) + ) + with pytest.raises(UserError, match="SDK sandbox tools"): + report.raise_for_errors() + + +def test_native_recovery_cannot_be_required_with_sdk_workspace(tmp_path): + report = ( + CodexProvider(cwd=tmp_path) + .get_model(None) + .preflight( + ModelRequest( + input="start", + resumable=True, + tool_execution=ToolExecutionConfig( + workspace_execution="sdk", require_native_approval_recovery=True + ), + ) + ) + ) + with pytest.raises(UserError, match="provider-owned"): + report.raise_for_errors() diff --git a/tests/models/test_python_preflight.py b/tests/models/test_python_preflight.py new file mode 100644 index 0000000000..8188d427bd --- /dev/null +++ b/tests/models/test_python_preflight.py @@ -0,0 +1,674 @@ +import json +from unittest.mock import AsyncMock + +import httpx2 +import pytest +from openai import AsyncOpenAI, BadRequestError +from openai.types.responses.web_search_tool import Filters +from openai.types.shared import Reasoning +from pydantic import field_serializer + +from agents import ( + Agent, + ComputerTool, + HostedMCPTool, + ModelRequest, + ModelSettings, + ModelTracing, + RunConfig, + RunHooks, + Runner, + ToolExecutionConfig, + UserError, + WebSearchTool, + function_tool, +) +from agents.models.openai_chatcompletions import OpenAIChatCompletionsModel +from agents.models.openai_responses import OpenAIResponsesModel, OpenAIResponsesWSModel +from tests.test_computer_tool_lifecycle import FakeComputer + + +@pytest.fixture(params=[OpenAIResponsesModel, OpenAIChatCompletionsModel]) +def model(request): + # A synthetic key and uncalled client keep the test at the adapter boundary. + client = AsyncOpenAI(api_key="synthetic-test-key", base_url="https://api.openai.com/v1") + client.responses.create = AsyncMock(side_effect=AssertionError("Unexpected sampling")) + client.chat.completions.create = AsyncMock(side_effect=AssertionError("Unexpected sampling")) + return request.param("fixture-chat", client) + + +@function_tool +def edit_file() -> str: + """Apply an application-owned edit.""" + raise AssertionError("Preflight must not execute tools") + + +def test_python_adapters_accept_named_sdk_tool_and_file_without_upload(model): + report = model.preflight( + ModelRequest( + input=[ + { + "role": "user", + "content": [{"type": "input_file", "file_id": "file-existing-pdf"}], + } + ], + tools=[edit_file], + model_settings=ModelSettings(tool_choice="edit_file"), + tool_execution=ToolExecutionConfig(workspace_execution="sdk"), + ) + ) + assert report.static_validation == "passed" + assert report.model_name == "fixture-chat" + assert report.adapter == f"{type(model).__module__}.{type(model).__qualname__}" + assert [(item.name, item.executor) for item in report.tools] == [("edit_file", "sdk")] + assert any("files" in check for check in report.unchecked) + model._client.responses.create.assert_not_called() + model._client.chat.completions.create.assert_not_called() + + +@pytest.mark.parametrize( + "tool", + [ + WebSearchTool(), + HostedMCPTool({"server_label": "external", "server_url": "https://service.example/mcp"}), + ], +) +def test_sdk_profile_refuses_hosted_or_external_workspace_routes(model, tool): + report = model.preflight( + ModelRequest( + input="start", + tools=[tool], + tool_execution=ToolExecutionConfig(workspace_execution="sdk"), + ) + ) + assert report.static_validation == "failed" + with pytest.raises(UserError, match="SDK callback"): + report.raise_for_errors() + assert report.tools[0].executor in ("provider", "external") + model._client.responses.create.assert_not_called() + model._client.chat.completions.create.assert_not_called() + + +@pytest.mark.parametrize( + "settings", + [ + ModelSettings(extra_args={"tools": [{"type": "web_search"}]}), + ModelSettings(extra_body={"tools": [{"type": "web_search"}]}), + ], +) +def test_sdk_profile_refuses_raw_tool_overrides(model, settings): + report = model.preflight( + ModelRequest( + input="start", + tools=[edit_file], + model_settings=settings, + tool_execution=ToolExecutionConfig(workspace_execution="sdk"), + ) + ) + with pytest.raises(UserError, match="raw tool"): + report.raise_for_errors() + + +@pytest.mark.asyncio +@pytest.mark.parametrize("streamed", [False, True]) +async def test_python_runner_checks_explicit_model_before_dispatch(model, streamed): + config = RunConfig( + tracing_disabled=True, + tool_execution=ToolExecutionConfig(require_native_approval_recovery=True), + ) + agent = Agent(name="explicit model", model=model, tools=[edit_file]) + with pytest.raises(UserError, match="CodexProvider"): + if streamed: + run = Runner.run_streamed(agent, "start", run_config=config) + async for _ in run.stream_events(): + pass + else: + await Runner.run(agent, "start", run_config=config) + model._client.responses.create.assert_not_called() + model._client.chat.completions.create.assert_not_called() + + +def test_preflight_leaves_one_shot_input_unconsumed(model): + class OneShotContent: + def __init__(self): + self.iterations = 0 + + def __iter__(self): + self.iterations += 1 + yield {"type": "input_text", "text": "one-shot content"} + + content = OneShotContent() + request = ModelRequest(input=[{"role": "user", "content": content}]) + report = model.preflight(request) + assert report.static_validation == "unknown" + assert content.iterations == 0 + assert request.input[0]["content"] is content + + +@pytest.mark.asyncio +@pytest.mark.allow_call_model_methods +@pytest.mark.parametrize("streamed", [False, True]) +@pytest.mark.parametrize("strict", [False, True]) +async def test_chat_replay_predicate_runs_once_on_actual_request_only(streamed, strict): + import httpx + + callbacks = [] + requests = [] + + def predicate(context): + callbacks.append(context.reasoning.item) + return True + + def respond(request): + requests.append(request) + if json.loads(request.content).get("stream"): + chunks = [ + { + "id": "chatcmpl-local", + "created": 0, + "model": "fixture-chat", + "object": "chat.completion.chunk", + "choices": [ + { + "index": 0, + "delta": {"role": "assistant", "content": "done"}, + "finish_reason": None, + } + ], + }, + { + "id": "chatcmpl-local", + "created": 0, + "model": "fixture-chat", + "object": "chat.completion.chunk", + "choices": [{"index": 0, "delta": {}, "finish_reason": "stop"}], + }, + ] + body = "".join("data: " + json.dumps(chunk) + "\n\n" for chunk in chunks) + return httpx.Response( + 200, headers={"content-type": "text/event-stream"}, text=body + "data: [DONE]\n\n" + ) + return httpx.Response( + 200, + json={ + "id": "chatcmpl-local", + "created": 0, + "model": "fixture-chat", + "object": "chat.completion", + "choices": [ + { + "index": 0, + "finish_reason": "stop", + "message": { + "role": "assistant", + "content": "done", + }, + } + ], + }, + ) + + async with httpx.AsyncClient(transport=httpx.MockTransport(respond)) as http_client: + client = AsyncOpenAI(api_key="synthetic", http_client=http_client) + model = OpenAIChatCompletionsModel( + "fixture-chat", + client, + should_replay_reasoning_content=predicate, + strict_feature_validation=strict, + ) + history = [ + {"role": "user", "content": "before"}, + { + "type": "reasoning", + "id": "reasoning-prior", + "summary": [ + {"type": "summary_text", "text": "A prior reasoning summary."}, + ], + }, + {"role": "assistant", "content": "earlier answer"}, + {"role": "user", "content": "continue"}, + ] + snapshot = repr(history) + report = model.preflight(ModelRequest(input=history)) + assert report.static_validation == "unknown" + assert callbacks == [] and repr(history) == snapshot + if streamed: + result = Runner.run_streamed( + Agent(name="replay", model=model), + history, + run_config=RunConfig(tracing_disabled=True), + ) + async for _ in result.stream_events(): + pass + else: + result = await Runner.run( + Agent(name="replay", model=model), + history, + run_config=RunConfig(tracing_disabled=True), + ) + assert result.final_output == "done" + assert len(callbacks) == 1 and len(requests) == 1 + assert repr(history) == snapshot + + +async def _dispatch_chat(model, request): + return await model.get_response( + system_instructions=None, + input=request.input, + tools=[], + output_schema=None, + handoffs=[], + tracing=ModelTracing.DISABLED, + model_settings=request.model_settings, + prompt=request.prompt, + previous_response_id=request.previous_response_id, + conversation_id=request.conversation_id, + ) + + +@pytest.mark.asyncio +@pytest.mark.allow_call_model_methods +@pytest.mark.parametrize( + "kwargs, expected", + [ + ({"model_settings": ModelSettings(reasoning=Reasoning(mode="pro"))}, "reasoning.mode"), + ( + {"model_settings": ModelSettings(reasoning=Reasoning(context="all_turns"))}, + "reasoning.context", + ), + ({"prompt": {}}, "prompt"), + ({"previous_response_id": ""}, "previous_response_id"), + ({"conversation_id": ""}, "conversation_id"), + ], +) +async def test_strict_chat_preflight_matches_dispatch_for_unsupported_settings(kwargs, expected): + async with AsyncOpenAI(api_key="synthetic") as client: + client.chat.completions.create = AsyncMock( + side_effect=AssertionError("Unexpected sampling") + ) + model = OpenAIChatCompletionsModel("fixture-chat", client, strict_feature_validation=True) + request = ModelRequest(input="start", **kwargs) + report = model.preflight(request) + assert report.static_validation == "failed" + with pytest.raises(UserError, match=expected) as error: + await _dispatch_chat(model, request) + assert report.errors == (str(error.value),) + + +@pytest.mark.asyncio +@pytest.mark.allow_call_model_methods +@pytest.mark.parametrize("replay", [False, True]) +@pytest.mark.parametrize( + "item, expected", + [ + ( + { + "role": "user", + "content": [{"type": "input_video", "video_url": "https://example.com/video"}], + }, + "Unsupported content type", + ), + ( + {"type": "function_call_output", "call_id": "call", "output": []}, + "tool outputs cannot be empty", + ), + ], +) +async def test_strict_chat_checks_static_input_without_calling_replay_predicate( + item, expected, replay +): + callbacks = [] + + def predicate(context): + callbacks.append(context) + return replay + + history = [{"type": "reasoning", "id": "prior", "summary": []}, item] + async with AsyncOpenAI(api_key="synthetic", base_url="https://api.openai.com/v1") as client: + client.chat.completions.create = AsyncMock( + side_effect=AssertionError("Unexpected sampling") + ) + model = OpenAIChatCompletionsModel( + "fixture-chat", + client, + strict_feature_validation=True, + should_replay_reasoning_content=predicate, + ) + request = ModelRequest(input=history) + report = model.preflight(request) + assert callbacks == [] + assert report.static_validation == "failed" + with pytest.raises(UserError, match=expected) as error: + await _dispatch_chat(model, request) + assert report.errors == (str(error.value),) + client.chat.completions.create.assert_not_called() + + +@pytest.mark.asyncio +@pytest.mark.allow_call_model_methods +async def test_legacy_chat_preflight_leaves_reasoning_warning_to_dispatch(caplog): + async with AsyncOpenAI(api_key="synthetic") as client: + client.chat.completions.create = AsyncMock(side_effect=RuntimeError("sampling reached")) + model = OpenAIChatCompletionsModel("fixture-chat", client) + settings = ModelSettings(reasoning=Reasoning(mode="pro", context="all_turns")) + request = ModelRequest(input="start", model_settings=settings) + report = model.preflight(request) + assert report.static_validation == "passed" + warning = "Ignoring unsupported reasoning settings" + assert warning not in caplog.text + for _ in range(2): + with pytest.raises(RuntimeError, match="sampling reached"): + await _dispatch_chat(model, request) + assert caplog.text.count(warning) == 1 + + +@pytest.mark.asyncio +async def test_strict_chat_preflight_accepts_reasoning_effort(): + async with AsyncOpenAI(api_key="synthetic") as client: + model = OpenAIChatCompletionsModel("fixture-chat", client, strict_feature_validation=True) + settings = ModelSettings(reasoning=Reasoning(effort="low")) + report = model.preflight(ModelRequest(input="start", model_settings=settings)) + assert report.static_validation == "passed" + + +@pytest.mark.asyncio +@pytest.mark.allow_call_model_methods +@pytest.mark.parametrize("streamed", [False, True]) +@pytest.mark.parametrize("adapter", ["chat", "strict-chat", "responses"]) +async def test_duplicate_extra_args_fail_before_hooks_but_direct_dispatch_keeps_type_error( + adapter, streamed +): + starts = [] + + class Observer(RunHooks): + async def on_llm_start(self, context, agent, system_prompt, input_items): + starts.append(agent.name) + + async with AsyncOpenAI(api_key="synthetic") as client: + sampling = AsyncMock(side_effect=AssertionError("Unexpected sampling")) + client.chat.completions.create = sampling + client.responses.create = sampling + model = ( + OpenAIResponsesModel("fixture-model", client) + if adapter == "responses" + else OpenAIChatCompletionsModel( + "fixture-model", client, strict_feature_validation=adapter == "strict-chat" + ) + ) + settings = ModelSettings(temperature=0, extra_args={"temperature": 0.7}) + report = model.preflight(ModelRequest(input="start", model_settings=settings)) + message = "multiple values for keyword argument 'temperature'" + assert report.static_validation == "failed" + with pytest.raises(UserError, match=message): + report.raise_for_errors() + agent = Agent(name="worker", model=model, model_settings=settings) + for opted_in in (True, False): + config = RunConfig( + tracing_disabled=True, + tool_execution=ToolExecutionConfig(workspace_execution="sdk") if opted_in else None, + ) + with pytest.raises(UserError if opted_in else TypeError, match=message): + if streamed: + result = Runner.run_streamed( + agent, "start", hooks=Observer(), run_config=config + ) + async for _ in result.stream_events(): + pass + else: + await Runner.run(agent, "start", hooks=Observer(), run_config=config) + assert starts == ([] if opted_in else ["worker"]) + sampling.assert_not_called() + + +@pytest.mark.asyncio +@pytest.mark.allow_call_model_methods +@pytest.mark.parametrize("streamed", [False, True]) +async def test_legacy_chat_preflight_warns_only_when_dispatch_replaces_tool_output( + streamed, caplog +): + history = [{"type": "function_call_output", "call_id": "call", "output": []}] + async with AsyncOpenAI(api_key="synthetic") as client: + sampling = AsyncMock(side_effect=RuntimeError("sampling reached")) + client.chat.completions.create = sampling + model = OpenAIChatCompletionsModel("fixture-chat", client) + report = model.preflight(ModelRequest(input=history)) + assert report.static_validation == "passed" + warning = "Replacing the tool output with a placeholder" + assert warning not in caplog.text + config = RunConfig( + tracing_disabled=True, tool_execution=ToolExecutionConfig(workspace_execution="sdk") + ) + agent = Agent(name="worker", model=model) + with pytest.raises(RuntimeError, match="sampling reached"): + if streamed: + result = Runner.run_streamed(agent, history, run_config=config) + async for _ in result.stream_events(): + pass + else: + await Runner.run(agent, history, run_config=config) + assert caplog.text.count(warning) == 1 + assert sampling.call_args.kwargs["messages"][-1]["content"] == "[tool output omitted]" + + +@pytest.mark.parametrize( + "model, settings, key", + [ + ( + OpenAIResponsesModel, + ModelSettings(max_tokens=2, extra_args={"max_output_tokens": 5}), + "max_output_tokens", + ), + (OpenAIResponsesModel, ModelSettings(verbosity="low", extra_args={"text": {}}), "text"), + ( + OpenAIChatCompletionsModel, + ModelSettings( + reasoning=Reasoning(effort="low"), extra_args={"reasoning_effort": "high"} + ), + "reasoning_effort", + ), + (OpenAIChatCompletionsModel, ModelSettings(extra_args={"messages": []}), "messages"), + (OpenAIResponsesWSModel, ModelSettings(extra_args={"stream": False}), "stream"), + ], + indirect=["model"], +) +def test_preflight_rejects_duplicate_provider_key_even_when_setting_name_differs( + model, settings, key +): + report = model.preflight(ModelRequest(input="start", model_settings=settings)) + with pytest.raises(UserError, match=key): + report.raise_for_errors() + + +@pytest.mark.parametrize( + "extra_args", + [ + {"temperature": 0}, + {"vendor_option": "opaque"}, + {"stream": False}, + {"parallel_tool_calls": True}, + ], +) +def test_preflight_leaves_extra_args_without_definite_collisions_unchecked(model, extra_args): + report = model.preflight( + ModelRequest( + input="start", + model_settings=ModelSettings(parallel_tool_calls=False, extra_args=extra_args), + ) + ) + assert report.static_validation == "unknown" + assert any("extra_args" in item for item in report.unchecked) + report.raise_for_errors() + + +@pytest.mark.asyncio +@pytest.mark.allow_call_model_methods +@pytest.mark.parametrize("streamed", [False, True]) +@pytest.mark.parametrize("use_chat", [False, True]) +async def test_automatic_preflight_preserves_raw_overrides_of_omitted_arguments(use_chat, streamed): + bodies = [] + + def capture(request): + bodies.append(json.loads(request.content)) + return httpx2.Response(400, json={"error": {"message": "request captured"}}) + + async with AsyncOpenAI( + api_key="synthetic", + http_client=httpx2.AsyncClient(transport=httpx2.MockTransport(capture)), + ) as client: + if use_chat: + model = OpenAIChatCompletionsModel("fixture-chat", client) + raw = {"temperature": 0, "reasoning_effort": "low", "logprobs": True} + else: + model = OpenAIResponsesModel("fixture-responses", client) + raw = {"temperature": 0, "max_output_tokens": 10, "text": {"verbosity": "low"}} + settings = ModelSettings(top_logprobs=2, extra_args=raw) + agent = Agent(name="worker", model=model, model_settings=settings) + config = RunConfig( + tracing_disabled=True, tool_execution=ToolExecutionConfig(workspace_execution="sdk") + ) + with pytest.raises(BadRequestError, match="request captured"): + if streamed: + result = Runner.run_streamed(agent, "start", run_config=config) + async for _ in result.stream_events(): + pass + else: + await Runner.run(agent, "start", run_config=config) + (body,) = bodies + assert {key: body[key] for key in raw} == raw + assert body["top_logprobs"] == 2 + + +@pytest.mark.asyncio +async def test_responses_preflight_respects_prompt_owned_omissions(): + async with AsyncOpenAI(api_key="synthetic") as client: + model = OpenAIResponsesModel("fixture", client, model_is_explicit=False) + request = ModelRequest( + input="start", + prompt={"id": "pmpt_fixture"}, + model_settings=ModelSettings( + tool_choice="lookup", + extra_args={"model": "other", "tools": [], "tool_choice": "auto"}, + ), + ) + report = model.preflight(request) + assert report.static_validation == "unknown" + report.raise_for_errors() + + +@pytest.mark.asyncio +@pytest.mark.parametrize("model_name", ["gpt-5.4", "computer-use-preview"]) +@pytest.mark.parametrize( + "key, typed, raw", + [ + ("store", {"store": False}, True), + ("parallel_tool_calls", {"parallel_tool_calls": False}, True), + ("tool_choice", {"tool_choice": "auto"}, "none"), + ("tool_choice", {"tool_choice": "computer"}, "auto"), + ("tools", {}, []), + ], +) +async def test_responses_preflight_checks_known_collisions_without_loading_dynamic_tools( + model_name, key, typed, raw +): + def load_computer(**kwargs): + raise AssertionError("Preflight must not load a computer") + + async with AsyncOpenAI(api_key="synthetic") as client: + model = OpenAIResponsesModel(model_name, client) + report = model.preflight( + ModelRequest( + input="start", + prompt={"id": "pmpt_fixture"} if key == "tools" else None, + tools=[ComputerTool(computer=load_computer), edit_file], + model_settings=ModelSettings(**typed, extra_args={key: raw}), + ) + ) + with pytest.raises(UserError, match=key): + report.raise_for_errors() + + +@pytest.mark.asyncio +async def test_responses_preflight_defers_preview_metadata_and_allows_omitted_choice(): + class UnreadableComputer(FakeComputer): + @property + def environment(self): + raise AssertionError("Preflight must not query the computer environment") + + @property + def dimensions(self): + raise AssertionError("Preflight must not query the computer dimensions") + + async with AsyncOpenAI(api_key="synthetic") as client: + model = OpenAIResponsesModel("gpt-5.4", client, model_is_explicit=False) + report = model.preflight( + ModelRequest( + input="start", + prompt={"id": "pmpt_fixture"}, + tools=[ComputerTool(computer=UnreadableComputer())], + model_settings=ModelSettings(extra_args={"tool_choice": "auto", "model": "other"}), + ) + ) + assert report.static_validation == "unknown" + report.raise_for_errors() + + +@pytest.mark.asyncio +@pytest.mark.allow_call_model_methods +@pytest.mark.parametrize("with_computer", [False, True], ids=["web", "computer-and-web"]) +@pytest.mark.parametrize("streamed", [False, True], ids=["awaited", "streamed"]) +async def test_web_search_filters_serialize_once_at_dispatch(with_computer, streamed): + events = [] + bodies = [] + + class DomainFilters(Filters): + @field_serializer("allowed_domains") + def serialize_domains(self, domains) -> list[str]: + events.append("serialize") + return domains if events.count("serialize") == 1 else ["second.example.org"] + + class Observer(RunHooks): + async def on_llm_start(self, context, agent, system_prompt, input_items): + events.append("llm_start") + + def capture(request): + bodies.append(json.loads(request.content)) + return httpx2.Response(400, json={"error": {"message": "request captured"}}) + + domains = ["first.example.org"] + web = WebSearchTool(filters=DomainFilters(allowed_domains=domains)) + tools = [ComputerTool(computer=FakeComputer()), web] if with_computer else [web] + async with AsyncOpenAI( + api_key="synthetic", + http_client=httpx2.AsyncClient(transport=httpx2.MockTransport(capture)), + ) as client: + model = OpenAIResponsesModel("gpt-5.4", client) + settings = ModelSettings(tool_choice="web_search") + report = model.preflight(ModelRequest(input="start", tools=tools, model_settings=settings)) + collision = model.preflight( + ModelRequest( + input="start", + tools=tools, + model_settings=ModelSettings( + tool_choice="web_search", extra_args={"tool_choice": "none"} + ), + ) + ) + with pytest.raises(UserError, match="tool_choice"): + collision.raise_for_errors() + assert events == [] + assert report.static_validation == "unknown" + assert any("web search" in item for item in report.unchecked) + + agent = Agent(name="worker", model=model, tools=tools, model_settings=settings) + config = RunConfig(tracing_disabled=True, model_selector=lambda data: None) + with pytest.raises(BadRequestError, match="request captured"): + if streamed: + result = Runner.run_streamed(agent, "start", run_config=config, hooks=Observer()) + async for _ in result.stream_events(): + pass + else: + await Runner.run(agent, "start", run_config=config, hooks=Observer()) + assert events == ["llm_start", "serialize"] + (body,) = bodies + assert body["tools"][-1]["filters"]["allowed_domains"] == domains + assert body["tool_choice"] == {"type": "web_search"} diff --git a/tests/test_controls_composition.py b/tests/test_controls_composition.py new file mode 100644 index 0000000000..f0b60b8a7c --- /dev/null +++ b/tests/test_controls_composition.py @@ -0,0 +1,331 @@ +"""Cross-feature acceptance at SDK admission and dispatch boundaries.""" + +from __future__ import annotations + +import asyncio +from typing import Any + +import httpx2 +import pytest +from openai import AsyncOpenAI +from openai.types.shared import Reasoning + +from agents import ( + Agent, + ComputerTool, + ModelSettings, + RunBudget, + RunBudgetError, + RunConfig, + RunControl, + RunHooks, + Runner, + Usage, + UserError, +) +from agents.decorators import tool +from agents.models.interface import ModelProvider +from agents.models.openai_chatcompletions import OpenAIChatCompletionsModel +from agents.models.openai_responses import OpenAIResponsesModel +from agents.testing import ModelStep, ScriptedModel, assistant_message, function_call +from tests.test_computer_tool_lifecycle import FakeComputer +from tests.utils.simple_session import SimpleListSession + +pytestmark = pytest.mark.asyncio + + +class RecordingProvider(ModelProvider): + def __init__(self, models): + self.models = models + self.names = [] + + def get_model(self, name): + self.names.append(name) + return self.models[name] + + +async def drive(streamed: bool, agent: Agent[Any], **kwargs: Any) -> Any: + if not streamed: + return await Runner.run(agent, "start", **kwargs) + result = Runner.run_streamed(agent, "start", **kwargs) + try: + async for _ in result.stream_events(): + pass + return result + finally: + if not result.is_complete: + result.cancel() + + +async def stop(task: asyncio.Task[Any], release: asyncio.Event) -> None: + release.set() + if not task.done(): + task.cancel() + await asyncio.gather(task, return_exceptions=True) + + +def text(item: Any) -> str | None: + if not isinstance(item, dict) or item.get("role") != "user": + return None + content = item.get("content") + if isinstance(content, str): + return content + return "".join(part.get("text", "") for part in content or [] if isinstance(part, dict)) + + +def count_message(items: list[Any], message: str) -> int: + return sum(text(item) == message for item in items) + + +@pytest.mark.parametrize("streamed", [False, True], ids=["awaited", "streamed"]) +async def test_request_budget_denial_after_live_admission_preserves_truthful_receipt( + streamed: bool, +) -> None: + entered, release = asyncio.Event(), asyncio.Event() + effects = [] + + @tool + async def failing_test() -> str: + entered.set() + await release.wait() + effects.append("test failed") + return "test failed" + + first = ScriptedModel([[function_call("failing_test", "{}", call_id="test")]]) + stronger = ScriptedModel([[assistant_message("must not dispatch")]]) + provider = RecordingProvider({"base": first, "stronger": stronger}) + selections = [] + + def select(data): + selections.append(data.turn_number) + return "stronger" if data.turn_number == 2 else None + + agent = Agent(name="worker", model="base", tools=[failing_test]) + control, session = RunControl(), SimpleListSession() + config = RunConfig( + model_provider=provider, + model_selector=select, + budget=RunBudget(max_outer_requests=1), + tracing_disabled=True, + ) + task = asyncio.create_task( + drive(streamed, agent, control=control, session=session, run_config=config) + ) + try: + await asyncio.wait_for(entered.wait(), 3) + receipt = control.send("Explain before editing.") + release.set() + with pytest.raises(RunBudgetError) as caught: + await asyncio.wait_for(task, 3) + assert caught.value.limit == "outer_requests" + outcome = await asyncio.wait_for(receipt.wait(), 3) + assert outcome.status == "not_submitted" and outcome.retained is True + assert len(first.calls) == 1 and not stronger.calls + assert effects == ["test failed"] and agent.model == "base" + assert count_message(await session.get_items(), "Explain before editing.") == 1 + assert selections[0] == 1 + with pytest.raises(UserError): + control.send("after budget failure") + finally: + await stop(task, release) + + +@pytest.mark.parametrize("streamed", [False, True], ids=["awaited", "streamed"]) +async def test_selected_model_observes_tokens_and_later_budget_failure_preserves_receipt( + streamed: bool, +) -> None: + entered, release = asyncio.Event(), asyncio.Event() + effects = [] + + @tool + async def advance() -> str: + entered.set() + await release.wait() + effects.append("advanced") + return "next" + + usage = Usage(input_tokens=1, output_tokens=1, total_tokens=2) + first = ScriptedModel( + [ + ModelStep( + output=[function_call("advance", "{}", call_id="first")], + usage=usage, + ) + ] + ) + second = ScriptedModel( + [ + ModelStep( + output=[function_call("advance", "{}", call_id="second")], + usage=usage, + ) + ] + ) + provider = RecordingProvider({"base": first, "stronger": second}) + + control = RunControl() + agent = Agent(name="worker", model="base", tools=[advance]) + config = RunConfig( + model_provider=provider, + model_selector=lambda data: "stronger" if data.turn_number == 2 else None, + budget=RunBudget(max_tokens=3), + tracing_disabled=True, + ) + task = asyncio.create_task(drive(streamed, agent, control=control, run_config=config)) + try: + await asyncio.wait_for(entered.wait(), 3) + receipt = control.send("Use the stronger model to explain.") + release.set() + with pytest.raises(RunBudgetError) as caught: + await asyncio.wait_for(task, 3) + assert caught.value.limit == "tokens" + assert len(first.calls) == len(second.calls) == 1 + assert effects == ["advanced", "advanced"] + outcome = await asyncio.wait_for(receipt.wait(), 3) + assert outcome.status == "submitted" and outcome.turn_number == 2 + assert count_message(second.calls[0].input, "Use the stronger model to explain.") == 1 + finally: + await stop(task, release) + + +@pytest.mark.allow_call_model_methods +@pytest.mark.parametrize( + "incompatibility", ["prompt", "reasoning", "parallel_tool_calls", "tool_choice"] +) +@pytest.mark.parametrize("streamed", [False, True], ids=["awaited", "streamed"]) +async def test_selected_adapter_preflight_rejects_before_receipt_submission_or_network( + streamed: bool, + incompatibility: str, +) -> None: + entered, release = asyncio.Event(), asyncio.Event() + network_requests = [] + llm_starts = [] + + class Observer(RunHooks): + async def on_llm_start(self, context, agent, system_prompt, input_items): + llm_starts.append(agent.name) + + def unexpected_request(request): + network_requests.append(request) + raise AssertionError("Known adapter incompatibility reached the transport.") + + client = AsyncOpenAI( + api_key="synthetic-key", + http_client=httpx2.AsyncClient(transport=httpx2.MockTransport(unexpected_request)), + ) + with_computer = incompatibility in {"parallel_tool_calls", "tool_choice"} + selected = ( + OpenAIResponsesModel("gpt-5.4", client) + if with_computer + else OpenAIChatCompletionsModel( + model="fixture-chat", openai_client=client, strict_feature_validation=True + ) + ) + + @tool + async def failing_test() -> str: + entered.set() + await release.wait() + return "test failed" + + first = ScriptedModel([[function_call("failing_test", "{}", call_id="test")]]) + provider = RecordingProvider({"base": first, "selected": selected}) + settings = { + "reasoning": ModelSettings(reasoning=Reasoning(mode="pro", context="all_turns")), + "parallel_tool_calls": ModelSettings( + parallel_tool_calls=False, extra_args={"parallel_tool_calls": True} + ), + "tool_choice": ModelSettings(tool_choice="auto", extra_args={"tool_choice": "none"}), + } + agent = Agent( + name="worker", + model="base", + tools=[failing_test, ComputerTool(computer=FakeComputer())] + if with_computer + else [failing_test], + prompt={"id": "pmpt_synthetic"} if incompatibility == "prompt" else None, + model_settings=settings.get(incompatibility, ModelSettings()), + reset_tool_choice=not with_computer, + ) + control, session = RunControl(), SimpleListSession() + config = RunConfig( + model_provider=provider, + model_selector=lambda data: "selected" if data.turn_number == 2 else None, + budget=RunBudget(max_outer_requests=2), + tracing_disabled=True, + ) + task = asyncio.create_task( + drive( + streamed, agent, control=control, session=session, run_config=config, hooks=Observer() + ) + ) + try: + await asyncio.wait_for(entered.wait(), 3) + receipt = control.send("Explain before editing.") + release.set() + with pytest.raises(UserError, match=incompatibility): + await asyncio.wait_for(task, 3) + outcome = await asyncio.wait_for(receipt.wait(), 3) + assert outcome.status == "not_submitted" and outcome.retained is True + assert llm_starts == ["worker"] + assert provider.names == ["base", "selected"] + assert network_requests == [] and len(first.calls) == 1 + assert count_message(await session.get_items(), "Explain before editing.") == 1 + finally: + await stop(task, release) + await client.close() + + +@pytest.mark.parametrize("streamed", [False, True], ids=["awaited", "streamed"]) +async def test_nested_run_shares_last_tool_slot_without_consuming_parent_correction( + streamed: bool, +) -> None: + entered, release = asyncio.Event(), asyncio.Event() + effects = [] + + @tool + async def write(value: str) -> str: + effects.append(value) + return value + + async def child_request(call): + entered.set() + await release.wait() + return [function_call("write", '{"value":"left"}', call_id="left")] + + child_model = ScriptedModel( + [ + ModelStep.respond(child_request), + [function_call("write", '{"value":"right"}', call_id="right")], + ] + ) + child = Agent(name="child", model=child_model, tools=[write]) + delegate = child.as_tool("delegate", "Delegate", failure_error_function=None) + parent_model = ScriptedModel( + [ + [function_call("delegate", '{"input":"child question"}', call_id="delegate")], + ] + ) + parent = Agent(name="parent", model=parent_model, tools=[delegate]) + control = RunControl() + config = RunConfig( + budget=RunBudget(max_tool_starts=2, share_with_children=True), + tracing_disabled=True, + ) + task = asyncio.create_task(drive(streamed, parent, control=control, run_config=config)) + try: + await asyncio.wait_for(entered.wait(), 3) + receipt = control.send("Parent-only correction.") + release.set() + with pytest.raises(RunBudgetError) as caught: + await asyncio.wait_for(task, 3) + assert caught.value.limit == "tool_starts" + assert effects == ["left"] + assert len(parent_model.calls) == 1 and len(child_model.calls) == 2 + assert all( + count_message(call.input, "Parent-only correction.") == 0 for call in child_model.calls + ) + outcome = await asyncio.wait_for(receipt.wait(), 3) + assert outcome.status == "not_submitted" and outcome.retained is False + finally: + await stop(task, release) diff --git a/tests/test_shared_run_budget.py b/tests/test_shared_run_budget.py index 435884c4d9..bfa7c6f071 100644 --- a/tests/test_shared_run_budget.py +++ b/tests/test_shared_run_budget.py @@ -14,6 +14,7 @@ RunConfig, Runner, RunState, + ToolExecutionConfig, UserError, tool_namespace, ) @@ -823,11 +824,21 @@ def record() -> str: @pytest.mark.asyncio -async def test_shared_codex_child_rejects_unenforceable_native_delegation(tmp_path): +@pytest.mark.parametrize("sdk_workspace", [False, True]) +@pytest.mark.parametrize("streamed", [False, True]) +async def test_shared_codex_child_rejects_unenforceable_native_delegation( + tmp_path, sdk_workspace, streamed +): + provider = CodexProvider(cwd=tmp_path) child = Agent(name="native-child").as_tool( "ask", "Ask child", - run_config=RunConfig(model_provider=CodexProvider(cwd=tmp_path)), + run_config=RunConfig( + model_provider=provider, + tool_execution=ToolExecutionConfig(workspace_execution="sdk") + if sdk_workspace + else None, + ), failure_error_function=None, ) root = Agent( @@ -836,7 +847,12 @@ async def test_shared_codex_child_rejects_unenforceable_native_delegation(tmp_pa tools=[child], ) with pytest.raises(UserError, match="controlled native delegation"): - await execute(root, RunBudget(max_tool_starts=2, share_with_children=True)) + await execute( + root, + RunBudget(max_tool_starts=2, share_with_children=True), + streamed=streamed, + ) + assert provider._manager is None @pytest.mark.asyncio