AI › AI Tools

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.

Filtering OpenRouter models and tracking usage costs and errors

Hardcoding a model ID from the OpenRouter console exposes batch jobs to pricing changes and unsupported parameters, while summing only usage.cost hides 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/models and GET /api/v1/providers) come from live, unauthenticated HTTP GET requests to OpenRouter on 2026-12-02T12:42:15Z. The nine POST /api/v1/chat/completions and GET /api/v1/generation?id=... scenarios ran without an OPENROUTER_API_KEY using Python 3.14.7 against a local OpenRouter-compatible mock HTTP server. Switching base_url to https://openrouter.ai/api/v1 and 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.

SetupBest fitTrade-off
Hardcoded model ID + HTTP status check onlyOne-off scripts, quick prototypesMisses output-price spikes and HTTP 200 body errors
Public catalog filter + usage.include + JSONL auditDaily batch workers with budget capsNeeds periodic catalog sync; live latency (TTFT) measured separately
Direct single-vendor SDKFixed vendor contract, strict low-latency SLAHigher 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 lengthInput ($/M)Output ($/M)Notes
z-ai/glm-5.21,048,576$0.007$5.800Cheap input, high output rate
upstage/solar-mini-4-5524,288$0.010$0.040Low input and output pricing
deepseek/deepseek-v4.1-flash-10171,048,576$0.020$0.2001M context window
~deepseek/deepseek-flash-latest1,048,576$0.020$0.200Alias ID
inclusionai/ling-3.0-flash262,144$0.021$0.063256K context window
z-ai/glm-5.3-flash:batch1,048,576$0.023$0.068:batch variant
openai/gpt-oss-20b:batch131,072$0.024$0.112:batch variant
openai/gpt-5-nano:batch400,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 typeusage.is_byokusage.cost (OpenRouter billed)cost_details.upstream_inference_costEffective cost rule
Standard paidfalse> 0> 0Use usage.cost
:free variantfalse000 (track daily quota separately)
BYOK requesttrue0> 0Use 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:

ScenarioHTTPActionerror_classOpenRouter USDEffective USDgeneration check
paid_normal200ok-$0.000182$0.000182OK
free_variant200ok-$0.000000$0.000000OK
byok_request200ok-$0.000000$0.000245OK
err_401401abortauth_invalid_key$0.000000$0.000000-
err_402402abortinsufficient_credits$0.000000$0.000000-
err_429 (Retry-After: 2)429retryupstream_rate_limit$0.000000$0.000000-
err_502502retryprovider_http_502$0.000000$0.000000-
http_200_error200retryhttp_200_body_error$0.000000$0.000000-
http_200_finish_error200retryfinish_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.

Terminal output showing live OpenRouter public catalog filtering and 9 local mock server cost and error scenarios 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-02 and change frequently. Because the POST /api/v1/chat/completions and GET /api/v1/generation tests 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:

  1. Cap both input and output rates: As z-ai/glm-5.2 showed, filtering on input price alone can select a model with high output pricing or a :batch variant. Enforce both a completion-price ceiling and an explicit suffix filter.
  2. Watch model expiration and free quotas: Schedule periodic checks against /api/v1/models for price shifts or expiration_date, and inspect GET /api/v1/key when relying on :free daily limits.
  3. Handle streaming final chunks separately: If you enable stream: true, OpenRouter delivers usage in the final SSE chunk and reports mid-stream failures inside HTTP 200 chunks (error or finish_reason: "error").
  4. Move generation reconciliation off the hot path: Calling GET /api/v1/generation?id=... inline adds an extra round trip per ticket. In production, log generation_id to JSONL immediately and reconcile billing asynchronously.
Lists the models available to the caller with their pricing, context length, modalities, and supported parameters, plus presets when the caller is authenticated. An unfiltered call returns every text-output model (often several hundred KB of JSON or more; set output_modalities to list models with other outputs); use limit and offset to cap the result and filters such as q, output_modalities, input_modalities, or supported_parameters to narrow it (sort only reorders), or call GET /api/v1/model/{author}/{slug} to inspect a single catalog model. category is a usage shortlist, not a catalog filter: it returns only the top 20 models in that category by past-week token usage, never presets, and cannot be combined with limit, offset, or supported_parameters.
Learn how to track AI model usage including prompt tokens, completion tokens, and cached tokens without additional API calls.
Learn how to handle errors and debug requests in OpenRouter API interactions. Comprehensive guide to error codes, messages, debugging options, and best practices.
This post is licensed under CC BY 4.0 by the author.