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

gemini.ts

424 lines12.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 { geminiModelFeatures } from './gemini-features.ts'
10import { geminiModelPricing } from './gemini-pricing.ts'
11import {
12 GEMINI_DISCOVERY_URL,
13 geminiRequestMap,
14 geminiWire,
15} from './gemini-request.ts'
16import { geminiGenerationEndpointId } from './model-meta.ts'
17import {
18 GEMINI_RELEASE_DATES,
19 curatedReleasedAt,
20 geminiIdSuffixDate,
21} from './release-dates.ts'
22import { fetchJson, fetchText, sha256Text, skippedResult } from './types.ts'
23import { usEgressFetch } from './us-egress.ts'
24import type {
25 ListModelsResult,
26 OpenApiDocument,
27 ProviderConfig,
28 ProviderEnvironment,
29 ProviderSecrets,
30 SpecFetchResult,
31} from './types.ts'
32​
33const GEMINI_MODELS_URL =
34 'https://generativelanguage.googleapis.com/v1beta/models'
35​
36interface DiscoverySchema {
37 id?: string
38 type?: string
39 format?: string
40 description?: string
41 properties?: Record<string, DiscoverySchema>
42 items?: DiscoverySchema
43 $ref?: string
44 enum?: Array<string>
45 required?: Array<string>
46 additionalProperties?: DiscoverySchema | boolean
48​
49interface DiscoveryParameter {
50 type?: string
51 description?: string
52 location?: 'query' | 'path' | 'header'
53 required?: boolean
54 enum?: Array<string>
56​
57interface DiscoveryMethod {
58 id: string
59 path?: string
60 flatPath?: string
61 httpMethod?: string
62 description?: string
63 parameters?: Record<string, DiscoveryParameter>
64 request?: { $ref?: string }
65 response?: { $ref?: string }
67​
68interface DiscoveryResource {
69 methods?: Record<string, DiscoveryMethod>
70 resources?: Record<string, DiscoveryResource>
72​
73export interface DiscoveryDoc {
74 rootUrl?: string
75 servicePath?: string
76 baseUrl?: string
77 schemas?: Record<string, DiscoverySchema>
78 resources?: Record<string, DiscoveryResource>
79 title?: string
80 version?: string
82​
83type JsonSchema = Record<string, unknown>
84​
85function convertSchema(schema: DiscoverySchema): JsonSchema {
86 if (schema.$ref) {
87 return { $ref: `#/components/schemas/${schema.$ref}` }
88 }
89 const out: JsonSchema = {}
90 if (schema.type) out.type = schema.type
91 if (schema.format) out.format = schema.format
92 if (schema.description) out.description = schema.description
93 if (schema.enum) out.enum = schema.enum
94 if (schema.required) out.required = schema.required
95 if (schema.items) out.items = convertSchema(schema.items)
96 if (schema.properties) {
97 out.properties = Object.fromEntries(
98 Object.entries(schema.properties).map(([name, value]) => [
99 name,
100 convertSchema(value),
101 ]),
102 )
103 }
104 if (schema.additionalProperties !== undefined) {
105 out.additionalProperties =
106 typeof schema.additionalProperties === 'boolean'
107 ? schema.additionalProperties
108 : convertSchema(schema.additionalProperties)
109 }
110 return out
112​
113function collectMethods(
114 resources: Record<string, DiscoveryResource> | undefined,
115 acc: Array<DiscoveryMethod>,
116): void {
117 if (!resources) return
118 for (const resource of Object.values(resources)) {
119 if (resource.methods) {
120 for (const method of Object.values(resource.methods)) {
121 acc.push(method)
122 }
123 }
124 collectMethods(resource.resources, acc)
125 }
127​
128export function discoveryToOpenApi(doc: DiscoveryDoc): OpenApiDocument {
129 const schemas = Object.fromEntries(
130 Object.entries(doc.schemas ?? {}).map(([name, schema]) => [
131 name,
132 convertSchema(schema),
133 ]),
134 )
135​
136 const paths: NonNullable<OpenApiDocument['paths']> = {}
137 const methods: Array<DiscoveryMethod> = []
138 collectMethods(doc.resources, methods)
139​
140 for (const method of methods) {
141 const path = `/${(method.flatPath ?? method.path ?? '').replace(/^\/+/, '')}`
142 const httpMethod = (method.httpMethod ?? 'GET').toLowerCase()
143 paths[path] ??= {}
144​
145 const operation: Record<string, unknown> = {
146 operationId: method.id,
147 description: method.description,
148 parameters: Object.entries(method.parameters ?? {}).map(
149 ([name, param]) => ({
150 name,
151 in: param.location ?? 'query',
152 required: param.required ?? (param.location ?? 'query') === 'path',
153 schema: { type: param.type, enum: param.enum },
154 description: param.description,
155 }),
156 ),
157 responses: {
158 '200': {
159 description: 'Success',
160 content: method.response?.$ref
161 ? {
162 'application/json': {
163 schema: {
164 $ref: `#/components/schemas/${method.response.$ref}`,
165 },
166 },
167 }
168 : undefined,
169 },
170 },
171 }
172 if (method.request?.$ref) {
173 operation.requestBody = {
174 required: true,
175 content: {
176 'application/json': {
177 schema: { $ref: `#/components/schemas/${method.request.$ref}` },
178 },
179 },
180 }
181 }
182 paths[path][httpMethod] = operation
183 }
184​
185 const serverUrl =
186 doc.baseUrl ??
187 (doc.rootUrl && doc.servicePath
188 ? `${doc.rootUrl.replace(/\/$/, '')}/${doc.servicePath.replace(/^\//, '')}`
189 : 'https://generativelanguage.googleapis.com/')
190​
191 return {
192 openapi: '3.0.4',
193 info: {
194 title: doc.title ?? 'Google Generative Language API',
195 version: doc.version ?? 'v1beta',
196 },
197 servers: [{ url: serverUrl.replace(/\/$/, '') }],
198 paths,
199 components: { schemas },
200 }
202​
203/**
204 * Gemini paths encode the operation as a `:method` suffix
205 * (`v1beta/models/{modelsId}:generateContent`); classify by that verb.
206 * Imagen runs through `:predict`, Veo through `:predictLongRunning`.
207 * Tuning management, cached contents, corpora, files, and batch job
208 * submission are platform endpoints.
209 */
210const GEMINI_VERB_ACTIVITIES: Record<string, Activity> = {
211 generateContent: 'chat',
212 streamGenerateContent: 'chat',
213 generateAnswer: 'chat',
214 generateMessage: 'chat',
215 generateText: 'chat',
216 countTokens: 'chat',
217 countMessageTokens: 'chat',
218 countTextTokens: 'chat',
219 embedContent: 'embeddings',
220 batchEmbedContents: 'embeddings',
221 embedText: 'embeddings',
222 batchEmbedText: 'embeddings',
223 predict: 'image',
224 predictLongRunning: 'video',
226​
227function classify(path: string): Activity | null {
228 const verb = path.match(/:([A-Za-z]+)$/)?.[1]
229 if (!verb) return null
230 return GEMINI_VERB_ACTIVITIES[verb] ?? null
232​
233/**
234 * Model-level activity. Google's models API doesn't label modality, so
235 * derive it from the signals it does carry: `predict`, `predictLongRunning`,
236 * and `embedContent` uniquely identify Imagen, Veo, and embedding models.
237 * The generateContent surface serves chat, image (Nano Banana), and TTS
238 * models alike, so it splits on the id's `-image`/`-tts` segments. The
239 * live/native-audio bidiGenerateContent models group with chat, matching
240 * the OpenAI Realtime → chat mapping.
241 */
242export function geminiModelActivity(
243 rawId: string,
244 methods: Array<string>,
245): Activity | null {
246 if (methods.includes('predict')) return 'image'
247 if (methods.includes('predictLongRunning')) return 'video'
248 if (methods.includes('embedContent') || methods.includes('embedText')) {
249 return 'embeddings'
250 }
251 const generates =
252 methods.includes('generateContent') ||
253 methods.includes('bidiGenerateContent') ||
254 methods.includes('generateAnswer')
255 if (!generates) return null
256 if (/(^|-)image(-|$)/.test(rawId)) return 'image'
257 if (/(^|-)tts(-|$)/.test(rawId)) return 'audio'
258 return 'chat'
260​
261async function fetchSpec(_env: ProviderSecrets): Promise<SpecFetchResult> {
262 const text = await fetchText(GEMINI_DISCOVERY_URL)
263 const discovery = JSON.parse(text) as DiscoveryDoc
264 return {
265 specs: [discoveryToOpenApi(discovery)],
266 sources: [{ url: GEMINI_DISCOVERY_URL, hash: await sha256Text(text) }],
267 outputStrategy: 'post-200',
268 }
270​
271interface GeminiModel {
272 name: string
273 displayName?: string
274 inputTokenLimit?: number
275 outputTokenLimit?: number
276 supportedGenerationMethods?: Array<string>
277 temperature?: number
278 topP?: number
279 topK?: number
280 thinking?: boolean
282​
283interface GeminiModelList {
284 models?: Array<GeminiModel>
285 nextPageToken?: string
287​
288/**
289 * Request features the Models API row states: `thinking`, and a sampling
290 * default present ⇒ that param is accepted. Tool use and structured output
291 * are not on the row and stay unset. Modalities are not on the row either:
292 * they come from the model's docs page (`gemini-features.ts`).
293 */
294export function geminiCapabilities(
295 m: Pick<GeminiModel, 'temperature' | 'topP' | 'topK' | 'thinking'>,
296): Array<string> | null {
297 const out: Array<string> = []
298 if (m.thinking) out.push('reasoning')
299 if (m.temperature !== undefined) out.push('temperature')
300 if (m.topP !== undefined) out.push('top_p')
301 if (m.topK !== undefined) out.push('top_k')
302 return out.length > 0 ? out : null
304​
305async function listModels(
306 env: ProviderEnvironment,
307 kv?: KVNamespace,
308): Promise<ListModelsResult> {
309 const key = env.GEMINI_API_KEY
310 if (!key) {
311 return { models: [], ...skippedResult('gemini', 'GEMINI_API_KEY') }
312 }
313 const pricingPromise = geminiModelPricing(kv)
314 const wirePromise = geminiWire(kv)
315 const listed: Array<GeminiModel> = []
316 let pageToken: string | undefined
317 do {
318 const url = new URL(GEMINI_MODELS_URL)
319 url.searchParams.set('pageSize', '1000')
320 if (pageToken) url.searchParams.set('pageToken', pageToken)
321 // Header, not `?key=`: fetchJson errors quote the URL into telemetry.
322 const body = (await fetchJson(
323 url.toString(),
324 { headers: { 'x-goog-api-key': key } },
325 usEgressFetch(env),
326 )) as GeminiModelList
327 listed.push(...(body.models ?? []))
328 pageToken = body.nextPageToken
329 } while (pageToken)
330 const rawIdOf = (m: GeminiModel) => m.name.replace(/^models\//, '')
331 const [pricing, wire, { features, docsFailures }] = await Promise.all([
332 pricingPromise,
333 wirePromise,
334 geminiModelFeatures(listed.map(rawIdOf), kv),
335 ])
336 return {
337 docsFailures,
338 models: listed.map((m) => {
339 const rawId = rawIdOf(m)
340 const methods = m.supportedGenerationMethods ?? []
341 const activity = geminiModelActivity(rawId, methods)
342 const priced = pricing(rawId)
343 const feat = features(rawId, m.thinking)
344 const capabilities = [
345 ...new Set([
346 ...(geminiCapabilities(m) ?? []),
347 ...(feat.capabilities ?? []),
348 ]),
349 ]
350 const usesConfig =
351 methods.includes('generateContent') ||
352 methods.includes('bidiGenerateContent')
353 const requestMap =
354 activity === 'chat' && usesConfig
355 ? geminiRequestMap(wire.fields, feat.reasoning, feat.budget)
356 : null
357 return {
358 rawId,
359 displayName: m.displayName ?? null,
360 activity,
361 schemaEndpointId:
362 activity === null
363 ? null
364 : geminiGenerationEndpointId(activity, methods),
365 contextWindow: m.inputTokenLimit ?? null,
366 maxOutput: m.outputTokenLimit ?? null,
367 modalities: feat.modalities,
368 capabilities: capabilities.length ? capabilities : null,
369 ...(m.thinking === false
370 ? { unsupportedCapabilities: ['reasoning'] }
371 : {}),
372 // Gemini's API has no release timestamp: curated dates first, then
373 // the MM-YYYY month embedded in preview ids.
374 releasedAt:
375 curatedReleasedAt(GEMINI_RELEASE_DATES, rawId) ??
376 geminiIdSuffixDate(rawId),
377 pricing: priced.pricing,
378 reasoning: feat.reasoning,
379 serverTools: feat.serverTools,
380 ...(requestMap ? { requestMap } : {}),
381 factSources: {
382 ...priced.factSources,
383 ...feat.factSources,
384 ...(requestMap ? { requestMap: wire.source } : {}),
385 },
386 ...(priced.absent || feat.absent
387 ? { absent: { ...priced.absent, ...feat.absent } }
388 : {}),
389 }
390 }),
391 }
393​
394export const geminiProvider: ProviderConfig = {
395 id: 'gemini',
396 modelNamespaces: ['google', 'google-ai-studio'],
397 displayName: 'Google Gemini',
398 authEnvVar: 'GEMINI_API_KEY',
399 defaultDerivation: 'upstream-spec',
400 specGrain: 'provider',
401 connect: {
402 servers: [{ url: 'https://generativelanguage.googleapis.com' }],
403 securitySchemes: {
404 apiKey: { type: 'apiKey', in: 'query', name: 'key' },
405 },
406 security: [{ apiKey: [] }],
407 },
408 fetchSpec,
409 listModels,
410 classify,
411 // Un-repolled rows still have supportedGenerationMethods in capabilities.
412 // After poll, resolveSchemaEndpointId prefers schemaEndpointId, so the
413 // new request-feature flags never drive the route.
414 generationEndpointId: ({ activity, capabilities }) =>
415 geminiGenerationEndpointId(
416 activity,
417 // A listing's list at poll time, a stored row's map at read time.
418 Array.isArray(capabilities)
419 ? capabilities.filter(
420 (value): value is string => typeof value === 'string',
421 )
422 : supportedFlags(capabilities),
423 ),