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

gemini.ts

544 lines16.9 KB

1/**
2 * Google Gemini — pulls the Generative Language API Discovery doc and
3 * converts it to OpenAPI 3.0. The converter is intentionally minimal
4 * (ported from PR #622): it covers the Discovery subset Google's gen-AI API
5 * actually uses, not general-purpose conversion.
6 */
7import type { Activity } from '#/db/schema.ts'
8import { supportedFlags } from '#/lib/capabilities.ts'
9import {
10 GEMINI_DEPRECATIONS_URL,
11 attachGeminiPublishedFacts,
12 geminiPublishedBindings,
13} from './gemini-bindings.ts'
14import { geminiModelFeatures } from './gemini-features.ts'
15import { geminiModelPricing } from './gemini-pricing.ts'
16import { geminiVideoEndpoints } from './gemini-video.ts'
17import {
18 GEMINI_DISCOVERY_URL,
19 geminiRequestMap,
20 geminiWire,
21} from './gemini-request.ts'
22import { docsReport, docsRun } from './model-facts.ts'
23import { geminiGenerationEndpointId } from './model-meta.ts'
24import {
25 GEMINI_RELEASE_DATES,
26 curatedReleasedAt,
27 dateToEpoch,
28 geminiIdSuffixDate,
29} from './release-dates.ts'
30import { fetchJson, fetchText, sha256Text, skippedResult } from './types.ts'
31import { usEgressFetch } from './us-egress.ts'
32import type {
33 ListModelsResult,
34 OpenApiDocument,
35 ProviderConfig,
36 ProviderEnvironment,
37 ProviderSecrets,
38 SpecFetchResult,
39} from './types.ts'
40​
41const GEMINI_MODELS_URL =
42 'https://generativelanguage.googleapis.com/v1beta/models'
43​
44interface DiscoverySchema {
45 id?: string
46 type?: string
47 format?: string
48 description?: string
49 properties?: Record<string, DiscoverySchema>
50 items?: DiscoverySchema
51 $ref?: string
52 enum?: Array<string>
53 required?: Array<string>
54 additionalProperties?: DiscoverySchema | boolean
56​
57interface DiscoveryParameter {
58 type?: string
59 description?: string
60 location?: 'query' | 'path' | 'header'
61 required?: boolean
62 enum?: Array<string>
64​
65interface DiscoveryMethod {
66 id: string
67 path?: string
68 flatPath?: string
69 httpMethod?: string
70 description?: string
71 parameters?: Record<string, DiscoveryParameter>
72 request?: { $ref?: string }
73 response?: { $ref?: string }
75​
76interface DiscoveryResource {
77 methods?: Record<string, DiscoveryMethod>
78 resources?: Record<string, DiscoveryResource>
80​
81export interface DiscoveryDoc {
82 rootUrl?: string
83 servicePath?: string
84 baseUrl?: string
85 schemas?: Record<string, DiscoverySchema>
86 resources?: Record<string, DiscoveryResource>
87 title?: string
88 version?: string
90​
91type JsonSchema = Record<string, unknown>
92​
93function convertSchema(schema: DiscoverySchema): JsonSchema {
94 if (schema.$ref) {
95 return { $ref: `#/components/schemas/${schema.$ref}` }
96 }
97 const out: JsonSchema = {}
98 if (schema.type) out.type = schema.type
99 if (schema.format) out.format = schema.format
100 if (schema.description) out.description = schema.description
101 if (schema.enum) out.enum = schema.enum
102 if (schema.required) out.required = schema.required
103 if (schema.items) out.items = convertSchema(schema.items)
104 if (schema.properties) {
105 out.properties = Object.fromEntries(
106 Object.entries(schema.properties).map(([name, value]) => [
107 name,
108 convertSchema(value),
109 ]),
110 )
111 }
112 if (schema.additionalProperties !== undefined) {
113 out.additionalProperties =
114 typeof schema.additionalProperties === 'boolean'
115 ? schema.additionalProperties
116 : convertSchema(schema.additionalProperties)
117 }
118 return out
120​
121function collectMethods(
122 resources: Record<string, DiscoveryResource> | undefined,
123 acc: Array<DiscoveryMethod>,
124): void {
125 if (!resources) return
126 for (const resource of Object.values(resources)) {
127 if (resource.methods) {
128 for (const method of Object.values(resource.methods)) {
129 acc.push(method)
130 }
131 }
132 collectMethods(resource.resources, acc)
133 }
135​
136export function discoveryToOpenApi(doc: DiscoveryDoc): OpenApiDocument {
137 const schemas = Object.fromEntries(
138 Object.entries(doc.schemas ?? {}).map(([name, schema]) => [
139 name,
140 convertSchema(schema),
141 ]),
142 )
143​
144 const paths: NonNullable<OpenApiDocument['paths']> = {}
145 const methods: Array<DiscoveryMethod> = []
146 collectMethods(doc.resources, methods)
147​
148 for (const method of methods) {
149 const path = `/${(method.flatPath ?? method.path ?? '').replace(/^\/+/, '')}`
150 const httpMethod = (method.httpMethod ?? 'GET').toLowerCase()
151 paths[path] ??= {}
152​
153 const operation: Record<string, unknown> = {
154 operationId: method.id,
155 description: method.description,
156 parameters: Object.entries(method.parameters ?? {}).map(
157 ([name, param]) => ({
158 name,
159 in: param.location ?? 'query',
160 required: param.required ?? (param.location ?? 'query') === 'path',
161 schema: { type: param.type, enum: param.enum },
162 description: param.description,
163 }),
164 ),
165 responses: {
166 '200': {
167 description: 'Success',
168 content: method.response?.$ref
169 ? {
170 'application/json': {
171 schema: {
172 $ref: `#/components/schemas/${method.response.$ref}`,
173 },
174 },
175 }
176 : undefined,
177 },
178 },
179 }
180 if (method.request?.$ref) {
181 operation.requestBody = {
182 required: true,
183 content: {
184 'application/json': {
185 schema: { $ref: `#/components/schemas/${method.request.$ref}` },
186 },
187 },
188 }
189 }
190 paths[path][httpMethod] = operation
191 }
192​
193 const serverUrl =
194 doc.baseUrl ??
195 (doc.rootUrl && doc.servicePath
196 ? `${doc.rootUrl.replace(/\/$/, '')}/${doc.servicePath.replace(/^\//, '')}`
197 : 'https://generativelanguage.googleapis.com/')
198​
199 return {
200 openapi: '3.0.4',
201 info: {
202 title: doc.title ?? 'Google Generative Language API',
203 version: doc.version ?? 'v1beta',
204 },
205 servers: [{ url: serverUrl.replace(/\/$/, '') }],
206 paths,
207 components: { schemas },
208 }
210​
211/**
212 * Gemini paths encode the operation as a `:method` suffix
213 * (`v1beta/models/{modelsId}:generateContent`); classify by that verb.
214 * Imagen runs through `:predict`, Veo through `:predictLongRunning`.
215 * Tuning management, cached contents, corpora, files, and batch job
216 * submission are platform endpoints.
217 */
218const GEMINI_VERB_ACTIVITIES: Record<string, Activity> = {
219 generateContent: 'chat',
220 streamGenerateContent: 'chat',
221 generateAnswer: 'chat',
222 generateMessage: 'chat',
223 generateText: 'chat',
224 countTokens: 'chat',
225 countMessageTokens: 'chat',
226 countTextTokens: 'chat',
227 embedContent: 'embeddings',
228 batchEmbedContents: 'embeddings',
229 embedText: 'embeddings',
230 batchEmbedText: 'embeddings',
231 predict: 'image',
232 predictLongRunning: 'video',
234​
235function classify(path: string): Activity | null {
236 const verb = path.match(/:([A-Za-z]+)$/)?.[1]
237 if (!verb) return null
238 return GEMINI_VERB_ACTIVITIES[verb] ?? null
240​
241/** A dash-separated id segment, so `live` does not match inside another word. */
242function hasSegment(rawId: string, segment: string): boolean {
243 return new RegExp(`(^|-)${segment}(-|$)`).test(rawId)
245​
246/**
247 * Model-level activity. Google's models API doesn't label modality, so
248 * derive it from the signals it does carry: `predict`, `predictLongRunning`,
249 * and `embedContent` uniquely identify Imagen, Veo, and embedding models.
250 * The generateContent surface also serves music (Lyria), image (Nano
251 * Banana), transcription, TTS, and Live models. Those are classified by
252 * the id, because the shared route is not what the model does (#661).
253 * Live and native-audio models are audio: they are the Live API, not
254 * generateContent chat. Omni stays a chat listing here. Its docs page is
255 * what says video, and an unread page must not replace the stored row
256 * (#658).
257 */
258export function geminiModelActivity(
259 rawId: string,
260 methods: Array<string>,
261): Activity | null {
262 if (methods.includes('predict')) return 'image'
263 if (methods.includes('predictLongRunning')) return 'video'
264 if (methods.includes('embedContent') || methods.includes('embedText')) {
265 return 'embeddings'
266 }
267 if (rawId.startsWith('lyria')) return 'audio'
268 if (rawId.includes('nano-banana') || hasSegment(rawId, 'image')) {
269 return 'image'
270 }
271 if (rawId.includes('transcribe') || hasSegment(rawId, 'tts')) return 'audio'
272 if (hasSegment(rawId, 'live') || rawId.includes('native-audio')) {
273 return 'audio'
274 }
275 const generates =
276 methods.includes('generateContent') ||
277 methods.includes('bidiGenerateContent') ||
278 methods.includes('generateAnswer')
279 if (!generates) return null
280 return 'chat'
282​
283async function fetchSpec(_env: ProviderSecrets): Promise<SpecFetchResult> {
284 const [text, video] = await Promise.all([
285 fetchText(GEMINI_DISCOVERY_URL),
286 geminiVideoEndpoints(),
287 ])
288 const discovery = JSON.parse(text) as DiscoveryDoc
289 return {
290 specs: [discoveryToOpenApi(discovery)],
291 sources: [{ url: GEMINI_DISCOVERY_URL, hash: await sha256Text(text) }],
292 outputStrategy: 'post-200',
293 bundledEndpoints: video.endpoints,
294 ...(video.warnings.length > 0 ? { warnings: video.warnings } : {}),
295 }
297​
298interface GeminiModel {
299 name: string
300 displayName?: string
301 inputTokenLimit?: number
302 outputTokenLimit?: number
303 supportedGenerationMethods?: Array<string>
304 temperature?: number
305 topP?: number
306 topK?: number
307 thinking?: boolean
309​
310interface GeminiModelList {
311 models?: Array<GeminiModel>
312 nextPageToken?: string
314​
315/**
316 * Request features the Models API row states: `thinking`, and a sampling
317 * default present ⇒ that param is accepted. Tool use and structured output
318 * are not on the row and stay unset. Modalities are not on the row either:
319 * they come from the model's docs page (`gemini-features.ts`).
320 */
321export function geminiCapabilities(
322 m: Pick<GeminiModel, 'temperature' | 'topP' | 'topK' | 'thinking'>,
323): Array<string> | null {
324 const out: Array<string> = []
325 if (m.thinking) out.push('reasoning')
326 if (m.temperature !== undefined) out.push('temperature')
327 if (m.topP !== undefined) out.push('top_p')
328 if (m.topK !== undefined) out.push('top_k')
329 return out.length > 0 ? out : null
331​
332/**
333 * Curated dates win, then the deprecations page, then an id's `-MM-YYYY`
334 * suffix. `releasedOn` is empty when that page failed, so a blip cannot
335 * replace a date the page would have stated.
336 */
337function geminiReleasedAt(
338 rawId: string,
339 releasedOn: Record<string, string>,
340): number | null {
341 return (
342 curatedReleasedAt(GEMINI_RELEASE_DATES, rawId) ??
343 statedRelease(rawId, releasedOn) ??
344 geminiIdSuffixDate(rawId)
345 )
347​
348function statedRelease(
349 rawId: string,
350 releasedOn: Record<string, string>,
351): number | null {
352 const date = releasedOn[rawId]
353 return date ? dateToEpoch(date) : null
355​
356/** Provenance only for the date the deprecations page itself supplied. */
357function geminiReleaseSource(
358 rawId: string,
359 releasedOn: Record<string, string>,
360):
361 | {
362 releasedAt: {
363 derivation: 'docs-derived'
364 sourceUrl: string
365 path: string
366 }
367 }
368 | Record<string, never> {
369 if (curatedReleasedAt(GEMINI_RELEASE_DATES, rawId) != null) return {}
370 if (!releasedOn[rawId]) return {}
371 return {
372 releasedAt: {
373 derivation: 'docs-derived',
374 sourceUrl: GEMINI_DEPRECATIONS_URL,
375 path: 'Release date',
376 },
377 }
379​
380async function listModels(
381 env: ProviderEnvironment,
382 kv?: KVNamespace,
383): Promise<ListModelsResult> {
384 const key = env.GEMINI_API_KEY
385 if (!key) {
386 return { models: [], ...skippedResult('gemini', 'GEMINI_API_KEY') }
387 }
388 // A docs miss is `unavailable` on the rows plus `docsFailures` on the
389 // result. It must not throw away the listing (#567).
390 const docs = docsRun()
391 const pricingPromise = geminiModelPricing(kv, docs)
392 const wirePromise = geminiWire(kv)
393 const bindingsPromise = geminiPublishedBindings(kv)
394 const listed: Array<GeminiModel> = []
395 let pageToken: string | undefined
396 do {
397 const url = new URL(GEMINI_MODELS_URL)
398 url.searchParams.set('pageSize', '1000')
399 if (pageToken) url.searchParams.set('pageToken', pageToken)
400 // Header, not `?key=`: fetchJson errors quote the URL into telemetry.
401 const body = (await fetchJson(
402 url.toString(),
403 { headers: { 'x-goog-api-key': key } },
404 usEgressFetch(env),
405 )) as GeminiModelList
406 listed.push(...(body.models ?? []))
407 pageToken = body.nextPageToken
408 } while (pageToken)
409 const rawIdOf = (m: GeminiModel) => m.name.replace(/^models\//, '')
410 const [pricing, wire, { features, docsFailures, thinkingLoaded }, bindings] =
411 await Promise.all([
412 pricingPromise,
413 wirePromise,
414 geminiModelFeatures(listed.map(rawIdOf), kv),
415 bindingsPromise,
416 ])
417 const models = listed.map((m) => {
418 const rawId = rawIdOf(m)
419 const methods = m.supportedGenerationMethods ?? []
420 const priced = pricing(rawId)
421 const feat = features(rawId, m.thinking)
422 // The Models API lists a video model like a chat model. Its docs page
423 // is what says video, so a poll that could not read the page keeps the
424 // stored activity and route instead of calling the row chat (#658).
425 const listing = geminiModelActivity(rawId, methods)
426 const pageUnread =
427 listing === 'chat' && feat.absent?.modalities === 'unavailable'
428 const activity = pageUnread ? null : feat.outputVideo ? 'video' : listing
429 const capabilities = [
430 ...new Set([
431 ...(geminiCapabilities(m) ?? []),
432 ...(feat.capabilities ?? []),
433 ]),
434 ]
435 const usesConfig =
436 methods.includes('generateContent') ||
437 methods.includes('bidiGenerateContent')
438 // The thinking page supplies budget numbers the map's thinking body
439 // needs. While it is unread, keep the stored map.
440 const requestMap =
441 activity === 'chat' && usesConfig && thinkingLoaded
442 ? geminiRequestMap(wire.fields, feat.reasoning, feat.budget)
443 : null
444 const absent = {
445 ...priced.absent,
446 ...feat.absent,
447 ...(thinkingLoaded || activity !== 'chat' || !usesConfig
448 ? {}
449 : { requestMap: 'unavailable' as const }),
450 ...(pageUnread
451 ? {
452 activity: 'unavailable' as const,
453 schemaEndpointId: 'unavailable' as const,
454 requestMap: 'unavailable' as const,
455 }
456 : {}),
457 }
458 return {
459 rawId,
460 displayName: m.displayName ?? null,
461 activity,
462 // A video model's route is its own Interactions schema
463 // (`gemini-video.ts`), stored under the model id.
464 schemaEndpointId:
465 activity === null
466 ? null
467 : feat.outputVideo
468 ? rawId
469 : geminiGenerationEndpointId(activity, methods),
470 contextWindow: m.inputTokenLimit ?? null,
471 maxOutput: m.outputTokenLimit ?? null,
472 modalities: feat.modalities,
473 capabilities: capabilities.length ? capabilities : null,
474 ...(m.thinking === false
475 ? { unsupportedCapabilities: ['reasoning'] }
476 : {}),
477 // Gemini's API has no release timestamp: curated dates, then the
478 // deprecations page's Release date column, then the MM-YYYY month
479 // embedded in preview ids. A model the page does not date keeps a
480 // stored date, and firstSeenAt covers one that was never dated.
481 releasedAt: geminiReleasedAt(rawId, pricing.releasedOn),
482 pricing: priced.pricing,
483 reasoning: feat.reasoning,
484 serverTools: feat.serverTools,
485 ...(requestMap ? { requestMap } : {}),
486 factSources: {
487 ...priced.factSources,
488 ...feat.factSources,
489 ...(requestMap ? { requestMap: wire.source } : {}),
490 ...geminiReleaseSource(rawId, pricing.releasedOn),
491 },
492 ...(Object.keys(absent).length > 0 ? { absent } : {}),
493 }
494 })
495 const pricingDocs = docsReport(docs)
496 return {
497 docsFailures: {
498 failed:
499 pricingDocs.failed + docsFailures.failed + bindings.docsFailures.failed,
500 skipped:
501 pricingDocs.skipped +
502 docsFailures.skipped +
503 bindings.docsFailures.skipped,
504 first: [
505 ...pricingDocs.first,
506 ...docsFailures.first,
507 ...bindings.docsFailures.first,
508 ].slice(0, 5),
509 },
510 models: attachGeminiPublishedFacts(models, bindings),
511 }
513​
514export const geminiProvider: ProviderConfig = {
515 id: 'gemini',
516 modelNamespaces: ['google', 'google-ai-studio'],
517 displayName: 'Google Gemini',
518 authEnvVar: 'GEMINI_API_KEY',
519 defaultDerivation: 'upstream-spec',
520 specGrain: 'provider',
521 connect: {
522 servers: [{ url: 'https://generativelanguage.googleapis.com' }],
523 securitySchemes: {
524 apiKey: { type: 'apiKey', in: 'query', name: 'key' },
525 },
526 security: [{ apiKey: [] }],
527 },
528 fetchSpec,
529 listModels,
530 classify,
531 // Un-repolled rows still have supportedGenerationMethods in capabilities.
532 // After poll, resolveSchemaEndpointId prefers schemaEndpointId, so the
533 // new request-feature flags never drive the route.
534 generationEndpointId: ({ activity, capabilities }) =>
535 geminiGenerationEndpointId(
536 activity,
537 // A listing's list at poll time, a stored row's map at read time.
538 Array.isArray(capabilities)
539 ? capabilities.filter(
540 (value): value is string => typeof value === 'string',
541 )
542 : supportedFlags(capabilities),
543 ),