Skip to main content

OpenAI Codex CLI Complete Tutorial

Installation, Configuration and Usage Guide - Support for Direct API Connection in China
📖 Contents Covered:This article provides detailed instructions on how to install and configure OpenAI Codex CLI, combined with GPT Proto Aggregation API, which can be used directly in China without configuring a proxy. Supports Windows/Linux/Mac multi-platform, and can be configured with third-party IDEs such as VS Code.

1. Codex CLI Introduction and System Requirements

What is OpenAI Codex?

OpenAI Codex is an open-source command-line tool (CLI) that serves as a lightweight coding agent, capable of reading, modifying, and running code in the terminal. Codex is based on GPT models and is specifically optimized for code generation and understanding.

System Requirements

ItemRequirement
Officially Supported SystemsmacOS and Linux (Recommended)
Windows UsersStrongly recommend using Windows Subsystem for Linux (WSL)
Node.js VersionNode.js 18+ (Required)
npm Versionnpm 10.x.x or higher

2. Codex CLI Installation Tutorial

Installation Steps (Using Ubuntu as Example)

Step 1: Update System Packages
sudo apt update && sudo apt upgrade -y
Step 2: Add NodeSource Repository (Node.js 22) Visit Node.js official website for the latest version information.
curl -fsSL https://deb.nodesource.com/setup_22.x | sudo -E bash -
Step 3: Install Node.js and npm
sudo apt install nodejs -y
Step 4: Verify Installation
node --version  # Should display v22.x.x
npm --version   # Should display 10.x.x or higher
Step 5: Install Codex CLI Install Codex CLI globally via npm:
sudo npm install -g @openai/codex@latest
Step 6: Verify Installation
codex --version  # Should display version number, e.g., 0.40.0
🎉 Congratulations! Codex CLI installation is complete!

macOS Installation Method

macOS users are recommended to use Homebrew for installation: 1. Install Homebrew (if not installed)
/bin/bash -c "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/HEAD/install.sh)"
2. Install Node.js
brew install node
3. Install Codex CLI
npm install -g @openai/codex@latest

Windows (WSL) Installation Method

Windows users need to install WSL first, then follow the Ubuntu installation steps. 1. Install WSL Open PowerShell as administrator and run:
wsl --install
For detailed instructions, refer to Microsoft WSL Installation Documentation 2. Continue After Restarting After restarting, follow the Ubuntu installation steps above to complete Codex CLI installation.

3. Codex CLI Configuration Tutorial

Configure API Key

1. Get API Key
Recommended: Use GPT Proto Aggregation API (Direct Connection in China)Visit https://gptproto.com to get API Key
  • ✅ Direct connection in China, no proxy needed
  • ✅ Supports multiple OpenAI models
  • ✅ Affordable pricing, pay-as-you-go
2. Temporary Configuration (Valid for Current Session)
export OPENAI_API_KEY="sk-your-GPT_Proto-key"
3. Permanent Configuration (Recommended) Edit shell configuration file:
# For bash users
nano ~/.bashrc

# For zsh users
nano ~/.zshrc
Add the following content:
export OPENAI_API_KEY="sk-your-GPT_Proto-key"
Make configuration effective:
# bash users
source ~/.bashrc

# zsh users
source ~/.zshrc

Configure config.toml

Default configuration file path: ~/.codex/config.toml Official configuration documentation: Codex Configuration Documentation Basic Configuration Example
# ~/.codex/config.toml

model = "gpt-5-codex"
model_provider = "openai-chat-completions"

[model_providers.openai-chat-completions]
name = "OpenAI using Chat Completions"
base_url = "https://gptproto.com/v1"
env_key = "OPENAI_API_KEY"
wire_api = "chat"
Configuration Explanation:
  • model: Model name to use (e.g., gpt-4, gpt-3.5-turbo, etc.)
  • model_provider: Model provider configuration
  • base_url: API base address (using GPT Proto Aggregation API)
  • env_key: Environment variable name
  • wire_api: API type (chat or completions)
Advanced Configuration Options
# Advanced configuration example

model = "gpt-5-codex"
model_provider = "openai-response"
temperature = 0.7
max_tokens = 2000

[model_providers.openai-chat-completions]
name = "OpenAI using Chat Completions"
base_url = "https://gptproto.com/v1"
env_key = "OPENAI_API_KEY"
wire_api = "response"

[ui]
theme = "dark"  # or "light"
show_token_count = true

4. IDE Integration Configuration

VS Code Integration

For third-party IDEs (such as VS Code), you need to install the corresponding Codex plugin. Installation Steps
  1. Search for “OpenAI Codex” in VS Code extension store
  2. Install the official extension
  3. Configure Codex CLI path in settings
  4. Configure API Key (using the environment variable above)

Other IDE Support

IDESupport StatusDescription
VS CodeOfficial SupportFull plugin support
JetBrains SeriesCommunity SupportIntegrated through terminal
Vim/NeovimCommunity SupportSupported through plugins

5. Getting Started with Codex CLI

Initialize Project

# Navigate to project directory
cd /path/to/your/project

# Start Codex
codex

Common Command Examples

1. Basic Prompt
codex "Fix this bug: add error handling at line 42 in main.py"
2. Specify Model
codex -m gpt-4 "Build a simple web server"
3. Specify Operation Mode
codex --mode full-auto "Deploy ML model to Vercel"
4. Interactive Mode
# Start interactive session
codex

# Use commands in interactive mode
> Help me refactor this function
> Add unit tests
> Optimize performance

Common Interactive Commands

CommandFunction Description
/helpDisplay help information
/exit or Ctrl+CExit Codex
/clearClear conversation history
/configView current configuration
/model <name>Switch model
/tokensView token usage

Usage Scenario Examples

Scenario 1: Code Generation
codex "Create a Python function to calculate the nth Fibonacci number"
Scenario 2: Code Review
codex "Review auth.js file and find potential security issues"
Scenario 3: Bug Fixing
codex "Fix memory leak issue in app.py"
Scenario 4: Test Generation
codex "Generate complete unit tests for user_service.py"
Scenario 5: Documentation Generation
codex "Generate API documentation for the entire project"

6. Troubleshooting and Common Issues

Common Issue Solutions

1. Permission Issues
Problem: Encountering permission error “EACCES: permission denied”Solution:
# Method 1: Use sudo
sudo npm install -g @openai/codex

# Method 2: Modify npm global directory permissions (recommended)
mkdir ~/.npm-global
npm config set prefix '~/.npm-global'
echo 'export PATH=~/.npm-global/bin:$PATH' >> ~/.bashrc
source ~/.bashrc
2. Node Version Issues
Problem: Node.js version too lowSolution:
# Use nvm to manage Node.js versions
curl -o- https://raw.githubusercontent.com/nvm-sh/nvm/v0.39.0/install.sh | bash
nvm install 22
nvm use 22
3. Network Connection Issues
Problem: Cannot connect to APISolution:
  • Confirm API Key is configured correctly
  • Check if base_url configuration is correct
  • Use GPT Proto to ensure direct connection in China
  • Verify network connection: curl https://gptproto.com/v1/models
4. Invalid API Key
Problem: “Invalid API Key” errorSolution:
# Check environment variable
echo $OPENAI_API_KEY

# Reset API Key
export OPENAI_API_KEY="sk-your-key"

# Verify configuration
codex --help

Verify Configuration

# Check environment variable
echo $OPENAI_API_KEY

# Check Codex configuration
codex --help

# Test API connection
codex "Hello, Codex!"

# View version information
codex --version

# View configuration file
cat ~/.codex/config.toml

Debug Mode

Enable verbose log output to help diagnose issues:
# Enable debug mode
export DEBUG=codex:*
codex "test command"

# View log file
tail -f ~/.codex/logs/codex.log

7. Advanced Usage Tips

1. Custom Prompt Templates

Create commonly used prompt templates to improve efficiency:
# ~/.codex/templates/review.txt
Please review the following code, focusing on:
1. Code readability and maintainability
2. Performance optimization opportunities
3. Potential security vulnerabilities
4. Whether it follows best practices

# Use template
codex --template review.txt file.py

2. Batch Processing

# Batch process multiple files
for file in src/*.py; do
    codex "Add type annotations to $file"
done

3. Git Integration

# Review uncommitted changes
git diff | codex "Review these code changes"

# Generate commit message
git diff --cached | codex "Generate a clear commit message"

4. Configure Aliases

Add aliases in ~/.bashrc or ~/.zshrc:
alias cdx="codex"
alias cdx-review="codex --mode review"
alias cdx-test="codex --mode test"
alias cdx-doc="codex --mode documentation"

8. Best Practice Recommendations

RecommendationDescription
Clear PromptsProvide clear, specific instructions, explaining expected output format and requirements
Context InformationProvide sufficient context, such as project tech stack, coding standards, etc.
Iterative OptimizationGradually improve code through multiple rounds of dialogue, rather than expecting perfection in one go
Code ReviewAlways review AI-generated code to ensure it meets project standards
Version ControlUse Git to track changes for easy rollback and comparison
Security AwarenessDon’t send sensitive information (keys, passwords, etc.) to AI
Cost ControlMonitor token usage to avoid unnecessary API calls

Official Resources

Third-Party Resources


Summary

Through this guide, you have successfully:
  • ✅ Understood basic concepts and features of OpenAI Codex CLI
  • ✅ Installed Codex CLI on Linux/macOS/Windows systems
  • ✅ Configured GPT Proto Aggregation API (direct connection in China)
  • ✅ Mastered basic usage methods and common commands
  • ✅ Understood IDE integration methods
  • ✅ Learned troubleshooting and problem solving
  • ✅ Mastered advanced usage tips and best practices
🚀 You can now start enjoying the efficient coding experience brought by Codex CLI!

Need Help?

If you encounter problems during use:
© 2025 OpenAI Codex CLI Tutorial | Complete Installation Configuration Guide Thank you for using Codex CLI - Let AI be your programming assistant Recommended to use GPT Proto for stable direct connection API service in China