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

image.ts

212 lines6.3 KB

1import { fal } from '@fal-ai/client'
2import { resolveMediaPrompt } from '@tanstack/ai'
3import { BaseImageAdapter } from '@tanstack/ai/adapters'
4import {
5 configureFalClient,
6 generateId as utilGenerateId,
7} from '../utils/client'
8import { buildFalUsage, takeBillableUnits } from '../utils/billing'
9import { mapSizeToFalFormat } from '../image/image-provider-options'
10import { mapImageInputsToFalFields } from '../image/image-inputs'
11import type { OutputType, Result } from '@fal-ai/client'
12import type { FalClientConfig } from '../utils/client'
13import type {
14 GeneratedImage,
15 ImageGenerationOptions,
16 ImageGenerationResult,
17 ResolvedMediaPrompt,
18} from '@tanstack/ai'
19import type {
20 FalImagePromptModalitiesFor,
21 FalImageProviderOptions,
22 FalModel,
23 FalModelImageSize,
24 FalModelInput,
25} from '../model-meta'
26​
27/**
28 * fal.ai image generation adapter with full type inference.
29 *
30 * Uses fal.ai's comprehensive type system to provide autocomplete
31 *
32 * and type safety for all 600+ supported models.
33 *
34 * @example
35 * ```typescript
36 * const adapter = falImage('fal-ai/flux/dev')
37 * const result = await adapter.generateImages({
38 * model: 'fal-ai/flux/dev',
39 * prompt: 'a cat',
40 * modelOptions: {
41 * num_inference_steps: 28, // Type-safe! Autocomplete works
42 * guidance_scale: 3.5,
43 * },
44 * })
45 * ```
46 */
47export class FalImageAdapter<TModel extends FalModel> extends BaseImageAdapter<
48 TModel,
49 FalImageProviderOptions<TModel>,
50 Record<TModel, FalImageProviderOptions<TModel>>,
51 Record<TModel, FalModelImageSize<TModel>>,
52 Record<TModel, FalImagePromptModalitiesFor<TModel>>
53> {
54 override readonly kind = 'image' as const
55 readonly name = 'fal' as const
56 // Consumes fal storage URLs uploaded via falFiles().
57 override readonly supportsFileSources = true
58​
59 constructor(model: TModel, config?: FalClientConfig) {
60 super(model, {})
61 configureFalClient(config)
62 }
63​
64 async generateImages(
65 options: ImageGenerationOptions<
66 FalImageProviderOptions<TModel>,
67 FalModelImageSize<TModel>
68 >,
69 ): Promise<ImageGenerationResult> {
70 const { logger } = options
71​
72 logger.request(`activity=generateImage provider=fal model=${this.model}`, {
73 provider: 'fal',
74 model: this.model,
75 })
76​
77 const resolved = resolveMediaPrompt(options.prompt)
78​
79 if (resolved.videos.length > 0) {
80 throw new Error(
81 `fal.generateImages does not support video prompt parts on model ${this.model}.`,
82 )
83 }
84 if (resolved.audios.length > 0) {
85 throw new Error(
86 `fal.generateImages does not support audio prompt parts on model ${this.model}.`,
87 )
88 }
89​
90 try {
91 const input = this.buildInput(options, resolved)
92 // Pass request-specific abortSignal only — never via fal.config(), which
93 // is global and would cancel concurrent generations from other calls.
94 const result = await fal.subscribe(this.model, {
95 input,
96 ...(options.abortSignal ? { abortSignal: options.abortSignal } : {}),
97 })
98 return this.transformResponse(result)
99 } catch (error) {
100 logger.errors('fal.generateImage fatal', {
101 error,
102 source: 'fal.generateImage',
103 })
104 throw error
105 }
106 }
107​
108 private buildInput(
109 options: ImageGenerationOptions<
110 FalImageProviderOptions<TModel>,
111 FalModelImageSize<TModel>
112 >,
113 resolved: ResolvedMediaPrompt,
114 ): FalModelInput<TModel> {
115 const sizeParams = mapSizeToFalFormat(options.size)
116 // Order matters: size and derived image-input fields first, then
117 // modelOptions (so explicit user overrides win for mask_url /
118 // control_image_url / reference_image_urls), then the call-controlled
119 // prompt / num_images, which always take precedence.
120 const inputFields = mapImageInputsToFalFields(this.model, resolved.images)
121 const input = {
122 ...sizeParams,
123 ...inputFields,
124 ...options.modelOptions,
125 // Media-only prompts (e.g. upscalers, background removal) omit the
126 // prompt field entirely rather than sending an empty string.
127 ...(resolved.text ? { prompt: resolved.text } : {}),
128 num_images: options.numberOfImages,
129 } as FalModelInput<TModel>
130 return input
131 }
132​
133 protected override generateId(): string {
134 return utilGenerateId(this.name)
135 }
136​
137 private transformResponse(
138 response: Result<OutputType<TModel>>,
139 ): ImageGenerationResult {
140 const images: Array<GeneratedImage> = []
141 const data = response.data
142​
143 // Handle array of images (most models return { images: [...] })
144 if ('images' in data && Array.isArray(data.images)) {
145 for (const img of data.images) {
146 images.push(this.parseImage(img))
147 }
148 }
149 // Handle single image response (some models return { image: {...} })
150 else if ('image' in data && data.image && typeof data.image === 'object') {
151 images.push(this.parseImage(data.image))
152 }
153​
154 if (images.length === 0) {
155 throw new Error(
156 'Unexpected fal image response shape. Expected images[] or image{}. Got keys: ' +
157 Object.keys(data).join(','),
158 )
159 }
160​
161 const usage = buildFalUsage(takeBillableUnits(response.requestId))
162​
163 return {
164 id: response.requestId || this.generateId(),
165 model: this.model,
166 images,
167 ...(usage ? { usage } : {}),
168 }
169 }
170​
171 private parseImage(img: unknown): GeneratedImage {
172 let url: string
173 if (typeof img === 'string') {
174 url = img
175 } else if (
176 img &&
177 typeof img === 'object' &&
178 'url' in img &&
179 typeof img.url === 'string'
180 ) {
181 url = (img as { url: string }).url
182 } else {
183 throw new Error(
184 `Invalid image payload from fal response: expected string or { url: string }, received ${
185 img === null ? 'null' : typeof img
186 }`,
187 )
188 }
189​
190 if (url.startsWith('data:')) {
191 const base64Match = url.match(/^data:image\/[^;]+;base64,(.+)$/)
192 if (base64Match && base64Match[1]) {
193 return { b64Json: base64Match[1] }
194 }
195 }
196 return { url }
197 }
199​
200export function createFalImage<TModel extends FalModel>(
201 model: TModel,
202 config?: FalClientConfig,
203): FalImageAdapter<TModel> {
204 return new FalImageAdapter(model, config)
206​
207export function falImage<TModel extends FalModel>(
208 model: TModel,
209 config?: FalClientConfig,
210): FalImageAdapter<TModel> {
211 return createFalImage(model, config)