Open History to see the last commit
1import {
2 GenerateVideosOperation,
3 VideoGenerationReferenceType,
4} from '@google/genai'
5import {
6 fileReferenceFor,
7 isFileSource,
8 resolveMediaPrompt,
9 unsupportedFileSourceError,
10} from '@tanstack/ai'
11import { BaseVideoAdapter } from '@tanstack/ai/adapters'
12import { arrayBufferToBase64 } from '@tanstack/ai-utils'
13import { createGeminiClient, getGeminiApiKeyFromEnv } from '../utils'
14import {
15 getGeminiVideoDurationOptions,
16 isInteractionsVideoModel,
17 parseGeminiOmniVideoSize,
18} from '../video/video-provider-options'
19import type { DurationOptions } from '@tanstack/ai/adapters'
20import type {
21 ImagePart,
22 MediaInputMetadata,
23 TokenUsage,
24 VideoGenerationOptions,
25 VideoJobResult,
26 VideoPart,
27 VideoStatusResult,
28 VideoUrlResult,
29} from '@tanstack/ai'
30import type {
31 GenerateVideosConfig,
32 GoogleGenAI,
33 Image,
34 Interactions,
35 VideoGenerationReferenceImage,
36} from '@google/genai'
37import type {
38 GeminiOmniVideoProviderOptions,
39 GeminiVideoModel,
40 GeminiVideoModelDurationByName,
41 GeminiVideoModelInputModalitiesByName,
42 GeminiVideoModelProviderOptionsByName,
43 GeminiVideoModelSizeByName,
44 GeminiVideoProviderOptions,
45} from '../video/video-provider-options'
46import type { GeminiClientConfig } from '../utils/client'
47
48type Interaction = Interactions.Interaction
49type InteractionContent = Interactions.Content
50
51/**
52 * Configuration for Gemini video adapter.
53 *
54 * @experimental Video generation is an experimental feature and may change.
55 */
56export interface GeminiVideoConfig extends GeminiClientConfig {
57 /**
58 * Opt into fetching HTTP(S) image URL inputs. Veo's predict API accepts
59 * only inline `imageBytes` or a `gcsUri`, so an HTTP(S) URL has to be
60 * downloaded and base64-encoded locally — which buffers the whole image in
61 * memory and can OOM constrained runtimes (e.g. Cloudflare Workers). When
62 * `false` (the default), HTTP(S) URL image inputs throw; pass a `data:` URI
63 * or a `gs://` reference, or set this to `true` to opt into buffering.
64 */
65 allowUrlFetch?: boolean
66}
67
68/**
69 * Extract a human-readable message from a long-running operation's error,
70 * which the SDK types as `Record<string, unknown>` (a google.rpc.Status).
71 */
72function operationErrorMessage(error: Record<string, unknown>): string {
73 if (typeof error.message === 'string' && error.message.length > 0) {
74 return error.message
75 }
76 return JSON.stringify(error)
77}
78
79/**
80 * Convert a TanStack image prompt part into the genai `Image` shape Veo
81 * accepts: base64 `imageBytes` (data sources, data: URIs, fetched HTTP
82 * URLs) or a `gcsUri` passthrough for Cloud Storage references.
83 *
84 * Unlike `generateContent` (chat / native image generation), Veo's predict
85 * API has no `fileData.fileUri` equivalent — `Image` only accepts
86 * `imageBytes` or `gcsUri`. An HTTP(S) URL therefore has to be fetched and
87 * inlined locally, which buffers the whole image in memory; that only happens
88 * when the caller opts in via `allowUrlFetch`, otherwise it throws. Prefer a
89 * `gs://` reference on memory-constrained runtimes.
90 */
91async function imagePartToVeoImage(
92 part: ImagePart<MediaInputMetadata>,
93 allowUrlFetch: boolean,
94): Promise<Image> {
95 if (part.source.type === 'data') {
96 return {
97 imageBytes: part.source.value,
98 mimeType: part.source.mimeType || 'image/png',
99 }
100 }
101 if (isFileSource(part.source)) {
102 // Veo's predict API accepts only inline bytes or a gs:// reference — there's
103 // no way to reference a Files API handle here.
104 throw unsupportedFileSourceError(
105 'gemini',
106 'for Veo video generation, which needs inline image bytes or a gs:// reference — pass a data: URI or gs:// URL',
107 )
108 }
109 const url = part.source.value
110 if (url.startsWith('gs://')) {
111 return {
112 gcsUri: url,
113 ...(part.source.mimeType && { mimeType: part.source.mimeType }),
114 }
115 }
116 if (url.startsWith('data:')) {
117 const match = url.match(/^data:([^;,]+)?(;base64)?,(.*)$/)
118 if (!match || !match[2]) {
119 throw new Error(
120 'gemini: only base64 data: URIs are supported for video image inputs.',
121 )
122 }
123 return {
124 imageBytes: match[3] ?? '',
125 mimeType: match[1] || part.source.mimeType || 'image/png',
126 }
127 }
128 if (!allowUrlFetch) {
129 throw new Error(
130 `gemini Veo: HTTP(S) URL image inputs are not fetched by default because ` +
131 `Veo accepts only inline bytes, so the image would be downloaded and ` +
132 `buffered in memory (risking OOM on constrained runtimes). Pass a ` +
133 `data: URI or a gs:// reference, or set \`allowUrlFetch: true\` on the ` +
134 `adapter config to opt into fetching. URL: ${url}`,
135 )
136 }
137 const response = await fetch(url)
138 if (!response.ok) {
139 throw new Error(
140 `Failed to fetch image input (${response.status} ${response.statusText}): ${url}`,
141 )
142 }
143 const blob = await response.blob()
144 const buffer = await blob.arrayBuffer()
145 return {
146 imageBytes: arrayBufferToBase64(buffer),
147 mimeType: part.source.mimeType || blob.type || 'image/png',
148 }
149}
150
151/**
152 * Convert an image or video prompt part into an Interactions API content
153 * block. Data sources become inline base64 `data`; URL sources pass through
154 * as `uri` (Files API URIs — mirrors the Interactions text adapter).
155 */
156function mediaPartToInteractionsContent(
157 part: ImagePart<MediaInputMetadata> | VideoPart<MediaInputMetadata>,
158): InteractionContent {
159 // A Gemini Files API reference maps to the `uri` field, same as a public
160 // URL (mirrors the Interactions text adapter). `fileReferenceFor` throws
161 // when another provider issued the handle.
162 const sourceValue = isFileSource(part.source)
163 ? fileReferenceFor(part.source, 'gemini')
164 : part.source.value
165 const mimeType = part.source.mimeType
166 if (part.type === 'image') {
167 return part.source.type === 'data'
168 ? { type: 'image', data: sourceValue, mime_type: mimeType }
169 : { type: 'image', uri: sourceValue, mime_type: mimeType }
170 }
171 return part.source.type === 'data'
172 ? { type: 'video', data: sourceValue, mime_type: mimeType }
173 : { type: 'video', uri: sourceValue, mime_type: mimeType }
174}
175
176/**
177 * Pull the generated video out of a completed interaction. Prefers the
178 * SDK's `output_video` sugar, then walks `steps` back-to-front for the last
179 * `model_output` step carrying a video content block (the wire shape the
180 * raw REST response uses).
181 */
182function extractInteractionVideo(
183 interaction: Interaction,
184): { data?: string; uri?: string; mimeType: string } | undefined {
185 const direct = interaction.output_video
186 if (direct && (direct.data || direct.uri)) {
187 return {
188 data: direct.data,
189 uri: direct.uri,
190 mimeType: direct.mime_type || 'video/mp4',
191 }
192 }
193 const steps = interaction.steps ?? []
194 for (let i = steps.length - 1; i >= 0; i--) {
195 const step = steps[i]
196 if (step?.type !== 'model_output') continue
197 for (const block of step.content ?? []) {
198 if (block.type === 'video' && (block.data || block.uri)) {
199 return {
200 data: block.data,
201 uri: block.uri,
202 mimeType: block.mime_type || 'video/mp4',
203 }
204 }
205 }
206 }
207 return undefined
208}
209
210/**
211 * Map Interactions usage onto the canonical TokenUsage shape. Omni reports
212 * video output via `output_tokens_by_modality`; fall back to the video
213 * modality entry when the total is absent.
214 */
215function interactionUsageToTokenUsage(
216 usage: Interaction['usage'],
217): TokenUsage | undefined {
218 if (!usage) return undefined
219 const videoTokens = usage.output_tokens_by_modality?.find(
220 (entry) => entry.modality === 'video',
221 )?.tokens
222 const promptTokens = usage.total_input_tokens ?? 0
223 const completionTokens = usage.total_output_tokens ?? videoTokens ?? 0
224 return {
225 promptTokens,
226 completionTokens,
227 totalTokens: usage.total_tokens ?? promptTokens + completionTokens,
228 }
229}
230
231/**
232 * Gemini Video Generation Adapter (Veo + Gemini Omni Flash)
233 *
234 * Tree-shakeable adapter for Google video generation, routing by model:
235 *
236 * **Veo models** run as a long-running operation: `createVideoJob` starts
237 * the operation via the `:predictLongRunning` endpoint, `getVideoStatus`
238 * polls it, and `getVideo` extracts the generated video's URI once it
239 * completes. Image prompt parts are routed by `metadata.role`:
240 * - `'start_frame'` (or the first un-roled image) → the input image the
241 * video starts from
242 * - `'end_frame'` → `lastFrame` (the frame the video ends on)
243 * - `'reference'` / `'character'` → `referenceImages` (asset references,
244 * Veo 3.1)
245 *
246 * Note: the returned Veo video URI is served by the Gemini Files API and
247 * requires the API key (`x-goog-api-key` header or `?key=` query
248 * parameter) to download.
249 *
250 * **Gemini Omni Flash** (`gemini-omni-1.1-flash`) only serves the Interactions API:
251 * `createVideoJob` creates a background interaction with
252 * `response_modalities: ['video']`, `getVideoStatus` polls it by id, and
253 * `getVideo` returns the inline base64 MP4 as a `data:` URL (or the
254 * Files API URI when the server delivers by reference). Image and video
255 * prompt parts are sent as interaction content blocks, grouped as images,
256 * then videos, then the text prompt (interleaving is not preserved); pass
257 * `modelOptions.previous_interaction_id` to conversationally edit a prior
258 * Omni generation. `size` is an `aspectRatio_resolution` template
259 * (`'16:9'` or `'16:9_1080p'`); the optional suffix maps onto
260 * `response_format.resolution` (`'360p' | '720p' | '1080p' | '4k'`,
261 * default 720p).
262 *
263 * @experimental Video generation is an experimental feature and may change.
264 */
265export class GeminiVideoAdapter<
266 TModel extends GeminiVideoModel,
267> extends BaseVideoAdapter<
268 TModel,
269 GeminiVideoModelProviderOptionsByName[TModel],
270 GeminiVideoModelProviderOptionsByName,
271 GeminiVideoModelSizeByName,
272 GeminiVideoModelInputModalitiesByName,
273 GeminiVideoModelDurationByName
274> {
275 readonly name = 'gemini' as const
276 // The Interactions path consumes Gemini Files API references as content
277 // `uri`s; the Veo path still rejects them (raw bytes / gs:// only).
278 override readonly supportsFileSources = true
279
280 protected client: GoogleGenAI
281 private readonly allowUrlFetch: boolean
282
283 constructor(config: GeminiVideoConfig, model: TModel) {
284 super({}, model)
285 this.client = createGeminiClient(config)
286 this.allowUrlFetch = config.allowUrlFetch ?? false
287 }
288
289 async createVideoJob(
290 options: VideoGenerationOptions<
291 GeminiVideoModelProviderOptionsByName[TModel],
292 GeminiVideoModelSizeByName[TModel],
293 GeminiVideoModelDurationByName[TModel]
294 >,
295 ): Promise<VideoJobResult> {
296 const { prompt, size, duration, logger } = options
297
298 logger.request(
299 `activity=video.create provider=${this.name} model=${this.model} size=${size ?? 'default'} duration=${duration ?? 'default'}`,
300 { provider: this.name, model: this.model },
301 )
302
303 if (isInteractionsVideoModel(this.model)) {
304 return await this.createInteractionsVideoJob(options)
305 }
306 const modelOptions = options.modelOptions as
307 | GeminiVideoProviderOptions
308 | undefined
309
310 try {
311 const resolved = resolveMediaPrompt(prompt)
312
313 if (resolved.videos.length > 0) {
314 throw new Error(
315 `${this.name}.createVideoJob does not support video prompt parts (model: ${this.model}).`,
316 )
317 }
318 if (resolved.audios.length > 0) {
319 throw new Error(
320 `${this.name}.createVideoJob does not support audio prompt parts (model: ${this.model}).`,
321 )
322 }
323
324 const { image, lastFrame, referenceImages } = await this.routeImageParts(
325 resolved.images,
326 )
327
328 const config: GenerateVideosConfig = {
329 ...modelOptions,
330 ...(size !== undefined && { aspectRatio: size }),
331 ...(duration !== undefined && { durationSeconds: duration }),
332 ...(lastFrame && { lastFrame }),
333 ...(referenceImages.length > 0 && { referenceImages }),
334 }
335
336 const operation = await this.client.models.generateVideos({
337 model: this.model,
338 prompt: resolved.text,
339 ...(image && { image }),
340 config,
341 })
342
343 if (!operation.name) {
344 throw new Error(
345 'Veo did not return an operation name for the video generation job.',
346 )
347 }
348
349 return { jobId: operation.name, model: this.model }
350 } catch (error) {
351 logger.errors(`${this.name}.createVideoJob fatal`, {
352 error,
353 source: `${this.name}.createVideoJob`,
354 })
355 throw error
356 }
357 }
358
359 /**
360 * Gemini Omni Flash job creation via the Interactions API. Creates a
361 * background interaction requesting video output; the interaction id is
362 * the job id polled by `getVideoStatus` / `getVideo`.
363 */
364 private async createInteractionsVideoJob(
365 options: VideoGenerationOptions<
366 GeminiVideoModelProviderOptionsByName[TModel],
367 GeminiVideoModelSizeByName[TModel],
368 GeminiVideoModelDurationByName[TModel]
369 >,
370 ): Promise<VideoJobResult> {
371 const { prompt, size, duration, logger } = options
372 const modelOptions = options.modelOptions as
373 | GeminiOmniVideoProviderOptions
374 | undefined
375
376 try {
377 const resolved = resolveMediaPrompt(prompt)
378
379 if (resolved.audios.length > 0) {
380 throw new Error(
381 `${this.name}.createVideoJob does not support audio prompt parts (model: ${this.model}).`,
382 )
383 }
384
385 const content: Array<InteractionContent> = [
386 ...resolved.images.map(mediaPartToInteractionsContent),
387 ...resolved.videos.map(mediaPartToInteractionsContent),
388 ]
389 if (resolved.text) {
390 content.push({ type: 'text', text: resolved.text })
391 }
392 if (content.length === 0) {
393 throw new Error(
394 `${this.name}.createVideoJob: the prompt produced no content to send (model: ${this.model}).`,
395 )
396 }
397
398 // Reject out-of-range durations locally rather than snapping (which
399 // would silently change the clip length the caller asked for) or
400 // letting the live API reject them after the round trip.
401 const durations = this.availableDurations()
402 if (
403 duration !== undefined &&
404 durations.kind === 'range' &&
405 (duration < durations.min || duration > durations.max)
406 ) {
407 throw new Error(
408 `${this.name}.createVideoJob: duration ${duration}s is outside the ${durations.min}–${durations.max}s range supported by ${this.model}. Use snapDuration() to snap arbitrary values into range.`,
409 )
410 }
411
412 // Aspect ratio, clip length, and resolution ride on `response_format`.
413 // Duration is a `"<seconds>s"` string. Resolution comes from the
414 // optional `size` suffix (`'16:9_1080p'`), defaulting to 720p when
415 // omitted — https://ai.google.dev/gemini-api/docs/omni
416 const parsedSize =
417 size !== undefined ? parseGeminiOmniVideoSize(size) : undefined
418 const responseFormat =
419 parsedSize !== undefined || duration !== undefined
420 ? {
421 response_format: {
422 type: 'video' as const,
423 ...(parsedSize !== undefined && {
424 aspect_ratio: parsedSize.aspectRatio,
425 ...(parsedSize.resolution !== undefined && {
426 resolution: parsedSize.resolution,
427 }),
428 }),
429 ...(duration !== undefined && { duration: `${duration}s` }),
430 },
431 }
432 : {}
433
434 const interaction = await this.client.interactions.create({
435 ...modelOptions,
436 model: this.model,
437 input: [{ type: 'user_input', content }],
438 response_modalities: ['video'],
439 background: true,
440 ...responseFormat,
441 })
442
443 if (!interaction.id) {
444 throw new Error(
445 'Gemini Omni did not return an interaction id for the video generation job.',
446 )
447 }
448
449 return { jobId: interaction.id, model: this.model }
450 } catch (error) {
451 logger.errors(`${this.name}.createVideoJob fatal`, {
452 error,
453 source: `${this.name}.createVideoJob`,
454 })
455 throw error
456 }
457 }
458
459 /**
460 * Route image prompt parts onto Veo's request fields by `metadata.role`.
461 */
462 private async routeImageParts(
463 parts: Array<ImagePart<MediaInputMetadata>>,
464 ): Promise<{
465 image: Image | undefined
466 lastFrame: Image | undefined
467 referenceImages: Array<VideoGenerationReferenceImage>
468 }> {
469 let image: Image | undefined
470 let lastFrame: Image | undefined
471 const referenceImages: Array<VideoGenerationReferenceImage> = []
472
473 for (const part of parts) {
474 const role = part.metadata?.role
475 switch (role) {
476 case 'end_frame': {
477 if (lastFrame) {
478 throw new Error(
479 `${this.name}: Veo accepts at most one 'end_frame' image.`,
480 )
481 }
482 lastFrame = await imagePartToVeoImage(part, this.allowUrlFetch)
483 break
484 }
485 case 'reference':
486 case 'character': {
487 referenceImages.push({
488 image: await imagePartToVeoImage(part, this.allowUrlFetch),
489 referenceType: VideoGenerationReferenceType.ASSET,
490 })
491 break
492 }
493 case 'start_frame':
494 case undefined: {
495 if (image) {
496 throw new Error(
497 `${this.name}: Veo accepts at most one starting image; received multiple 'start_frame'/un-roled images. Use metadata.role ('end_frame', 'reference') to disambiguate the others.`,
498 )
499 }
500 image = await imagePartToVeoImage(part, this.allowUrlFetch)
501 break
502 }
503 case 'mask':
504 case 'control':
505 throw new Error(
506 `${this.name}: unsupported image role "${role}" for Veo video generation.`,
507 )
508 }
509 }
510
511 return { image, lastFrame, referenceImages }
512 }
513
514 async getVideoStatus(jobId: string): Promise<VideoStatusResult> {
515 if (isInteractionsVideoModel(this.model)) {
516 return await this.getInteractionsVideoStatus(jobId)
517 }
518 const operation = await this.getOperation(jobId)
519
520 if (!operation.done) {
521 return { jobId, status: 'processing' }
522 }
523
524 if (operation.error) {
525 return {
526 jobId,
527 status: 'failed',
528 error: operationErrorMessage(operation.error),
529 }
530 }
531
532 // The operation can finish "successfully" with every sample dropped by
533 // Responsible-AI filters — surface that as a failure instead of letting
534 // getVideo() throw on an empty response.
535 const videos = operation.response?.generatedVideos ?? []
536 if (videos.length === 0) {
537 const reasons = operation.response?.raiMediaFilteredReasons
538 return {
539 jobId,
540 status: 'failed',
541 error: reasons?.length
542 ? `Video was filtered by Responsible-AI: ${reasons.join('; ')}`
543 : 'Veo returned no generated videos.',
544 }
545 }
546
547 return { jobId, status: 'completed' }
548 }
549
550 /**
551 * Poll an Omni background interaction. `in_progress` maps to
552 * 'processing'; a `completed` interaction with no video content (e.g.
553 * filtered output) is surfaced as a failure so `getVideo` doesn't
554 * throw on an empty response. `requires_action` also fails: the adapter
555 * never sends tools, so it can only arise via
556 * `previous_interaction_id` chaining onto a tool-bearing interaction —
557 * and such an interaction never progresses without a client response,
558 * so polling it would spin until timeout.
559 */
560 private async getInteractionsVideoStatus(
561 jobId: string,
562 ): Promise<VideoStatusResult> {
563 const interaction = await this.getInteraction(jobId)
564 const status = interaction.status
565
566 if (status === 'in_progress') {
567 return { jobId, status: 'processing' }
568 }
569 if (status === 'requires_action') {
570 return {
571 jobId,
572 status: 'failed',
573 error:
574 'Gemini Omni interaction is waiting on a client action (tool response), which the video jobs flow does not support.',
575 }
576 }
577 if (status === 'completed') {
578 if (!extractInteractionVideo(interaction)) {
579 return {
580 jobId,
581 status: 'failed',
582 error:
583 'Gemini Omni completed the interaction without returning a video (the output may have been filtered).',
584 }
585 }
586 return { jobId, status: 'completed' }
587 }
588 return {
589 jobId,
590 status: 'failed',
591 error: `Gemini Omni video generation ended with status "${status}".`,
592 }
593 }
594
595 override async getVideo(jobId: string): Promise<VideoUrlResult> {
596 if (isInteractionsVideoModel(this.model)) {
597 return await this.getInteractionsVideoUrl(jobId)
598 }
599 const operation = await this.getOperation(jobId)
600
601 if (!operation.done) {
602 throw new Error(
603 `Video is not ready yet. Check status first. Job ID: ${jobId}`,
604 )
605 }
606
607 if (operation.error) {
608 throw new Error(
609 `Video generation failed: ${operationErrorMessage(operation.error)}`,
610 )
611 }
612
613 const uri = operation.response?.generatedVideos?.[0]?.video?.uri
614 if (!uri) {
615 const reasons = operation.response?.raiMediaFilteredReasons
616 throw new Error(
617 reasons?.length
618 ? `Video was filtered by Responsible-AI: ${reasons.join('; ')}`
619 : `Video URL not found in operation response. Job ID: ${jobId}`,
620 )
621 }
622
623 return { jobId, url: uri }
624 }
625
626 /**
627 * Extract the finished Omni video. Inline base64 output (the API default)
628 * becomes a `data:` URL — matching the OpenAI Sora adapter's inline
629 * delivery — and URI delivery passes through (Files API URIs need the API
630 * key to download, like Veo). Usage carries the video-modality output
631 * tokens (Omni bills per second of video, reported as tokens).
632 */
633 private async getInteractionsVideoUrl(
634 jobId: string,
635 ): Promise<VideoUrlResult> {
636 const interaction = await this.getInteraction(jobId)
637 const status = interaction.status
638
639 if (status === 'in_progress') {
640 throw new Error(
641 `Video is not ready yet. Check status first. Job ID: ${jobId}`,
642 )
643 }
644 if (status !== 'completed') {
645 throw new Error(
646 `Video generation failed: Gemini Omni interaction ended with status "${status}". Job ID: ${jobId}`,
647 )
648 }
649
650 const video = extractInteractionVideo(interaction)
651 if (!video) {
652 throw new Error(
653 `Video not found in interaction response (the output may have been filtered). Job ID: ${jobId}`,
654 )
655 }
656
657 const usage = interactionUsageToTokenUsage(interaction.usage)
658 const url = video.uri ?? `data:${video.mimeType};base64,${video.data}`
659 return { jobId, url, ...(usage && { usage }) }
660 }
661
662 override availableDurations(): DurationOptions<
663 GeminiVideoModelDurationByName[TModel]
664 > {
665 return getGeminiVideoDurationOptions(this.model)
666 }
667
668 /**
669 * Fetch the long-running operation by name. The SDK's
670 * `operations.getVideosOperation` needs a real `GenerateVideosOperation`
671 * instance (it calls `_fromAPIResponse` on it), so reconstruct one from
672 * the job ID rather than passing an object literal.
673 */
674 private async getOperation(jobId: string): Promise<GenerateVideosOperation> {
675 const operation = new GenerateVideosOperation()
676 operation.name = jobId
677 return await this.client.operations.getVideosOperation({ operation })
678 }
679
680 /**
681 * Fetch an Omni background interaction by id.
682 */
683 private async getInteraction(jobId: string): Promise<Interaction> {
684 return await this.client.interactions.get(jobId)
685 }
686}
687
688/**
689 * Creates a Gemini video adapter with an explicit API key.
690 * Type resolution happens here at the call site.
691 *
692 * @experimental Video generation is an experimental feature and may change.
693 *
694 * @param model - The model name (e.g., 'veo-3.1-generate-preview')
695 * @param apiKey - Your Google API key
696 * @param config - Optional additional configuration
697 * @returns Configured Gemini video adapter instance with resolved types
698 *
699 * @example
700 * ```typescript
701 * const adapter = createGeminiVideo('veo-3.1-generate-preview', 'your-api-key');
702 *
703 * const { jobId } = await generateVideo({
704 * adapter,
705 * prompt: 'A beautiful sunset over the ocean',
706 * duration: adapter.snapDuration(7), // → 6
707 * });
708 * ```
709 */
710export function createGeminiVideo<TModel extends GeminiVideoModel>(
711 model: TModel,
712 apiKey: string,
713 config?: Omit<GeminiVideoConfig, 'apiKey'>,
714): GeminiVideoAdapter<TModel>
715export function createGeminiVideo<TModel extends GeminiVideoModel>(
716 model: TModel,
717 apiKey: string,
718 config?: Omit<GeminiVideoConfig, 'apiKey'>,
719): GeminiVideoAdapter<TModel> {
720 return new GeminiVideoAdapter({ apiKey, ...config }, model)
721}
722
723/**
724 * Creates a Gemini video adapter with automatic API key detection from environment variables.
725 * Type resolution happens here at the call site.
726 *
727 * Looks for `GOOGLE_API_KEY` or `GEMINI_API_KEY` in:
728 * - `process.env` (Node.js)
729 * - `window.env` (Browser with injected env)
730 *
731 * @experimental Video generation is an experimental feature and may change.
732 *
733 * @param model - The model name (e.g., 'veo-3.1-generate-preview')
734 * @param config - Optional configuration (excluding apiKey which is auto-detected)
735 * @returns Configured Gemini video adapter instance with resolved types
736 * @throws Error if GOOGLE_API_KEY or GEMINI_API_KEY is not found in environment
737 *
738 * @example
739 * ```typescript
740 * // Automatically uses GOOGLE_API_KEY from environment
741 * const adapter = geminiVideo('veo-3.1-generate-preview');
742 *
743 * // Create a video generation job
744 * const { jobId } = await generateVideo({
745 * adapter,
746 * prompt: 'A cat playing piano'
747 * });
748 *
749 * // Poll for status
750 * const status = await getVideoJobStatus({ adapter, jobId });
751 * ```
752 */
753export function geminiVideo<TModel extends GeminiVideoModel>(
754 model: TModel,
755 config?: Omit<GeminiVideoConfig, 'apiKey'>,
756): GeminiVideoAdapter<TModel>
757export function geminiVideo<TModel extends GeminiVideoModel>(
758 model: TModel,
759 config?: Omit<GeminiVideoConfig, 'apiKey'>,
760): GeminiVideoAdapter<TModel> {
761 const apiKey = getGeminiApiKeyFromEnv()
762 return createGeminiVideo(model, apiKey, config)
763}