Open History to see the last commit
1/**
2 * A provider's own usage object → the card's usage levers.
3 *
4 * Card levers are disjoint: `input_tokens` excludes the tokens billed at a
5 * cache or modality lever, and `output_tokens` excludes any lever split out
6 * of it. Providers report overlapping counts instead: OpenAI and Gemini
7 * count cached tokens and cache writes inside the prompt total, Anthropic
8 * does not. Pass the usage object as the API returned it and
9 * `normalizeUsage` subtracts each part from its total.
10 *
11 * Cache reads and cache writes always get their own lever, so a card with
12 * no rate for that lever refuses them. Reasoning, audio, image and video
13 * tokens get their own lever only when the card reads it; otherwise they
14 * stay in their total,
15 * which is how the source bills them. A usage object in the card's own
16 * vocabulary passes through, except a zero lever the card does not read,
17 * which is dropped.
18 */
19import { RateCardError, cardParams, isRecord } from './evaluate.ts'
20import type { RateCard } from './card.ts'
21
22type Vars = Record<string, unknown>
23
24export type UsageFormat =
25 | 'card'
26 | 'openai-responses'
27 | 'openai-chat'
28 | 'anthropic'
29 | 'gemini'
30
31type NativeFormat = Exclude<UsageFormat, 'card'>
32
33/** Top-level keys of each native usage object. */
34const FORMAT_KEYS: Record<NativeFormat, readonly string[]> = {
35 'openai-responses': [
36 'input_tokens',
37 'output_tokens',
38 'total_tokens',
39 'input_tokens_details',
40 'output_tokens_details',
41 ],
42 'openai-chat': [
43 'prompt_tokens',
44 'completion_tokens',
45 'total_tokens',
46 'prompt_tokens_details',
47 'completion_tokens_details',
48 ],
49 anthropic: [
50 'input_tokens',
51 'output_tokens',
52 'cache_read_input_tokens',
53 'cache_creation_input_tokens',
54 'cache_creation',
55 'server_tool_use',
56 'service_tier',
57 ],
58 gemini: [
59 'promptTokenCount',
60 'cachedContentTokenCount',
61 'candidatesTokenCount',
62 'thoughtsTokenCount',
63 'toolUsePromptTokenCount',
64 'totalTokenCount',
65 'promptTokensDetails',
66 'cacheTokensDetails',
67 'candidatesTokensDetails',
68 'toolUsePromptTokensDetails',
69 'trafficType',
70 ],
71}
72
73const FORMATS = Object.keys(FORMAT_KEYS) as [NativeFormat, ...NativeFormat[]]
74
75/**
76 * Keys that do not mark a native format: card levers that a native format
77 * also uses with its own meaning, and totals, which price nothing.
78 */
79const NOT_MARKERS = new Set([
80 'input_tokens',
81 'output_tokens',
82 'total_tokens',
83 'totalTokenCount',
84])
85
86const NATIVE = new Set(
87 Object.values(FORMAT_KEYS)
88 .flat()
89 .filter((key) => !NOT_MARKERS.has(key)),
90)
91
92/** Levers split out even when the card does not read them. */
93const ALWAYS_SPLIT = new Set([
94 'cache_read_tokens',
95 'cache_write_tokens',
96 'cache_write_1h_tokens',
97])
98
99/**
100 * The format of a usage object: `card` when it has no key that only a
101 * provider's usage object has. A key the card reads is a card lever (the
102 * Seedance cards read `completion_tokens`). A key from another format, or
103 * a card lever beside native keys, throws `mixed-usage`.
104 */
105export function usageFormat(
106 card: Pick<RateCard, 'inputs'>,
107 usage: Vars,
108): UsageFormat {
109 const keys = Object.keys(usage)
110 const marked = keys.filter((key) => NATIVE.has(key))
111 if (marked.length === 0) return 'card'
112 const reads = cardParams(card).usage
113 if (marked.every((key) => reads.includes(key))) return 'card'
114 let closest: NativeFormat = FORMATS[0]
115 let foreign = keys
116 for (const format of FORMATS) {
117 const outside = keys.filter((key) => !FORMAT_KEYS[format].includes(key))
118 if (outside.length < foreign.length) {
119 closest = format
120 foreign = outside
121 }
122 }
123 if (foreign.length > 0) {
124 throw new RateCardError(
125 'mixed-usage',
126 `${foreign.map((key) => `usage.${key}`).join(', ')}: not a field of ${closest} usage. ` +
127 'Send the provider usage object as returned, or card levers only, not both',
128 )
129 }
130 return closest
131}
132
133function count(value: unknown, path: string): number {
134 if (value == null) return 0
135 if (typeof value !== 'number' || !Number.isInteger(value) || value < 0) {
136 throw new RateCardError(
137 'bad-input',
138 `usage.${path}: expected a token count, got ${JSON.stringify(value)}`,
139 )
140 }
141 return value
142}
143
144/** A format total. Missing is an incomplete bill, not a zero. */
145function requiredCount(value: unknown, path: string): number {
146 if (value == null) {
147 throw new RateCardError(
148 'bad-input',
149 `usage.${path}: expected a token count, got ${JSON.stringify(value)}`,
150 )
151 }
152 return count(value, path)
153}
154
155/**
156 * A count reader over a nested details object. A key this reader does not
157 * know throws.
158 */
159function details(
160 value: unknown,
161 path: string,
162 known: string[],
163): (key: string) => number {
164 if (value == null) return () => 0
165 if (!isRecord(value)) {
166 throw new RateCardError(
167 'bad-input',
168 `usage.${path}: expected an object, got ${JSON.stringify(value)}`,
169 )
170 }
171 const unknown = Object.keys(value).filter((key) => !known.includes(key))
172 if (unknown.length > 0) {
173 throw new RateCardError(
174 'unknown-usage-key',
175 `${unknown.map((key) => `usage.${path}.${key}`).join(', ')}: not read by the usage normalizer`,
176 )
177 }
178 return (key) => count(value[key], `${path}.${key}`)
179}
180
181type Modality = 'audio' | 'image' | 'video'
182
183const MODALITIES: Modality[] = ['audio', 'image', 'video']
184
185/** Gemini `[{ modality, tokenCount }]` → tokens per priced modality. */
186function byModality(value: unknown, path: string): Record<Modality, number> {
187 const out: Record<Modality, number> = { audio: 0, image: 0, video: 0 }
188 if (value == null) return out
189 if (!Array.isArray(value)) {
190 throw new RateCardError(
191 'bad-input',
192 `usage.${path}: expected a list, got ${JSON.stringify(value)}`,
193 )
194 }
195 value.forEach((entry: unknown, i) => {
196 const tokens = details(entry, `${path}[${i}]`, ['modality', 'tokenCount'])
197 const modality = MODALITIES.find(
198 (m) => isRecord(entry) && entry.modality === m.toUpperCase(),
199 )
200 if (modality) out[modality] += tokens('tokenCount')
201 })
202 return out
203}
204
205/**
206 * `total` split into `base` and the parts that get their own lever. A part
207 * stays in `base` unless it always splits or the card reads its lever.
208 */
209function apportion(
210 reads: Set<string>,
211 base: string,
212 total: number,
213 parts: Array<[lever: string, n: number]>,
214): Record<string, number> {
215 const out: Record<string, number> = {}
216 let rest = total
217 for (const [lever, n] of parts) {
218 if (n < 0) {
219 throw new RateCardError('bad-input', `usage: ${lever} is negative (${n})`)
220 }
221 if (n > 0 && (ALWAYS_SPLIT.has(lever) || reads.has(lever))) {
222 out[lever] = n
223 rest -= n
224 }
225 }
226 if (rest < 0) {
227 throw new RateCardError(
228 'bad-input',
229 `usage: the parts of ${base} add up to more than its total ${total}`,
230 )
231 }
232 out[base] = rest
233 return out
234}
235
236type Normalizer = (usage: Vars, reads: Set<string>) => Record<string, number>
237
238const NORMALIZERS: Record<NativeFormat, Normalizer> = {
239 // input_tokens includes cached_tokens and cache_write_tokens.
240 // output_tokens includes reasoning.
241 'openai-responses': (usage, reads) => {
242 const input = details(usage.input_tokens_details, 'input_tokens_details', [
243 'cached_tokens',
244 'cache_write_tokens',
245 ])
246 const output = details(
247 usage.output_tokens_details,
248 'output_tokens_details',
249 ['reasoning_tokens'],
250 )
251 return {
252 ...apportion(
253 reads,
254 'input_tokens',
255 requiredCount(usage.input_tokens, 'input_tokens'),
256 [
257 ['cache_read_tokens', input('cached_tokens')],
258 ['cache_write_tokens', input('cache_write_tokens')],
259 ],
260 ),
261 ...apportion(
262 reads,
263 'output_tokens',
264 requiredCount(usage.output_tokens, 'output_tokens'),
265 [['reasoning_tokens', output('reasoning_tokens')]],
266 ),
267 }
268 },
269 // prompt_tokens includes cached, audio and image tokens. text_tokens
270 // is the remainder already inside that total, so it is accepted and
271 // not subtracted. completion_tokens includes reasoning, audio and both
272 // prediction counts.
273 'openai-chat': (usage, reads) => {
274 const prompt = details(
275 usage.prompt_tokens_details,
276 'prompt_tokens_details',
277 [
278 'cached_tokens',
279 'cache_write_tokens',
280 'audio_tokens',
281 'image_tokens',
282 'text_tokens',
283 ],
284 )
285 const completion = details(
286 usage.completion_tokens_details,
287 'completion_tokens_details',
288 [
289 'reasoning_tokens',
290 'audio_tokens',
291 'accepted_prediction_tokens',
292 'rejected_prediction_tokens',
293 ],
294 )
295 return {
296 ...apportion(
297 reads,
298 'input_tokens',
299 requiredCount(usage.prompt_tokens, 'prompt_tokens'),
300 [
301 ['cache_read_tokens', prompt('cached_tokens')],
302 ['cache_write_tokens', prompt('cache_write_tokens')],
303 ['audio_tokens', prompt('audio_tokens')],
304 ['image_tokens', prompt('image_tokens')],
305 ],
306 ),
307 ...apportion(
308 reads,
309 'output_tokens',
310 requiredCount(usage.completion_tokens, 'completion_tokens'),
311 [
312 ['reasoning_tokens', completion('reasoning_tokens')],
313 ['audio_output_tokens', completion('audio_tokens')],
314 ],
315 ),
316 }
317 },
318 // input_tokens excludes cache reads and writes; cache_creation splits
319 // the writes by TTL.
320 anthropic: (usage, reads) => {
321 const creation = details(usage.cache_creation, 'cache_creation', [
322 'ephemeral_5m_input_tokens',
323 'ephemeral_1h_input_tokens',
324 ])
325 const tools = details(usage.server_tool_use, 'server_tool_use', [
326 'web_search_requests',
327 'web_fetch_requests',
328 ])
329 return {
330 input_tokens: requiredCount(usage.input_tokens, 'input_tokens'),
331 output_tokens: requiredCount(usage.output_tokens, 'output_tokens'),
332 cache_read_tokens: count(
333 usage.cache_read_input_tokens,
334 'cache_read_input_tokens',
335 ),
336 ...apportion(
337 reads,
338 'cache_write_tokens',
339 count(usage.cache_creation_input_tokens, 'cache_creation_input_tokens'),
340 [['cache_write_1h_tokens', creation('ephemeral_1h_input_tokens')]],
341 ),
342 web_searches: tools('web_search_requests'),
343 }
344 },
345 // promptTokenCount includes cachedContentTokenCount; thoughtsTokenCount
346 // and toolUsePromptTokenCount are outside the prompt and candidates.
347 gemini: (usage, reads) => {
348 const cached = count(
349 usage.cachedContentTokenCount,
350 'cachedContentTokenCount',
351 )
352 const prompt = byModality(usage.promptTokensDetails, 'promptTokensDetails')
353 const cache = byModality(usage.cacheTokensDetails, 'cacheTokensDetails')
354 const output = byModality(
355 usage.candidatesTokensDetails,
356 'candidatesTokensDetails',
357 )
358 const thoughts = count(usage.thoughtsTokenCount, 'thoughtsTokenCount')
359 const uncached =
360 requiredCount(usage.promptTokenCount, 'promptTokenCount') - cached
361 if (uncached < 0) {
362 throw new RateCardError(
363 'bad-input',
364 `usage: cachedContentTokenCount ${cached} is more than promptTokenCount`,
365 )
366 }
367 return {
368 ...apportion(
369 reads,
370 'input_tokens',
371 uncached +
372 count(usage.toolUsePromptTokenCount, 'toolUsePromptTokenCount'),
373 MODALITIES.map((m) => [`${m}_tokens`, prompt[m] - cache[m]]),
374 ),
375 ...apportion(
376 reads,
377 'cache_read_tokens',
378 cached,
379 MODALITIES.map((m) => [`${m}_cache_tokens`, cache[m]]),
380 ),
381 ...apportion(
382 reads,
383 'output_tokens',
384 requiredCount(usage.candidatesTokenCount, 'candidatesTokenCount') +
385 thoughts,
386 [
387 ['reasoning_tokens', thoughts],
388 ...MODALITIES.map((m): [string, number] => [
389 `${m}_output_tokens`,
390 output[m],
391 ]),
392 ],
393 ),
394 }
395 },
396}
397
398/**
399 * Drop a zero lever the card does not read. The same object when nothing
400 * drops, so a card-lever payload with no such zero stays the caller's.
401 */
402function withoutUnreadZeros(reads: ReadonlySet<string>, levers: Vars): Vars {
403 const dropped = Object.keys(levers).filter(
404 (lever) => levers[lever] === 0 && !reads.has(lever),
405 )
406 if (dropped.length === 0) return levers
407 const kept = { ...levers }
408 for (const lever of dropped) delete kept[lever]
409 return kept
410}
411
412/**
413 * `usage` in the card's lever vocabulary. A native OpenAI (Responses or
414 * Chat Completions), Anthropic or Gemini (`usageMetadata`) usage object is
415 * mapped to disjoint levers; card levers pass through. A zero lever the
416 * card does not read is dropped, whether it arrived as a card lever or
417 * from a native usage object, so a card with no cache rate still prices a
418 * call that cached nothing. A non-zero lever the card does not read is
419 * left in place; `priceDetailed` throws `unknown-usage-key` for it.
420 * Throws `mixed-usage` for a payload that mixes native fields and card
421 * levers.
422 */
423export function normalizeUsage(
424 card: Pick<RateCard, 'inputs'>,
425 usage: Vars,
426): Vars {
427 const format = usageFormat(card, usage)
428 const reads = new Set(cardParams(card).usage)
429 const levers = format === 'card' ? usage : NORMALIZERS[format](usage, reads)
430 return withoutUnreadZeros(reads, levers)
431}