Agent skill

Openrouter Reference Architecture

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

Design production architectures using OpenRouter as the LLM gateway.

MITAuto-check passedAI & LLM Engineering

Install Openrouter Reference Architecture

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

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

GitHub CLI
$ gh skill install jeremylongshore/tons-of-skills-marketplace openrouter-reference-architecture --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-reference-architecture .claude/skills/openrouter-reference-architecture && 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-reference-architecture
GitHub stars
2.8k
Token cost
~2.7k tokens
SKILL.md length
545 words
Files
7 (incl. references)
Skills in repo
3,342
Repo updated
First seen
Licence
MIT

At a glance

Design production architectures using OpenRouter as the LLM gateway.

  • Works in 5 steps: Score your system against the Choosing… → Start with Architecture 1 (Simple): one… → When you need task routing, caching, and… → …
  • Planning system design
  • SKILL.md covers Overview, Prerequisites, Instructions and Architecture 1: Simple (Single…, plus 8 more sections
  • Reaches openrouter.ai; needs OPENROUTER_API_KEY

What it does

Openrouter Reference Architecture is an agent skill from jeremylongshore/tons-of-skills-marketplace. Design production architectures using OpenRouter as the LLM gateway. Use when planning system design, reviewing architecture, or scaling AI applications. Triggers: 'openrouter architecture', 'openrouter system design', 'openrouter at scale', 'llm gateway architecture'.

Its SKILL.md is about 2.7k tokens, which your agent loads only when the skill is triggered. The skill folder holds 7 other files, including reference files (for example `references/client-layer-implementation.md`, `references/errors.md` and `references/examples.md`). Compatibility notes: Designed for Claude Code

It sits in AI & LLM Engineering, covering Model routing and gateways. It works with OpenRouter and Redis. 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

  • Planning system design
  • Reviewing architecture
  • Scaling AI applications

Example prompts

  • “openrouter architecture”
  • “openrouter system design”
  • “openrouter at scale”
  • “/openrouter-reference-architecture”

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. Score your system against the Choosing an Architecture table: team size, requests/day, latency needs, budget-tracking granularity, failure…
  2. Start with Architecture 1 (Simple): one shared client (max_retries=3, timeout=30.0) behind the logging complete() wrapper.
  3. When you need task routing, caching, and per-user budgets, move to Architecture 2 (Standard): a FastAPI /v1/complete endpoint with the…
  4. At 100K+ requests/day or mixed sync/async workloads, adopt Architecture 3 (Enterprise): queue (Redis/SQS) → auto-scaling workers running…
  5. Whichever tier you land on, route every call through the same OpenRouter client wrapper per Enterprise Considerations — consistent…

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

    No scripts in the folder and no shell commands in SKILL.md (its code samples are python).

    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 Reference Architecture loads about 2.7k tokens when it runs, and up to ~7.7k if it reads all its reference files. Until then it costs about 76 tokens; SKILL.md has 545 words of instructions outside code blocks.

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

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). 545 words, ~2,722 tokens.

Download SKILL.mdSave it as .claude/skills/openrouter-reference-architecture/SKILL.md (or your agent's skills folder). This skill also uses 6 other files; get the full folder from GitHub.
name
openrouter-reference-architecture
description
Design production architectures using OpenRouter as the LLM gateway. Use when planning system design, reviewing architecture, or scaling AI applications. Triggers: 'openrouter architecture', 'openrouter system design', 'openrouter at scale', 'llm gateway architecture'.
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, architecture, system-design, scaling

OpenRouter Reference Architecture

Overview

OpenRouter serves as a unified LLM gateway, abstracting provider complexity. A production architecture wraps it with caching, rate limiting, cost controls, observability, and async processing. This skill provides three reference architectures: simple (single service), standard (microservice), and enterprise (event-driven).

Prerequisites

  • 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; FastAPI + Pydantic for Architecture 2's AI service, and a Redis instance (with the redis package) for Architecture 2's cache and Architecture 3's queue/results store
  • SQLite or Postgres if you implement Architecture 2's budget enforcer
  • Your scale numbers — team size, requests/day, and latency needs drive the decision in Choosing an Architecture

Instructions

  1. Score your system against the Choosing an Architecture table: team size, requests/day, latency needs, budget-tracking granularity, failure handling, observability.
  2. Start with Architecture 1 (Simple): one shared client (max_retries=3, timeout=30.0) behind the logging complete() wrapper.
  3. When you need task routing, caching, and per-user budgets, move to Architecture 2 (Standard): a FastAPI /v1/complete endpoint with the ROUTING_TABLE, cache-first lookup, budget check, and a fallback chain (models + route: "fallback").
  4. At 100K+ requests/day or mixed sync/async workloads, adopt Architecture 3 (Enterprise): queue (Redis/SQS) → auto-scaling workers running worker_loop() → results store, with OTEL metrics feeding dashboards and alerts.
  5. Whichever tier you land on, route every call through the same OpenRouter client wrapper per Enterprise Considerations — consistent logging, cost tracking, and no budget bypass.

Architecture 1: Simple (Single Service)

┌─────────────┐     ┌──────────────────────────┐     ┌──────────────┐
│  Your App   │────▶│  OpenRouter Client        │────▶│  OpenRouter  │
│             │     │  - Retry (SDK built-in)   │     │  /api/v1     │
│             │◀────│  - Cost tracking          │◀────│              │
│             │     │  - Structured logging     │     └──────────────┘
└─────────────┘     └──────────────────────────┘
python
import os, logging
from openai import OpenAI

log = logging.getLogger("llm")

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

def complete(prompt, model="openai/gpt-4o-mini", **kwargs):
    kwargs.setdefault("max_tokens", 1024)
    response = client.chat.completions.create(
        model=model,
        messages=[{"role": "user", "content": prompt}],
        **kwargs,
    )
    log.info(f"[{response.model}] {response.usage.prompt_tokens}+{response.usage.completion_tokens} tokens")
    return response.choices[0].message.content

Architecture 2: Standard (Microservice)

┌─────────────┐     ┌─────────────────────┐     ┌──────────────┐
│  API Gateway│────▶│  AI Service          │────▶│  OpenRouter  │
│  (auth,     │     │  ┌─────────────┐    │     │  /api/v1     │
│   rate-limit│     │  │ Router      │    │     └──────────────┘
│   logging)  │     │  │ (task→model)│    │
└─────────────┘     │  └─────────────┘    │
                    │  ┌─────────────┐    │
                    │  │ Cache       │◀──▶│── Redis
                    │  │ (TTL-based) │    │
                    │  └─────────────┘    │
                    │  ┌─────────────┐    │
                    │  │ Budget      │◀──▶│── SQLite/Postgres
                    │  │ Enforcer    │    │
                    │  └─────────────┘    │
                    └─────────────────────┘
python
from fastapi import FastAPI, Depends, HTTPException
from pydantic import BaseModel

app = FastAPI()

class CompletionRequest(BaseModel):
    prompt: str
    task_type: str = "general"  # classification, code, analysis, etc.
    max_tokens: int = 1024
    user_id: str = "anonymous"

ROUTING_TABLE = {
    "classification": "openai/gpt-4o-mini",
    "code": "anthropic/claude-3.5-sonnet",
    "analysis": "anthropic/claude-3.5-sonnet",
    "general": "openai/gpt-4o-mini",
    "budget": "meta-llama/llama-3.1-8b-instruct",
}

@app.post("/v1/complete")
async def complete(req: CompletionRequest):
    model = ROUTING_TABLE.get(req.task_type, "openai/gpt-4o-mini")

    # Check cache first (for deterministic requests)
    cached = cache.get(model, req.prompt)
    if cached:
        return {"content": cached, "cached": True}

    # Check budget
    budget.check(req.user_id, model, estimate_tokens(req.prompt), req.max_tokens)

    # Call OpenRouter
    response = client.chat.completions.create(
        model=model,
        messages=[{"role": "user", "content": req.prompt}],
        max_tokens=req.max_tokens,
        extra_body={
            "models": [model, "openai/gpt-4o-mini"],  # Fallback
            "route": "fallback",
        },
    )

    # Record cost and cache
    budget.record(req.user_id, response.id)
    cache.set(model, req.prompt, response.choices[0].message.content)

    return {
        "content": response.choices[0].message.content,
        "model": response.model,
        "tokens": response.usage.prompt_tokens + response.usage.completion_tokens,
    }

Architecture 3: Enterprise (Event-Driven)

┌──────────┐    ┌───────────┐    ┌──────────────┐    ┌──────────────┐
│  API     │───▶│  Queue    │───▶│  Workers     │───▶│  OpenRouter  │
│  Gateway │    │  (Redis/  │    │  (auto-scale) │    │  /api/v1     │
└──────────┘    │  SQS)     │    │  ┌──────────┐│    └──────────────┘
                └───────────┘    │  │ Router   ││
                     │           │  │ Cache    ││
                     ▼           │  │ Budget   ││
                ┌───────────┐    │  │ Audit    ││
                │  Results  │◀───│  └──────────┘│
                │  Store    │    └──────────────┘
                └───────────┘
                     │
                ┌───────────┐    ┌──────────────┐
                │  Metrics  │───▶│  Dashboard   │
                │  (OTEL)   │    │  Alerts      │
                └───────────┘    └──────────────┘
python
# Worker that processes queued AI requests
import json, redis

r = redis.Redis()

def worker_loop():
    """Process AI requests from the queue."""
    while True:
        _, raw = r.brpop("ai:requests")
        request = json.loads(raw)

        try:
            response = client.chat.completions.create(
                model=request["model"],
                messages=request["messages"],
                max_tokens=request.get("max_tokens", 1024),
                extra_body={
                    "models": [request["model"], "openai/gpt-4o-mini"],
                    "route": "fallback",
                },
            )
            result = {
                "id": request["id"],
                "content": response.choices[0].message.content,
                "model": response.model,
                "status": "complete",
            }
        except Exception as e:
            result = {"id": request["id"], "error": str(e), "status": "failed"}

        r.lpush(f"ai:results:{request['id']}", json.dumps(result))
        r.expire(f"ai:results:{request['id']}", 3600)

Choosing an Architecture

FactorSimpleStandardEnterprise
Team size1-33-1010+
Requests/day<1K1K-100K100K+
Latency needsTolerantLowMixed (sync+async)
Budget trackingBasicPer-userPer-user + department
Failure handlingSDK retriesFallback chainQueue + retry + DLQ
ObservabilityLoggingMetrics + loggingFull OTEL tracing
Show full SKILL.md (251 more words)Show less

Output

  • An architecture selection (Simple / Standard / Enterprise) justified line-by-line against the Choosing an Architecture criteria
  • Architecture 1: a logging complete() wrapper that records the serving model and prompt+completion token counts on every call
  • Architecture 2: a /v1/complete FastAPI endpoint returning {content, model, tokens} — or {content, cached: true} on a cache hit — with task-type routing and budget enforcement applied
  • Architecture 3: worker-produced result records {id, content, model, status} pushed to ai:results:{id} with a one-hour TTL

Examples

Route a code task through the Architecture 2 microservice:

python
# POST /v1/complete  (Architecture 2)
req = CompletionRequest(prompt="Refactor this function...", task_type="code", user_id="u42")
# ROUTING_TABLE maps "code" -> anthropic/claude-3.5-sonnet, with openai/gpt-4o-mini as fallback
# -> {"content": "...", "model": "anthropic/claude-3.5-sonnet", "tokens": 348}

Repeating the identical request returns {"content": "...", "cached": true} straight from the TTL cache without touching OpenRouter or the budget. More worked examples: references/examples.md.

Error Handling

ErrorCauseFix
Single point of failureNo redundancy in AI serviceDeploy 2+ instances behind load balancer
Queue backlogWorker throughput < incoming rateAuto-scale workers; implement backpressure
Cache stampedeMany requests for same uncached keyUse cache locking or singleflight pattern
Budget bypassDirect calls skipping middlewareAll calls must go through the AI service

Enterprise Considerations

  • Start with Architecture 1 and evolve to 2/3 as scale demands
  • Use the queue-based pattern for any request that can tolerate >1s latency (cost reports, batch processing)
  • OpenTelemetry traces should span from API gateway through AI service to OpenRouter
  • Implement dead letter queues (DLQ) for failed requests that exhaust all retries
  • Run separate worker pools for different priority levels (real-time vs batch)
  • All architectures should share the same OpenRouter client wrapper for consistent logging and cost tracking

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 6 other files (references) in skills/.curated/openrouter-reference-architecture of jeremylongshore/tons-of-skills-marketplace.

  • SKILL.md
  • references/client-layer-implementation.md
  • references/errors.md
  • references/examples.md
  • references/kubernetes-deployment.md
  • references/microservice-architecture.md
  • references/monitoring-stack.md

Open the folder on GitHubat commit cfae287

Compare with similar skills

Openrouter Reference Architecture 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 Reference Architecture compared with similar skills
SkillStarsUsed inTokensAuto-checkLicenceRepo updated
Openrouter Reference Architecture this skilljeremylongshore/tons-of-skills-marketplace2.8k—~2.7kAutomated safety check: PassMIT
Embeddings via 9Routerdecolua/9router31k—~604Automated safety check: PassMIT
FreeRide Free Model ManagerShaivpidadi/FreeRide2382 repos~1.1kAutomated safety check: PassNone
Using Ccproxy APIstarbaser/ccproxy350—~4kAutomated safety check: PassCustom licence
Caching Architecturemajiayu000/litellm-rs118—~2kAutomated safety check: PassMIT
LLM GatewayBagelHole/DevOps-Security-Agent-Skills1.2k—~2kAutomated safety check: PassMIT

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
  • FreeRide Free Model Manager

    Shaivpidadi/FreeRide

    Configures OpenClaw to use free OpenRouter models, setting the best one as primary and adding ranked fallbacks so rate limits do not interrupt work.

    238 GitHub starsUsed in 2 repos~1.1k tokens
    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
  • Caching Architecture

    majiayu000/litellm-rs

    LiteLLM-RS response caching architecture. An agent skill from majiayu000/litellm-rs.

    118 GitHub stars~2k tokensUpdated today
    AI & LLM EngineeringAuto-check passed
  • LLM Gateway

    BagelHole/DevOps-Security-Agent-Skills

    Deploy an API gateway for LLM traffic with load balancing, rate limiting, key management, semantic caching, fallback routing, and cost tracking.

    1.2k GitHub stars~2k tokensUpdated 4 mo 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

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

Works with

Questions about Openrouter Reference Architecture

What does Openrouter Reference Architecture do?

Design production architectures using OpenRouter as the LLM gateway. Openrouter Reference Architecture is an agent skill from jeremylongshore/tons-of-skills-marketplace. Design production architectures using OpenRouter as the LLM gateway.

When should I use Openrouter Reference Architecture?

Openrouter Reference Architecture fits situations like: planning system design; reviewing architecture; scaling AI applications.

How do I install Openrouter Reference Architecture in Claude Code?

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

How do I install Openrouter Reference Architecture in Codex?

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

Can I use Openrouter Reference Architecture 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-reference-architecture -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-reference-architecture, .gemini/skills/openrouter-reference-architecture, .github/skills/openrouter-reference-architecture and .opencode/skills/openrouter-reference-architecture in your project.

What does Openrouter Reference Architecture need to run?

Going by SKILL.md and its folder, Openrouter Reference Architecture needs 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 Reference Architecture 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 Reference Architecture 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 Reference Architecture use?

Openrouter Reference Architecture 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 Reference Architecture use?

About 2.7k tokens (SKILL.md is roughly 11k 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 5k tokens, read only when the agent opens those files.

What are the alternatives to Openrouter Reference Architecture?

Skills that share tags, products or a category with Openrouter Reference Architecture: Embeddings via 9Router (decolua/9router, 31k stars), FreeRide Free Model Manager (Shaivpidadi/FreeRide, 238 stars), Using Ccproxy API (starbaser/ccproxy, 350 stars) and Caching Architecture (majiayu000/litellm-rs, 118 stars). The comparison table on this page puts their stars, adoption, token cost, safety result and licence side by side.

Who maintains Openrouter Reference Architecture?

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.