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

video.ts

781 lines26.4 KB

1import {
2 GenerateVideosOperation,
3 VideoGenerationReferenceType,
4} from '@google/genai'
5import {
6 fileReferenceFor,
7 isFileSource,
8 resolveMediaPrompt,
9 unsupportedFileSourceError,
10} from '@tanstack/ai'
11import { BaseVideoAdapter, snapToDurationOption } 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
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)
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 }
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 }
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
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 }
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 `getVideoUrl` 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`, plus the deprecated
251 * `gemini-omni-flash-preview` alias) only serves the Interactions API:
252 * `createVideoJob` creates a background interaction with
253 * `response_modalities: ['video']`, `getVideoStatus` polls it by id, and
254 * `getVideoUrl` returns the inline base64 MP4 as a `data:` URL (or the
255 * Files API URI when the server delivers by reference). Image and video
256 * prompt parts are sent as interaction content blocks, grouped as images,
257 * then videos, then the text prompt (interleaving is not preserved); pass
258 * `modelOptions.previous_interaction_id` to conversationally edit a prior
259 * Omni generation. `size` is an `aspectRatio_resolution` template
260 * (`'16:9'` or `'16:9_1080p'`); the optional suffix maps onto
261 * `response_format.resolution` (`'360p' | '720p' | '1080p' | '4k'`,
262 * default 720p).
263 *
264 * @experimental Video generation is an experimental feature and may change.
265 */
266export class GeminiVideoAdapter<
267 TModel extends GeminiVideoModel,
268> extends BaseVideoAdapter<
269 TModel,
270 GeminiVideoModelProviderOptionsByName[TModel],
271 GeminiVideoModelProviderOptionsByName,
272 GeminiVideoModelSizeByName,
273 GeminiVideoModelInputModalitiesByName,
274 GeminiVideoModelDurationByName
275> {
276 readonly name = 'gemini' as const
277 // The Interactions path consumes Gemini Files API references as content
278 // `uri`s; the Veo path still rejects them (raw bytes / gs:// only).
279 override readonly supportsFileSources = true
280​
281 protected client: GoogleGenAI
282 private readonly allowUrlFetch: boolean
283​
284 constructor(config: GeminiVideoConfig, model: TModel) {
285 super({}, model)
286 this.client = createGeminiClient(config)
287 this.allowUrlFetch = config.allowUrlFetch ?? false
288 }
289​
290 async createVideoJob(
291 options: VideoGenerationOptions<
292 GeminiVideoModelProviderOptionsByName[TModel],
293 GeminiVideoModelSizeByName[TModel],
294 GeminiVideoModelDurationByName[TModel]
295 >,
296 ): Promise<VideoJobResult> {
297 const { prompt, size, duration, logger } = options
298​
299 logger.request(
300 `activity=video.create provider=${this.name} model=${this.model} size=${size ?? 'default'} duration=${duration ?? 'default'}`,
301 { provider: this.name, model: this.model },
302 )
303​
304 if (isInteractionsVideoModel(this.model)) {
305 return await this.createInteractionsVideoJob(options)
306 }
307 const modelOptions = options.modelOptions as
308 | GeminiVideoProviderOptions
309 | undefined
310​
311 try {
312 const resolved = resolveMediaPrompt(prompt)
313​
314 if (resolved.videos.length > 0) {
315 throw new Error(
316 `${this.name}.createVideoJob does not support video prompt parts (model: ${this.model}).`,
317 )
318 }
319 if (resolved.audios.length > 0) {
320 throw new Error(
321 `${this.name}.createVideoJob does not support audio prompt parts (model: ${this.model}).`,
322 )
323 }
324​
325 const { image, lastFrame, referenceImages } = await this.routeImageParts(
326 resolved.images,
327 )
328​
329 const config: GenerateVideosConfig = {
330 ...modelOptions,
331 ...(size !== undefined && { aspectRatio: size }),
332 ...(duration !== undefined && { durationSeconds: duration }),
333 ...(lastFrame && { lastFrame }),
334 ...(referenceImages.length > 0 && { referenceImages }),
335 }
336​
337 const operation = await this.client.models.generateVideos({
338 model: this.model,
339 prompt: resolved.text,
340 ...(image && { image }),
341 config,
342 })
343​
344 if (!operation.name) {
345 throw new Error(
346 'Veo did not return an operation name for the video generation job.',
347 )
348 }
349​
350 return { jobId: operation.name, model: this.model }
351 } catch (error) {
352 logger.errors(`${this.name}.createVideoJob fatal`, {
353 error,
354 source: `${this.name}.createVideoJob`,
355 })
356 throw error
357 }
358 }
359​
360 /**
361 * Gemini Omni Flash job creation via the Interactions API. Creates a
362 * background interaction requesting video output; the interaction id is
363 * the job id polled by `getVideoStatus` / `getVideoUrl`.
364 */
365 private async createInteractionsVideoJob(
366 options: VideoGenerationOptions<
367 GeminiVideoModelProviderOptionsByName[TModel],
368 GeminiVideoModelSizeByName[TModel],
369 GeminiVideoModelDurationByName[TModel]
370 >,
371 ): Promise<VideoJobResult> {
372 const { prompt, size, duration, logger } = options
373 const modelOptions = options.modelOptions as
374 | GeminiOmniVideoProviderOptions
375 | undefined
376​
377 try {
378 const resolved = resolveMediaPrompt(prompt)
379​
380 if (resolved.audios.length > 0) {
381 throw new Error(
382 `${this.name}.createVideoJob does not support audio prompt parts (model: ${this.model}).`,
383 )
384 }
385​
386 const content: Array<InteractionContent> = [
387 ...resolved.images.map(mediaPartToInteractionsContent),
388 ...resolved.videos.map(mediaPartToInteractionsContent),
389 ]
390 if (resolved.text) {
391 content.push({ type: 'text', text: resolved.text })
392 }
393 if (content.length === 0) {
394 throw new Error(
395 `${this.name}.createVideoJob: the prompt produced no content to send (model: ${this.model}).`,
396 )
397 }
398​
399 // Reject out-of-range durations locally rather than snapping (which
400 // would silently change the clip length the caller asked for) or
401 // letting the live API reject them after the round trip.
402 const durations = this.availableDurations()
403 if (
404 duration !== undefined &&
405 durations.kind === 'range' &&
406 (duration < durations.min || duration > durations.max)
407 ) {
408 throw new Error(
409 `${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.`,
410 )
411 }
412​
413 // Aspect ratio, clip length, and resolution ride on `response_format`.
414 // Duration is a `"<seconds>s"` string. Resolution comes from the
415 // optional `size` suffix (`'16:9_1080p'`), defaulting to 720p when
416 // omitted — https://ai.google.dev/gemini-api/docs/omni
417 const parsedSize =
418 size !== undefined ? parseGeminiOmniVideoSize(size) : undefined
419 const responseFormat =
420 parsedSize !== undefined || duration !== undefined
421 ? {
422 response_format: {
423 type: 'video' as const,
424 ...(parsedSize !== undefined && {
425 aspect_ratio: parsedSize.aspectRatio,
426 ...(parsedSize.resolution !== undefined && {
427 resolution: parsedSize.resolution,
428 }),
429 }),
430 ...(duration !== undefined && { duration: `${duration}s` }),
431 },
432 }
433 : {}
434​
435 const interaction = await this.client.interactions.create({
436 ...modelOptions,
437 model: this.model,
438 input: [{ type: 'user_input', content }],
439 response_modalities: ['video'],
440 background: true,
441 ...responseFormat,
442 })
443​
444 if (!interaction.id) {
445 throw new Error(
446 'Gemini Omni did not return an interaction id for the video generation job.',
447 )
448 }
449​
450 return { jobId: interaction.id, model: this.model }
451 } catch (error) {
452 logger.errors(`${this.name}.createVideoJob fatal`, {
453 error,
454 source: `${this.name}.createVideoJob`,
455 })
456 throw error
457 }
458 }
459​
460 /**
461 * Route image prompt parts onto Veo's request fields by `metadata.role`.
462 */
463 private async routeImageParts(
464 parts: Array<ImagePart<MediaInputMetadata>>,
465 ): Promise<{
466 image: Image | undefined
467 lastFrame: Image | undefined
468 referenceImages: Array<VideoGenerationReferenceImage>
469 }> {
470 let image: Image | undefined
471 let lastFrame: Image | undefined
472 const referenceImages: Array<VideoGenerationReferenceImage> = []
473​
474 for (const part of parts) {
475 const role = part.metadata?.role
476 switch (role) {
477 case 'end_frame': {
478 if (lastFrame) {
479 throw new Error(
480 `${this.name}: Veo accepts at most one 'end_frame' image.`,
481 )
482 }
483 lastFrame = await imagePartToVeoImage(part, this.allowUrlFetch)
484 break
485 }
486 case 'reference':
487 case 'character': {
488 referenceImages.push({
489 image: await imagePartToVeoImage(part, this.allowUrlFetch),
490 referenceType: VideoGenerationReferenceType.ASSET,
491 })
492 break
493 }
494 case 'start_frame':
495 case undefined: {
496 if (image) {
497 throw new Error(
498 `${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.`,
499 )
500 }
501 image = await imagePartToVeoImage(part, this.allowUrlFetch)
502 break
503 }
504 case 'mask':
505 case 'control':
506 throw new Error(
507 `${this.name}: unsupported image role "${role}" for Veo video generation.`,
508 )
509 }
510 }
511​
512 return { image, lastFrame, referenceImages }
513 }
514​
515 async getVideoStatus(jobId: string): Promise<VideoStatusResult> {
516 if (isInteractionsVideoModel(this.model)) {
517 return await this.getInteractionsVideoStatus(jobId)
518 }
519 const operation = await this.getOperation(jobId)
520​
521 if (!operation.done) {
522 return { jobId, status: 'processing' }
523 }
524​
525 if (operation.error) {
526 return {
527 jobId,
528 status: 'failed',
529 error: operationErrorMessage(operation.error),
530 }
531 }
532​
533 // The operation can finish "successfully" with every sample dropped by
534 // Responsible-AI filters — surface that as a failure instead of letting
535 // getVideoUrl() throw on an empty response.
536 const videos = operation.response?.generatedVideos ?? []
537 if (videos.length === 0) {
538 const reasons = operation.response?.raiMediaFilteredReasons
539 return {
540 jobId,
541 status: 'failed',
542 error: reasons?.length
543 ? `Video was filtered by Responsible-AI: ${reasons.join('; ')}`
544 : 'Veo returned no generated videos.',
545 }
546 }
547​
548 return { jobId, status: 'completed' }
549 }
550​
551 /**
552 * Poll an Omni background interaction. `in_progress` maps to
553 * 'processing'; a `completed` interaction with no video content (e.g.
554 * filtered output) is surfaced as a failure so `getVideoUrl` doesn't
555 * throw on an empty response. `requires_action` also fails: the adapter
556 * never sends tools, so it can only arise via
557 * `previous_interaction_id` chaining onto a tool-bearing interaction —
558 * and such an interaction never progresses without a client response,
559 * so polling it would spin until timeout.
560 */
561 private async getInteractionsVideoStatus(
562 jobId: string,
563 ): Promise<VideoStatusResult> {
564 const interaction = await this.getInteraction(jobId)
565 const status = interaction.status
566​
567 if (status === 'in_progress') {
568 return { jobId, status: 'processing' }
569 }
570 if (status === 'requires_action') {
571 return {
572 jobId,
573 status: 'failed',
574 error:
575 'Gemini Omni interaction is waiting on a client action (tool response), which the video jobs flow does not support.',
576 }
577 }
578 if (status === 'completed') {
579 if (!extractInteractionVideo(interaction)) {
580 return {
581 jobId,
582 status: 'failed',
583 error:
584 'Gemini Omni completed the interaction without returning a video (the output may have been filtered).',
585 }
586 }
587 return { jobId, status: 'completed' }
588 }
589 return {
590 jobId,
591 status: 'failed',
592 error: `Gemini Omni video generation ended with status "${status}".`,
593 }
594 }
595​
596 async getVideoUrl(jobId: string): Promise<VideoUrlResult> {
597 if (isInteractionsVideoModel(this.model)) {
598 return await this.getInteractionsVideoUrl(jobId)
599 }
600 const operation = await this.getOperation(jobId)
601​
602 if (!operation.done) {
603 throw new Error(
604 `Video is not ready yet. Check status first. Job ID: ${jobId}`,
605 )
606 }
607​
608 if (operation.error) {
609 throw new Error(
610 `Video generation failed: ${operationErrorMessage(operation.error)}`,
611 )
612 }
613​
614 const uri = operation.response?.generatedVideos?.[0]?.video?.uri
615 if (!uri) {
616 const reasons = operation.response?.raiMediaFilteredReasons
617 throw new Error(
618 reasons?.length
619 ? `Video was filtered by Responsible-AI: ${reasons.join('; ')}`
620 : `Video URL not found in operation response. Job ID: ${jobId}`,
621 )
622 }
623​
624 return { jobId, url: uri }
625 }
626​
627 /**
628 * Extract the finished Omni video. Inline base64 output (the API default)
629 * becomes a `data:` URL — matching the OpenAI Sora adapter's inline
630 * delivery — and URI delivery passes through (Files API URIs need the API
631 * key to download, like Veo). Usage carries the video-modality output
632 * tokens (Omni bills per second of video, reported as tokens).
633 */
634 private async getInteractionsVideoUrl(
635 jobId: string,
636 ): Promise<VideoUrlResult> {
637 const interaction = await this.getInteraction(jobId)
638 const status = interaction.status
639​
640 if (status === 'in_progress') {
641 throw new Error(
642 `Video is not ready yet. Check status first. Job ID: ${jobId}`,
643 )
644 }
645 if (status !== 'completed') {
646 throw new Error(
647 `Video generation failed: Gemini Omni interaction ended with status "${status}". Job ID: ${jobId}`,
648 )
649 }
650​
651 const video = extractInteractionVideo(interaction)
652 if (!video) {
653 throw new Error(
654 `Video not found in interaction response (the output may have been filtered). Job ID: ${jobId}`,
655 )
656 }
657​
658 const usage = interactionUsageToTokenUsage(interaction.usage)
659 const url = video.uri ?? `data:${video.mimeType};base64,${video.data}`
660 return { jobId, url, ...(usage && { usage }) }
661 }
662​
663 override availableDurations(): DurationOptions<
664 GeminiVideoModelDurationByName[TModel]
665 > {
666 return getGeminiVideoDurationOptions(this.model)
667 }
668​
669 override snapDuration(
670 seconds: number,
671 ): GeminiVideoModelDurationByName[TModel] | undefined {
672 return snapToDurationOption(seconds, this.availableDurations())
673 }
674​
675 /**
676 * Fetch the long-running operation by name. The SDK's
677 * `operations.getVideosOperation` needs a real `GenerateVideosOperation`
678 * instance (it calls `_fromAPIResponse` on it), so reconstruct one from
679 * the job ID rather than passing an object literal.
680 */
681 private async getOperation(jobId: string): Promise<GenerateVideosOperation> {
682 const operation = new GenerateVideosOperation()
683 operation.name = jobId
684 return await this.client.operations.getVideosOperation({ operation })
685 }
686​
687 /**
688 * Fetch an Omni background interaction by id.
689 */
690 private async getInteraction(jobId: string): Promise<Interaction> {
691 return await this.client.interactions.get(jobId)
692 }
694​
695/** @deprecated Shuts down 2026-09-30. Use `gemini-omni-1.1-flash`. */
696export function createGeminiVideo(
697 model: 'gemini-omni-flash-preview',
698 apiKey: string,
699 config?: Omit<GeminiVideoConfig, 'apiKey'>,
700): GeminiVideoAdapter<'gemini-omni-flash-preview'>
701/**
702 * Creates a Gemini video adapter with an explicit API key.
703 * Type resolution happens here at the call site.
704 *
705 * @experimental Video generation is an experimental feature and may change.
706 *
707 * @param model - The model name (e.g., 'veo-3.1-generate-preview')
708 * @param apiKey - Your Google API key
709 * @param config - Optional additional configuration
710 * @returns Configured Gemini video adapter instance with resolved types
711 *
712 * @example
713 * ```typescript
714 * const adapter = createGeminiVideo('veo-3.1-generate-preview', 'your-api-key');
715 *
716 * const { jobId } = await generateVideo({
717 * adapter,
718 * prompt: 'A beautiful sunset over the ocean',
719 * duration: adapter.snapDuration(7), // → 6
720 * });
721 * ```
722 */
723export function createGeminiVideo<TModel extends GeminiVideoModel>(
724 model: TModel,
725 apiKey: string,
726 config?: Omit<GeminiVideoConfig, 'apiKey'>,
727): GeminiVideoAdapter<TModel>
728export function createGeminiVideo<TModel extends GeminiVideoModel>(
729 model: TModel,
730 apiKey: string,
731 config?: Omit<GeminiVideoConfig, 'apiKey'>,
732): GeminiVideoAdapter<TModel> {
733 return new GeminiVideoAdapter({ apiKey, ...config }, model)
735​
736/** @deprecated Shuts down 2026-09-30. Use `gemini-omni-1.1-flash`. */
737export function geminiVideo(
738 model: 'gemini-omni-flash-preview',
739 config?: Omit<GeminiVideoConfig, 'apiKey'>,
740): GeminiVideoAdapter<'gemini-omni-flash-preview'>
741/**
742 * Creates a Gemini video adapter with automatic API key detection from environment variables.
743 * Type resolution happens here at the call site.
744 *
745 * Looks for `GOOGLE_API_KEY` or `GEMINI_API_KEY` in:
746 * - `process.env` (Node.js)
747 * - `window.env` (Browser with injected env)
748 *
749 * @experimental Video generation is an experimental feature and may change.
750 *
751 * @param model - The model name (e.g., 'veo-3.1-generate-preview')
752 * @param config - Optional configuration (excluding apiKey which is auto-detected)
753 * @returns Configured Gemini video adapter instance with resolved types
754 * @throws Error if GOOGLE_API_KEY or GEMINI_API_KEY is not found in environment
755 *
756 * @example
757 * ```typescript
758 * // Automatically uses GOOGLE_API_KEY from environment
759 * const adapter = geminiVideo('veo-3.1-generate-preview');
760 *
761 * // Create a video generation job
762 * const { jobId } = await generateVideo({
763 * adapter,
764 * prompt: 'A cat playing piano'
765 * });
766 *
767 * // Poll for status
768 * const status = await getVideoJobStatus({ adapter, jobId });
769 * ```
770 */
771export function geminiVideo<TModel extends GeminiVideoModel>(
772 model: TModel,
773 config?: Omit<GeminiVideoConfig, 'apiKey'>,
774): GeminiVideoAdapter<TModel>
775export function geminiVideo<TModel extends GeminiVideoModel>(
776 model: TModel,
777 config?: Omit<GeminiVideoConfig, 'apiKey'>,
778): GeminiVideoAdapter<TModel> {
779 const apiKey = getGeminiApiKeyFromEnv()
780 return createGeminiVideo(model, apiKey, config)