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

video.ts

278 lines8.3 KB

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