OpenRouter API: полный гайд по GPT, Claude и Gemini — routing, код и production (2026)
Если вам нужны GPT-4o, Claude 3.5, Gemini, DeepSeek и Qwen в одном agent pipeline без N отдельных аккаунтов и SDK, OpenRouter — unified LLM gateway: один API key, OpenAI-compatible endpoint, 70+ провайдеров и 400+ моделей.
Разбор для backend- и platform-инженеров: двухуровневый routing (Model + Provider), сравнение с direct API, шесть шагов деплоя, curl/Python/Node/OpenAI SDK, fallback JSON, hard numbers по pricing и checklist для multilang SEO. Контекст рынка: OpenRouter rankings июнь 2026.
01 OpenRouter: unified endpoint и двухуровневый routing stack
OpenRouter — aggregation layer над inference endpoints: один API key + OpenAI-compatible /chat/completions вместо отдельных интеграций с OpenAI, Anthropic, Google, Meta, DeepSeek.
- Endpoint:
https://openrouter.ai/api/v1/chat/completions - Auth:
Authorization: Bearer $OPENROUTER_API_KEY - Протокол: OpenAI Chat Completions — миграция = смена
base_urlиapi_key - Model slug:
provider/model—openai/gpt-4o,anthropic/claude-3.5-sonnet,google/gemini-2.5-pro,deepseek/deepseek-chat
Ключ к пониманию latency и failover — два независимых routing hop внутри gateway:
| Слой | Решение | Control plane |
|---|---|---|
| Model Routing (L1) | Какая weights-конфигурация обрабатывает prompt | model; openrouter/auto для cost/latency-aware pick |
| Provider Routing (L2) | Какой upstream host обслуживает тот же model slug | provider object; default: inverse-square price weighting |
Provider Routing в деталях: один slug (anthropic/claude-3.5-sonnet) может резолвиться в несколько upstream endpoints (официальный Anthropic, reseller, regional mirror). Gateway выбирает candidate по price curve, health bit и rate-limit state — без изменения client payload.
Model Routing + Fallback chain: поле models: [...] с route: "fallback" задаёт ordered list. При 429/5xx/timeout L1 переключается на следующий slug; L2 внутри каждого slug повторяет provider failover. Client-side circuit breaker не нужен.
- Free tier: 25+ моделей; ~50 req/day без balance, ~1000/day после ≥$10 (cap 20/min).
- Pricing: token rate = provider list price; top-up 5.5% (min $0.80); crypto +5%; BYOK: first 1M req/month free, then 5% on excess.
- Extra hop latency: типично +10–80 ms TTFT — измерять под ваш prompt size и region.
02 OpenRouter vs direct OpenAI / Anthropic API — где ломается архитектура
- Account fragmentation: N провайдеров → N keys, billing consoles, audit trails.
- Schema drift: message format, streaming SSE deltas, error codes — каждый SDK свой.
- Single-provider SPOF: 429 на одном upstream без fallback = hard fail для user-facing agent.
- Observability gap: TTFT, throughput, spend размазаны по пяти dashboards.
| Dimension | OpenRouter | Direct API |
|---|---|---|
| Integration surface | base_url swap, один HTTP client | Per-vendor SDK + auth + billing |
| Failover | L1 model + L2 provider routing встроены | Custom retry, key pool, routing middleware |
| Latency | +10–80 ms gateway hop | Direct to inference region |
| Exclusive APIs | Chat Completions subset | Batch, Assistants, Prompt Caching, Vertex toolchain |
| Compliance | Traffic через US third-party gateway | Regional residency, enterprise DPA |
| Cost stack | List token price + 5.5% top-up или BYOK 5% | No middleware fee; enterprise volume deals |
Routing overhead оправдан для multi-model A/B и agent prototypes; для single-model hyperscale и sub-10 ms TTFT budget — стройте direct path или hybrid (OpenRouter только для fallback tier).
03 Пять преимуществ OpenRouter — и когда routing layer не нужен
- One key, all slugs: model swap = string replace в
modelfield. - Cross-provider failover: declarative
modelsarray, sequential L1 routing. - Unified billing/Observability: один dashboard для token, cost, TTFT across slugs.
- No token markup: только top-up fee; BYOK снижает effective rate на high QPS.
- Clear scope: prototyping, model shootouts, monthly spend до low thousands USD.
Direct API предпочтительнее:
- Single slug, monthly spend $10k+ — 5.5% fee окупает свой routing layer
- Нужны Anthropic Prompt Caching, OpenAI Batch/Assistants, Google Vertex hooks
- TTFT SLA не допускает +10–80 ms gateway hop
- Data residency: payload не должен проходить US middleware
04 Production integration: шесть шагов OpenRouter API
- Register: openrouter.ai — GitHub или email.
- API key: Keys page; per-project key + spend limit в production.
- Env var:
export OPENROUTER_API_KEY="sk-or-..."— не коммитить в git. - Smoke test: curl или OpenAI SDK; verify HTTP 200 и resolved model id в response.
- Model catalog:
curl https://openrouter.ai/api/v1/models -H "Authorization: Bearer $OPENROUTER_API_KEY" - Deploy: fallback chain, streaming, HTTP-Referer/X-Title (rankings attribution), key на 7×24 agent host.
05 Code samples: curl, Python, Node.js, OpenAI SDK, streaming, fallback routing
Runnable snippets после подстановки key.
cURL
curl https://openrouter.ai/api/v1/chat/completions \
-H "Authorization: Bearer $OPENROUTER_API_KEY" \
-H "Content-Type: application/json" \
-d '{
"model": "anthropic/claude-3.5-sonnet",
"messages": [{"role": "user", "content": "Объясни квантовые вычисления одним предложением"}]
}'
Python (requests)
import requests, os
r = requests.post(
"https://openrouter.ai/api/v1/chat/completions",
headers={"Authorization": f"Bearer {os.environ['OPENROUTER_API_KEY']}"},
json={"model": "google/gemini-2.5-pro",
"messages": [{"role": "user", "content": "Quicksort на Python"}]}
)
print(r.json()["choices"][0]["message"]["content"])
Python (OpenAI SDK migration)
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!"}],
extra_headers={"HTTP-Referer": "https://jexcloud.com", "X-Title": "JEXCLOUD Demo"},
)
Node.js (OpenAI SDK)
import OpenAI from "openai";
const openai = new OpenAI({
baseURL: "https://openrouter.ai/api/v1",
apiKey: process.env.OPENROUTER_API_KEY,
});
const completion = await openai.chat.completions.create({
model: "deepseek/deepseek-chat",
messages: [{ role: "user", content: "Explain OpenRouter in one sentence" }],
});
Streaming (SSE token deltas)
const stream = await openai.chat.completions.create({
model: "anthropic/claude-3.5-sonnet", stream: true,
messages: [{ role: "user", content: "Короткое осеннее стихотворение" }],
});
for await (const chunk of stream) {
const c = chunk.choices[0]?.delta?.content;
if (c) process.stdout.write(c);
}
L1 fallback routing JSON
{
"model": "anthropic/claude-3.5-sonnet",
"models": ["anthropic/claude-3.5-sonnet", "openai/gpt-4o", "google/gemini-2.5-pro"],
"route": "fallback",
"messages": [{"role": "user", "content": "Hello"}]
}
06 Pricing, free models и cite-ready hard numbers
- Catalog scale: 70+ providers, 400+ models — verify via
GET /modelsbefore routing rules. - Free tier: 25+ models; 50 req/day no balance, 1000/day after $10, rate cap 20/min.
- Fees: top-up 5.5% (min $0.80); crypto +5%; BYOK 1M req/month free tier.
- Gateway latency tax: +10–80 ms — benchmark under your payload size.
- Cost control: default route to Flash/cheap slugs; Opus only on critical steps; per-project spend limits.
OpenRouter не накручивает token list price — total cost = top-up fee + gateway hop + compliance boundary, не «model price × mystery multiplier».
07 FAQ: pricing, availability, security, Python
OpenRouter платный? Free + paid slugs; paid at provider token rate, top-up 5.5%.
Доступен из РФ/СНГ? API endpoint глобальный; оцените network path и data compliance самостоятельно.
Какие модели? 400+ в формате vendor/model; full list /api/v1/models.
OpenRouter vs Claude direct? Multi-model + failover: OpenRouter; exclusive APIs + hyperscale: direct.
Monthly cost? Зависит от slug и QPS — Flash agents часто $10–100, full Opus load может $1000+.
Security? Payload через gateway; sensitive data: BYOK или direct API.
Python call? Секция 05 — requests или OpenAI SDK.
08 Почему EN-страницы не получают трафик — prioritized diagnostic
P0 — Crawl/index:
- CDN/WAF blocks Googlebot — Search Console URL Inspection
- Missing hreflang — one language wins canonical
robots.txt/noindexon/en/- sitemap without per-lang URLs or alternates
- CSR empty shell — crawler sees no body
Content layer:
- Literal translation vs native queries (
OpenRouter vs OpenAI API) - No EN keyword research; weak E-E-A-T
Authority:
- CN distribution with backlinks; EN pages zero Reddit/HN/dev.to exposure
- GSC: EN URL indexed?
- CDN/WAF vs Googlebot
- hreflang, canonical, lang sitemap
- Rewrite 3–5 EN posts (not translate)
- First EN distribution: dev.to, Reddit, Hacker News
09 Multilingual SEO: keyword matrix и localization
RU: OpenRouter API, tutorial, OpenRouter vs OpenAI; long-tail: pricing, free models, Python example, fallback routing.
EN: OpenRouter API tutorial, is OpenRouter worth it, fallback routing, streaming response.
Title signals RU: полный гайд, пошагово, 2026 — keyword в title, lead, H2.
Principle: shared code blocks; per-lang title, lead, H2, FAQ; meta 120–160 chars; balanced «when NOT to use» section.
10 Multilingual site architecture, Schema и distribution channels
URL pattern (subdir, shared domain authority):
https://jexcloud.com/ru/blog/2026-0724-openrouter-api-tutorial-gpt-claude-gemini-guide.html
https://jexcloud.com/en/blog/2026-0724-openrouter-api-tutorial-gpt-claude-gemini-guide.html
hreflang (cross-ref + x-default):
<link rel="alternate" hreflang="ru" href="https://jexcloud.com/ru/blog/..." />
<link rel="alternate" hreflang="en" href="https://jexcloud.com/en/blog/..." />
<link rel="alternate" hreflang="x-default" href="https://jexcloud.com/en/blog/..." />
Per-lang canonical self-reference; sitemap xhtml:link alternates.
Schema: BlogPosting + FAQPage JSON-LD; FAQ questions in target language.
Distribution RU: Habr, Telegram tech channels; EN: dev.to, HN, Reddit r/LocalLLaMA.
11 Action checklist, tracking и JEXCLOUD production host
P0: GSC index check → CDN/WAF → hreflang/canonical/sitemap.
P1: localized posts → keywords → Article + FAQPage schema.
P2: distribution → GSC sitemap → impressions/CTR per lang path.
OpenRouter agent на личном Mac: lid closed = connection drop. Oversubscribed VPS без native macOS: SSH jitter рвёт multi-step tool loops. Shared team machine: key rotation и CLI version drift — production blockers вне scope API integration.
Для команд с 7×24 Cursor Agent, OpenClaw Gateway и OpenRouter routing стабильнее JEXCLOUD multi-region bare-metal Mac: dedicated Apple Silicon, authentic macOS, 120s provisioning, monthly flex. Model billing через OpenRouter, compute через bare metal — clean separation. Specs: pricing, onboarding: help center.