Agent skill

Openrouter Model Routing

by jeremylongshore in jeremylongshore/tons-of-skills-marketplace

Implement intelligent model routing to optimize cost, quality, and latency on OpenRouter.

MITAuto-check passedAI & LLM Engineering

Install Openrouter Model Routing

skills CLI
$ npx skills add jeremylongshore/tons-of-skills-marketplace --skill openrouter-model-routing -a claude-code

Project install by default; add -g for ~/.claude/skills/.

GitHub CLI
$ gh skill install jeremylongshore/tons-of-skills-marketplace openrouter-model-routing --agent claude-code

Project scope by default; add --scope user for a personal install. Needs GitHub CLI 2.90.0 or later (public preview).

Manual copy
$ git clone --depth 1 https://github.com/jeremylongshore/tons-of-skills-marketplace.git skills-src && mkdir -p .claude/skills && cp -r skills-src/skills/.curated/openrouter-model-routing .claude/skills/openrouter-model-routing && rm -rf skills-src

Use ~/.claude/skills/ instead of .claude/skills for a personal install. The folder must contain SKILL.md.

Claude Code skills documentation · loads skills from .claude/skills/

Facts

Skill name
openrouter-model-routing
GitHub stars
2.8k
Token cost
~2.4k tokens
SKILL.md length
522 words
Files
8 (incl. references)
Skills in repo
3,342
Repo updated
First seen
Licence
MIT

At a glance

Implement intelligent model routing to optimize cost, quality, and latency on OpenRouter.

  • Works in 5 steps: Define your tiers per Task-Based Router:… → When callers can't label tasks, switch… → Add resilience per OpenRouter Native… → …
  • Building multi-model systems
  • SKILL.md covers Overview, Prerequisites, Instructions and Task-Based Router, plus 8 more sections
  • Calls pip; reaches openrouter.ai; needs OPENROUTER_API_KEY

What it does

Openrouter Model Routing is an agent skill from jeremylongshore/tons-of-skills-marketplace. Implement intelligent model routing to optimize cost, quality, and latency on OpenRouter. Use when building multi-model systems or optimizing spend across task types. Triggers: 'openrouter routing', 'model routing', 'route to model', 'model selection openrouter'.

Its SKILL.md is about 2.4k tokens, which your agent loads only when the skill is triggered. The skill folder holds 8 other files, including reference files (for example `references/cascading-router.md`, `references/context-aware-routing.md` and `references/cost-quality-optimization.md`). Compatibility notes: Designed for Claude Code

It sits in AI & LLM Engineering, covering Model routing and gateways. It works with OpenRouter and OpenAI. The repository describes itself as: Model-agnostic agent-skills platform with a harness-free canonical layer, verified adapters, and the ccpi package manager. Explore at tonsofskills.com. The licence is MIT.

When your agent uses it

  • Building multi-model systems
  • Optimizing spend across task types

Example prompts

  • “openrouter routing”
  • “model routing”
  • “route to model”
  • “/openrouter-model-routing”

Requirements

  • Python 3
  • A credential in OPENROUTER_API_KEY
  • Compatibility (from SKILL.md): Designed for Claude Code
  • Pre-approved tools (allowed-tools): Read, Write, Edit, Grep, Bash(python3:*)

Workflow steps

5 steps, taken from the first numbered list in SKILL.md.

  1. Define your tiers per Task-Based Router: the MODELS dict (free → budget → mid → standard → premium) and the TASK_ROUTING map, then send…
  2. When callers can't label tasks, switch to the Complexity-Based Auto-Router — classify_complexity() scores word count, code, reasoning, and…
  3. Add resilience per OpenRouter Native Routing: extra_body={"models": [...], "route": "fallback"} tries models in order, provider.order…
  4. Keep pricing current per Cost-Aware Router — get_model_pricing() pulls live per-1M rates from GET /api/v1/models, and…
  5. Log every routing decision (task type, tier, model, cost) and tune per Error Handling and Enterprise Considerations — escalate the tier on…

What it can do on your machine

Read from SKILL.md and the folder at commit cfae287. It shows what the files ask for, not the result of running them.

  • Tool permissions

    Pre-approves these tools, so the agent can use them without asking each time:

    • Read
    • Write
    • Edit
    • Grep
    • Bash(python3:*)

    From allowed-tools in the SKILL.md frontmatter.

  • Runs code

    Shell commands in SKILL.md call:

    • pip

    From the folder's file list and the shell code blocks in SKILL.md.

  • Network

    Hosts in commands or code, which the agent is likely to contact:

    • openrouter.ai

    From URLs in SKILL.md, links to its own repository left out.

  • Credentials

    Names these keys or tokens, usually read from environment variables:

    • OPENROUTER_API_KEY

    From names ending in _API_KEY, _TOKEN, _SECRET, _KEY or _PASSWORD in SKILL.md.

  • Compatibility

    Designed for Claude Code

    From compatibility in the SKILL.md frontmatter.

Context cost

Openrouter Model Routing loads about 2.4k tokens when it runs, and up to ~11k if it reads all its reference files. Until then it costs about 72 tokens; SKILL.md has 522 words of instructions outside code blocks.

Always · name and description, kept in context so the agent knows when to use it
~72
When it runs · the whole SKILL.md, loaded when a task matches
~2.4k
With references · SKILL.md plus every file in references/, read only if the agent opens them
~11k

Estimates: characters ÷ 4, the usual rule of thumb; real counts depend on the model's tokenizer. Scripts and assets cost tokens only if the agent reads them.

Safety

Auto-check passed

The automated check found no risky patterns in SKILL.md.

Automated static check — not a guarantee. Review scripts before installing. It scans the text of SKILL.md for risky patterns (piping downloads into a shell, reading credential files, hidden Unicode, destructive commands); files beside SKILL.md are not scanned.

SKILL.md

The full file from jeremylongshore/tons-of-skills-marketplace at commit cfae287, republished under its MIT licence (© jeremylongshore). 522 words, ~2,438 tokens.

Download SKILL.mdSave it as .claude/skills/openrouter-model-routing/SKILL.md (or your agent's skills folder). This skill also uses 7 other files; get the full folder from GitHub.
name
openrouter-model-routing
description
Implement intelligent model routing to optimize cost, quality, and latency on OpenRouter. Use when building multi-model systems or optimizing spend across task types. Triggers: 'openrouter routing', 'model routing', 'route to model', 'model selection openrouter'.
allowed-tools
Read, Write, Edit, Grep, Bash(python3:*)
compatibility
Designed for Claude Code
version
1.20.0
license
MIT
author
Jeremy Longshore <jeremy@intentsolutions.io>
tags
saas, openrouter, routing, cost-optimization, model-selection

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

python
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

python
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

python
# 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

python
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
Show full SKILL.md (196 more words)Show less

Examples

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

python
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

© jeremylongshore, MIT. Rendered from Markdown: HTML in the file is shown as text, images as links, and headings moved down two levels. Raw file

Files

SKILL.md and 7 other files (references) in skills/.curated/openrouter-model-routing of jeremylongshore/tons-of-skills-marketplace.

  • SKILL.md
  • references/cascading-router.md
  • references/context-aware-routing.md
  • references/cost-quality-optimization.md
  • references/errors.md
  • references/examples.md
  • references/implementation.md
  • references/intelligent-model-selection.md

Open the folder on GitHubat commit cfae287

Compare with similar skills

Openrouter Model Routing next to the 5 skills that share the most tags, products or categories with it. Stars are the repository's; “used in” counts other GitHub owners with a copy.

Openrouter Model Routing compared with similar skills
SkillStarsUsed inTokensAuto-checkLicenceRepo updated
Openrouter Model Routing this skilljeremylongshore/tons-of-skills-marketplace2.8k—~2.4kAutomated safety check: PassMIT
Embeddings via 9Routerdecolua/9router31k—~604Automated safety check: PassMIT
Using Ccproxy Inspectorstarbaser/ccproxy350—~2.7kAutomated safety check: PassCustom licence
Mecatl Model Router Configstacklok/mecatl254—~2.7kAutomated safety check: PassApache-2.0
Using Ccproxy APIstarbaser/ccproxy350—~4kAutomated safety check: PassCustom licence
Configuring Visionoxbshw/watch-skill470—~509Automated safety check: NotesMIT

Similar skills

  • Embeddings via 9Router

    decolua/9router

    Generates vector embeddings through the 9Router /v1/embeddings endpoint, using models from providers such as OpenAI, Gemini, Mistral and Voyage for RAG and semantic search.

    31k GitHub stars~604 tokensUpdated 3 days ago
    AI & LLM EngineeringAuto-check passed
  • Using Ccproxy Inspector

    starbaser/ccproxy

    Operates the ccproxy inspector MITM system for intercepting, inspecting, and transforming LLM API traffic.

    350 GitHub stars~2.7k tokensUpdated 2 mo ago
    AI & LLM EngineeringAuto-check passed
  • Interviews you about provider, cost, openness and image needs, then designs the models section of a mecatl settings file with aliases, slots and router categories.

    254 GitHub stars~2.7k tokensUpdated yesterday
    AI & LLM EngineeringAuto-check passed
  • Using Ccproxy API

    starbaser/ccproxy

    Guides users through ccproxy as an OpenAI-compatible and Anthropic-compatible LLM API server with SDK integration, OAuth authentication, sentinel key substitution, model routing, and troubleshooting.

    350 GitHub stars~4k tokensUpdated 2 mo ago
    AI & LLM EngineeringAuto-check passed
  • Configuring Vision

    oxbshw/watch-skill

    The user wants to connect an LLM or vision provider, already has an API key, asks "can I use OpenAI/Anthropic/Gemini/OpenRouter", wants local Ollama, or needs different cheap and strong models.

    470 GitHub stars~509 tokensUpdated 26 days ago
    AI & LLM EngineeringAuto-check: notes
  • Quorum

    Detrol/quorum-cli

    Run a structured debate between agent CLIs (claude, codex, agy, grok) and the user's configured API or local models (OpenAI, Anthropic, Google, xAI, OpenRouter, Ollama and more) through the Quorum…

    119 GitHub stars~807 tokensUpdated 14 days ago
    AI & LLM EngineeringAuto-check: notes

More from jeremylongshore/tons-of-skills-marketplace

All 3,342 skills in this repo
  • Performing Security Code Review

    jeremylongshore/tons-of-skills-marketplace

    Execute this skill enables AI assistant to conduct a security-focused code review using the security-agent plugin.

    2.8k GitHub starsUsed in 2 repos~1.3k tokens
    Auto-check: notes
  • Adapting Transfer Learning Models

    jeremylongshore/tons-of-skills-marketplace

    Build this skill automates the adaptation of pre-trained machine learning models using transfer learning techniques.

    2.8k GitHub stars~1.1k tokensUpdated today
    Auto-check passed
  • Agent Context Loader

    jeremylongshore/tons-of-skills-marketplace

    Execute proactive auto-loading: automatically detects and loads agents.md files.

    2.8k GitHub stars~1.1k tokensUpdated today
    Auto-check passed
  • Aggregating Performance Metrics

    jeremylongshore/tons-of-skills-marketplace

    Aggregate and centralize performance metrics from applications, systems, databases, caches, and services.

    2.8k GitHub stars~1.2k tokensUpdated today
    Auto-check passed
  • Analyzing Capacity Planning

    jeremylongshore/tons-of-skills-marketplace

    Execute this skill enables AI assistant to analyze capacity requirements and plan for future growth.

    2.8k GitHub stars~947 tokensUpdated today
    Auto-check passed
  • Analyzing Database Indexes

    jeremylongshore/tons-of-skills-marketplace

    Process use when you need to work with database indexing. An agent skill from jeremylongshore/tons-of-skills-marketplace.

    2.8k GitHub stars~2k tokensUpdated today
    Auto-check passed

Questions about Openrouter Model Routing

What does Openrouter Model Routing do?

Implement intelligent model routing to optimize cost, quality, and latency on OpenRouter. Openrouter Model Routing is an agent skill from jeremylongshore/tons-of-skills-marketplace. Implement intelligent model routing to optimize cost, quality, and latency on OpenRouter.

When should I use Openrouter Model Routing?

Openrouter Model Routing fits situations like: building multi-model systems; optimizing spend across task types.

How do I install Openrouter Model Routing in Claude Code?

Run `npx skills add jeremylongshore/tons-of-skills-marketplace --skill openrouter-model-routing -a claude-code`. Or copy the skill folder (skills/.curated/openrouter-model-routing in jeremylongshore/tons-of-skills-marketplace) into .claude/skills/openrouter-model-routing in your project. Claude Code loads it when a task matches its description.

How do I install Openrouter Model Routing in Codex?

Run `npx skills add jeremylongshore/tons-of-skills-marketplace --skill openrouter-model-routing -a codex`. Or copy the skill folder (skills/.curated/openrouter-model-routing in jeremylongshore/tons-of-skills-marketplace) into .agents/skills/openrouter-model-routing in your project. Codex loads it when a task matches its description.

Can I use Openrouter Model Routing in Cursor, Gemini CLI or GitHub Copilot?

Cursor, Gemini CLI, GitHub Copilot and OpenCode also load SKILL.md folders. With the skills CLI, run `npx skills add jeremylongshore/tons-of-skills-marketplace --skill openrouter-model-routing -a cursor` (or -a gemini-cli, github-copilot or opencode for the others). To copy it by hand, put the folder in .cursor/skills/openrouter-model-routing, .gemini/skills/openrouter-model-routing, .github/skills/openrouter-model-routing and .opencode/skills/openrouter-model-routing in your project.

What does Openrouter Model Routing need to run?

Going by SKILL.md and its folder, Openrouter Model Routing needs the command-line tools its instructions call (pip) and credentials named OPENROUTER_API_KEY. Our summary lists: Python 3; A credential in OPENROUTER_API_KEY. Its frontmatter pre-approves these tools: Read, Write, Edit, Grep, Bash(python3:*). Compatibility (from SKILL.md): Designed for Claude Code.

Does Openrouter Model Routing access the network?

SKILL.md names 1 domain. In commands or code: openrouter.ai; the agent is likely to contact it when it follows the instructions. This is read from the text; nothing was executed.

Is Openrouter Model Routing safe to install?

Our automated static check of SKILL.md found no risky patterns, such as piping downloads into a shell, reading credential files or hidden Unicode. It is not a guarantee. Review the folder before installing.

What licence does Openrouter Model Routing use?

Openrouter Model Routing is published under the MIT licence (declared in SKILL.md). It allows redistribution, so the full SKILL.md is shown on this page.

How many tokens does Openrouter Model Routing use?

About 2.4k tokens (SKILL.md is roughly 9.8k characters). Agents keep only the skill's name and description in context until a task matches; then they load SKILL.md in full. Its references folder adds about 8.8k tokens, read only when the agent opens those files.

What are the alternatives to Openrouter Model Routing?

Skills that share tags, products or a category with Openrouter Model Routing: Embeddings via 9Router (decolua/9router, 31k stars), Using Ccproxy Inspector (starbaser/ccproxy, 350 stars), Mecatl Model Router Config (stacklok/mecatl, 254 stars) and Using Ccproxy API (starbaser/ccproxy, 350 stars). The comparison table on this page puts their stars, adoption, token cost, safety result and licence side by side.

Who maintains Openrouter Model Routing?

jeremylongshore (a GitHub user) maintains it in jeremylongshore/tons-of-skills-marketplace, which has 2,827 GitHub stars. The repository holds 3,342 skills in this directory. The repository was last updated on October 10, 2026.

Source: jeremylongshore/tons-of-skills-marketplace on GitHub. Facts on this page come from the repository at the commit we read; the author's words are quoted as theirs.