Back to All Cheatsheet Libraries cheatsheets

OpenAI Codex

Model and API parameter reference plus setup guidance for building with OpenAI's Codex/code-focused models.

"Codex" means something completely different now

If you remember Codex as the 2021 code-davinci model behind early Copilot — that was deprecated in 2023 and is gone. Codex today is a coding agent, written in Rust, that runs locally in your terminal. Same name, unrelated product.

It runs on four surfaces: the CLI, an IDE extension (VS Code, Cursor, Windsurf), a desktop app, and Codex Web in the cloud at chatgpt.com/codex.

# macOS / Linux curl -fsSL https://chatgpt.com/codex/install.sh | sh # Windows (PowerShell) powershell -ExecutionPolicy ByPass -c "irm https://chatgpt.com/codex/install.ps1 | iex" # Package managers npm install -g @openai/codex brew install --cask codex codex # start it codex app # launch the desktop app

Sign in with your ChatGPT plan (Plus, Pro, Business, Edu, Enterprise) — that is the recommended path and needs no API key. An API key works too but requires extra setup and bills separately.

Subcommand Purpose
codexInteractive TUI session. The default.
codex exec "task"Non-interactive. The scriptable surface — run a task, get output, exit. This is what you use in CI.
codex reviewRun a code review non-interactively.
codex applyApply the agent's latest diff as a git apply.
codex resume / forkResume or branch a previous session — picker by default.
codex queueQueue a message for an existing session.
codex archive / unarchive / deleteSession lifecycle management.
codex agentsBrowse all agent sessions on the shared local daemon.
codex sandboxRun arbitrary commands inside Codex's sandbox — useful on its own.
codex mcpManage external MCP servers.
codex mcp-serverRuns Codex itself as an MCP server over stdio, so another agent can drive it.
codex pluginManage Codex plugins.
codex login / logoutAuthentication.
codex doctorDiagnose the install and update to the latest version.
codex completionGenerate shell completion scripts.
codex cloudExperimental — browse Codex Cloud tasks and apply changes locally.
codex execpolicyExecution-policy tooling.
codex featuresInspect feature flags.
AGENTS.md and configuration
  • AGENTS.md is Codex's project-instruction file — the equivalent of CLAUDE.md. Generate one with /init.
  • It is an open, cross-tool convention, not an OpenAI-only format — several agents read it.
  • Config lives in ~/.codex/config.toml. Admins can enforce policy through requirements.toml, including allow_managed_hooks_only to ignore user and project hook configs.
  • /import pulls your setup, project config and recent chats across from Claude Code — a genuinely useful migration path in either direction.
Group Command What it does
Session/modelchoose what model and reasoning effort to use
Setup/ide—
Security/permissionschoose what Codex is allowed to do
Setup/keymapremap TUI shortcuts
Setup/vimtoggle Vim mode for the composer
Security/setup-default-sandboxset up elevated agent sandbox
Security/sandbox-add-read-dir—
Setup/experimentaltoggle experimental features
Security/approveapprove one retry of a recent auto-review denial
Context/memoriesconfigure memory use and generation
Setup/skillsuse skills to improve how Codex performs specific tasks
Setup/importimport setup, this project, and recent chats from Claude Code
Setup/hooksview and manage lifecycle hooks
Code/reviewreview my current changes and find issues
Session/renamerename the current thread
Session/newstart a new chat during a conversation
Session/archivearchive this session and exit
Session/deletepermanently delete this session and exit
Session/resumeresume a saved chat
Session/forkfork the current chat
Surfaces/appcontinue this session in the Desktop app
Context/initcreate an AGENTS.md file with instructions for Codex
Context/compactsummarize conversation to prevent hitting the context limit
Session/planswitch to Plan mode
Session/goalset or view the goal for a long-running task
Agents/agentsview and switch between all active agent sessions
Agents/side—
Session/btw—
Output/copycopy the last response, code block, or quote
Output/exportexport the conversation as markdown
Output/rawtoggle raw scrollback mode for copy-friendly terminal selection
Code/diffshow git diff (including untracked files)
Context/mentionmention a file
Info/statusshow current session configuration and token usage
Files/cdchange the current working directory
Files/pwdshow the current working directory
Info/usageview account usage or use a usage limit reset
Info/debug-configshow config layers and requirement sources for debugging
Setup/titleconfigure which items appear in the terminal title
Setup/statuslineconfigure which items appear in the status line
Setup/themechoose a syntax highlighting theme
Extras/petschoose or hide the terminal pet
Integrations/mcplist configured MCP tools; use /mcp verbose for details
Integrations/appsmanage apps
Integrations/pluginsbrowse plugins
Account/logoutlog out of Codex
Session/quit—
Session/exitexit Codex
Info/feedbacksend logs to maintainers
Info/rolloutprint the rollout file path
Processes/pslist background terminals
Processes/stopstop all background terminals
Session/clearclear the terminal and start a new chat
Setup/personalitychoose a communication style for Codex
Agents/subagentsswitch between this session's subagents

Codex the agent and the OpenAI API are different things

Worth separating before anything else, because the naming invites confusion. Codex is the coding agent you run. The OpenAI API is what you call from your own code. Codex uses the API underneath, but "generating an image with Codex" and "generating an image with the API" are two different operations.

This tab covers the API. The next covers what the agent produces on disk.

# The Responses API is the current primary interface from openai import OpenAI client = OpenAI() # reads OPENAI_API_KEY resp = client.responses.create( model="gpt-5.6", input="Summarise this changelog in three bullets.", ) print(resp.output_text) # Chat Completions still works and is widely supported resp = client.chat.completions.create( model="gpt-5.6", messages=[{"role": "user", "content": "Hello"}], )

Generating images

Two routes, and the choice matters

The Image API (/v1/images/generations) for standalone image work. The Responses API with the built-in image_generation tool when the image is part of a conversation — the model then decides whether to create a new image or edit one already in the thread.

# Standalone — Image API result = client.images.generate( model="gpt-image-2", prompt="A cutaway diagram of a server rack, technical illustration", size="1536x1024", quality="high", output_format="png", # png (default) | jpeg | webp background="transparent", # transparent | opaque | auto ) # Returns base64-encoded image data # In-conversation — Responses API tool resp = client.responses.create( model="gpt-5.6", input="Draw the architecture we just discussed, then label the cache layer.", tools=[{"type": "image_generation"}], )
Model Notes
gpt-image-2Current flagship. Accepts custom resolutions, not just fixed presets.
gpt-image-1.5Previous generation.
gpt-image-1Older.
gpt-image-1-miniSmaller and cheaper.
Size constraints that will reject your request
  • Common sizes: 1024x1024, 1536x1024, 1024x1536, 2048x2048, 3840x2160. Default is auto.
  • Max edge 3840px. Dimensions must be multiples of 16.
  • Aspect ratio capped at 3:1 — no ultra-wide banners in one shot.
  • Total pixels must fall between 655,360 and 8,294,400.
  • quality: low / medium / high / auto. output_compression (0–100) applies to JPEG and WebP only.
  • Output is base64-encoded in the response — you decode and write the file yourself.

PDFs, ZIPs and everything else

There is no PDF endpoint. There is no ZIP endpoint.

Images are the only file type with a dedicated generation API. Everything else — PDF, ZIP, XLSX, DOCX, CSV, charts — is produced by the Code Interpreter tool, which runs Python in a sandboxed container and writes real files.

If you have been searching the API reference for a document endpoint, this is why you have not found one.

# Code Interpreter — works with Responses, Chat Completions and Assistants container = client.containers.create(name="report-box", memory_limit="4g") resp = client.responses.create( model="gpt-5.6", tools=[{"type": "code_interpreter", "container": container.id}], input="Read the attached CSV, chart revenue by month, " "and save a PDF report plus a ZIP of the source charts.", ) # Generated files come back as annotations on the response: # container_file_citation -> { container_id, file_id, filename } # Retrieve each with the "Retrieve container file content" endpoint.
Container limits worth knowing before you build on it
  • A container expires after 20 minutes idle, and expired containers are inaccessible. Download generated files before then — this is the single most common way people lose output.
  • Memory tiers: 1 GB (default), 4 GB, 16 GB, 64 GB. Set memory_limit at creation for anything data-heavy.
  • Rate limit: 100 requests per minute per organisation.
  • Files are retrieved by container_file_citation annotation, not returned inline — you must make a second call per file.
  • Inputs it accepts: CSV, JSON, PDF, XLSX, DOCX, PPTX, images, source code, ZIP and TAR archives.

What Codex can generate on the fly

There is no fixed list, because Codex does not have "file export" as a feature. It writes text files directly, and produces every binary format by writing a script and running it. The practical limit is which libraries are installed, not which formats are blessed.

How Formats Needs
Written directly.md .txt .csv .tsv .json .yaml .toml .xml .html .svg .css .js .ts .py .rs .go .sh .sql .ipynb .env and any other plain textNothing. No code executed, no library required.
Script.pdfreportlab, weasyprint, or render HTML → PDF. Merging and form-filling via pypdf.
Script.xlsx .xlsmopenpyxl for formulas and formatting, pandas for bulk data.
Script.docx .pptxpython-docx, python-pptx, or the JS equivalents.
Script.zip .tar .tar.gz .gzShell zip/tar, or Python zipfile/tarfile. Nothing to install.
Script.png .jpg .webp .gifmatplotlib / plotly for charts, Pillow for manipulation. Rendered from code, not drawn.
Script.parquet .sqlite .db .featherpandas, pyarrow, sqlite3.
API call.png .jpeg .webp from a promptAn OpenAI API key and gpt-image-2. The only format generated by a model rather than by code.
The limits that actually bite
  • Context, not file size, is the constraint. Reading a large CSV into the conversation wastes the window and degrades the answer. Tell Codex to process it with pandas instead — the file then never enters context and size stops mattering.
  • The sandbox governs where files can be written. Codex confines writes by default; /permissions and /setup-default-sandbox control it. A script that writes outside the workspace will be blocked, not silently fail.
  • XLSX caps at 1,048,576 rows × 16,384 columns per sheet — an Excel format limit, not a Codex one. Beyond that, split sheets or use Parquet.
  • Codex cannot see the rendered output. It writes plotting code without looking at the chart, so clipped labels and unreadable colour choices go unnoticed unless you check.
  • Missing libraries are a permission prompt, not magic — Codex will offer to install them.

Gotchas

Worth knowing
  • The old Codex model is dead. Any tutorial referencing code-davinci-002 is describing a product retired in 2023 and unrelated to this one.
  • Container files vanish after 20 minutes idle. If you build a pipeline on Code Interpreter, download before the container expires or the output is gone.
  • Images return as base64, not a URL. You decode and save them yourself.
  • Image dimensions must be multiples of 16, max edge 3840, aspect ratio within 3:1. Requests outside those bounds are rejected rather than clamped.
  • Piping an install script straight to a shell is convenient, not careful. Release binaries are on GitHub if you would rather inspect first.
  • codex mcp-server makes Codex controllable by another agent — powerful, and worth understanding before enabling.
  • Codex moves fast; the CLI is Rust and Apache-2.0, so when docs and behaviour disagree, the repo is the answer.

Tips

codex exec for automation

The non-interactive surface. Run a task, capture stdout, exit with a status code — the right entry point for CI, cron and scripts.

/import from Claude Code

Brings your setup, project config and recent chats across. If you are evaluating both, this removes most of the switching cost.

Write an AGENTS.md

/init generates one. It is a cross-tool open convention, so the same file guides several agents — not effort spent on one vendor.

Set permissions deliberately

/permissions and /setup-default-sandbox decide what Codex may touch. Choose once, properly, rather than approving prompt after prompt.

/ps and /stop

Background terminals keep running. /ps lists them, /stop kills them all — useful after a session that spawned dev servers.

Size the container up front

Code Interpreter defaults to 1 GB. Pass memory_limit="4g" or higher at creation for real datasets — you cannot resize it later.

Resources