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 { getOpenAIApiKeyFromEnv } from '../utils/client'
6import { imagePartToFile } from '../image/image-input-to-file'
7import {
8 getOpenAIVideoDurationOptions,
9 toApiSeconds,
10 validateVideoSeconds,
11 validateVideoSize,
12} from '../video/video-provider-options'
13import type { DurationOptions } from '@tanstack/ai/adapters'
14import type {
15 VideoGenerationOptions,
16 VideoJobResult,
17 VideoStatusResult,
18 VideoStreamResult,
19 VideoUrlResult,
20} from '@tanstack/ai'
21import type OpenAI_SDK from 'openai'
22import type { OpenAIVideoModel } from '../model-meta'
23import type {
24 OpenAIVideoModelDurationByName,
25 OpenAIVideoModelInputModalitiesByName,
26 OpenAIVideoModelProviderOptionsByName,
27 OpenAIVideoModelSizeByName,
28 OpenAIVideoProviderOptions,
29 OpenAIVideoSeconds,
30} from '../video/video-provider-options'
31import type { OpenAIClientConfig } from '../utils/client'
32
33/**
34 * Configuration for OpenAI video adapter.
35 *
36 * @experimental Video generation is an experimental feature and may change.
37 */
38export interface OpenAIVideoConfig extends OpenAIClientConfig {
39 /**
40 * Opt into fetching HTTP(S) image URL inputs for Sora's `input_reference`.
41 * The endpoint requires uploaded file bytes (no URL passthrough), so an
42 * HTTP(S) URL has to be downloaded and buffered in memory — which can OOM
43 * constrained runtimes (e.g. Cloudflare Workers). When `false` (the
44 * default), HTTP(S) URL image inputs throw; pass a `data:` URI, or set this
45 * to `true` to opt into buffering.
46 */
47 allowUrlFetch?: boolean
48}
49
50/**
51 * OpenAI Video Generation Adapter
52 *
53 * Tree-shakeable adapter for OpenAI video generation functionality using Sora-2.
54 * Uses a jobs/polling architecture for async video generation.
55 *
56 * @experimental Video generation is an experimental feature and may change.
57 *
58 * Features:
59 * - Async job-based video generation
60 * - Status polling for job progress
61 * - URL retrieval for completed videos
62 * - Model-specific type-safe provider options
63 */
64export class OpenAIVideoAdapter<
65 TModel extends OpenAIVideoModel,
66> extends BaseVideoAdapter<
67 TModel,
68 OpenAIVideoProviderOptions,
69 OpenAIVideoModelProviderOptionsByName,
70 OpenAIVideoModelSizeByName,
71 OpenAIVideoModelInputModalitiesByName,
72 OpenAIVideoModelDurationByName
73> {
74 readonly name = 'openai' as const
75
76 protected client: OpenAI
77 protected clientConfig: OpenAIVideoConfig
78
79 constructor(config: OpenAIVideoConfig, model: TModel) {
80 // `VideoAdapterConfig` declares its optional fields without `| undefined`,
81 // which collides with `OpenAIClientConfig` fields like `timeout?: number | undefined`.
82 // We hold our own typed copy on `clientConfig` and pass an empty object up.
83 super({}, model)
84 this.clientConfig = config
85 const { allowUrlFetch: _allowUrlFetch, ...clientOptions } = config
86 this.client = new OpenAI(clientOptions)
87 }
88
89 async createVideoJob(
90 options: VideoGenerationOptions<
91 OpenAIVideoProviderOptions,
92 OpenAIVideoModelSizeByName[TModel],
93 OpenAIVideoModelDurationByName[TModel]
94 >,
95 ): Promise<VideoJobResult> {
96 const { model, size, duration, modelOptions } = options
97
98 const resolvedSize = size ?? modelOptions?.size
99 validateVideoSize(model, resolvedSize)
100 const seconds = duration ?? modelOptions?.seconds
101 validateVideoSeconds(model, seconds)
102
103 const resolved = resolveMediaPrompt(options.prompt)
104
105 if (resolved.videos.length > 0) {
106 throw new Error(
107 `${this.name}.createVideoJob does not support video prompt parts (model: ${model}).`,
108 )
109 }
110 if (resolved.audios.length > 0) {
111 throw new Error(
112 `${this.name}.createVideoJob does not support audio prompt parts (model: ${model}).`,
113 )
114 }
115 if (resolved.images.length > 1) {
116 throw new Error(
117 `${this.name}: Sora accepts at most one input_reference image; received ${resolved.images.length}.`,
118 )
119 }
120
121 const request: OpenAI_SDK.Videos.VideoCreateParams = {
122 model,
123 prompt: resolved.text,
124 }
125 const [inputReference] = resolved.images
126 if (inputReference) {
127 // Sora's `input_reference` is a single Uploadable; convert TanStack
128 // ImagePart (URL or base64) → File before handing it to the SDK.
129 request.input_reference = await imagePartToFile(
130 inputReference,
131 'input-reference',
132 this.clientConfig.allowUrlFetch ?? false,
133 )
134 }
135 // `VideoCreateParams.size` is `size?: VideoSize` (no `| undefined`), so we
136 // narrow before assignment instead of casting from a `T | undefined` source.
137 if (resolvedSize) {
138 request.size = resolvedSize
139 }
140 if (seconds !== undefined) {
141 const apiSeconds = toApiSeconds(seconds)
142 if (apiSeconds !== undefined) {
143 request.seconds = apiSeconds
144 }
145 }
146
147 try {
148 options.logger.request(
149 `activity=video.create provider=${this.name} model=${model} size=${request.size ?? 'default'} seconds=${request.seconds ?? 'default'}`,
150 { provider: this.name, model },
151 )
152 const videosClient = this.getVideosClient()
153 const response = await videosClient.create(request)
154 return { jobId: response.id, model }
155 } catch (error: any) {
156 options.logger.errors(`${this.name}.createVideoJob fatal`, {
157 error: toRunErrorPayload(error, `${this.name}.createVideoJob failed`),
158 source: `${this.name}.createVideoJob`,
159 })
160 if (error?.message?.includes('videos') || error?.code === 'invalid_api') {
161 throw new Error(
162 `Video generation API is not available. The API may require special access. ` +
163 `Original error: ${error.message}`,
164 )
165 }
166 throw error
167 }
168 }
169
170 /**
171 * The video API on the OpenAI SDK is still experimental and shipped on some
172 * SDK versions but not others; access through `videosClient` lets us treat
173 * the path uniformly even when the SDK lacks first-class typings here.
174 */
175 private getVideosClient(): {
176 create: (req: Record<string, any>) => Promise<{ id: string }>
177 retrieve: (id: string) => Promise<{
178 id: string
179 status: string
180 progress?: number
181 url?: string
182 expires_at?: number
183 error?: { message?: string }
184 }>
185 downloadContent: (id: string) => Promise<Response>
186 } {
187 return (this.client as { videos: any }).videos
188 }
189
190 async getVideoStatus(jobId: string): Promise<VideoStatusResult> {
191 try {
192 const videosClient = this.getVideosClient()
193 const response = await videosClient.retrieve(jobId)
194 // `VideoStatusResult` declares optional fields without `| undefined`;
195 // spread conditionally so we omit absent fields rather than assigning
196 // `undefined`.
197 return {
198 jobId,
199 status: this.mapStatus(response.status),
200 progress: response.progress,
201 ...(response.error?.message !== undefined && {
202 error: response.error.message,
203 }),
204 }
205 } catch (error: any) {
206 if (error.status === 404) {
207 return { jobId, status: 'failed', error: 'Job not found' }
208 }
209 throw error
210 }
211 }
212
213 override async getVideo(
214 jobId: string,
215 ): Promise<VideoUrlResult | VideoStreamResult> {
216 try {
217 const videosClient = this.getVideosClient()
218
219 // Prefer retrieve() because many openai-compatible backends (and the
220 // aimock test harness) return the URL directly on the video resource
221 // and do not implement a separate /content endpoint.
222 const videoInfo = await videosClient.retrieve(jobId)
223 if (videoInfo.url) {
224 // `VideoUrlResult.expiresAt` is `expiresAt?: Date` without `| undefined`;
225 // omit the field when the API didn't return an expiry.
226 return {
227 jobId,
228 url: videoInfo.url,
229 ...(videoInfo.expires_at !== undefined && {
230 expiresAt: new Date(videoInfo.expires_at),
231 }),
232 }
233 }
234
235 // No URL: hand the download stream to generation middleware (which
236 // stores it and sets the URL) instead of buffering the whole video.
237 const response = await videosClient.downloadContent(jobId)
238 if (!response.body) throw new Error('Video download returned no body')
239 return {
240 jobId,
241 body: response.body,
242 contentType: response.headers.get('content-type') || 'video/mp4',
243 }
244 } catch (error: any) {
245 if (error.status === 404) {
246 throw new Error(`Video job not found: ${jobId}`)
247 }
248 if (error.status === 400) {
249 throw new Error(
250 `Video is not ready for download. Check status first. Job ID: ${jobId}`,
251 )
252 }
253 throw error
254 }
255 }
256
257 override availableDurations(): DurationOptions<OpenAIVideoSeconds> {
258 return getOpenAIVideoDurationOptions(this.model)
259 }
260
261 /**
262 * Returns the API string (`'4' | '8' | '12'`). Ties keep the earlier
263 * option, so `6` and `"6s"` snap to `'4'`.
264 */
265 override snapDuration(
266 input: number | string,
267 ): OpenAIVideoSeconds | undefined {
268 return snapToDurationOption(
269 input,
270 getOpenAIVideoDurationOptions(this.model),
271 )
272 }
273
274 protected mapStatus(
275 apiStatus: string,
276 ): 'pending' | 'processing' | 'completed' | 'failed' {
277 switch (apiStatus) {
278 case 'queued':
279 case 'pending':
280 return 'pending'
281 case 'processing':
282 case 'in_progress':
283 return 'processing'
284 case 'completed':
285 case 'succeeded':
286 return 'completed'
287 case 'failed':
288 case 'error':
289 case 'cancelled':
290 return 'failed'
291 default:
292 return 'processing'
293 }
294 }
295}
296
297/**
298 * Creates an OpenAI video adapter with an explicit API key.
299 * Type resolution happens here at the call site.
300 *
301 * @experimental Video generation is an experimental feature and may change.
302 *
303 * @param model - The model name (e.g., 'sora-2')
304 * @param apiKey - Your OpenAI API key
305 * @param config - Optional additional configuration
306 * @returns Configured OpenAI video adapter instance with resolved types
307 *
308 * @example
309 * ```typescript
310 * const adapter = createOpenaiVideo('sora-2', 'your-api-key');
311 *
312 * const { jobId } = await generateVideo({
313 * adapter,
314 * prompt: 'A beautiful sunset over the ocean'
315 * });
316 * ```
317 */
318export function createOpenaiVideo<TModel extends OpenAIVideoModel>(
319 model: TModel,
320 apiKey: string,
321 config?: Omit<OpenAIVideoConfig, 'apiKey'>,
322): OpenAIVideoAdapter<TModel> {
323 return new OpenAIVideoAdapter({ apiKey, ...config }, model)
324}
325
326/**
327 * Creates an OpenAI video adapter with automatic API key detection from environment variables.
328 * Type resolution happens here at the call site.
329 *
330 * Looks for `OPENAI_API_KEY` in:
331 * - `process.env` (Node.js)
332 * - `window.env` (Browser with injected env)
333 *
334 * @experimental Video generation is an experimental feature and may change.
335 *
336 * @param model - The model name (e.g., 'sora-2')
337 * @param config - Optional configuration (excluding apiKey which is auto-detected)
338 * @returns Configured OpenAI video adapter instance with resolved types
339 * @throws Error if OPENAI_API_KEY is not found in environment
340 *
341 * @example
342 * ```typescript
343 * // Automatically uses OPENAI_API_KEY from environment
344 * const adapter = openaiVideo('sora-2');
345 *
346 * // Create a video generation job
347 * const { jobId } = await generateVideo({
348 * adapter,
349 * prompt: 'A cat playing piano'
350 * });
351 *
352 * // Poll for status
353 * const status = await getVideoJobStatus({
354 * adapter,
355 * jobId
356 * });
357 * ```
358 */
359export function openaiVideo<TModel extends OpenAIVideoModel>(
360 model: TModel,
361 config?: Omit<OpenAIVideoConfig, 'apiKey'>,
362): OpenAIVideoAdapter<TModel> {
363 const apiKey = getOpenAIApiKeyFromEnv()
364 return createOpenaiVideo(model, apiKey, config)
365}