What one generated image costs, and why my account total did not show it
I generate artwork for a few channels through a hosted image model, one call per piece, from a script. For about a month every call came back HTTP 402 with the same body: This account never purchased credits. The key had been on disk the whole time, and the same key answered a read on the account endpoint without complaint.
A 402 is a billing state, not a bad key
The two status codes get lumped together when a request fails and nobody stops to read the body. 401 means the request did not carry credentials the server accepts. 402 means the credentials were accepted and the account behind them has no balance to spend. In a script I had just written, the difference changes what the next line should do: a 401 sends me back to the environment file, a 402 sends me to the provider dashboard.
Treating 402 as transient is the expensive mistake. In the adapter I run here, 402 is listed next to 429 and 503 as a status worth retrying on the next model in the chain. That list is reasonable for a busy upstream and wrong for an empty wallet: the same request goes out again, and if a second model is configured, the failure arrives as a different model name and looks like a model problem.
The only thing I needed was to fund the account. Everything else in that month of errors was noise produced by not reading the status.
The price of one call is in the response body
My first assumption was that a price table would tell me the cost, and a monthly total would confirm it. Both were wrong in different ways. The image endpoint returns the charge of that specific call inside the response body:
{ "usage": { "cost": 0.0336165, "total_tokens": 1186 } } The adapter that saves the image keeps that field and nothing else:
usage = _dict_at(body, "usage") if isinstance(usage.get("cost"), (int, float)): extra["cost_usd"] = usage["cost"] if isinstance(usage.get("total_tokens"), int): extra["total_tokens"] = usage["total_tokens"] No price table is consulted, and no arithmetic reconstructs the charge from tokens. A price list is a document that goes stale quietly, and models get retired. The model I had pinned, google/gemini-2.5-flash-image, was discontinued on the same day I first generated an image with its replacement, google/gemini-3.1-flash-lite-image. Had I been multiplying tokens by a price I had copied from a blog post, the number would have been wrong in a way that produces no error message.
Two calls, two shapes, and what the numbers actually tracked
These are the first two images produced after the account was funded, taken from the records kept at the time.
An icon, square, plain background:
model ....... google/gemini-3.1-flash-lite-image cost ........ US$ 0.0336165 tokens ...... 1186 file ........ JPEG 1024x1024, 64 KB time ........ about 10 seconds A cover, asked for a 4:5 portrait, delivered at 768x1376 (ratio 0.558, a strict 9:16 that I did not ask for and had to work around):
cost ........ US$ 0.03365425 tokens ...... 1337 file ........ JPEG 768x1376, 97 KB Compare the ratios. Tokens went up 12.7% between the two calls. Output area went up 0.78%. The charge went up 0.11%. The bill followed the pixels, not the tokens, which is what a per-image price looks like from the inside. A token counter is a fine thing to log and a poor cost meter, and the two calls are enough to show why.
The second call is also a reminder that the output size is not always the size I ordered. That is a separate problem from the bill, but it lands in the same place: the record has to store what arrived, not what I requested.
The account endpoint answers a different question
GET https://openrouter.ai/api/v1/credits with the same bearer key returns two numbers, total_credits and total_usage. It is a pure read and it costs nothing.
Right after that first generation, total_usage had not moved. I checked twice and concluded the endpoint was useless for auditing. Weeks later, against the same ten dollar purchase, it reads 0.42386975, which is about twelve and a half images at the unit price I measured. So the aggregate does move. It just does not answer the question I was asking it, which was what the call I made thirty seconds ago cost. The endpoint answers a cheaper and more useful one: is this failure about money?
A second endpoint, /api/v1/key, returns fields the credits call does not: is_free_tier, usage_daily, usage_weekly, usage_monthly, and a per-key limit with its remaining amount. is_free_tier: false told me the account state in one request, before I spent anything, and it is the value that would have pointed at the real cause during the month of 402s.
A budget check before the loop
Measured unit cost turns a balance into a number of images, which is the form I can act on. This script reads the account, translates the balance, and exits nonzero when a planned batch does not fit.
#!/usr/bin/env python3 """Ask the provider what is left, then translate the balance into images.""" import json import os import sys import urllib.request KEY = os.environ["OPENROUTER_API_KEY"] UNIT_USD = float(os.environ.get("UNIT_USD", "0.0336165")) def credits(key): req = urllib.request.Request( "https://openrouter.ai/api/v1/credits", headers={"Authorization": f"Bearer {key}"}, ) with urllib.request.urlopen(req, timeout=20) as resp: return json.load(resp)["data"] data = credits(KEY) left = float(data["total_credits"]) - float(data["total_usage"]) planned = int(sys.argv[1]) if len(sys.argv) > 1 else 0 print(f"purchased {data['total_credits']:.2f} used {data['total_usage']:.8f} left {left:.8f}") print(f"at {UNIT_USD} per image, that is {left / UNIT_USD:.0f} images left") if planned: cost = planned * UNIT_USD print(f"planned {planned} images = {cost:.4f} USD") if cost > left: sys.exit(f"short by {cost - left:.4f} USD") Run against the live account, asking whether a batch of twenty fits:
$ python3 orcamento_imagem.py 20 purchased 10.00 used 0.42386975 left 9.57613025 at 0.0336165 per image, that is 285 images left planned 20 images = 0.6723 USD The exit code is the part that matters in a scheduled job. A cron that generates art on a loop can check the budget before the first request and stop with a message instead of collecting 402s at four in the morning.
What changed in how I run this
- The unit cost is measured once, from the response, and then written into the script as
UNIT_USD. It is a number in code, not something I remember. - 402 stops the run. No retry, no fallback to another model, because a different model name would hide the only fact that matters, which is that the account cannot pay.
- Every generation records
cost_usdnext to the file it produced, so the ledger is the sum of real charges rather than an estimate built from tokens. - The model id is pinned in configuration and checked after each upgrade. The last one disappeared without a deprecation warning I could read in advance.
- The arithmetic happens before the schedule, not after. At the measured price, 120 images a month is US$ 4.03, a year of one a day is US$ 12.27, and ten a day for a year is US$ 122.70. Those are small numbers until a loop multiplies them, and the multiplication is free to do in advance.
None of this is specific to images. Any metered API that returns its own cost per request can be handled the same way: read the charge from the response, keep it with the artifact, and translate the balance into units you can plan with. The aggregate figure on the dashboard is there to tell you which kind of failure you are looking at.
Se você gera imagem por API em algum projeto, o custo por chamada está na resposta, não no painel. Medir uma vez e colocar esse número no script evita a surpresa de descobrir o gasto quando o loop já rodou mil vezes. Se você já passou por um 402 confundido com chave inválida, conta aqui nos comentários como descobriu.



