> ## Documentation Index
> Fetch the complete documentation index at: https://docs.aiandgpu.com/llms.txt
> Use this file to discover all available pages before exploring further.

# Codex

Installation, configuration and usage guide - Support for direct API connection in China

# OpenAI Codex CLI Complete Tutorial

[**Codex**](https://openai.com/index/openai-codex/) is an AI coding assistant developed by OpenAI. It helps developers write, debug, and improve code using natural language instructions.

<Note>
  **📖 Contents Covered:**

  This guide explains how to install and set up the [**OpenAI Codex CLI**](https://openai.com/index/openai-codex/) using the [**AGCloud Aggregation API**](https://developer.aiandgpu.com), enabling direct usage in China without the need for a proxy. It supports Windows, Linux, and macOS, and can be integrated with third-party IDEs like VS Code.
</Note>

## 1. Codex CLI Introduction and System Requirements

> [**Codex AI**](https://openai.com/index/openai-codex/) is an AI-powered coding assistant developed by OpenAI. It can understand natural language instructions and help developers with software tasks such as writing code, fixing bugs, refactoring, and generating pull requests. Codex works across tools like terminals, IDEs, and web interfaces, and is designed to make software development faster and more efficient by acting as an intelligent partner that can read and modify your codebase in context.

### **System Requirements**

| **Item**                     | **Requirement**                                                                                                         |
| :--------------------------- | :---------------------------------------------------------------------------------------------------------------------- |
| Officially Supported Systems | macOS and Linux (Recommended)                                                                                           |
| Windows Users                | Strongly recommend using [**Windows Subsystem for Linux (WSL)**](https://learn.microsoft.com/en-us/windows/wsl/install) |
| Node.js Version              | Node.js 18+ (Required)                                                                                                  |
| npm Version                  | npm 10 or higher                                                                                                        |

## 2.  Codex CLI Installation

### 2.1 Linux(Ubuntu) Installation

**Step 1: Update System Packages**

```shellscript theme={null}
sudo apt update && sudo apt upgrade -y
```

**Step 2: Add NodeSource Repository (Node.js 22)**

Visit [**Node.js official website**](https://nodejs.org/) for the latest version information.

```shellscript theme={null}
curl -fsSL https://deb.nodesource.com/setup_22.x | sudo -E bash -
```

**Step 3: Install Node.js and npm**

```shellscript theme={null}
sudo apt install nodejs -y
```

**Step 4: Verify Installation**

```shellscript theme={null}
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:

```shellscript theme={null}
sudo npm install -g @openai/codex@latest
```

**Step 6: Verify Installation**

```shellscript theme={null}
codex --version  # Should display version number, e.g., 0.40.0
```

<Check>
  **🎉 Congratulations! Codex CLI installation is complete!**
</Check>

### 2.2 macOS Installation

macOS users are recommended to use [**Homebrew**](https://brew.sh/) for installation:

**1. Install Homebrew**

```shellscript theme={null}
/bin/bash -c "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/HEAD/install.sh)"
```

**2. Install Node.js**

```shellscript theme={null}
brew install node
```

**3. Install Codex CLI**

```shellscript theme={null}
npm install -g @openai/codex@latest
```

### 2.3 Windows (WSL) Installation

Windows users need to install WSL first, then follow the Ubuntu installation steps.

**1. Install WSL**

Open PowerShell as administrator and run:

```shellscript theme={null}
wsl --install
```

For detailed instructions, refer to [**Microsoft WSL Installation Documentation**](https://learn.microsoft.com/en-us/windows/wsl/install)

**2. Continue After Restarting**

After restarting, follow the Ubuntu installation steps above to complete Codex CLI installation.

## 3. Codex CLI Configuration Tutorial

### 1. Get You API Key

<Tip>
  \*\*Recommended: Use AGCloud Aggregation API (Direct Connection in China)\*\*Visit [**https://developer.aiandgpu.com**](https://developer.aiandgpu.com) to get API Key

  * ✅ Direct connection in China, no proxy needed
  * ✅ Supports multiple OpenAI models
  * ✅ Affordable pricing, pay-as-you-go
</Tip>

**2. Temporary Configuration (Valid for Current Session)**

```shellscript theme={null}
export OPEN_API_KEY="<YOUR_API_KEY>"
```

**3. Permanent Configuration (Recommended)**

Edit shell configuration file:

```shellscript theme={null}
# Check your shell
echo $SHELL
# /bin/zsh or /bin bash

# For bash users
nano ~/.bashrc

# For zsh users
nano ~/.zshrc
```

Add the following content:

```shellscript theme={null}
export OPEN_API_KEY="<YOUR_API_KEY>"
```

Make configuration effective:

```shellscript theme={null}
# bash users
source ~/.bashrc

# zsh users
source ~/.zshrc
```

### Windows Environment Variables & Model Configuration

#### PowerShell Environment Variables

<Note>
  Run the following commands in PowerShell. To persist them, add the same lines to `$PROFILE` or set them through **System Properties → Environment Variables**.
</Note>

```powershell theme={null}
$env:OPEN_API_KEY = "<YOUR_API_KEY>"
$env:CODEX_DEFAULT_MODEL = "gpt-5-codex"
$env:CODEX_BACKUP_MODEL = "gpt-4.1"
```

#### Reload Your Profile

```powershell theme={null}
# Restart PowerShell or reload your profile manually
. $PROFILE
```

#### Configure Models in config.toml

On Windows, the Codex CLI config file lives at `C:\Users\<USERNAME>\.codex\config.toml`. Use it to persist your model choices and AGCloud endpoint:

```toml theme={null}
model = "gpt-5-codex"
model_provider = "agcloud"
temperature = 0.7
max_tokens = 2000
model_reasoning_effort = "medium"

[model_providers.agcloud]
name = "OpenAI Compatible"
base_url = "https://aiandgpu.com/v1"
env_key = "OPEN_API_KEY"

wire_api = "responses"
```

<Tip>
  Need different models per task? Set `CODEX_DEFAULT_MODEL` (primary) and `CODEX_BACKUP_MODEL` (fallback) as environment variables, then reference them inside `config.toml` using `${CODEX_DEFAULT_MODEL}` syntax where supported.
</Tip>

### Configure config.toml

Default configuration file path:`~/.codex/config.toml`

Official configuration documentation:[**Codex Configuration Documentation**](https://github.com/openai/openai-codex/blob/main/docs/configuration.md)

<Note>
  **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 AGCloud Aggregation API)
  * `env_key`: Environment variable name
  * `wire_api`: API type (chat or completions)
</Note>

**Basic Configuration Options**

```toml theme={null}
model = "gpt-5-codex"
model_provider = "agcloud"
temperature = 0.7
max_tokens = 2000
model_reasoning_effort = "medium"

[model_providers.agcloud]
name = "OpenAI Compatible"
base_url = "https://aiandgpu.com/v1"
env_key = "OPEN_API_KEY"

wire_api = "responses"

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

**VS Code Integration**

For third-party IDEs (such as [**VS Code**](https://code.visualstudio.com/)), 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

| **IDE**          | **Support Status** | **Description**             |
| :--------------- | :----------------- | :-------------------------- |
| VS Code          | Official Support   | Full plugin support         |
| JetBrains Series | Community Support  | Integrated through terminal |
| Vim/Neovim       | Community Support  | Supported through plugins   |

## 5. Getting Started with Codex CLI

### Initialize Project

```shellscript theme={null}
# Navigate to project directory
cd /path/to/your/project

# Start Codex
codex
```

**Common Command Examples**

**1. Basic Prompt**

```shellscript theme={null}
codex "Fix this bug: add error handling at line 42 in main.py"
```

**2. Specify Model**

```shellscript theme={null}
codex -m gpt-4 "Build a simple web server"
```

**3. Specify Operation Mode**

```shellscript theme={null}
codex --mode full-auto "Deploy ML model to Vercel"
```

**4. Interactive Mode**

```shellscript theme={null}
# Start interactive session
codex

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

| **Command**         | **Function Description**   |
| :------------------ | :------------------------- |
| `/help`             | Display help information   |
| `/exit` or `Ctrl+C` | Exit Codex                 |
| `/clear`            | Clear conversation history |
| `/config`           | View current configuration |
| `/model <name>`     | Switch model               |
| `/tokens`           | View token usage           |

### Usage Scenario Examples

**Scenario 1: Code Generation**

```shellscript theme={null}
codex "Create a Python function to calculate the nth Fibonacci number"
```

**Scenario 2: Code Review**

```shellscript theme={null}
codex "Review auth.js file and find potential security issues"
```

**Scenario 3: Bug Fixing**

```shellscript theme={null}
codex "Fix memory leak issue in app.py"
```

**Scenario 4: Test Generation**

```shellscript theme={null}
codex "Generate complete unit tests for user_service.py"
```

**Scenario 5: Documentation Generation**

```shellscript theme={null}
codex "Generate API documentation for the entire project"
```

## 6. Troubleshooting and Common Issues

### **Common Issue Solutions**

**1. Permission Issues**

<Warning>
  Encountering permission error “EACCES: permission denied”
</Warning>

**Solution:**

```shellscript theme={null}
# 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**

<Warning>
  Node.js version lower than 22.
</Warning>

**Solution:**

```shellscript theme={null}
# 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**

<Warning>
  Cannot connect to API.
</Warning>

**Solution:**

* Confirm API Key is configured correctly
* Check if `base_url` configuration is correct
* Use [**AGCloud**](https://aiandgpu.com) to ensure direct connection in China
* Verify network connection: `curl https://aiandgpu.com/v1/models`

**4. Invalid API Key**

<Warning>
  “Invalid API Key” error
</Warning>

**Solution:**

```shellscript theme={null}
# Check environment variable
echo $OPEN_API_KEY

# Reset API Key
export OPEN_API_KEY="<YOUR_API_KEY>"

# Verify configuration
codex --help
```

**5.Model configuration missing**

<Warning>
  Unexpected status 404 Not Found: Model configuration missing.
</Warning>

**Solution:** See: **[https://aiandgpu.com/v1/models](https://aiandgpu.com/v1/models)** listed models whether contain the model that you choosed. And then:

```shellscript theme={null}
# Select specific model in terminal
codex --model gpt-5-codex

# Or switch other model in codex CLI
/model
```

### **Verify Configuration**

```shellscript theme={null}
# Check environment variable
echo $OPEN_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:

```shellscript theme={null}
# 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:

```shellscript theme={null}
# ~/.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**

```shellscript theme={null}
# Batch process multiple files
for file in src/*.py; do
    codex "Add type annotations to $file"
done
```

**3. Git Integration**

```shellscript theme={null}
# 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`:

```shellscript theme={null}
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

| **Recommendation**     | **Description**                                                                                        |
| :--------------------- | :----------------------------------------------------------------------------------------------------- |
| Clear Prompts          | Provide clear, specific instructions, explaining expected output format and requirements               |
| Context Information    | Provide sufficient context, such as project tech stack, coding standards, etc.                         |
| Iterative Optimization | Gradually improve code through multiple rounds of dialogue, rather than expecting perfection in one go |
| Code Review            | Always review AI-generated code to ensure it meets project standards                                   |
| Version Control        | Use Git to track changes for easy rollback and comparison                                              |
| Security Awareness     | Don’t send sensitive information (keys, passwords, etc.) to AI                                         |
| Cost Control           | Monitor token usage to avoid unnecessary API calls                                                     |

## 9. Resource Links

**9.1 Official Resources**

* [**OpenAI Official Website**](https://openai.com/)
* [**Codex CLI GitHub Repository**](https://github.com/openai/openai-codex)
* [**OpenAI API Documentation**](https://platform.openai.com/docs)
* [**OpenAI Community Forum**](https://community.openai.com/)

**9.2 Third-Party Resources**

* [**AGCloud - Direct Connection API Service in China**](https://aiandgpu.com/)
* [**Node.js Official Website**](https://nodejs.org/)
* [**Windows WSL Documentation**](https://learn.microsoft.com/en-us/windows/wsl/)
* [**Visual Studio Code**](https://code.visualstudio.com/)

## Summary

<Tip>
  **Through this guide, you have successfully:**

  * ✅ Understood basic concepts and features of OpenAI Codex CLI
  * ✅ Installed Codex CLI on Linux/macOS/Windows systems
  * ✅ Configured AGCloud 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!**
</Tip>

### Need Help?

If you encounter problems during use:

* Check [**GitHub Issues**](https://github.com/openai/openai-codex/issues)
* Visit [**OpenAI Community**](https://community.openai.com/)
* Refer to [**Official Documentation**](https://platform.openai.com/docs)
* © 2025 OpenAI Codex CLI Tutorial | Complete Installation Configuration Guide
* Thank you for using Codex CLI - Let AI be your programming assistant
* Recommended to use [**AGCloud**](https://aiandgpu.com) for stable direct connection API service in China
