OpenAI Codex turns natural-language instructions into code edits and files. Run it inside an E2B Sandbox and you get an isolated, long-running environment where the agent can safely create files, install tools, and execute without interactive prompts.
What we’ll build
- Spin up an E2B sandbox from the prebuilt
codextemplate. - Inject your OpenAI API key into the sandbox.
- Run a Codex prompt that creates a Hello World file.
- Print the output and shut the sandbox down.
See full example in the E2B Cookbook.
Components we’ll use
- E2B Python SDK: creates and controls the sandbox.
- Prebuilt template:
codex– Codex CLI is preinstalled. - OpenAI API: used by Codex via CODEX_API_KEY, which holds your OpenAI API key.
Prerequisites
- Python 3.11+
- E2B account +
E2B_API_KEY - OpenAI API key
Outline
- Create the project
- Add the files (pyproject.toml, main.py)
- Set E2B_API_KEY and CODEX_API_KEY in .env
- Install with pip and run
1) Create the project
Create and commit .gitignore before .env so secrets never enter git history.
Target structure:
2) Files to add
File: pyproject.toml
File: src/openai_codex_in_sandbox_python/main.py
This script loads .env (so the SDK sees E2B_API_KEY), creates the sandbox from the codex template while injecting your OpenAI key, runs a Codex exec prompt that generates index.html, prints the result, and then shuts the sandbox down.
Load configuration and SDK:
Create the sandbox (OpenAI key read from .env and passed in as CODEX_API_KEY) and log its ID:
Run a Codex prompt that creates a file (no per-command timeout), and shut the sandbox down even if the run fails:
File: .gitignore
File: .env
3) Set up and install
4) Run the example
Expected: console output from Codex. The generated index.html lives inside the sandbox filesystem.
See full example in the E2B Cookbook.
