Embed the Codex agent in your Python workflows and applications.
The Python SDK wraps the bundled codex binary. It spawns the CLI and exchanges JSONL events over stdin/stdout.
pip install codex-sdkRequires Python 3.8+.
import asyncio
from codex_sdk import Codex
async def main():
codex = Codex()
thread = codex.start_thread()
turn = await thread.run("Diagnose the test failure and propose a fix")
print(turn.final_response)
print(turn.items)
if __name__ == "__main__":
asyncio.run(main())Call run() repeatedly on the same Thread instance to continue that conversation.
next_turn = await thread.run("Implement the fix")run() buffers events until the turn finishes. To react to intermediate progress—tool calls, streaming responses, and file diffs—use run_streamed() instead, which returns an async generator of structured events.
async def main():
codex = Codex()
thread = codex.start_thread()
result = await thread.run_streamed("Diagnose the test failure and propose a fix")
async for event in result.events:
if event.type == "item.completed":
print("item", event.item)
elif event.type == "turn.completed":
print("usage", event.usage)
if __name__ == "__main__":
asyncio.run(main())The Codex agent can produce a JSON response that conforms to a specified schema. The schema can be provided for each turn as a plain JSON object.
import asyncio
from codex_sdk import Codex, TurnOptions
async def main():
schema = {
"type": "object",
"properties": {
"summary": {"type": "string"},
"status": {"type": "string", "enum": ["ok", "action_required"]},
},
"required": ["summary", "status"],
"additionalProperties": False,
}
codex = Codex()
thread = codex.start_thread()
turn_options = TurnOptions(output_schema=schema)
turn = await thread.run("Summarize repository status", turn_options)
print(turn.final_response)
if __name__ == "__main__":
asyncio.run(main())Threads are persisted in ~/.codex/sessions. If you lose the in-memory Thread object, reconstruct it with resume_thread() and keep going.
import asyncio
import os
from codex_sdk import Codex
async def main():
saved_thread_id = os.environ["CODEX_THREAD_ID"]
codex = Codex()
thread = codex.resume_thread(saved_thread_id)
await thread.run("Implement the fix")
if __name__ == "__main__":
asyncio.run(main())Codex runs in the current working directory by default. To avoid unrecoverable errors, Codex requires the working directory to be a Git repository. You can skip the Git repository check by passing the skip_git_repo_check option when creating a thread.
import asyncio
from codex_sdk import Codex, ThreadOptions
async def main():
codex = Codex()
thread_options = ThreadOptions(
working_directory="/path/to/project",
skip_git_repo_check=True
)
thread = codex.start_thread(thread_options)
if __name__ == "__main__":
asyncio.run(main())The main class for interacting with the Codex agent.
Creates a new Codex instance.
Parameters:
options: Optional configuration options
Starts a new conversation with an agent.
Parameters:
options: Optional thread configuration options
Returns:
- A new thread instance
Resumes a conversation with an agent based on the thread id.
Parameters:
thread_id: The id of the thread to resumeoptions: Optional thread configuration options
Returns:
- A new thread instance
Represents a thread of conversation with the agent.
Provides the input to the agent and returns the completed turn.
Parameters:
input: The input to send to the agentturn_options: Optional turn configuration options
Returns:
- A completed turn with items, final response, and usage
Provides the input to the agent and streams events as they are produced during the turn.
Parameters:
input: The input to send to the agentturn_options: Optional turn configuration options
Returns:
- A result containing an async generator of events
codex_path_override: Optional[str] - Override the path to the codex binarybase_url: Optional[str] - Base URL for the APIapi_key: Optional[str] - API key for authentication
model: Optional[str] - Model to use for the threadsandbox_mode: Optional[SandboxMode] - Sandbox mode for the threadworking_directory: Optional[str] - Working directory for the threadskip_git_repo_check: Optional[bool] - Skip Git repository check
output_schema: Optional[Any] - JSON schema describing the expected agent output
The SDK provides various event types that can be streamed:
ThreadStartedEvent: Emitted when a new thread is startedTurnStartedEvent: Emitted when a turn is startedTurnCompletedEvent: Emitted when a turn is completedTurnFailedEvent: Indicates that a turn failed with an errorItemStartedEvent: Emitted when a new item is added to the threadItemUpdatedEvent: Emitted when an item is updatedItemCompletedEvent: Signals that an item has reached a terminal stateThreadErrorEvent: Represents an unrecoverable error
The SDK provides various item types that represent different actions and outputs:
AgentMessageItem: Response from the agentReasoningItem: Agent's reasoning summaryCommandExecutionItem: A command executed by the agentFileChangeItem: A set of file changes by the agentMcpToolCallItem: A call to an MCP toolWebSearchItem: A web search requestTodoListItem: The agent's running to-do listErrorItem: A non-fatal error surfaced as an item
git clone https://github.com/openai/codex.git
cd codex/sdk/python
pip install -e ".[dev]"pytestblack src tests
isort src testsmypy srcApache-2.0