Codex SDK Programmatic Setup
Introduction
Welcome back to Mastering Advanced AI Tooling in Codex. In the previous unit, we explored the two primary CLI execution modes: single shot commands for quick advice and exec mode for autonomous action.
Those tools are great for interactive work, but now we’ll take the next step: programmatically driving the same “run → validate → react” loop using the Python SDK, so the workflow becomes durable automation you can run in CI, cron jobs, or internal tooling.
Why Not Just Use "codex exec"?
If codex exec already automates execution, why write Python scripts at all?
The CLI is a convenience wrapper around agent execution—optimized for human interaction in a terminal. However, it offers limited composability, opaque prompt packaging, and no native integration with your existing Python tooling.
By contrast, the SDK provides:
- Pipeline embedding: Call Codex from within CI/CD jobs, test runners, or data workflows
- Structured integration: Parse outputs, chain calls, and combine results with other Python logic
- Prompt control: Explicitly engineer instructions and contexts rather than relying on CLI defaults
- Composability: Mix model intelligence with file I/O, API calls, and custom validation logic
When you need repeatable automation—not just an interactive assistant—the SDK is the right abstraction.
From Interactive to Automated: A Programmable "exec" Loop
Manual CLI interactions require your presence, and the context of each session disappears when the terminal closes. That’s fine for ad-hoc help, but it breaks down when you need a repeatable execution contract.
In this lesson, we’ll implement a lightweight programmable version of exec:
- Run real commands (tests/build/lint)
- Check exit codes
- Only consult the model when something fails
- Persist a fix plan as an artifact
This pattern is durable, inspectable, and easy to wire into existing automation.
Foundation and Imports
We’ll use:
subprocessto run commands and capture outputosto create artifact directoriesOpenAIfrom the official SDK
Set this environment variable:
OPENAI_API_KEY(the SDK reads it automatically)
We’ll define the model name directly in code to keep execution consistent across environments.
