Open History to see the last commit
1/**
2 * Gemini Enterprise Agent Platform catalog (issue #203).
3 *
4 * `publishers.models.list` needs a service account. The locations page
5 * names the Google model ids that are served, and each model's card
6 * states limits, modalities, tools, and versions. The thinking page
7 * names `thinking_level` or `thinking_budget`. Partner models and Chirp
8 * are not this provider.
9 */
10import type { Activity } from '#/db/schema.ts'
11
12import { tagDocsFacts } from './fact-sources.ts'
13import {
14 assertParsed,
15 cachedDocs,
16 mapConcurrent,
17 parseDay,
18 tokenCount,
19} from './model-facts.ts'
20import { fetchText } from './types.ts'
21import type { ModelInfo, ModelReasoning } from './types.ts'
22import { normModelName } from './vertex-text.ts'
23import { vertexModelPricing } from './vertex-pricing.ts'
24
25export const VERTEX_LOCATIONS_URL =
26 'https://docs.cloud.google.com/gemini-enterprise-agent-platform/resources/locations'
27export const VERTEX_THINKING_URL =
28 'https://docs.cloud.google.com/gemini-enterprise-agent-platform/models/thinking'
29const DOCS = 'https://docs.cloud.google.com'
30
31const MODEL_ID = /^[a-z0-9][a-z0-9._-]*$/
32
33const ENDPOINT =
34 'v1/projects/{projectsId}/locations/{locationsId}/publishers/{publishersId}/models/{modelsId}'
35
36export interface LocationModel {
37 rawId: string
38 cardPath: string | null
39}
40
41export interface CardVersion {
42 rawId: string
43 releasedAt: number | null
44 deprecated: boolean
45}
46
47export interface VertexCard {
48 title: string
49 modelId: string | null
50 versions: Array<CardVersion>
51 contextWindow: number | null
52 maxOutput: number | null
53 modalities: { input: Array<string>; output: Array<string> } | null
54 capabilities: Array<string>
55 serverTools: Array<string>
56 /** `null` when the card has no Thinking row. */
57 thinkingSupported: boolean | null
58}
59
60export interface VertexThinking {
61 /** Normed card title → thinking_level values. */
62 effort: Map<string, Array<string>>
63 /** Normed card title → whether thinking can be turned off. */
64 budgetOff: Set<string>
65 budgetOn: Set<string>
66}
67
68function linesOf(html: string): Array<string> {
69 return html
70 .replace(/<script[\s\S]*?<\/script>/gi, ' ')
71 .replace(/<style[\s\S]*?<\/style>/gi, ' ')
72 .replace(/<[^>]+>/g, '\n')
73 .replace(/ /g, ' ')
74 .replace(/&/g, '&')
75 .replace(/'|'/g, "'")
76 .split('\n')
77 .map((line) => line.trim())
78 .filter((line) => line.length > 0)
79}
80
81function isModelId(id: string): boolean {
82 return (
83 MODEL_ID.test(id) &&
84 /^(gemini|veo|imagen|lyria|virtual-try-on|text-embedding|text-multilingual-embedding|multimodalembedding)/.test(
85 id,
86 ) &&
87 !id.startsWith('chirp')
88 )
89}
90
91function codeIds(raw: string): Array<string> {
92 const text = raw.replace(/<[^>]+>/g, '')
93 const quoted = [...text.matchAll(/'([a-z0-9][a-z0-9._-]*)'/g)].map(
94 (match) => match[1] ?? '',
95 )
96 if (quoted.length > 0) return quoted.filter((id) => id.length > 0)
97 const bare = text.replace(/[()[\]]/g, '').trim()
98 return bare ? [bare] : []
99}
100
101/** Google model ids in `#google-models`, each tied to the card linked above it. */
102export function parseLocationModels(html: string): Array<LocationModel> {
103 const start = html.indexOf('<h2 id="google-models"')
104 const end = html.indexOf('<h2 id="genai-partner-models"')
105 if (start < 0 || end < start) return []
106 const section = html.slice(start, end)
107 const found = new Map<string, string | null>()
108 let card: string | null = null
109 const re =
110 /href="(\/gemini-enterprise-agent-platform\/models\/(?:gemini|veo|vto)\/[^"#?]+)"|<code[^>]*>([\s\S]*?)<\/code>/g
111 for (const match of section.matchAll(re)) {
112 if (match[1]) {
113 card = match[1]
114 continue
115 }
116 for (const rawId of codeIds(match[2] ?? '')) {
117 if (!isModelId(rawId)) continue
118 const prior = found.get(rawId)
119 if (prior === undefined) found.set(rawId, card)
120 else if (prior === null && card) found.set(rawId, card)
121 }
122 card = null
123 }
124 return [...found].map(([rawId, cardPath]) => ({ rawId, cardPath }))
125}
126
127function sliceBetween(
128 lines: Array<string>,
129 start: string,
130 ends: Array<string>,
131 accept: (slice: Array<string>) => boolean,
132): Array<string> {
133 for (let index = 0; index < lines.length; index++) {
134 if (lines[index] !== start) continue
135 const end = lines.findIndex((line, at) => at > index && ends.includes(line))
136 const slice = lines.slice(index + 1, end < 0 ? index + 48 : end)
137 if (accept(slice)) return slice
138 }
139 return []
140}
141
142const MODALITY = new Set(['text', 'image', 'audio', 'video'])
143
144function modalitiesOf(lines: Array<string>): VertexCard['modalities'] {
145 const slice = sliceBetween(
146 lines,
147 'Modalities',
148 ['Token limits', 'Capabilities'],
149 (part) => part.some((line) => /input|output|not supported/i.test(line)),
150 )
151 const input: Array<string> = []
152 const output: Array<string> = []
153 for (let index = 0; index < slice.length; index++) {
154 const name = slice[index]?.toLowerCase()
155 if (!name || !MODALITY.has(name)) continue
156 const direction = slice
157 .slice(index + 1, index + 4)
158 .find((line) =>
159 /input and output|input only|output only|not supported/i.test(line),
160 )
161 if (!direction || /not supported/i.test(direction)) continue
162 if (/input/i.test(direction)) input.push(name)
163 if (/output/i.test(direction)) output.push(name)
164 }
165 if (input.length === 0 && output.length === 0) return null
166 return { input, output }
167}
168
169const SERVER_TOOLS: Record<string, string> = {
170 'code execution': 'codeExecution',
171 'url context': 'urlContext',
172 'computer use': 'computerUse',
173}
174
175function labelBefore(
176 slice: Array<string>,
177 index: number,
178): { label: string; detail: string } {
179 const collected: Array<string> = []
180 for (let at = index - 1; at >= 0 && collected.length < 2; at--) {
181 const line = slice[at] ?? ''
182 if (/^preview( feature)?$/i.test(line)) continue
183 collected.push(line)
184 }
185 const [nearest, prior] = collected
186 if (nearest?.includes(',') && prior) return { label: prior, detail: nearest }
187 return { label: nearest ?? '', detail: '' }
188}
189
190function flagsIn(slice: Array<string>): {
191 capabilities: Array<string>
192 serverTools: Array<string>
193 thinkingSupported: boolean | null
194} {
195 const capabilities: Array<string> = []
196 const serverTools: Array<string> = []
197 let thinkingSupported: boolean | null = null
198 for (let index = 0; index < slice.length; index++) {
199 const line = slice[index] ?? ''
200 if (!/^supported$/i.test(line) && !/^not supported$/i.test(line)) continue
201 const supported = /^supported$/i.test(line)
202 const { label, detail } = labelBefore(slice, index)
203 const name = label.toLowerCase()
204 if (name === 'thinking') thinkingSupported = supported
205 if (supported && name === 'structured output') {
206 capabilities.push('structured_outputs')
207 }
208 if (supported && name === 'function calling') capabilities.push('tools')
209 if (supported && name === 'grounding' && /google search/i.test(detail)) {
210 serverTools.push('googleSearch')
211 }
212 const tool = SERVER_TOOLS[name]
213 if (supported && tool) serverTools.push(tool)
214 }
215 const order = ['googleSearch', 'codeExecution', 'urlContext', 'computerUse']
216 return {
217 capabilities,
218 serverTools: order.filter((tool) => serverTools.includes(tool)),
219 thinkingSupported,
220 }
221}
222
223function versionsOf(lines: Array<string>): Array<CardVersion> {
224 const start = lines.findIndex(
225 (line, index) =>
226 line === 'Versions' &&
227 isModelId((lines[index + 1] ?? '').replace(/\*$/, '')),
228 )
229 if (start < 0) return []
230 const versions: Array<CardVersion> = []
231 let current: CardVersion | null = null
232 for (const line of lines.slice(start + 1)) {
233 if (
234 /^send feedback$|^except as otherwise noted$|^last updated\b/i.test(line)
235 ) {
236 break
237 }
238 const id = line.replace(/\*$/, '')
239 if (isModelId(id)) {
240 current = { rawId: id, releasedAt: null, deprecated: false }
241 versions.push(current)
242 continue
243 }
244 if (!current) continue
245 if (/^launch stage:/i.test(line) && /deprecated|retired/i.test(line)) {
246 current.deprecated = true
247 }
248 const released = /^release date:\s*(.+)$/i.exec(line)?.[1]
249 if (released) {
250 const day = parseDay(released)
251 if (day !== null) current.releasedAt = day / 1000
252 }
253 }
254 return versions
255}
256
257/** The model name is the text before the docs-site bookmark widget. */
258function pageTitle(html: string): string {
259 const inner = html.match(/<h1[^>]*>([\s\S]*?)<\/h1>/i)?.[1] ?? ''
260 const heading = inner.split(/<devsite-/i)[0] ?? ''
261 return heading
262 .replace(/<[^>]+>/g, ' ')
263 .replace(/\s+/g, ' ')
264 .trim()
265}
266
267export function parseCard(html: string): VertexCard {
268 const lines = linesOf(html)
269 const title = pageTitle(html)
270 const modelIdLine = lines.findIndex(
271 (line, index) =>
272 line === 'Model ID' &&
273 isModelId(lines[index + 1]?.replace(/\*$/, '') ?? ''),
274 )
275 const modelId =
276 modelIdLine < 0
277 ? null
278 : (lines[modelIdLine + 1]?.replace(/\*$/, '') ?? null)
279 const contextAt = lines.indexOf('Context window')
280 const outputAt = lines.indexOf('Maximum output tokens')
281 const capabilitySlice = [
282 ...sliceBetween(
283 lines,
284 'Capabilities',
285 ['Tools', 'Consumption options', 'Technical specifications'],
286 (part) =>
287 part.some(
288 (line) => /^supported$/i.test(line) || /^not supported$/i.test(line),
289 ),
290 ),
291 ...sliceBetween(
292 lines,
293 'Tools',
294 ['Consumption options', 'Technical specifications'],
295 (part) =>
296 part.some(
297 (line) => /^supported$/i.test(line) || /^not supported$/i.test(line),
298 ),
299 ),
300 ]
301 const flags = flagsIn(capabilitySlice)
302 const capabilities = [...flags.capabilities]
303 if (lines.some((line) => /^Temperature:/i.test(line))) {
304 capabilities.push('temperature')
305 }
306 if (lines.some((line) => /^topP:/i.test(line))) capabilities.push('top_p')
307 if (lines.some((line) => /^topK:/i.test(line))) capabilities.push('top_k')
308 return {
309 title,
310 modelId,
311 versions: versionsOf(lines),
312 contextWindow: contextAt < 0 ? null : tokenCount(lines[contextAt + 1]),
313 maxOutput: outputAt < 0 ? null : tokenCount(lines[outputAt + 1]),
314 modalities: modalitiesOf(lines),
315 capabilities,
316 serverTools: flags.serverTools,
317 thinkingSupported: flags.thinkingSupported,
318 }
319}
320
321function namesIn(sentence: string): Array<string> {
322 return sentence.split(/\s+and\s+|,\s*/).flatMap((part) => {
323 const name =
324 /^(Gemini\s+\d+(?:\.\d+)?(?:\s+(?:Flash-Lite|Flash|Pro|Lite|Image|Live|Cyber|Omni|TTS|preview)){0,4})/i.exec(
325 part.trim(),
326 )
327 return name?.[1] ? [normModelName(name[1])] : []
328 })
329}
330
331function tableRows(table: string): Array<Array<string>> {
332 return [...table.matchAll(/<tr[\s\S]*?<\/tr>/gi)].map((row) =>
333 [...row[0].matchAll(/<t[dh][^>]*>([\s\S]*?)<\/t[dh]>/gi)].map(
334 (cell) =>
335 cell[1]
336 ?.replace(/<[^>]+>/g, ' ')
337 .replace(/\s+/g, ' ')
338 .trim() ?? '',
339 ),
340 )
341}
342
343/** Effort levels and which 2.5 models can set thinking_budget to 0. */
344export function parseThinking(html: string): VertexThinking {
345 const effort = new Map<string, Array<string>>()
346 const text = html
347 .replace(/<script[\s\S]*?<\/script>/gi, ' ')
348 .replace(/<style[\s\S]*?<\/style>/gi, ' ')
349 .replace(/<[^>]+>/g, ' ')
350 .replace(/'|'/g, "'")
351 .replace(/\s+/g, ' ')
352 const budgetOff = new Set(
353 namesIn(
354 /can turn off thinking for (.+?)(?:\.(?!\d)|$)/i.exec(text)?.[1] ?? '',
355 ),
356 )
357 const budgetOn = new Set(
358 namesIn(
359 /(?:can't|cannot) turn off thinking for (.+?)(?:\.(?!\d)|$)/i.exec(
360 text,
361 )?.[1] ?? '',
362 ),
363 )
364 for (const match of html.matchAll(/<table[\s\S]*?<\/table>/gi)) {
365 const rows = tableRows(match[0])
366 const header = rows[0]?.join(' ').toLowerCase() ?? ''
367 if (header.includes('thinking_level')) {
368 for (const row of rows.slice(1)) {
369 const name = row[0]
370 if (!name || /^model$/i.test(name)) continue
371 const efforts = row
372 .slice(1)
373 .join(' ')
374 .split(/[^A-Za-z]+/)
375 .map((token) => token.toUpperCase())
376 .filter((token) =>
377 ['MINIMAL', 'LOW', 'MEDIUM', 'HIGH'].includes(token),
378 )
379 const unique = [...new Set(efforts)]
380 if (unique.length === 0) continue
381 effort.set(normModelName(name), unique)
382 }
383 }
384 }
385 return { effort, budgetOff, budgetOn }
386}
387
388export function vertexActivity(rawId: string): Activity {
389 if (rawId.startsWith('veo-')) return 'video'
390 if (
391 rawId.includes('embedding') ||
392 rawId.startsWith('text-embedding') ||
393 rawId.startsWith('text-multilingual-embedding') ||
394 rawId.startsWith('multimodalembedding')
395 ) {
396 return 'embeddings'
397 }
398 if (
399 rawId.includes('image') ||
400 rawId.startsWith('virtual-try-on') ||
401 rawId.startsWith('imagen')
402 ) {
403 return 'image'
404 }
405 if (
406 /(?:^|-)tts(?:-|$)/.test(rawId) ||
407 rawId.includes('transcribe') ||
408 rawId.includes('live-translate')
409 ) {
410 return 'audio'
411 }
412 return 'chat'
413}
414
415export function vertexEndpoint(rawId: string): string {
416 const activity = vertexActivity(rawId)
417 if (activity === 'embeddings') return `${ENDPOINT}:embedContent`
418 if (activity === 'video') return `${ENDPOINT}:predictLongRunning`
419 if (rawId.startsWith('virtual-try-on') || rawId.startsWith('imagen')) {
420 return `${ENDPOINT}:predict`
421 }
422 return `${ENDPOINT}:generateContent`
423}
424
425function reasoningFor(
426 title: string,
427 thinkingSupported: boolean | null,
428 thinking: VertexThinking,
429): ModelReasoning | null {
430 if (thinkingSupported === false) return null
431 const key = normModelName(title)
432 const efforts = thinking.effort.get(key)
433 if (efforts) return { mode: 'effort', mandatory: true, efforts }
434 if (thinking.budgetOff.has(key) || thinking.budgetOn.has(key)) {
435 return { mode: 'budget', mandatory: !thinking.budgetOff.has(key) }
436 }
437 return null
438}
439
440function cardUrl(path: string): string {
441 return `${DOCS}${path}`
442}
443
444async function loadCards(
445 paths: Array<string>,
446 kv?: KVNamespace,
447): Promise<Map<string, VertexCard>> {
448 const cards = new Map<string, VertexCard>()
449 await mapConcurrent(paths, 4, async (path) => {
450 const card = await cachedDocs(kv, cardUrl(path), async () =>
451 parseCard(await fetchText(cardUrl(path))),
452 )
453 cards.set(path, card)
454 })
455 return cards
456}
457
458/**
459 * Served Google model ids, plus version ids published on those cards.
460 * Prices come from the standard token table, joined by card title.
461 */
462export async function vertexModelList(
463 kv?: KVNamespace,
464): Promise<Array<ModelInfo>> {
465 const locations = await cachedDocs(kv, VERTEX_LOCATIONS_URL, async () => {
466 const models = parseLocationModels(await fetchText(VERTEX_LOCATIONS_URL))
467 assertParsed(
468 new Map(models.map((model) => [model.rawId, model])),
469 'vertex locations',
470 )
471 return models
472 })
473 const paths = [
474 ...new Set(
475 locations.flatMap((model) => (model.cardPath ? [model.cardPath] : [])),
476 ),
477 ]
478 const cards = await loadCards(paths, kv)
479 const thinking = await cachedDocs(kv, VERTEX_THINKING_URL, async () => {
480 const parsed = parseThinking(await fetchText(VERTEX_THINKING_URL))
481 if (
482 parsed.effort.size === 0 &&
483 parsed.budgetOff.size + parsed.budgetOn.size === 0
484 ) {
485 throw new Error('vertex thinking page: parsed 0 model rows')
486 }
487 return {
488 effort: Object.fromEntries(parsed.effort),
489 budgetOff: [...parsed.budgetOff],
490 budgetOn: [...parsed.budgetOn],
491 }
492 })
493 const thinkingMaps: VertexThinking = {
494 effort: new Map(Object.entries(thinking.effort)),
495 budgetOff: new Set(thinking.budgetOff),
496 budgetOn: new Set(thinking.budgetOn),
497 }
498 const pricing = await vertexModelPricing(kv)
499
500 const rows = new Map<
501 string,
502 { card: VertexCard | null; cardPath: string | null }
503 >()
504 for (const location of locations) {
505 rows.set(location.rawId, {
506 card: location.cardPath ? (cards.get(location.cardPath) ?? null) : null,
507 cardPath: location.cardPath,
508 })
509 }
510 for (const [path, card] of cards) {
511 const ids = [
512 ...card.versions.map((version) => version.rawId),
513 ...(card.modelId ? [card.modelId] : []),
514 ]
515 for (const rawId of ids) {
516 if (!rows.has(rawId)) rows.set(rawId, { card, cardPath: path })
517 else if (!rows.get(rawId)?.card) rows.set(rawId, { card, cardPath: path })
518 }
519 }
520
521 return [...rows].map(([rawId, row]) => {
522 const card = row.card
523 const version = card?.versions.find((item) => item.rawId === rawId) ?? null
524 const activity = vertexActivity(rawId)
525 const reasoning = card
526 ? reasoningFor(card.title, card.thinkingSupported, thinkingMaps)
527 : null
528 const capabilities = card
529 ? [
530 ...card.capabilities,
531 ...(reasoning || card.thinkingSupported ? ['reasoning'] : []),
532 ].filter((flag, index, all) => all.indexOf(flag) === index)
533 : null
534 const priced = card ? pricing(card.title) : {}
535 const facts = {
536 contextWindow: card?.contextWindow ?? null,
537 maxOutput: card?.maxOutput ?? null,
538 modalities: card?.modalities ?? null,
539 capabilities,
540 reasoning,
541 serverTools:
542 card && card.serverTools.length > 0 ? card.serverTools : null,
543 }
544 const sourceUrl = row.cardPath
545 ? cardUrl(row.cardPath)
546 : VERTEX_LOCATIONS_URL
547 return {
548 rawId,
549 displayName: card?.title || null,
550 activity,
551 schemaEndpointId: vertexEndpoint(rawId),
552 contextWindow: facts.contextWindow,
553 maxOutput: facts.maxOutput,
554 modalities: facts.modalities,
555 capabilities:
556 capabilities && capabilities.length > 0 ? capabilities : null,
557 reasoning,
558 serverTools: facts.serverTools,
559 releasedAt: version?.releasedAt ?? null,
560 deprecated: version?.deprecated ?? false,
561 pricing: priced.pricing ?? null,
562 factSources: {
563 ...tagDocsFacts(facts, sourceUrl),
564 ...priced.factSources,
565 },
566 }
567 })
568}