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

gemini-bindings.ts

513 lines16.3 KB

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 ModelFact,
28 ModelFactSources,
29} from './types.ts'
30​
31export const GEMINI_DEPRECATIONS_URL =
32 'https://aistudio.google.com/docs/deprecations.md'
33​
34export const GEMINI_CHANGELOG_URL =
35 'https://aistudio.google.com/docs/changelog.md'
36​
37/** Served as HTML only: the `.md.txt` mirror is gone (issue #568). */
38export const GEMMA_MODEL_CARD_URL =
39 'https://ai.google.dev/gemma/docs/core/model_card_4'
40​
41const CHANGELOG_MARK = 'This page documents updates to the Gemini API'
42​
43/** Opening sentence of the deprecations page. An error document lacks it. */
44const DEPRECATIONS_MARK = 'This page lists the known deprecation schedules'
45​
46const ID = String.raw`[a-z0-9][a-z0-9.-]+`
47​
48export interface GemmaModalities {
49 input: Array<string>
50 output: Array<string>
52​
53/** `source` → the one id API requests are automatically routed to. */
54export function parseAutomaticRoutes(text: string): Map<string, string> {
55 const routes = new Map<string, string>()
56 const targetOf =
57 /automatically (?:routed to|routes api requests to) `([a-z0-9][a-z0-9.-]+)`/i
58 for (const chunk of text.split(/\n\s*\n/)) {
59 const lines = chunk.includes('|') ? chunk.split('\n') : [chunk]
60 for (const line of lines) {
61 const target = targetOf.exec(line)?.[1]
62 if (!target) continue
63 const ids = [...line.matchAll(new RegExp(`\`(${ID})\``, 'gi'))].map(
64 (match) => match[1] ?? '',
65 )
66 const sources = [
67 ...new Set(ids.filter((id) => id !== '' && id !== target)),
68 ]
69 const source = sources.length === 1 ? sources[0] : undefined
70 if (!source || routes.has(source)) continue
71 routes.set(source, target)
72 }
73 }
74 return routes
76​
77/**
78 * `October 13, 2026` → that day. `August 2026` → the first of the month,
79 * the same grain as a preview id's `-MM-YYYY` suffix. Anything else is
80 * not a date this page stated.
81 */
82function statedReleaseDay(cell: string): string | null {
83 const text = cell.trim()
84 const day = parseDay(text)
85 if (day !== null) return new Date(day).toISOString().slice(0, 10)
86 const month = /^([A-Za-z]+) (\d{4})$/.exec(text)
87 if (!month?.[1] || !month[2]) return null
88 const first = parseDay(`${month[1]} 1, ${month[2]}`)
89 return first === null ? null : new Date(first).toISOString().slice(0, 10)
91​
92/**
93 * Model id → `YYYY-MM-DD` from a Release date column. An id mentioned only
94 * inside parentheses (a route target in the model cell) is not that row's
95 * model. The first table that dates an id wins; the page does not disagree
96 * with itself.
97 */
98export function parseGeminiReleaseDates(markdown: string): Map<string, string> {
99 const out = new Map<string, string>()
100 let releaseCol = -1
101 for (const line of markdocTables(markdown).split('\n')) {
102 if (!line.startsWith('|')) {
103 releaseCol = -1
104 continue
105 }
106 const columns = line
107 .split('|')
108 .slice(1, -1)
109 .map((cell) => cell.trim())
110 if (columns.some((cell) => /release date/i.test(cell))) {
111 releaseCol = columns.findIndex((cell) => /release date/i.test(cell))
112 continue
113 }
114 if (releaseCol < 0 || columns.every((cell) => /^:?-+:?$/.test(cell))) {
115 continue
116 }
117 const date = statedReleaseDay(columns[releaseCol] ?? '')
118 if (!date) continue
119 const subject = (columns[0] ?? '').replace(/\([^)]*\)/g, '')
120 for (const match of subject.matchAll(/`([a-z0-9][a-z0-9.-]+)`/g)) {
121 const id = match[1]
122 if (id && !out.has(id)) out.set(id, date)
123 }
124 }
125 return out
127​
128/**
129 * `-latest` alias → the model the changelog says it is. The file is
130 * newest first; the first sentence wins. An alias with no sentence is
131 * absent. "points to" is not an alias.
132 */
133export function parseChangelogAliases(markdown: string): Map<string, string> {
134 if (!markdown.includes(CHANGELOG_MARK)) {
135 throw new Error('gemini changelog: not the Gemini API changelog')
136 }
137 const aliases = new Map<string, string>()
138 const set = (alias: string, target: string) => {
139 if (!alias.includes('latest') || alias === target || aliases.has(alias)) {
140 return
141 }
142 aliases.set(alias, target)
143 }
144 for (const item of markdown.split(/\n(?=\s*- )/)) {
145 for (const line of item.split('\n')) {
146 const switched = line.match(
147 new RegExp(`\`(${ID})\` switched to \`(${ID})\``, 'i'),
148 )
149 if (switched?.[1] && switched[2]) set(switched[1], switched[2])
150 }
151 const behind = item.match(
152 new RegExp(String.raw`model behind \`(${ID})\``, 'i'),
153 )
154 const alias = behind?.[1]
155 if (!alias) continue
156 const others = [
157 ...new Set(
158 [...item.matchAll(/`(gemini-[a-z0-9][a-z0-9.-]*)`/gi)]
159 .map((match) => match[1] ?? '')
160 .filter((id) => id !== '' && id !== alias),
161 ),
162 ]
163 const target = others.length === 1 ? others[0] : undefined
164 if (target) set(alias, target)
165 }
166 return aliases
168​
169const GEMMA_MEDIA: Record<string, string> = {
170 text: 'text',
171 image: 'image',
172 audio: 'audio',
173 video: 'video',
175const GEMMA_MEDIA_ORDER = ['text', 'image', 'audio', 'video']
176​
177function cells(line: string): Array<string> {
178 return line
179 .split('|')
180 .slice(1, -1)
181 .map((cell) => cell.trim())
183​
184/** Each HTML `<table>` as `| a | b |` lines, one per `<tr>`. */
185export function htmlTables(html: string): string {
186 return html.replace(
187 /<table[^>]*>([\s\S]*?)<\/table>/g,
188 (_table, body: string) =>
189 `\n${[...body.matchAll(/<tr[^>]*>([\s\S]*?)<\/tr>/g)]
190 .map(
191 ([, row = '']) =>
192 `| ${[...row.matchAll(/<t[hd][^>]*>([\s\S]*?)<\/t[hd]>/g)]
193 .map(([, cell = '']) =>
194 cell
195 .replace(/<[^>]*>/g, '')
196 .replace(/\s+/g, ' ')
197 .trim(),
198 )
199 .join(' | ')} |`,
200 )
201 .join('\n')}\n`,
202 )
204​
205function gemmaId(header: string): string | null {
206 const clean = header.replace(/[*_`]/g, '').trim()
207 const size = /(?:^|[^a-z])(\d+)\s*b/i.exec(clean)
208 if (!size?.[1]) return null
209 const kind = /a4b/i.test(clean) ? `${size[1]}b-a4b` : `${size[1]}b`
210 return `gemma-4-${kind}-it`
212​
213function gemmaInputs(cell: string): Array<string> {
214 const found = new Set<string>()
215 const items = cell
216 .replace(/[*_`]/g, '')
217 .split(/,|\band\b/i)
218 .map((item) => item.trim().toLowerCase())
219 .filter((item) => item !== '')
220 for (const item of items) {
221 const medium = GEMMA_MEDIA[item]
222 if (!medium) throw new Error(`gemma model card: unknown modality "${item}"`)
223 found.add(medium)
224 }
225 if (found.size === 0) throw new Error('gemma model card: empty modality cell')
226 return GEMMA_MEDIA_ORDER.filter((medium) => found.has(medium))
228​
229/**
230 * Size column → input from that Supported Modalities cell, output text.
231 * No such row is an empty map. A row that names no size, or a word that
232 * is not a medium, throws. "E2B" is not a 2B model.
233 */
234export function parseGemmaModalities(
235 markdown: string,
236): Map<string, GemmaModalities> {
237 const out = new Map<string, GemmaModalities>()
238 if (!/^\|.*Supported Modalities/im.test(markdown)) return out
239 if (!/generating text output/i.test(markdown)) {
240 throw new Error(
241 'gemma model card: Supported Modalities without a text-output sentence',
242 )
243 }
244 const lines = markdown.split('\n')
245 for (let i = 0; i < lines.length; i++) {
246 const headerLine = lines[i] ?? ''
247 if (!/^\|\s*Property\s*\|/i.test(headerLine)) continue
248 const headers = cells(headerLine)
249 let modalities: Array<string> | null = null
250 for (let j = i + 1; j < lines.length; j++) {
251 const line = lines[j] ?? ''
252 if (!line.startsWith('|')) break
253 if (/^\|\s*\**Supported Modalities\**/i.test(line)) {
254 modalities = cells(line)
255 break
256 }
257 }
258 if (!modalities) continue
259 let bound = 0
260 for (let column = 1; column < headers.length; column++) {
261 const id = gemmaId(headers[column] ?? '')
262 if (!id) continue
263 const cell = (modalities[column] ?? '').replace(/[*_`]/g, '').trim()
264 if (cell === '' || cell === '-' || cell === '—' || /^n\/a$/i.test(cell)) {
265 continue
266 }
267 out.set(id, { input: gemmaInputs(cell), output: ['text'] })
268 bound++
269 }
270 if (bound === 0) {
271 throw new Error(
272 'gemma model card: Supported Modalities row did not bind a model',
273 )
274 }
275 }
276 if (out.size === 0) {
277 throw new Error(
278 'gemma model card: Supported Modalities row did not bind a model',
279 )
280 }
281 return out
283​
284export interface GeminiDeprecationFacts {
285 routes: Record<string, string>
286 /** Model id → `YYYY-MM-DD`. Empty when a cached doc predates the column. */
287 released: Record<string, string>
289​
290/**
291 * Throws when the fetch fails or the body is not the deprecations page.
292 * A real page that names no automatic route returns empty `routes`, and
293 * the poll may then clear those cards. `geminiModelPricing` loads this
294 * through `tryDocs`, so a throw keeps stored cards instead of failing
295 * the poll.
296 */
297export async function geminiAutomaticRoutes(
298 kv?: KVNamespace,
299 cached: typeof cachedDocs = cachedDocs,
300): Promise<GeminiDeprecationFacts> {
301 const doc = await cached(kv, GEMINI_DEPRECATIONS_URL, async () => {
302 const markdown = await fetchText(GEMINI_DEPRECATIONS_URL)
303 if (!markdown.includes(DEPRECATIONS_MARK)) {
304 throw new Error(
305 'gemini deprecations: not the Gemini API deprecations page',
306 )
307 }
308 return {
309 routes: Object.fromEntries(parseAutomaticRoutes(markdown)),
310 released: Object.fromEntries(parseGeminiReleaseDates(markdown)),
311 hash: await sha256Text(markdown),
312 }
313 })
314 // A hit cached before the Release date column was stored has no
315 // `released`. The next refresh fills it; until then dates stay empty.
316 return { routes: doc.routes, released: cachedReleaseDates(doc) }
318​
319function cachedReleaseDates(doc: {
320 released?: Record<string, string>
321}): Record<string, string> {
322 return doc.released ?? {}
324​
325export interface GeminiPublishedBindings {
326 /** Null when the changelog could not be read. `{}` means it names none. */
327 aliases: Record<string, string> | null
328 changelog: { url: string; hash: string }
329 /** Null when the model card could not be read. */
330 gemma: Record<string, GemmaModalities> | null
331 gemmaSource: { url: string; hash: string }
332 docsFailures: DocsFailures
334​
335export async function geminiPublishedBindings(
336 kv?: KVNamespace,
337): Promise<GeminiPublishedBindings> {
338 const run = docsRun()
339 const [changelog, gemma] = await Promise.all([
340 tryDocs(run, GEMINI_CHANGELOG_URL, (cached) =>
341 cached(kv, GEMINI_CHANGELOG_URL, async () => {
342 const markdown = await fetchText(GEMINI_CHANGELOG_URL)
343 return {
344 aliases: Object.fromEntries(parseChangelogAliases(markdown)),
345 hash: await sha256Text(markdown),
346 }
347 }),
348 ),
349 tryDocs(run, GEMMA_MODEL_CARD_URL, (cached) =>
350 cached(kv, GEMMA_MODEL_CARD_URL, async () => {
351 const markdown = await fetchText(GEMMA_MODEL_CARD_URL)
352 if (!markdown.includes('Gemma 4')) {
353 throw new Error('gemma model card: not the Gemma 4 card')
354 }
355 return {
356 modalities: Object.fromEntries(
357 parseGemmaModalities(htmlTables(markdown)),
358 ),
359 hash: await sha256Text(markdown),
360 }
361 }),
362 ),
363 ])
364 return {
365 aliases: changelog ? changelog.aliases : null,
366 changelog: {
367 url: GEMINI_CHANGELOG_URL,
368 hash: changelog?.hash ?? '',
369 },
370 gemma: gemma ? gemma.modalities : null,
371 gemmaSource: { url: GEMMA_MODEL_CARD_URL, hash: gemma?.hash ?? '' },
372 docsFailures: docsReport(run),
373 }
375​
376interface FactRow {
377 rawId: string
378 modalities?: unknown
379 aliases?: Array<string> | null
380 pricing?: unknown
381 factSources?: ModelFactSources
382 absent?: Partial<Record<ModelFact, FactAbsence>>
384​
385function sourceHash(hash: string | undefined): { sourceHash?: string } {
386 return hash ? { sourceHash: hash } : {}
388​
389/**
390 * Copy a published Gemma cell, then a changelog alias's modalities, onto
391 * rows that still have none. A failed document keeps stored modalities
392 * (`unavailable`) instead of clearing them.
393 */
394export function attachGeminiPublishedFacts<T extends FactRow>(
395 models: Array<T>,
396 bindings: GeminiPublishedBindings,
397): Array<T> {
398 const byId = new Map(models.map((model) => [model.rawId, { ...model }]))
399 const put = (model: T) => {
400 byId.set(model.rawId, model)
401 }
402​
403 const rawIds = Array.from(byId.keys())
404 if (bindings.gemma) {
405 for (const rawId of rawIds) {
406 const model = byId.get(rawId)
407 const modalities = model ? bindings.gemma[rawId] : undefined
408 if (!model || model.modalities != null || !modalities) continue
409 put({
410 ...model,
411 modalities,
412 factSources: {
413 ...model.factSources,
414 modalities: {
415 derivation: 'docs-derived',
416 sourceUrl: bindings.gemmaSource.url,
417 ...sourceHash(bindings.gemmaSource.hash),
418 path: 'Supported Modalities',
419 },
420 },
421 })
422 }
423 }
424​
425 if (bindings.aliases) {
426 for (const [alias, targetId] of Object.entries(bindings.aliases)) {
427 const aliasRow = byId.get(alias)
428 const target = byId.get(targetId)
429 if (!aliasRow || !target) continue
430 if (aliasRow.modalities == null && target.modalities != null) {
431 const prior = target.factSources?.modalities
432 put({
433 ...aliasRow,
434 modalities: target.modalities,
435 factSources: {
436 ...aliasRow.factSources,
437 modalities: {
438 derivation: 'docs-derived',
439 sourceUrl: prior?.sourceUrl ?? bindings.changelog.url,
440 ...sourceHash(prior?.sourceHash ?? bindings.changelog.hash),
441 path: `Supported data types; alias of ${targetId}`,
442 },
443 },
444 })
445 }
446 const current = byId.get(targetId)
447 if (!current) continue
448 put({
449 ...current,
450 aliases: [...new Set([...(current.aliases ?? []), alias])].sort(),
451 })
452 const priced = byId.get(targetId)
453 const aliasNow = byId.get(alias)
454 if (
455 !aliasNow ||
456 !priced ||
457 aliasNow.pricing != null ||
458 priced.pricing == null
459 ) {
460 continue
461 }
462 const prior = priced.factSources?.pricing
463 const absent = { ...aliasNow.absent }
464 delete absent.pricing
465 const next: T = {
466 ...aliasNow,
467 pricing: priced.pricing,
468 factSources: {
469 ...aliasNow.factSources,
470 pricing: {
471 derivation: 'docs-derived',
472 sourceUrl: prior?.sourceUrl ?? bindings.changelog.url,
473 ...sourceHash(
474 prior?.sourceUrl ? prior.sourceHash : bindings.changelog.hash,
475 ),
476 path: prior?.path
477 ? `${prior.path}; alias of ${targetId}`
478 : `alias of ${targetId}`,
479 },
480 },
481 }
482 if (Object.keys(absent).length > 0) next.absent = absent
483 else delete next.absent
484 put(next)
485 }
486 } else {
487 for (const rawId of rawIds) {
488 const model = byId.get(rawId)
489 if (!model || !rawId.includes('latest') || model.modalities != null) {
490 continue
491 }
492 put({
493 ...model,
494 absent: { ...model.absent, modalities: 'unavailable' },
495 })
496 }
497 }
498​
499 if (!bindings.gemma) {
500 for (const rawId of rawIds) {
501 const model = byId.get(rawId)
502 if (!model || !rawId.startsWith('gemma-4-') || model.modalities != null) {
503 continue
504 }
505 put({
506 ...model,
507 absent: { ...model.absent, modalities: 'unavailable' },
508 })
509 }
510 }
511​
512 return models.map((model) => byId.get(model.rawId) ?? model)