OP

openrouter-fallback-config

Sets up automatic model failover chains on OpenRouter to ensure uptime during provider outages.

Install

mkdir -p .claude/skills/openrouter-fallback-config && curl -L -o skill.zip "https://agentskills.codes/api/skills/download/2756" && unzip -o skill.zip -d .claude/skills/openrouter-fallback-config && rm skill.zip

Installs to .claude/skills/openrouter-fallback-config

Activation

This is the description your AI agent reads to decide when to run this skill — the better it matches your request, the more reliably it fires.

Configure automatic model fallbacks for high availability on OpenRouter.
72 charsno explicit “when” trigger
Advanced

Key capabilities

  • Configure native model fallbacks on OpenRouter for server-side resilience
  • Log `response.model` to detect when a fallback model served a request
  • Implement provider fallbacks to use the same model from different vendors
  • Create client-side fallback chains with per-model timeouts and custom error handling
  • Match fallback models by capability for tool calling, vision, or context length
  • Test fallback behavior by intentionally failing the primary model

How it works

The skill configures OpenRouter to try multiple models in order until one succeeds, either natively on the server, by specifying provider order, or through a client-side chain with timeouts.

Inputs & outputs

You give it
OpenRouter API requests with multiple model IDs or provider order specifications
You get back
LLM responses served by the primary model or a fallback model, with logging of the serving model

When to use openrouter-fallback-config

  • Configuring server-side model fallbacks
  • Building provider-agnostic AI systems
  • Handling API outages gracefully
  • Setting up high-availability routing for LLMs

About this skill

OpenRouter Fallback Config

Overview

OpenRouter supports native model fallbacks: pass multiple model IDs and OpenRouter tries each in order until one succeeds. You can also use provider.order to control which provider serves a specific model. This skill covers native fallbacks, provider routing, client-side fallback chains, and timeout configuration.

Prerequisites

  • An OpenRouter API key (sk-or-v1-...) exported as OPENROUTER_API_KEY — see the openrouter-install-auth skill for setup
  • Python 3.8+ with the OpenAI SDK (pip install openai) for the fallback patterns; curl and jq for the Testing Fallbacks step
  • A ranked list of acceptable models for your workload, matched by capability (tool calling, vision, context length) so a fallback never silently drops a feature you depend on

Instructions

  1. Start with Native Model Fallback (Server-Side): pass a models array plus route: "fallback" in extra_body and let OpenRouter try each model in order.
  2. Log response.model after every call — it tells you which model actually served the request, which is how you detect that a fallback fired.
  3. If you need the same model from specific vendors (e.g., Claude via Anthropic direct vs AWS Bedrock), use Provider Fallback with provider.order and allow_fallbacks.
  4. For per-model timeouts and custom error handling, implement the Client-Side Fallback Chain: resilient_completion() walks FALLBACK_CHAIN (primary → secondary → budget-fallback → last-resort) and raises once every entry fails.
  5. Pick chains per feature with Fallback with Capability Matching — CAPABILITY_CHAINS keeps tool-calling, vision, long-context, and budget workloads on models that actually support them.
  6. Verify the behavior with Testing Fallbacks: send the curl request with an invalid primary model and confirm the response comes back from openai/gpt-4o-mini.

Native Model Fallback (Server-Side)

import os
from openai import OpenAI

client = OpenAI(
    base_url="https://openrouter.ai/api/v1",
    api_key=os.environ["OPENROUTER_API_KEY"],
    default_headers={"HTTP-Referer": "https://my-app.com", "X-Title": "my-app"},
)

# Pass multiple models -- OpenRouter tries each in order
response = client.chat.completions.create(
    model="anthropic/claude-3.5-sonnet",  # Primary (used for param validation)
    messages=[{"role": "user", "content": "Explain recursion"}],
    max_tokens=500,
    extra_body={
        "models": [
            "anthropic/claude-3.5-sonnet",
            "openai/gpt-4o",
            "google/gemini-2.0-flash-001",
        ],
        "route": "fallback",  # Try in order until one succeeds
    },
)

# Check which model actually served the request
print(f"Served by: {response.model}")

Provider Fallback (Same Model, Different Providers)

# Route to specific providers in priority order
response = client.chat.completions.create(
    model="anthropic/claude-3.5-sonnet",
    messages=[{"role": "user", "content": "Hello"}],
    max_tokens=200,
    extra_body={
        "provider": {
            "order": ["Anthropic", "AWS Bedrock", "GCP Vertex"],
            "allow_fallbacks": True,  # Fall to next provider if first fails
        },
    },
)

Client-Side Fallback Chain

import logging
from openai import OpenAI, APIError, APITimeoutError

log = logging.getLogger("openrouter.fallback")

FALLBACK_CHAIN = [
    {"model": "anthropic/claude-3.5-sonnet", "timeout": 30.0, "label": "primary"},
    {"model": "openai/gpt-4o", "timeout": 25.0, "label": "secondary"},
    {"model": "openai/gpt-4o-mini", "timeout": 15.0, "label": "budget-fallback"},
    {"model": "google/gemini-2.0-flash-001", "timeout": 15.0, "label": "last-resort"},
]

def resilient_completion(messages: list[dict], max_tokens: int = 1024, **kwargs):
    """Try each model in the fallback chain until one succeeds."""
    last_error = None

    for config in FALLBACK_CHAIN:
        try:
            client = OpenAI(
                base_url="https://openrouter.ai/api/v1",
                api_key=os.environ["OPENROUTER_API_KEY"],
                timeout=config["timeout"],
                default_headers={"HTTP-Referer": "https://my-app.com", "X-Title": "my-app"},
            )
            response = client.chat.completions.create(
                model=config["model"],
                messages=messages,
                max_tokens=max_tokens,
                **kwargs,
            )
            log.info(f"Served by {config['label']}: {response.model}")
            return response

        except (APIError, APITimeoutError) as e:
            last_error = e
            log.warning(f"{config['label']} failed ({config['model']}): {e}")
            continue

    raise RuntimeError(f"All fallbacks exhausted. Last error: {last_error}")

Fallback with Capability Matching

# Different models support different features. Match capabilities.
CAPABILITY_CHAINS = {
    "tool_calling": [
        "anthropic/claude-3.5-sonnet",
        "openai/gpt-4o",
        "openai/gpt-4o-mini",
    ],
    "vision": [
        "openai/gpt-4o",
        "anthropic/claude-3.5-sonnet",
        "google/gemini-2.0-flash-001",
    ],
    "long_context": [
        "google/gemini-2.0-flash-001",    # 1M context
        "anthropic/claude-3.5-sonnet",     # 200K context
        "openai/gpt-4o",                   # 128K context
    ],
    "budget": [
        "openai/gpt-4o-mini",
        "meta-llama/llama-3.1-8b-instruct",
        "google/gemma-2-9b-it:free",
    ],
}

def capability_fallback(messages, capability="tool_calling", **kwargs):
    """Select fallback chain based on required capability."""
    chain = CAPABILITY_CHAINS.get(capability, CAPABILITY_CHAINS["tool_calling"])
    return resilient_completion(messages, **kwargs)  # Uses FALLBACK_CHAIN

Testing Fallbacks

# Test with an invalid model to trigger fallback
curl -s https://openrouter.ai/api/v1/chat/completions \
  -H "Authorization: Bearer $OPENROUTER_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{
    "model": "invalid/model-name",
    "messages": [{"role": "user", "content": "test"}],
    "max_tokens": 10,
    "models": ["invalid/model-name", "openai/gpt-4o-mini"],
    "route": "fallback"
  }' | jq '{model: .model, content: .choices[0].message.content}'
# Should succeed with openai/gpt-4o-mini

Output

A configured fallback setup produces:

  • Chat completions whose response.model field reveals the model that actually served each request — the primary when healthy, a chain entry when a fallback fired
  • Log lines from resilient_completion(): Served by primary: anthropic/claude-3.5-sonnet on success, primary failed (anthropic/claude-3.5-sonnet): ... warnings per failed hop
  • A RuntimeError("All fallbacks exhausted. Last error: ...") when every model in FALLBACK_CHAIN fails — the signal to alert on
  • From the Testing Fallbacks curl: a {model, content} JSON showing the request survived an invalid primary model

Examples

Force a fallback by putting an invalid model first in the models array:

curl -s https://openrouter.ai/api/v1/chat/completions \
  -H "Authorization: Bearer $OPENROUTER_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{"model": "invalid/model-name", "messages": [{"role": "user", "content": "test"}],
       "max_tokens": 10, "models": ["invalid/model-name", "openai/gpt-4o-mini"], "route": "fallback"}' \
  | jq '{model: .model, content: .choices[0].message.content}'
{"model": "openai/gpt-4o-mini", "content": "Test received!"}

The model field proves the fallback chain worked. More worked examples: references/examples.md.

Error Handling

ErrorCauseFix
All fallbacks exhaustedEvery model in chain failedAdd more diverse providers; alert on full chain failure
Slow cascadeEach model timing out sequentiallyReduce per-model timeout to 10-15s
Inconsistent responsesDifferent models have different capabilitiesEnsure all fallback models support features your prompt uses
Wrong model servedFallback triggered unexpectedlyLog which model served each request; check primary model health

Enterprise Considerations

  • Use server-side fallback (models + route: "fallback") for simplicity; client-side for fine-grained control
  • Set per-model timeouts -- expensive models get longer timeouts, budget fallbacks get shorter
  • Log which model served each request to track fallback frequency (indicates primary model issues)
  • Test fallback chains regularly by intentionally failing the primary model
  • Match fallback models by capability (tool calling, vision, context length) to avoid silent feature degradation
  • Use provider.order when you need the same model from a different provider (e.g., Claude via Anthropic direct vs AWS Bedrock)

References

When not to use it

  • When a ranked list of acceptable models for your workload is not available
  • When models in the fallback chain do not support features your prompt uses

Prerequisites

An OpenRouter API key exported as OPENROUTER_API_KEYPython 3.8+ with the OpenAI SDKcurl and jq for testing fallbacks

Limitations

  • Different models have different capabilities, which can lead to inconsistent responses if not matched
  • Slow cascades can occur if each model times out sequentially

How it compares

This skill provides specific OpenRouter configurations and Python code for implementing model fallbacks, offering a concrete solution compared to general discussions of LLM reliability.

Compared to similar skills

openrouter-fallback-config side by side with the closest alternatives in the catalog.

SkillInstallsUpdatedSafetyDifficulty
openrouter-fallback-config (this skill)225dCautionAdvanced
openrouter199moReviewIntermediate
langchain-architecture82moReviewIntermediate
ai-sdk112moReviewAdvanced

Try saying

Example prompts that trigger this skill in your AI assistant.

More by jeremylongshore

View all by jeremylongshore

analyzing-logs

jeremylongshore

Analyze application logs to detect performance issues, identify error patterns, and improve stability by extracting key insights.

14123

ollama-setup

jeremylongshore

Configure auto-configure Ollama when user needs local LLM deployment, free AI alternatives, or wants to eliminate hosted API costs. Trigger phrases: "install ollama", "local AI", "free LLM", "self-hosted AI", "replace OpenAI", "no API costs". Use when appropriate context detected. Trigger with relevant phrases based on skill purpose.

1167

backtesting-trading-strategies

jeremylongshore

Backtest crypto and traditional trading strategies against historical data. Calculates performance metrics (Sharpe, Sortino, max drawdown), generates equity curves, and optimizes strategy parameters. Use when user wants to test a trading strategy, validate signals, or compare approaches. Trigger with phrases like "backtest strategy", "test trading strategy", "historical performance", "simulate trades", "optimize parameters", or "validate signals".

1071

generating-database-seed-data

jeremylongshore

Process this skill enables AI assistant to generate realistic test data and database seed scripts for development and testing environments. it uses faker libraries to create realistic data, maintains relational integrity, and allows configurable data volumes. u... Use when working with databases or data models. Trigger with phrases like 'database', 'query', or 'schema'.

1033

cursor-codebase-indexing

jeremylongshore

Execute set up and optimize Cursor codebase indexing. Triggers on "cursor index setup", "codebase indexing", "index codebase", "cursor semantic search". Use when working with cursor codebase indexing functionality. Trigger with phrases like "cursor codebase indexing", "cursor indexing", "cursor".

885

testing-mobile-apps

jeremylongshore

Execute mobile app testing on iOS and Android devices/simulators. Use when performing specialized testing. Trigger with phrases like "test mobile app", "run iOS tests", or "validate Android functionality".

810

You might also like

openrouter

rawveg

OpenRouter API - Unified access to 400+ AI models through one API

19178

langchain-architecture

wshobson

Design LLM applications using the LangChain framework with agents, memory, and tool integration patterns. Use when building LangChain applications, implementing AI agents, or creating complex LLM workflows.

899

ai-sdk

vercel

Answer questions about the AI SDK and help build AI-powered features. Use when developers: (1) Ask about AI SDK functions like generateText, streamText, ToolLoopAgent, embed, or tools, (2) Want to build AI agents, chatbots, RAG systems, or text generation features, (3) Have questions about AI providers (OpenAI, Anthropic, Google, etc.), streaming, tool calling, structured output, or embeddings, (4) Use React hooks like useChat or useCompletion. Triggers on: "AI SDK", "Vercel AI SDK", "generateText", "streamText", "add AI to my app", "build an agent", "tool calling", "structured output", "useChat".

1150

voice-ai-development

davila7

Expert in building voice AI applications - from real-time voice agents to voice-enabled apps. Covers OpenAI Realtime API, Vapi for voice agents, Deepgram for transcription, ElevenLabs for synthesis, LiveKit for real-time infrastructure, and WebRTC fundamentals. Knows how to build low-latency, production-ready voice experiences. Use when: voice ai, voice agent, speech to text, text to speech, realtime voice.

553

python-sdk

comet-ml

Python SDK patterns for Opik. Use when working in sdks/python, on SDK APIs, integrations, or message processing.

426

hugging-face-tool-builder

patchy631

Use this skill when the user wants to build tool/scripts or achieve a task where using data from the Hugging Face API would help. This is especially useful when chaining or combining API calls or the task will be repeated/automated. This Skill creates a reusable script to fetch, enrich or process data.

714

Search skills

Search the agent skills registry