jrajasekera/claude-skills/openrouter-api

Claude Code and agent skill by jrajasekera/claude-skills

Trust tier 3
  • community
Source check pending

Checking that the SKILL.md file is still in the repository.

Build, migrate, debug, and operate integrations with the OpenRouter API. Covers live model and provider discovery, Chat Completions, the stateless Responses API, the Anthropic-compatible Messages API, official SDKs, routing and fallbacks, reasoning, structured outputs, client and server tools, streaming, multimodal inputs, image/audio/video generation, embeddings, reranking, caching, OAuth, administration, observability, privacy, and production error handling. Use whenever code calls openrouter.ai, a user asks which OpenRouter endpoint/model/provider to use, or an existing OpenRouter integration may be stale.

Install

npx vskill@latest install jrajasekera/claude-skills/openrouter-api

SKILL.md

OpenRouter API

Last verified against OpenRouter's public documentation, OpenAPI specification, changelog, and official skill repository: 2026-07-25.

OpenRouter exposes several interoperable API “skins” plus specialized media, retrieval, and administration endpoints under one base URL:

text
https://openrouter.ai/api/v1

The endpoint surface is relatively stable, but the model catalog, aliases, providers, capabilities, accepted parameters, prices, rate limits, service tiers, and beta features change frequently.

Non-negotiable operating rules

  1. Discover live metadata; do not guess. Never invent a model ID, provider slug, voice, price, context limit, media dimension, duration, supported parameter, or rate limit. Query the catalog and, for beta or unfamiliar endpoints, inspect the current OpenAPI schema.
  2. Use a concrete model ID for reproducibility. Use a ~author/family-latest alias or a router only when automatic upgrades are an intentional product decision. Record the concrete model returned by OpenRouter.
  3. Match capabilities before sending the request. Inspect architecture.input_modalities, architecture.output_modalities, supported_parameters, model-level reasoning metadata, and provider endpoint metadata.
  4. Choose the API skin deliberately. Chat Completions, Responses, and Messages use different request, response, streaming, tool, and error shapes. Do not mix fields between them casually.
  5. Treat Responses, server tools, response caching, dedicated media APIs, and other marked features as evolving. Check the changelog and OpenAPI before shipping generated types or durable abstractions.
  6. Distinguish three extension mechanisms: user-defined function tools are executed by the caller; OpenRouter server tools can run zero or more times during a request; plugins transform a request or response once.
  7. Distinguish prompt caching from response caching. Provider prompt caches reduce repeated input processing. OpenRouter response caching can replay an identical completed response from the edge.
  8. Preserve continuation state exactly. When continuing a conversation, round-trip reasoning_details unchanged and in the original order. Never synthesize, edit, or reorder encrypted/signed reasoning blocks. Preserve and resend assistant phase metadata (commentary or final_answer) whenever the response supplies it.
  9. Parse streams as SSE, not newline-delimited JSON. Buffer partial frames, ignore comments, recognize [DONE], and handle in-band errors after HTTP status 200.
  10. Keep credentials out of clients, logs, prompts, screenshots, and repositories. A management key is more privileged than an inference key and must remain server-side. Use OAuth PKCE only when the product intentionally lets users authorize their own OpenRouter key.
  11. Do not retry permanent failures unchanged. Retry only transient failures with bounded exponential backoff and jitter, honoring Retry-After. Once a stream has emitted content, provider fallback cannot safely restart it.
  12. Log identifiers and routing facts, not sensitive payloads. Capture X-Generation-Id, the response id, resolved model/provider, typed error_type, cache status, service tier, and optional router metadata.

Start every task with this decision flow

1. Choose the API surface
NeedEndpoint or packageNotes
General text, reasoning, structured output, tools, multimodal inputPOST /chat/completionsBroadest OpenAI-compatible surface
OpenAI Responses-compatible typed items and server toolsPOST /responsesBeta and stateless; send the full required history
Anthropic Messages-compatible clients and payloadsPOST /messagesAnthropic-shaped messages, thinking, tools, and streaming
Legacy text completionPOST /completionsUse only for an existing compatibility requirement
Text or multimodal embeddingsPOST /embeddingsDiscover with GET /embeddings/models or the filtered general catalog
Rank documents against a queryPOST /rerankDocuments may be strings or supported structured inputs
Generate or edit an imagePOST /imagesDedicated Image API; discover per-model controls first
Text-to-speechPOST /audio/speechReturns raw audio bytes, not JSON on success
Speech-to-textPOST /audio/transcriptionsJSON/base64 or OpenAI-style multipart body
Generate videoPOST /videos then pollAsynchronous submit, poll, and download workflow
Upload, list, inspect, or delete reusable filesGET/POST /files, /files/{file_id}*Multipart upload; workspace-scoped IDs and cursor pagination
Browse text/embedding/general modelsGET /modelsPublic catalog with filters, prices, modalities, and parameters
Inspect one modelGET /model/{author}/{slug}Singular model path
Inspect serving endpoints for a modelGET /models/{author}/{slug}/endpointsProvider performance, pricing, capabilities, and status
Inspect image or video capabilities/images/models*, /videos/models*Dedicated model metadata for media controls
Direct, type-safe API access@openrouter/sdk, openrouter, Go SDKThin clients generated from OpenAPI
Managed agent loop and caller tools@openrouter/agentTypeScript agent primitives and stop conditions
User-authorized API keyOAuth PKCENo client secret; validate the pending PKCE callback/session and store keys securely
Keys, guardrails, workspaces, analyticsManagement APIsRequire a management/provisioning key where documented
2. Discover the current model and endpoint capabilities

Use the included dependency-free helper:

bash
# Browse and filter models
python scripts/discover_models.py --query coding --output-modality text
python scripts/discover_models.py --parameter tools --parameter structured_outputs
python scripts/discover_models.py --output-modality embeddings --json
# Inspect a concrete model and its provider endpoints
python scripts/discover_models.py --model 'author/model-slug' --json
python scripts/discover_models.py --endpoints 'author/model-slug' --json
# Inspect dedicated media catalogs
python scripts/discover_models.py --image-endpoints 'author/image-model' --json
python scripts/discover_models.py --video-models --json

The catalog endpoint is also directly callable:

bash
curl -sS 'https://openrouter.ai/api/v1/models?output_modalities=text' \
-H 'Accept: application/json'

Before selecting a model, inspect at least:

  • exact id, canonical_slug, expiration_date, and returned alias resolution;
  • context_length and top_provider.max_completion_tokens;
  • architecture.input_modalities and architecture.output_modalities;
  • supported_parameters, especially tools, structured_outputs, reasoning, and search-related parameters;
  • model-level reasoning metadata such as supported efforts, default state, and whether reasoning is mandatory;
  • pricing fields, remembering token prices are normally per token as decimal strings, and pricing.overrides for long-context or UTC-window pricing exceptions;
  • endpoint status, latency/throughput percentiles, quantization, data policy, service tier, and accepted parameters.

For a recently added or beta endpoint, inspect the live schema:

bash
python scripts/inspect_openapi.py --search responses
python scripts/inspect_openapi.py --path /responses
python scripts/inspect_openapi.py --schema ResponsesRequest

See references/routing-providers.md and references/api-endpoints.md.

3. Validate the request against the selected model

Do not assume that a provider silently ignores unsupported parameters. Prefer one of these approaches:

  • omit optional fields the selected model does not advertise;
  • set provider.require_parameters: true so routing only considers endpoints that support every supplied parameter;
  • explicitly constrain provider.only, provider.ignore, or provider.order using current provider slugs;
  • supply a compatible models fallback list rather than falling back to models with incompatible modalities or tools.
4. Select a stable or adaptive routing strategy
  • Pinned concrete ID: evaluations, regression tests, reproducible production behavior.
  • Latest alias (`~author/family-latest`): automatic upgrades within a known model family.
  • Multiple `models`: explicit ordered model fallback.
  • Provider preferences: control cost, latency, throughput, data policy, service tier, or provider.
  • OpenRouter router: task-aware or specialized model selection; always read the returned concrete model.

Do not hardcode the current members or defaults of a router. See references/routing-providers.md.

Authentication and app attribution

Required for authenticated endpoints:

http
Authorization: Bearer $OPENROUTER_API_KEY
Content-Type: application/json

Optional attribution headers:

http
HTTP-Referer: https://your-app.example
X-OpenRouter-Title: Your App Name
X-OpenRouter-Categories: cli-agent,programming-app

X-OpenRouter-Title is the preferred title header. The older X-Title name remains a compatibility alias but should not be used in new integrations.

Minimal REST request

Require the caller to choose a live model rather than embedding a dated example:

bash
: "${OPENROUTER_API_KEY:?Set OPENROUTER_API_KEY}"
: "${OPENROUTER_MODEL:?Set OPENROUTER_MODEL to an ID from /models}"
curl -sS https://openrouter.ai/api/v1/chat/completions \
-H "Authorization: Bearer $OPENROUTER_API_KEY" \
-H 'Content-Type: application/json' \
-H 'X-OpenRouter-Metadata: enabled' \
-d "$(jq -n --arg model "$OPENROUTER_MODEL" '{
model: $model,
messages: [{role: "user", content: "Explain optimistic concurrency control."}]
}')"

Official client SDK quick starts

TypeScript
typescript
import { OpenRouter } from "@openrouter/sdk";
const model = process.env.OPENROUTER_MODEL;
if (!model) throw new Error("Set OPENROUTER_MODEL from the live /models catalog");
const client = new OpenRouter({
apiKey: process.env.OPENROUTER_API_KEY ?? "",
httpReferer: "https://your-app.example",
appTitle: "Your App",
});
const response = await client.chat.send({
model,
messages: [{ role: "user", content: "Hello from OpenRouter" }],
});
console.log(response.choices[0]?.message.content);
console.log("Resolved model:", response.model);
Python
python
import os
from openrouter import OpenRouter
model = os.environ["OPENROUTER_MODEL"]
with OpenRouter(
api_key=os.environ["OPENROUTER_API_KEY"],
http_referer="https://your-app.example",
x_open_router_title="Your App",
) as client:
response = client.chat.send(
model=model,
messages=[{"role": "user", "content": "Hello from OpenRouter"}],
)
print(response.choices[0].message.content)
print("Resolved model:", response.model)

The official client SDKs mirror the REST API. Use @openrouter/agent when a TypeScript application wants OpenRouter to manage a multi-turn caller-tool loop. Use OpenAI or Anthropic SDK compatibility when migrating an existing codebase, but place OpenRouter-only fields in the SDK's extension mechanism (extra_body, extra headers, or equivalent). See references/sdk-integration.md.

Core request patterns

Structured output

Require live support for structured_outputs, route only to compatible endpoints, and still validate the returned value locally:

This is the start of the file. Read the full SKILL.md on GitHub.

Security

  • Security scanPassed, 92 of 100Pattern checks on the skill's files.
  • Model reviewPassed

Quality evaluation

  • Task evaluationNot runNo evaluation yet. Run one in Skill Studio.

Source

Popularity

Repository stars
1
7-day trend score
3

Stars and forks are for the whole GitHub repository, not this skill alone. Refreshed 17 Mar 2026, 8 months ago.

Works with

Any agent vskill installs to: 56 targets in all. These 39 have a page on this site.

  • Claude Code
  • Cursor
  • GitHub Copilot
  • Windsurf
  • Codex
  • Gemini CLI
  • Cline
  • Amp
  • Roo Code
  • Goose
  • Continue
  • Kilo Code
  • Junie
  • Trae
  • OpenHands
  • Qwen Code
  • AI Agent
  • Tabnine Chat
  • Sourcegraph Cody
  • Amazon Q
  • Firebase Genkit
  • Sweep
  • Devin
  • Phind
  • Mentat
  • Claude Desktop
  • Aider
  • GPT Pilot
  • Plandex
  • bolt.new
  • v0
  • Replit Agent
  • Anse
  • TypingMind
  • BetterChatGPT
  • LibreChat
  • Warp AI
  • Pieces
  • Fig AI
Embed badge
vskill VERIFIED badge
[![vskill VERIFIED](https://verified-skill.com/api/v1/skills/jrajasekera/claude-skills/openrouter-api/badge)](https://verified-skill.com/skills/jrajasekera/claude-skills/openrouter-api)

Something wrong with this skill or its page? Tell us.