Open History to see the last commit
1/**
2 * Gemini prices from Google's own pricing page (issue #61). Google
3 * publishes no pricing API and no markdown mirror, so this parses the
4 * server-rendered page: one `models-section` per price, every model id in
5 * the heading group's `<code>` (siblings share the table), and the paid-tier
6 * column of the section's "Standard" table.
7 *
8 * Fail-closed: only the token rows (input / output / context caching) are
9 * levers, and any priced row, qualifier or unit the parser does not
10 * recognise (per-image, per-minute, per-song, date-conditional, Batch or
11 * Flex tables) refuses that model rather than quoting part of its bill.
12 * A page that yields no model at all throws, so stored cards survive a
13 * layout change until the parser is taught the new one.
14 */
15import { compileTokenCard, compileUnitCard } from '@modelschemas/rate-card'
16import type {
17 RateCard,
18 TokenRateTier,
19 UnitCardSpec,
20} from '@modelschemas/rate-card'
21
22import { tagDocsFacts } from './fact-sources.ts'
23import {
24 assertParsed,
25 cachedDocs,
26 parseDay,
27 tokenCount,
28} from './model-facts.ts'
29import { fetchText, sha256Text } from './types.ts'
30import type { ModelInfo } from './types.ts'
31
32export const GEMINI_PRICING_URL =
33 'https://ai.google.dev/gemini-api/docs/pricing'
34
35/**
36 * A row's lever per modality. `default` takes any price the row quotes for
37 * text (Gemini sums text, image and video into one prompt-token count, so
38 * one rate covering them all is the default lever); a modality named on its
39 * own is priced differently and gets its own lever.
40 */
41interface RowLevers {
42 default: string
43 audio?: string
44 image?: string
45 video?: string
46}
47
48/** Row label → its levers. */
49const ROW_LEVERS: Array<[RegExp, RowLevers]> = [
50 // A trailing parenthetical names the modalities the row covers ("Input
51 // price (text, image, video)"); a leading modality is a different row
52 // ("Audio input price"), which this must not match.
53 [
54 /^input price( \([^)]*\))?$/,
55 {
56 default: 'input_tokens',
57 audio: 'audio_tokens',
58 image: 'image_tokens',
59 video: 'video_tokens',
60 },
61 ],
62 [/^text input price$/, { default: 'input_tokens' }],
63 [/^image input price$/, { default: 'image_tokens' }],
64 [/^audio input price$/, { default: 'audio_tokens' }],
65 [/^video input price$/, { default: 'video_tokens' }],
66 [
67 /^output price( \([^)]*\))?$/,
68 {
69 default: 'output_tokens',
70 audio: 'audio_output_tokens',
71 image: 'image_output_tokens',
72 video: 'video_output_tokens',
73 },
74 ],
75 [
76 /^context caching price$/,
77 {
78 default: 'cache_read_tokens',
79 audio: 'audio_cache_tokens',
80 image: 'image_cache_tokens',
81 },
82 ],
83]
84
85/** Modality words a qualifier may name, singular or plural. */
86const MODALITIES: Record<string, keyof RowLevers> = {
87 text: 'default',
88 texts: 'default',
89 thinking: 'default',
90 image: 'image',
91 images: 'image',
92 video: 'video',
93 videos: 'video',
94 audio: 'audio',
95}
96
97/** Rows that are not a per-token cost of one request. */
98const IGNORED_ROWS =
99 /^(grounding with |used to improve|context caching \(storage\)|tuning price|live api)/
100
101const ENTITIES: Record<string, string> = {
102 amp: '&',
103 lt: '<',
104 gt: '>',
105 quot: '"',
106 '#39': "'",
107 nbsp: ' ',
108}
109
110function plain(html: string): string {
111 return (
112 html
113 // Footnote markers are not part of a price.
114 .replace(/<sup>[\s\S]*?<\/sup>/g, '')
115 // A real tag only; a bare `<=` in a qualifier must survive.
116 .replace(/<\/?[a-zA-Z][^>]*>/g, '')
117 .replace(/&([a-z]+|#\d+);/gi, (match, name: string) => {
118 return ENTITIES[name.toLowerCase()] ?? match
119 })
120 .replace(/\s+/g, ' ')
121 .trim()
122 )
123}
124
125const DAY_MS = 86_400_000
126
127type Fragment = {
128 levers: Array<string>
129 rate: number
130 tier: number | null
131 /** Instant this rate stops applying, for a dated price change. */
132 expiresAt: number | null
133}
134
135/**
136 * One `$x (qualifier)` fragment of a paid-tier cell. `null` refuses the
137 * model; `[]` is a fragment that prices nothing here (storage, "not
138 * available").
139 */
140function fragment(
141 raw: string,
142 levers: RowLevers,
143 now: number,
144 first: boolean,
145): Array<Fragment> | null {
146 const cell = plain(raw)
147 // "$6.50 ($0.00016 per second)" / "$3.00 or $0.005/min (audio)": the
148 // column is per 1M tokens, so a second amount in another unit restates
149 // the token rate rather than adding to it.
150 .replace(/\s*\(\s*\$[^)]*\)/g, '')
151 .replace(/\s+or \$[\d.,]+\s*\/\s*\w+/gi, '')
152 .trim()
153 if (cell === '' || /^(not available|free of charge)$/i.test(cell)) return []
154 // Cache storage is quoted per token-hour, not per request.
155 if (/per hour|storage price/i.test(cell)) return []
156 // A price in a unit other than the column's tokens: after the first
157 // fragment it restates the token rate ("Equivalent to $0.134 per 1K/2K
158 // image", "and $0.24 per 4K image"); as the first, it *is* the price and
159 // this card has no lever for it.
160 if (/equivalent|\bper \d|\bper [a-z]+\b/i.test(cell)) {
161 return first ? null : []
162 }
163 const match = cell.match(/^\$([\d,]+(?:\.\d+)?)\s*(.*)$/)
164 if (!match?.[1]) return null
165 const rate = Number(match[1].replace(/,/g, '')) / 1e6
166 let qualifier = (match[2] ?? '')
167 .trim()
168 .toLowerCase()
169 // A qualifier follows the price as a parenthetical or after a comma.
170 .replace(/^,\s*/, '')
171 .replace(/\.$/, '')
172 .trim()
173
174 // A dated price change ("$0.75 through December 31, 2026" / "$1.50
175 // starting January 1, 2027"): the rate in effect now wins and stamps the
176 // card's `expiresAt`, so it is re-extracted once the change lands.
177 let expiresAt: number | null = null
178 const dated = qualifier.match(
179 /^(.*?)\s*(through|starting) ([a-z]+ \d{1,2}, \d{4})$/,
180 )
181 if (dated?.[3]) {
182 const day = parseDay(dated[3])
183 if (day === null) return null
184 const ends = dated[2] === 'through' ? day + DAY_MS : day
185 if (dated[2] === 'through' ? now >= ends : now < ends) return []
186 if (dated[2] === 'through') expiresAt = ends
187 qualifier = (dated[1] ?? '').trim()
188 }
189 qualifier = qualifier.replace(/^\((.*)\)$/, '$1').trim()
190
191 if (qualifier === '') {
192 return [{ levers: [levers.default], rate, tier: null, expiresAt }]
193 }
194 const threshold = qualifier.match(
195 /^prompts?\s*(<=|>)\s*([\d,.]+\s*[km]?)\s*(tokens?)?$/,
196 )
197 if (threshold) {
198 const tokens = tokenCount(threshold[2])
199 if (tokens === null) return null
200 return [
201 {
202 levers: [levers.default],
203 rate,
204 tier: threshold[1] === '>' ? tokens : null,
205 expiresAt,
206 },
207 ]
208 }
209 // "(text / image / video)", "(audio)", "(text and thinking)": every word
210 // must be a modality this row prices, or the model is refused.
211 const named = new Set<keyof RowLevers>()
212 for (const word of qualifier.replace(/[().]/g, ' ').split(/[,/+\s]+/)) {
213 const part = word.trim()
214 if (part === '' || part === 'and') continue
215 const modality = MODALITIES[part]
216 if (!modality) return null
217 named.add(modality)
218 }
219 if (named.size === 0) return null
220 // A rate quoted for text covers the prompt-token count as a whole.
221 const targets = named.has('default')
222 ? ['default' as const, ...[...named].filter((m) => m === 'audio')]
223 : [...named]
224 const filled: Array<string> = []
225 for (const modality of targets) {
226 const lever = levers[modality]
227 // A modality this row does not price separately (an image rate on the
228 // caching row, say) would have to be guessed.
229 if (!lever) return null
230 filled.push(lever)
231 }
232 return [{ levers: filled, rate, tier: null, expiresAt }]
233}
234
235interface ParsedRates {
236 base: Record<string, number>
237 tiers: Record<number, Record<string, number>>
238 expiresAt: number | null
239}
240
241function parseTable(segment: string, now: number): ParsedRates | null {
242 const out: ParsedRates = { base: {}, tiers: {}, expiresAt: null }
243 for (const [, row = ''] of segment.matchAll(/<tr>([\s\S]*?)<\/tr>/g)) {
244 const cells = [...row.matchAll(/<td>([\s\S]*?)<\/td>/g)].map(
245 ([, cell = '']) => cell,
246 )
247 if (cells.length < 2) continue
248 const label = plain(cells[0] ?? '').toLowerCase()
249 if (IGNORED_ROWS.test(label)) continue
250 const levers = ROW_LEVERS.find(([match]) => match.test(label))?.[1]
251 if (!levers) {
252 // An unrecognised row that quotes a price is a cost this card would
253 // silently drop.
254 if (/price|cost|\$/.test(label)) return null
255 continue
256 }
257 const paid = cells[cells.length - 1] ?? ''
258 const parts = paid.split(/<br\s*\/?>/)
259 for (const [index, part = ''] of parts.entries()) {
260 const parsed = fragment(part, levers, now, index === 0)
261 if (!parsed) return null
262 for (const { levers: filled, rate, tier, expiresAt } of parsed) {
263 const target = tier === null ? out.base : (out.tiers[tier] ??= {})
264 for (const lever of filled) target[lever] = rate
265 if (expiresAt !== null) {
266 out.expiresAt = Math.min(out.expiresAt ?? expiresAt, expiresAt)
267 }
268 }
269 }
270 }
271 return out
272}
273
274/**
275 * The paid-tier column states the unit every price in it is quoted in
276 * ("Paid Tier, per second in USD"). Anything but tokens is a per-unit card.
277 */
278const UNIT_QUANTITY: Record<string, string | undefined> = {
279 second: 'video_seconds',
280 // "per request" rows quote the whole call ("$0.08 per song").
281 request: undefined,
282}
283
284/** `720p`, `1080p`, `4k` — an output size a per-unit rate is keyed by. */
285const RESOLUTION = /^\d{1,4}[pk]$/
286
287interface UnitRow {
288 label: string
289 /** A flat rate, or one per resolution. */
290 rates: number | Record<string, number>
291}
292
293/**
294 * Rows of a per-unit table. `null` refuses the model: a price this parser
295 * cannot key is worse than no card.
296 */
297function parseUnitRows(segment: string): Array<UnitRow> | null {
298 const rows: Array<UnitRow> = []
299 for (const [, row = ''] of segment.matchAll(/<tr>([\s\S]*?)<\/tr>/g)) {
300 const cells = [...row.matchAll(/<td>([\s\S]*?)<\/td>/g)].map(
301 ([, cell = '']) => cell,
302 )
303 if (cells.length < 2) continue
304 const label = plain(cells[0] ?? '')
305 if (IGNORED_ROWS.test(label.toLowerCase())) continue
306 let flat: number | null = null
307 const rates: Record<string, number> = {}
308 for (const part of (cells[cells.length - 1] ?? '').split(/<br\s*\/?>/)) {
309 const cell = plain(part)
310 if (
311 cell === '' ||
312 /not available|not supported|free of charge/i.test(cell)
313 ) {
314 continue
315 }
316 const match = cell.match(/^\$([\d,]+(?:\.\d+)?)\s*(.*)$/)
317 if (!match?.[1]) return null
318 const rate = Number(match[1].replace(/,/g, ''))
319 const qualifier = (match[2] ?? '')
320 .toLowerCase()
321 .replace(/^\((.*)\)$/, '$1')
322 .replace(/\.$/, '')
323 .trim()
324 // "$0.08 per song" restates the column's own unit.
325 if (qualifier === '' || qualifier.startsWith('per ')) {
326 if (flat !== null) return null
327 flat = rate
328 continue
329 }
330 const sizes = qualifier
331 .replace(/\(|\)/g, '')
332 .split(/\s+and\s+|[,/]/)
333 .map((size) => size.trim())
334 .filter((size) => size !== '' && !/output|supported/.test(size))
335 if (sizes.length === 0 || !sizes.every((size) => RESOLUTION.test(size))) {
336 return null
337 }
338 for (const size of sizes) rates[size] = rate
339 }
340 const keyed = Object.keys(rates).length > 0
341 if (keyed && flat !== null) return null
342 if (!keyed && flat === null) continue
343 rows.push({ label, rates: keyed ? rates : (flat ?? 0) })
344 }
345 return rows.length > 0 ? rows : null
346}
347
348/**
349 * The row that speaks for `id` when a section prices several models: the
350 * one naming every token that tells this id apart from its siblings, or
351 * the "standard" row for an id with no such token. An ambiguous match is
352 * no card.
353 */
354function rowForId(
355 id: string,
356 ids: Array<string>,
357 rows: Array<UnitRow>,
358): UnitRow | undefined {
359 if (rows.length === 1) return rows[0]
360 const tokens = (value: string) =>
361 value
362 .toLowerCase()
363 .split(/[^a-z0-9.]+/)
364 .filter(Boolean)
365 const shared = new Set(
366 tokens(ids[0] ?? '').filter((token) =>
367 ids.every((other) => tokens(other).includes(token)),
368 ),
369 )
370 const distinguishing = tokens(id).filter((token) => !shared.has(token))
371 const wanted = distinguishing.length > 0 ? distinguishing : ['standard']
372 const matched = rows.filter((row) =>
373 wanted.every((token) => tokens(row.label).includes(token)),
374 )
375 return matched.length === 1 ? matched[0] : undefined
376}
377
378export interface GeminiRates {
379 base: Record<string, number>
380 tiers: Array<TokenRateTier>
381 /** ISO instant a dated price change takes effect, when the page names one. */
382 expiresAt?: string
383 /** Set instead of `base` when the model is billed per second or request. */
384 unit?: UnitCardSpec
385}
386
387/** Model id → per-token rates parsed from its Standard table. */
388export function parseGeminiPricing(
389 html: string,
390 now: number = Date.now(),
391): Map<string, GeminiRates> {
392 const out = new Map<string, GeminiRates>()
393 for (const chunk of html.split('<div class="models-section">').slice(1)) {
394 // The heading group's `<em>` lists every id the section prices.
395 const ids = [
396 ...chunk
397 .slice(0, chunk.indexOf('</em>'))
398 .matchAll(/<code[^>]*>([a-z0-9][a-z0-9.-]+)<\/code>/g),
399 ].map(([, value = '']) => value)
400 // The first table of the chunk is the model's own. Its `</table>` can
401 // fall outside the chunk (the last section on the page ends mid-table),
402 // so `</tbody>` closes it too — but one of them must be there, or a
403 // Batch/Flex table further down would be read as Standard rates.
404 const end = ['</tbody>', '</table>']
405 .map((tag) => chunk.indexOf(tag))
406 .filter((at) => at >= 0)
407 // One Standard table covers every id named in the heading
408 // (`gemini-3.1-pro-preview` and `gemini-3.1-pro-preview-customtools`).
409 if (ids.length === 0 || end.length === 0) continue
410 if (ids.every((each) => out.has(each))) continue
411 const segment = chunk.slice(0, Math.min(...end))
412 // Standard rates only: Batch and Flex are separate `<section>` tabs.
413 const heading = [...segment.matchAll(/<h3[^>]*data-text="([^"]*)"/g)].at(-1)
414 if (heading && heading[1] !== 'Standard') continue
415 const unit = segment.match(/Paid Tier, per ([^<]*?) in USD/)?.[1]?.trim()
416 if (unit !== undefined && unit !== '1M tokens') {
417 if (!(unit in UNIT_QUANTITY)) continue
418 const rows = parseUnitRows(segment)
419 if (!rows) continue
420 const quantity = UNIT_QUANTITY[unit]
421 for (const each of ids) {
422 const row = rowForId(each, ids, rows)
423 if (!row || out.has(each)) continue
424 const keyed = typeof row.rates !== 'number'
425 out.set(each, {
426 base: {},
427 tiers: [],
428 unit: {
429 // Duration and output size are nested under the request's
430 // untyped `parameters`, so the caller states them.
431 ...(quantity && {
432 quantity: { param: quantity, bound: 'usage' as const },
433 }),
434 ...(keyed && {
435 keys: [
436 {
437 param: 'resolution',
438 bound: 'usage' as const,
439 values: Object.keys(row.rates),
440 },
441 ],
442 }),
443 rates: row.rates,
444 },
445 })
446 }
447 continue
448 }
449 const parsed = parseTable(segment, now)
450 if (!parsed || Object.keys(parsed.base).length === 0) continue
451 const rates: GeminiRates = {
452 base: parsed.base,
453 tiers: Object.entries(parsed.tiers).map(([min, tierRates]) => ({
454 minPromptTokens: Number(min),
455 rates: { ...parsed.base, ...tierRates },
456 })),
457 ...(parsed.expiresAt !== null && {
458 expiresAt: new Date(parsed.expiresAt).toISOString(),
459 }),
460 }
461 for (const each of ids) {
462 if (!out.has(each)) out.set(each, rates)
463 }
464 }
465 return out
466}
467
468type PricedFacts = Pick<ModelInfo, 'pricing' | 'factSources'>
469
470/** Card lookup by model id; ids the page does not price get nothing. */
471export async function geminiModelPricing(
472 kv?: KVNamespace,
473): Promise<(rawId: string) => PricedFacts> {
474 const doc = await cachedDocs(kv, GEMINI_PRICING_URL, async () => {
475 const html = await fetchText(GEMINI_PRICING_URL)
476 const parsed = parseGeminiPricing(html)
477 assertParsed(parsed, 'gemini pricing page')
478 return {
479 rates: Object.fromEntries(parsed),
480 hash: await sha256Text(html),
481 extractedAt: new Date().toISOString(),
482 }
483 })
484 const card = (rawId: string): RateCard | null => {
485 const rates = doc.rates[rawId]
486 if (!rates) return null
487 const source = {
488 url: GEMINI_PRICING_URL,
489 hash: doc.hash,
490 extractedAt: doc.extractedAt,
491 ...(rates.expiresAt && { expiresAt: rates.expiresAt }),
492 }
493 return rates.unit
494 ? compileUnitCard(rates.unit, source)
495 : compileTokenCard(rates.base, rates.tiers, source)
496 }
497 return (rawId) => {
498 // `gemini-2.5-flash-preview-09-2025` is priced by its family row.
499 const pricing = card(rawId) ?? card(rawId.replace(/-preview.*$/, ''))
500 if (!pricing) return {}
501 return {
502 pricing,
503 factSources: tagDocsFacts({ pricing }, GEMINI_PRICING_URL, doc.hash),
504 }
505 }
506}