Filtering OpenRouter models and tracking usage costs and errors
Filter OpenRouter models via the public catalog API and track paid, free, and BYOK costs alongside HTTP and body-level errors in a Python batch worker.
Hardcoding a model ID from the OpenRouter console exposes batch jobs to pricing changes and unsupported parameters, while summing only
usage.costhides BYOK spend. I built a Python client that filters candidates from the unauthenticated catalog API and logs per-request costs plus HTTP and body-level errors to JSONL.
Verification scope and environment: The catalog counts (
GET /api/v1/modelsandGET /api/v1/providers) come from live, unauthenticated HTTP GET requests to OpenRouter on2026-12-02T12:42:15Z. The ninePOST /api/v1/chat/completionsandGET /api/v1/generation?id=...scenarios ran without anOPENROUTER_API_KEYusing Python3.14.7against a local OpenRouter-compatible mock HTTP server. Switchingbase_urltohttps://openrouter.ai/api/v1and supplying an API key runs the same client code against live endpoints.
Where model selection and cost tracking break down
Consider a support ticket triage batch worker that classifies thousands of daily customer tickets by category and urgency. OpenRouter gives you one API across hundreds of models, which fits batch workloads well, but three failure modes show up quickly in production.
First, copying a cheap-looking model ID from the dashboard hides output-token pricing spikes and variant suffixes such as :free or :batch. Second, if you mix :free routes or Bring Your Own Key (BYOK) credentials and only sum usage.cost, OpenRouter reports 0 for BYOK calls while your upstream vendor still bills you. Third, OpenRouter can return failures not only as HTTP 401, 402, 429, or 502 responses, but also as an HTTP 200 body containing a top-level error object or choices[0].finish_reason == "error". Checking only the HTTP status code lets empty or broken responses slip into your database.
| Setup | Best fit | Trade-off |
|---|---|---|
| Hardcoded model ID + HTTP status check only | One-off scripts, quick prototypes | Misses output-price spikes and HTTP 200 body errors |
Public catalog filter + usage.include + JSONL audit | Daily batch workers with budget caps | Needs periodic catalog sync; live latency (TTFT) measured separately |
| Direct single-vendor SDK | Fixed vendor contract, strict low-latency SLA | Higher model-switching cost; no need for OpenRouter catalog layer |
If your service depends on a single vendor contract or requires the lowest possible streaming latency, calling that vendor directly removes an extra hop. If you run batch jobs that swap models by budget and need per-ticket cost reconciliation, automating the catalog filter and audit client pays off immediately.
Filtering candidate models with the public catalog API
Both GET https://openrouter.ai/api/v1/models and GET https://openrouter.ai/api/v1/providers work without an API key. In the catalog payload, pricing.prompt and pricing.completion are USD-per-token strings, so multiplying by 1_000_000 converts them to dollars per million tokens.
For the ticket triage worker, I filtered for models with context_length >= 128,000, structured_outputs in supported_parameters, and input pricing at or below $0.50/M using Python’s standard library (urllib.request):
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
# catalog_filter.py (Python 3.14.7, standard library only)
import json
import urllib.request
MODELS_URL = "https://openrouter.ai/api/v1/models"
PROVIDERS_URL = "https://openrouter.ai/api/v1/providers"
MIN_CONTEXT = 128_000
MAX_PROMPT_USD_PER_M = 0.50
REQUIRED_PARAM = "structured_outputs"
def fetch_json(url: str) -> dict:
req = urllib.request.Request(
url,
headers={
"Accept": "application/json",
"User-Agent": "openrouter-catalog-filter/1.0",
},
)
with urllib.request.urlopen(req, timeout=20) as resp:
if resp.status != 200:
raise RuntimeError(f"Unexpected HTTP {resp.status} from {url}")
return json.loads(resp.read().decode("utf-8"))
def price_per_million(raw_value: str | None) -> float | None:
if raw_value is None:
return None
try:
val = float(raw_value)
except (TypeError, ValueError):
return None
return None if val < 0 else val * 1_000_000.0
Negative pricing entries (used for special router entries) are skipped in price_per_million, and matched models are split into paid candidates and :free candidates.
Running python3 catalog_filter.py against the live public API on 2026-12-02T12:42:15Z returned 465 models and 124 providers, including 10 :free variants and 404 models supporting structured_outputs. Exactly 190 models matched all three criteria (187 paid and 3 :free).
| Model ID (top 8 paid by input price) | Context length | Input ($/M) | Output ($/M) | Notes |
|---|---|---|---|---|
z-ai/glm-5.2 | 1,048,576 | $0.007 | $5.800 | Cheap input, high output rate |
upstage/solar-mini-4-5 | 524,288 | $0.010 | $0.040 | Low input and output pricing |
deepseek/deepseek-v4.1-flash-1017 | 1,048,576 | $0.020 | $0.200 | 1M context window |
~deepseek/deepseek-flash-latest | 1,048,576 | $0.020 | $0.200 | Alias ID |
inclusionai/ling-3.0-flash | 262,144 | $0.021 | $0.063 | 256K context window |
z-ai/glm-5.3-flash:batch | 1,048,576 | $0.023 | $0.068 | :batch variant |
openai/gpt-oss-20b:batch | 131,072 | $0.024 | $0.112 | :batch variant |
openai/gpt-5-nano:batch | 400,000 | $0.025 | $0.200 | :batch variant |
The three matched :free models were baidu/ernie-5.5-flash-preview:free (1,024,000), nvidia/nemotron-3.5-super-vl:free (1,000,000), and liquid/lfm-3-1.7b:free (262,144).
That live output caught two practical traps right away. First, sorting only by input price puts z-ai/glm-5.2 at the top ($0.007/M input), even though its output rate is $5.800/M. Second, :batch variants show up in the cheapest tier. In production, always filter on an output-price ceiling (completion_pm <= MAX_COMPLETION_USD_PER_M) and explicitly exclude unwanted variant suffixes.
Tracking per-request costs and generation metadata
Adding "usage": {"include": true} to the chat completion payload instructs OpenRouter to return usage.cost, usage.is_byok, and usage.cost_details.upstream_inference_cost inline.
BYOK requests are where naive cost ledgers drift. When usage.is_byok is true, OpenRouter bills 0 in usage.cost, while the upstream provider’s inference charge appears in usage.cost_details.upstream_inference_cost. Logging both openrouter_cost_usd and effective_cost_usd keeps platform credit spend and total spend distinct.
| Request type | usage.is_byok | usage.cost (OpenRouter billed) | cost_details.upstream_inference_cost | Effective cost rule |
|---|---|---|---|---|
| Standard paid | false | > 0 | > 0 | Use usage.cost |
:free variant | false | 0 | 0 | 0 (track daily quota separately) |
| BYOK request | true | 0 | > 0 | Use upstream_inference_cost |
You can also store the response id (gen-...) and query GET /api/v1/generation?id=<gen_id> to verify total_cost, provider_name, is_byok, and token counts after the fact. Here is the cost calculation and generation lookup from triage_client.py:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
# triage_client.py — split cost accounting and generation metadata check
usage = body.get("usage") or {}
cost_details = usage.get("cost_details") or {}
is_byok = bool(usage.get("is_byok", False))
openrouter_cost = float(usage.get("cost") or 0.0)
upstream_cost = float(cost_details.get("upstream_inference_cost") or 0.0)
effective_cost = upstream_cost if is_byok and openrouter_cost == 0.0 else openrouter_cost
gen_id = body.get("id")
gen_meta = self.fetch_generation(gen_id) if gen_id else None
gen_verified = bool(
gen_meta
and gen_meta.get("id") == gen_id
and bool(gen_meta.get("is_byok", False)) == is_byok
)
Splitting HTTP errors from HTTP 200 body errors
A batch worker needs a clear boundary between retrying a ticket and stopping the run. Retrying 401 (invalid key) or 402 (insufficient credits) wastes time and floods logs across thousands of tickets, whereas 429 (rate limit, respecting Retry-After) and 502/503 (provider outage) belong on a retry queue.
The trickier path is an HTTP 200 error. If an upstream provider fails mid-generation, OpenRouter can still return HTTP 200 with a top-level error object or choices[0].finish_reason == "error". The client must check both paths before reading usage or writing ticket output:
flowchart TD
Req["POST /api/v1/chat/completions"] --> HttpCheck{"HTTP status"}
HttpCheck -->|"401 / 402"| Abort["Stop batch (abort)"]
HttpCheck -->|"429 / 502 / 503"| RetryHttp["Backoff retry (retry)"]
HttpCheck -->|"200 OK"| BodyCheck{"Body error or\nfinish_reason == error"}
BodyCheck -->|"Yes"| RetryBody["Queue retry (retry)"]
BodyCheck -->|"No"| Audit["Log cost and verify generation (ok)"]
On 429 responses, checking error.metadata.provider_name separates an upstream provider rate limit (upstream_rate_limit) from an OpenRouter account limit (openrouter_rate_limit). Here is how triage_client.py classifies both paths:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
# triage_client.py — HTTP 200 body-level error checks
if "error" in body and body["error"]:
return AuditRecord(
ticket_id=ticket_id, scenario=scenario or "", http_status=status,
action="retry", error_class="http_200_body_error", retry_after_sec=None,
generation_id=body.get("id"), model=body.get("model"), provider=body.get("provider"),
is_byok=False, openrouter_cost_usd=0.0, upstream_cost_usd=0.0,
effective_cost_usd=0.0, generation_verified=False,
)
choices = body.get("choices") or []
finish_reason = choices[0].get("finish_reason") if choices else None
if finish_reason == "error":
return AuditRecord(
ticket_id=ticket_id, scenario=scenario or "", http_status=status,
action="retry", error_class="finish_reason_error", retry_after_sec=None,
generation_id=body.get("id"), model=body.get("model"), provider=body.get("provider"),
is_byok=False, openrouter_cost_usd=0.0, upstream_cost_usd=0.0,
effective_cost_usd=0.0, generation_verified=False,
)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
# triage_client.py — HTTP status error classification
retry_after_raw = headers.get("Retry-After") if headers else None
retry_after = int(retry_after_raw) if retry_after_raw and retry_after_raw.isdigit() else None
if status == 401:
action, err_class = "abort", "auth_invalid_key"
elif status == 402:
action, err_class = "abort", "insufficient_credits"
elif status == 429:
meta = (err_body.get("error") or {}).get("metadata") or {}
err_class = "upstream_rate_limit" if meta.get("provider_name") else "openrouter_rate_limit"
action = "retry"
elif status in (502, 503):
action, err_class = "retry", f"provider_http_{status}"
else:
action, err_class = "abort", f"http_{status}"
Verifying nine scenarios against a local mock server
To test every branch without spending credits or exposing an API key, I ran test_triage_client.py against a local ThreadingHTTPServer mock on 127.0.0.1. The suite sends nine ticket requests covering paid, :free, BYOK, HTTP errors, and HTTP 200 body errors, writes all nine records to audit_log.jsonl, and asserts both the action routing and cost totals.
1
2
python3 catalog_filter.py
PRINT_TABLE=1 python3 -m unittest -v test_triage_client.py
All nine scenarios matched their expected actions and error classes, and all three successful calls passed GET /api/v1/generation?id=... verification:
| Scenario | HTTP | Action | error_class | OpenRouter USD | Effective USD | generation check |
|---|---|---|---|---|---|---|
paid_normal | 200 | ok | - | $0.000182 | $0.000182 | OK |
free_variant | 200 | ok | - | $0.000000 | $0.000000 | OK |
byok_request | 200 | ok | - | $0.000000 | $0.000245 | OK |
err_401 | 401 | abort | auth_invalid_key | $0.000000 | $0.000000 | - |
err_402 | 402 | abort | insufficient_credits | $0.000000 | $0.000000 | - |
err_429 (Retry-After: 2) | 429 | retry | upstream_rate_limit | $0.000000 | $0.000000 | - |
err_502 | 502 | retry | provider_http_502 | $0.000000 | $0.000000 | - |
http_200_error | 200 | retry | http_200_body_error | $0.000000 | $0.000000 | - |
http_200_finish_error | 200 | retry | finish_reason_error | $0.000000 | $0.000000 | - |
Across the nine JSONL rows, openrouter_billed totaled $0.000182, while effective_total (including the $0.000245 BYOK upstream cost) totaled $0.000427. Summing only usage.cost would have underreported actual spend by more than half.
Figure 1. Live OpenRouter public catalog filtering output on 2026-12-02 (top) and the 9-scenario local mock server test with JSONL cost totals (bottom).
Production caveats and checklist
Warning: The model count (465), provider count (124), and token prices reflect a live snapshot from
2026-12-02and change frequently. Because thePOST /api/v1/chat/completionsandGET /api/v1/generationtests ran against a local mock server, measure live latency and mid-stream error rates in staging with a real key before turning on high-volume batches.
Before deploying this pattern to a production worker, verify four items:
- Cap both input and output rates: As
z-ai/glm-5.2showed, filtering on input price alone can select a model with high output pricing or a:batchvariant. Enforce both a completion-price ceiling and an explicit suffix filter. - Watch model expiration and free quotas: Schedule periodic checks against
/api/v1/modelsfor price shifts orexpiration_date, and inspectGET /api/v1/keywhen relying on:freedaily limits. - Handle streaming final chunks separately: If you enable
stream: true, OpenRouter deliversusagein the final SSE chunk and reports mid-stream failures inside HTTP200chunks (errororfinish_reason: "error"). - Move generation reconciliation off the hot path: Calling
GET /api/v1/generation?id=...inline adds an extra round trip per ticket. In production, loggeneration_idto JSONL immediately and reconcile billing asynchronously.