Skip to content

Codex

Python Agents SDK backed by the embedded Codex engine.

Agent dataclass

Reusable configuration for an agent across turns and sessions.

Source code in src/openai_agents/codex/agent.py
@dataclass(kw_only=True)
class Agent:
    """Reusable configuration for an agent across turns and sessions."""

    model: str
    """The model ID to use for inference."""

    name: str | None = None
    """A human-readable name for the agent."""

    instructions: str | None = None
    """Instructions to append to Codex's base instructions."""

    tools: list[Tool] = field(default_factory=list)
    """Tools to make available alongside the harness's default tools."""

    reasoning: Reasoning | None = None
    """Overrides for the model's reasoning settings."""

    hooks: list[Hook] = field(default_factory=list)
    """Codex command hooks to run on the selected executor."""

    approval_policy: ApprovalPolicy | None = None
    """When Codex asks for review. Defaults to on-request with a reviewer, never otherwise."""

    guardian: bool = False
    """Use Codex Guardian for native actions eligible for automatic review."""

    approval_handler: ApprovalHandler | None = None
    """Decide application approval requests. Return True to approve, False to reject."""

    subagents: bool | None = None
    """Set True to enable Codex collaboration, False to disable it, or use the model default."""

    def session(
        self,
        *,
        environment: Environment | EllipsisType = ...,
        workspace: str | PathLike[str] | None = None,
        sandbox: Sandbox | None = None,
        state: ConversationState | None = None,
        storage: SessionStorage | None = None,
        session_id: str | None = None,
    ) -> Session:
        """Open a conversation for multiple turns with `async with`."""
        return Session(
            self,
            environment=environment,
            workspace=workspace,
            sandbox=sandbox,
            state=state,
            storage=storage,
            session_id=session_id,
        )

    async def run(
        self,
        input: str | None = None,
        *,
        text: str | None = None,
        environment: Environment | EllipsisType = ...,
        workspace: str | PathLike[str] | None = None,
        sandbox: Sandbox | None = None,
        state: ConversationState | None = None,
        storage: SessionStorage | None = None,
        session_id: str | None = None,
        store: ConversationStore | None = None,
        conversation_id: str | None = None,
    ) -> RunResult:
        """Run one turn in a fresh session from an explicit snapshot or a stored ID."""
        text = _turn_input(input, text)
        return await _drain(
            self.stream(
                text,
                environment=environment,
                workspace=workspace,
                sandbox=sandbox,
                state=state,
                storage=storage,
                session_id=session_id,
                store=store,
                conversation_id=conversation_id,
            )
        )

    @_turn_stream
    async def stream(
        self,
        input: str | None = None,
        *,
        text: str | None = None,
        environment: Environment | EllipsisType = ...,
        workspace: str | PathLike[str] | None = None,
        sandbox: Sandbox | None = None,
        state: ConversationState | None = None,
        storage: SessionStorage | None = None,
        session_id: str | None = None,
        store: ConversationStore | None = None,
        conversation_id: str | None = None,
    ) -> AsyncGenerator[RunEvent, None]:
        """Yield live events, then the result after shutdown and any store commit."""
        text = _turn_input(input, text)
        if store is not None and storage is not None:
            raise ValueError("Pass either store or storage")
        async with (
            _lock_conversation(store, conversation_id, state) as conversation,
            self.session(
                environment=environment,
                workspace=workspace,
                sandbox=sandbox,
                state=conversation.state,
                storage=storage,
                session_id=session_id,
            ) as session,
            aclosing(session.stream(text)) as events,
        ):
            async for event in events:
                if isinstance(event, RunResult):
                    result = event
                    break
                yield event
            else:
                raise EngineError("Stream ended before the result")
            conversation.state = result.state
            if conversation_id is not None:
                result.state["session_id"] = conversation_id
        yield result

model instance-attribute

model: str

The model ID to use for inference.

name class-attribute instance-attribute

name: str | None = None

A human-readable name for the agent.

instructions class-attribute instance-attribute

instructions: str | None = None

Instructions to append to Codex's base instructions.

tools class-attribute instance-attribute

tools: list[Tool] = field(default_factory=list)

Tools to make available alongside the harness's default tools.

reasoning class-attribute instance-attribute

reasoning: Reasoning | None = None

Overrides for the model's reasoning settings.

hooks class-attribute instance-attribute

hooks: list[Hook] = field(default_factory=list)

Codex command hooks to run on the selected executor.

approval_policy class-attribute instance-attribute

approval_policy: ApprovalPolicy | None = None

When Codex asks for review. Defaults to on-request with a reviewer, never otherwise.

guardian class-attribute instance-attribute

guardian: bool = False

Use Codex Guardian for native actions eligible for automatic review.

approval_handler class-attribute instance-attribute

approval_handler: ApprovalHandler | None = None

Decide application approval requests. Return True to approve, False to reject.

subagents class-attribute instance-attribute

subagents: bool | None = None

Set True to enable Codex collaboration, False to disable it, or use the model default.

session

session(
    *,
    environment: Environment | EllipsisType = ...,
    workspace: str | PathLike[str] | None = None,
    sandbox: Sandbox | None = None,
    state: ConversationState | None = None,
    storage: SessionStorage | None = None,
    session_id: str | None = None,
) -> Session

Open a conversation for multiple turns with async with.

Source code in src/openai_agents/codex/agent.py
def session(
    self,
    *,
    environment: Environment | EllipsisType = ...,
    workspace: str | PathLike[str] | None = None,
    sandbox: Sandbox | None = None,
    state: ConversationState | None = None,
    storage: SessionStorage | None = None,
    session_id: str | None = None,
) -> Session:
    """Open a conversation for multiple turns with `async with`."""
    return Session(
        self,
        environment=environment,
        workspace=workspace,
        sandbox=sandbox,
        state=state,
        storage=storage,
        session_id=session_id,
    )

run async

run(
    input: str | None = None,
    *,
    text: str | None = None,
    environment: Environment | EllipsisType = ...,
    workspace: str | PathLike[str] | None = None,
    sandbox: Sandbox | None = None,
    state: ConversationState | None = None,
    storage: SessionStorage | None = None,
    session_id: str | None = None,
    store: ConversationStore | None = None,
    conversation_id: str | None = None,
) -> RunResult

Run one turn in a fresh session from an explicit snapshot or a stored ID.

Source code in src/openai_agents/codex/agent.py
async def run(
    self,
    input: str | None = None,
    *,
    text: str | None = None,
    environment: Environment | EllipsisType = ...,
    workspace: str | PathLike[str] | None = None,
    sandbox: Sandbox | None = None,
    state: ConversationState | None = None,
    storage: SessionStorage | None = None,
    session_id: str | None = None,
    store: ConversationStore | None = None,
    conversation_id: str | None = None,
) -> RunResult:
    """Run one turn in a fresh session from an explicit snapshot or a stored ID."""
    text = _turn_input(input, text)
    return await _drain(
        self.stream(
            text,
            environment=environment,
            workspace=workspace,
            sandbox=sandbox,
            state=state,
            storage=storage,
            session_id=session_id,
            store=store,
            conversation_id=conversation_id,
        )
    )

stream async

stream(
    input: str | None = None,
    *,
    text: str | None = None,
    environment: Environment | EllipsisType = ...,
    workspace: str | PathLike[str] | None = None,
    sandbox: Sandbox | None = None,
    state: ConversationState | None = None,
    storage: SessionStorage | None = None,
    session_id: str | None = None,
    store: ConversationStore | None = None,
    conversation_id: str | None = None,
) -> AsyncGenerator[RunEvent, None]

Yield live events, then the result after shutdown and any store commit.

Source code in src/openai_agents/codex/agent.py
@_turn_stream
async def stream(
    self,
    input: str | None = None,
    *,
    text: str | None = None,
    environment: Environment | EllipsisType = ...,
    workspace: str | PathLike[str] | None = None,
    sandbox: Sandbox | None = None,
    state: ConversationState | None = None,
    storage: SessionStorage | None = None,
    session_id: str | None = None,
    store: ConversationStore | None = None,
    conversation_id: str | None = None,
) -> AsyncGenerator[RunEvent, None]:
    """Yield live events, then the result after shutdown and any store commit."""
    text = _turn_input(input, text)
    if store is not None and storage is not None:
        raise ValueError("Pass either store or storage")
    async with (
        _lock_conversation(store, conversation_id, state) as conversation,
        self.session(
            environment=environment,
            workspace=workspace,
            sandbox=sandbox,
            state=conversation.state,
            storage=storage,
            session_id=session_id,
        ) as session,
        aclosing(session.stream(text)) as events,
    ):
        async for event in events:
            if isinstance(event, RunResult):
                result = event
                break
            yield event
        else:
            raise EngineError("Stream ended before the result")
        conversation.state = result.state
        if conversation_id is not None:
            result.state["session_id"] = conversation_id
    yield result

Reasoning dataclass

Settings for the model's reasoning effort and summary.

Source code in src/openai_agents/codex/agent.py
@dataclass(kw_only=True)
class Reasoning:
    """Settings for the model's reasoning effort and summary."""

    effort: Literal["none", "minimal", "low", "medium", "high", "xhigh", "max"] | None = None
    summary: Literal["auto", "concise", "detailed"] | None = None

Runner

Run a turn with a Codex agent.

Source code in src/openai_agents/codex/agent.py
class Runner:
    """Run a turn with a Codex agent."""

    @staticmethod
    async def run(
        agent: Agent,
        input: str | None = None,
        *,
        text: str | None = None,
        environment: Environment | EllipsisType = ...,
        workspace: str | PathLike[str] | None = None,
        sandbox: Sandbox | None = None,
        state: ConversationState | None = None,
        storage: SessionStorage | None = None,
        session_id: str | None = None,
        store: ConversationStore | None = None,
        conversation_id: str | None = None,
    ) -> RunResult:
        """Run the agent once, using the same session options as Agent.run."""
        if not isinstance(agent, Agent):
            raise TypeError("Use openai_agents.classic.Runner for Classic agents")
        return await agent.run(
            input,
            text=text,
            environment=environment,
            workspace=workspace,
            sandbox=sandbox,
            state=state,
            storage=storage,
            session_id=session_id,
            store=store,
            conversation_id=conversation_id,
        )

run async staticmethod

run(
    agent: Agent,
    input: str | None = None,
    *,
    text: str | None = None,
    environment: Environment | EllipsisType = ...,
    workspace: str | PathLike[str] | None = None,
    sandbox: Sandbox | None = None,
    state: ConversationState | None = None,
    storage: SessionStorage | None = None,
    session_id: str | None = None,
    store: ConversationStore | None = None,
    conversation_id: str | None = None,
) -> RunResult

Run the agent once, using the same session options as Agent.run.

Source code in src/openai_agents/codex/agent.py
@staticmethod
async def run(
    agent: Agent,
    input: str | None = None,
    *,
    text: str | None = None,
    environment: Environment | EllipsisType = ...,
    workspace: str | PathLike[str] | None = None,
    sandbox: Sandbox | None = None,
    state: ConversationState | None = None,
    storage: SessionStorage | None = None,
    session_id: str | None = None,
    store: ConversationStore | None = None,
    conversation_id: str | None = None,
) -> RunResult:
    """Run the agent once, using the same session options as Agent.run."""
    if not isinstance(agent, Agent):
        raise TypeError("Use openai_agents.classic.Runner for Classic agents")
    return await agent.run(
        input,
        text=text,
        environment=environment,
        workspace=workspace,
        sandbox=sandbox,
        state=state,
        storage=storage,
        session_id=session_id,
        store=store,
        conversation_id=conversation_id,
    )

ApprovalRequest dataclass

One proposed action. details contains the original Codex request payload.

Source code in src/openai_agents/codex/approvals.py
@dataclass(frozen=True, kw_only=True)
class ApprovalRequest:
    """One proposed action. details contains the original Codex request payload."""

    kind: Literal["command", "patch", "permissions", "function_tool"]
    thread_id: str
    turn_id: str
    call_id: str
    details: dict[str, Any]

Engine

An embedded Codex engine. Open with async with Engine() and run one turn at a time.

Source code in src/openai_agents/codex/engine.py
class Engine:
    """An embedded Codex engine. Open with `async with Engine()` and run one turn at a time."""

    def __init__(self) -> None:
        self.codex_version: str | None = None
        self._native: _NativeEngine | None = None
        self._request_id = 0
        self._busy = False

    async def __aenter__(self) -> Engine:
        if self._native is not None or self._busy:
            raise EngineError("Engine is already open")
        native = _native()
        try:
            executable = import_module("codex_cli_bin").bundled_codex_path()
            self._native = native.Engine(executable)
        except (ImportError, OSError, RuntimeError) as exc:
            raise EngineError(f"Codex startup failed: {exc}") from exc
        self.codex_version = native.codex_version
        return self

    async def __aexit__(self, *exc: object) -> None:
        await self._close()

    async def _close(self) -> None:
        native, self._native = self._native, None
        if native is not None:
            try:
                await native.close()
            except RuntimeError as exc:
                raise EngineError(f"Codex shutdown failed: {exc}") from exc

    async def run(
        self,
        agent: Agent,
        input: str | None = None,
        *,
        text: str | None = None,
        environment: Environment | EllipsisType = ...,
        workspace: str | os.PathLike[str] | None = None,
        sandbox: Sandbox | None = None,
        state: ConversationState | None = None,
        store: ConversationStore | None = None,
        conversation_id: str | None = None,
    ) -> RunResult:
        """Run one turn from an explicit snapshot or a conversation in a store."""
        text = _turn_input(input, text)
        return await _drain(
            self.stream(
                agent,
                text,
                environment=environment,
                workspace=workspace,
                sandbox=sandbox,
                state=state,
                store=store,
                conversation_id=conversation_id,
            )
        )

    @_turn_stream
    async def stream(
        self,
        agent: Agent,
        input: str | None = None,
        *,
        text: str | None = None,
        environment: Environment | EllipsisType = ...,
        workspace: str | os.PathLike[str] | None = None,
        sandbox: Sandbox | None = None,
        state: ConversationState | None = None,
        store: ConversationStore | None = None,
        conversation_id: str | None = None,
    ) -> AsyncGenerator[RunEvent, None]:
        """Yield live events followed by a RunResult. Closing early shuts down this engine."""
        text = _turn_input(input, text)
        if self._busy:
            raise EngineError("Engine is already busy")
        self._busy = True
        try:
            async with _lock_conversation(store, conversation_id, state) as conversation:
                target = _resolve_environment(environment, workspace, sandbox)
                callbacks = await self._open_session(agent, target, conversation.state)
                async with aclosing(self._stream_turn(text, callbacks)) as events:
                    async for event in events:
                        if isinstance(event, RunResult):
                            result = event
                            break
                        yield event
                    else:
                        raise EngineError("Stream ended before the result")
                await self._request("close", {})
                conversation.state = result.state
                if conversation_id is not None:
                    result.state["session_id"] = conversation_id
        finally:
            self._busy = False
        yield result

    async def _open_session(
        self,
        agent: Agent,
        environment: Environment | EllipsisType,
        state: ConversationState | None,
        *,
        save_settings: bool = False,
    ) -> _Callbacks:
        # Keep omission distinct from explicit None until resume checks have run.
        if environment is ...:
            environment = None
        params, functions = _prepare_session(agent, environment, state)
        self._settings = None
        if save_settings or (state is not None and "sdk_settings" in state):
            from openai_agents.codex._settings import settings_for

            self._settings = settings_for(agent, environment)
        callbacks = _Callbacks(functions, agent.approval_handler)
        opened = await self._request("open", params)
        self._session_id = state.session_id if state is not None else opened["thread_id"]
        return callbacks

    async def _request(self, method: str, params: dict[str, Any]) -> Any:
        try:
            native = self._start_request(method, params)
            return self._result(await _receive(native))
        except RunError:
            raise
        except BaseException:
            await self._close()
            raise

    def _start_request(self, method: str, params: dict[str, Any]) -> _NativeEngine:
        native = self._native
        if native is None:
            raise EngineError("Engine is closed. Open it with 'async with Engine()'.")
        self._request_id += 1
        _write(native, {"id": self._request_id, "method": method, "params": params})
        return native

    def _result(self, reply: dict[str, Any]) -> Any:
        if reply.get("id") != self._request_id:
            raise EngineError("Unexpected engine response ID")
        if "error" in reply:
            failure = reply["error"]
            code, details = _error_info(failure.get("data"))
            raise RunError(failure["message"], code=code, details=details)
        if "result" not in reply:
            raise EngineError("Missing engine result")
        return reply["result"]

    async def _stream_turn(
        self, text: str, callbacks: _Callbacks, control: _TurnControl | None = None
    ) -> AsyncGenerator[RunEvent, None]:
        items: list[RunItem] = []
        responses: list[ResponseUsage] = []
        turn_id = None
        finished = False
        try:
            native = self._start_request("run", {"text": text})
            if control is None:
                control = _TurnControl()
            control.bind(native, self._request_id)
            while True:
                if self._native is not native:
                    raise EngineError("Engine closed during the turn")
                reply = await _receive(native)
                if reply.get("method") == "callback/request":
                    control.dispatch(callbacks, reply)
                    continue
                if reply.get("method") == "callback/cancel":
                    control.cancel(reply["params"]["id"])
                    continue
                if "method" not in reply:
                    break
                event = _parse_event(reply["method"], reply["params"])
                if isinstance(event, TurnStarted):
                    turn_id = event.turn_id
                elif isinstance(event, ItemCompleted):
                    items.append(event.item)
                elif isinstance(event, ResponseCompleted):
                    responses.append(event.response)
                yield event

            if control.failure is not None:
                raise control.failure
            data = self._result(reply)
            if self._settings is not None:
                data["state"]["sdk_settings"] = deepcopy(self._settings)
            if self._session_id != data["state"]["thread_id"]:
                data["state"]["session_id"] = self._session_id
            if data.get("interrupted") and control.stopping:
                # An immediate stop can precede the turn/started notification.
                if turn_id is not None and turn_id != data["turn_id"]:
                    raise EngineError("Unexpected interrupted turn")
                turn_id = data["turn_id"]
                raise _Interrupted(ConversationState(data["state"]))
            if turn_id is None or data["turn_id"] != turn_id:
                raise EngineError("Unexpected completed turn")
            counts = data["thread_usage"]
            result = RunResult(
                turn_id=turn_id,
                final_output=data["final_output"],
                new_items=items,
                usage=Usage(
                    responses=responses,
                    thread=TokenUsage(**counts) if counts is not None else None,
                    model_context_window=data["model_context_window"],
                ),
                state=ConversationState(data["state"]),
            )
            finished = True
        except RunError as failure:
            finished = control is None or control.failure is None
            failure.turn_id = turn_id
            failure.new_items = items
            failure.usage = Usage(responses=responses)
            raise
        except (KeyError, TypeError, ValueError, OSError) as error:
            raise EngineError(f"Engine exchange failed: {error}") from error
        finally:
            if control is not None:
                await control.finish()
            if not finished:
                await self._close()
        yield result

run async

run(
    agent: Agent,
    input: str | None = None,
    *,
    text: str | None = None,
    environment: Environment | EllipsisType = ...,
    workspace: str | PathLike[str] | None = None,
    sandbox: Sandbox | None = None,
    state: ConversationState | None = None,
    store: ConversationStore | None = None,
    conversation_id: str | None = None,
) -> RunResult

Run one turn from an explicit snapshot or a conversation in a store.

Source code in src/openai_agents/codex/engine.py
async def run(
    self,
    agent: Agent,
    input: str | None = None,
    *,
    text: str | None = None,
    environment: Environment | EllipsisType = ...,
    workspace: str | os.PathLike[str] | None = None,
    sandbox: Sandbox | None = None,
    state: ConversationState | None = None,
    store: ConversationStore | None = None,
    conversation_id: str | None = None,
) -> RunResult:
    """Run one turn from an explicit snapshot or a conversation in a store."""
    text = _turn_input(input, text)
    return await _drain(
        self.stream(
            agent,
            text,
            environment=environment,
            workspace=workspace,
            sandbox=sandbox,
            state=state,
            store=store,
            conversation_id=conversation_id,
        )
    )

stream async

stream(
    agent: Agent,
    input: str | None = None,
    *,
    text: str | None = None,
    environment: Environment | EllipsisType = ...,
    workspace: str | PathLike[str] | None = None,
    sandbox: Sandbox | None = None,
    state: ConversationState | None = None,
    store: ConversationStore | None = None,
    conversation_id: str | None = None,
) -> AsyncGenerator[RunEvent, None]

Yield live events followed by a RunResult. Closing early shuts down this engine.

Source code in src/openai_agents/codex/engine.py
@_turn_stream
async def stream(
    self,
    agent: Agent,
    input: str | None = None,
    *,
    text: str | None = None,
    environment: Environment | EllipsisType = ...,
    workspace: str | os.PathLike[str] | None = None,
    sandbox: Sandbox | None = None,
    state: ConversationState | None = None,
    store: ConversationStore | None = None,
    conversation_id: str | None = None,
) -> AsyncGenerator[RunEvent, None]:
    """Yield live events followed by a RunResult. Closing early shuts down this engine."""
    text = _turn_input(input, text)
    if self._busy:
        raise EngineError("Engine is already busy")
    self._busy = True
    try:
        async with _lock_conversation(store, conversation_id, state) as conversation:
            target = _resolve_environment(environment, workspace, sandbox)
            callbacks = await self._open_session(agent, target, conversation.state)
            async with aclosing(self._stream_turn(text, callbacks)) as events:
                async for event in events:
                    if isinstance(event, RunResult):
                        result = event
                        break
                    yield event
                else:
                    raise EngineError("Stream ended before the result")
            await self._request("close", {})
            conversation.state = result.state
            if conversation_id is not None:
                result.state["session_id"] = conversation_id
    finally:
        self._busy = False
    yield result

LocalEnvironment dataclass

Run commands in a directory on the machine running the harness.

Source code in src/openai_agents/codex/environment.py
@dataclass(frozen=True, kw_only=True)
class LocalEnvironment:
    """Run commands in a directory on the machine running the harness."""

    workspace_directory: str | PathLike[str] = "."

EngineError

Bases: RuntimeError

Base SDK error, including engine startup, connection and protocol failures.

Source code in src/openai_agents/codex/errors.py
class EngineError(RuntimeError):
    """Base SDK error, including engine startup, connection and protocol failures."""

RunError

Bases: EngineError

A failed run with the items and usage observed before the failure.

Source code in src/openai_agents/codex/errors.py
class RunError(EngineError):
    """A failed run with the items and usage observed before the failure."""

    def __init__(self, message: str, *, code: str, details: dict[str, Any] | None = None) -> None:
        super().__init__(message)
        self.code = code
        self.details = details or {}
        self.turn_id: str | None = None
        self.new_items: list[RunItem] = []
        self.usage = Usage(responses=[])

ToolError

Bases: RunError

A Python handler failed. The original exception is available as cause.

Source code in src/openai_agents/codex/errors.py
class ToolError(RunError):
    """A Python handler failed. The original exception is available as __cause__."""

    def __init__(self, message: str, *, tool_name: str, call_id: str) -> None:
        super().__init__(message, code="tool_error")
        self.tool_name = tool_name
        self.call_id = call_id

Hook dataclass

A native Codex command hook on the agent's executor. Timeout is in seconds.

Source code in src/openai_agents/codex/hooks.py
@dataclass(frozen=True, kw_only=True)
class Hook:
    """A native Codex command hook on the agent's executor. Timeout is in seconds."""

    event: HookEvent
    command: str
    matcher: str | None = None
    timeout: int | None = None

    def __post_init__(self) -> None:
        if self.event not in get_args(HookEvent):
            raise ValueError(f"Unknown hook event {self.event!r}")
        if not self.command.strip():
            raise ValueError("Hook command is required")
        if self.timeout is not None and (type(self.timeout) is not int or self.timeout <= 0):
            raise ValueError("Hook timeout must be a positive integer")

ContextCompactionItem dataclass

Bases: _Item

Codex compacted the conversation history.

Source code in src/openai_agents/codex/items.py
@dataclass(frozen=True, kw_only=True)
class ContextCompactionItem(_Item):
    """Codex compacted the conversation history."""

    type: Literal["context_compaction"] = field(default="context_compaction", init=False)

id instance-attribute

id: str | None

Codex's item identifier, when supplied.

raw class-attribute instance-attribute

raw: dict[str, Any] = field(repr=False)

The underlying record, including any extra harness or provider fields.

UnknownItem dataclass

Bases: _Item

An additional Codex item, accessible through raw.

Source code in src/openai_agents/codex/items.py
@dataclass(frozen=True, kw_only=True)
class UnknownItem(_Item):
    """An additional Codex item, accessible through raw."""

    type: Literal["unknown"] = field(default="unknown", init=False)

id instance-attribute

id: str | None

Codex's item identifier, when supplied.

raw class-attribute instance-attribute

raw: dict[str, Any] = field(repr=False)

The underlying record, including any extra harness or provider fields.

ConversationState

Bases: dict[str, Any]

Conversation history through a completed or interrupted turn, ready to resume.

Source code in src/openai_agents/codex/result.py
class ConversationState(dict[str, Any]):
    """Conversation history through a completed or interrupted turn, ready to resume."""

    @property
    def thread_id(self) -> str:
        return cast(str, self["thread_id"])

    @property
    def session_id(self) -> str:
        return cast(str, self.get("session_id", self.thread_id))

    @property
    def codex_revision(self) -> str | None:
        """Codex commit that produced this snapshot, or None for older snapshots."""
        return self.get("codex_revision")

    def to_json(self) -> str:
        """Serialize the snapshot for storage or transfer."""
        return json.dumps(self, allow_nan=False)

    @classmethod
    def from_json(cls, data: str | bytes) -> "ConversationState":
        """Load a snapshot. The engine validates the history when resuming."""
        state = json.loads(data)
        if (
            not isinstance(state, dict)
            or not isinstance(state.get("thread_id"), str)
            or ("session_id" in state and not isinstance(state["session_id"], str))
            or type(state.get("version")) is not int
            or not isinstance(state.get("items"), list)
            or ("codex_revision" in state and not isinstance(state["codex_revision"], str))
        ):
            raise ValueError("Invalid conversation state")
        return cls(state)

codex_revision property

codex_revision: str | None

Codex commit that produced this snapshot, or None for older snapshots.

to_json

to_json() -> str

Serialize the snapshot for storage or transfer.

Source code in src/openai_agents/codex/result.py
def to_json(self) -> str:
    """Serialize the snapshot for storage or transfer."""
    return json.dumps(self, allow_nan=False)

from_json classmethod

from_json(data: str | bytes) -> ConversationState

Load a snapshot. The engine validates the history when resuming.

Source code in src/openai_agents/codex/result.py
@classmethod
def from_json(cls, data: str | bytes) -> "ConversationState":
    """Load a snapshot. The engine validates the history when resuming."""
    state = json.loads(data)
    if (
        not isinstance(state, dict)
        or not isinstance(state.get("thread_id"), str)
        or ("session_id" in state and not isinstance(state["session_id"], str))
        or type(state.get("version")) is not int
        or not isinstance(state.get("items"), list)
        or ("codex_revision" in state and not isinstance(state["codex_revision"], str))
    ):
        raise ValueError("Invalid conversation state")
    return cls(state)

RunResult dataclass

Output of one completed turn.

Source code in src/openai_agents/codex/result.py
@dataclass(kw_only=True)
class RunResult:
    """Output of one completed turn."""

    api_type: ClassVar[str] = "agent.session.turn.completed"

    turn_id: str
    final_output: str | None
    """The final assistant message, if the turn produced one."""

    new_items: list[RunItem]
    """Completed items from this turn, in stream order."""

    usage: Usage

    state: ConversationState = field(repr=False)
    """Snapshot through the end of this turn, ready to pass to another run."""

    type: Literal["result"] = field(default="result", init=False)

    @property
    def session_id(self) -> str:
        return self.state.session_id

    @property
    def output_text(self) -> str | None:
        return self.final_output

    @property
    def items(self) -> list[RunItem]:
        return self.new_items

final_output instance-attribute

final_output: str | None

The final assistant message, if the turn produced one.

new_items instance-attribute

new_items: list[RunItem]

Completed items from this turn, in stream order.

state class-attribute instance-attribute

state: ConversationState = field(repr=False)

Snapshot through the end of this turn, ready to pass to another run.

Sandbox dataclass

An executor address. Supply it each time you open or restore a conversation.

Source code in src/openai_agents/codex/sandbox/__init__.py
@dataclass(frozen=True, kw_only=True)
class Sandbox:
    """An executor address. Supply it each time you open or restore a conversation."""

    id: str
    url: str
    cwd: str | PathLike[str]
    token: str = field(repr=False)

    def __post_init__(self) -> None:
        if not self.id.strip() or self.id == "local":
            raise ValueError("Sandbox requires a non-empty id other than Codex's reserved 'local'")
        validate_url(self.url)
        validate_token(self.token)
        _cwd_uri(self.cwd)

    def _params(self) -> dict[str, str]:
        return {"id": self.id, "url": self.url, "cwd": _cwd_uri(self.cwd), "token": self.token}

Session

One live conversation. Open with async with agent.session() as session.

Source code in src/openai_agents/codex/session.py
class Session:
    """One live conversation. Open with `async with agent.session() as session`."""

    def __init__(
        self,
        agent: Agent | None,
        *,
        environment: Environment | EllipsisType = ...,
        workspace: str | PathLike[str] | None = None,
        sandbox: Sandbox | None = None,
        state: ConversationState | None = None,
        storage: SessionStorage | None = None,
        session_id: str | None = None,
    ) -> None:
        self._agent = agent
        if session_id is not None:
            _validate_id(session_id)
            if storage is None or state is not None:
                raise ValueError("Resume by session_id requires storage and excludes state")
        self._storage = storage
        self._resuming = session_id is not None
        self._id = session_id
        if storage is not None and session_id is None:
            self._id = f"sess_{uuid4().hex}"
        self._environment = _resolve_environment(environment, workspace, sandbox)
        self._state = ConversationState(deepcopy(state)) if state is not None else None
        self._engine = Engine()
        self._callbacks: _Callbacks | None = None
        self._lifecycle = asyncio.Lock()
        self._entered = False
        self._closing: asyncio.Task[None] | None = None
        self._turn: _Turn | None = None

    @classmethod
    def resume(
        cls,
        session_id: str,
        *,
        storage: SessionStorage,
        environment: Environment | EllipsisType = ...,
    ) -> Session:
        """Resume without an executor. Use agent.session() for current tools and permissions."""
        _validate_id(session_id)
        return cls(None, storage=storage, session_id=session_id, environment=environment)

    def _bind(self) -> Agent:
        if self._resuming and self._state is not None and "sdk_settings" in self._state:
            from openai_agents.codex._settings import SessionSettings

            settings = SessionSettings.read(self._state["sdk_settings"])
            if self._environment is ...:
                settings.require_no_executor()
                self._environment = None
            agent = settings.bind(self._agent)
            if self._environment is not None and self._agent is None:
                raise RunError(
                    "Supply an agent with agent.session() to resume with an executor",
                    code="session_bindings_required",
                )
            return agent
        if self._agent is None:
            raise RunError("Supply an agent with agent.session()", code="session_bindings_required")
        if self._resuming and self._environment is ...:
            raise RunError(
                "Supply environment= to resume this session", code="session_bindings_required"
            )
        return self._agent

    async def __aenter__(self) -> Session:
        async with self._lifecycle:
            if self._entered or self._closing is not None:
                raise EngineError("A session can only be opened once")
            self._entered = True
            await self._engine.__aenter__()
            try:
                async with self._lock() as record:
                    if self._resuming:
                        if record.state is None:
                            raise SessionNotFound(self.id)
                        self._state = record.state
                    elif self._storage is not None and record.state is not None:
                        raise EngineError(f"Session {self.id!r} already exists")
                    agent = self._bind()
                    callbacks = await self._engine._open_session(
                        agent,
                        self._environment,
                        self._state,
                        save_settings=self._storage is not None,
                    )
                    if self._storage is not None:
                        if self._state is None:
                            self._state = ConversationState(
                                await self._engine._request("prepare", {})
                            )
                        self._state["session_id"] = self.id
                        if not self._resuming:
                            self._state["sdk_settings"] = deepcopy(self._engine._settings)
                        self._engine._session_id = self.id
                        record.state = self._state
                    else:
                        self._id = self._engine._session_id
                self._callbacks = callbacks
            except BaseException:
                await self._engine._close()
                raise
            if self._closing is not None:
                raise EngineError("Session closed while opening")
        return self

    def _lock(self) -> AbstractAsyncContextManager[StoredConversation]:
        if self._storage is None:
            return nullcontext(StoredConversation(self._state))
        return self._storage.lock(self.id)

    async def __aexit__(self, *exc: object) -> None:
        await self.close()

    @property
    def id(self) -> str:
        """The conversation's stable ID, available from entry through shutdown."""
        if self._id is None:
            raise EngineError("Open the session to get its ID")
        return self._id

    def snapshot(self) -> ConversationState | None:
        """Copy the last completed or interrupted state, or the initial state before any turns."""
        return deepcopy(self._state)

    async def run(self, input: str | None = None, *, text: str | None = None) -> RunResult:
        """Run one turn on this conversation."""
        text = _turn_input(input, text)
        return await _drain(self.stream(text))

    @_turn_stream
    async def stream(
        self, input: str | None = None, *, text: str | None = None
    ) -> AsyncGenerator[RunEvent, None]:
        """Yield one turn's events and final result. Closing the iterator stops that turn."""
        text = _turn_input(input, text)
        if self._callbacks is None or self._closing is not None:
            raise EngineError("Session is closed. Open it with 'async with agent.session()'.")
        if self._turn is not None:
            raise EngineError("Session already has an active turn")
        if not isinstance(text, str) or not text.strip():
            raise RunError("Turn input is required", code="invalid_input")
        turn = self._turn = _Turn()
        turn.reader = asyncio.create_task(self._read_turn(turn, text, self._callbacks))
        try:
            while True:
                event = await turn.events.get()
                if isinstance(event, BaseException):
                    raise event
                yield event
                if isinstance(event, RunResult):
                    return
                turn.advance.set()
        finally:
            await turn.stop()

    async def _read_turn(
        self, turn: _Turn, text: str, callbacks: _Callbacks
    ) -> BaseException | None:
        try:
            async with self._lock() as record:
                if record.state != self._state:
                    raise RunError(
                        "Stored session changed. Reopen it by ID.", code="session_changed"
                    )
                try:
                    outcome: RunResult | _Interrupted = await self._forward(turn, text, callbacks)
                except _Interrupted as stopped:
                    outcome = stopped
                record.state = deepcopy(outcome.state)
            self._state = record.state
            turn.events.put_nowait(outcome)
            return None
        except (Exception, asyncio.CancelledError) as failure:
            # The live thread may have progressed beyond the last portable snapshot.
            self._callbacks = None
            turn.events.put_nowait(failure)
            await self._engine._close()
            return failure
        finally:
            self._turn = None

    async def _forward(self, turn: _Turn, text: str, callbacks: _Callbacks) -> RunResult:
        async with aclosing(self._engine._stream_turn(text, callbacks, turn.control)) as events:
            async for event in events:
                if isinstance(event, RunResult):
                    return event
                turn.advance.clear()
                turn.events.put_nowait(event)
                # Follow the consumer's pace until stop takes over draining events.
                if not turn.control.stopping:
                    await turn.advance.wait()
        raise EngineError("Stream ended before the result")

    async def interrupt(self) -> None:
        """Stop the active turn and wait until its snapshot is ready. Idle calls do nothing."""
        if self._turn is not None:
            await self._turn.stop()

    async def cancel(self) -> None:
        """Cancel the current turn and wait for its snapshot to be saved."""
        await self.interrupt()

    async def close(self) -> None:
        """Stop active work and shut down the session. Safe to call more than once."""
        if self._closing is None:
            self._closing = asyncio.create_task(self._shutdown())
        await asyncio.shield(self._closing)

    async def _shutdown(self) -> None:
        async with self._lifecycle:
            try:
                await self.interrupt()
                if self._callbacks is not None:
                    await self._engine._request("close", {})
            finally:
                self._callbacks = None
                await self._engine._close()

id property

id: str

The conversation's stable ID, available from entry through shutdown.

resume classmethod

resume(
    session_id: str,
    *,
    storage: SessionStorage,
    environment: Environment | EllipsisType = ...,
) -> Session

Resume without an executor. Use agent.session() for current tools and permissions.

Source code in src/openai_agents/codex/session.py
@classmethod
def resume(
    cls,
    session_id: str,
    *,
    storage: SessionStorage,
    environment: Environment | EllipsisType = ...,
) -> Session:
    """Resume without an executor. Use agent.session() for current tools and permissions."""
    _validate_id(session_id)
    return cls(None, storage=storage, session_id=session_id, environment=environment)

snapshot

snapshot() -> ConversationState | None

Copy the last completed or interrupted state, or the initial state before any turns.

Source code in src/openai_agents/codex/session.py
def snapshot(self) -> ConversationState | None:
    """Copy the last completed or interrupted state, or the initial state before any turns."""
    return deepcopy(self._state)

run async

run(
    input: str | None = None, *, text: str | None = None
) -> RunResult

Run one turn on this conversation.

Source code in src/openai_agents/codex/session.py
async def run(self, input: str | None = None, *, text: str | None = None) -> RunResult:
    """Run one turn on this conversation."""
    text = _turn_input(input, text)
    return await _drain(self.stream(text))

stream async

stream(
    input: str | None = None, *, text: str | None = None
) -> AsyncGenerator[RunEvent, None]

Yield one turn's events and final result. Closing the iterator stops that turn.

Source code in src/openai_agents/codex/session.py
@_turn_stream
async def stream(
    self, input: str | None = None, *, text: str | None = None
) -> AsyncGenerator[RunEvent, None]:
    """Yield one turn's events and final result. Closing the iterator stops that turn."""
    text = _turn_input(input, text)
    if self._callbacks is None or self._closing is not None:
        raise EngineError("Session is closed. Open it with 'async with agent.session()'.")
    if self._turn is not None:
        raise EngineError("Session already has an active turn")
    if not isinstance(text, str) or not text.strip():
        raise RunError("Turn input is required", code="invalid_input")
    turn = self._turn = _Turn()
    turn.reader = asyncio.create_task(self._read_turn(turn, text, self._callbacks))
    try:
        while True:
            event = await turn.events.get()
            if isinstance(event, BaseException):
                raise event
            yield event
            if isinstance(event, RunResult):
                return
            turn.advance.set()
    finally:
        await turn.stop()

interrupt async

interrupt() -> None

Stop the active turn and wait until its snapshot is ready. Idle calls do nothing.

Source code in src/openai_agents/codex/session.py
async def interrupt(self) -> None:
    """Stop the active turn and wait until its snapshot is ready. Idle calls do nothing."""
    if self._turn is not None:
        await self._turn.stop()

cancel async

cancel() -> None

Cancel the current turn and wait for its snapshot to be saved.

Source code in src/openai_agents/codex/session.py
async def cancel(self) -> None:
    """Cancel the current turn and wait for its snapshot to be saved."""
    await self.interrupt()

close async

close() -> None

Stop active work and shut down the session. Safe to call more than once.

Source code in src/openai_agents/codex/session.py
async def close(self) -> None:
    """Stop active work and shut down the session. Safe to call more than once."""
    if self._closing is None:
        self._closing = asyncio.create_task(self._shutdown())
    await asyncio.shield(self._closing)

SQLiteSessionStorage

Persist snapshots in a local database. Workers share the same file path.

Source code in src/openai_agents/codex/sqlite.py
class SQLiteSessionStorage:
    """Persist snapshots in a local database. Workers share the same file path."""

    def __init__(self, path: str | os.PathLike[str]) -> None:
        if os.fspath(path) == ":memory:":
            raise ValueError("Use InMemorySessionStorage for sessions in memory")
        self._path = Path(path).resolve()
        self._locks = self._path.with_name(self._path.name + ".locks")

    @staticmethod
    def _release(gate: sqlite3.Connection, lock: sqlite3.Connection, path: Path) -> None:
        # Keep other workers from opening the file between close and unlink.
        try:
            gate.execute("BEGIN EXCLUSIVE")
        finally:
            lock.close()
        path.unlink()

    def _load(self, stack: ExitStack, key: str) -> StoredConversation:
        self._locks.mkdir(mode=0o700, exist_ok=True)
        path = self._locks / hashlib.sha256(key.encode()).hexdigest()
        # Serialize file creation and removal. Only the per-ID lock spans the turn.
        gate = stack.enter_context(
            closing(sqlite3.connect(self._locks / "gate", check_same_thread=False))
        )
        with gate:
            gate.execute("BEGIN EXCLUSIVE")
            lock = sqlite3.connect(path, timeout=0, check_same_thread=False)
            try:
                lock.execute("BEGIN EXCLUSIVE")
            except sqlite3.Error as error:
                lock.close()
                if str(error) == "database is locked":
                    raise _busy(key) from error
                raise
            stack.callback(self._release, gate, lock, path)

        try:
            self._path.touch(mode=0o600, exist_ok=False)
        except FileExistsError:
            pass
        with closing(sqlite3.connect(self._path)) as db:
            db.execute(
                "CREATE TABLE IF NOT EXISTS agents_codex_conversations "
                "(conversation_id TEXT PRIMARY KEY, snapshot TEXT NOT NULL)"
            )
            row = db.execute(
                "SELECT snapshot FROM agents_codex_conversations WHERE conversation_id = ?",
                (key,),
            ).fetchone()
        return StoredConversation(ConversationState.from_json(row[0]) if row else None)

    def _save(self, key: str, state: ConversationState) -> None:
        snapshot = state.to_json()
        with closing(sqlite3.connect(self._path)) as db, db:
            db.execute(
                "INSERT INTO agents_codex_conversations (conversation_id, snapshot) VALUES (?, ?) "
                "ON CONFLICT (conversation_id) DO UPDATE SET snapshot = excluded.snapshot",
                (key, snapshot),
            )

    @asynccontextmanager
    async def lock(self, conversation_id: str) -> AsyncIterator[StoredConversation]:
        _validate_id(conversation_id)
        stack = ExitStack()
        try:
            record = await run_sync(lambda: self._load(stack, conversation_id))
            yield record
            state = record.state
            if state is not None:
                await run_sync(lambda: self._save(conversation_id, state))
        finally:
            await run_sync(stack.close)

ConversationStore

Bases: Protocol

Source code in src/openai_agents/codex/store.py
class ConversationStore(Protocol):
    def lock(self, conversation_id: str) -> AbstractAsyncContextManager[StoredConversation]:
        """Acquire exclusive access to the ID before reading its last committed state.

        Acquire even for an ID that has no snapshot yet. Yield a private copy.
        On normal exit, commit the new state if set, then release the lock.
        On exceptional exit, discard changes and release the lock. A worker
        that loses the lock must be unable to commit its snapshot.
        """
        ...

lock

lock(
    conversation_id: str,
) -> AbstractAsyncContextManager[StoredConversation]

Acquire exclusive access to the ID before reading its last committed state.

Acquire even for an ID that has no snapshot yet. Yield a private copy. On normal exit, commit the new state if set, then release the lock. On exceptional exit, discard changes and release the lock. A worker that loses the lock must be unable to commit its snapshot.

Source code in src/openai_agents/codex/store.py
def lock(self, conversation_id: str) -> AbstractAsyncContextManager[StoredConversation]:
    """Acquire exclusive access to the ID before reading its last committed state.

    Acquire even for an ID that has no snapshot yet. Yield a private copy.
    On normal exit, commit the new state if set, then release the lock.
    On exceptional exit, discard changes and release the lock. A worker
    that loses the lock must be unable to commit its snapshot.
    """
    ...

InMemorySessionStorage

Share snapshots by ID for the lifetime of this object.

Source code in src/openai_agents/codex/store.py
class InMemorySessionStorage:
    """Share snapshots by ID for the lifetime of this object."""

    def __init__(self) -> None:
        self._states: dict[str, ConversationState] = {}
        self._active: set[str] = set()
        self._guard = Lock()

    @asynccontextmanager
    async def lock(self, conversation_id: str) -> AsyncIterator[StoredConversation]:
        _validate_id(conversation_id)
        with self._guard:
            if conversation_id in self._active:
                raise _busy(conversation_id)
            self._active.add(conversation_id)
        try:
            stored = StoredConversation(deepcopy(self._states.get(conversation_id)))
            yield stored
            if stored.state is not None:
                self._states[conversation_id] = deepcopy(stored.state)
        finally:
            with self._guard:
                self._active.remove(conversation_id)

StoredConversation dataclass

The snapshot held under a lock. A new conversation starts with state=None.

Source code in src/openai_agents/codex/store.py
@dataclass
class StoredConversation:
    """The snapshot held under a lock. A new conversation starts with state=None."""

    state: ConversationState | None

TurnStream

Bases: AsyncGenerator[RunEvent, None]

Stream one turn, retaining its final result after delivery.

Source code in src/openai_agents/codex/stream.py
class TurnStream(AsyncGenerator[RunEvent, None]):
    """Stream one turn, retaining its final result after delivery."""

    def __init__(self, events: AsyncGenerator[RunEvent, None]) -> None:
        self._events = events
        self._result: RunResult | None = None

    async def __aenter__(self) -> TurnStream:
        return self

    async def __aexit__(self, *exc: object) -> None:
        await self.aclose()

    def _observe(self, event: RunEvent) -> RunEvent:
        if isinstance(event, RunResult):
            self._result = event
        return event

    async def asend(self, value: None, /) -> RunEvent:
        return self._observe(await self._events.asend(value))

    async def athrow(self, *args: Any) -> RunEvent:
        return self._observe(await self._events.athrow(*args))

    async def aclose(self) -> None:
        await self._events.aclose()

    async def get_final_result(self) -> RunResult:
        """Consume any remaining events and return the completed turn."""
        if self._result is None:
            async for _ in self:
                pass
        if self._result is None:
            raise EngineError("Stream ended before the result")
        return self._result

get_final_result async

get_final_result() -> RunResult

Consume any remaining events and return the completed turn.

Source code in src/openai_agents/codex/stream.py
async def get_final_result(self) -> RunResult:
    """Consume any remaining events and return the completed turn."""
    if self._result is None:
        async for _ in self:
            pass
    if self._result is None:
        raise EngineError("Stream ended before the result")
    return self._result

FunctionTool dataclass

Declaration of a function the model can ask the application to call.

Source code in src/openai_agents/codex/tool.py
@dataclass(kw_only=True)
class FunctionTool:
    """Declaration of a function the model can ask the application to call."""

    name: str
    description: str
    parameters: dict[str, Any]
    """JSON Schema describing the function's arguments."""

    handler: Callable[[dict[str, Any]], str | Awaitable[str]] | None = None
    """Application callback that receives the decoded arguments and returns text."""

    needs_approval: bool = False
    """Ask the agent's approval handler before each invocation."""

    type: Literal["function"] = field(default="function", init=False)

parameters instance-attribute

parameters: dict[str, Any]

JSON Schema describing the function's arguments.

handler class-attribute instance-attribute

handler: (
    Callable[[dict[str, Any]], str | Awaitable[str]] | None
) = None

Application callback that receives the decoded arguments and returns text.

needs_approval class-attribute instance-attribute

needs_approval: bool = False

Ask the agent's approval handler before each invocation.

WebSearchTool dataclass

Declaration of the built-in web search tool.

Source code in src/openai_agents/codex/tool.py
@dataclass(kw_only=True)
class WebSearchTool:
    """Declaration of the built-in web search tool."""

    type: Literal["web_search"] = field(default="web_search", init=False)

TokenUsage dataclass

Provider counts. Cached and reasoning tokens are subsets of input and output.

Source code in src/openai_agents/codex/usage.py
@dataclass(frozen=True, kw_only=True)
class TokenUsage:
    """Provider counts. Cached and reasoning tokens are subsets of input and output."""

    input_tokens: int
    cached_input_tokens: int
    cache_write_input_tokens: int
    output_tokens: int
    reasoning_output_tokens: int
    total_tokens: int

Usage dataclass

Source code in src/openai_agents/codex/usage.py
@dataclass(frozen=True, kw_only=True)
class Usage:
    responses: list[ResponseUsage]
    """One entry per completed model response in this turn, in arrival order."""

    thread: TokenUsage | None = None
    """All reported tokens in the conversation through the completed turn."""

    model_context_window: int | None = None

    @property
    def turn(self) -> TokenUsage | None:
        """Exact total for these responses, when all supplied usage."""
        counts = [response.tokens for response in self.responses if response.tokens is not None]
        if not counts or len(counts) != len(self.responses):
            return None
        return TokenUsage(
            input_tokens=sum(c.input_tokens for c in counts),
            cached_input_tokens=sum(c.cached_input_tokens for c in counts),
            cache_write_input_tokens=sum(c.cache_write_input_tokens for c in counts),
            output_tokens=sum(c.output_tokens for c in counts),
            reasoning_output_tokens=sum(c.reasoning_output_tokens for c in counts),
            total_tokens=sum(c.total_tokens for c in counts),
        )

responses instance-attribute

responses: list[ResponseUsage]

One entry per completed model response in this turn, in arrival order.

thread class-attribute instance-attribute

thread: TokenUsage | None = None

All reported tokens in the conversation through the completed turn.

turn property

turn: TokenUsage | None

Exact total for these responses, when all supplied usage.

codex_version

codex_version() -> str

Return the Codex version linked into this SDK.

Source code in src/openai_agents/codex/engine.py
def codex_version() -> str:
    """Return the Codex version linked into this SDK."""
    return str(_native().codex_version)

local_sandbox async

local_sandbox(
    cwd: str | PathLike[str] = ".", *, id: str | None = None
) -> AsyncIterator[Sandbox]

Run a private exec-server on a kernel-assigned loopback port for this block.

Source code in src/openai_agents/codex/sandbox/__init__.py
@asynccontextmanager
async def local_sandbox(
    cwd: str | PathLike[str] = ".", *, id: str | None = None
) -> AsyncIterator[Sandbox]:
    """Run a private exec-server on a kernel-assigned loopback port for this block."""
    directory = await asyncio.to_thread(Path(cwd).resolve, strict=True)
    token = secrets.token_urlsafe(32)
    async with loopback_server(digest(token), cwd=directory) as (_, url):
        yield Sandbox(
            id=id if id is not None else f"sandbox-{secrets.token_hex(8)}",
            url=url,
            cwd=str(directory),
            token=token,
        )

function_tool

function_tool(
    func: _Function,
    *,
    name_override: str | None = None,
    description_override: str | None = None,
    needs_approval: bool = False,
) -> FunctionTool
function_tool(
    *,
    name_override: str | None = None,
    description_override: str | None = None,
    needs_approval: bool = False,
) -> Callable[[_Function], FunctionTool]
function_tool(
    func: _Function | None = None,
    *,
    name_override: str | None = None,
    description_override: str | None = None,
    needs_approval: bool = False,
) -> FunctionTool | Callable[[_Function], FunctionTool]

Turn a sync or async function into a tool using its signature and docstring.

Source code in src/openai_agents/codex/tool.py
def function_tool(
    func: _Function | None = None,
    *,
    name_override: str | None = None,
    description_override: str | None = None,
    needs_approval: bool = False,
) -> FunctionTool | Callable[[_Function], FunctionTool]:
    """Turn a sync or async function into a tool using its signature and docstring."""

    def decorate(fn: _Function) -> FunctionTool:
        name = fn.__name__ if name_override is None else name_override
        doc = docstring_parser.parse(inspect.getdoc(fn) or "")
        description = description_override
        if description is None:
            separator = "\n\n" if doc.blank_after_short_description else "\n"
            description = separator.join(
                filter(None, (doc.short_description, doc.long_description))
            )

        descriptions = {p.arg_name.lstrip("*"): p.description for p in doc.params}
        signature = inspect.signature(fn)
        adapter, kwargs_name = _tool_arguments(fn, signature, descriptions)

        async def handler(arguments: dict[str, Any]) -> str:
            bound = inspect.BoundArguments(
                signature, OrderedDict(adapter.validate_python(arguments))
            )
            # Expand **kwargs separately so Python catches duplicate keywords.
            extra = bound.arguments.pop(kwargs_name) if kwargs_name else {}
            if inspect.iscoroutinefunction(fn):
                result = fn(*bound.args, **bound.kwargs, **extra)
            else:
                result = await run_sync(lambda: fn(*bound.args, **bound.kwargs, **extra))
            if inspect.isawaitable(result):
                result = await result
            if isinstance(result, str):
                return result
            return _result_adapter.dump_json(result).decode()

        return FunctionTool(
            name=name,
            description=description,
            parameters=adapter.json_schema(),
            handler=handler,
            needs_approval=needs_approval,
        )

    return decorate if func is None else decorate(func)