OP

openrouter-common-errors

A diagnostic guide for identifying and resolving OpenRouter API errors and HTTP status codes.

Install

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

Installs to .claude/skills/openrouter-common-errors

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.

Diagnose and fix common OpenRouter API errors. Use when encountering
68 chars✓ has a “when” trigger
Intermediate

Key capabilities

  • Identify OpenRouter API error causes by HTTP status and error code
  • Run a diagnostic script to check authentication, credits, and model availability
  • Implement a Python error handler for automatic retries of 429 and 5xx errors
  • Add pre-flight validation to catch malformed requests before API calls
  • Check OpenRouter's status page for service outages

How it works

The skill identifies the error by HTTP status and code, then runs a diagnostic script to check API key, credits, and model. It provides code for automatic retries and pre-flight validation.

Inputs & outputs

You give it
An OpenRouter API error, such as a 401, 402, 429, 400, or 5xx status code
You get back
A four-line diagnostic report, categorized exceptions, or pre-flight validation errors

When to use openrouter-common-errors

  • Troubleshoot OpenRouter 401 authentication errors
  • Resolve rate limit 429 issues
  • Debug upstream provider failures
  • Validate API request structure

About this skill

OpenRouter Common Errors

Overview

OpenRouter returns standard HTTP error codes plus OpenRouter-specific error codes in the response body. The most common: 401 (auth), 402 (credits), 429 (rate limit), 400 (bad request), and 5xx (upstream provider errors). Each error includes a code field and a human-readable message. This skill covers every common error, its root cause, and the exact fix.

Prerequisites

  • An OpenRouter API key (sk-or-v1-...) exported as OPENROUTER_API_KEY — see the openrouter-install-auth skill for setup
  • curl and jq to run the Diagnostic Script
  • Python 3.8+ with the OpenAI SDK for the categorized error handler; Node.js 18+ for the TypeScript typed-error classifier in the references
  • The requests package if you use the Prevention Middleware's pre-flight model check

Instructions

  1. Identify the failure by HTTP status and code using the Complete Error Reference table (400/401/402/403/408/429/5xx each map to a specific fix).
  2. Inspect the body per Error Response Format — error.code, error.message, and error.metadata.provider_name tell you whether OpenRouter or the upstream provider failed.
  3. Run the Diagnostic Script: it checks auth via GET /api/v1/auth/key, computes remaining credits, verifies the model exists in /api/v1/models, and fires a minimal 1-token completion.
  4. Wrap production calls with safe_completion() from Python Error Handler — max_retries=3 auto-retries 429 and 5xx, and each exception class raises with its exact remedy.
  5. Add validate_before_send() from Prevention Middleware to catch bad model IDs (with suggestions), malformed messages, and context overflows before spending money on a 400.
  6. If errors persist across retries and providers, check status.openrouter.ai per the Error Handling table.

Complete Error Reference

HTTPError CodeCauseFix
400bad_requestMalformed request bodyValidate messages array format; ensure model ID includes provider prefix
400invalid_modelModel ID not foundCheck model exists: curl -s https://openrouter.ai/api/v1/models | jq '.data[].id'
400context_length_exceededPrompt + max_tokens > model limitReduce prompt size or use a larger-context model
400invalid_tool_schemaTool definition has unsupported typesUse basic JSON Schema types only (string, number, boolean, object, array)
401invalid_api_keyKey malformed, revoked, or wrongRegenerate at openrouter.ai/keys; key must start with sk-or-v1-
401missing_api_keyNo Authorization headerAdd Authorization: Bearer sk-or-v1-... header
402insufficient_creditsCredit balance is zeroTop up at openrouter.ai/credits
402credit_limit_reachedPer-key credit limit hitIncrease key limit in dashboard or create new key
403key_disabledKey was disabled by adminRe-enable in dashboard or create new key
408request_timeoutModel took too longReduce max_tokens; use streaming; try faster model
429rate_limit_exceededToo many requests per intervalSDK auto-retries; increase max_retries; use multiple keys
502provider_errorUpstream provider returned errorRetry with backoff; try different provider via provider.order
503model_unavailableModel temporarily offlineUse fallback models; check status.openrouter.ai

Error Response Format

{
  "error": {
    "code": 401,
    "message": "Invalid API key. Please check your API key and try again.",
    "metadata": {
      "provider_name": "Anthropic",
      "raw": "..."
    }
  }
}

Diagnostic Script

#!/bin/bash
echo "=== OpenRouter Error Diagnostics ==="

# 1. Test authentication
echo -n "1. Auth: "
AUTH=$(curl -s -o /dev/null -w "%{http_code}" \
  https://openrouter.ai/api/v1/auth/key \
  -H "Authorization: Bearer $OPENROUTER_API_KEY")
[ "$AUTH" = "200" ] && echo "OK" || echo "FAIL (HTTP $AUTH)"

# 2. Check credit balance
echo -n "2. Credits: "
CREDITS=$(curl -s https://openrouter.ai/api/v1/auth/key \
  -H "Authorization: Bearer $OPENROUTER_API_KEY" | \
  jq -r '(.data.limit // 0) - .data.usage')
echo "\$$CREDITS remaining"

# 3. Test model availability
echo -n "3. Model: "
MODEL="openai/gpt-4o-mini"
EXISTS=$(curl -s https://openrouter.ai/api/v1/models | \
  jq --arg m "$MODEL" '[.data[] | select(.id == $m)] | length')
[ "$EXISTS" -gt 0 ] && echo "$MODEL available" || echo "$MODEL NOT FOUND"

# 4. Test a minimal request
echo -n "4. Request: "
RESP=$(curl -s -w "\n%{http_code}" \
  https://openrouter.ai/api/v1/chat/completions \
  -H "Authorization: Bearer $OPENROUTER_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{"model":"openai/gpt-4o-mini","messages":[{"role":"user","content":"hi"}],"max_tokens":1}')
HTTP=$(echo "$RESP" | tail -1)
[ "$HTTP" = "200" ] && echo "OK" || echo "FAIL (HTTP $HTTP)"

Python Error Handler

import os
from openai import OpenAI, APIError, AuthenticationError, RateLimitError, BadRequestError, APITimeoutError

client = OpenAI(
    base_url="https://openrouter.ai/api/v1",
    api_key=os.environ["OPENROUTER_API_KEY"],
    max_retries=3,  # Auto-retry 429 and 5xx
    timeout=30.0,
    default_headers={"HTTP-Referer": "https://my-app.com", "X-Title": "my-app"},
)

def safe_completion(messages, model="openai/gpt-4o-mini", **kwargs):
    """Completion with categorized error handling."""
    try:
        return client.chat.completions.create(
            model=model, messages=messages, **kwargs
        )
    except AuthenticationError as e:
        # 401: Bad or missing API key
        raise SystemExit(f"AUTH ERROR: Check OPENROUTER_API_KEY. {e}")
    except BadRequestError as e:
        # 400: Bad model ID, invalid params, context too long
        if "context_length" in str(e):
            raise ValueError(f"Prompt too long for {model}. Trim or use larger-context model.")
        raise ValueError(f"Bad request: {e}")
    except RateLimitError:
        # 429: SDK already retried max_retries times
        raise RuntimeError("Rate limited after all retries. Wait or use more API keys.")
    except APITimeoutError:
        # Timeout: model too slow
        raise TimeoutError(f"Model {model} timed out. Try streaming or a faster model.")
    except APIError as e:
        # 402, 5xx, other
        if e.status_code == 402:
            raise RuntimeError("Insufficient credits. Top up at openrouter.ai/credits")
        raise RuntimeError(f"API error {e.status_code}: {e}")

Prevention Middleware

import requests

def validate_before_send(model: str, messages: list, max_tokens: int = 1024):
    """Pre-flight validation to catch common mistakes before API call."""
    errors = []

    # Check model exists
    models = requests.get("https://openrouter.ai/api/v1/models").json()["data"]
    model_ids = {m["id"] for m in models}
    if model not in model_ids:
        # Try to suggest correct ID
        prefix = model.split("/")[0] if "/" in model else ""
        suggestions = [m for m in model_ids if prefix and m.startswith(prefix)][:3]
        errors.append(f"Model '{model}' not found. Did you mean: {suggestions}")

    # Check messages format
    if not messages or not isinstance(messages, list):
        errors.append("messages must be a non-empty list")
    for msg in messages:
        if "role" not in msg or "content" not in msg:
            errors.append(f"Each message needs 'role' and 'content': {msg}")

    # Estimate context usage
    total_chars = sum(len(str(m.get("content", ""))) for m in messages)
    est_tokens = total_chars // 4
    model_info = next((m for m in models if m["id"] == model), None)
    if model_info:
        ctx_limit = model_info["context_length"]
        if est_tokens + max_tokens > ctx_limit:
            errors.append(f"Estimated {est_tokens} + {max_tokens} max_tokens > {ctx_limit} context limit")

    if errors:
        raise ValueError("Pre-flight validation failed:\n" + "\n".join(f"  - {e}" for e in errors))

Output

  • A four-line diagnostic report: auth OK/FAIL, dollars of credit remaining, model availability in /api/v1/models, and the HTTP status of a minimal live request
  • Categorized exceptions from safe_completion() — auth failures exit pointing at the key, 402s point at credit top-up, context overflows raise ValueError naming the model to trim for
  • Pre-flight ValueErrors from validate_before_send() listing every problem found (unknown model with suggested IDs, missing role/content fields, estimated-token overflow) before any API call is made

Examples

A healthy integration produces this from the Diagnostic Script:

=== OpenRouter Error Diagnostics ===
1. Auth: OK
2. Credits: $46.58 remaining
3. Model: openai/gpt-4o-mini available
4. Request: OK

Any FAIL line maps straight to a row in the Complete Error Reference table — e.g. 1. Auth: FAIL (HTTP 401) means regenerating the key at openrouter.ai/keys. More worked examples: references/examples.md.

Error Handling

ScenarioSDK BehaviorYour Action
429 rate limitAuto-retries with backoffIncrease max_retries or add keys
5xx server errorAuto-retries with backoffIncrease max_retries; add fallback models
401 auth errorFails immediately (no retry)Fix API key and retry
400 bad requestFails immediately (no retry)Fix request parameters
402 no creditsFails immediately (no retry)Top up credits

Enterprise Considerations

  • The OpenAI SDK handles 429 and 5xx retries automatically -- configure max_retries (default 2, recommend 3-5)
  • Implement pre-flight validation to catch 400 errors before making API calls (saves money and time)
  • Log error codes and rates to detect systemat

Content truncated.

When not to use it

  • When the issue is not related to OpenRouter API errors
  • When debugging non-API related application failures

Prerequisites

An OpenRouter API key exported as OPENROUTER_API_KEYcurl and jq to run the Diagnostic ScriptPython 3.8+ with the OpenAI SDK for the categorized error handlerThe requests package if you use the Prevention Middleware's pre-flight model check

Limitations

  • The skill focuses only on OpenRouter API errors
  • The skill does not cover issues outside of API responses or authentication

How it compares

This skill provides specific code examples and a diagnostic script to troubleshoot OpenRouter API errors, unlike manually checking error codes and documentation.

Compared to similar skills

openrouter-common-errors side by side with the closest alternatives in the catalog.

SkillInstallsUpdatedSafetyDifficulty
openrouter-common-errors (this skill)327dCautionIntermediate
n8n-expression-syntax64moNo flagsBeginner
claude-in-chrome-troubleshooting22moReviewIntermediate
linear-common-errors127dCautionAdvanced

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

n8n-expression-syntax

czlonkowski

Validate n8n expression syntax and fix common errors. Use when writing n8n expressions, using {{}} syntax, accessing $json/$node variables, troubleshooting expression errors, or working with webhook data in workflows.

6111

claude-in-chrome-troubleshooting

trailofbits

Diagnose and fix Claude in Chrome MCP extension connectivity issues. Use when mcp__claude-in-chrome__* tools fail, return "Browser extension is not connected", or behave erratically.

211

linear-common-errors

jeremylongshore

Diagnose and fix common Linear API errors. Use when encountering Linear API errors, debugging integration issues, or troubleshooting authentication problems. Trigger with phrases like "linear error", "linear API error", "debug linear", "linear not working", "linear authentication error".

16

gamma-common-errors

jeremylongshore

Debug and resolve common Gamma API errors. Use when encountering authentication failures, rate limits, generation errors, or unexpected API responses. Trigger with phrases like "gamma error", "gamma not working", "gamma API error", "gamma debug", "gamma troubleshoot".

12

groq-common-errors

jeremylongshore

Diagnose and fix Groq common errors and exceptions. Use when encountering Groq errors, debugging failed requests, or troubleshooting integration issues. Trigger with phrases like "groq error", "fix groq", "groq not working", "debug groq".

12

linear-debug-bundle

jeremylongshore

Comprehensive debugging toolkit for Linear integrations. Use when setting up logging, tracing API calls, or building debug utilities for Linear. Trigger with phrases like "debug linear integration", "linear logging", "trace linear API", "linear debugging tools", "linear troubleshooting".

12

Search skills

Search the agent skills registry