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

video.ts

299 lines8.7 KB

1import { fal } from '@fal-ai/client'
2import { resolveMediaPrompt } from '@tanstack/ai'
3import { BaseVideoAdapter } from '@tanstack/ai/adapters'
4import {
5 configureFalClient,
6 generateId as utilGenerateId,
7} from '../utils/client'
8import { buildFalUsage, takeBillableUnits } from '../utils/billing'
9import {
10 getFalVideoDurationOptions,
11 mapVideoSizeToFalFormat,
12} from '../video/video-provider-options'
13import {
14 contentSourceToFalUrl,
15 mapImageInputsToFalVideoFields,
16} from '../image/image-inputs'
17import type { DurationOptions } from '@tanstack/ai/adapters'
18import type {
19 AudioPart,
20 MediaInputMetadata,
21 VideoGenerationOptions,
22 VideoJobResult,
23 VideoPart,
24 VideoStatusResult,
25 VideoUrlResult,
26} from '@tanstack/ai'
27import type {
28 FalModel,
29 FalModelInput,
30 FalModelVideoDuration,
31 FalModelVideoSize,
32 FalVideoPromptModalitiesFor,
33 FalVideoProviderOptions,
34} from '../model-meta'
35import type { FalClientConfig } from '../utils/client'
36​
37/**
38 * Map video conditioning inputs onto fal field names.
39 * Video-to-video endpoints on fal almost universally use `video_url`; the
40 * occasional model takes `video_urls` (rare). Mirror the image-input logic
41 * positionally with a `reference` role escape hatch via `reference_video_urls`.
42 */
43function mapVideoInputsToFalFields(
44 videoInputs?: ReadonlyArray<VideoPart<MediaInputMetadata>>,
45): Record<string, unknown> {
46 if (!videoInputs || videoInputs.length === 0) return {}
47 const references: Array<string> = []
48 const sources: Array<string> = []
49 for (const part of videoInputs) {
50 const url = videoPartToUrl(part)
51 if (
52 part.metadata?.role === 'reference' ||
53 part.metadata?.role === 'character'
54 ) {
55 references.push(url)
56 } else {
57 sources.push(url)
58 }
59 }
60 const out: Record<string, unknown> = {}
61 if (references.length > 0) out.reference_video_urls = references
62 if (sources.length === 1) {
63 out.video_url = sources[0]
64 } else if (sources.length > 1) {
65 out.video_urls = sources
66 }
67 return out
69​
70function mapAudioInputsToFalFields(
71 audioInputs?: ReadonlyArray<AudioPart<MediaInputMetadata>>,
72): Record<string, unknown> {
73 if (!audioInputs || audioInputs.length === 0) return {}
74 const [part, ...rest] = audioInputs
75 if (!part || rest.length > 0) {
76 throw new Error(
77 `fal: exactly one audio prompt part is supported (received ${audioInputs.length}).`,
78 )
79 }
80 return {
81 audio_url: contentSourceToFalUrl(part.source),
82 }
84​
85function videoPartToUrl(part: VideoPart<MediaInputMetadata>): string {
86 return contentSourceToFalUrl(part.source)
88​
89type FalQueueStatus = 'IN_QUEUE' | 'IN_PROGRESS' | 'COMPLETED'
90​
91interface FalStatusResponse {
92 status: FalQueueStatus
93 queue_position?: number
94 logs?: Array<{ message: string }>
96​
97interface FalVideoResultData {
98 video?: { url: string }
99 video_url?: string
101​
102/**
103 * Maps fal.ai queue status to TanStack AI video status.
104 *
105 * Note: fal.ai does not return a FAILED queue status. Errors surface
106 * as exceptions when fetching results from a COMPLETED job (e.g. 422
107 * validation errors). Those are handled in getVideo().
108 */
109function mapFalStatusToVideoStatus(
110 falStatus: FalQueueStatus,
111): VideoStatusResult['status'] {
112 switch (falStatus) {
113 case 'IN_QUEUE':
114 return 'pending'
115 case 'IN_PROGRESS':
116 return 'processing'
117 case 'COMPLETED':
118 return 'completed'
119 default:
120 return 'processing'
121 }
123​
124/**
125 * fal.ai video generation adapter.
126 * Supports MiniMax, Luma, Kling, Hunyuan, and other fal.ai video models.
127 *
128 * Uses fal.ai's comprehensive type system to provide autocomplete
129 * and type safety for all supported video models.
130 *
131 * @experimental Video generation is an experimental feature and may change.
132 */
133export class FalVideoAdapter<TModel extends FalModel> extends BaseVideoAdapter<
134 TModel,
135 FalVideoProviderOptions<TModel>,
136 Record<TModel, FalVideoProviderOptions<TModel>>,
137 Record<TModel, FalModelVideoSize<TModel>>,
138 Record<TModel, FalVideoPromptModalitiesFor<TModel>>,
139 Record<TModel, FalModelVideoDuration<TModel>>
140> {
141 override readonly kind = 'video' as const
142 readonly name = 'fal' as const
143 // Consumes fal storage URLs uploaded via falFiles().
144 override readonly supportsFileSources = true
145​
146 constructor(model: TModel, config?: FalClientConfig) {
147 super({}, model)
148 configureFalClient(config)
149 }
150​
151 async createVideoJob(
152 options: VideoGenerationOptions<
153 FalVideoProviderOptions<TModel>,
154 FalModelVideoSize<TModel>,
155 FalModelVideoDuration<TModel>
156 >,
157 ): Promise<VideoJobResult> {
158 const { size, duration, modelOptions, logger } = options
159​
160 logger.request(`activity=generateVideo provider=fal model=${this.model}`, {
161 provider: 'fal',
162 model: this.model,
163 })
164​
165 try {
166 const resolved = resolveMediaPrompt(options.prompt)
167 const sizeParams = mapVideoSizeToFalFormat(size)
168 const inputImageFields = mapImageInputsToFalVideoFields(
169 this.model,
170 resolved.images,
171 )
172 const videoFields = mapVideoInputsToFalFields(resolved.videos)
173 const audioFields = mapAudioInputsToFalFields(resolved.audios)
174​
175 const input = {
176 ...sizeParams,
177 ...inputImageFields,
178 ...videoFields,
179 ...audioFields,
180 // modelOptions applied after derived media fields so explicit user
181 // overrides (video_url, reference_video_urls, audio_url, ...) win.
182 ...modelOptions,
183 // Media-only prompts omit the prompt field rather than sending an
184 // empty string (e.g. pure image-to-video endpoints).
185 ...(resolved.text ? { prompt: resolved.text } : {}),
186 ...(duration !== undefined ? { duration } : {}),
187 } as FalModelInput<TModel>
188​
189 // Submit to queue and get request ID. Request-specific abortSignal only —
190 // never via fal.config() (global; would cancel concurrent jobs).
191 const { request_id } = await fal.queue.submit(this.model, {
192 input,
193 ...(options.abortSignal ? { abortSignal: options.abortSignal } : {}),
194 })
195​
196 return {
197 jobId: request_id,
198 model: this.model,
199 }
200 } catch (error) {
201 logger.errors('fal.createVideoJob fatal', {
202 error,
203 source: 'fal.createVideoJob',
204 })
205 throw error
206 }
207 }
208​
209 override availableDurations(): DurationOptions<
210 FalModelVideoDuration<TModel>
211 > {
212 return getFalVideoDurationOptions(this.model)
213 }
214​
215 async getVideoStatus(jobId: string): Promise<VideoStatusResult> {
216 const statusResponse = (await fal.queue.status(this.model, {
217 requestId: jobId,
218 logs: true,
219 })) as FalStatusResponse
220​
221 return {
222 jobId,
223 status: mapFalStatusToVideoStatus(statusResponse.status),
224 ...(statusResponse.queue_position != null
225 ? {
226 progress: Math.max(0, 100 - statusResponse.queue_position * 10),
227 }
228 : {}),
229 }
230 }
231​
232 override async getVideo(jobId: string): Promise<VideoUrlResult> {
233 let result
234 try {
235 result = await fal.queue.result(this.model, {
236 requestId: jobId,
237 })
238 } catch (error: unknown) {
239 // fal.ai may report COMPLETED status but throw on result fetch
240 // (e.g. 422 validation errors). Extract the detailed error info.
241 const err = error as { body?: { detail?: unknown }; message?: string }
242 const detail = err.body?.detail
243 if (Array.isArray(detail)) {
244 const messages = detail.map(
245 (d: { msg?: string; loc?: Array<string> }) =>
246 d.loc ? `${d.loc.join('.')}: ${d.msg}` : d.msg,
247 )
248 throw new Error(`Video generation failed: ${messages.join('; ')}`)
249 }
250 throw new Error(
251 `Failed to retrieve video result: ${err.message || String(error)}`,
252 )
253 }
254​
255 const data = result.data as FalVideoResultData
256​
257 // Different models return video URL in different formats
258 const url = data.video?.url || data.video_url
259 if (!url) {
260 throw new Error('Video URL not found in response')
261 }
262​
263 const usage = buildFalUsage(takeBillableUnits(result.requestId))
264​
265 return {
266 jobId,
267 url,
268 ...(usage ? { usage } : {}),
269 }
270 }
271​
272 protected override generateId(): string {
273 return utilGenerateId(this.name)
274 }
276​
277/**
278 * Create a fal.ai video adapter with an explicit API key.
279 *
280 * @experimental Video generation is an experimental feature and may change.
281 */
282export function createFalVideo<TModel extends FalModel>(
283 model: TModel,
284 config?: FalClientConfig,
285): FalVideoAdapter<TModel> {
286 return new FalVideoAdapter(model, config)
288​
289/**
290 * Create a fal.ai video adapter using config.apiKey or the FAL_KEY environment variable.
291 *
292 * @experimental Video generation is an experimental feature and may change.
293 */
294export function falVideo<TModel extends FalModel>(
295 model: TModel,
296 config?: FalClientConfig,
297): FalVideoAdapter<TModel> {
298 return createFalVideo(model, config)