# OpenCode Integration

AVELIN API works seamlessly with [OpenCode](https://opencode.ai) — a terminal-based AI coding tool that provides fast, context-aware code assistance directly in your terminal.

> **Why AVELIN + OpenCode?** Get access to frontier coding models with 1M-token context windows for large codebases, automatic failover, 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 OpenCode

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

```bash
npm install -g opencode-ai
opencode -v
```

### Step 3: Configure OpenCode

Create the configuration file at `~/.config/opencode/opencode.json`:

```json
{
  "$schema": "https://opencode.ai/config.json",
  "provider": {
    "avelin": {
      "npm": "@ai-sdk/anthropic",
      "name": "AVELIN AI",
      "options": {
        "baseURL": "https://api.avelin.ai",
        "apiKey": "sk-a...
      },
      "models": {
        "avelin-coding-pro": {
          "name": "Avelin Coding Plus",
          "options": {
            "thinking": {
              "type": "enabled",
              "budgetTokens": 32768
            }
          }
        },
        "avelin-coding-fast": {
          "name": "Avelin Coding",
          "options": {
            "thinking": {
              "type": "enabled",
              "budgetTokens": 32768
            }
          }
        },
        "avelin-coding-ultra": {
          "name": "Avelin Coding Architect",
          "options": {
            "thinking": {
              "type": "enabled",
              "budgetTokens": 32768
            }
          }
        },
        "avelin-fast": {
          "name": "Avelin Fast"
        }
      }
    }
  }
}
```

### Step 4: Start OpenCode

```bash
opencode
```

OpenCode will automatically use AVELIN as the backend.

---

## Recommended Models

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

For everyday coding tasks:

| Feature | avelin-coding-pro | Why it matters for OpenCode |
|---|---|---|
| **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 |
| **Tool calling** | First-class support | Reliable file operations and command execution |

### 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 OpenCode?

### 1. **Cost Optimization**

OpenCode sessions can be long with large context windows. AVELIN delivers frontier-tier coding quality at sustainable economics:

- **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**

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

---

## Example Session

```bash
$ opencode

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

You> Add input validation to the user registration endpoint.

OpenCode> I'll add comprehensive validation to the registration endpoint.
          Let me examine the current implementation...

[Reads routes/auth.js, models/User.js]

Here's my plan:
1. Add validation middleware using Joi
2. Validate email format, password strength, username uniqueness
3. Add error handling for validation failures
4. Write tests for valid and invalid inputs

Shall I proceed?

You> yes

OpenCode> [Creates middleware/validateRegistration.js]
          [Updates routes/auth.js to use validation]
          [Creates tests/auth.validation.test.js]

Done! I've added:
- Email format validation
- Password strength check (min 8 chars, uppercase, lowercase, number, special char)
- Username uniqueness check
- 8 passing tests covering valid and invalid cases

Run `npm test` to verify.
```

---

## Advanced Configuration

### Thinking Budget

The configuration includes `budgetTokens: 32768` for thinking. This allocates tokens for the model's reasoning process:

- **Higher budget** (32K+): Better for complex refactors, architecture decisions
- **Lower budget** (8K): Faster responses for simple edits
- **Disabled**: For quick questions where speed matters most

```json
{
  "avelin-fast": {
    "name": "Avelin Fast",
    "options": {
      "thinking": {
        "type": "disabled"
      }
    }
  }
}
```

### Model Switching

You can switch models on-the-fly in OpenCode:

```bash
opencode --model avelin-coding-ultra
```

Or set different models for different tasks in your config.

---

## Troubleshooting

| Issue | Solution |
|---|---|
| **"Provider not found"** | Ensure `@ai-sdk/anthropic` is specified in the npm field |
| **"Model not available"** | Use a valid AVELIN model name from the [Model Catalog](../../models/README.md) |
| **Slow first response** | Normal — model thinks before responding. Streaming starts after reasoning completes. |
| **Context too long errors** | Set `context_length: 1000000` in your configuration |
| **API key errors** | Verify your AVELIN API key is correct and active |

---

## 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
- [OpenCode Docs](https://opencode.ai) — Official OpenCode documentation
