openrouter-common-errors

1
2
Source

Execute diagnose and fix common OpenRouter API errors. Use when troubleshooting failed requests. Trigger with phrases like 'openrouter error', 'openrouter not working', 'openrouter 401', 'openrouter 429', 'fix openrouter'.

Install

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

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

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.

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))

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 systematic issues (e.g., provider outages show as 502 spike)
  • Build a status dashboard that checks both your error rates and status.openrouter.ai
  • For 402 errors, implement credit balance monitoring with alerts at 20% remaining

References

svg-icon-generator

jeremylongshore

Svg Icon Generator - Auto-activating skill for Visual Content. Triggers on: svg icon generator, svg icon generator Part of the Visual Content skill category.

6814

d2-diagram-creator

jeremylongshore

D2 Diagram Creator - Auto-activating skill for Visual Content. Triggers on: d2 diagram creator, d2 diagram creator Part of the Visual Content skill category.

2412

performing-penetration-testing

jeremylongshore

This skill enables automated penetration testing of web applications. It uses the penetration-tester plugin to identify vulnerabilities, including OWASP Top 10 threats, and suggests exploitation techniques. Use this skill when the user requests a "penetration test", "pentest", "vulnerability assessment", or asks to "exploit" a web application. It provides comprehensive reporting on identified security flaws.

379

designing-database-schemas

jeremylongshore

Design and visualize efficient database schemas, normalize data, map relationships, and generate ERD diagrams and SQL statements.

978

performing-security-audits

jeremylongshore

This skill allows Claude to conduct comprehensive security audits of code, infrastructure, and configurations. It leverages various tools within the security-pro-pack plugin, including vulnerability scanning, compliance checking, cryptography review, and infrastructure security analysis. Use this skill when a user requests a "security audit," "vulnerability assessment," "compliance review," or any task involving identifying and mitigating security risks. It helps to ensure code and systems adhere to security best practices and compliance standards.

86

django-view-generator

jeremylongshore

Generate django view generator operations. Auto-activating skill for Backend Development. Triggers on: django view generator, django view generator Part of the Backend Development skill category. Use when working with django view generator functionality. Trigger with phrases like "django view generator", "django generator", "django".

15

You might also like

flutter-development

aj-geddes

Build beautiful cross-platform mobile apps with Flutter and Dart. Covers widgets, state management with Provider/BLoC, navigation, API integration, and material design.

643969

drawio-diagrams-enhanced

jgtolentino

Create professional draw.io (diagrams.net) diagrams in XML format (.drawio files) with integrated PMP/PMBOK methodologies, extensive visual asset libraries, and industry-standard professional templates. Use this skill when users ask to create flowcharts, swimlane diagrams, cross-functional flowcharts, org charts, network diagrams, UML diagrams, BPMN, project management diagrams (WBS, Gantt, PERT, RACI), risk matrices, stakeholder maps, or any other visual diagram in draw.io format. This skill includes access to custom shape libraries for icons, clipart, and professional symbols.

591705

ui-ux-pro-max

nextlevelbuilder

"UI/UX design intelligence. 50 styles, 21 palettes, 50 font pairings, 20 charts, 8 stacks (React, Next.js, Vue, Svelte, SwiftUI, React Native, Flutter, Tailwind). Actions: plan, build, create, design, implement, review, fix, improve, optimize, enhance, refactor, check UI/UX code. Projects: website, landing page, dashboard, admin panel, e-commerce, SaaS, portfolio, blog, mobile app, .html, .tsx, .vue, .svelte. Elements: button, modal, navbar, sidebar, card, table, form, chart. Styles: glassmorphism, claymorphism, minimalism, brutalism, neumorphism, bento grid, dark mode, responsive, skeuomorphism, flat design. Topics: color palette, accessibility, animation, layout, typography, font pairing, spacing, hover, shadow, gradient."

318398

godot

bfollington

This skill should be used when working on Godot Engine projects. It provides specialized knowledge of Godot's file formats (.gd, .tscn, .tres), architecture patterns (component-based, signal-driven, resource-based), common pitfalls, validation tools, code templates, and CLI workflows. The `godot` command is available for running the game, validating scripts, importing resources, and exporting builds. Use this skill for tasks involving Godot game development, debugging scene/resource files, implementing game systems, or creating new Godot components.

339397

nano-banana-pro

garg-aayush

Generate and edit images using Google's Nano Banana Pro (Gemini 3 Pro Image) API. Use when the user asks to generate, create, edit, modify, change, alter, or update images. Also use when user references an existing image file and asks to modify it in any way (e.g., "modify this image", "change the background", "replace X with Y"). Supports both text-to-image generation and image-to-image editing with configurable resolution (1K default, 2K, or 4K for high resolution). DO NOT read the image file first - use this skill directly with the --input-image parameter.

451339

fastapi-templates

wshobson

Create production-ready FastAPI projects with async patterns, dependency injection, and comprehensive error handling. Use when building new FastAPI applications or setting up backend API projects.

304231

Stay ahead of the MCP ecosystem

Get weekly updates on new skills and servers.