Skip to content

OpenAI Codex CLI | Official Setup & Configuration Guide

OpenAI Codex CLI - Official Guide

Codex is OpenAI’s official command-line coding agent. It integrates deeply with OpenAI’s models and is designed specifically for software development tasks.

Overview

Codex provides:

  • Deep OpenAI integration - Best-in-class GPT-4o performance
  • Agentic coding - Autonomous task execution with safety controls
  • Sandboxed execution - Runs code in isolated environments
  • Multi-file editing - Coordinates changes across your codebase

Key Features

FeatureDescription
GPT-4o PoweredUses the latest OpenAI models
SandboxedCode runs in secure containers
Multi-fileEdits multiple files in one session
Git-awareUnderstands your repository structure
Review modeShows changes before applying

Installation

Requirements

  • macOS (Linux/Windows coming soon)
  • OpenAI API key
  • Node.js 18+

Install

Terminal window
npm install -g @openai/codex

Or with Homebrew:

Terminal window
brew install openai/codex/codex

Configuration

API Key Setup

Terminal window
export OPENAI_API_KEY="sk-..."

Add to your shell profile for persistence:

Terminal window
echo 'export OPENAI_API_KEY="sk-..."' >> ~/.zshrc

Config File (~/.codex/config.json)

{
"model": "gpt-4o",
"approvalMode": "suggest", // or "auto" or "manual"
"sandbox": {
"enabled": true,
"allowedDirs": ["/path/to/project"]
},
"git": {
"requireClean": false,
"autoCommit": false
}
}

Approval Modes

ModeDescription
suggestShows proposed changes, asks for confirmation (default)
autoAutomatically applies safe changes
manualAsks before every action

Usage

Interactive Mode

Terminal window
codex

Single Task

Terminal window
codex "Add error handling to the login function"

With File Context

Terminal window
codex -f src/auth.js "Refactor authentication"

With Directory Context

Terminal window
codex -d src/ "Implement user profile page"

Quiet Mode (non-interactive)

Terminal window
codex --quiet "Generate unit tests for utils.js"

Common Commands

Code Generation

Terminal window
# Generate a function
codex "Create a function to validate email addresses"
# Generate with tests
codex "Create a stack implementation with unit tests"
# Generate React component
codex "Create a modal component with TypeScript"

Refactoring

Terminal window
# Refactor for performance
codex "Optimize this database query"
# Modernize code
codex "Convert this to use async/await"
# Add types
codex "Add TypeScript types to this file"

Code Review

Terminal window
# Review for bugs
codex "Find potential bugs in src/"
# Security review
codex "Check for security vulnerabilities"
# Performance review
codex "Identify performance bottlenecks"

Documentation

Terminal window
# Generate docstrings
codex "Add JSDoc comments to all functions"
# Update README
codex "Update README with new API endpoints"

Working with Context

Include Files

Terminal window
# Specific files
codex -f src/auth.js -f src/users.js "Implement password reset"
# Glob patterns
codex -f "src/**/*.js" "Refactor error handling"

Include Images (for UI tasks)

Terminal window
codex -i mockup.png "Create this UI component"

Git Integration

Terminal window
# Works with git state
codex "Fix the bug introduced in the last commit"
# Considers staged changes
codex "Complete the partial implementation"

Safety Features

Sandboxed Execution

All code execution happens in isolated containers:

  • File system access is restricted
  • Network access can be disabled
  • Resource limits prevent runaway processes

Approval Flow

Review changes before they’re applied:

Terminal window
# See diff before applying
codex "Add logging" --approval suggest
# Review each file
codex "Refactor codebase" --approval manual

Rollback

Undo changes if something goes wrong:

Terminal window
# Codex tracks all changes
codex --undo

Advanced Usage

Custom Instructions

Create .codex/instructions.md for project-specific guidance:

# Project Guidelines
## Code Style
- Use functional React components
- Prefer async/await over callbacks
- Always handle errors explicitly
## Testing
- Write tests for all new functions
- Use Jest and React Testing Library
- Aim for >80% coverage
## Architecture
- Follow MVC pattern
- Use dependency injection
- Keep functions under 50 lines

Multiple Models

Terminal window
# Use specific model
codex --model gpt-4o "Complex refactoring task"
# Use faster model
codex --model gpt-4o-mini "Simple edits"

Batch Processing

Terminal window
# Process multiple tasks
codex -f tasks.md
# tasks.md contains:
# 1. Fix typo in README
# 2. Add input validation
# 3. Update dependencies

Pricing

Codex uses your OpenAI API key. Costs depend on:

  • Model used (GPT-4o vs GPT-4o-mini)
  • Number of tokens processed
  • Number of tool calls made

Typical costs:

  • Small tasks: $0.01-0.10
  • Medium refactoring: $0.10-0.50
  • Large codebase changes: $0.50-2.00

Comparison

FeatureCodexClaude CodeOpenCodeHermes
ProviderOpenAI onlyAnthropic onlyAnyAny
Sandboxing⚠️
Multi-file
Autonomous⚠️
Open SourcePartial
PriceUsage-based$20/moFreeFree

Troubleshooting

”API key not found"

Terminal window
# Verify key is set
echo $OPENAI_API_KEY
# Set it
export OPENAI_API_KEY="sk-..."

"Model not available”

  • Check your OpenAI account has access to the model
  • Try a different model: --model gpt-4o-mini
  • Verify billing is set up

”Sandbox failed”

  • Disable sandbox: --sandbox false
  • Check Docker is running (if using container sandbox)
  • Add directory to allowed list in config

Changes not applied

  • Check approval mode isn’t set to suggest
  • Verify you confirmed the changes
  • Check file permissions

Rate limit errors

  • Add rate limiting: --rate-limit 10/minute
  • Switch to GPT-4o-mini for lower costs
  • Upgrade your OpenAI tier

Best Practices

  1. Start with suggest mode - Review changes before applying
  2. Use specific prompts - Clear instructions get better results
  3. Provide context - Use -f and -d flags for relevant files
  4. Commit first - Always commit before major refactoring
  5. Review carefully - AI can make mistakes, always review output
  6. Monitor costs - Keep an eye on your OpenAI usage dashboard

Resources