How the Codex runtime works
A model decides whether to answer or request a tool. The runtime sends model requests, runs tool calls, and returns tool results to the model until the turn ends. In v1, openai_agents.Runner uses the actual Rust Codex core for this loop inside your Python process. Your application supplies its own functions and access controls. Codex handles the repeated model and tool calls and manages the conversation context.
Follow an order lookup through one turn
Suppose a customer asks when their order will arrive. Only your application knows how to look up an order. You can give Codex a Python function that does just that. After the installation check, set OPENAI_API_KEY and OPENAI_MODEL as in the quickstart. Save the example as orders.py and run python orders.py. It uses sample order data and makes billable model requests.
import asyncio
import os
from openai_agents import Agent, Runner
from openai_agents.codex import function_tool
@function_tool
def delivery_date(order_id: str) -> str:
"""Look up the expected delivery date for an order."""
return {"A12": "Friday"}.get(order_id, "Unknown order")
async def main():
agent = Agent(
model=os.environ["OPENAI_MODEL"],
instructions="Use delivery_date to check the order before you answer.",
tools=[delivery_date],
)
result = await Runner.run(agent, "When will order A12 arrive?")
print(result.output_text)
if __name__ == "__main__":
asyncio.run(main())
When the model requests the lookup, the turn goes through four steps.
- Python starts the turn.
Runner.run(agent, prompt)passes the prompt, instructions, and tool definition through a Python binding (PyO3) to the Rust Codex engine in the same process.agent.run(prompt)takes the same path. - Codex calls the model. The model sees the description and argument schema for
delivery_date. It can request a call withorder_id="A12". The function body stays in your application. - Python runs the tool. The SDK dispatches the call to
delivery_dateon your worker. Codex adds the returned value,Friday, to the conversation and sends the next request. A turn can include several tool calls. - Python receives the result. When the model finishes, the result includes the reply, the items produced during the turn, usage, and a checkpoint. For a live UI, use
agent.stream(prompt)to receive events as the turn progresses.
In a real application, check that the current user can access the order inside the tool. For a tool that changes an address, you can use @function_tool(needs_approval=True) and provide an approval_handler on the agent. The approval handler decides whether to allow that invocation.
Where code runs
The wheel embeds Codex in your Python worker, so you don't have to start a Codex service or manage a CLI process for each conversation. Sessions in a worker share a Rust async runtime (Tokio). Each session has its own history and callbacks. The model still runs remotely. Commands can use helper processes.
A new session starts without built-in shell or file tools. Pass an environment to agent.run() or agent.session() when the task needs them.
| Environment | Where shell commands and file operations run |
|---|---|
Omitted on a new session, or None |
No built-in shell or file executor. The order lookup above works in this mode. |
LocalEnvironment(workspace_directory="./repo") |
On the worker, in the workspace you select. |
Sandbox(...) |
On the Codex execution server you connect to. |
Import LocalEnvironment and Sandbox from openai_agents.codex. In all three cases, Python function tools run on your worker with your application's permissions. A sandbox for commands does not move Python functions into that sandbox.
Investigate a failing test
Make a disposable copy of your repository at ./repo-copy. Prepare the test dependencies in that copy. Set OPENAI_API_KEY and OPENAI_MODEL as in the quickstart, then save this script as investigate.py outside the copy. The agent can change files in ./repo-copy and make billable model requests.
import asyncio
import os
from openai_agents import Agent
from openai_agents.codex import LocalEnvironment
async def main():
agent = Agent(model=os.environ["OPENAI_MODEL"])
result = await agent.run(
"Investigate the failing test, fix the cause, and rerun the test.",
environment=LocalEnvironment(workspace_directory="./repo-copy"),
)
print(result.output_text)
if __name__ == "__main__":
asyncio.run(main())
Run python investigate.py from the directory containing repo-copy. Codex can give the test output to the model, apply a requested edit, and rerun the test. Inspect the resulting diff and test output before using the changes.
Set approval_handler if your application needs to review commands or patches that Codex asks to approve. If you omit approval_policy, Codex uses on-request when you provide an approval_handler or set guardian=True. Otherwise, it uses never. For native commands and patches, never means Codex does not request approval. The never policy does not by itself determine whether a command is allowed or blocked.
What survives the turn
Use async with agent.session() as session and call await session.run(...) for each message in a conversation. Codex manages the context across turns. To continue after the worker exits, pass a session store such as SQLiteSessionStorage when opening the session, or save result.state yourself.
A checkpoint includes conversation history, including the histories of open child agents. It doesn't copy workspace files. Keep checkpoints private. When resuming by ID with agent.session(storage=..., session_id=..., environment=...), supply the current agent's tools, approval policy, and execution environment. See the two-turn SQLite example.
If your server forks workers, start them before opening Codex sessions or use Python's spawn multiprocessing context. The native runtime shares the worker's lifetime.
For the design behind the loop, see Unrolling the Codex agent loop and Unlocking the Codex harness. The latter describes the App Server, another way to embed the same core. The Python SDK calls the core in process.