OP

openrouter-model-routing

Configures dynamic routing to automatically assign tasks to the most efficient OpenRouter model based on complexity and budget.

Install

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

Installs to .claude/skills/openrouter-model-routing

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.

Implement intelligent model routing to optimize cost, quality, and latency
74 charsno explicit “when” trigger
Intermediate

Key capabilities

  • Route requests to specific model tiers based on task type
  • Classify prompt complexity using heuristics
  • Implement fallback chains for model availability
  • Fetch live model pricing data
  • Log routing decisions for audit trails

How it works

It maps task categories to predefined model tiers and uses a routing function to select the appropriate model, optionally using complexity heuristics to auto-route.

Inputs & outputs

You give it
A task type and prompt messages
You get back
A model response along with the chosen tier and token usage

When to use openrouter-model-routing

  • Route coding tasks to premium models and summarization to budget models
  • A/B test different model outputs
  • Optimize token costs based on task difficulty
  • Implement failover logic for model availability

About this skill

OpenRouter Model Routing

Overview

OpenRouter gives you access to 100+ models through one API. The key to cost efficiency is routing each request to the right model based on task complexity, required capabilities, cost budget, and latency requirements. This skill covers task-based routing, complexity classification, cost-aware selection, and OpenRouter's native routing features.

Prerequisites

  • An OpenRouter API key exported as OPENROUTER_API_KEY — see the openrouter-install-auth skill for setup
  • Python 3.8+ with the OpenAI SDK and requests (pip install openai requests)
  • A rough inventory of your task mix (classification, summarization, code generation, deep reasoning, ...) to seed the TASK_ROUTING table
  • Credits sized for the tiers you route to — the premium tier (openai/o1) runs $15/$60 per 1M tokens, 250x the budget tier

Instructions

  1. Define your tiers per Task-Based Router: the MODELS dict (free → budget → mid → standard → premium) and the TASK_ROUTING map, then send requests through route_request(), which returns content, the serving model, tier, and token count.
  2. When callers can't label tasks, switch to the Complexity-Based Auto-Router — classify_complexity() scores word count, code, reasoning, and math markers to pick a tier inside auto_route().
  3. Add resilience per OpenRouter Native Routing: extra_body={"models": [...], "route": "fallback"} tries models in order, provider.order controls which provider serves, and the :floor variant picks the cheapest provider automatically.
  4. Keep pricing current per Cost-Aware Router — get_model_pricing() pulls live per-1M rates from GET /api/v1/models, and cheapest_model_for_task() selects under context/tooling constraints.
  5. Log every routing decision (task type, tier, model, cost) and tune per Error Handling and Enterprise Considerations — escalate the tier on quality regressions and cap per-request cost with max_tokens.

Task-Based Router

import os, re
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"},
)

# Model tiers by cost and capability
MODELS = {
    "free":    "google/gemma-2-9b-it:free",          # $0/0 — testing only
    "budget":  "meta-llama/llama-3.1-8b-instruct",   # $0.06/$0.06 per 1M
    "mid":     "openai/gpt-4o-mini",                  # $0.15/$0.60 per 1M
    "standard":"anthropic/claude-3.5-sonnet",         # $3/$15 per 1M
    "premium": "openai/o1",                           # $15/$60 per 1M
}

TASK_ROUTING = {
    "classification":  "budget",   # Simple label assignment
    "translation":     "mid",      # Moderate quality needed
    "summarization":   "mid",      # Good quality, cost-effective
    "code_generation": "standard", # Needs high accuracy
    "code_review":     "standard", # Needs reasoning
    "analysis":        "standard", # Complex reasoning
    "creative_writing":"standard", # Quality matters
    "deep_reasoning":  "premium",  # Multi-step logic
    "simple_qa":       "budget",   # Basic questions
    "chat":            "mid",      # General conversation
}

def route_request(task_type: str, messages: list[dict], **kwargs) -> dict:
    """Route to appropriate model based on task type."""
    tier = TASK_ROUTING.get(task_type, "mid")
    model = MODELS[tier]

    response = client.chat.completions.create(
        model=model, messages=messages, **kwargs
    )
    return {
        "content": response.choices[0].message.content,
        "model": response.model,
        "tier": tier,
        "tokens": response.usage.prompt_tokens + response.usage.completion_tokens,
    }

Complexity-Based Auto-Router

def classify_complexity(prompt: str) -> str:
    """Classify prompt complexity to select model tier.

    Simple heuristics -- replace with a trained classifier for production.
    """
    word_count = len(prompt.split())
    has_code = bool(re.search(r'```|def |function |class |import ', prompt))
    has_reasoning = bool(re.search(r'explain|analyze|compare|why|how does|trade.?off', prompt, re.I))
    has_math = bool(re.search(r'calculate|equation|formula|derive|proof', prompt, re.I))

    if has_math or (has_reasoning and has_code):
        return "premium"
    if has_code or has_reasoning or word_count > 500:
        return "standard"
    if word_count > 100:
        return "mid"
    return "budget"

def auto_route(messages: list[dict], **kwargs):
    """Automatically select model based on prompt complexity."""
    user_msg = next((m["content"] for m in reversed(messages) if m["role"] == "user"), "")
    tier = classify_complexity(user_msg)
    model = MODELS[tier]

    response = client.chat.completions.create(model=model, messages=messages, **kwargs)
    return response

OpenRouter Native Routing

# Route: "fallback" — try models in order until one succeeds
response = client.chat.completions.create(
    model="anthropic/claude-3.5-sonnet",
    messages=[{"role": "user", "content": "Hello"}],
    max_tokens=200,
    extra_body={
        "models": [
            "anthropic/claude-3.5-sonnet",
            "openai/gpt-4o",
            "openai/gpt-4o-mini",
        ],
        "route": "fallback",
    },
)

# Provider routing — control which provider serves a model
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"],
            "allow_fallbacks": True,
        },
    },
)

# Model variant: ":floor" picks cheapest provider
response = client.chat.completions.create(
    model="anthropic/claude-3.5-sonnet:floor",
    messages=[{"role": "user", "content": "Hello"}],
    max_tokens=200,
)

Cost-Aware Router

import requests

def get_model_pricing() -> dict:
    """Fetch current pricing for cost-aware routing."""
    models = requests.get("https://openrouter.ai/api/v1/models").json()["data"]
    return {
        m["id"]: {
            "prompt": float(m["pricing"]["prompt"]) * 1_000_000,
            "completion": float(m["pricing"]["completion"]) * 1_000_000,
            "context": m["context_length"],
        }
        for m in models
    }

def cheapest_model_for_task(pricing: dict, min_context: int = 4096,
                             needs_tools: bool = False) -> str:
    """Find the cheapest model that meets requirements."""
    candidates = [
        (mid, p) for mid, p in pricing.items()
        if p["context"] >= min_context and p["prompt"] > 0  # Exclude free (unreliable)
    ]
    candidates.sort(key=lambda x: x[1]["prompt"] + x[1]["completion"])
    return candidates[0][0] if candidates else "openai/gpt-4o-mini"

Output

  • Routed completion dicts from route_request(): the reply content, the actual model that served, the tier chosen, and total tokens consumed
  • Router decision traces per request, e.g. [Router] Task=code -> Model=anthropic/claude-3.5-sonnet, giving you an audit trail to tune the routing table against
  • A live pricing map from get_model_pricing() keyed by model ID: per-1M prompt/completion cost plus context length for cost-aware selection

Examples

The same router sends trivial and demanding prompts to opposite ends of the cost spectrum:

print(routed_completion("What is 2+2?"))
# [Router] Task=simple -> Model=google/gemma-2-9b-it:free

print(routed_completion("Write a Python function to merge two sorted lists."))
# [Router] Task=code -> Model=anthropic/claude-3.5-sonnet

The 4-word arithmetic prompt lands on the free tier while the code request escalates to Claude 3.5 Sonnet — the spread between those two decisions is where the cost savings live. More worked examples: references/examples.md.

Error Handling

ErrorCauseFix
Wrong model selectedClassification too coarseAdd more task categories; test with diverse prompts
Model unavailableSelected model temporarily downAdd fallback chain per tier
Cost overrunComplex tasks routed to premium modelsSet max_tokens and daily budget caps
Quality regressionBudget model can't handle taskMonitor output quality; escalate tier on poor results

Enterprise Considerations

  • Start with manual task-type routing (explicit labels), then graduate to auto-classification
  • Log every routing decision (task type, tier, model, cost) to tune the router over time
  • Use OpenRouter's :floor variant to automatically get the cheapest provider for any model
  • Set max_tokens on every request to cap per-request cost regardless of model tier
  • A/B test routing rules: send 10% of traffic to a different tier and compare quality metrics
  • Combine with fallback chains so each tier has backup models

References

When not to use it

  • When task types are not clearly defined
  • When real-time latency requirements are extremely strict

Prerequisites

OpenRouter API key exported as OPENROUTER_API_KEYPython 3.8+ with openai and requests packages

Limitations

  • Classification heuristics may be too coarse for complex tasks
  • Requires manual maintenance of the task routing table

How it compares

This approach automates model selection based on business logic rather than manually choosing a model for every request.

Compared to similar skills

openrouter-model-routing side by side with the closest alternatives in the catalog.

SkillInstallsUpdatedSafetyDifficulty
openrouter-model-routing (this skill)125dCautionIntermediate
llama-cpp218moReviewIntermediate
mcp-builder1363moReviewAdvanced
langchain268moReviewIntermediate

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

llama-cpp

zechenzhangAGI

Runs LLM inference on CPU, Apple Silicon, and consumer GPUs without NVIDIA hardware. Use for edge deployment, M1/M2/M3 Macs, AMD/Intel GPUs, or when CUDA is unavailable. Supports GGUF quantization (1.5-8 bit) for reduced memory and 4-10× speedup vs PyTorch on CPU.

21471

mcp-builder

anthropics

Guide for creating high-quality MCP (Model Context Protocol) servers that enable LLMs to interact with external services through well-designed tools. Use when building MCP servers to integrate external APIs or services, whether in Python (FastMCP) or Node/TypeScript (MCP SDK).

136215

langchain

zechenzhangAGI

Framework for building LLM-powered applications with agents, chains, and RAG. Supports multiple providers (OpenAI, Anthropic, Google), 500+ integrations, ReAct agents, tool calling, memory management, and vector store retrieval. Use for building chatbots, question-answering systems, autonomous agents, or RAG applications. Best for rapid prototyping and production deployments.

26138

llama-factory

zechenzhangAGI

Expert guidance for fine-tuning LLMs with LLaMA-Factory - WebUI no-code, 100+ models, 2/3/4/5/6/8-bit QLoRA, multimodal support

15112

langgraph

davila7

Expert in LangGraph - the production-grade framework for building stateful, multi-actor AI applications. Covers graph construction, state management, cycles and branches, persistence with checkpointers, human-in-the-loop patterns, and the ReAct agent pattern. Used in production at LinkedIn, Uber, and 400+ companies. This is LangChain's recommended approach for building agents. Use when: langgraph, langchain agent, stateful agent, agent graph, react agent.

1374

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

Search skills

Search the agent skills registry