# ChatGPT / Codex Setup

Codex is OpenAI's official command-line AI coding assistant. Connect it through the 4AICode API to manage keys, team quotas, and usage in one console, with billing based on actual token usage.

> 💡 **Beginner tip**: We recommend starting with **[Method 1: Connection Assistant (GUI)]**. You don't need to type commands—configure everything with just a few clicks.

---

## Prerequisites: Get Your Token

Whichever setup method you choose, you first need your 4AICode token:

1. Sign in to 4AICode and go to [Dashboard → Manage Tokens](https://4aicode.com/tokens).
2. Click **"New Token"**.
3. Copy the generated string (formatted like `sk-4ai-<your-token>`).

> ⚠️ **Important notes**:
> - The token is shown only once upon creation. Save it to a password manager or notes app.
> - `sk-4ai-<your-token>` in this guide is a placeholder. Replace it with your actual token.
> - When using command-line examples, replace the angle brackets and their placeholder contents with your actual token.
> - Treat your token like a password: never share it or commit it to GitHub.

---

## Method 1: Connection Assistant (Recommended for Beginners)

The 4AICode Connection Assistant uses MyGo to build its native desktop interface and requires no terminal commands.

### 1. Download the Connection Assistant

| OS Platform | Download Link | Notes |
| --- | --- | --- |
| **Windows 10 / 11** (64-bit) | [📥 Download Connection Assistant for Windows (.exe)](/downloads/windows/4aicode-assistant-windows-amd64.exe) | Run the installer directly |
| **macOS 12+** (Apple Silicon / M-series) | [📥 Download Connection Assistant for Apple Silicon (.dmg)](/downloads/macos/4aicode-assistant-macos-arm64.dmg) | Open DMG and drag to Applications |
| **macOS 12+** (Intel) | [📥 Download Connection Assistant for Intel (.dmg)](/downloads/macos/4aicode-assistant-macos-amd64.dmg) | Open DMG and drag to Applications |

> The Windows build currently has no publisher signature and may show a SmartScreen prompt on first launch. Defender validation is pending. From the download directory, run `certutil -hashfile 4aicode-assistant-windows-amd64.exe SHA256` (Windows) and compare it with the hash at the start of the matching file line in [SHA256SUMS.txt](/downloads/SHA256SUMS.txt).

Both macOS architectures use Developer ID signing and Apple notarization. Open the DMG and drag the app into Applications to install.

*(Checksum verification: [SHA-256 Checksums](/downloads/SHA256SUMS.txt) · [Version info](/downloads/latest.json))*

The download link shows the release version. Before updating, choose **Quit** from the assistant’s system tray/menu bar; closing its window keeps it running. Replace the app and reopen it, then compare the version and build ID at the top right of the window with the download page.

### 2. Configure in 3 Simple Steps

1. **Connect Account**: Open the assistant, paste your `sk-4ai-<your-token>`, select **Mainland China (国内线路)** or **International (国际线路)**, then choose a model from the dropdown loaded automatically from that route’s API and click **"Connect"**. Changing the token or route reloads the models; use **Refresh Models (刷新模型)** to retry.
2. **Install & Launch**: Click **"Select Project & Launch Codex"**. On first use, if Codex CLI is missing, the assistant downloads and installs it before launching it in your chosen directory. The assistant shows a status message while downloading; wait for it to finish.
3. **Keep it available**: Closing the window keeps the assistant in the system tray (Windows) or menu bar (macOS) for quick access.

> Your token is saved securely in the system credential manager. Click the eye icon beside the input to show or hide what you entered. Connecting hides it again.

### 3. Connect the Official Windows Desktop App

Local Codex supports API-key sign-in and can use your 4AICode balance directly:

1. Select a model and connect in the assistant. The model list supports mouse-wheel scrolling and keyboard selection.
2. Click **Copy Desktop Login Key (复制桌面登录密钥)**. The assistant prepares the desktop provider configuration and copies its local connection key.
3. **Fully quit and reopen** the official ChatGPT / Codex desktop app. Choose **Sign in another way → API key**, paste into **OpenAI API key**, and continue.
4. Keep the assistant running and start a new local task. Restart the desktop app after changing the model or route.

Use the same Windows user and Codex configuration directory for both apps (normally `%USERPROFILE%\.codex`). If you set `CODEX_HOME`, both apps must use that directory.

Treat `config.toml` as private because it contains the local connection key. Redact credentials before sharing troubleshooting information. **Restore Original Configuration** exits the assistant's desktop sign-in mode.

The copied key connects to the local assistant; your 4AICode token stays in the system credential vault. Users already signed in with ChatGPT can keep their login, click this button, and restart the app. API-key mode supports local Codex work. ChatGPT web chat, workspace, and cloud features use their respective official account permissions. [Official authentication documentation](https://learn.chatgpt.com/docs/auth#sign-in-with-an-api-key)

### Desktop error: Model provider `fouraicode_assistant` not found

The configuration loaded by the desktop app is missing the assistant's provider definition:

1. Quit the old assistant from the system tray, download the latest version, and click **Connect (连接)**. If it still shows connected, click **Disconnect (断开)** and connect again. From v0.1.2, the assistant checks configuration regularly and can restore a missing definition on reconnect when its backup confirms ownership.
2. **Fully quit and reopen** the official ChatGPT / Codex desktop app, then open the affected conversation.
3. If the error persists, check that both apps use the same Windows user and configuration directory, including `CODEX_HOME` when set. Share the assistant version, steps, and configuration directory with support.

After using **Restore Original Configuration**, reconnect before continuing an assistant conversation. To use your original provider, restart the desktop app and start a new task.

### Connection settings changed

Click **Reconfigure and Connect (重新配置并连接)**, then confirm **Back Up and Connect (备份并连接)**. The assistant saves your current settings and previous backup before switching to 4AICode, preserving project trust, MCP, and other providers. Restoring afterwards returns to the settings from before this switch. Restart the desktop app when finished.

### Connection failed

Follow the specific message: retry a timeout, check the local proxy app and port for proxy failures, check the computer's date and time for certificate failures, or refresh an invalid model list. Contact support for persistent service errors. Handle token, balance, and usage-limit messages in the dashboard. Share the assistant version and error message with support; redact credentials before sharing configuration files.

---

## Method 2: Command-Line Setup (For Developers)

If you are comfortable using the terminal, run the install command and one-click setup script. It takes about 2 minutes.


**macOS / Linux**


### 1. Open Terminal
Press `⌘ + Space`, type "Terminal", and press Enter.

### 2. Install Codex CLI
Ensure Node.js or Homebrew is installed, then run either command:

```bash
# Option A: via npm (recommended, requires Node.js 16+)
npm install -g @openai/codex

# Option B: via Homebrew (macOS only)
brew install --cask codex
```

Run `codex --version`. Seeing a version number means it was installed successfully.

### 3. Run One-Click Setup Script
Replace `sk-4ai-<your-token>` with your actual token and run:

```bash
# International route (recommended)
export RELAY4AI_BASE_URL=https://relay.4aicode.com/v1
curl -fsSL https://4aicode.com/codex-setup.sh | bash -s install 'sk-4ai-<your-token>'

# Mainland China direct route (.net)
curl -fsSL https://4aicode.net/codex-setup.sh | bash -s install 'sk-4ai-<your-token>'
```

Seeing `✓ Written ...` confirms configuration is complete!

### 4. Verify Setup
**Open a new terminal window**, navigate to any project folder, and run:

```bash
codex
```
Try asking: `Explain the file structure of this directory`. A prompt response indicates you are connected!


**Windows**


### 1. Open PowerShell
Press the `Windows key`, search for **PowerShell**, and open it.

### 2. Install Codex CLI
Ensure Node.js is installed, then run in PowerShell:

```powershell
npm install -g @openai/codex
```

Run `codex --version`. Seeing a version number means it was installed successfully.

### 3. Run One-Click Setup Script
Run the setup script in PowerShell:

```powershell
# Interactive setup (prompts for your token and model)
$env:RELAY4AI_BASE_URL='https://relay.4aicode.com/v1'
irm https://4aicode.com/codex-setup.ps1 | iex
```

Or pass your token directly without prompts (remember to replace the placeholder):

```powershell
$env:RELAY4AI_BASE_URL='https://relay.4aicode.com/v1'
& ([scriptblock]::Create((irm https://4aicode.com/codex-setup.ps1))) install 'sk-4ai-<your-token>'
```

### 4. Verify Setup
**Open a new PowerShell window**, navigate to your project directory, and run:

```powershell
codex
```
Send a test message to Codex to verify it's working properly!


---

## Common Operations

### 1. Switching Models & Reasoning Effort

With the assistant, click **Disconnect**, select another model from the dropdown, reconnect, and restart Codex.

For command-line setup, edit the local config file:

- **macOS / Linux**: `~/.codex/config.toml`
- **Windows**: `%USERPROFILE%\.codex\config.toml`

Update these two lines (leave other fields intact):

```toml
model = "gpt-5.6-terra"
model_reasoning_effort = "xhigh"
```

| Model | Recommended Use Case |
| --- | --- |
| `gpt-5.6-terra` | **Everyday coding (Default)**: Best balance of speed and code quality |
| `gpt-6-astra` | **Next-gen flagship**: Top-tier capabilities, billed at 15% of official list price |
| `gpt-5.6-sol` | **Complex engineering**: Strongest reasoning (supports `max` effort level) |
| `gpt-5.6-luna` | **Fast & economical**: Light tasks, budget-friendly |
| `gpt-5.5` / `gpt-5.4` | Legacy workflow compatibility |

*Reasoning effort options: `low`, `medium`, `high`, `xhigh`. Changes take effect after restarting Codex.*

### 2. Check Status or Rollback Configuration


**macOS / Linux**


```bash
# Check current provider and model status
curl -fsSL https://4aicode.com/codex-setup.sh | bash -s status

# Uninstall and restore pre-setup config
curl -fsSL https://4aicode.com/codex-setup.sh | bash -s uninstall
```


**Windows**


```powershell
# Check status
& ([scriptblock]::Create((irm https://4aicode.com/codex-setup.ps1))) status

# Uninstall and restore original config
& ([scriptblock]::Create((irm https://4aicode.com/codex-setup.ps1))) uninstall
```


---

## Troubleshooting & FAQ

### Q1: `codex: command not found` or not recognized?
- **Cause**: Codex CLI is not installed or your terminal environment path has not refreshed.
- **Fix**: Close the current terminal and open a new one. If it persists, ensure Node.js is installed and re-run `npm install -g @openai/codex`.

### Q2: Encountered `401 Unauthorized`?
- **Cause**: Invalid or revoked token, or placeholder was not replaced.
- **Fix**: Check whether `sk-4ai-<your-token>` was replaced with your actual token. You can generate a new token in the [Dashboard](https://4aicode.com/tokens) and rerun the setup command.

### Q3: PowerShell blocks the script with execution policy error?
- **Fix**: Use the `& ([scriptblock]::Create(...))` command shown above, or run `Set-ExecutionPolicy -Scope CurrentUser RemoteSigned` in PowerShell to allow local scripts.

### Q4: Config or model changes don't take effect?
- **Fix**: Codex caches configuration upon startup. Completely exit Codex CLI or close the Codex App, open a fresh terminal, and run `codex` again.

### Q5: How to use the official Codex desktop app (Codex App)?
- Connect in the assistant, click **Copy Desktop Login Key (复制桌面登录密钥)**, fully quit and reopen the desktop app, then choose API-key sign-in and paste. See the Windows desktop instructions above.
- To return to an official provider, restore the original configuration in the assistant. If you signed in with the local key, sign out in the desktop app and select your own official sign-in method.

---

## Other Tools & SDK Integration

If you use other editors or SDKs, connect them to 4AICode's ChatGPT pool with standard OpenAI-compatible parameters:

| Tool / Environment | Guide |
| --- | --- |
| **CC Switch** (GUI provider switcher) | See [CC Switch Guide](/docs/en/guides/cc-switch) |
| **VS Code / Cursor / Windsurf** | See [VS Code / Cursor Guide](/docs/en/guides/vscode) |
| **Claude Code using GPT models** | See [Claude Setup Guide](/docs/en/guides/claude) |
| **Droid / Pi** | See [Droid / Pi Guide](/docs/en/guides/droid-pi) |
| **Official OpenAI Python / Node SDK** | Set Base URL and API Key (see code samples below) |

### API Parameters
- **Base URL**: `https://relay.4aicode.com/v1` (or `https://relay.4aicode.net/v1` in mainland China)
- **API Key**: Your 4AICode Token (`sk-4ai-<your-token>`)

#### Python SDK Example
```python
from openai import OpenAI

client = OpenAI(
    base_url="https://relay.4aicode.com/v1",
    api_key="sk-4ai-<your-token>",  # Replace with your actual token
)

response = client.chat.completions.create(
    model="gpt-5.6-terra",
    messages=[{"role": "user", "content": "Hello! Please write a quicksort algorithm."}],
)

print(response.choices[0].message.content)
```

#### cURL Example
```bash
curl https://relay.4aicode.com/v1/chat/completions \
  -H "Authorization: Bearer sk-4ai-<your-token>" \
  -H "Content-Type: application/json" \
  -d '{
    "model": "gpt-5.6-terra",
    "messages": [{"role": "user", "content": "ping"}]
  }'
```

---

## Appendix: Manual Advanced Setup (For Reference)

> 💡 Standard users can safely ignore this section. Intended for developers who need to review or manually merge configurations.

Config file locations:
- macOS / Linux: `~/.codex/`
- Windows: `%USERPROFILE%\.codex\`

### 1. `auth.json`
Retain ChatGPT official login auth structure:
```json
{
  "auth_mode": "chatgpt",
  "OPENAI_API_KEY": null,
  "tokens": {
    "id_token": "...",
    "access_token": "...",
    "refresh_token": "...",
    "account_id": "..."
  },
  "last_refresh": "..."
}
```

### 2. `config.toml`
Set 4AICode as the model provider:
```toml
model_provider = "OpenAI"
openai_base_url = "https://relay.4aicode.com/v1"
model = "gpt-5.6-terra"
model_reasoning_effort = "xhigh"

[model_providers.OpenAI]
name = "4aicode"
base_url = "https://relay.4aicode.com/v1"
wire_api = "responses"
experimental_bearer_token = "sk-4ai-<your-token>"
requires_openai_auth = true
```
