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