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. A tier that depends on a
5 * request field we cannot name, or a price unit this does not know, is
6 * not a card. Token prices that step up above a prompt length are the one
7 * range tier read.
8 */
9import { compileTokenCard, compileUnitCard } from '@modelschemas/rate-card'
10import type { RateCard, TokenRateTier, UnitKey } from '@modelschemas/rate-card'
11
12import { tagDocsFacts } from './fact-sources.ts'
13import type { ModelInfo } from './types.ts'
14
15interface ReplicateCriterion {
16 title?: string
17 type?: string
18 subtype?: string
19 /** A string for `equals`, `[from, to]` for `range`. */
20 value?: unknown
21}
22
23interface ReplicatePrice {
24 metric?: string
25 price?: string
26 title?: string
27 type?: string
28}
29
30interface ReplicateTier {
31 criteria?: Array<ReplicateCriterion>
32 prices?: Array<ReplicatePrice>
33}
34
35export interface ReplicateBilling {
36 current_tiers?: Array<ReplicateTier>
37}
38
39const METRIC_PARAM: Record<string, string> = {
40 image_output_count: 'output_images',
41 token_input_count: 'input_tokens',
42 token_output_count: 'output_tokens',
43 video_output_duration_seconds: 'video_seconds',
44 audio_output_duration_seconds: 'audio_seconds',
45}
46
47/** `$3` / `$0.03` → dollars. Anything else is not a price we can store. */
48export function replicateDollars(price: string | undefined): number | null {
49 const match = price?.trim().match(/^\$(\d+(?:\.\d+)?)$/)
50 if (!match?.[1]) return null
51 const dollars = Number(match[1])
52 return Number.isFinite(dollars) && dollars > 0 ? dollars : null
53}
54
55/** `per thousand …` → how many billed units one quoted price covers. */
56export function replicatePriceScale(title: string | undefined): number | null {
57 const text = title?.trim().toLowerCase() ?? ''
58 if (text.startsWith('per thousand')) return 1000
59 if (text.startsWith('per million')) return 1_000_000
60 if (text.startsWith('per second')) return 1
61 if (text.startsWith('per output image') || text.startsWith('per image')) {
62 return 1
63 }
64 if (text.startsWith('per minute')) return 60
65 if (text.startsWith('per hour')) return 3600
66 return null
67}
68
69function criterionParam(title: string | undefined): string | null {
70 const slug = title
71 ?.trim()
72 .toLowerCase()
73 .replace(/[^a-z0-9]+/g, '_')
74 .replace(/^_|_$/g, '')
75 if (!slug || slug.length > 40) return null
76 return slug
77}
78
79interface Leaf {
80 param: string
81 /** USD per one unit of `param`. */
82 rate: number
83 key?: { param: string; value: string }
84}
85
86function leaf(price: ReplicatePrice, key?: Leaf['key']): Leaf | null {
87 if (price.type !== undefined && price.type !== 'per-unit') return null
88 const param = price.metric ? METRIC_PARAM[price.metric] : undefined
89 const dollars = replicateDollars(price.price)
90 const scale = replicatePriceScale(price.title)
91 if (!param || dollars === null || scale === null) return null
92 // Duration titles ("per minute") quote several seconds; token and image
93 // titles ("per thousand") quote that many billed units. Both are USD / scale.
94 // toPrecision: `$0.015` per thousand is 0.000015, not 0.0000149999….
95 const rate = Number((dollars / scale).toPrecision(12))
96 if (!(rate > 0)) return null
97 return { param, rate, ...(key ? { key } : {}) }
98}
99
100function tokenRates(
101 prices: Array<ReplicatePrice>,
102): Record<string, number> | null {
103 const rates: Record<string, number> = {}
104 for (const price of prices) {
105 const row = leaf(price)
106 if (!row || !row.param.endsWith('_tokens') || row.param in rates) {
107 return null
108 }
109 rates[row.param] = row.rate
110 }
111 return 'input_tokens' in rates && 'output_tokens' in rates ? rates : null
112}
113
114/**
115 * Token prices by prompt length: one `≤ N` tier (the base) and one `> N`
116 * tier that re-quotes above it. Any other range shape is not a card.
117 */
118function compilePromptTiers(
119 tiers: Array<ReplicateTier>,
120 source: RateCard['source'],
121): RateCard | null {
122 let base: { rates: Record<string, number>; upTo: number } | null = null
123 let above: TokenRateTier | null = null
124 for (const tier of tiers) {
125 const [criterion, ...more] = tier.criteria ?? []
126 const rates = tokenRates(tier.prices ?? [])
127 const range = criterion?.value
128 if (
129 !criterion ||
130 more.length > 0 ||
131 !rates ||
132 criterion.type !== 'range' ||
133 criterion.title !== 'input token' ||
134 !Array.isArray(range) ||
135 range.length !== 2
136 ) {
137 return null
138 }
139 const bounds: Array<unknown> = range
140 const [from, to] = bounds
141 if (
142 from === null &&
143 typeof to === 'number' &&
144 criterion.subtype === 'open-closed' &&
145 !base
146 ) {
147 base = { rates, upTo: to }
148 } else if (
149 typeof from === 'number' &&
150 to === null &&
151 criterion.subtype === 'open' &&
152 !above
153 ) {
154 above = { minPromptTokens: from, rates }
155 } else {
156 return null
157 }
158 }
159 if (!base || !above || base.upTo !== above.minPromptTokens) return null
160 return compileTokenCard(base.rates, [above], source)
161}
162
163/**
164 * Dollar prediction price → rate card.
165 * `null` when the config has no usable published price.
166 */
167export function compileReplicateBilling(
168 billing: ReplicateBilling | null | undefined,
169 source: RateCard['source'],
170): RateCard | null {
171 const tiers = billing?.current_tiers
172 if (!tiers || tiers.length === 0) return null
173 if (tiers.some((tier) => tier.criteria?.some((c) => c.type === 'range'))) {
174 return compilePromptTiers(tiers, source)
175 }
176
177 const leaves: Array<Leaf> = []
178 for (const tier of tiers) {
179 const criteria = tier.criteria ?? []
180 const prices = tier.prices ?? []
181 if (prices.length === 0) return null
182 let key: Leaf['key']
183 if (criteria.length > 0) {
184 if (criteria.length !== 1 || prices.length !== 1) return null
185 const criterion = criteria[0]
186 if (!criterion || criterion.type !== 'equals') return null
187 const param = criterionParam(criterion.title)
188 if (
189 !param ||
190 typeof criterion.value !== 'string' ||
191 criterion.value === ''
192 ) {
193 return null
194 }
195 key = { param, value: criterion.value }
196 }
197 for (const price of prices) {
198 const row = leaf(price, key)
199 if (!row) return null
200 leaves.push(row)
201 }
202 }
203
204 const params = new Set(leaves.map((row) => row.param))
205 const keyParams = new Set(
206 leaves.flatMap((row) => (row.key ? [row.key.param] : [])),
207 )
208 if (keyParams.size > 1) return null
209 const tokenParams = [...params].filter((param) => param.endsWith('_tokens'))
210 if (tokenParams.length > 0) {
211 if (tokenParams.length !== params.size || keyParams.size > 0) return null
212 if (new Set(leaves.map((row) => row.param)).size !== leaves.length)
213 return null
214 return compileTokenCard(
215 Object.fromEntries(leaves.map((row) => [row.param, row.rate])),
216 [],
217 source,
218 )
219 }
220 if (params.size !== 1) return null
221 const param = [...params][0]
222 if (!param) return null
223 const keyParam = [...keyParams][0]
224 if (!keyParam) {
225 if (leaves.length !== 1) return null
226 return compileUnitCard(
227 {
228 quantity: { param, bound: 'usage' },
229 rates: leaves[0]?.rate ?? 0,
230 },
231 source,
232 )
233 }
234 const values = leaves.map((row) => row.key?.value ?? '')
235 if (new Set(values).size !== values.length) return null
236 const key: UnitKey = { param: keyParam, values, bound: 'usage' }
237 const rates = Object.fromEntries(
238 leaves.map((row) => [row.key?.value ?? '', row.rate]),
239 )
240 return compileUnitCard(
241 {
242 quantity: { param, bound: 'usage' },
243 keys: [key],
244 rates,
245 },
246 source,
247 )
248}
249
250/** Opens the JSON every official model page embeds. */
251export const BILLING_MARKER = '{"billingConfig":'
252
253/** `billingConfig` JSON embedded in a public model page, if the page has one. */
254export function replicateBillingFromHtml(
255 html: string,
256): ReplicateBilling | null {
257 const start = html.indexOf(BILLING_MARKER)
258 if (start < 0) return null
259 const parsed = parseJsonObject(html, start)
260 if (!parsed || typeof parsed !== 'object') return null
261 const billing = (parsed as { billingConfig?: unknown }).billingConfig
262 if (!billing || typeof billing !== 'object') return null
263 return billing
264}
265
266function parseJsonObject(text: string, start: number): unknown | null {
267 let depth = 0
268 let inString = false
269 let escaped = false
270 for (let i = start; i < text.length; i++) {
271 const char = text[i]
272 if (inString) {
273 if (escaped) escaped = false
274 else if (char === '\\') escaped = true
275 else if (char === '"') inString = false
276 continue
277 }
278 if (char === '"') inString = true
279 else if (char === '{') depth += 1
280 else if (char === '}') {
281 depth -= 1
282 if (depth === 0) {
283 try {
284 return JSON.parse(text.slice(start, i + 1)) as unknown
285 } catch {
286 return null
287 }
288 }
289 }
290 }
291 return null
292}
293
294type PricedFacts = Pick<ModelInfo, 'pricing' | 'factSources'>
295
296/** Card for one official model page. No billing section → no card. */
297export function replicatePagePricing(
298 html: string,
299 source: RateCard['source'],
300): PricedFacts {
301 const pricing = compileReplicateBilling(
302 replicateBillingFromHtml(html),
303 source,
304 )
305 if (!pricing) return {}
306 return {
307 pricing,
308 factSources: tagDocsFacts({ pricing }, source.url, source.hash),
309 }
310}