Open History to see the last commit
1/**
2 * Facts Google states outside the pricing page and the model index
3 * (issue #497).
4 *
5 * A deprecations row that says API requests are automatically routed to
6 * one id is that id's Standard card. A recommended replacement is not.
7 * A changelog sentence that names a `-latest` alias binds that alias to
8 * one model, newest sentence first, and does not follow a later "points
9 * to". That alias is billed as the target, so it takes the target's price
10 * when it has none of its own. Gemma 4 sizes come from the model card's
11 * Supported Modalities cell; the card's "generating text output" sentence
12 * is the output. A deprecations table's Release date column is the model's
13 * release day, or the first of a month when the cell names only the month.
14 */
15import {
16 cachedDocs,
17 docsReport,
18 docsRun,
19 markdocTables,
20 parseDay,
21 tryDocs,
22} from './model-facts.ts'
23import { fetchText, sha256Text } from './types.ts'
24import type {
25 DocsFailures,
26 FactAbsence,
27 FactSource,
28 ModelFact,
29 ModelFactSources,
30} from './types.ts'
31
32export const GEMINI_DEPRECATIONS_URL =
33 'https://aistudio.google.com/docs/deprecations.md'
34
35export const GEMINI_CHANGELOG_URL =
36 'https://aistudio.google.com/docs/changelog.md'
37
38/** Served as HTML only: the `.md.txt` mirror is gone (issue #568). */
39export const GEMMA_MODEL_CARD_URL =
40 'https://ai.google.dev/gemma/docs/core/model_card_4'
41
42const CHANGELOG_MARK = 'This page documents updates to the Gemini API'
43
44/** Opening sentence of the deprecations page. An error document lacks it. */
45const DEPRECATIONS_MARK = 'This page lists the known deprecation schedules'
46
47const ID = String.raw`[a-z0-9][a-z0-9.-]+`
48
49export interface GemmaModalities {
50 input: Array<string>
51 output: Array<string>
52}
53
54/** `source` → the one id API requests are automatically routed to. */
55export function parseAutomaticRoutes(text: string): Map<string, string> {
56 const routes = new Map<string, string>()
57 const targetOf =
58 /automatically (?:routed to|routes api requests to) `([a-z0-9][a-z0-9.-]+)`/i
59 for (const chunk of text.split(/\n\s*\n/)) {
60 const lines = chunk.includes('|') ? chunk.split('\n') : [chunk]
61 for (const line of lines) {
62 const target = targetOf.exec(line)?.[1]
63 if (!target) continue
64 const ids = [...line.matchAll(new RegExp(`\`(${ID})\``, 'gi'))].map(
65 (match) => match[1] ?? '',
66 )
67 const sources = [
68 ...new Set(ids.filter((id) => id !== '' && id !== target)),
69 ]
70 const source = sources.length === 1 ? sources[0] : undefined
71 if (!source || routes.has(source)) continue
72 routes.set(source, target)
73 }
74 }
75 return routes
76}
77
78/**
79 * `October 13, 2026` → that day. `August 2026` → the first of the month,
80 * the same grain as a preview id's `-MM-YYYY` suffix. Anything else is
81 * not a date this page stated.
82 */
83function statedReleaseDay(cell: string): string | null {
84 const text = cell.trim()
85 const day = parseDay(text)
86 if (day !== null) return new Date(day).toISOString().slice(0, 10)
87 const month = /^([A-Za-z]+) (\d{4})$/.exec(text)
88 if (!month?.[1] || !month[2]) return null
89 const first = parseDay(`${month[1]} 1, ${month[2]}`)
90 return first === null ? null : new Date(first).toISOString().slice(0, 10)
91}
92
93/**
94 * Model id → `YYYY-MM-DD` from a Release date column. An id mentioned only
95 * inside parentheses (a route target in the model cell) is not that row's
96 * model. The first table that dates an id wins; the page does not disagree
97 * with itself.
98 */
99export function parseGeminiReleaseDates(markdown: string): Map<string, string> {
100 const out = new Map<string, string>()
101 let releaseCol = -1
102 for (const line of markdocTables(markdown).split('\n')) {
103 if (!line.startsWith('|')) {
104 releaseCol = -1
105 continue
106 }
107 const columns = line
108 .split('|')
109 .slice(1, -1)
110 .map((cell) => cell.trim())
111 if (columns.some((cell) => /release date/i.test(cell))) {
112 releaseCol = columns.findIndex((cell) => /release date/i.test(cell))
113 continue
114 }
115 if (releaseCol < 0 || columns.every((cell) => /^:?-+:?$/.test(cell))) {
116 continue
117 }
118 const date = statedReleaseDay(columns[releaseCol] ?? '')
119 if (!date) continue
120 const subject = (columns[0] ?? '').replace(/\([^)]*\)/g, '')
121 for (const match of subject.matchAll(/`([a-z0-9][a-z0-9.-]+)`/g)) {
122 const id = match[1]
123 if (id && !out.has(id)) out.set(id, date)
124 }
125 }
126 return out
127}
128
129/**
130 * `-latest` alias → the model the changelog says it is. The file is
131 * newest first; the first sentence wins. An alias with no sentence is
132 * absent. "points to" is not an alias.
133 */
134export function parseChangelogAliases(markdown: string): Map<string, string> {
135 if (!markdown.includes(CHANGELOG_MARK)) {
136 throw new Error('gemini changelog: not the Gemini API changelog')
137 }
138 const aliases = new Map<string, string>()
139 const set = (alias: string, target: string) => {
140 if (!alias.includes('latest') || alias === target || aliases.has(alias)) {
141 return
142 }
143 aliases.set(alias, target)
144 }
145 for (const item of markdown.split(/\n(?=\s*- )/)) {
146 for (const line of item.split('\n')) {
147 const switched = line.match(
148 new RegExp(`\`(${ID})\` switched to \`(${ID})\``, 'i'),
149 )
150 if (switched?.[1] && switched[2]) set(switched[1], switched[2])
151 }
152 const behind = item.match(
153 new RegExp(String.raw`model behind \`(${ID})\``, 'i'),
154 )
155 const alias = behind?.[1]
156 if (!alias) continue
157 const others = [
158 ...new Set(
159 [...item.matchAll(/`(gemini-[a-z0-9][a-z0-9.-]*)`/gi)]
160 .map((match) => match[1] ?? '')
161 .filter((id) => id !== '' && id !== alias),
162 ),
163 ]
164 const target = others.length === 1 ? others[0] : undefined
165 if (target) set(alias, target)
166 }
167 return aliases
168}
169
170const GEMMA_MEDIA: Record<string, string> = {
171 text: 'text',
172 image: 'image',
173 audio: 'audio',
174 video: 'video',
175}
176const GEMMA_MEDIA_ORDER = ['text', 'image', 'audio', 'video']
177
178function cells(line: string): Array<string> {
179 return line
180 .split('|')
181 .slice(1, -1)
182 .map((cell) => cell.trim())
183}
184
185/** Each HTML `<table>` as `| a | b |` lines, one per `<tr>`. */
186export function htmlTables(html: string): string {
187 return html.replace(
188 /<table[^>]*>([\s\S]*?)<\/table>/g,
189 (_table, body: string) =>
190 `\n${[...body.matchAll(/<tr[^>]*>([\s\S]*?)<\/tr>/g)]
191 .map(
192 ([, row = '']) =>
193 `| ${[...row.matchAll(/<t[hd][^>]*>([\s\S]*?)<\/t[hd]>/g)]
194 .map(([, cell = '']) =>
195 cell
196 .replace(/<[^>]*>/g, '')
197 .replace(/\s+/g, ' ')
198 .trim(),
199 )
200 .join(' | ')} |`,
201 )
202 .join('\n')}\n`,
203 )
204}
205
206function gemmaId(header: string): string | null {
207 const clean = header.replace(/[*_`]/g, '').trim()
208 const size = /(?:^|[^a-z])(\d+)\s*b/i.exec(clean)
209 if (!size?.[1]) return null
210 const kind = /a4b/i.test(clean) ? `${size[1]}b-a4b` : `${size[1]}b`
211 return `gemma-4-${kind}-it`
212}
213
214function gemmaInputs(cell: string): Array<string> {
215 const found = new Set<string>()
216 const items = cell
217 .replace(/[*_`]/g, '')
218 .split(/,|\band\b/i)
219 .map((item) => item.trim().toLowerCase())
220 .filter((item) => item !== '')
221 for (const item of items) {
222 const medium = GEMMA_MEDIA[item]
223 if (!medium) throw new Error(`gemma model card: unknown modality "${item}"`)
224 found.add(medium)
225 }
226 if (found.size === 0) throw new Error('gemma model card: empty modality cell')
227 return GEMMA_MEDIA_ORDER.filter((medium) => found.has(medium))
228}
229
230/**
231 * Size column → input from that Supported Modalities cell, output text.
232 * No such row is an empty map. A row that names no size, or a word that
233 * is not a medium, throws. "E2B" is not a 2B model.
234 */
235export function parseGemmaModalities(
236 markdown: string,
237): Map<string, GemmaModalities> {
238 const out = new Map<string, GemmaModalities>()
239 if (!/^\|.*Supported Modalities/im.test(markdown)) return out
240 if (!/generating text output/i.test(markdown)) {
241 throw new Error(
242 'gemma model card: Supported Modalities without a text-output sentence',
243 )
244 }
245 const lines = markdown.split('\n')
246 for (let i = 0; i < lines.length; i++) {
247 const headerLine = lines[i] ?? ''
248 if (!/^\|\s*Property\s*\|/i.test(headerLine)) continue
249 const headers = cells(headerLine)
250 let modalities: Array<string> | null = null
251 for (let j = i + 1; j < lines.length; j++) {
252 const line = lines[j] ?? ''
253 if (!line.startsWith('|')) break
254 if (/^\|\s*\**Supported Modalities\**/i.test(line)) {
255 modalities = cells(line)
256 break
257 }
258 }
259 if (!modalities) continue
260 let bound = 0
261 for (let column = 1; column < headers.length; column++) {
262 const id = gemmaId(headers[column] ?? '')
263 if (!id) continue
264 const cell = (modalities[column] ?? '').replace(/[*_`]/g, '').trim()
265 if (cell === '' || cell === '-' || cell === '—' || /^n\/a$/i.test(cell)) {
266 continue
267 }
268 out.set(id, { input: gemmaInputs(cell), output: ['text'] })
269 bound++
270 }
271 if (bound === 0) {
272 throw new Error(
273 'gemma model card: Supported Modalities row did not bind a model',
274 )
275 }
276 }
277 if (out.size === 0) {
278 throw new Error(
279 'gemma model card: Supported Modalities row did not bind a model',
280 )
281 }
282 return out
283}
284
285/** What the Gemma 4 card's header states about every size it binds. */
286export interface GemmaCardFacts {
287 /** The "Authors" line, as written. Null when the card has none. */
288 maker: string | null
289 /** True when the card says the release includes open-weights models. */
290 openWeights: boolean | null
291 /** The header's "Hugging Face" link, only with `openWeights`. */
292 weightsUrl: string | null
293}
294
295/**
296 * Maker and weights from the card header (issue #710): `Authors : Google
297 * DeepMind`, the "includes open-weights models" sentence, and the header's
298 * Hugging Face link. Nothing here is inferred from the name Gemma.
299 */
300export function parseGemmaCardFacts(html: string): GemmaCardFacts {
301 const maker =
302 /<strong>Authors<\/strong>\s*:\s*(?:<a [^>]*>)?([^<|]+)/i
303 .exec(html)?.[1]
304 ?.trim() ?? ''
305 const openWeights = /includes open-weights models/i.test(
306 html.replace(/\s+/g, ' '),
307 )
308 ? true
309 : null
310 const weightsUrl = openWeights
311 ? (/<a href="(https:\/\/huggingface\.co\/[^"]+)">Hugging Face<\/a>/.exec(
312 html,
313 )?.[1] ?? null)
314 : null
315 return { maker: maker === '' ? null : maker, openWeights, weightsUrl }
316}
317
318export interface GeminiDeprecationFacts {
319 routes: Record<string, string>
320 /** Model id → `YYYY-MM-DD`. Empty when a cached doc predates the column. */
321 released: Record<string, string>
322}
323
324/**
325 * Throws when the fetch fails or the body is not the deprecations page.
326 * A real page that names no automatic route returns empty `routes`, and
327 * the poll may then clear those cards. `geminiModelPricing` loads this
328 * through `tryDocs`, so a throw keeps stored cards instead of failing
329 * the poll.
330 */
331export async function geminiAutomaticRoutes(
332 kv?: KVNamespace,
333 cached: typeof cachedDocs = cachedDocs,
334): Promise<GeminiDeprecationFacts> {
335 const doc = await cached(kv, GEMINI_DEPRECATIONS_URL, async () => {
336 const markdown = await fetchText(GEMINI_DEPRECATIONS_URL)
337 if (!markdown.includes(DEPRECATIONS_MARK)) {
338 throw new Error(
339 'gemini deprecations: not the Gemini API deprecations page',
340 )
341 }
342 return {
343 routes: Object.fromEntries(parseAutomaticRoutes(markdown)),
344 released: Object.fromEntries(parseGeminiReleaseDates(markdown)),
345 hash: await sha256Text(markdown),
346 }
347 })
348 // A hit cached before the Release date column was stored has no
349 // `released`. The next refresh fills it; until then dates stay empty.
350 return { routes: doc.routes, released: cachedReleaseDates(doc) }
351}
352
353function cachedReleaseDates(doc: {
354 released?: Record<string, string>
355}): Record<string, string> {
356 return doc.released ?? {}
357}
358
359export interface GeminiPublishedBindings {
360 /** Null when the changelog could not be read. `{}` means it names none. */
361 aliases: Record<string, string> | null
362 changelog: { url: string; hash: string }
363 /** Null when the model card could not be read. */
364 gemma: Record<string, GemmaModalities> | null
365 /** Null when the model card could not be read. */
366 gemmaCard: GemmaCardFacts | null
367 gemmaSource: { url: string; hash: string }
368 docsFailures: DocsFailures
369}
370
371export async function geminiPublishedBindings(
372 kv?: KVNamespace,
373): Promise<GeminiPublishedBindings> {
374 const run = docsRun()
375 const [changelog, gemma] = await Promise.all([
376 tryDocs(run, GEMINI_CHANGELOG_URL, (cached) =>
377 cached(kv, GEMINI_CHANGELOG_URL, async () => {
378 const markdown = await fetchText(GEMINI_CHANGELOG_URL)
379 return {
380 aliases: Object.fromEntries(parseChangelogAliases(markdown)),
381 hash: await sha256Text(markdown),
382 }
383 }),
384 ),
385 tryDocs(run, GEMMA_MODEL_CARD_URL, (cached) =>
386 cached(kv, GEMMA_MODEL_CARD_URL, async () => {
387 const markdown = await fetchText(GEMMA_MODEL_CARD_URL)
388 if (!markdown.includes('Gemma 4')) {
389 throw new Error('gemma model card: not the Gemma 4 card')
390 }
391 return {
392 modalities: Object.fromEntries(
393 parseGemmaModalities(htmlTables(markdown)),
394 ),
395 card: parseGemmaCardFacts(markdown),
396 hash: await sha256Text(markdown),
397 }
398 }),
399 ),
400 ])
401 return {
402 aliases: changelog ? changelog.aliases : null,
403 changelog: {
404 url: GEMINI_CHANGELOG_URL,
405 hash: changelog?.hash ?? '',
406 },
407 gemma: gemma ? gemma.modalities : null,
408 gemmaCard: gemma ? gemma.card : null,
409 gemmaSource: { url: GEMMA_MODEL_CARD_URL, hash: gemma?.hash ?? '' },
410 docsFailures: docsReport(run),
411 }
412}
413
414interface FactRow {
415 rawId: string
416 modalities?: unknown
417 aliases?: Array<string> | null
418 aliasOf?: string | null
419 maker?: string | null
420 openWeights?: boolean | null
421 weightsUrl?: string | null
422 pricing?: unknown
423 serverTools?: Array<string> | null
424 factSources?: ModelFactSources
425 absent?: Partial<Record<ModelFact, FactAbsence>>
426}
427
428function sourceHash(hash: string | undefined): { sourceHash?: string } {
429 return hash ? { sourceHash: hash } : {}
430}
431
432/**
433 * Copy a published Gemma cell, then a changelog alias's modalities and
434 * server tools, onto rows that still have none. A failed document keeps stored modalities
435 * (`unavailable`) instead of clearing them.
436 */
437export function attachGeminiPublishedFacts<T extends FactRow>(
438 models: Array<T>,
439 bindings: GeminiPublishedBindings,
440): Array<T> {
441 const byId = new Map(models.map((model) => [model.rawId, { ...model }]))
442 const put = (model: T) => {
443 byId.set(model.rawId, model)
444 }
445
446 const rawIds = Array.from(byId.keys())
447 if (bindings.gemma && bindings.gemmaCard) {
448 // The card's header speaks for every size its table binds.
449 const card = bindings.gemmaCard
450 const source = (path: string) => ({
451 derivation: 'docs-derived' as const,
452 sourceUrl: bindings.gemmaSource.url,
453 ...sourceHash(bindings.gemmaSource.hash),
454 path,
455 })
456 for (const rawId of rawIds) {
457 const model = byId.get(rawId)
458 if (!model || !(rawId in bindings.gemma)) continue
459 put({
460 ...model,
461 maker: card.maker,
462 openWeights: card.openWeights,
463 weightsUrl: card.weightsUrl,
464 factSources: {
465 ...model.factSources,
466 maker: source(card.maker === null ? 'unstated' : 'Authors'),
467 ...(card.openWeights === null
468 ? {}
469 : { openWeights: source('open-weights models; Hugging Face') }),
470 },
471 })
472 }
473 } else if (!bindings.gemma) {
474 // No card: keep what it stated before on every row it may bind.
475 for (const rawId of rawIds) {
476 const model = byId.get(rawId)
477 if (!model) continue
478 put({
479 ...model,
480 absent: {
481 ...model.absent,
482 maker: 'unavailable',
483 openWeights: 'unavailable',
484 },
485 })
486 }
487 }
488 if (bindings.gemma) {
489 for (const rawId of rawIds) {
490 const model = byId.get(rawId)
491 const modalities = model ? bindings.gemma[rawId] : undefined
492 if (!model || model.modalities != null || !modalities) continue
493 put({
494 ...model,
495 modalities,
496 factSources: {
497 ...model.factSources,
498 modalities: {
499 derivation: 'docs-derived',
500 sourceUrl: bindings.gemmaSource.url,
501 ...sourceHash(bindings.gemmaSource.hash),
502 path: 'Supported Modalities',
503 },
504 },
505 })
506 }
507 }
508
509 if (bindings.aliases) {
510 const changelogSource = (path: string) => ({
511 derivation: 'docs-derived' as const,
512 sourceUrl: bindings.changelog.url,
513 ...sourceHash(bindings.changelog.hash),
514 path,
515 })
516 // A `-latest` row the changelog names no target for (issue #709). The
517 // link itself comes only from a changelog sentence, never the id.
518 for (const rawId of rawIds) {
519 const model = byId.get(rawId)
520 if (!model || !rawId.includes('latest') || rawId in bindings.aliases) {
521 continue
522 }
523 put({
524 ...model,
525 aliasOf: null,
526 factSources: {
527 ...model.factSources,
528 aliasOf: changelogSource('unstated'),
529 },
530 })
531 }
532 for (const [alias, targetId] of Object.entries(bindings.aliases)) {
533 const stated = byId.get(alias)
534 // The stated target is kept even while it is not listed; the catalog
535 // serves the link only while that row is live.
536 if (stated) {
537 put({
538 ...stated,
539 aliasOf: targetId,
540 factSources: {
541 ...stated.factSources,
542 aliasOf: changelogSource('latest alias'),
543 },
544 })
545 }
546 const aliasRow = byId.get(alias)
547 const target = byId.get(targetId)
548 if (!aliasRow || !target) continue
549 if (aliasRow.modalities == null && target.modalities != null) {
550 const prior = target.factSources?.modalities
551 put({
552 ...aliasRow,
553 modalities: target.modalities,
554 factSources: {
555 ...aliasRow.factSources,
556 modalities: {
557 derivation: 'docs-derived',
558 sourceUrl: prior?.sourceUrl ?? bindings.changelog.url,
559 ...sourceHash(prior?.sourceHash ?? bindings.changelog.hash),
560 path: `Supported data types; alias of ${targetId}`,
561 },
562 },
563 })
564 }
565 // The alias is the target model, so the target page's tools are its
566 // own (#707). A silent target stays the alias's silence, and an
567 // unread one leaves the alias unread.
568 const aliasTools = byId.get(alias)
569 if (aliasTools && aliasTools.serverTools == null) {
570 const prior = target.factSources?.serverTools
571 const tools = target.serverTools ?? null
572 const sources =
573 tools && tools.length > 0 && prior
574 ? Object.fromEntries(
575 Object.entries(prior as Record<string, FactSource>).map(
576 ([tool, source]) => [
577 tool,
578 { ...source, path: `${source.path}; alias of ${targetId}` },
579 ],
580 ),
581 )
582 : prior?.derivation === 'source-silent'
583 ? prior
584 : undefined
585 if (sources) {
586 put({
587 ...aliasTools,
588 ...(tools && tools.length > 0 ? { serverTools: tools } : {}),
589 factSources: { ...aliasTools.factSources, serverTools: sources },
590 })
591 } else if (target.absent?.serverTools === 'unavailable') {
592 // The target's page failed: the alias keeps its stored tools too.
593 put({
594 ...aliasTools,
595 absent: { ...aliasTools.absent, serverTools: 'unavailable' },
596 })
597 }
598 }
599 const current = byId.get(targetId)
600 if (!current) continue
601 put({
602 ...current,
603 aliases: [...new Set([...(current.aliases ?? []), alias])].sort(),
604 factSources: {
605 ...current.factSources,
606 aliases: changelogSource('latest alias'),
607 },
608 })
609 const priced = byId.get(targetId)
610 const aliasNow = byId.get(alias)
611 if (
612 !aliasNow ||
613 !priced ||
614 aliasNow.pricing != null ||
615 priced.pricing == null
616 ) {
617 continue
618 }
619 const prior = priced.factSources?.pricing
620 const absent = { ...aliasNow.absent }
621 delete absent.pricing
622 const next: T = {
623 ...aliasNow,
624 pricing: priced.pricing,
625 factSources: {
626 ...aliasNow.factSources,
627 pricing: {
628 derivation: 'docs-derived',
629 sourceUrl: prior?.sourceUrl ?? bindings.changelog.url,
630 ...sourceHash(
631 prior?.sourceUrl ? prior.sourceHash : bindings.changelog.hash,
632 ),
633 path: prior?.path
634 ? `${prior.path}; alias of ${targetId}`
635 : `alias of ${targetId}`,
636 },
637 },
638 }
639 if (Object.keys(absent).length > 0) next.absent = absent
640 else delete next.absent
641 put(next)
642 }
643 } else {
644 for (const rawId of rawIds) {
645 const model = byId.get(rawId)
646 if (!model) continue
647 // Every alias link comes from the changelog: keep the stored ones.
648 const absent: Partial<Record<ModelFact, FactAbsence>> = {
649 ...model.absent,
650 aliases: 'unavailable',
651 }
652 if (rawId.includes('latest')) {
653 absent.aliasOf = 'unavailable'
654 if (model.modalities == null) absent.modalities = 'unavailable'
655 if (model.serverTools == null) absent.serverTools = 'unavailable'
656 }
657 put({ ...model, absent })
658 }
659 }
660
661 if (!bindings.gemma) {
662 for (const rawId of rawIds) {
663 const model = byId.get(rawId)
664 if (!model || !rawId.startsWith('gemma-4-') || model.modalities != null) {
665 continue
666 }
667 put({
668 ...model,
669 absent: { ...model.absent, modalities: 'unavailable' },
670 })
671 }
672 }
673
674 return models.map((model) => byId.get(model.rawId) ?? model)
675}