Open History to see the last commit
1/**
2 * Chat Pricing sections whose billed price is tokens, compiled without an
3 * LLM. Two shapes FAL actually publishes:
4 *
5 * - One `$X per N units` price, with input and output each costing a stated
6 * number of units, and a higher number past one token threshold. The
7 * threshold is the page's `128k` (1000, not 1024). "Over" is `>`, so the
8 * exact threshold stays on the under rate — the page never prices "at".
9 * Input and output cross it independently. Output length is the page's
10 * "reasoning + output", read as `output_tokens`.
11 * - One `$X per N tokens` line and nothing else. The page does not split
12 * input from output, so both levers are that rate. A second amount, or
13 * the word input/output between the count and "tokens", is not this shape.
14 *
15 * Anything else returns null. The unit-rate parser still owns per-image,
16 * per-second, and the other single-unit lines.
17 */
18import {
19 rateCardSchema,
20 verifyExamples,
21 compileTokenCard,
22} from '@modelschemas/rate-card'
23import type { Expr, RateCard } from '@modelschemas/rate-card'
24
25import { tokenCount } from '#/server/providers/model-facts.ts'
26
27const PRICING_LINK = /For more details, see \[fal\.ai pricing\]\([^)]*\)\.?/gi
28
29/** One `$X per N units` schedule. Groups: amount, count, threshold, inLow, inHigh, outLow, outHigh. */
30const UNIT_SCHEDULE =
31 /^your request will cost \$(\d+(?:\.\d+)?) per ([\d,]+) units\. for inputs under (\d+(?:\.\d+)?[km]) tokens, the units per input token is (\d+)\. for inputs of over \3 tokens, (\d+) units will be charged per token\. similarly, each output token costs (\d+) units, provided the total output length \(reasoning \+ output\) is under \3 tokens, and (\d+) units per token otherwise\.?$/i
32
33/** The whole section is one undifferentiated token price. */
34const FLAT_TOKENS =
35 /^(?:-\s*)?(?:price:\s*)?\$(\d+(?:\.\d+)?) per ([\d,]+) tokens$/i
36
37function pricingBody(section: string): string {
38 // `markdownSection` keeps the `## Pricing` line. The rate starts after it.
39 return section
40 .replace(/\*\*/g, '')
41 .replace(PRICING_LINK, '')
42 .replace(/\s+/g, ' ')
43 .trim()
44 .replace(/^##\s+pricing\s+/i, '')
45}
46
47function positive(text: string): number | null {
48 const value = Number(text.replace(/,/g, ''))
49 return Number.isFinite(value) && value > 0 ? value : null
50}
51
52function positiveInt(text: string): number | null {
53 const value = positive(text)
54 return value !== null && Number.isInteger(value) ? value : null
55}
56
57function quoteOf(section: string): string {
58 const paragraphs = section
59 .split(/\n\s*\n/)
60 .map((part) => part.trim())
61 .filter((part) => part.length > 0 && !/^##\s+pricing$/i.test(part))
62 return paragraphs[0] ?? section.trim()
63}
64
65function checked(card: RateCard): RateCard | null {
66 const parsed = rateCardSchema.safeParse(card)
67 if (!parsed.success) return null
68 if (verifyExamples(parsed.data).some((result) => !result.ok)) return null
69 return parsed.data
70}
71
72function rateOf(
73 lever: 'input_tokens' | 'output_tokens',
74 tier: 'base' | 'long',
75): Expr {
76 return { lookup: { table: 'rate', keys: [tier, lever] } }
77}
78
79/** `lever` billed at `long` only when that lever is over `threshold`. */
80function leverPrice(
81 lever: 'input_tokens' | 'output_tokens',
82 threshold: number,
83): Expr {
84 return {
85 '*': [
86 { var: lever },
87 {
88 if: [
89 { '>': [{ var: lever }, threshold] },
90 rateOf(lever, 'long'),
91 rateOf(lever, 'base'),
92 ],
93 },
94 ],
95 }
96}
97
98function scheduleCard(
99 section: string,
100 source: RateCard['source'],
101): RateCard | null {
102 const match = UNIT_SCHEDULE.exec(pricingBody(section).toLowerCase())
103 if (!match) return null
104 const amount = positive(match[1] ?? '')
105 const count = positiveInt(match[2] ?? '')
106 const threshold = tokenCount(match[3])
107 const units = [match[4], match[5], match[6], match[7]].map((text) =>
108 positiveInt(text ?? ''),
109 )
110 if (
111 amount === null ||
112 count === null ||
113 threshold === null ||
114 threshold <= 0 ||
115 units.some((unit) => unit === null)
116 ) {
117 return null
118 }
119 const [inLow, inHigh, outLow, outHigh] = units as [
120 number,
121 number,
122 number,
123 number,
124 ]
125 const perUnit = amount / count
126 const inputLow = perUnit * inLow
127 const inputHigh = perUnit * inHigh
128 const outputLow = perUnit * outLow
129 const outputHigh = perUnit * outHigh
130 const rates = [inputLow, inputHigh, outputLow, outputHigh]
131 if (rates.some((rate) => !Number.isFinite(rate) || rate < 0)) return null
132 const quote = quoteOf(section)
133 const at = (tokens: number, perToken: number) => tokens * perToken
134 return checked({
135 inputs: {
136 input_tokens: { param: 'input_tokens', bound: 'usage', kind: 'number' },
137 output_tokens: {
138 param: 'output_tokens',
139 bound: 'usage',
140 kind: 'number',
141 },
142 },
143 tables: {
144 rate: {
145 base: { input_tokens: inputLow, output_tokens: outputLow },
146 long: { input_tokens: inputHigh, output_tokens: outputHigh },
147 },
148 },
149 price: {
150 '+': [
151 leverPrice('input_tokens', threshold),
152 leverPrice('output_tokens', threshold),
153 ],
154 },
155 examples: [
156 {
157 params: { input_tokens: count, output_tokens: 0 },
158 usd: at(count, inputLow),
159 quote,
160 },
161 {
162 params: { input_tokens: 0, output_tokens: count },
163 usd: at(count, outputLow),
164 quote,
165 },
166 {
167 params: { input_tokens: threshold, output_tokens: 0 },
168 usd: at(threshold, inputLow),
169 quote,
170 },
171 {
172 params: { input_tokens: threshold + 1, output_tokens: 0 },
173 usd: at(threshold + 1, inputHigh),
174 quote,
175 },
176 {
177 params: { input_tokens: 0, output_tokens: threshold + 1 },
178 usd: at(threshold + 1, outputHigh),
179 quote,
180 },
181 ],
182 source,
183 })
184}
185
186function flatCard(
187 section: string,
188 source: RateCard['source'],
189): RateCard | null {
190 const match = FLAT_TOKENS.exec(pricingBody(section).toLowerCase())
191 if (!match) return null
192 const amount = positive(match[1] ?? '')
193 const count = positiveInt(match[2] ?? '')
194 if (amount === null || count === null) return null
195 const perToken = amount / count
196 if (!Number.isFinite(perToken) || perToken <= 0) return null
197 const card = compileTokenCard(
198 { input_tokens: perToken, output_tokens: perToken },
199 [],
200 source,
201 )
202 if (card === null) return null
203 const quote = quoteOf(section)
204 return checked({
205 ...card,
206 examples: [
207 {
208 params: { input_tokens: count, output_tokens: 0 },
209 usd: amount,
210 quote,
211 },
212 {
213 params: { input_tokens: 0, output_tokens: count },
214 usd: amount,
215 quote,
216 },
217 ],
218 })
219}
220
221/**
222 * Token card for a chat Pricing section, or null when this is not one of
223 * the two shapes above. Never a per-image or per-second card.
224 */
225export function compileFalTokenCard(
226 section: string,
227 source: RateCard['source'],
228): RateCard | null {
229 return scheduleCard(section, source) ?? flatCard(section, source)
230}