Skip to content
Source
Sign inSign up
TanStack/ai
Open History to see the last commit

billing.ts

51 lines1.8 KB

1import type { StreamChunk } from '@tanstack/ai'
2​
3/**
4 * Billing figures a finished video job reports. `VideoGenerateResult` — what
5 * `useGenerateVideo` hands back as its result — carries only the job id, url
6 * and expiry, so these are read off the terminal `generation:result` chunk
7 * through the hook's `onChunk` instead.
8 */
9export interface VideoBilling {
10 /** Priced units billed — fal units, or seconds of video on xAI Imagine. */
11 unitsBilled?: number
12 /** Provider-reported cost in USD, for providers that report one. */
13 cost?: number
14 /** Token total, for providers that bill media generation as tokens. */
15 totalTokens?: number
17​
18function numberField(source: object, key: string): number | undefined {
19 const value: unknown = Reflect.get(source, key)
20 return typeof value === 'number' ? value : undefined
22​
23/**
24 * Reads the usage block off a generation's terminal result chunk, or
25 * `undefined` for every other chunk (and for providers that report no usage).
26 */
27export function readVideoBilling(chunk: StreamChunk): VideoBilling | undefined {
28 if (chunk.type !== 'CUSTOM' || chunk.name !== 'generation:result') {
29 return undefined
30 }
31 const value: unknown = chunk.value
32 if (typeof value !== 'object' || value === null) return undefined
33 const usage: unknown = Reflect.get(value, 'usage')
34 if (typeof usage !== 'object' || usage === null) return undefined
35​
36 const unitsBilled = numberField(usage, 'unitsBilled')
37 const cost = numberField(usage, 'cost')
38 const totalTokens = numberField(usage, 'totalTokens')
39 if (
40 unitsBilled === undefined &&
41 cost === undefined &&
42 totalTokens === undefined
43 ) {
44 return undefined
45 }
46 return {
47 ...(unitsBilled !== undefined && { unitsBilled }),
48 ...(cost !== undefined && { cost }),
49 ...(totalTokens !== undefined && { totalTokens }),
50 }