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