Skip to content

usage.cost and /v1/generation

Every priced relay response tells you what the request was charged, in USD, so you do not have to compute it from token counts and a price list.

The amount is a JSON number: USD, after your discount, with up to nine decimal places (0.000045). It is the amount that is booked to your balance.

Endpoint Where
/v1/chat/completions usage.cost; when streaming, in the final chunk (the one with choices: [])
/v1/responses usage.cost of the response object, and of response.completed when streaming
/v1/messages usage.cost; when streaming, in the usage of the last message_delta
Gemini generateContent, streamGenerateContent, embedContent, batchEmbedContents usageMetadata.cost; when streaming, in the last chunk
/v1/embeddings, /v1/images/* usage.cost (image models priced per image have no usage of their own; the gateway adds {"usage": {"cost": ...}})
/v1/audio/* usage.cost where the response has a usage object (JSON responses; plain text, SRT and VTT bodies have none; use /v1/generation)

Sum costs as decimals, not floats. Floating-point addition of many small amounts drifts; use decimal in Python, or take the exact integer from total_cost_nano below.

The id of a request is in its X-Request-Id response header. The generation endpoint returns the record of that request: what was charged, how the amount is made up, and how the request went.

Terminal window
# 1. Make a request and keep its id.
id=$(curl -s -D - -o /dev/null https://api.test.whocare.xyz/v1/chat/completions \
-H "Authorization: Bearer $GATEWAY_API_KEY" -H "Content-Type: application/json" \
-d '{"model": "gpt-4o-mini", "messages": [{"role": "user", "content": "Say hello in one word."}]}' \
| awk 'tolower($1) == "x-request-id:" {print $2}' | tr -d '\r')
# 2. Look it up. The record is written when the request settles, normally within a second.
for i in 1 2 3 4 5 6 7 8 9 10; do
if curl -s -f -o generation.json "https://api.test.whocare.xyz/v1/generation?id=$id" \
-H "Authorization: Bearer $GATEWAY_API_KEY"; then break; fi
sleep 1
done
cat generation.json
# expect: total_cost

The Python version uses httpx (pip install httpx) next to the OpenAI SDK.

import json
import os
import time
import httpx
from decimal import Decimal
from openai import OpenAI
base = "https://api.test.whocare.xyz"
headers = {"Authorization": f"Bearer {os.environ['GATEWAY_API_KEY']}"}
client = OpenAI(base_url=f"{base}/v1", api_key=os.environ["GATEWAY_API_KEY"])
raw = client.chat.completions.with_raw_response.create(
model="gpt-4o-mini",
messages=[{"role": "user", "content": "Say hello in one word."}],
)
request_id = raw.headers["x-request-id"]
resp = raw.parse()
print("cost in the response:", resp.usage.model_extra["cost"])
# The record is written when the request settles; a 404 right after the response means "not yet".
for _ in range(10):
r = httpx.get(f"{base}/v1/generation", params={"id": request_id}, headers=headers)
if r.status_code != 404:
break
time.sleep(1)
r.raise_for_status()
gen = json.loads(r.text, parse_float=Decimal)["data"]
print("provider:", gen["provider"], "status:", gen["status"], "attempts:", gen["attempts"])
print("total_cost_nano:", gen["total_cost_nano"])
# The lines add up to the total exactly.
assert sum(line["amount"] for line in gen["cost_details"]) == gen["total_cost"]
for line in gen["cost_details"]:
print(line["kind"], line["quantity"], line["amount"])

An id that does not exist, or that belongs to another organisation, is 404 generation_not_found; so is a request that has not settled yet, so retry for a few seconds before giving up. A malformed id is 400.

{
"data": {
"id": "0192b4c1-7a2e-7c3a-9d4e-5f6a7b8c9d0e",
"model": "gpt-4o-mini",
"provider": "openai",
"operation": "chat",
"streamed": false,
"status": "success",
"finish_reason": "stop",
"created_at": "2026-11-28T03:12:45.123456789Z",
"total_cost": 0.00036,
"total_cost_nano": "360000",
"list_cost": 0.00036,
"discount_ppm": 0,
"cost_details": [
{ "kind": "input", "quantity": 1200, "unit_price": 150000000, "unit": "per_million", "amount": 0.00018 },
{ "kind": "output", "quantity": 300, "unit_price": 600000000, "unit": "per_million", "amount": 0.00018 },
{ "kind": "request", "quantity": 1, "unit_price": 0, "unit": "each", "amount": 0 }
],
"attempts": 1,
"retries": 0,
"generation_time_ms": 912,
"ttft_ms": 310,
"usage_estimated": false,
"price_version_id": "0192b4c1-0000-7000-8000-000000000001",
"api_key_id": "0192b4c1-1111-7000-8000-000000000002",
"usage": {
"input_tokens": 1200,
"output_tokens": 300,
"reasoning_tokens": 0,
"cache_read_tokens": 0,
"cache_write_5m_tokens": 0,
"cache_write_1h_tokens": 0,
"image_input_tokens": 0,
"image_output_tokens": 0,
"audio_input_tokens": 0,
"audio_output_tokens": 0,
"input_chars": 0,
"audio_input_ms": 0,
"images": 0,
"web_search_calls": 0,
"total_tokens": 1500,
"source": "upstream"
}
}
}

The values above are an illustration of the shape.

Field Meaning
id The request id (X-Request-Id).
model The model that served the request. With a fallback, the fallback’s slug.
provider Tag of the provider that served it.
operation chat, embeddings, image_generation, speech, transcription.
status success, partial (content delivered, response incomplete), canceled (you disconnected), client_error, upstream_error. The last two carry no charge.
total_cost, total_cost_nano The amount charged, as a USD number and as an integer string of nano-USD (1 USD = 1,000,000,000). Prefer the string for bookkeeping.
list_cost, discount_ppm The amount at list price, and your discount in parts per million. total_cost is list_cost less the discount, rounded up.
cost_details[] One entry per line that has a quantity (kind as in Billing basis): quantity, unit_price (the list price in nano-USD per unit; per_million means per 1,000,000 units), and amount (USD charged for that line, after discount). A chat request always has a request line with quantity 1; its amount is 0 unless the model has a per-request price.
attempts, retries Upstream attempts made, and attempts minus one.
generation_time_ms, ttft_ms Total duration; time to first token (omitted when unknown).
usage The disjoint counters that were billed.
usage_estimated, usage.source true / "estimated" when the gateway counted the usage itself instead of the provider (Billing basis).
price_version_id The price list that was applied.
api_key_id The key that made the request.

The same records, with filters and totals, are in the console’s request log. The relay API has no endpoint for listing or summing requests; collect usage.cost and the request ids as you go if you need to bill your own customers.