Skip to content

Latest commit

 

History

History
 
 

README.md

Codex SDK for Python

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.

Installation

pip install codex-sdk

Requires Python 3.8+.

Quickstart

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")

Streaming responses

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())

Structured output

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())

Resuming an existing thread

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())

Working directory controls

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())

API Reference

Codex

The main class for interacting with the Codex agent.

Codex(options: Optional[CodexOptions] = None)

Creates a new Codex instance.

Parameters:

  • options: Optional configuration options

start_thread(options: Optional[ThreadOptions] = None) -> Thread

Starts a new conversation with an agent.

Parameters:

  • options: Optional thread configuration options

Returns:

  • A new thread instance

resume_thread(thread_id: str, options: Optional[ThreadOptions] = None) -> Thread

Resumes a conversation with an agent based on the thread id.

Parameters:

  • thread_id: The id of the thread to resume
  • options: Optional thread configuration options

Returns:

  • A new thread instance

Thread

Represents a thread of conversation with the agent.

run(input: str, turn_options: Optional[TurnOptions] = None) -> Turn

Provides the input to the agent and returns the completed turn.

Parameters:

  • input: The input to send to the agent
  • turn_options: Optional turn configuration options

Returns:

  • A completed turn with items, final response, and usage

run_streamed(input: str, turn_options: Optional[TurnOptions] = None) -> RunStreamedResult

Provides the input to the agent and streams events as they are produced during the turn.

Parameters:

  • input: The input to send to the agent
  • turn_options: Optional turn configuration options

Returns:

  • A result containing an async generator of events

Configuration Options

CodexOptions

  • codex_path_override: Optional[str] - Override the path to the codex binary
  • base_url: Optional[str] - Base URL for the API
  • api_key: Optional[str] - API key for authentication

ThreadOptions

  • model: Optional[str] - Model to use for the thread
  • sandbox_mode: Optional[SandboxMode] - Sandbox mode for the thread
  • working_directory: Optional[str] - Working directory for the thread
  • skip_git_repo_check: Optional[bool] - Skip Git repository check

TurnOptions

  • output_schema: Optional[Any] - JSON schema describing the expected agent output

Event Types

The SDK provides various event types that can be streamed:

  • ThreadStartedEvent: Emitted when a new thread is started
  • TurnStartedEvent: Emitted when a turn is started
  • TurnCompletedEvent: Emitted when a turn is completed
  • TurnFailedEvent: Indicates that a turn failed with an error
  • ItemStartedEvent: Emitted when a new item is added to the thread
  • ItemUpdatedEvent: Emitted when an item is updated
  • ItemCompletedEvent: Signals that an item has reached a terminal state
  • ThreadErrorEvent: Represents an unrecoverable error

Item Types

The SDK provides various item types that represent different actions and outputs:

  • AgentMessageItem: Response from the agent
  • ReasoningItem: Agent's reasoning summary
  • CommandExecutionItem: A command executed by the agent
  • FileChangeItem: A set of file changes by the agent
  • McpToolCallItem: A call to an MCP tool
  • WebSearchItem: A web search request
  • TodoListItem: The agent's running to-do list
  • ErrorItem: A non-fatal error surfaced as an item

Development

Setup

git clone https://github.com/openai/codex.git
cd codex/sdk/python
pip install -e ".[dev]"

Running Tests

pytest

Code Formatting

black src tests
isort src tests

Type Checking

mypy src

License

Apache-2.0