用量与账单

JoyToken 的计费链路围绕 tier 钱包、路由器模型费率、billing-service 费用计算、用量记录和分析聚合展开。模型请求成功后,响应仍保持 OpenAI 兼容结构,同时在 metadata.billing 中补充 JoyToken 的成本字段。

请求生命周期

Validate API Key
-> policy and wallet precheck
-> route model
-> estimate credits
-> wallet freeze
-> provider invoke
-> calculate usage
-> record usage
-> wallet settle or release

Credit tiers

当前工程按三档 tier 管理钱包和模型路由:

Tier常见代码用途
economyE成本优先、低价模型和批处理
standardS默认平衡档
premiumP高质量、高成本或高 SLA 请求

具体 Credits 消耗不应该手算。网关会从路由器查询模型费率,然后让 billing-service 根据 token 和费率计算。

预冻结

如果启用了钱包额度,网关会在调用提供方前先冻结 Credits。

预估输入来自:

输入来源
输入 token 估算messages 字符数粗略换算
输出 token 估算请求 max_tokens,没有时使用网关默认 max tokens,再没有时使用 1024
输入/输出价格路由器返回的所选模型客户侧费率
最小冻结估算大于 0 时至少冻结 0.000001 Credits;否则使用配置的默认冻结值或 1 Credit

提供方失败时会释放冻结。提供方成功后,如果费用计算或用量记录失败,也会释放冻结,避免错误扣费。

费用计算

网关会调用:

  • router-service GetBillingRates:取模型费率。
  • billing-service Calculate:计算 credits_usedusd_cost、提供方成本和毛利。
  • billing-service RecordUsage:按 request_id 幂等记录用量。
  • wallet-service Settle:用真实 Credits 结算冻结。

metadata.billing 常见字段:

字段含义
credits_used本次请求消耗 Credits
input_tokens输入 tokens
output_tokens输出 tokens
cached_input_tokenscache read / cached input tokens
cached_output_tokenscache write / cached output tokens

用量记录字段

网关记录用量时会传递:

字段说明
request_id用量记录的幂等键,由网关生成 usage-*
user_id / tenant_id个人或组织归属
api_key_idAPI Key 归因
model_key请求或路由侧模型 key
model提供方实际返回模型,缺省时使用所选模型
tier计费 tier
billing_modePERSONALORG
provider实际提供方
input_tokens / output_tokenstoken 消耗
cache_read_tokens / cache_write_tokenscache 相关 token
upstream_latency_ms提供方延迟
failover_triggered是否触发提供方故障切换
customer_*_rate客户侧费率
provider_*_rate_usdprovider 成本费率

流式计费

流式响应会边转发提供方分块,边解析用量。结束前,网关会追加一条元数据事件:

Streaming tail
data: {"metadata":{"tier":"standard","billing":{"credits_used":"0.2288","input_tokens":54,"output_tokens":545}}}
data: [DONE]

如果流式响应没拿到可用用量,网关会释放冻结,并记录为无法结算的流式请求。

分析指标

billing-service 和 analytics 侧提供这些聚合视图:

视图用途
用量汇总总请求量、tokens、Credits、USD cost
成本趋势按日/周/月看费用趋势
模型排行按模型排行
API Key 排行按 Key 成本归因
成员排行团队成员成本归因
Tier 分布economy / standard / premium 分布
用量指标cache hit rate、decision latency、upstream latency

成本控制建议

  • 每个环境和工作流使用独立 API Key。
  • 给 IDE、Agent、RAG indexing 使用单独预算。
  • 优先使用 model: "auto" + tier 策略做成本治理。
  • 对关键生产链路固定模型或固定 tier,避免上线后成本曲线漂移。
  • X-Request-ID 把应用日志和 JoyToken Usage / Billing 关联起来。