OP

openrouter-known-pitfalls

Audit your OpenRouter implementation against known pitfalls to avoid production issues and API errors.

Install

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

Installs to .claude/skills/openrouter-known-pitfalls

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.

Avoid common OpenRouter integration mistakes and gotchas. Use proactively
73 charsno explicit “when” trigger
Intermediate

Key capabilities

  • Audit code for hardcoded API keys
  • Validate model ID configurations
  • Enforce cost control via max_tokens
  • Detect unexpected provider fallbacks
  • Verify caching of deterministic responses

How it works

This skill provides a checklist and validation scripts to identify common integration errors such as missing provider prefixes, lack of token limits, and hardcoded secrets. It includes code snippets to centralize model configuration and validate availability at startup.

Inputs & outputs

You give it
Source code repository
You get back
Audit report of OpenRouter integration pitfalls

When to use openrouter-known-pitfalls

  • Auditing new OpenRouter integrations
  • Debugging unexpected 429 rate limit errors
  • Reviewing model ID configuration patterns
  • Setting up cost management controls

About this skill

OpenRouter Known Pitfalls

Overview

A curated list of real-world mistakes developers make when integrating OpenRouter, each with the specific API behavior that causes the problem and the exact fix. These are not theoretical -- they come from production incidents and support requests.

Prerequisites

  • An existing (or in-progress) OpenRouter integration to audit against the 10 pitfalls below
  • 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) to run the validation snippets (e.g., the startup check against /api/v1/models)
  • Grep access to the codebase to hunt hardcoded sk-or-v1- keys and scattered model IDs

Instructions

  1. Audit request format first: every model ID uses the provider/model form (Pitfall 1), and model IDs live in one MODELS config validated against /api/v1/models at startup instead of being scattered through the code (Pitfall 3).
  2. Check cost controls: max_tokens is set on every request (Pitfall 2) and no :free models are used in production, where the 50-1000 req/day limits will 429 you (Pitfall 5).
  3. Review routing: sensitive-data requests pin provider.order with allow_fallbacks: False (Pitfall 4), and response.model is logged on every call to catch unexpected fallbacks (Pitfall 6).
  4. Inspect client hygiene: one shared client instance with connection pooling (Pitfall 7) configured with timeout and max_retries (Pitfall 9).
  5. Sweep for secrets: grep for hardcoded sk-or-v1- strings and move any hits to env vars or a secrets manager, rotating the exposed keys (Pitfall 8).
  6. Verify caching only stores deterministic temperature=0 responses (Pitfall 10).
  7. Finish by walking the Quick Checklist (PITFALL_CHECKLIST) top to bottom — it condenses all 10 pitfalls into a code-review pass.

Pitfall 1: Missing Provider Prefix on Model ID

# WRONG: Model ID without provider prefix
response = client.chat.completions.create(
    model="gpt-4o",  # ← Will fail with 400 "model not found"
    messages=[{"role": "user", "content": "Hello"}],
)

# RIGHT: Always include provider/model format
response = client.chat.completions.create(
    model="openai/gpt-4o",  # ← Correct
    messages=[{"role": "user", "content": "Hello"}],
)

Pitfall 2: No max_tokens = Runaway Costs

# WRONG: No max_tokens -- model may generate 4000+ tokens
response = client.chat.completions.create(
    model="anthropic/claude-3.5-sonnet",  # $15/1M completion tokens
    messages=[{"role": "user", "content": "Write a story"}],
    # No max_tokens → could generate $0.06+ per request
)

# RIGHT: Always set max_tokens
response = client.chat.completions.create(
    model="anthropic/claude-3.5-sonnet",
    messages=[{"role": "user", "content": "Write a story"}],
    max_tokens=500,  # ← Caps cost at ~$0.0075
)

Pitfall 3: Hardcoded Model IDs Break When Models Are Renamed

# WRONG: Hardcoded model ID scattered across codebase
# When "claude-3-opus" becomes "claude-3-opus-20240229", everything breaks

# RIGHT: Centralize model IDs in config
MODELS = {
    "primary": "anthropic/claude-3.5-sonnet",
    "budget": "openai/gpt-4o-mini",
    "free": "google/gemma-2-9b-it:free",
}

# Validate at startup
import requests
available = {m["id"] for m in requests.get("https://openrouter.ai/api/v1/models").json()["data"]}
for name, model_id in MODELS.items():
    if model_id not in available:
        print(f"WARNING: {name} model '{model_id}' not available!")

Pitfall 4: Fallbacks Route to Unexpected Providers

# WRONG: Default allow_fallbacks=True without controlling which providers
response = client.chat.completions.create(
    model="anthropic/claude-3.5-sonnet",
    messages=[{"role": "user", "content": sensitive_data}],
    # OpenRouter might fall back to a different provider you didn't approve
)

# RIGHT: Control fallback behavior explicitly
response = client.chat.completions.create(
    model="anthropic/claude-3.5-sonnet",
    messages=[{"role": "user", "content": sensitive_data}],
    extra_body={
        "provider": {
            "order": ["Anthropic"],      # Only approved provider
            "allow_fallbacks": False,     # No surprise routing
        },
    },
)

Pitfall 5: Ignoring the Free Model Daily Limit

# WRONG: Using free models in production
# Free models have limits: 50 req/day (no credits), 1000 req/day (with credits)
response = client.chat.completions.create(
    model="google/gemma-2-9b-it:free",  # Will 429 after daily limit
    messages=[{"role": "user", "content": "Hello"}],
)

# RIGHT: Use free models only for dev/testing
# Use paid models with credit limits for production

Pitfall 6: Not Checking Which Model Actually Served the Request

# WRONG: Assuming the model you requested is the model that responded
response = client.chat.completions.create(
    model="anthropic/claude-3.5-sonnet",
    messages=[{"role": "user", "content": "Hello"}],
)
print(response.choices[0].message.content)  # Might be from a fallback model!

# RIGHT: Always check response.model
response = client.chat.completions.create(
    model="anthropic/claude-3.5-sonnet",
    messages=[{"role": "user", "content": "Hello"}],
)
print(f"Served by: {response.model}")  # Log this for debugging
if response.model != "anthropic/claude-3.5-sonnet":
    log.warning(f"Fallback triggered: requested claude-3.5-sonnet, got {response.model}")

Pitfall 7: Creating New Client Instance Per Request

# WRONG: New client per request (new TCP/TLS handshake each time)
for prompt in prompts:
    client = OpenAI(base_url="https://openrouter.ai/api/v1", api_key=key)
    client.chat.completions.create(...)  # Slow!

# RIGHT: Reuse single client (connection pooling)
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"},
)
for prompt in prompts:
    client.chat.completions.create(...)  # Reuses HTTP connection

Pitfall 8: Storing API Keys in Source Code

# WRONG: Key in source code
client = OpenAI(
    base_url="https://openrouter.ai/api/v1",
    api_key="sk-or-v1-abc123...",  # ← Will be committed to git
)

# RIGHT: Environment variable + secrets manager
client = OpenAI(
    base_url="https://openrouter.ai/api/v1",
    api_key=os.environ["OPENROUTER_API_KEY"],  # From .env (gitignored) or secrets manager
)

Pitfall 9: Not Setting Timeouts

# WRONG: No timeout -- request hangs forever if model is slow
client = OpenAI(base_url="https://openrouter.ai/api/v1", api_key=key)

# RIGHT: Set explicit timeout
client = OpenAI(
    base_url="https://openrouter.ai/api/v1",
    api_key=os.environ["OPENROUTER_API_KEY"],
    timeout=30.0,      # 30s per request
    max_retries=3,     # Retry on 429/5xx
)

Pitfall 10: Caching Non-Deterministic Responses

# WRONG: Caching responses with temperature > 0
# Each call produces different output, so cache is meaningless
cache[key] = client.chat.completions.create(
    model="openai/gpt-4o-mini",
    messages=msgs,
    temperature=0.7,  # ← Non-deterministic!
)

# RIGHT: Only cache with temperature=0
if temperature == 0:
    cache[key] = response

Quick Checklist

PITFALL_CHECKLIST = [
    "Model IDs use provider/model format (e.g., openai/gpt-4o)",
    "max_tokens set on every request",
    "API keys in env vars or secrets manager, never in code",
    "Single client instance reused (not created per request)",
    "Timeout and max_retries configured",
    "response.model checked (may differ from requested model)",
    "Free models NOT used in production",
    "Fallback behavior explicitly controlled for sensitive data",
    "Model IDs centralized in config (not scattered in code)",
    "Only deterministic responses (temp=0) are cached",
]

Output

An audit pass with this skill produces:

  • A pitfall-by-pitfall verdict on your integration — each of the 10 items either confirmed clean or flagged with the exact fix from its section
  • Startup validation output from the Pitfall 3 snippet: WARNING: primary model 'anthropic/claude-3.5-sonnet' not available! for any config entry missing from /api/v1/models
  • Fallback-detection log lines from Pitfall 6: Fallback triggered: requested claude-3.5-sonnet, got <response.model>
  • The completed PITFALL_CHECKLIST — a 10-line review artifact to attach to the integration PR

Examples

Validating your centralized model config at startup (Pitfall 3):

available = {m["id"] for m in requests.get("https://openrouter.ai/api/v1/models").json()["data"]}
for name, model_id in MODELS.items():
    if model_id not in available:
        print(f"WARNING: {name} model '{model_id}' not available!")
# WARNING: primary model 'anthropic/claude-3-opus' not available!

A warning here means a rename or removal upstream — update the one MODELS entry instead of chasing hardcoded IDs across the codebase. More worked examples: references/examples.md.

Error Handling

PitfallSymptomQuick Fix
Missing provider prefix400 model not foundAdd openai/, anthropic/, etc.
No max_tokensUnexpected high costsAdd max_tokens to every call
Hardcoded API keyKey exposed in git historyRotate key; use env vars
No timeoutHanging requestsSet timeout=30.0
Free model in prod429 after 50-1000 requestsUse paid models

Enterprise Considerations

  • Run the pitfall checklist during code review for any OpenRouter integration PR
  • Add pre-commit hooks that scan for hardcoded sk-or-v1- patterns
  • Centralize model IDs in a config file and validate against /api/v1/models at startup
  • Log response.model on every request to catch unexpected fallbacks
  • Set max_tokens as

Content truncated.

When not to use it

  • When using free models for production workloads
  • When ignoring rate limit constraints

Prerequisites

OpenRouter API keyPython 3.8+OpenAI SDK

Limitations

  • Requires manual rotation of exposed keys
  • Does not automatically fix hardcoded secrets

How it compares

This approach uses production-incident patterns to audit code, rather than relying on generic linting or manual review.

Compared to similar skills

openrouter-known-pitfalls side by side with the closest alternatives in the catalog.

SkillInstallsUpdatedSafetyDifficulty
openrouter-known-pitfalls (this skill)027dCautionIntermediate
flutter-development1,5555moNo flagsIntermediate
godot1,0445moReviewIntermediate
fastapi-templates5202moNo flagsIntermediate

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

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.

1,5551,991

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.

1,0441,947

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.

5201,086

software-architecture

davila7

Guide for quality focused software architecture. This skill should be used when users want to write code, design architecture, analyze code, in any case that relates to software development.

333868

drizzle

lobehub

Drizzle ORM schema and database guide. Use when working with database schemas (src/database/schemas/*), defining tables, creating migrations, or database model code. Triggers on Drizzle schema definition, database migrations, or ORM usage questions.

238873

frontend-design

anthropics

Create distinctive, production-grade frontend interfaces with high design quality. Use this skill when the user asks to build web components, pages, or applications. Generates creative, polished code that avoids generic AI aesthetics.

481544

Search skills

Search the agent skills registry