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