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

worldlabs-pricing.ts

184 lines6.1 KB

1/**
2 * World Labs API prices from https://docs.worldlabs.ai/api/pricing
3 * (issue #617). Credits convert at the page's stated rate ($1.00 per
4 * 1,250 credits). Draft and standard models have one total per published
5 * input type. Marble 1.1 Plus totals are ranges (variable world size),
6 * so that id stays unpriced. A page that prices none of the fixed models
7 * throws.
8 */
9import { compileUnitCard } from '@modelschemas/rate-card'
10import type { UnitCardSpec } from '@modelschemas/rate-card'
11​
12import { tagDocsFacts } from './fact-sources.ts'
13import { assertParsed, markdownTableRows } from './model-facts.ts'
14import type { cachedDocs } from './model-facts.ts'
15import { fetchText, sha256Text } from './types.ts'
16import type { ModelInfo } from './types.ts'
17​
18export const WORLDLABS_PRICING_URL = 'https://docs.worldlabs.ai/api/pricing.md'
19​
20/**
21 * Pricing-page input type (`Image (pano)`, `Text`, …). The generate body's
22 * `world_prompt` is an object, and pano vs non-pano is nested `is_pano`,
23 * so the evaluator cannot read this off a real request. Callers pass
24 * `world_prompt_kind` on the estimate body. Omitted, `POST /v1/estimate`
25 * returns `byInput`. `CARD_LEVEL_LEVERS` allows the name so the poller
26 * does not refuse the card once the generate schema is bound.
27 */
28export const WORLDLABS_PROMPT_INPUT = 'world_prompt_kind'
29​
30const INPUTS = [
31 'Image (pano)',
32 'Text',
33 'Image (non-pano)',
34 'Multi-image',
35 'Video',
36] as const
37​
38const FIXED_MODELS = ['marble-1.0-draft', 'marble-1.0', 'marble-1.1'] as const
39​
40const CREDIT_RATE = /\\?\$1\.00 USD per ([\d,]+) credits/
41​
42type Total = number | 'range'
43​
44function uncomma(cell: string): string {
45 return cell.replace(/,/g, '').trim()
47​
48function parseTotal(cell: string | undefined): Total | null {
49 if (cell === undefined) return null
50 const text = uncomma(cell)
51 if (/^\d+$/.test(text)) return Number(text)
52 if (/^\d+-\d+$/.test(text)) return 'range'
53 return null
55​
56function section(
57 page: string,
58 title: string,
59): { ids: Array<string>; body: string } | null {
60 const marker = `#### ${title}`
61 const start = page.indexOf(marker)
62 if (start < 0) return null
63 const after = page.slice(start)
64 const next = after.indexOf('\n#### ', marker.length)
65 const block = next < 0 ? after : after.slice(0, next)
66 const heading = block.slice(0, block.indexOf('\n'))
67 const ids = [...heading.matchAll(/`([^`]+)`/g)].map((match) => match[1] ?? '')
68 return { ids: ids.filter((id) => id.length > 0), body: block }
70​
71/** Input label → credits. Missing or unreadable cells throw. */
72function inputTotals(body: string, heading: string): Map<string, Total> {
73 const found = new Map<string, Total>()
74 for (const row of markdownTableRows(body)) {
75 const label = row[0]
76 if (!label || !(INPUTS as ReadonlyArray<string>).includes(label)) continue
77 const total = parseTotal(row[row.length - 1])
78 if (total === null) {
79 throw new Error(`worldlabs pricing: ${heading} ${label} has no total`)
80 }
81 found.set(label, total)
82 }
83 for (const label of INPUTS) {
84 if (!found.has(label)) {
85 throw new Error(`worldlabs pricing: ${heading} omits ${label}`)
86 }
87 }
88 return found
90​
91function creditsPerDollar(page: string): number {
92 const match = page.match(CREDIT_RATE)?.[1]?.replace(/,/g, '')
93 const credits = match === undefined ? Number.NaN : Number(match)
94 if (!Number.isFinite(credits) || credits <= 0) {
95 throw new Error('worldlabs pricing: no $1.00 credit rate')
96 }
97 return credits
99​
100function sheet(
101 totals: Map<string, Total>,
102 perDollar: number,
103): UnitCardSpec | 'range' {
104 const values = INPUTS.map((label) => totals.get(label))
105 if (values.every((value) => value === 'range')) return 'range'
106 if (values.some((value) => value === 'range' || typeof value !== 'number')) {
107 throw new Error('worldlabs pricing: a model mixes fixed totals and ranges')
108 }
109 const rates: Record<string, number> = {}
110 for (const label of INPUTS) {
111 const credits = totals.get(label)
112 if (typeof credits !== 'number') {
113 throw new Error(`worldlabs pricing: ${label} is not a credit total`)
114 }
115 rates[label] = credits / perDollar
116 }
117 return {
118 keys: [{ param: WORLDLABS_PROMPT_INPUT, values: [...INPUTS] }],
119 rates,
120 }
122​
123/**
124 * Catalog id → unit sheet. Marble 1.1 Plus is absent while its totals are
125 * ranges. Throws when the credit rate or a fixed model's table is missing.
126 */
127export function parseWorldlabsPricing(page: string): Map<string, UnitCardSpec> {
128 const perDollar = creditsPerDollar(page)
129 const sections = [
130 section(page, 'Draft model totals'),
131 section(page, 'Standard model totals'),
132 section(page, 'Marble 1.1 Plus totals'),
133 ]
134 const out = new Map<string, UnitCardSpec>()
135 for (const block of sections) {
136 if (!block || block.ids.length === 0) {
137 throw new Error('worldlabs pricing: a model totals table is missing')
138 }
139 const totals = inputTotals(block.body, block.ids.join(', '))
140 const spec = sheet(totals, perDollar)
141 for (const id of block.ids) {
142 if (spec === 'range') continue
143 if (out.has(id))
144 throw new Error(`worldlabs pricing: ${id} is priced twice`)
145 out.set(id, spec)
146 }
147 }
148 for (const id of FIXED_MODELS) {
149 if (!out.has(id)) throw new Error(`worldlabs pricing: ${id} has no card`)
150 }
151 return out
153​
154type PricedFacts = Pick<ModelInfo, 'pricing' | 'factSources'>
155​
156export async function worldlabsModelPricing(
157 kv: KVNamespace | undefined,
158 cached: typeof cachedDocs,
159): Promise<(rawId: string) => PricedFacts> {
160 const doc = await cached(kv, WORLDLABS_PRICING_URL, async () => {
161 const source = await fetchText(WORLDLABS_PRICING_URL)
162 const parsed = parseWorldlabsPricing(source)
163 assertParsed(parsed, 'worldlabs pricing page')
164 return {
165 cards: Object.fromEntries(parsed),
166 hash: await sha256Text(source),
167 extractedAt: new Date().toISOString(),
168 }
169 })
170 return (rawId) => {
171 const spec = doc.cards[rawId]
172 if (!spec) return {}
173 const pricing = compileUnitCard(spec, {
174 url: WORLDLABS_PRICING_URL,
175 hash: doc.hash,
176 extractedAt: doc.extractedAt,
177 })
178 if (!pricing) return {}
179 return {
180 pricing,
181 factSources: tagDocsFacts({ pricing }, WORLDLABS_PRICING_URL, doc.hash),
182 }
183 }