Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
52 changes: 52 additions & 0 deletions examples/model_providers/model_preflight.py
Original file line number Diff line number Diff line change
@@ -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))
4 changes: 4 additions & 0 deletions src/agents/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -377,6 +378,9 @@ def enable_verbose_stdout_logging() -> None:


__all__ = [
"ModelPreflight",
"ModelRequest",
"ToolOwnership",
"Agent",
"AgentBase",
"AgentToolStreamEvent",
Expand Down
144 changes: 144 additions & 0 deletions src/agents/model_preflight.py
Original file line number Diff line number Diff line change
@@ -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
16 changes: 11 additions & 5 deletions src/agents/models/_codex_inputs.py
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand All @@ -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:
Expand Down Expand Up @@ -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 = []
Expand All @@ -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:
Expand All @@ -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]] = []
Expand Down Expand Up @@ -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:
Expand Down
19 changes: 19 additions & 0 deletions src/agents/models/_openai_shared.py
Original file line number Diff line number Diff line change
Expand Up @@ -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)
15 changes: 10 additions & 5 deletions src/agents/models/chatcmpl_converter.py
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand Down Expand Up @@ -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
Expand Down Expand Up @@ -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",
Expand Down
Loading
Loading