跳转到内容

usage.cost 与 /v1/generation

每个计价的中继响应都会告诉你这次请求扣了多少美元,不用再根据 token 数和价格表自己算。

金额是一个 JSON 数字:美元、已扣除你的折扣、最多九位小数(0.000045)。它就是记到你余额上的金额。

端点 位置
/v1/chat/completions usage.cost;流式时在最后一个 chunk(choices: [] 的那个)里
/v1/responses 响应对象的 usage.cost;流式时在 response.completed 里
/v1/messages usage.cost;流式时在最后一个 message_delta 的 usage 里
Gemini generateContent、streamGenerateContent、embedContent、batchEmbedContents usageMetadata.cost;流式时在最后一个 chunk 里
/v1/embeddings、/v1/images/* usage.cost(按张计价的图像模型本身没有 usage,网关会补上 {"usage": {"cost": ...}})
/v1/audio/* 响应带 usage 对象时在 usage.cost(JSON 响应有;纯文本、SRT、VTT 没有,请用 /v1/generation)

累加费用请用十进制数,不要用浮点数。很多小额浮点相加会产生漂移:Python 里用 decimal,或者用下面 total_cost_nano 里的精确整数。

请求的 id 在响应头 X-Request-Id 里。generation 端点返回该请求的记录:扣了多少、金额由哪些部分组成、请求是怎么跑的。

终端窗口
# 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

Python 版本在 OpenAI SDK 之外还用到 httpx(pip install httpx)。

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"])

不存在的 id,或属于别的组织的 id,返回 404 generation_not_found;还没结算完的请求也是这个结果,所以放弃之前请重试几秒。id 格式不对返回 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"
}
}
}

上面的数值只是用来展示结构。

字段 含义
id 请求 id(X-Request-Id)。
model 实际处理请求的模型。用了备用模型时是备用模型的 slug。
provider 处理请求的供应商标签。
operation chat、embeddings、image_generation、speech、transcription。
status success、partial(内容已送达但响应不完整)、canceled(你断开了连接)、client_error、upstream_error。后两种不扣费。
total_cost、total_cost_nano 实际扣的金额,分别是美元数字和纳美元整数字符串(1 USD = 1,000,000,000)。记账请用字符串。
list_cost、discount_ppm 标价金额,以及你的折扣(百万分比)。total_cost 是 list_cost 扣折扣后向上取整。
cost_details[] 每个有计数的行一项(kind 见计费口径):quantity、unit_price(按 unit 计的标价,单位是纳美元;per_million 表示每 1,000,000 个单位)、amount(该行扣除折扣后实际扣的美元)。聊天请求总会有一行数量为 1 的 request;模型没有按请求计价时它的金额是 0。
attempts、retries 发往上游的尝试次数,以及尝试次数减一。
generation_time_ms、ttft_ms 总耗时;首字延迟(未知时不返回)。
usage 实际计费所用的互不重叠的计数。
usage_estimated、usage.source 用量由网关而不是供应商计数时为 true / "estimated"(见计费口径)。
price_version_id 使用的价格版本。
api_key_id 发起请求的密钥。

同样的记录,带筛选和汇总,在控制台的请求日志里。中继 API 没有列出或汇总请求的端点;如果你要给自己的客户计费,请在调用时自己记下 usage.cost 和请求 id。