Track and analyze OpenRouter API usage patterns, costs, and performance. Use when building dashboards, optimizing spend, or reporting on AI usage. Triggers: 'openrouter analytics', 'openrouter usage', 'openrouter metrics', 'track openrouter spend'.
Installer avec Codex ou Claude Copiez ce prompt, collez-le dans Codex, Claude ou un autre assistant, puis laissez-le vérifier la page du skill et l'installer pour vous.
Une commande directe contourne le prompt de vérification. Examinez la source avant de l'exécuter.
Track and analyze OpenRouter API usage patterns, costs, and performance. Use when building dashboards, optimizing spend, or reporting on AI usage. Triggers: 'openrouter analytics', 'openrouter usage', 'openrouter metrics', 'track openrouter spend'.
Designed for Claude Code, also compatible with Codex and OpenClaw
OpenRouter Usage Analytics
Overview
OpenRouter provides usage data through three endpoints: GET /api/v1/auth/key (credit balance and rate limits), GET /api/v1/generation?id= (per-request cost and metadata), and response usage fields (token counts). This skill covers collecting metrics from these sources, building analytics pipelines, cost reporting, and performance dashboards.
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 plus requests (used to fetch exact per-request cost from the generation endpoint); sqlite3 (stdlib) backs the analytics database
curl and jq for the Credit Balance Monitoring one-liner
HTTP-Referer / X-Title headers set on the client if you also want OpenRouter dashboard attribution
Instructions
Route completions through tracked_completion (Collect Per-Request Metrics) — it times each call, then fetches the exact total_cost from GET /api/v1/generation?id= and emits a JSON metric with tokens, latency, and model_requested vs model_used.
Initialize openrouter_analytics.db with init_analytics_db (Analytics Database) and persist every metric via store_metric — the generation_id unique constraint plus INSERT OR IGNORE deduplicates retries.
Query the store with the Analytics Queries: daily cost summary, cost by model, top users by spend, hourly request pattern, and 30-day cost trend.
Watch remaining credits with the Credit Balance Monitoring snippet — curl + jq against /api/v1/auth/key reports credits_used, credit_limit, and remaining.
Generate the Weekly Report Generator output for stakeholders (totals plus top 5 models by cost).
Apply the retention and alerting policies from Enterprise Considerations (aggregate raw rows after 30 days, alert when daily cost exceeds 2x the historical average).
defweekly_report(conn) -> str:
"""Generate a text-based weekly analytics report."""
summary = conn.execute("""
SELECT COUNT(*) as requests,
ROUND(SUM(total_cost), 2) as cost,
ROUND(AVG(latency_ms)) as avg_latency,
SUM(prompt_tokens + completion_tokens) as tokens
FROM metrics WHERE timestamp > datetime('now', '-7 days')
""").fetchone()
top_models = conn.execute("""
SELECT model_used, COUNT(*) as n, ROUND(SUM(total_cost), 4) as cost
FROM metrics WHERE timestamp > datetime('now', '-7 days')
GROUP BY model_used ORDER BY cost DESC LIMIT 5
""").fetchall()
report = f"""
=== OpenRouter Weekly Report ===
Period: Last 7 days
Requests: {summary[0]:,}
Total Cost: ${summary[1]:.2f}
Avg Latency: {summary[2]:.0f}ms
Total Tokens: {summary[3]:,}
Avg Cost/Request: ${summary[1]/max(summary[0],1):.4f}
Top Models by Cost:
"""for model, count, cost in top_models:
report += f" {model}: {count} requests, ${cost:.4f}\n"return report
Output
A JSON-logged metric per request: timestamp, generation_id, model_requested vs model_used, prompt/completion tokens, exact total_cost, latency_ms, and user_id
An openrouter_analytics.db sqlite store with an indexed metrics table ready for the daily/model/user/hourly queries
A credit-status JSON from the curl + jq snippet: credits_used, credit_limit, and remaining
A weekly text report with request count, total cost, average latency, total tokens, avg cost/request, and the top 5 models by cost
After a week of stored metrics, print(weekly_report(conn)) renders the === OpenRouter Weekly Report === block with totals and top models. More worked examples: references/examples.md.
Error Handling
Error
Cause
Fix
Missing cost data
Generation endpoint fetch failed
Retry after 1-2s; log warning
Metric storage growing too fast
No aggregation or retention
Aggregate to hourly/daily; retain raw data 30 days
Stale dashboard
Query pipeline lagging
Add data freshness check; alert on >5 min staleness
Duplicate metrics
Retry caused duplicate generation_ids
Use INSERT OR IGNORE with generation_id unique constraint
Enterprise Considerations
Query /api/v1/generation?id= after each request for exact cost (don't estimate from token counts)
Aggregate raw metrics to hourly/daily summaries after 30 days to manage storage growth
Build automated weekly reports with cost trends, top users, and anomaly detection
Set alerts on daily cost exceeding 2x historical average (anomaly detection)
Track model_requested vs model_used to monitor fallback frequency
Use the hourly request pattern to capacity-plan API key rate limits