OpenRouter unified API gateway: один ключ для GPT Claude Gemini и 400+ LLM моделей

Руководство OpenRouter API 2026: GPT, Claude, Gemini и 400+ моделей через один ключ

Пять vendor API keys — пять rate-limit handlers, пять billing dashboards и пять мест, где agent pipeline ломается в 3:00 ночи. OpenRouter — unified LLM gateway с OpenAI-compatible endpoint: один OPENROUTER_API_KEY, slug anthropic/claude-sonnet-4 или google/gemini-2.5-pro, и provider routing на стороне gateway. Это независимый русскоязычный runbook: routing specs, честная таблица vs direct API, production code, streaming/fallback/pricing — плюс performance-угол (latency hops, гибрид с локальным Metal/Ollama) и мост SFTPMAC к 24/7 remote Mac.

1. Что такое OpenRouter: gateway и routing stack

TL;DR: POST на https://openrouter.ai/api/v1/chat/completions, header Authorization: Bearer $OPENROUTER_API_KEY, body с model slug. Request/response — OpenAI Chat Completions schema. Migration существующего OpenAI SDK-кода: сменить base_url + key.

На каждый request OpenRouter принимает два routing решения. Model routing — поле model или openrouter/auto. Provider routing — какой upstream cluster обслуживает slug; default weighting по price/uptime. При 429/5xx — failover на alternate provider или backup slug из массива models без custom retry layer в вашем коде.

Slug pattern: vendor/model. Июль 2026: openai/gpt-4o, anthropic/claude-sonnet-4, google/gemini-2.5-pro, deepseek/deepseek-chat, meta-llama/llama-3.3-70b-instruct. Catalog: GET /api/v1/models. Реальное распределение spend — июньский rankings guide и майская routing matrix.

2. OpenRouter vs Direct API (OpenAI, Anthropic, Google)

Измерение OpenRouter Direct vendor API
Account setup Один account, один key, один dashboard Отдельный signup/billing/key rotation per vendor
SDK compatibility OpenAI-compatible; swap base_url + key Native SDKs: Batch API, Prompt Caching, Vertex tools
Model switching Одна строка в model Rewrite client config, auth, message schema
Failover Built-in provider failover + optional model chain Circuit breakers и retry — ваш код
Token pricing Provider list price, no markup; 5,5 % на credit purchase Direct invoice; volume discounts per vendor
Latency (p50 overhead) +10–80 ms gateway hop (region-dependent) Минимальный theoretical latency к vendor edge
Compliance Traffic через US infrastructure OpenRouter Vendor DPA, regional endpoints, VPC
Best fit Prototypes, A/B, multi-model agents, spend < ~$5k–10k/mo Single-model high volume, strict residency, exclusive APIs

3. Пять причин переключиться на OpenRouter

  1. Один key — все frontier models. Нет параллельных интеграций OpenAI/Anthropic/Google/DeepSeek. Onboarding = одна env var.
  2. Near-zero migration cost. OpenAI SDK → base_url OpenRouter. Message arrays, tool calls, streaming loops intact.
  3. Automatic failover. Provider 429 и transient 5xx поглощаются до application layer — критично для long-running agent tool loops.
  4. Unified billing + latency dashboards. TTFT, throughput, spend по реально используемым slugs — не по архитектурной диаграмме.
  5. No token markup + free tier. Benchmark Claude vs Gemini vs DeepSeek на одном prompt без трёх vendor accounts.

4. Когда OpenRouter не использовать

  • Single-vendor scale economics — enterprise direct contract дешевле при $10k+/mo на одном slug.
  • Vendor-exclusive features — OpenAI Batch, Anthropic Prompt Caching billing, Vertex grounding.
  • Strict data residency — regulated health/finance/gov без US aggregator routing.
  • Sub-100 ms realtime loops — benchmark direct endpoints first.
  • Free/preview models с unclear logging — sensitive data только через reviewed vendor retention.

5. API key: пошаговый setup

  1. Account на openrouter.ai (email/OAuth).
  2. Settings → Keys → Create Key. Именование: prod-agent-gateway, local-dev.
  3. Copy sk-or- key immediately — one-time display.
  4. Credits для paid models. Free tier без balance. 5,5 % fee на top-up.
  5. Smoke test:
export OPENROUTER_API_KEY="sk-or-v1-..."

curl -s https://openrouter.ai/api/v1/chat/completions \
  -H "Authorization: Bearer $OPENROUTER_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{
    "model": "openai/gpt-4o",
    "messages": [{"role": "user", "content": "Reply exactly: OpenRouter OK"}]
  }' | jq -r '.choices[0].message.content'

6. Code examples: cURL, Python, Node.js, OpenAI SDK drop-in

cURL

curl https://openrouter.ai/api/v1/chat/completions \
  -H "Authorization: Bearer $OPENROUTER_API_KEY" \
  -H "Content-Type: application/json" \
  -H "HTTP-Referer: https://sftpmac.com" \
  -H "X-Title: SFTPMAC OpenRouter Demo" \
  -d '{
    "model": "anthropic/claude-sonnet-4",
    "messages": [
      {"role": "user", "content": "Explain quantum computing in one sentence."}
    ]
  }'

Python (requests)

import os
import requests

response = requests.post(
    url="https://openrouter.ai/api/v1/chat/completions",
    headers={
        "Authorization": f"Bearer {os.environ['OPENROUTER_API_KEY']}",
        "Content-Type": "application/json",
        "HTTP-Referer": "https://sftpmac.com",
        "X-Title": "SFTPMAC OpenRouter Demo",
    },
    json={
        "model": "google/gemini-2.5-pro",
        "messages": [
            {"role": "user", "content": "Write quicksort in 15 lines of Python."}
        ],
    },
    timeout=60,
)
response.raise_for_status()
print(response.json()["choices"][0]["message"]["content"])

Node.js (OpenAI SDK)

import OpenAI from "openai";

const client = new OpenAI({
  baseURL: "https://openrouter.ai/api/v1",
  apiKey: process.env.OPENROUTER_API_KEY,
  defaultHeaders: {
    "HTTP-Referer": "https://sftpmac.com",
    "X-Title": "SFTPMAC OpenRouter Demo",
  },
});

const completion = await client.chat.completions.create({
  model: "deepseek/deepseek-chat",
  messages: [{ role: "user", content: "Explain OpenRouter in one sentence." }],
});

console.log(completion.choices[0].message.content);

OpenAI SDK drop-in (Python)

import os
from openai import OpenAI

client = OpenAI(
    base_url="https://openrouter.ai/api/v1",
    api_key=os.environ["OPENROUTER_API_KEY"],
)

completion = client.chat.completions.create(
    model="openai/gpt-4o",
    messages=[{"role": "user", "content": "Hello from OpenRouter."}],
    extra_headers={
        "HTTP-Referer": "https://sftpmac.com",
        "X-Title": "SFTPMAC OpenRouter Demo",
    },
)
print(completion.choices[0].message.content)

List models

curl -s https://openrouter.ai/api/v1/models \
  -H "Authorization: Bearer $OPENROUTER_API_KEY" \
  | jq '.data[] | {id: .id, pricing: .pricing}' | head

7. Streaming, fallback configuration, pricing 2026

Streaming

const stream = await client.chat.completions.create({
  model: "anthropic/claude-sonnet-4",
  messages: [{ role: "user", content: "Write a short poem about autumn." }],
  stream: true,
});

for await (const chunk of stream) {
  const text = chunk.choices[0]?.delta?.content;
  if (text) process.stdout.write(text);
}

Model fallback chain

{
  "model": "anthropic/claude-sonnet-4",
  "models": [
    "anthropic/claude-sonnet-4",
    "openai/gpt-4o",
    "google/gemini-2.5-pro"
  ],
  "route": "fallback",
  "messages": [{ "role": "user", "content": "Summarize this incident." }]
}

OpenClaw: mirror primary/fallback slugs в openclaw.json, keys через SecretRef. Incident playbook: channels probe + 429.

Pricing table 2026

Компонент Ставка Примечания
Paid tokens Provider list price / M tokens No OpenRouter markup
Credit purchase fee 5,5 % (min $0.80) At top-up, not per request
Free tier $0 on 25+ models ~50 req/day unfunded; ~1 000/day after $10+ at 20 req/min
BYOK First 1M req/mo free; 5 % after Attach native vendor keys

8. Performance: latency budget, Metal и гибридные архитектуры

Gateway hop добавляет типично 10–80 ms p50 к TTFT — negligible для batch agent pipelines, заметно для sub-second chat UX. Профилируйте end-to-end: curl -w '%{time_starttransfer}\n' vs direct vendor endpoint на том же region egress.

Гибрид OpenRouter + local Metal: routing policy в OpenClaw — frontier reasoning через OpenRouter (Claude/GPT), classification/summarization на Ollama + Metal локально на Mac mini M4. Unified memory Apple Silicon даёт ~100+ tok/s на 8B–14B quant models без PCIe bottleneck VPS. OpenRouter fallback chain остаётся для tasks, где local model недостаточен; local tier снимает 80 % token spend и убирает network hop для hot path.

Concurrency на Apple Silicon: agent с parallel sub-agents держит несколько HTTP connections к OpenRouter — Node 22 + undici pool, timeout 60–120 s на long context. Mac mini M4 Pro 32 GB: 4–8 concurrent OpenRouter streams без swap thrash; при Docker sandbox sub-agents — выделите отдельный remote Mac, не ноутбук с sleep.

429 storm mitigation: exponential backoff на application layer после OpenRouter provider failover исчерпан; pin fallback slugs с lower rate-limit profile (DeepSeek, Qwen) в models array. См. model selection guide.

9. FAQ

OpenRouter бесплатный? 25+ models, daily limits, ~50 req/day unfunded, ~1 000/day после $10+ balance.

Markup на tokens? Нет. 5,5 % только на credit purchase.

Безопасность? Established aggregator; prompts через US infra. Compliance review для regulated data.

OpenRouter vs LiteLLM? OpenRouter = hosted gateway + billing. LiteLLM = self-hosted proxy. Zero ops → OpenRouter; on-prem control → LiteLLM.

Сменить model без rewrite? Изменить model string + optional models fallback array.

10. OpenRouter agents на remote Mac (SFTPMAC bridge)

OpenRouter решает model access — не gateway uptime. Laptop sleep, VPN drops, background kill = channels silent при healthy model layer.

Production pattern: Apple Silicon, Node 22, OPENROUTER_API_KEY в SecretRef, primary/fallback slugs в openclaw.json, gateway под launchd, workspace sync SFTP/rsync. Debug serial: gateway health → channels probe → OpenRouter 429 → model swap.

SFTPMAC remote Mac rental — native macOS permission boundaries, 24/7 connectivity для Telegram/Slack callbacks, APFS rollback. Пара: OpenClaw installation runbook + rankings guides выше.