# Codex Integration

AVELIN API works seamlessly with [OpenAI Codex](https://openai.com/codex) — OpenAI's terminal AI coding assistant. Codex provides natural language interface for code generation, debugging, and refactoring directly in your terminal.

> **Why AVELIN + Codex?** Access frontier coding models through Codex's terminal interface with 1M-token context windows and competitive pricing.

---

## Quick Setup

### Step 1: Get your AVELIN API key

Sign up at [avelin.ai](https://avelin.ai) and generate an API key. It will look like `sk-ave...xxxx`.

### Step 2: Install Codex

**Prerequisites:** Install [Node.js](https://nodejs.org/en/download/) (v18.0 or later).

```bash
npm install -g @openai/codex
codex --version
```

**Note:** For best compatibility, you may need version 0.80.0:

```bash
npm install -g @openai/codex@0.80.0
```

### Step 3: Configure Codex

Edit `~/.codex/config.toml`:

```toml
model_provider = "AVELIN"
model = "avelin-coding-pro"

[model_providers.AVELIN]
name = "AVELIN"
base_url = "https://api.avelin.ai/v1"
env_key = "OPENAI_API_KEY"
wire_api = "chat"
```

### Step 4: Set Environment Variable

Add to your shell profile (`~/.bashrc`, `~/.zshrc`, or `~/.config/fish/config.fish`):

```bash
export OPENAI_API_KEY="sk-avelin-YOUR_KEY"
```

Apply changes:

```bash
source ~/.zshrc  # or source ~/.bash_profile
```

### Step 5: Start Codex

Open a **new** terminal window and start Codex:

```bash
codex
```

If the chat interface launches successfully, your configuration is correct.

---

## Recommended Models

### Primary Recommendation: `avelin-coding-pro`

For everyday coding tasks:

| Feature | avelin-coding-pro | Why it matters for Codex |
|---|---|---|
| **Context window** | **1M tokens** | Large codebases and multi-file refactors without context loss |
| **Max output** | **65K tokens** | Generate large code files and comprehensive tests |
| **Throughput** | **~100 tokens/sec** | 2× faster than standard tiers — faster feedback loops |
| **Reasoning** | Deep step-by-step thinking | Catches subtle bugs, understands architectural impact |

### Alternative Models

| Model | When to use |
|---|---|
| `avelin-coding-fast` | Lighter coding tasks, quick questions — saves cost on simple work |
| `avelin-coding-ultra` | System design, architecture reviews, security-sensitive refactors |
| `avelin-fast` | Quick lookups and simple extractions — lowest cost, fastest response |

---

## Why AVELIN for Codex?

### 1. **Cost Optimization**

Codex sessions can involve many API calls. AVELIN optimizes costs:

- **Prompt caching**: ~80% cost reduction on repeated system prompts
- **Competitive pricing**: Lower per-token costs than direct provider APIs
- **Pay-per-token**: No subscription lock-in

### 2. **Model Diversity**

Access multiple frontier coding models through one API. AVELIN routes your requests to a diverse set of frontier models across multiple cloud providers, ensuring high availability and consistent quality. If one provider is slow or unavailable, your request automatically routes to the next best option.

### 3. **Reliability**

- **Automatic failover**: If one provider is slow or down, AVELIN switches to another
- **Retry logic**: Transient errors are handled automatically
- **99.9% uptime**: Enterprise-grade infrastructure

### 4. **1M Context Windows**

Codex works best with large context. AVELIN's coding models support 1M tokens — load entire repositories without chunking.

---

## Example Session

```bash
$ codex

╭─ Codex ──────────────────────────────────────╮
│ Model: avelin-coding-pro                   │
│ Provider: AVELIN (api.avelin.ai)           │
╰─────────────────────────────────────────────╯

You> Write a Python function to parse CSV files and convert them to JSON.

Codex> Here's a Python function that parses CSV files and converts them to JSON:
```

```python
import csv
import json
from typing import List, Dict, Any

def csv_to_json(csv_file_path: str, json_file_path: str = None) -> List[Dict[str, Any]]:
    """
    Parse a CSV file and convert it to JSON format.
    
    Args:
        csv_file_path: Path to the input CSV file
        json_file_path: Optional path to save JSON output
        
    Returns:
        List of dictionaries representing the CSV data
    """
    data = []
    
    with open(csv_file_path, mode='r', encoding='utf-8') as csv_file:
        csv_reader = csv.DictReader(csv_file)
        
        for row in csv_reader:
            # Convert numeric strings to numbers
            converted_row = {}
            for key, value in row.items():
                try:
                    # Try converting to int first
                    converted_row[key] = int(value)
                except ValueError:
                    try:
                        # Try converting to float
                        converted_row[key] = float(value)
                    except ValueError:
                        # Keep as string
                        converted_row[key] = value
            data.append(converted_row)
    
    # Optionally save to JSON file
    if json_file_path:
        with open(json_file_path, mode='w', encoding='utf-8') as json_file:
            json.dump(data, json_file, indent=2, ensure_ascii=False)
    
    return data

# Example usage:
# data = csv_to_json('input.csv', 'output.json')
# print(data)
```

This function:
- Reads CSV files using `csv.DictReader`
- Automatically converts numeric strings to int/float
- Optionally saves to a JSON file
- Returns the data as a list of dictionaries

```bash
You> Good, now add error handling for missing files.

Codex> Here's the updated function with comprehensive error handling:

[Provides updated code with try/except blocks, file existence checks, etc.]
```

---

## Advanced Configuration

### Multiple Models

You can configure multiple AVELIN models in `~/.codex/config.toml`:

```toml
model_provider = "AVELIN"
model = "avelin-coding-pro"

[model_providers.AVELIN]
name = "AVELIN"
base_url = "https://api.avelin.ai/v1"
env_key = "OPENAI_API_KEY"
wire_api = "chat"

[model_providers.AVELIN_Fast]
name = "AVELIN Fast"
base_url = "https://api.avelin.ai/v1"
env_key = "OPENAI_API_KEY"
wire_api = "chat"
```

Switch models by changing the `model_provider` and `model` fields.

### Wire API Options

Codex supports two API formats:

- **`wire_api = "chat"`**: Standard OpenAI Chat Completions API (recommended for most models)
- **`wire_api = "responses"`**: Newer Responses API (for supported models like `avelin-coding-pro`)

Use `"chat"` for maximum compatibility.

---

## Troubleshooting

| Issue | Solution |
|---|---|
| **`wire_api = chat is no longer supported`** | Latest Codex uses Responses API. Either change to `wire_api = "responses"` or downgrade: `npm install -g @openai/codex@0.80.0` |
| **`unexpected status 401 Unauthorized`** | API key mismatch or typo. Verify your AVELIN API key is correct |
| **`Model not found`** | Ensure the model name is valid (e.g., `avelin-coding-pro`, not `avelin-coding-fast+`) |
| **Slow first response** | Normal — model thinks before responding. Streaming starts after reasoning completes |
| **Context too long errors** | Set `context_length: 1000000` in your configuration |

---

## Related

- [API Quickstart](../../api/quickstart.md) — First API call in 5 minutes
- [Hermes Agent Guide](../hermes.md) — Another terminal-based coding tool
- [Claude Code Guide](claude-code.md) — Anthropic's CLI tool
- [Model Catalog](../../models/README.md) — Full model comparison
- [OpenAI Codex Docs](https://openai.com/codex) — Official Codex documentation
