OP

openrouter-pricing-basics

Calculates OpenRouter API usage costs to help with budgeting and model selection.

Install

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

Installs to .claude/skills/openrouter-pricing-basics

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.

Understand OpenRouter pricing, calculate costs, and optimize spend.
67 charsno explicit “when” trigger
Beginner

Key capabilities

  • Query OpenRouter model pricing
  • Estimate cost for OpenRouter API requests
  • Track actual cost per OpenRouter request
  • Check OpenRouter credit balance
  • Utilize OpenRouter model variants for cost savings
  • Understand OpenRouter special pricing considerations

How it works

This skill provides instructions and code examples to query OpenRouter model pricing, estimate API call costs, track actual expenses, and manage prepaid credits.

Inputs & outputs

You give it
OpenRouter model IDs, prompt/completion token counts, and API key
You get back
Model pricing, estimated/actual request costs, and credit balance

When to use openrouter-pricing-basics

  • Estimating API costs
  • Comparing model pricing tiers
  • Managing budget alerts
  • Querying model token rates

About this skill

OpenRouter Pricing Basics

Overview

OpenRouter charges per token with separate rates for prompt (input) and completion (output) tokens. Prices are listed per token in the models API (multiply by 1M for per-million rates). Credits are prepaid with a 5.5% processing fee ($0.80 minimum). Free models are available for testing and low-volume use.

Prerequisites

  • An OpenRouter API key (sk-or-v1-...) exported as OPENROUTER_API_KEY — see the openrouter-install-auth skill for setup
  • curl and jq for the model-pricing and credit-balance queries
  • Python 3.8+ with the OpenAI SDK plus the requests package for the cost-calculation and generation-endpoint snippets
  • Prepaid credits for paid models — the public models/pricing endpoint needs no auth, but real completions require credits or a :free model

Instructions

  1. Read How Pricing Works: prepaid credits (5.5% fee, $0.80 minimum) are drawn down per request as (prompt_tokens * prompt_rate) + (completion_tokens * completion_rate).
  2. Query per-token rates via GET /api/v1/models per Query Model Pricing, and place candidate models in the Cost Tiers table (free → premium).
  3. Estimate spend before committing: run estimate_cost() from Calculate Request Cost with your expected prompt/completion token counts.
  4. After sending real traffic, fetch the exact charge with GET /api/v1/generation?id= per Track Actual Cost Per Request.
  5. Watch the balance via GET /api/v1/auth/key per Check Credit Balance, and enable auto-topup for production keys.
  6. Cut costs with the :floor and :free variants per Save Money with Variants, and check Special Pricing for reasoning tokens, image inputs, per-request fees, and BYOK.

How Pricing Works

  1. Buy credits at openrouter.ai/credits (5.5% fee, $0.80 minimum)
  2. Each request deducts (prompt_tokens * prompt_rate) + (completion_tokens * completion_rate)
  3. Check balance via GET /api/v1/auth/key or the dashboard
  4. Auto-topup is available to prevent service interruption

Query Model Pricing

# Get pricing for all models
curl -s https://openrouter.ai/api/v1/models | jq '.data[] | select(.id == "anthropic/claude-3.5-sonnet") | {
  id: .id,
  prompt_per_M: ((.pricing.prompt | tonumber) * 1000000),
  completion_per_M: ((.pricing.completion | tonumber) * 1000000),
  context: .context_length
}'
# → { "id": "anthropic/claude-3.5-sonnet", "prompt_per_M": 3, "completion_per_M": 15, "context": 200000 }

Cost Tiers (Representative)

TierExample ModelPrompt/1MCompletion/1MUse Case
Freegoogle/gemma-2-9b-it:free$0.00$0.00Testing, prototyping
Budgetmeta-llama/llama-3.1-8b-instruct$0.06$0.06Simple Q&A, classification
Midopenai/gpt-4o-mini$0.15$0.60General purpose
Standardanthropic/claude-3.5-sonnet$3.00$15.00Complex reasoning, code
Premiumopenai/o1$15.00$60.00Deep reasoning

Calculate Request Cost

def estimate_cost(model_id: str, prompt_tokens: int, completion_tokens: int) -> float:
    """Calculate cost for a single request."""
    import requests
    models = requests.get("https://openrouter.ai/api/v1/models").json()["data"]
    model = next((m for m in models if m["id"] == model_id), None)
    if not model:
        raise ValueError(f"Model {model_id} not found")

    prompt_rate = float(model["pricing"]["prompt"])       # Cost per token
    completion_rate = float(model["pricing"]["completion"])
    return (prompt_tokens * prompt_rate) + (completion_tokens * completion_rate)

# Example: Claude 3.5 Sonnet, 1000 prompt + 500 completion tokens
cost = estimate_cost("anthropic/claude-3.5-sonnet", 1000, 500)
print(f"Estimated cost: ${cost:.6f}")  # ~$0.0105

Track Actual Cost Per Request

import requests

# Method 1: From response usage (estimate)
response = client.chat.completions.create(
    model="anthropic/claude-3.5-sonnet",
    messages=[{"role": "user", "content": "Hello"}],
    max_tokens=100,
)
# response.usage.prompt_tokens, response.usage.completion_tokens

# Method 2: Query generation endpoint (exact cost from OpenRouter)
gen = requests.get(
    f"https://openrouter.ai/api/v1/generation?id={response.id}",
    headers={"Authorization": f"Bearer {os.environ['OPENROUTER_API_KEY']}"},
).json()
print(f"Exact cost: ${gen['data']['total_cost']}")
print(f"Tokens: {gen['data']['tokens_prompt']} prompt + {gen['data']['tokens_completion']} completion")

Check Credit Balance

curl -s https://openrouter.ai/api/v1/auth/key \
  -H "Authorization: Bearer $OPENROUTER_API_KEY" | jq '{
    credits_used: .data.usage,
    credit_limit: .data.limit,
    remaining: ((.data.limit // 0) - .data.usage),
    is_free_tier: .data.is_free_tier
  }'

Save Money with Variants

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

# :free variant uses free providers (where available)
response = client.chat.completions.create(
    model="google/gemma-2-9b-it:free",
    messages=[{"role": "user", "content": "Hello"}],
    max_tokens=100,
)

Special Pricing

ItemPricing
Reasoning tokensCharged as output tokens at completion rate
Image inputsPer-image charge listed in pricing.image
Per-request feeSome models charge a flat fee per request (pricing.request)
BYOKFirst 1M requests/month free; then 5% of normal provider cost
Free model limits50 req/day (free users), 1000 req/day (with $10+ credits)

Output

  • A per-model pricing record from the models API: prompt_per_M, completion_per_M, context (e.g. $3 / $15 per 1M tokens for anthropic/claude-3.5-sonnet)
  • A pre-request dollar estimate from estimate_cost() and the exact post-request figures from the generation endpoint: total_cost, tokens_prompt, tokens_completion
  • A credit-balance snapshot from /api/v1/auth/key: credits_used, credit_limit, remaining, is_free_tier

Examples

Check remaining credits before a batch job:

curl -s https://openrouter.ai/api/v1/auth/key \
  -H "Authorization: Bearer $OPENROUTER_API_KEY" | jq '{
    credits_used: .data.usage,
    remaining: ((.data.limit // 0) - .data.usage)
  }'
# {"credits_used": 2.34, "remaining": 47.66}

Estimating first keeps surprises out: 1,000 prompt + 500 completion tokens on anthropic/claude-3.5-sonnet comes to roughly $0.0105 via estimate_cost(), and the generation endpoint then confirms the exact charge. More worked examples: references/examples.md.

Error Handling

HTTPCauseFix
402Insufficient creditsTop up at openrouter.ai/credits or use :free model
402Key credit limit reachedIncrease key limit or use a different key

Enterprise Considerations

  • Set per-key credit limits via the dashboard or provisioning API to isolate blast radius
  • Query /api/v1/generation?id= after each request for exact cost auditing
  • Use :floor variant to automatically pick the cheapest provider
  • Route simple tasks to budget models and complex tasks to premium models (see openrouter-model-routing)
  • Set max_tokens on every request to cap completion cost
  • Enable auto-topup to prevent service interruptions in production

References

When not to use it

  • When not using OpenRouter API
  • When an OpenRouter API key is not available

Prerequisites

An OpenRouter API key (`sk-or-v1-...`) exported as `OPENROUTER_API_KEY``curl` and `jq` for the model-pricing and credit-balance queriesPython 3.8+ with the OpenAI SDK plus the `requests` package

Limitations

  • Requires an OpenRouter API key
  • Requires `curl` and `jq` for certain queries
  • Requires Python 3.8+ with OpenAI SDK and `requests` package

How it compares

This skill offers specific commands and code for OpenRouter's pricing model, providing a direct method for cost management unlike general API cost estimation.

Compared to similar skills

openrouter-pricing-basics side by side with the closest alternatives in the catalog.

SkillInstallsUpdatedSafetyDifficulty
openrouter-pricing-basics (this skill)127dCautionBeginner
jupyter-notebook306moReviewIntermediate
using-serena-for-exploration98moReviewIntermediate
cursor-explorer-mcp68moNo 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

jupyter-notebook

davila7

Use when the user asks to create, scaffold, or edit Jupyter notebooks (`.ipynb`) for experiments, explorations, or tutorials; prefer the bundled templates and run the helper script `new_notebook.py` to generate a clean starting notebook.

30158

using-serena-for-exploration

seanGSISG

Use when exploring codebases with Serena MCP tools for architectural understanding and pattern discovery - guides efficient symbolic exploration workflow minimizing token usage through targeted symbol reads, overview tools, and progressive narrowing

9127

cursor-explorer-mcp

sepiabrown

Use for token-expensive operations requiring multi-file analysis - codebase exploration, broad searches, architecture understanding, tracing flows, finding implementations across files. Uses MCP cursor-agent server (company pays) with clean async interface. Do NOT use for single-file analysis, explaining code already in immediate context, or pure reasoning tasks.

699

lecture-transcript-slide-matcher

az9713

Combines YouTube lecture transcripts with PDF slides to create an interactive HTML page. Matches each slide to corresponding transcript segments, organized by key concepts. Use when users want to create synchronized lecture notes from transcript text files and slide PDFs.

669

skill-from-github

GBSOSS

Create skills by learning from high-quality GitHub projects

739

react-expert

reactjs

Use when researching React APIs or concepts for documentation. Use when you need authoritative usage examples, caveats, warnings, or errors for a React feature.

823

Search skills

Search the agent skills registry