Reading model and usage data from OpenRouter responses
Follow a free OpenRouter request from the model ID in your Python code to the model, provider, token counts, and cost recorded for the call.
A request to
openrouter/freecan come back with a specific model name you never put in your code. I use a Jekyll release summary to show where to read the model, provider, token counts, and cost for that call.
I ran the Python snippets with Python 3.14.7 and OpenAI Python SDK 3.60.0 using mock HTTP responses. The screenshot comes from a separate browser exercise that made a real request through the free router. OpenAI Python SDK
Follow the model ID through the request
OpenRouter exposes an OpenAI-compatible Chat Completions endpoint. A request can name a specific model or ask the free router to pick one. When I send openrouter/free as the model argument, OpenRouter selects a free model that can serve the request. The response’s model field identifies the model that ran, and provider tells me who served it. I keep both fields because the same model can run with different providers. Free Models Router · Read the response
| What you want to check | Request to make |
|---|---|
| Whether the key and request format work | Send one request to openrouter/free and inspect the response. |
| How two models summarize the same text | Request two specific model IDs with identical messages and the same output cap. |
| Which provider ran a particular model | Pin the model and read provider or look up the generation. |
Prepare a free request with a fixed input
Start with an OpenRouter API key. Create a Python virtual environment, install the SDK, and enter the key in the same Bash or Zsh session where you’ll run Python. The prompt hides the key as you type. The free router is a convenient first call because it chooses an available free model for you. Request limits still apply, and the eligible models can change. Check the rate-limit documentation if you plan to repeat the exercise many times. Create an API key · OpenRouter limits
1
2
3
4
5
6
7
8
python3 -m venv .venv
source .venv/bin/activate
python -m pip install 'openai==3.60.0'
printf 'OpenRouter API key: '
IFS= read -r -s OPENROUTER_API_KEY
printf '\n'
export OPENROUTER_API_KEY
Save this excerpt as release-notes.md in the directory where you’ll run the example. It paraphrases three changes from the public Jekyll 4.4.0 release. Keeping the excerpt in a file gives every model the same facts to work from. It also gives you a short source to check when a summary sounds plausible but leaves something out. Jekyll 4.4.0 release
1
2
3
4
5
Jekyll 4.4.0
The minimum supported Ruby version moved to 2.7.
Projects can select which lines to highlight in a code block through Liquid.
Jekyll now declares csv, base64, and json as runtime gem dependencies.
Write one record per request
Put the next two snippets in compare_models.py, in order. The first connects the Python client to OpenRouter and reads the input once. I disabled automatic retries so a failed request produces a record immediately.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
import json
import os
import sys
from pathlib import Path
from openai import APIError, APIStatusError, OpenAI
client = OpenAI(
base_url="https://openrouter.ai/api/v1",
api_key=os.environ["OPENROUTER_API_KEY"],
max_retries=0,
timeout=30.0,
)
notes = Path("release-notes.md").read_text(encoding="utf-8")
messages = [
{"role": "system", "content": "Summarize the release notes in three bullets using only facts from the input."},
{"role": "user", "content": notes},
]
The second snippet reads the response body as JSON so the record includes OpenRouter-specific fields along with the text. A response with HTTP 200 can carry an error in the body or in a completion choice. The parser checks those cases and verifies that the choice and message are objects before it reads the summary. A clipped output, refusal, or empty summary gets an incomplete status. An unexpected response shape gets an error status. Chat Completions reference · OpenRouter error handling
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
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
def read_reply(data):
if not isinstance(data, dict):
raise ValueError("Expected a response object")
row = {
"response_model": data.get("model"),
"provider": data.get("provider"),
"generation_id": data.get("id"),
"usage": data.get("usage"),
}
if data.get("error"):
return dict(row, status="error", error_type="response_error")
choices = data.get("choices")
if not isinstance(choices, list) or not choices or not isinstance(choices[0], dict):
raise ValueError("Expected an object in choices[0]")
choice = choices[0]
reason = choice.get("finish_reason")
if choice.get("error") or reason == "error":
return dict(row, status="error", finish_reason=reason, error_type="choice_error")
message = choice.get("message")
if not isinstance(message, dict):
raise ValueError("Expected a message object")
summary = message.get("content")
has_text = isinstance(summary, str) and bool(summary.strip())
status = "ok" if reason == "stop" and has_text and not message.get("refusal") else "incomplete"
return dict(row, status=status, finish_reason=reason, summary=summary)
failed = False
for model in sys.argv[1:] or ["openrouter/free"]:
row = {"requested_model": model, "status": "error"}
try:
response = client.chat.completions.with_raw_response.create(
model=model, messages=messages, max_completion_tokens=1024,
)
row["http_status"] = response.status_code
row.update(read_reply(response.http_response.json()))
except APIStatusError as exc:
row.update(http_status=exc.status_code, retry_after=exc.response.headers.get("Retry-After"))
except (APIError, ValueError) as exc:
row["error_type"] = type(exc).__name__
print(json.dumps(row, ensure_ascii=False))
failed = failed or row["status"] != "ok"
raise SystemExit(1 if failed else 0)
Without arguments, the script sends one request to openrouter/free. Each requested model gets one JSON object on its own line in the output file. If any request fails or ends early, the exit code is 1 and you can still read the saved records. The second command formats them for inspection.
1
2
python compare_models.py > results.jsonl
python -m json.tool --json-lines results.jsonl
Check the model and cost in a real log
I also sent this Jekyll excerpt to openrouter/free in a browser exercise that streamed the summary. On December 1, 2026, at 00:12 KST, the log showed Particle-1 (free) served by Particle AI, with 196 input tokens, 190 output tokens, and a charge of US$0.00. Those figures describe that request. Another run can select a different model and use a different number of tokens.
Figure 1. The real OpenRouter log for the free-router call made by the browser exercise.
| Fields | What I check |
|---|---|
requested_model, response_model, provider | The ID I sent, the model that answered, and its provider. |
generation_id | A reference for finding the same request in OpenRouter. |
usage.prompt_tokens, usage.completion_tokens, usage.cost | Input and output tokens and the charge in credits. If usage is absent, the charge is unknown from this response. |
finish_reason, summary | Why the model stopped and what it wrote. A length finish means it reached the output token limit. |
Two models can count the same input differently because their tokenizers can differ. Compare the usage reported for each individual call, and keep the responding model beside the cost. OpenRouter usage accounting
Keep the conditions fixed for a two-model comparison
Choose two IDs from the model catalog, check their current availability and pricing, and replace the two placeholders. Paid model IDs can use credits. The script sends both models the same messages and max_completion_tokens so the two rows describe the same summarization task.
1
python compare_models.py 'FIRST_MODEL_ID' 'SECOND_MODEL_ID' > results.jsonl
I tested the failure path by giving the first request a mock HTTP 200 response with {"choices":[null]}. The first line showed status=error and error_type=ValueError. The second request still ran, and its successful response appeared on the following line. The same checks covered a body-level error, a rate limit, clipped output, and a refusal.
When both requests succeed, read each summary against the release notes. Ruby 2.7 is the minimum supported version. Check whether both summaries also mention Liquid’s highlighted-line selection and all three runtime dependencies, csv, base64, and json. Token and cost figures tell you how each request ran, and the source text lets you check what each summary kept.
If a request fails, 401 is a reason to check the key. For 402, check available credit and budget. For 429, check the applicable request limit and honor Retry-After when present. To keep the model fixed and inspect which provider handled the call, see provider routing and model fallback in OpenRouter. OpenRouter error codes