ai-billing

Compare original and translation side by side

🇺🇸

Original

English
🇨🇳

Translation

Chinese

AI Billing

AI计费

Quick Start

快速开始

Wrap any Vercel AI SDK model with
tracked()
to automatically bill for token usage:
typescript
import { Commet } from "@commet/node";
import { tracked } from "@commet/ai-sdk";
import { anthropic } from "@ai-sdk/anthropic";
import { generateText } from "ai";

const commet = new Commet({ apiKey: process.env.COMMET_API_KEY! });

const result = await generateText({
  model: tracked(anthropic("claude-sonnet-4-20250514"), {
    commet,
    feature: "ai_generation",
    customerId: "user_123",
  }),
  prompt: "Explain quantum computing",
});
// Tokens tracked, cost calculated, balance deducted. Done.
That's it.
tracked()
intercepts the model response, reports
inputTokens
,
outputTokens
,
cacheReadTokens
, and
cacheWriteTokens
to Commet, which calculates cost from the AI model catalog and deducts from the customer's balance.
使用
tracked()
封装任意Vercel AI SDK模型,即可自动针对Token用量计费:
typescript
import { Commet } from "@commet/node";
import { tracked } from "@commet/ai-sdk";
import { anthropic } from "@ai-sdk/anthropic";
import { generateText } from "ai";

const commet = new Commet({ apiKey: process.env.COMMET_API_KEY! });

const result = await generateText({
  model: tracked(anthropic("claude-sonnet-4-20250514"), {
    commet,
    feature: "ai_generation",
    customerId: "user_123",
  }),
  prompt: "Explain quantum computing",
});
// Tokens tracked, cost calculated, balance deducted. Done.
就这么简单。
tracked()
会拦截模型响应,将
inputTokens
outputTokens
cacheReadTokens
cacheWriteTokens
上报到Commet,Commet会基于AI模型目录计算成本并从客户余额中扣除对应费用。

How It Works

工作原理

Your app                    Commet                         AI Provider
   |                          |                                |
   |-- tracked(model) ------->|                                |
   |                          |                                |
   |-- generateText() --------|-------- API call ------------->|
   |                          |                                |
   |<-- tokens + response ----|<------- response --------------|
   |                          |                                |
   |                          |-- resolve model price          |
   |                          |-- apply margin                 |
   |                          |-- deduct from balance          |
   |                          |-- record ledger entry          |
   |                          |                                |
   |<-- result (unchanged) ---|                                |
你的应用                    Commet                         AI供应商
   |                          |                                |
   |-- tracked(model) ------->|                                |
   |                          |                                |
   |-- generateText() --------|-------- API调用 ------------->|
   |                          |                                |
   |<-- Token + 响应 ---------|<------- 响应 -----------------|
   |                          |                                |
   |                          |-- 匹配模型定价                  |
   |                          |-- 应用利润率                    |
   |                          |-- 扣除余额                      |
   |                          |-- 记录台账条目                  |
   |                          |                                |
   |<-- 结果(无修改)--------|                                |

Balance Model Overview

余额模式概述

AI billing uses the balance consumption model. Customers get a dollar balance (e.g., $10.00/month) that depletes as they use AI features. When the balance reaches zero, behavior depends on configuration:
  • blockOnExhaustion = true
    : API returns 402, customer must top up or wait for renewal
  • blockOnExhaustion = false
    : Usage continues, overage charged at period end
Balance resets to
includedBalance
at each billing period renewal.
AI计费采用余额消耗模式。客户会获得一笔美元余额(例如每月$10.00),随着使用AI功能逐步消耗。余额归零时的行为取决于配置:
  • blockOnExhaustion = true
    :API返回402,客户需要充值或等待周期续期
  • blockOnExhaustion = false
    :可继续使用,超额部分在周期结束时统一收费
余额会在每个计费周期续期时重置为
includedBalance
的数值。

Cost Formula

成本计算公式

All values use rate scale (10000 = $1.00) for sub-cent precision:
inputCost    = ceil(inputTokens    x inputPricePerMillionTokens    / 1,000,000)
outputCost   = ceil(outputTokens   x outputPricePerMillionTokens   / 1,000,000)
subtotal     = inputCost + outputCost + cacheReadCost + cacheWriteCost
marginAmount = ceil(subtotal x margin / 10000)
total        = subtotal + marginAmount
Margin is configured per feature per plan in basis points (2000 = 20% markup). All costs use
Math.ceil()
to prevent underbilling.
所有数值采用费率刻度(10000 = $1.00)以保证亚分精度:
inputCost    = ceil(inputTokens    x inputPricePerMillionTokens    / 1,000,000)
outputCost   = ceil(outputTokens   x outputPricePerMillionTokens   / 1,000,000)
subtotal     = inputCost + outputCost + cacheReadCost + cacheWriteCost
marginAmount = ceil(subtotal x margin / 10000)
total        = subtotal + marginAmount
利润率按每个套餐的每个功能以基点配置(2000 = 20%溢价)。所有成本采用
Math.ceil()
计算以避免少计费。

Key Gotchas

关键注意事项

#GotchaDetail
1Feature must be
pricingMode: "ai_model"
Configure this in the Commet dashboard before tracking works
2Model must exist in the catalogCommet syncs models from AI Gateway automatically, but verify your model is listed
3Tracking is non-blockingIf token reporting fails, the AI response still returns. Use
onTrackingError
to catch failures
4Balance deduction is real-timeCost is deducted immediately, not at period end
5Rate scale, not centsToken prices and costs use rate scale (10000 = $1.00), not settlement scale (100 = $1.00)
6Margin is per feature per planDifferent plans can have different markups on the same AI feature
#注意事项详情
1功能必须配置
pricingMode: "ai_model"
跟踪功能生效前需要在Commet控制台完成该配置
2模型必须存在于目录中Commet会自动从AI网关同步模型,但请确认你使用的模型在列表中
3跟踪逻辑是非阻塞的如果Token上报失败,AI响应仍会正常返回。可使用
onTrackingError
捕获失败事件
4余额扣减是实时的成本会立即扣除,而非在周期结束时结算
5采用费率刻度,而非美分Token定价和成本使用费率刻度(10000 = $1.00),而非结算刻度(100 = $1.00)
6利润率按套餐下的功能单独配置同一个AI功能在不同套餐中可以设置不同的溢价

What Do You Need?

相关任务指引

TaskReference
Set up tracked() middlewaretracked-middleware.md -- installation, streaming, multiple models, error handling
Understand cost calculationcost-calculation.md -- AI model catalog, pricing, margins, multi-currency
Configure balance modelbalance-model.md -- how balance works, exhaustion, top-ups, choosing the right model
任务参考文档
搭建tracked()中间件tracked-middleware.md -- 安装、流式处理、多模型、错误处理
了解成本计算逻辑cost-calculation.md -- AI模型目录、定价、利润率、多币种
配置余额模式balance-model.md -- 余额规则、用尽处理、充值、选择合适的模式

Prerequisites

前提条件

  1. Feature configured with
    pricingMode: "ai_model"
    in the Commet dashboard
  2. Plan using the balance consumption model
  3. Margin configured on the plan feature (0 basis points = pass-through cost)
  4. Customer with an active subscription to that plan
  1. 在Commet控制台中已将功能配置为
    pricingMode: "ai_model"
  2. 套餐采用余额消耗模式
  3. 套餐功能下已配置利润率(0基点 = 成本价透传)
  4. 客户已订阅该套餐且订阅有效

Common Setup

通用配置

API Key

API Key

Store in environment variable:
bash
export COMMET_API_KEY=ck_xxxxxxxxx
存储在环境变量中:
bash
export COMMET_API_KEY=ck_xxxxxxxxx

Install

安装

bash
npm install @commet/node @commet/ai-sdk
bash
npm install @commet/node @commet/ai-sdk

Error Handling Quick Reference

错误处理快速参考

CodeConditionAction
402Insufficient balanceCustomer needs to top up or upgrade plan
403Feature not in planCheck customer's subscription includes the AI feature
404Model not in catalogVerify the model ID matches the catalog (e.g.,
claude-sonnet-4-20250514
)
422Missing required fields
inputTokens
is required when
model
is provided
错误码触发条件处理方案
402余额不足客户需要充值或升级套餐
403套餐不包含该功能检查客户的订阅是否包含该AI功能
404模型不在目录中确认模型ID与目录一致(例如
claude-sonnet-4-20250514
422缺少必填字段提供
model
inputTokens
是必填项