# ClaudeApi — Programmatic AI from AV Widgets

Call Claude models (Haiku, Sonnet, Opus) from any AV widget or server-side code via the `/api/claude` proxy on the AV server (port 8770). This lets widgets, skills, and scripts trigger AI requests without a full Claude Code session — useful for deterministic code blocks that need AI assistance at a specific step.

## Why This Exists

Sometimes you need a **deterministic block of code** — a function, a build step, a widget — to make its own AI request and use the result programmatically. Running the full Claude Code CLI for this is overkill and expensive (Opus). The `/api/claude` proxy lets you pick the right model for the job:

| Model | ID | Input $/M tok | Output $/M tok | Claude Max 20x | Use for |
|-------|----|---------------|----------------|----------------|---------|
| **Haiku 4.5** | `claude-haiku-4-5-20251001` | $0.80 | $4.00 | $16 / $80 | Quick lookups, simple transforms, classification |
| **Sonnet 4.6** | `claude-sonnet-4-6` | $3.00 | $15.00 | $60 / $300 | Code generation, analysis, structured output |
| **Opus 4.6** | `claude-opus-4-6` | $15.00 | $75.00 | $300 / $1500 | Complex reasoning, architecture, long context |

## AV Widget

The **ClaudeApi** view is a first-class AV citizen — find it in the AV dropdown under **Tools > ClaudeApi — Claude API Playground**.

- **Vision card** — drop an image, Haiku suggests a filename
- **Three model cards** — Haiku, Sonnet, Opus with editable prompts
- **"Run All"** fires all three in parallel
- **Dual cost display** — API base rate + Claude Max 20x multiplier
- **Execution timing** — see how fast each model responds
- **Token counts** — input/output tokens per request
- **API docs** — scrollable reference at the bottom

View ID: `ClaudeApi` | Dropdown key: `claudeapi` | HTML: `viewer/viewer/claude-api.html`

## API Reference

### Endpoint

```
POST /api/claude   (on AV server, port 8770)
```

### Request Body (JSON)

| Param | Type | Default | Description |
|-------|------|---------|-------------|
| `model` | string | `claude-haiku-4-5-20251001` | Model ID |
| `messages` | array | *required* | Array of `{role, content}` objects |
| `max_tokens` | number | 1024 | Max output tokens |
| `system` | string | *none* | System prompt |
| `temperature` | number | *API default* | 0.0 - 1.0 |

### JavaScript (from an AV widget)

```javascript
const API_BASE = (() => {
  let path = location.pathname;
  if (path === '/' || location.href.includes('about:srcdoc')) {
    try { path = parent.location.pathname; } catch {}
  }
  const m = path.match(/^(\/proxy\/\d+)\//);
  return m ? m[1] : '';
})();

async function askClaude(prompt, model = 'claude-haiku-4-5-20251001') {
  const res = await fetch(API_BASE + '/api/claude', {
    method: 'POST',
    headers: { 'Content-Type': 'application/json' },
    body: JSON.stringify({
      model,
      max_tokens: 1024,
      messages: [{ role: 'user', content: prompt }],
    }),
  });
  const data = await res.json();
  if (data.error) throw new Error(data.error.message || data.error);
  return {
    text: data.content?.[0]?.text || '',
    inputTokens: data.usage?.input_tokens || 0,
    outputTokens: data.usage?.output_tokens || 0,
    model: data.model,
  };
}
```

### Bash / curl

```bash
curl -s http://localhost:8770/api/claude \
  -H "content-type: application/json" \
  -d '{
    "model": "claude-haiku-4-5-20251001",
    "max_tokens": 256,
    "messages": [{"role": "user", "content": "What is 2+2?"}]
  }'
```

## Architecture

The proxy lives in `viewer/server.js` as the `POST /api/claude` route. It reads the OAuth access token from the local credentials file, forwards the request to `api.anthropic.com/v1/messages`, and returns the raw response (including `usage` for cost calculation). 120-second timeout, CORS enabled. No API keys to manage — it reuses the Claude Code OAuth token automatically.

## Vision Support

The Messages API supports image content blocks. Pass them in the `messages` array:

```javascript
messages: [{
  role: 'user',
  content: [
    { type: 'image', source: { type: 'base64', media_type: 'image/png', data: base64Data } },
    { type: 'text', text: 'Describe this image' }
  ]
}]
```

The ClaudeApi widget includes a built-in vision test card with drag-and-drop image support and a sample bridge image for testing.
