Open History to see the last commit
1/**
2 * Replicate prediction prices (issue #120). Official model pages embed a
3 * `billingConfig` for the price of one prediction. Hardware-timed community
4 * models publish no such config and stay null. `equals` tiers become a
5 * rate lookup keyed by each criterion; a tier quoting several metrics is
6 * billed for their sum. A criterion we cannot name, tiers that disagree on
7 * their criteria, a missing combination, or a price unit this does not
8 * know is not a card. A keyed tier no card can state is left out, so a
9 * request naming it is refused (`stateable`). Token prices that step up above a prompt length
10 * are the one range tier read.
11 */
12import { compileTokenCard, compileUnitCard } from '@modelschemas/rate-card'
13import type {
14 Expr,
15 RateCard,
16 Table,
17 TokenRateTier,
18 UnitKey,
19} from '@modelschemas/rate-card'
20
21import { tagDocsFacts } from './fact-sources.ts'
22import type { ModelInfo } from './types.ts'
23
24interface ReplicateCriterion {
25 title?: string
26 type?: string
27 subtype?: string
28 /** A string for `equals`, `[from, to]` for `range`. */
29 value?: unknown
30}
31
32interface ReplicatePrice {
33 metric?: string
34 price?: string
35 title?: string
36 type?: string
37}
38
39interface ReplicateTier {
40 criteria?: Array<ReplicateCriterion>
41 prices?: Array<ReplicatePrice>
42}
43
44export interface ReplicateBilling {
45 current_tiers?: Array<ReplicateTier>
46}
47
48const METRIC_PARAM: Record<string, string> = {
49 image_output_count: 'output_images',
50 image_input_megapixel_count: 'input_megapixels',
51 token_input_count: 'input_tokens',
52 token_output_count: 'output_tokens',
53 video_output_duration_seconds: 'video_seconds',
54 audio_output_duration_seconds: 'audio_seconds',
55}
56
57/** `$3` / `$0.03` → dollars. Anything else is not a price we can store. */
58export function replicateDollars(price: string | undefined): number | null {
59 const match = price?.trim().match(/^\$(\d+(?:\.\d+)?)$/)
60 if (!match?.[1]) return null
61 const dollars = Number(match[1])
62 return Number.isFinite(dollars) && dollars > 0 ? dollars : null
63}
64
65/** `per thousand …` → how many billed units one quoted price covers. */
66export function replicatePriceScale(title: string | undefined): number | null {
67 const text = title?.trim().toLowerCase() ?? ''
68 if (text.startsWith('per thousand')) return 1000
69 if (text.startsWith('per million')) return 1_000_000
70 if (text.startsWith('per second')) return 1
71 if (
72 text.startsWith('per output image') ||
73 text.startsWith('per image') ||
74 text.startsWith('per input image megapixel')
75 ) {
76 return 1
77 }
78 if (text.startsWith('per minute')) return 60
79 if (text.startsWith('per hour')) return 3600
80 return null
81}
82
83function criterionParam(title: string | undefined): string | null {
84 const slug = title
85 ?.trim()
86 .toLowerCase()
87 .replace(/[^a-z0-9]+/g, '_')
88 .replace(/^_|_$/g, '')
89 if (!slug || slug.length > 40) return null
90 return slug
91}
92
93interface Leaf {
94 param: string
95 /** USD per one unit of `param`. */
96 rate: number
97 /** Request fields this tier is keyed by, in criterion order. */
98 keys: Array<{ param: string; value: string }>
99}
100
101function leaf(price: ReplicatePrice, keys: Leaf['keys']): Leaf | null {
102 if (price.type !== undefined && price.type !== 'per-unit') return null
103 const param = price.metric ? METRIC_PARAM[price.metric] : undefined
104 const dollars = replicateDollars(price.price)
105 const scale = replicatePriceScale(price.title)
106 if (!param || dollars === null || scale === null) return null
107 // Duration titles ("per minute") quote several seconds; token and image
108 // titles ("per thousand") quote that many billed units. Both are USD / scale.
109 // toPrecision: `$0.015` per thousand is 0.000015, not 0.0000149999….
110 const rate = Number((dollars / scale).toPrecision(12))
111 if (!(rate > 0)) return null
112 return { param, rate, keys }
113}
114
115function tokenRates(
116 prices: Array<ReplicatePrice>,
117): Record<string, number> | null {
118 const rates: Record<string, number> = {}
119 for (const price of prices) {
120 const row = leaf(price, [])
121 if (!row || !row.param.endsWith('_tokens') || row.param in rates) {
122 return null
123 }
124 rates[row.param] = row.rate
125 }
126 return 'input_tokens' in rates && 'output_tokens' in rates ? rates : null
127}
128
129/**
130 * Token prices by prompt length: one `≤ N` tier (the base) and one `> N`
131 * tier that re-quotes above it. Any other range shape is not a card.
132 */
133function compilePromptTiers(
134 tiers: Array<ReplicateTier>,
135 source: RateCard['source'],
136): RateCard | null {
137 let base: { rates: Record<string, number>; upTo: number } | null = null
138 let above: TokenRateTier | null = null
139 for (const tier of tiers) {
140 const [criterion, ...more] = tier.criteria ?? []
141 const rates = tokenRates(tier.prices ?? [])
142 const range = criterion?.value
143 if (
144 !criterion ||
145 more.length > 0 ||
146 !rates ||
147 criterion.type !== 'range' ||
148 criterion.title !== 'input token' ||
149 !Array.isArray(range) ||
150 range.length !== 2
151 ) {
152 return null
153 }
154 const bounds: Array<unknown> = range
155 const [from, to] = bounds
156 if (
157 from === null &&
158 typeof to === 'number' &&
159 criterion.subtype === 'open-closed' &&
160 !base
161 ) {
162 base = { rates, upTo: to }
163 } else if (
164 typeof from === 'number' &&
165 to === null &&
166 criterion.subtype === 'open' &&
167 !above
168 ) {
169 above = { minPromptTokens: from, rates }
170 } else {
171 return null
172 }
173 }
174 if (!base || !above || base.upTo !== above.minPromptTokens) return null
175 return compileTokenCard(base.rates, [above], source)
176}
177
178/**
179 * A keyed tier a card can state. One the card cannot is left out, so its
180 * key value is not in the card and a request naming it is refused, never
181 * priced: a `null` value (the price when the request names none — an enum
182 * input cannot be absent), a metric with no known quantity
183 * (`unspecified_billing_metric`), or token prices under a key. The tiers
184 * left must still form the full grid.
185 */
186function stateable(tier: ReplicateTier): boolean {
187 const criteria = tier.criteria ?? []
188 if (criteria.length === 0) return true
189 if (criteria.some((c) => c.type === 'equals' && c.value === null)) {
190 return false
191 }
192 // Only these two known shapes are left out. A metric this file has never
193 // seen keeps its tier, so the grid fails and the poll logs pricing_lost.
194 return !(tier.prices ?? []).some(
195 (price) =>
196 price.metric === 'unspecified_billing_metric' ||
197 (price.metric !== undefined &&
198 Object.hasOwn(METRIC_PARAM, price.metric) &&
199 METRIC_PARAM[price.metric]!.endsWith('_tokens')),
200 )
201}
202
203/**
204 * Dollar prediction price → rate card.
205 * `null` when the config has no usable published price.
206 *
207 * Tiers keyed by request fields (`equals` criteria) become a lookup nested
208 * in criterion order. Every tier must use the same criteria in the same
209 * order, quote the same metrics, and together cover every combination. A
210 * tier that quotes more than one metric (an output image plus each input
211 * megapixel) is billed for all of them, so the card sums one
212 * `quantity × rate` term per metric.
213 */
214export function compileReplicateBilling(
215 billing: ReplicateBilling | null | undefined,
216 source: RateCard['source'],
217): RateCard | null {
218 const listed = billing?.current_tiers
219 if (!listed || listed.length === 0) return null
220 if (listed.some((tier) => tier.criteria?.some((c) => c.type === 'range'))) {
221 return compilePromptTiers(listed, source)
222 }
223 const tiers = listed.filter(stateable)
224
225 const leaves: Array<Leaf> = []
226 let keyParams: Array<string> | null = null
227 for (const tier of tiers) {
228 const prices = tier.prices ?? []
229 if (prices.length === 0) return null
230 const keys: Leaf['keys'] = []
231 for (const criterion of tier.criteria ?? []) {
232 const param = criterionParam(criterion.title)
233 if (
234 criterion.type !== 'equals' ||
235 !param ||
236 typeof criterion.value !== 'string' ||
237 criterion.value === ''
238 ) {
239 return null
240 }
241 keys.push({ param, value: criterion.value })
242 }
243 const tierParams = keys.map((key) => key.param)
244 if (new Set(tierParams).size !== tierParams.length) return null
245 if (keyParams === null) keyParams = tierParams
246 else if (tierParams.join('\0') !== keyParams.join('\0')) return null
247 const tierLeaves: Array<Leaf> = []
248 for (const price of prices) {
249 const row = leaf(price, keys)
250 if (!row || tierLeaves.some((other) => other.param === row.param)) {
251 return null
252 }
253 tierLeaves.push(row)
254 }
255 leaves.push(...tierLeaves)
256 }
257 if (!keyParams) return null
258 // Unkeyed tiers name no field to choose between them.
259 if (keyParams.length === 0 && tiers.length !== 1) return null
260
261 const params = [...new Set(leaves.map((row) => row.param))]
262 const tokenParams = params.filter((param) => param.endsWith('_tokens'))
263 if (tokenParams.length > 0) {
264 if (tokenParams.length !== params.length || keyParams.length > 0) {
265 return null
266 }
267 if (params.length !== leaves.length) return null
268 return compileTokenCard(
269 Object.fromEntries(leaves.map((row) => [row.param, row.rate])),
270 [],
271 source,
272 )
273 }
274
275 const combos = tiers.length
276 if (leaves.length !== combos * params.length) return null
277 // A criterion and a metric sharing a name would be one input of two kinds.
278 if (keyParams.some((param) => params.includes(param))) return null
279 const keys: Array<UnitKey> = keyParams.map((param, index) => ({
280 param,
281 values: [...new Set(leaves.flatMap((row) => row.keys[index]?.value ?? []))],
282 bound: 'usage',
283 }))
284 const terms: Array<{ param: string; card: RateCard; rates: number | Table }> =
285 []
286 for (const param of params) {
287 const rows = leaves.filter((row) => row.param === param)
288 if (rows.length !== combos) return null
289 let rates: number | Table
290 if (keys.length === 0) {
291 const [row] = rows
292 if (!row || rows.length !== 1) return null
293 rates = row.rate
294 } else {
295 const table: Table = {}
296 for (const row of rows) {
297 let node = table
298 for (const [index, key] of row.keys.entries()) {
299 if (index === row.keys.length - 1) {
300 if (Object.hasOwn(node, key.value)) return null
301 node[key.value] = row.rate
302 } else {
303 const next: number | Table =
304 (Object.hasOwn(node, key.value) && node[key.value]) || {}
305 if (typeof next === 'number') return null
306 node[key.value] = next
307 node = next
308 }
309 }
310 }
311 rates = table
312 }
313 const card = compileUnitCard(
314 { quantity: { param, bound: 'usage' }, keys, rates },
315 source,
316 )
317 if (!card) return null
318 terms.push({ param, card, rates })
319 }
320 const [only] = terms
321 if (terms.length === 1 && only) return only.card
322
323 // A keyed metric gets a rate table named for it, a flat one is inlined;
324 // the price adds the per-metric terms.
325 const lookupKeys = keys.map((key) => ({ var: key.param }))
326 return {
327 inputs: Object.fromEntries(
328 terms.flatMap(({ card }) => Object.entries(card.inputs)),
329 ),
330 tables: Object.fromEntries(
331 terms.flatMap(({ param, rates }) =>
332 typeof rates === 'number' ? [] : [[param, rates]],
333 ),
334 ),
335 price: {
336 '+': terms.map(({ param, rates }): Expr => ({
337 '*': [
338 { var: param },
339 typeof rates === 'number'
340 ? rates
341 : { lookup: { table: param, keys: lookupKeys } },
342 ],
343 })),
344 },
345 examples: [],
346 source,
347 }
348}
349
350/** Opens the JSON every official model page embeds. */
351export const BILLING_MARKER = '{"billingConfig":'
352
353/** `billingConfig` JSON embedded in a public model page, if the page has one. */
354export function replicateBillingFromHtml(
355 html: string,
356): ReplicateBilling | null {
357 const start = html.indexOf(BILLING_MARKER)
358 if (start < 0) return null
359 const parsed = parseJsonObject(html, start)
360 if (!parsed || typeof parsed !== 'object') return null
361 const billing = (parsed as { billingConfig?: unknown }).billingConfig
362 if (!billing || typeof billing !== 'object') return null
363 return billing
364}
365
366function parseJsonObject(text: string, start: number): unknown {
367 let depth = 0
368 let inString = false
369 let escaped = false
370 for (let i = start; i < text.length; i++) {
371 const char = text[i]
372 if (inString) {
373 if (escaped) escaped = false
374 else if (char === '\\') escaped = true
375 else if (char === '"') inString = false
376 continue
377 }
378 if (char === '"') inString = true
379 else if (char === '{') depth += 1
380 else if (char === '}') {
381 depth -= 1
382 if (depth === 0) {
383 try {
384 return JSON.parse(text.slice(start, i + 1)) as unknown
385 } catch {
386 return null
387 }
388 }
389 }
390 }
391 return null
392}
393
394type PricedFacts = Pick<ModelInfo, 'pricing' | 'factSources'>
395
396/** Card for one official model page. No billing section → no card. */
397export function replicatePagePricing(
398 html: string,
399 source: RateCard['source'],
400): PricedFacts {
401 const pricing = compileReplicateBilling(
402 replicateBillingFromHtml(html),
403 source,
404 )
405 if (!pricing) return {}
406 return {
407 pricing,
408 factSources: tagDocsFacts({ pricing }, source.url, source.hash),
409 }
410}