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

gemini-pricing.ts

639 lines21.5 KB

1/**
2 * Gemini prices from Google's own pricing page (issues #61, #568). Google
3 * publishes no pricing API, so this parses the page's Markdoc mirror: one
4 * `## ` section per price, every model id linked in backticks above the
5 * section's first `{% hr /%}` (siblings share the table), and the paid-tier
6 * column of the section's "Standard" tab, or of its only 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 inside `tryDocs`. The listing
13 * still writes, and every row keeps its stored card (`unavailable`) until
14 * the parser is taught the new page.
15 */
16import { compileTokenCard, compileUnitCard } from '@modelschemas/rate-card'
17import type {
18 RateCard,
19 TokenRateTier,
20 UnitCardSpec,
21} from '@modelschemas/rate-card'
22​
23import {
24 GEMINI_DEPRECATIONS_URL,
25 geminiAutomaticRoutes,
26} from './gemini-bindings.ts'
27import { tagDocsFacts } from './fact-sources.ts'
28import {
29 assertParsed,
30 docsRun,
31 markdocTables,
32 markdownTableRows,
33 parseDay,
34 tokenCount,
35 tryDocs,
36 unavailable,
37} from './model-facts.ts'
38import { fetchText, sha256Text } from './types.ts'
39import type { DocsRun } from './model-facts.ts'
40import type { ModelInfo } from './types.ts'
41​
42export const GEMINI_PRICING_URL = 'https://aistudio.google.com/docs/pricing.md'
43​
44/**
45 * A row's lever per modality. `default` takes any price the row quotes for
46 * text (Gemini sums text, image and video into one prompt-token count, so
47 * one rate covering them all is the default lever); a modality named on its
48 * own is priced differently and gets its own lever.
49 */
50interface RowLevers {
51 default: string
52 audio?: string
53 image?: string
54 video?: string
56​
57/** Row label → its levers. */
58const ROW_LEVERS: Array<[RegExp, RowLevers]> = [
59 // A trailing parenthetical names the modalities the row covers ("Input
60 // price (text, image, video)"); a leading modality is a different row
61 // ("Audio input price"), which this must not match.
62 [
63 /^input price( \([^)]*\))?$/,
64 {
65 default: 'input_tokens',
66 audio: 'audio_tokens',
67 image: 'image_tokens',
68 video: 'video_tokens',
69 },
70 ],
71 [/^text input price$/, { default: 'input_tokens' }],
72 [/^image input price$/, { default: 'image_tokens' }],
73 [/^audio input price$/, { default: 'audio_tokens' }],
74 [/^video input price$/, { default: 'video_tokens' }],
75 [
76 /^output price( \([^)]*\))?$/,
77 {
78 default: 'output_tokens',
79 audio: 'audio_output_tokens',
80 image: 'image_output_tokens',
81 video: 'video_output_tokens',
82 },
83 ],
84 [
85 /^context caching price$/,
86 {
87 default: 'cache_read_tokens',
88 audio: 'audio_cache_tokens',
89 image: 'image_cache_tokens',
90 },
91 ],
93​
94/** Modality words a qualifier may name, singular or plural. */
95const MODALITIES: Record<string, keyof RowLevers> = {
96 text: 'default',
97 texts: 'default',
98 thinking: 'default',
99 image: 'image',
100 images: 'image',
101 video: 'video',
102 videos: 'video',
103 audio: 'audio',
105​
106/** Rows that are not a per-token cost of one request. */
107const IGNORED_ROWS =
108 /^(grounding with |used to improve|context caching \(storage\)|tuning price|live api)/
109​
110const ENTITIES: Record<string, string> = {
111 amp: '&',
112 lt: '<',
113 gt: '>',
114 quot: '"',
115 '#39': "'",
116 nbsp: ' ',
118​
119function plain(html: string): string {
120 return (
121 html
122 // Footnote markers are not part of a price.
123 .replace(/<sup>[\s\S]*?<\/sup>/g, '')
124 // `[No](/docs/terms)` → `No`.
125 .replace(/\[([^\]]*)\]\([^)]*\)/g, '$1')
126 .replace(/\*\*|`/g, '')
127 // A real tag only; a bare `<=` in a qualifier must survive.
128 .replace(/<\/?[a-zA-Z][^>]*>/g, '')
129 .replace(/&([a-z]+|#\d+);/gi, (match, name: string) => {
130 return ENTITIES[name.toLowerCase()] ?? match
131 })
132 .replace(/\s+/g, ' ')
133 .trim()
134 )
136​
137const DAY_MS = 86_400_000
138​
139type Fragment = {
140 levers: Array<string>
141 rate: number
142 tier: number | null
143 /** Instant this rate stops applying, for a dated price change. */
144 expiresAt: number | null
146​
147/**
148 * One `$x (qualifier)` fragment of a paid-tier cell. `null` refuses the
149 * model; `[]` is a fragment that prices nothing here (storage, "not
150 * available").
151 */
152function fragment(
153 raw: string,
154 levers: RowLevers,
155 now: number,
156 first: boolean,
157): Array<Fragment> | null {
158 const cell = plain(raw)
159 // "$6.50 ($0.00016 per second)" / "$3.00 or $0.005/min (audio)": the
160 // column is per 1M tokens, so a second amount in another unit restates
161 // the token rate rather than adding to it.
162 .replace(/\s*\(\s*\$[^)]*\)/g, '')
163 .replace(/\s+or \$[\d.,]+\s*\/\s*\w+/gi, '')
164 .trim()
165 if (cell === '' || /^(not available|free of charge)$/i.test(cell)) return []
166 // Cache storage is quoted per token-hour, not per request.
167 if (/per hour|storage price/i.test(cell)) return []
168 // "Implicit caching only (explicit caching is not supported)." scopes the
169 // caching rate above it and quotes no amount.
170 if (!first && /^implicit caching only\b[^$]*$/i.test(cell)) return []
171 // A price in a unit other than the column's tokens: after the first
172 // fragment it restates the token rate ("Equivalent to $0.134 per 1K/2K
173 // image", "and $0.24 per 4K image"); as the first, it *is* the price and
174 // this card has no lever for it.
175 if (/equivalent|\bper \d|\bper [a-z]+\b/i.test(cell)) {
176 return first ? null : []
177 }
178 const match = cell.match(/^\$([\d,]+(?:\.\d+)?)\s*(.*)$/)
179 if (!match?.[1]) return null
180 const rate = Number(match[1].replace(/,/g, '')) / 1e6
181 let qualifier = (match[2] ?? '')
182 .trim()
183 .toLowerCase()
184 // A qualifier follows the price as a parenthetical or after a comma.
185 .replace(/^,\s*/, '')
186 .replace(/\.$/, '')
187 .trim()
188​
189 // A dated price change ("$0.75 through December 31, 2026" / "$1.50
190 // starting January 1, 2027"): the rate in effect now wins and stamps the
191 // card's `expiresAt`, so it is re-extracted once the change lands.
192 let expiresAt: number | null = null
193 const dated = qualifier.match(
194 /^(.*?)\s*(through|starting) ([a-z]+ \d{1,2}, \d{4})$/,
195 )
196 if (dated?.[3]) {
197 const day = parseDay(dated[3])
198 if (day === null) return null
199 const ends = dated[2] === 'through' ? day + DAY_MS : day
200 if (dated[2] === 'through' ? now >= ends : now < ends) return []
201 if (dated[2] === 'through') expiresAt = ends
202 qualifier = (dated[1] ?? '').trim()
203 }
204 qualifier = qualifier.replace(/^\((.*)\)$/, '$1').trim()
205​
206 if (qualifier === '') {
207 return [{ levers: [levers.default], rate, tier: null, expiresAt }]
208 }
209 const threshold = qualifier.match(
210 /^prompts?\s*(<=|>)\s*([\d,.]+\s*[km]?)\s*(tokens?)?$/,
211 )
212 if (threshold) {
213 const tokens = tokenCount(threshold[2])
214 if (tokens === null) return null
215 return [
216 {
217 levers: [levers.default],
218 rate,
219 tier: threshold[1] === '>' ? tokens : null,
220 expiresAt,
221 },
222 ]
223 }
224 // "(text / image / video)", "(audio)", "(text and thinking)": every word
225 // must be a modality this row prices, or the model is refused.
226 const named = new Set<keyof RowLevers>()
227 for (const word of qualifier.replace(/[().]/g, ' ').split(/[,/+\s]+/)) {
228 const part = word.trim()
229 if (part === '' || part === 'and') continue
230 const modality = MODALITIES[part]
231 if (!modality) return null
232 named.add(modality)
233 }
234 if (named.size === 0) return null
235 // A rate quoted for text covers the prompt-token count as a whole.
236 const targets = named.has('default')
237 ? ['default' as const, ...[...named].filter((m) => m === 'audio')]
238 : [...named]
239 const filled: Array<string> = []
240 for (const modality of targets) {
241 const lever = levers[modality]
242 // A modality this row does not price separately (an image rate on the
243 // caching row, say) would have to be guessed.
244 if (!lever) return null
245 filled.push(lever)
246 }
247 return [{ levers: filled, rate, tier: null, expiresAt }]
249​
250interface ParsedRates {
251 base: Record<string, number>
252 tiers: Record<number, Record<string, number>>
253 expiresAt: number | null
255​
256function parseTable(
257 table: Array<Array<string>>,
258 now: number,
259): ParsedRates | null {
260 const out: ParsedRates = { base: {}, tiers: {}, expiresAt: null }
261 for (const cells of table) {
262 if (cells.length < 2) continue
263 const label = plain(cells[0] ?? '').toLowerCase()
264 if (IGNORED_ROWS.test(label)) continue
265 const levers = ROW_LEVERS.find(([match]) => match.test(label))?.[1]
266 if (!levers) {
267 // An unrecognised row that quotes a price is a cost this card would
268 // silently drop.
269 if (/price|cost|\$/.test(label)) return null
270 continue
271 }
272 const paid = cells[cells.length - 1] ?? ''
273 const parts = paid.split(/<br\s*\/?>/)
274 for (const [index, part = ''] of parts.entries()) {
275 const parsed = fragment(part, levers, now, index === 0)
276 if (!parsed) return null
277 for (const { levers: filled, rate, tier, expiresAt } of parsed) {
278 const target = tier === null ? out.base : (out.tiers[tier] ??= {})
279 for (const lever of filled) target[lever] = rate
280 if (expiresAt !== null) {
281 out.expiresAt = Math.min(out.expiresAt ?? expiresAt, expiresAt)
282 }
283 }
284 }
285 }
286 return out
288​
289/**
290 * The paid-tier column states the unit every price in it is quoted in
291 * ("Paid Tier, per second in USD"). Anything but tokens is a per-unit card.
292 */
293const UNIT_QUANTITY: Record<string, string | undefined> = {
294 second: 'video_seconds',
295 // "per request" rows quote the whole call ("$0.08 per song").
296 request: undefined,
298​
299/** `720p`, `1080p`, `4k` — an output size a per-unit rate is keyed by. */
300const RESOLUTION = /^\d{1,4}[pk]$/
301​
302interface UnitRow {
303 label: string
304 /** A flat rate, or one per resolution. */
305 rates: number | Record<string, number>
307​
308/**
309 * Rows of a per-unit table. `null` refuses the model: a price this parser
310 * cannot key is worse than no card.
311 */
312function parseUnitRows(table: Array<Array<string>>): Array<UnitRow> | null {
313 const rows: Array<UnitRow> = []
314 for (const cells of table) {
315 if (cells.length < 2) continue
316 const label = plain(cells[0] ?? '')
317 if (IGNORED_ROWS.test(label.toLowerCase())) continue
318 let flat: number | null = null
319 const rates: Record<string, number> = {}
320 for (const part of (cells[cells.length - 1] ?? '').split(/<br\s*\/?>/)) {
321 const cell = plain(part)
322 if (
323 cell === '' ||
324 /not available|not supported|free of charge/i.test(cell)
325 ) {
326 continue
327 }
328 const match = cell.match(/^\$([\d,]+(?:\.\d+)?)\s*(.*)$/)
329 if (!match?.[1]) return null
330 const rate = Number(match[1].replace(/,/g, ''))
331 const qualifier = (match[2] ?? '')
332 .toLowerCase()
333 .replace(/^\((.*)\)$/, '$1')
334 .replace(/\.$/, '')
335 .trim()
336 // "$0.08 per song" restates the column's own unit.
337 if (qualifier === '' || qualifier.startsWith('per ')) {
338 if (flat !== null) return null
339 flat = rate
340 continue
341 }
342 const sizes = qualifier
343 .replace(/\(|\)/g, '')
344 .split(/\s+and\s+|[,/]/)
345 .map((size) => size.trim())
346 .filter((size) => size !== '' && !/output|supported/.test(size))
347 if (sizes.length === 0 || !sizes.every((size) => RESOLUTION.test(size))) {
348 return null
349 }
350 for (const size of sizes) rates[size] = rate
351 }
352 const keyed = Object.keys(rates).length > 0
353 if (keyed && flat !== null) return null
354 if (!keyed && flat === null) continue
355 rows.push({ label, rates: keyed ? rates : (flat ?? 0) })
356 }
357 return rows.length > 0 ? rows : null
359​
360/**
361 * The row that speaks for `id` when a section prices several models: the
362 * one naming every token that tells this id apart from its siblings, or
363 * the "standard" row for an id with no such token. An ambiguous match is
364 * no card.
365 */
366function rowForId(
367 id: string,
368 ids: Array<string>,
369 rows: Array<UnitRow>,
370): UnitRow | undefined {
371 if (rows.length === 1) return rows[0]
372 const tokens = (value: string) =>
373 value
374 .toLowerCase()
375 .split(/[^a-z0-9.]+/)
376 .filter(Boolean)
377 const shared = new Set(
378 tokens(ids[0] ?? '').filter((token) =>
379 ids.every((other) => tokens(other).includes(token)),
380 ),
381 )
382 const distinguishing = tokens(id).filter((token) => !shared.has(token))
383 const wanted = distinguishing.length > 0 ? distinguishing : ['standard']
384 const matched = rows.filter((row) =>
385 wanted.every((token) => tokens(row.label).includes(token)),
386 )
387 return matched.length === 1 ? matched[0] : undefined
389​
390export interface GeminiRates {
391 base: Record<string, number>
392 tiers: Array<TokenRateTier>
393 /** ISO instant a dated price change takes effect, when the page names one. */
394 expiresAt?: string
395 /** Set instead of `base` when the model is billed per second or request. */
396 unit?: UnitCardSpec
398​
399/** The page's `## ` sections, tables rewritten as `| a | b |` rows. */
400function sections(markdown: string): Array<string> {
401 return markdocTables(markdown)
402 .split(/^(?=## )/m)
403 .filter((chunk) => chunk.startsWith('## '))
405​
406const LINKED_ID = /\[`([a-z0-9][a-z0-9.-]+)`\]\(/g
407​
408/**
409 * Ids linked in backticks above the section's first `{% hr /%}`; prose
410 * below it names other models. A section that links ids but has no rule
411 * throws: dropping its ids would read as "no longer priced" and clear
412 * their stored cards. Tool and Gemma sections link no ids and pass.
413 */
414function headingIds(section: string): Array<string> {
415 const end = section.indexOf('{% hr /%}')
416 if (end < 0) {
417 const table = section.search(/^\|/m)
418 if (section.slice(0, table < 0 ? undefined : table).match(LINKED_ID)) {
419 throw new Error(
420 `gemini pricing page: no {% hr /%} under ${JSON.stringify(section.split('\n')[0])}`,
421 )
422 }
423 return []
424 }
425 return [...section.slice(0, end).matchAll(LINKED_ID)].map(
426 ([, value = '']) => value,
427 )
429​
430/**
431 * The section's first table, when it is the Standard rates: Batch, Flex
432 * and Priority are later `{% tab %}`s, and a section with no tabs has one
433 * table.
434 */
435function standardTable(section: string): Array<Array<string>> | null {
436 const lines = section.split('\n')
437 const start = lines.findIndex((line) => line.startsWith('|'))
438 if (start < 0) return null
439 let end = start
440 while (lines[end]?.startsWith('|')) end++
441 const tab = [
442 ...lines
443 .slice(0, start)
444 .join('\n')
445 .matchAll(/\{%\s*tab\b[^%]*title="([^"]*)"/g),
446 ].at(-1)
447 if (tab && tab[1] !== 'Standard') return null
448 return markdownTableRows(lines.slice(start, end).join('\n'))
450​
451/**
452 * Every id a section heading names, including sections `parseGeminiPricing`
453 * refuses. A listed id missing from this is one the page no longer prices.
454 * `geminiModelPricing` still copies a successor's Standard card when the
455 * deprecations page says API requests are automatically routed to that id
456 * (issue #497). A recommended replacement is not a rate (issue #300).
457 */
458export function geminiNamedIds(markdown: string): Array<string> {
459 return [...new Set(sections(markdown).flatMap(headingIds))]
461​
462/** Model id → per-token rates parsed from its Standard table. */
463export function parseGeminiPricing(
464 markdown: string,
465 now: number = Date.now(),
466): Map<string, GeminiRates> {
467 const out = new Map<string, GeminiRates>()
468 for (const section of sections(markdown)) {
469 const ids = headingIds(section)
470 // One Standard table covers every id named in the heading
471 // (`gemini-3.1-pro-preview` and `gemini-3.1-pro-preview-customtools`).
472 if (ids.length === 0) continue
473 if (ids.every((each) => out.has(each))) continue
474 const table = standardTable(section)
475 if (!table) continue
476 const [header = [], ...body] = table
477 // The last column is read as the paid price only when it says so.
478 const unit = header
479 .at(-1)
480 ?.match(/^Paid Tier, per (.+?) in USD$/)?.[1]
481 ?.trim()
482 if (unit === undefined) continue
483 if (unit !== '1M tokens') {
484 if (!(unit in UNIT_QUANTITY)) continue
485 const rows = parseUnitRows(body)
486 if (!rows) continue
487 const quantity = UNIT_QUANTITY[unit]
488 for (const each of ids) {
489 const row = rowForId(each, ids, rows)
490 if (!row || out.has(each)) continue
491 const keyed = typeof row.rates !== 'number'
492 out.set(each, {
493 base: {},
494 tiers: [],
495 unit: {
496 // Duration and output size are nested under the request's
497 // untyped `parameters`, so the caller states them.
498 ...(quantity && {
499 quantity: { param: quantity, bound: 'usage' as const },
500 }),
501 ...(keyed && {
502 keys: [
503 {
504 param: 'resolution',
505 bound: 'usage' as const,
506 values: Object.keys(row.rates),
507 },
508 ],
509 }),
510 rates: row.rates,
511 },
512 })
513 }
514 continue
515 }
516 const parsed = parseTable(body, now)
517 if (!parsed || Object.keys(parsed.base).length === 0) continue
518 const rates: GeminiRates = {
519 base: parsed.base,
520 tiers: Object.entries(parsed.tiers).map(([min, tierRates]) => ({
521 minPromptTokens: Number(min),
522 rates: { ...parsed.base, ...tierRates },
523 })),
524 ...(parsed.expiresAt !== null && {
525 expiresAt: new Date(parsed.expiresAt).toISOString(),
526 }),
527 }
528 for (const each of ids) {
529 if (!out.has(each)) out.set(each, rates)
530 }
531 }
532 return out
534​
535type PricedFacts = Pick<ModelInfo, 'pricing' | 'factSources' | 'absent'>
536​
537export interface GeminiPricingLookup {
538 (rawId: string): PricedFacts
539 /** `YYYY-MM-DD` from the deprecations page. Empty when that page failed. */
540 releasedOn: Record<string, string>
542​
543/**
544 * Card lookup by model id. An id no section names is `cleared`: the page
545 * visibly does not price it. An id a section names but the parser refuses
546 * gets nothing, so its stored card is kept and `pricing_lost` is logged.
547 * A failed pricing or deprecations load is recorded on `run` and does not
548 * throw: every row is `unavailable` when the price page itself failed, and
549 * an id with no card of its own is `unavailable` when the routes page
550 * failed, so a blip cannot clear a card that page might have routed.
551 */
552export async function geminiModelPricing(
553 kv?: KVNamespace,
554 run: DocsRun = docsRun(),
555): Promise<GeminiPricingLookup> {
556 const [doc, routes] = await Promise.all([
557 tryDocs(run, GEMINI_PRICING_URL, (cached) =>
558 cached(kv, GEMINI_PRICING_URL, async () => {
559 const markdown = await fetchText(GEMINI_PRICING_URL)
560 const parsed = parseGeminiPricing(markdown)
561 assertParsed(parsed, 'gemini pricing page')
562 return {
563 rates: Object.fromEntries(parsed),
564 named: geminiNamedIds(markdown),
565 hash: await sha256Text(markdown),
566 extractedAt: new Date().toISOString(),
567 }
568 }),
569 ),
570 // A failed fetch, or a body that is not the deprecations page, is a
571 // docs failure. A real page that names no automatic route is Google
572 // stating no automatic routing.
573 tryDocs(run, GEMINI_DEPRECATIONS_URL, (cached) =>
574 geminiAutomaticRoutes(kv, cached),
575 ),
576 ])
577 const releasedOn = routes?.released ?? {}
578 if (!doc) {
579 const unread = (_rawId: string): PricedFacts => unavailable('pricing')
580 unread.releasedOn = releasedOn
581 return unread
582 }
583 const routeTo = new Map(Object.entries(routes?.routes ?? {}))
584 const card = (rawId: string): RateCard | null => {
585 const rates = doc.rates[rawId]
586 if (!rates) return null
587 const source = {
588 url: GEMINI_PRICING_URL,
589 hash: doc.hash,
590 extractedAt: doc.extractedAt,
591 ...(rates.expiresAt && { expiresAt: rates.expiresAt }),
592 }
593 return rates.unit
594 ? compileUnitCard(rates.unit, source)
595 : compileTokenCard(rates.base, rates.tiers, source)
596 }
597 const familyOf = (rawId: string) => rawId.replace(/-preview.*$/, '')
598 const named = (rawId: string | undefined) =>
599 rawId !== undefined && doc.named.includes(rawId)
600 const priced = (pricing: RateCard, path?: string): PricedFacts => {
601 const factSources = tagDocsFacts({ pricing }, GEMINI_PRICING_URL, doc.hash)
602 if (path && factSources.pricing) {
603 factSources.pricing = { ...factSources.pricing, path }
604 }
605 return { pricing, factSources }
606 }
607 const lookup = (rawId: string): PricedFacts => {
608 // `gemini-2.5-flash-preview-09-2025` is priced by its family row.
609 const family = familyOf(rawId)
610 const own = card(rawId) ?? (family === rawId ? null : card(family))
611 if (own) return priced(own)
612 // One hop, and only when the deprecations page says requests are
613 // automatically routed. The successor's own family card counts; its
614 // replacement does not.
615 const target = routeTo.get(rawId)
616 const targetFamily = target === undefined ? undefined : familyOf(target)
617 const pricedId =
618 target !== undefined && card(target)
619 ? target
620 : targetFamily !== undefined &&
621 targetFamily !== target &&
622 card(targetFamily)
623 ? targetFamily
624 : null
625 if (pricedId) {
626 const pricing = card(pricedId)
627 return pricing ? priced(pricing, `routed to ${pricedId}`) : {}
628 }
629 // Routes unread: an id with no card of its own might still be routed.
630 // Keep the stored card. A page that loaded and does not name it is a clear.
631 return named(rawId) || named(family) || named(target) || named(targetFamily)
632 ? {}
633 : routes
634 ? { absent: { pricing: 'cleared' } }
635 : unavailable('pricing')
636 }
637 lookup.releasedOn = releasedOn
638 return lookup