Open History to see the last commit
1import OpenAI from 'openai'
2import { resolveMediaPrompt } from '@tanstack/ai'
3import { BaseVideoAdapter, snapToDurationOption } from '@tanstack/ai/adapters'
4import { toRunErrorPayload } from '@tanstack/ai/adapter-internals'
5import { arrayBufferToBase64 } from '@tanstack/ai-utils'
6import {
7 getLovableApiKeyFromEnv,
8 openaiRequestOptions,
9 withLovableDefaults,
10} from '../utils/client'
11import { imagePartToFile } from '../image/image-input-to-file'
12import {
13 toApiSeconds,
14 validateHighResDuration,
15 validateVideoSeconds,
16 validateVideoSize,
17} from '../video/video-provider-options'
18import type { DurationOptions } from '@tanstack/ai/adapters'
19import type {
20 VideoGenerationOptions,
21 VideoJobResult,
22 VideoStatusResult,
23 VideoUrlResult,
24} from '@tanstack/ai'
25import type OpenAI_SDK from 'openai'
26import type {
27 LovableVideoModel,
28 LovableVideoModelDurationByName,
29 LovableVideoModelInputModalitiesByName,
30 LovableVideoModelProviderOptionsByName,
31 LovableVideoModelSizeByName,
32} from '../model-meta'
33import type {
34 LovableVideoDuration,
35 LovableVideoProviderOptions,
36} from '../video/video-provider-options'
37import type { LovableClientConfig } from '../utils/client'
38
39const LARGE_MEDIA_BUFFER_BYTES = 10 * 1024 * 1024
40const VIDEO_DURATIONS = [
41 4, 6, 8,
42] as const satisfies ReadonlyArray<LovableVideoDuration>
43
44function warnIfLargeMediaBuffer(byteLength: number, source: string): void {
45 if (byteLength <= LARGE_MEDIA_BUFFER_BYTES) return
46 console.warn(
47 `[lovable.${source}] downloaded ${(byteLength / 1024 / 1024).toFixed(1)} MiB into memory before base64 encoding. ` +
48 `Workers/serverless runtimes commonly run out of memory above ~10 MiB. ` +
49 `Consider streaming the video through a CDN or your own storage layer instead.`,
50 )
51}
52
53/**
54 * @experimental Video generation is an experimental feature and may change.
55 */
56export interface LovableVideoConfig extends LovableClientConfig {
57 /**
58 * Opt into fetching HTTP(S) image URL inputs for `input_reference`.
59 * The endpoint requires uploaded file bytes, so an HTTP(S) URL has to be
60 * downloaded and buffered in memory. When `false` (the default), HTTP(S)
61 * URL image inputs throw.
62 */
63 allowUrlFetch?: boolean
64}
65
66/**
67 * @experimental Video generation is an experimental feature and may change.
68 */
69export class LovableVideoAdapter<
70 TModel extends LovableVideoModel,
71> extends BaseVideoAdapter<
72 TModel,
73 LovableVideoProviderOptions,
74 LovableVideoModelProviderOptionsByName,
75 LovableVideoModelSizeByName,
76 LovableVideoModelInputModalitiesByName,
77 LovableVideoModelDurationByName
78> {
79 readonly name = 'lovable' as const
80
81 protected client: OpenAI
82 protected clientConfig: LovableVideoConfig
83
84 constructor(config: LovableVideoConfig, model: TModel) {
85 super({}, model)
86 this.clientConfig = config
87 const { allowUrlFetch: _allowUrlFetch, ...clientOptions } = config
88 this.client = new OpenAI(withLovableDefaults(clientOptions))
89 }
90
91 async createVideoJob(
92 options: VideoGenerationOptions<
93 LovableVideoProviderOptions,
94 LovableVideoModelSizeByName[TModel],
95 LovableVideoModelDurationByName[TModel]
96 >,
97 ): Promise<VideoJobResult> {
98 const { model, size, duration, modelOptions } = options
99
100 const resolvedSize = size ?? modelOptions?.size
101 validateVideoSize(model, resolvedSize)
102 const seconds = duration ?? modelOptions?.seconds
103 validateVideoSeconds(model, seconds)
104 validateHighResDuration(model, resolvedSize, seconds)
105
106 const resolved = resolveMediaPrompt(options.prompt)
107
108 if (resolved.videos.length > 0) {
109 throw new Error(
110 `${this.name}.createVideoJob does not support video prompt parts (model: ${model}).`,
111 )
112 }
113 if (resolved.audios.length > 0) {
114 throw new Error(
115 `${this.name}.createVideoJob does not support audio prompt parts (model: ${model}).`,
116 )
117 }
118 if (resolved.images.length > 1) {
119 throw new Error(
120 `${this.name}: video models accept at most one input_reference image; received ${resolved.images.length}.`,
121 )
122 }
123
124 const request: OpenAI_SDK.Videos.VideoCreateParams = {
125 model,
126 prompt: resolved.text,
127 }
128 const [inputReference] = resolved.images
129 if (inputReference) {
130 request.input_reference = await imagePartToFile(
131 inputReference,
132 'input-reference',
133 this.clientConfig.allowUrlFetch ?? false,
134 options.abortSignal,
135 )
136 }
137 if (resolvedSize) {
138 // Gateway Veo sizes include 1080p and 4K, which are not in the OpenAI SDK union.
139 request.size = resolvedSize as OpenAI_SDK.Videos.VideoSize
140 }
141 if (seconds !== undefined) {
142 const apiSeconds = toApiSeconds(seconds)
143 if (apiSeconds !== undefined) {
144 // Gateway Veo clips can be 6 seconds. The OpenAI SDK union is 4/8/12.
145 request.seconds = apiSeconds as OpenAI_SDK.Videos.VideoSeconds
146 }
147 }
148
149 try {
150 options.logger.request(
151 `activity=video.create provider=${this.name} model=${model} size=${request.size ?? 'default'} seconds=${request.seconds ?? 'default'}`,
152 { provider: this.name, model },
153 )
154 const response = await this.client.videos.create(
155 request,
156 openaiRequestOptions(options.abortSignal),
157 )
158 return { jobId: response.id, model }
159 } catch (error: unknown) {
160 options.logger.errors(`${this.name}.createVideoJob fatal`, {
161 error: toRunErrorPayload(error, `${this.name}.createVideoJob failed`),
162 source: `${this.name}.createVideoJob`,
163 })
164 throw error
165 }
166 }
167
168 async getVideoStatus(jobId: string): Promise<VideoStatusResult> {
169 try {
170 const response = await this.client.videos.retrieve(jobId)
171 return {
172 jobId,
173 status: this.mapStatus(response.status),
174 progress: response.progress,
175 ...(response.error?.message !== undefined && {
176 error: response.error.message,
177 }),
178 }
179 } catch (error: unknown) {
180 if (isHttpStatus(error, 404)) {
181 return { jobId, status: 'failed', error: 'Job not found' }
182 }
183 throw error
184 }
185 }
186
187 async getVideoUrl(jobId: string): Promise<VideoUrlResult> {
188 try {
189 const videoInfo = await this.client.videos.retrieve(jobId)
190 const directUrl = videoResourceUrl(videoInfo)
191 if (directUrl) {
192 return {
193 jobId,
194 url: directUrl,
195 ...(videoInfo.expires_at != null && {
196 expiresAt: new Date(videoInfo.expires_at * 1000),
197 }),
198 }
199 }
200
201 const contentResponse = await this.client.videos.downloadContent(jobId)
202 return dataUrlFromResponse(
203 jobId,
204 contentResponse,
205 'video.downloadContent',
206 )
207 } catch (error: unknown) {
208 if (isHttpStatus(error, 404)) {
209 throw new Error(`Video job not found: ${jobId}`)
210 }
211 if (isHttpStatus(error, 400)) {
212 throw new Error(
213 `Video is not ready for download. Check status first. Job ID: ${jobId}`,
214 )
215 }
216 throw error
217 }
218 }
219
220 override availableDurations(): DurationOptions<LovableVideoDuration> {
221 return { kind: 'discrete', values: VIDEO_DURATIONS }
222 }
223
224 override snapDuration(seconds: number): LovableVideoDuration | undefined {
225 return snapToDurationOption(seconds, this.availableDurations())
226 }
227
228 protected mapStatus(
229 apiStatus: string,
230 ): 'pending' | 'processing' | 'completed' | 'failed' {
231 switch (apiStatus) {
232 case 'queued':
233 case 'pending':
234 return 'pending'
235 case 'processing':
236 case 'in_progress':
237 return 'processing'
238 case 'completed':
239 case 'succeeded':
240 return 'completed'
241 case 'failed':
242 case 'error':
243 case 'cancelled':
244 return 'failed'
245 default:
246 return 'processing'
247 }
248 }
249}
250
251async function dataUrlFromResponse(
252 jobId: string,
253 contentResponse: Response,
254 source: string,
255): Promise<VideoUrlResult> {
256 const videoBlob = await contentResponse.blob()
257 const buffer = await videoBlob.arrayBuffer()
258 warnIfLargeMediaBuffer(buffer.byteLength, source)
259 const base64 = arrayBufferToBase64(buffer)
260 const mimeType = contentResponse.headers.get('content-type') || 'video/mp4'
261 return {
262 jobId,
263 url: `data:${mimeType};base64,${base64}`,
264 }
265}
266
267function videoResourceUrl(video: OpenAI_SDK.Videos.Video): string | undefined {
268 const extra = video as OpenAI_SDK.Videos.Video & { url?: string }
269 if (extra.url && extra.url.length > 0) {
270 return extra.url
271 }
272 return undefined
273}
274
275function isHttpStatus(error: unknown, status: number): boolean {
276 return (
277 typeof error === 'object' &&
278 error !== null &&
279 'status' in error &&
280 (error as { status: unknown }).status === status
281 )
282}
283
284/**
285 * @experimental Video generation is an experimental feature and may change.
286 */
287export function createLovableVideo<TModel extends LovableVideoModel>(
288 model: TModel,
289 apiKey: string,
290 config?: Omit<LovableVideoConfig, 'apiKey'>,
291): LovableVideoAdapter<TModel> {
292 return new LovableVideoAdapter({ apiKey, ...config }, model)
293}
294
295/**
296 * @experimental Video generation is an experimental feature and may change.
297 */
298export function lovableVideo<TModel extends LovableVideoModel>(
299 model: TModel,
300 config?: Omit<LovableVideoConfig, 'apiKey'>,
301): LovableVideoAdapter<TModel> {
302 return createLovableVideo(model, getLovableApiKeyFromEnv(), config)
303}