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

compare-fal-extract-models.ts

352 lines11.4 KB

1/**
2 * Issue #550: score candidate FAL rate-card extract models on the same
3 * Pricing sections, through the production prompt, checks and repair turn
4 * (`extractRateCard` over `gatewayChat`, as production runs). Only the
5 * gateway hop is swapped: a stand-in binding sends the Anthropic adapter's
6 * request to Anthropic with the dev key (env or Doppler `dev`). The gateway
7 * passes provider rates through, so the cost column matches what Unified
8 * Billing would charge (before its 5% fee).
9 *
10 * pnpm run compare-fal -- [--leftovers 13] [--models a,b] [--cache file.json]
11 *
12 * Ground truth: the hand-checked FAL cards in packages/rate-card/src/fixtures.
13 * A fixture matches when the extracted card reproduces every one of the
14 * fixture's examples within 1%.
15 */
16import { readFile, writeFile } from 'node:fs/promises'
17​
18import { price } from '../packages/rate-card/src/evaluate.ts'
19import type { RateCard } from '../packages/rate-card/src/card.ts'
20import {
21 GPT_IMAGE_2_5_FLARE_EDIT,
22 GPT_IMAGE_2_5_FLARE_TEXT_TO_IMAGE,
23} from '../packages/rate-card/src/fixtures/gpt-image-2-5-flare-text-to-image.ts'
24import { GROK_IMAGINE_VIDEO_REFERENCE_TO_VIDEO } from '../packages/rate-card/src/fixtures/grok-imagine-video-reference-to-video.ts'
25import {
26 H3_MAX_IMAGE_TO_VIDEO,
27 H3_MAX_TEXT_TO_VIDEO,
28} from '../packages/rate-card/src/fixtures/h3-max-image-to-video.ts'
29import { H3_MAX_REFERENCE_TO_VIDEO } from '../packages/rate-card/src/fixtures/h3-max-reference-to-video.ts'
30import { KLING_V3_PRO_IMAGE_TO_VIDEO } from '../packages/rate-card/src/fixtures/kling-v3-pro-image-to-video.ts'
31import { NANO_BANANA_2 } from '../packages/rate-card/src/fixtures/nano-banana-2.ts'
32import { SEEDANCE_FAL_RATE_CARDS } from '../packages/rate-card/src/fixtures/seedance-fal.ts'
33import {
34 extractRateCard,
35 gatewayChat,
36 isStubPricingSection,
37 pricingSection,
38 pricingSectionHash,
39} from '../src/server/ingest/extract-fal-pricing.ts'
40import type { ExtractChat } from '../src/server/ingest/extract-fal-pricing.ts'
41import { priceFalNamedSection } from '../src/server/ingest/fal-unit-rate.ts'
42import { falModels, requestPropertiesOf, secret } from './fal-models.ts'
43​
44interface Candidate {
45 model: Parameters<typeof gatewayChat>[2] & string
46 /** USD per million tokens (Anthropic list price, which the gateway passes through). */
47 input: number
48 output: number
50​
51const CANDIDATES: Array<Candidate> = [
52 { model: 'claude-sonnet-5-5', input: 2, output: 10 },
53 { model: 'claude-haiku-5-5', input: 0.1, output: 0.5 },
55​
56interface Usage {
57 input: number
58 output: number
60​
61/** Token totals of a streamed Messages reply: `message_start` in, `message_delta` out. */
62async function readUsage(response: Response): Promise<Usage> {
63 const usage: Usage = { input: 0, output: 0 }
64 for (const line of (await response.text()).split('\n')) {
65 if (!line.startsWith('data: {')) continue
66 const event = JSON.parse(line.slice(6)) as {
67 message?: { usage?: { input_tokens?: number } }
68 usage?: { output_tokens?: number }
69 }
70 usage.input += event.message?.usage?.input_tokens ?? 0
71 usage.output = event.usage?.output_tokens ?? usage.output
72 }
73 return usage
75​
76/**
77 * Stands in for `env.AI`: the binding fetch's `run('anthropic/<model>',
78 * body)` goes to Anthropic's Messages API with the dev key instead of the
79 * gateway, and the raw response comes back as the gateway's would.
80 */
81function standInBinding(
82 onUsage: (usage: Usage) => void,
83 pending: Array<Promise<void>>,
84): Ai {
85 const key = secret('ANTHROPIC_API_KEY')
86 const run = async (model: string, body: Record<string, unknown>) => {
87 const response = await fetch('https://api.anthropic.com/v1/messages', {
88 method: 'POST',
89 headers: {
90 'Content-Type': 'application/json',
91 'x-api-key': key,
92 'anthropic-version': '2023-06-01',
93 },
94 body: JSON.stringify({
95 ...body,
96 // Back from the gateway catalog id to Anthropic's.
97 model: model.replace(/^anthropic\//, '').replaceAll('.', '-'),
98 }),
99 })
100 if (response.ok) pending.push(readUsage(response.clone()).then(onUsage))
101 return response
102 }
103 return { run } as unknown as Ai
105​
106interface Section {
107 rawId: string
108 text: string
109 hash: string
110 requestProperties: Set<string>
111 truth?: RateCard
113​
114const FIXTURES: Array<RateCard> = [
115 GPT_IMAGE_2_5_FLARE_TEXT_TO_IMAGE,
116 GPT_IMAGE_2_5_FLARE_EDIT,
117 GROK_IMAGINE_VIDEO_REFERENCE_TO_VIDEO,
118 H3_MAX_IMAGE_TO_VIDEO,
119 H3_MAX_TEXT_TO_VIDEO,
120 H3_MAX_REFERENCE_TO_VIDEO,
121 KLING_V3_PRO_IMAGE_TO_VIDEO,
122 NANO_BANANA_2,
123 ...Object.values(SEEDANCE_FAL_RATE_CARDS),
125​
126function rawIdOf(llmsUrl: string): string {
127 return llmsUrl
128 .replace('https://fal.ai/models/', '')
129 .replace(/\/llms\.txt$/, '')
131​
132async function loadSection(rawId: string): Promise<Section | null> {
133 const response = await fetch(`https://fal.ai/models/${rawId}/llms.txt`)
134 if (!response.ok) return null
135 const text = pricingSection(await response.text())
136 if (text.length === 0) return null
137 return {
138 rawId,
139 text,
140 hash: await pricingSectionHash(text),
141 requestProperties: await requestPropertiesOf(rawId),
142 }
144​
145/** Priced sections the unit-rate parser cannot compile — what reaches the model. */
146async function sampleLeftovers(
147 count: number,
148 skip: ReadonlySet<string>,
149): Promise<Array<Section>> {
150 const rawIds = (await falModels(new URLSearchParams({ status: 'active' })))
151 .map((m) => m.endpoint_id)
152 .filter((id) => !skip.has(id))
153 .sort()
154 // Deterministic spread over the roster, not the first N alphabetically.
155 const step = 7
156 const picked: Array<Section> = []
157 const hashes = new Set<string>()
158 for (let offset = 0; offset < step && picked.length < count; offset++) {
159 for (
160 let i = offset;
161 i < rawIds.length && picked.length < count;
162 i += step
163 ) {
164 const section = await loadSection(rawIds[i] as string)
165 if (!section || isStubPricingSection(section.text)) continue
166 if (hashes.has(section.hash)) continue
167 const compiled = priceFalNamedSection(
168 section.text,
169 section.requestProperties,
170 { url: 'x', hash: section.hash, extractedAt: new Date().toISOString() },
171 )
172 if (compiled) continue
173 hashes.add(section.hash)
174 picked.push(section)
175 }
176 }
177 return picked
179​
180/** null = the card reproduces every hand-card example within 1%; else the first miss. */
181function truthMiss(card: RateCard, truth: RateCard): string | null {
182 for (const example of truth.examples) {
183 try {
184 // Same flat-bag read as verifyExamples.
185 const amount = price(card, example.params, example.params)
186 if (Math.abs(amount - example.usd) > example.usd * 0.01)
187 return `${JSON.stringify(example.params)} → ${amount}, hand card ${example.usd}`
188 } catch (error) {
189 return `${JSON.stringify(example.params)} → ${error instanceof Error ? error.message : String(error)}`
190 }
191 }
192 return null
194​
195interface Row {
196 model: string
197 sections: number
198 passed: number
199 repaired: number
200 truthTotal: number
201 truthMatched: number
202 usd: number
203 ms: Array<number>
204 failures: Array<string>
206​
207async function score(candidate: Candidate, sections: Array<Section>) {
208 const row: Row = {
209 model: candidate.model,
210 sections: sections.length,
211 passed: 0,
212 repaired: 0,
213 truthTotal: 0,
214 truthMatched: 0,
215 usd: 0,
216 ms: [],
217 failures: [],
218 }
219 const pending: Array<Promise<void>> = []
220 for (const section of sections) {
221 let turns = 0
222 const binding = standInBinding((usage) => {
223 row.usd +=
224 (usage.input * candidate.input + usage.output * candidate.output) / 1e6
225 }, pending)
226 const gateway = gatewayChat(binding, 'stand-in', candidate.model)
227 const chat: ExtractChat = (turnsSoFar) => {
228 turns++
229 return gateway(turnsSoFar)
230 }
231 const started = performance.now()
232 const result = await extractRateCard({
233 pricingText: section.text,
234 requestProperties: section.requestProperties,
235 sourceUrl: `https://fal.ai/models/${section.rawId}/llms.txt`,
236 sourceHash: section.hash,
237 now: Math.floor(Date.now() / 1000),
238 chat,
239 })
240 row.ms.push(performance.now() - started)
241 const ok = result !== 'unverified' && !('error' in result)
242 if (ok) row.passed++
243 else
244 row.failures.push(
245 `${section.rawId}: ${result === 'unverified' ? 'unverified' : result.error.slice(0, 160)}`,
246 )
247 if (ok && turns > 1) row.repaired++
248 if (section.truth) {
249 row.truthTotal++
250 const miss = ok ? truthMiss(result, section.truth) : 'no card'
251 if (miss === null) row.truthMatched++
252 else if (ok)
253 row.failures.push(
254 `${section.rawId}: ≠ hand card: ${miss.slice(0, 200)}`,
255 )
256 }
257 process.stderr.write('.')
258 }
259 await Promise.all(pending)
260 process.stderr.write(` ${candidate.model}\n`)
261 return row
263​
264async function readCache(path: string): Promise<Array<Section> | null> {
265 const text = await readFile(path, 'utf8').catch(() => null)
266 if (text === null) return null
267 const rows = JSON.parse(text) as Array<
268 Omit<Section, 'requestProperties'> & { requestProperties: Array<string> }
269 >
270 return rows.map((row) => ({
271 ...row,
272 requestProperties: new Set(row.requestProperties),
273 }))
275​
276async function writeCache(
277 path: string,
278 sections: Array<Section>,
279): Promise<void> {
280 await writeFile(
281 path,
282 JSON.stringify(
283 sections.map((section) => ({
284 ...section,
285 requestProperties: [...section.requestProperties],
286 })),
287 null,
288 2,
289 ),
290 )
292​
293function median(values: Array<number>): number {
294 const sorted = [...values].sort((a, b) => a - b)
295 return sorted[Math.floor(sorted.length / 2)] ?? 0
297​
298async function main(): Promise<void> {
299 const argv = process.argv.slice(2)
300 const flag = (name: string): string | undefined => {
301 const at = argv.indexOf(name)
302 return at >= 0 ? argv[at + 1] : undefined
303 }
304 const leftoverCount = Number(flag('--leftovers') ?? 13)
305 const modelIds = (
306 flag('--models') ?? CANDIDATES.map((c) => c.model).join(',')
307 ).split(',')
308​
309 const cachePath = flag('--cache')
310 const cached = cachePath ? await readCache(cachePath) : null
311 const sections: Array<Section> = cached ?? []
312 if (!cached) {
313 for (const truth of FIXTURES) {
314 const section = await loadSection(rawIdOf(truth.source.url))
315 if (section) sections.push({ ...section, truth })
316 }
317 sections.push(
318 ...(await sampleLeftovers(
319 leftoverCount,
320 new Set(sections.map((s) => s.rawId)),
321 )),
322 )
323 if (cachePath) await writeCache(cachePath, sections)
324 }
325 console.error(
326 `${sections.length} sections, ${sections.filter((s) => s.truth).length} with hand cards`,
327 )
328​
329 const rows: Array<Row> = []
330 for (const id of modelIds) {
331 const candidate = CANDIDATES.find((c) => c.model === id)
332 if (!candidate) throw new Error(`unknown model ${id}`)
333 rows.push(await score(candidate, sections))
334 }
335​
336 console.log(
337 '| Model | Pass | Hand-card match | Repair turns | Cost / page | Median latency |',
338 )
339 console.log('|---|---|---|---|---|---|')
340 for (const row of rows) {
341 console.log(
342 `| ${row.model} | ${row.passed}/${row.sections} | ${row.truthMatched}/${row.truthTotal} | ${row.repaired}/${row.passed} | $${(row.usd / row.sections).toFixed(4)} | ${(median(row.ms) / 1000).toFixed(1)}s |`,
343 )
344 }
345 for (const row of rows) {
346 if (row.failures.length === 0) continue
347 console.log(`\n${row.model}:`)
348 for (const failure of row.failures) console.log(`- ${failure}`)
349 }
351​
352await main()