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

catalog-prices.ts

245 lines8.0 KB

1/**
2 * Rate cards from numbers a `/models` row already publishes (issue #109).
3 * A missing unit, a zero quote, or a tier the row says is not flat stays
4 * null. Nothing here invents a price.
5 */
6import { compileTokenCard } from '@modelschemas/rate-card'
7import type { RateCard } from '@modelschemas/rate-card'
8​
9import { sha256Text } from './types.ts'
10​
11async function tokenCard(
12 rates: Record<string, number>,
13 url: string,
14 raw: unknown,
15): Promise<RateCard | null> {
16 const priced: Record<string, number> = {}
17 for (const [key, value] of Object.entries(rates)) {
18 if (Number.isFinite(value) && value > 0) priced[key] = value
19 }
20 return compileTokenCard(priced, [], {
21 url,
22 hash: await sha256Text(JSON.stringify(raw)),
23 extractedAt: new Date().toISOString(),
24 })
26​
27function decimalPerMillion(node: unknown): number | null {
28 if (node === null || typeof node !== 'object') return null
29 const value = (node as { price_per_m_decimal?: unknown }).price_per_m_decimal
30 if (typeof value !== 'string' || !/^\d+(?:\.\d+)?$/.test(value)) return null
31 return Number(value) / 1e6
33​
34/** Novita `pricing.*.price_per_m_decimal` is USD per million tokens. */
35export async function novitaListingCard(
36 pricing: unknown,
37 tiered: boolean | undefined,
38 url: string,
39): Promise<RateCard | null> {
40 if (tiered || pricing === null || typeof pricing !== 'object') return null
41 const row = pricing as Record<string, unknown>
42 const rates: Record<string, number> = {}
43 const input = decimalPerMillion(row.prompt)
44 const output = decimalPerMillion(row.completion)
45 const cacheRead = decimalPerMillion(row.input_cache_read)
46 const cacheWrite = decimalPerMillion(row.input_cache_write)
47 if (input !== null) rates.input_tokens = input
48 if (output !== null) rates.output_tokens = output
49 if (cacheRead !== null) rates.cache_read_tokens = cacheRead
50 if (cacheWrite !== null) rates.cache_write_tokens = cacheWrite
51 return tokenCard(rates, url, pricing)
53​
54const NOVITA_TIER_LEVERS = [
55 ['prompt', 'input_tokens'],
56 ['completion', 'output_tokens'],
57 ['input_cache_read', 'cache_read_tokens'],
58 ['input_cache_write', 'cache_write_tokens'],
59] as const
60​
61/**
62 * Novita `tiered_billing_configs`. The standard rate is the lowest
63 * `min_tokens` bracket. A later bracket applies once the prompt is past
64 * that bracket's `min_tokens`. A missing or empty config list is not a
65 * published table. A present list that cannot be read throws.
66 */
67export async function novitaTieredCard(
68 configs: unknown,
69 url: string,
70): Promise<RateCard | null> {
71 if (configs == null) return null
72 if (!Array.isArray(configs)) {
73 throw new Error('novita tiered billing: configs are not an array')
74 }
75 if (configs.length === 0) return null
76 const brackets = configs.map((config, index) =>
77 novitaTierBracket(config, index),
78 )
79 brackets.sort((a, b) => a.minTokens - b.minTokens)
80 for (let i = 1; i < brackets.length; i++) {
81 if (brackets[i]?.minTokens === brackets[i - 1]?.minTokens) {
82 throw new Error('novita tiered billing: duplicate min_tokens')
83 }
84 }
85 const base = brackets[0]
86 if (!base) return null
87 for (const bracket of brackets.slice(1)) {
88 for (const lever of Object.keys(base.rates)) {
89 if (bracket.rates[lever] === undefined) {
90 throw new Error(
91 `novita tiered billing: a higher bracket omits ${lever}`,
92 )
93 }
94 }
95 }
96 const card = compileTokenCard(
97 base.rates,
98 brackets.slice(1).map((bracket) => ({
99 minPromptTokens: bracket.minTokens,
100 rates: bracket.rates,
101 })),
102 {
103 url,
104 hash: await sha256Text(JSON.stringify(configs)),
105 extractedAt: new Date().toISOString(),
106 },
107 )
108 if (!card) throw new Error('novita tiered billing: configs did not compile')
109 return card
111​
112function novitaTierBracket(
113 config: unknown,
114 index: number,
115): { minTokens: number; rates: Record<string, number> } {
116 if (config === null || typeof config !== 'object') {
117 throw new Error(
118 `novita tiered billing: bracket ${String(index)} is not an object`,
119 )
120 }
121 const row = config as { min_tokens?: unknown; pricing?: unknown }
122 if (typeof row.min_tokens !== 'number' || !Number.isInteger(row.min_tokens)) {
123 throw new Error(
124 `novita tiered billing: bracket ${String(index)} has no min_tokens`,
125 )
126 }
127 if (row.min_tokens < 0) {
128 throw new Error(
129 `novita tiered billing: bracket ${String(index)} has no min_tokens`,
130 )
131 }
132 return {
133 minTokens: row.min_tokens,
134 rates: novitaTierRates(row.pricing, index),
135 }
137​
138function novitaTierRates(
139 pricing: unknown,
140 index: number,
141): Record<string, number> {
142 if (pricing === null || typeof pricing !== 'object') {
143 throw new Error(
144 `novita tiered billing: bracket ${String(index)} has no pricing`,
145 )
146 }
147 const row = pricing as Record<string, unknown>
148 const rates: Record<string, number> = {}
149 for (const [key, lever] of NOVITA_TIER_LEVERS) {
150 const required = key === 'prompt' || key === 'completion'
151 if (!(key in row)) {
152 if (required) {
153 throw new Error(
154 `novita tiered billing: bracket ${String(index)} omits ${key}`,
155 )
156 }
157 continue
158 }
159 const value = decimalPerMillion(row[key])
160 if (value === null) {
161 throw new Error(
162 `novita tiered billing: bracket ${String(index)} ${key} is unreadable`,
163 )
164 }
165 if (value <= 0) {
166 if (required) {
167 throw new Error(
168 `novita tiered billing: bracket ${String(index)} ${key} is not positive`,
169 )
170 }
171 continue
172 }
173 rates[lever] = value
174 }
175 return rates
177​
178function finite(value: unknown): number | null {
179 return typeof value === 'number' && Number.isFinite(value) ? value : null
181​
182/** Perplexity quotes USD per million and names the unit on the row. */
183export async function perplexityListingCard(
184 pricing: unknown,
185 url: string,
186): Promise<RateCard | null> {
187 if (pricing === null || typeof pricing !== 'object') return null
188 const row = pricing as Record<string, unknown>
189 if (row.unit !== 'usd_per_1m_tokens') return null
190 const rates: Record<string, number> = {}
191 const input = finite(row.input)
192 const output = finite(row.output)
193 const cacheRead = finite(row.cache_read)
194 const cacheWrite = finite(row.cache_write)
195 if (input !== null) rates.input_tokens = input / 1e6
196 if (output !== null) rates.output_tokens = output / 1e6
197 if (cacheRead !== null) rates.cache_read_tokens = cacheRead / 1e6
198 if (cacheWrite !== null) rates.cache_write_tokens = cacheWrite / 1e6
199 return tokenCard(rates, url, pricing)
201​
202function perToken(value: unknown): number | null {
203 if (typeof value === 'number' && Number.isFinite(value)) return value
204 if (typeof value === 'string' && /^\d+(?:\.\d+)?$/.test(value)) {
205 return Number(value)
206 }
207 return null
209​
210/**
211 * Jina and SambaNova `pricing.prompt` / `completion` are USD per token
212 * (a per-million reading of `0.00000005` is not a published rate).
213 */
214export async function perTokenListingCard(
215 pricing: unknown,
216 url: string,
217): Promise<RateCard | null> {
218 if (pricing === null || typeof pricing !== 'object') return null
219 const row = pricing as Record<string, unknown>
220 const rates: Record<string, number> = {}
221 const input = perToken(row.prompt)
222 const output = perToken(row.completion)
223 const cacheRead = perToken(row.input_cache_read)
224 const cacheWrite = perToken(row.input_cache_write)
225 if (input !== null) rates.input_tokens = input
226 if (output !== null) rates.output_tokens = output
227 if (cacheRead !== null) rates.cache_read_tokens = cacheRead
228 if (cacheWrite !== null) rates.cache_write_tokens = cacheWrite
229 return tokenCard(rates, url, pricing)
231​
232/**
233 * Hyperbolic `input_price` / `output_price` are USD per million tokens.
234 * The same numbers as per-token rates would be dollars per single token.
235 */
236export async function hyperbolicListingCard(
237 input: unknown,
238 output: unknown,
239 url: string,
240): Promise<RateCard | null> {
241 const rates: Record<string, number> = {}
242 if (typeof input === 'number') rates.input_tokens = input / 1e6
243 if (typeof output === 'number') rates.output_tokens = output / 1e6
244 return tokenCard(rates, url, { input, output })