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

gemini-pricing.ts

534 lines17.9 KB

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
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 ],
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',
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: ' ',
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 )
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
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 // "Implicit caching only (explicit caching is not supported)." scopes the
157 // caching rate above it and quotes no amount.
158 if (!first && /^implicit caching only\b[^$]*$/i.test(cell)) return []
159 // A price in a unit other than the column's tokens: after the first
160 // fragment it restates the token rate ("Equivalent to $0.134 per 1K/2K
161 // image", "and $0.24 per 4K image"); as the first, it *is* the price and
162 // this card has no lever for it.
163 if (/equivalent|\bper \d|\bper [a-z]+\b/i.test(cell)) {
164 return first ? null : []
165 }
166 const match = cell.match(/^\$([\d,]+(?:\.\d+)?)\s*(.*)$/)
167 if (!match?.[1]) return null
168 const rate = Number(match[1].replace(/,/g, '')) / 1e6
169 let qualifier = (match[2] ?? '')
170 .trim()
171 .toLowerCase()
172 // A qualifier follows the price as a parenthetical or after a comma.
173 .replace(/^,\s*/, '')
174 .replace(/\.$/, '')
175 .trim()
176​
177 // A dated price change ("$0.75 through December 31, 2026" / "$1.50
178 // starting January 1, 2027"): the rate in effect now wins and stamps the
179 // card's `expiresAt`, so it is re-extracted once the change lands.
180 let expiresAt: number | null = null
181 const dated = qualifier.match(
182 /^(.*?)\s*(through|starting) ([a-z]+ \d{1,2}, \d{4})$/,
183 )
184 if (dated?.[3]) {
185 const day = parseDay(dated[3])
186 if (day === null) return null
187 const ends = dated[2] === 'through' ? day + DAY_MS : day
188 if (dated[2] === 'through' ? now >= ends : now < ends) return []
189 if (dated[2] === 'through') expiresAt = ends
190 qualifier = (dated[1] ?? '').trim()
191 }
192 qualifier = qualifier.replace(/^\((.*)\)$/, '$1').trim()
193​
194 if (qualifier === '') {
195 return [{ levers: [levers.default], rate, tier: null, expiresAt }]
196 }
197 const threshold = qualifier.match(
198 /^prompts?\s*(<=|>)\s*([\d,.]+\s*[km]?)\s*(tokens?)?$/,
199 )
200 if (threshold) {
201 const tokens = tokenCount(threshold[2])
202 if (tokens === null) return null
203 return [
204 {
205 levers: [levers.default],
206 rate,
207 tier: threshold[1] === '>' ? tokens : null,
208 expiresAt,
209 },
210 ]
211 }
212 // "(text / image / video)", "(audio)", "(text and thinking)": every word
213 // must be a modality this row prices, or the model is refused.
214 const named = new Set<keyof RowLevers>()
215 for (const word of qualifier.replace(/[().]/g, ' ').split(/[,/+\s]+/)) {
216 const part = word.trim()
217 if (part === '' || part === 'and') continue
218 const modality = MODALITIES[part]
219 if (!modality) return null
220 named.add(modality)
221 }
222 if (named.size === 0) return null
223 // A rate quoted for text covers the prompt-token count as a whole.
224 const targets = named.has('default')
225 ? ['default' as const, ...[...named].filter((m) => m === 'audio')]
226 : [...named]
227 const filled: Array<string> = []
228 for (const modality of targets) {
229 const lever = levers[modality]
230 // A modality this row does not price separately (an image rate on the
231 // caching row, say) would have to be guessed.
232 if (!lever) return null
233 filled.push(lever)
234 }
235 return [{ levers: filled, rate, tier: null, expiresAt }]
237​
238interface ParsedRates {
239 base: Record<string, number>
240 tiers: Record<number, Record<string, number>>
241 expiresAt: number | null
243​
244function parseTable(segment: string, now: number): ParsedRates | null {
245 const out: ParsedRates = { base: {}, tiers: {}, expiresAt: null }
246 for (const [, row = ''] of segment.matchAll(/<tr>([\s\S]*?)<\/tr>/g)) {
247 const cells = [...row.matchAll(/<td>([\s\S]*?)<\/td>/g)].map(
248 ([, cell = '']) => cell,
249 )
250 if (cells.length < 2) continue
251 const label = plain(cells[0] ?? '').toLowerCase()
252 if (IGNORED_ROWS.test(label)) continue
253 const levers = ROW_LEVERS.find(([match]) => match.test(label))?.[1]
254 if (!levers) {
255 // An unrecognised row that quotes a price is a cost this card would
256 // silently drop.
257 if (/price|cost|\$/.test(label)) return null
258 continue
259 }
260 const paid = cells[cells.length - 1] ?? ''
261 const parts = paid.split(/<br\s*\/?>/)
262 for (const [index, part = ''] of parts.entries()) {
263 const parsed = fragment(part, levers, now, index === 0)
264 if (!parsed) return null
265 for (const { levers: filled, rate, tier, expiresAt } of parsed) {
266 const target = tier === null ? out.base : (out.tiers[tier] ??= {})
267 for (const lever of filled) target[lever] = rate
268 if (expiresAt !== null) {
269 out.expiresAt = Math.min(out.expiresAt ?? expiresAt, expiresAt)
270 }
271 }
272 }
273 }
274 return out
276​
277/**
278 * The paid-tier column states the unit every price in it is quoted in
279 * ("Paid Tier, per second in USD"). Anything but tokens is a per-unit card.
280 */
281const UNIT_QUANTITY: Record<string, string | undefined> = {
282 second: 'video_seconds',
283 // "per request" rows quote the whole call ("$0.08 per song").
284 request: undefined,
286​
287/** `720p`, `1080p`, `4k` — an output size a per-unit rate is keyed by. */
288const RESOLUTION = /^\d{1,4}[pk]$/
289​
290interface UnitRow {
291 label: string
292 /** A flat rate, or one per resolution. */
293 rates: number | Record<string, number>
295​
296/**
297 * Rows of a per-unit table. `null` refuses the model: a price this parser
298 * cannot key is worse than no card.
299 */
300function parseUnitRows(segment: string): Array<UnitRow> | null {
301 const rows: Array<UnitRow> = []
302 for (const [, row = ''] of segment.matchAll(/<tr>([\s\S]*?)<\/tr>/g)) {
303 const cells = [...row.matchAll(/<td>([\s\S]*?)<\/td>/g)].map(
304 ([, cell = '']) => cell,
305 )
306 if (cells.length < 2) continue
307 const label = plain(cells[0] ?? '')
308 if (IGNORED_ROWS.test(label.toLowerCase())) continue
309 let flat: number | null = null
310 const rates: Record<string, number> = {}
311 for (const part of (cells[cells.length - 1] ?? '').split(/<br\s*\/?>/)) {
312 const cell = plain(part)
313 if (
314 cell === '' ||
315 /not available|not supported|free of charge/i.test(cell)
316 ) {
317 continue
318 }
319 const match = cell.match(/^\$([\d,]+(?:\.\d+)?)\s*(.*)$/)
320 if (!match?.[1]) return null
321 const rate = Number(match[1].replace(/,/g, ''))
322 const qualifier = (match[2] ?? '')
323 .toLowerCase()
324 .replace(/^\((.*)\)$/, '$1')
325 .replace(/\.$/, '')
326 .trim()
327 // "$0.08 per song" restates the column's own unit.
328 if (qualifier === '' || qualifier.startsWith('per ')) {
329 if (flat !== null) return null
330 flat = rate
331 continue
332 }
333 const sizes = qualifier
334 .replace(/\(|\)/g, '')
335 .split(/\s+and\s+|[,/]/)
336 .map((size) => size.trim())
337 .filter((size) => size !== '' && !/output|supported/.test(size))
338 if (sizes.length === 0 || !sizes.every((size) => RESOLUTION.test(size))) {
339 return null
340 }
341 for (const size of sizes) rates[size] = rate
342 }
343 const keyed = Object.keys(rates).length > 0
344 if (keyed && flat !== null) return null
345 if (!keyed && flat === null) continue
346 rows.push({ label, rates: keyed ? rates : (flat ?? 0) })
347 }
348 return rows.length > 0 ? rows : null
350​
351/**
352 * The row that speaks for `id` when a section prices several models: the
353 * one naming every token that tells this id apart from its siblings, or
354 * the "standard" row for an id with no such token. An ambiguous match is
355 * no card.
356 */
357function rowForId(
358 id: string,
359 ids: Array<string>,
360 rows: Array<UnitRow>,
361): UnitRow | undefined {
362 if (rows.length === 1) return rows[0]
363 const tokens = (value: string) =>
364 value
365 .toLowerCase()
366 .split(/[^a-z0-9.]+/)
367 .filter(Boolean)
368 const shared = new Set(
369 tokens(ids[0] ?? '').filter((token) =>
370 ids.every((other) => tokens(other).includes(token)),
371 ),
372 )
373 const distinguishing = tokens(id).filter((token) => !shared.has(token))
374 const wanted = distinguishing.length > 0 ? distinguishing : ['standard']
375 const matched = rows.filter((row) =>
376 wanted.every((token) => tokens(row.label).includes(token)),
377 )
378 return matched.length === 1 ? matched[0] : undefined
380​
381export interface GeminiRates {
382 base: Record<string, number>
383 tiers: Array<TokenRateTier>
384 /** ISO instant a dated price change takes effect, when the page names one. */
385 expiresAt?: string
386 /** Set instead of `base` when the model is billed per second or request. */
387 unit?: UnitCardSpec
389​
390const SECTION = '<div class="models-section">'
391​
392/** The heading group's `<em>` lists every id the section prices. */
393function headingIds(chunk: string): Array<string> {
394 return [
395 ...chunk
396 .slice(0, chunk.indexOf('</em>'))
397 .matchAll(/<code[^>]*>([a-z0-9][a-z0-9.-]+)<\/code>/g),
398 ].map(([, value = '']) => value)
400​
401/**
402 * Every id a section heading names, including sections `parseGeminiPricing`
403 * refuses. A listed id missing from this is one the page no longer prices
404 * (issue #300: deprecated ids routed to a successor), not a parser miss.
405 */
406export function geminiNamedIds(html: string): Array<string> {
407 return [...new Set(html.split(SECTION).slice(1).flatMap(headingIds))]
409​
410/** Model id → per-token rates parsed from its Standard table. */
411export function parseGeminiPricing(
412 html: string,
413 now: number = Date.now(),
414): Map<string, GeminiRates> {
415 const out = new Map<string, GeminiRates>()
416 for (const chunk of html.split(SECTION).slice(1)) {
417 const ids = headingIds(chunk)
418 // The first table of the chunk is the model's own. Its `</table>` can
419 // fall outside the chunk (the last section on the page ends mid-table),
420 // so `</tbody>` closes it too — but one of them must be there, or a
421 // Batch/Flex table further down would be read as Standard rates.
422 const end = ['</tbody>', '</table>']
423 .map((tag) => chunk.indexOf(tag))
424 .filter((at) => at >= 0)
425 // One Standard table covers every id named in the heading
426 // (`gemini-3.1-pro-preview` and `gemini-3.1-pro-preview-customtools`).
427 if (ids.length === 0 || end.length === 0) continue
428 if (ids.every((each) => out.has(each))) continue
429 const segment = chunk.slice(0, Math.min(...end))
430 // Standard rates only: Batch and Flex are separate `<section>` tabs.
431 const heading = [...segment.matchAll(/<h3[^>]*data-text="([^"]*)"/g)].at(-1)
432 if (heading && heading[1] !== 'Standard') continue
433 const unit = segment.match(/Paid Tier, per ([^<]*?) in USD/)?.[1]?.trim()
434 if (unit !== undefined && unit !== '1M tokens') {
435 if (!(unit in UNIT_QUANTITY)) continue
436 const rows = parseUnitRows(segment)
437 if (!rows) continue
438 const quantity = UNIT_QUANTITY[unit]
439 for (const each of ids) {
440 const row = rowForId(each, ids, rows)
441 if (!row || out.has(each)) continue
442 const keyed = typeof row.rates !== 'number'
443 out.set(each, {
444 base: {},
445 tiers: [],
446 unit: {
447 // Duration and output size are nested under the request's
448 // untyped `parameters`, so the caller states them.
449 ...(quantity && {
450 quantity: { param: quantity, bound: 'usage' as const },
451 }),
452 ...(keyed && {
453 keys: [
454 {
455 param: 'resolution',
456 bound: 'usage' as const,
457 values: Object.keys(row.rates),
458 },
459 ],
460 }),
461 rates: row.rates,
462 },
463 })
464 }
465 continue
466 }
467 const parsed = parseTable(segment, now)
468 if (!parsed || Object.keys(parsed.base).length === 0) continue
469 const rates: GeminiRates = {
470 base: parsed.base,
471 tiers: Object.entries(parsed.tiers).map(([min, tierRates]) => ({
472 minPromptTokens: Number(min),
473 rates: { ...parsed.base, ...tierRates },
474 })),
475 ...(parsed.expiresAt !== null && {
476 expiresAt: new Date(parsed.expiresAt).toISOString(),
477 }),
478 }
479 for (const each of ids) {
480 if (!out.has(each)) out.set(each, rates)
481 }
482 }
483 return out
485​
486type PricedFacts = Pick<ModelInfo, 'pricing' | 'factSources' | 'absent'>
487​
488/**
489 * Card lookup by model id. An id no section names is `cleared`: the page
490 * visibly does not price it. An id a section names but the parser refuses
491 * gets nothing, so its stored card is kept and `pricing_lost` is logged.
492 */
493export async function geminiModelPricing(
494 kv?: KVNamespace,
495): Promise<(rawId: string) => PricedFacts> {
496 const doc = await cachedDocs(kv, GEMINI_PRICING_URL, async () => {
497 const html = await fetchText(GEMINI_PRICING_URL)
498 const parsed = parseGeminiPricing(html)
499 assertParsed(parsed, 'gemini pricing page')
500 return {
501 rates: Object.fromEntries(parsed),
502 named: geminiNamedIds(html),
503 hash: await sha256Text(html),
504 extractedAt: new Date().toISOString(),
505 }
506 })
507 const card = (rawId: string): RateCard | null => {
508 const rates = doc.rates[rawId]
509 if (!rates) return null
510 const source = {
511 url: GEMINI_PRICING_URL,
512 hash: doc.hash,
513 extractedAt: doc.extractedAt,
514 ...(rates.expiresAt && { expiresAt: rates.expiresAt }),
515 }
516 return rates.unit
517 ? compileUnitCard(rates.unit, source)
518 : compileTokenCard(rates.base, rates.tiers, source)
519 }
520 return (rawId) => {
521 // `gemini-2.5-flash-preview-09-2025` is priced by its family row.
522 const family = rawId.replace(/-preview.*$/, '')
523 const pricing = card(rawId) ?? card(family)
524 if (!pricing) {
525 return doc.named.includes(rawId) || doc.named.includes(family)
526 ? {}
527 : { absent: { pricing: 'cleared' } }
528 }
529 return {
530 pricing,
531 factSources: tagDocsFacts({ pricing }, GEMINI_PRICING_URL, doc.hash),
532 }
533 }