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
| Feature | Description |
|---|---|
| GPT-4o Powered | Uses the latest OpenAI models |
| Sandboxed | Code runs in secure containers |
| Multi-file | Edits multiple files in one session |
| Git-aware | Understands your repository structure |
| Review mode | Shows changes before applying |
Installation
Requirements
- macOS (Linux/Windows coming soon)
- OpenAI API key
- Node.js 18+
Install
npm install -g @openai/codexOr with Homebrew:
brew install openai/codex/codexConfiguration
API Key Setup
export OPENAI_API_KEY="sk-..."Add to your shell profile for persistence:
echo 'export OPENAI_API_KEY="sk-..."' >> ~/.zshrcConfig 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
| Mode | Description |
|---|---|
suggest | Shows proposed changes, asks for confirmation (default) |
auto | Automatically applies safe changes |
manual | Asks before every action |
Usage
Interactive Mode
codexSingle Task
codex "Add error handling to the login function"With File Context
codex -f src/auth.js "Refactor authentication"With Directory Context
codex -d src/ "Implement user profile page"Quiet Mode (non-interactive)
codex --quiet "Generate unit tests for utils.js"Common Commands
Code Generation
# Generate a functioncodex "Create a function to validate email addresses"
# Generate with testscodex "Create a stack implementation with unit tests"
# Generate React componentcodex "Create a modal component with TypeScript"Refactoring
# Refactor for performancecodex "Optimize this database query"
# Modernize codecodex "Convert this to use async/await"
# Add typescodex "Add TypeScript types to this file"Code Review
# Review for bugscodex "Find potential bugs in src/"
# Security reviewcodex "Check for security vulnerabilities"
# Performance reviewcodex "Identify performance bottlenecks"Documentation
# Generate docstringscodex "Add JSDoc comments to all functions"
# Update READMEcodex "Update README with new API endpoints"Working with Context
Include Files
# Specific filescodex -f src/auth.js -f src/users.js "Implement password reset"
# Glob patternscodex -f "src/**/*.js" "Refactor error handling"Include Images (for UI tasks)
codex -i mockup.png "Create this UI component"Git Integration
# Works with git statecodex "Fix the bug introduced in the last commit"
# Considers staged changescodex "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:
# See diff before applyingcodex "Add logging" --approval suggest
# Review each filecodex "Refactor codebase" --approval manualRollback
Undo changes if something goes wrong:
# Codex tracks all changescodex --undoAdvanced 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 linesMultiple Models
# Use specific modelcodex --model gpt-4o "Complex refactoring task"
# Use faster modelcodex --model gpt-4o-mini "Simple edits"Batch Processing
# Process multiple taskscodex -f tasks.md
# tasks.md contains:# 1. Fix typo in README# 2. Add input validation# 3. Update dependenciesPricing
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
| Feature | Codex | Claude Code | OpenCode | Hermes |
|---|---|---|---|---|
| Provider | OpenAI only | Anthropic only | Any | Any |
| Sandboxing | ✅ | ✅ | ❌ | ⚠️ |
| Multi-file | ✅ | ✅ | ✅ | ✅ |
| Autonomous | ⚠️ | ❌ | ✅ | ✅ |
| Open Source | ❌ | ❌ | ✅ | Partial |
| Price | Usage-based | $20/mo | Free | Free |
Troubleshooting
”API key not found"
# Verify key is setecho $OPENAI_API_KEY
# Set itexport 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
- Start with suggest mode - Review changes before applying
- Use specific prompts - Clear instructions get better results
- Provide context - Use
-fand-dflags for relevant files - Commit first - Always commit before major refactoring
- Review carefully - AI can make mistakes, always review output
- Monitor costs - Keep an eye on your OpenAI usage dashboard