Skip to content

Engine

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

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)