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

fal.md

474 lines16.2 KB

1---
2title: fal.ai
3id: fal-adapter
4description: "Use fal.ai in TanStack AI with @tanstack/ai-fal: 600+ hosted models for images, video, live video, speech, transcription, music, and sound effects."
5keywords:
6 - tanstack ai
7 - fal.ai
8 - fal
9 - image generation
10 - video generation
11 - flux
12 - nano banana
13 - adapter
14---
15​
16The fal.ai adapter calls hosted models for images, video, live video, speech, transcription, music, and sound effects. It has no text chat and no tools.
17​
18The quick setup below generates an image on your server and shows it in React. For a full app, see the [media example](https://github.com/TanStack/ai/tree/main/examples/ts-react-media).
19​
20## 1. Install
21​
22<!-- ::start:tabs variant="package-manager" mode="install" -->
23​
24react: @tanstack/ai-fal
25vue: @tanstack/ai-fal
26solid: @tanstack/ai-fal
27svelte: @tanstack/ai-fal
28preact: @tanstack/ai-fal
29angular: @tanstack/ai-fal
30vanilla: @tanstack/ai-fal
31octane: @tanstack/ai-fal
32​
33<!-- ::end:tabs -->
34​
35## 2. Set the API key
36​
37Create a key at [fal.ai](https://fal.ai). Put it in the environment of your server:
38​
39```bash
40FAL_KEY=your-fal-api-key
41```
42​
43All fal adapters read `FAL_KEY`. To pass the key in code, set `apiKey` in the config:
44​
45```typescript
46import { falImage } from "@tanstack/ai-fal";
47​
48const adapter = falImage("fal-ai/nano-banana-pro", {
49 apiKey: process.env.FAL_KEY!,
50});
51```
52​
53## 3. Generate an image on the server
54​
55Add a `POST` route at `/api/generate/image`:
56​
57```typescript
58import {
59 generateImage,
60 generationParamsFromRequest,
61 toServerSentEventsResponse,
62} from "@tanstack/ai";
63import { falImage } from "@tanstack/ai-fal";
64​
65export async function POST(request: Request) {
66 const { input, threadId } = await generationParamsFromRequest("image", request);
67 if (typeof input.prompt !== "string") {
68 return new Response("Send a text prompt.", { status: 400 });
69 }
70​
71 const stream = generateImage({
72 adapter: falImage("fal-ai/nano-banana-pro"),
73 prompt: input.prompt,
74 threadId,
75 stream: true,
76 });
77​
78 return toServerSentEventsResponse(stream);
80```
81​
82## 4. Show the image
83​
84```tsx
85import { fetchServerSentEvents, useGenerateImage } from "@tanstack/ai-react";
86​
87export function ImageGenerator() {
88 const { generate, result, isLoading, error } = useGenerateImage({
89 connection: fetchServerSentEvents("/api/generate/image"),
90 threadId: "image-studio",
91 });
92​
93 return (
94 <div>
95 <button
96 onClick={() => generate({ prompt: "A futuristic cityscape at sunset" })}
97 disabled={isLoading}
98 >
99 {isLoading ? "Generating..." : "Generate"}
100 </button>
101 {error && <p role="alert">{error.message}</p>}
102 {result?.images.map((image, index) => (
103 <img
104 key={index}
105 src={image.url || `data:image/png;base64,${image.b64Json}`}
106 alt="Generated image"
107 />
108 ))}
109 </div>
110 );
112```
113​
114Click the button. The image shows up below it. For the other frameworks, see [Generation Hooks](../media/generation-hooks).
115​
116## Model options
117​
118Each fal model has its own options. Write the model id as a string literal, and TypeScript completes `size` and `modelOptions` for that model:
119​
120```typescript
121import { generateImage } from "@tanstack/ai";
122import { falImage } from "@tanstack/ai-fal";
123​
124const result = await generateImage({
125 adapter: falImage("fal-ai/z-image/turbo"),
126 prompt: "A serene mountain landscape",
127 threadId: "thread-1",
128 numberOfImages: 1,
129 size: "landscape_16_9",
130 modelOptions: {
131 acceleration: "high",
132 enable_prompt_expansion: true,
133 },
134});
135​
136console.log(result.images);
137```
138​
139- Pass the id directly, not through a `string` variable. A variable loses the types of the model.
140- Any string works as a model id. A model that is newer than the fal SDK types runs, but has no autocomplete.
141​
142For the `size` formats, see [Image sizes](#image-sizes).
143​
144## Video
145​
146> Video generation is an [experimental feature](../media/video-generation).
147​
148Video runs as a job. `generateVideo()` starts the job, and `getVideoJobStatus()` reads its status:
149​
150```typescript
151import { generateVideo, getVideoJobStatus } from "@tanstack/ai";
152import { falVideo } from "@tanstack/ai-fal";
153​
154const adapter = falVideo("fal-ai/kling-video/v2.6/pro/text-to-video");
155​
156const job = await generateVideo({
157 adapter,
158 prompt: "A timelapse of a flower blooming",
159 threadId: "thread-1",
160 size: "16:9",
161 duration: "5",
162});
163​
164const status = await getVideoJobStatus({ adapter, jobId: job.jobId });
165​
166console.log(status.status); // "pending" | "processing" | "completed"
167```
168​
169To animate an image, use an image-to-video model and set the start image in `modelOptions`:
170​
171```typescript
172import { generateVideo } from "@tanstack/ai";
173import { falVideo } from "@tanstack/ai-fal";
174​
175const job = await generateVideo({
176 adapter: falVideo("fal-ai/kling-video/v2.6/pro/image-to-video"),
177 prompt: "Animate this scene with gentle wind",
178 threadId: "thread-1",
179 duration: "5",
180 modelOptions: {
181 start_image_url: "https://example.com/image.jpg",
182 generate_audio: true,
183 },
184});
185​
186console.log(job.jobId);
187```
188​
189The `duration` values of each model are in [Video durations](#video-durations). To poll from a React component, see [Video Generation](../media/video-generation).
190​
191## Live video
192​
193`falLiveVideo("minimax/h3-max/director")` starts a live video stream that you can steer. The browser connects through a proxy on your server. See [Live Generation](../media/live-generation#fal-h3-max-director).
194​
195## Speech
196​
197`falSpeech` gets the audio from the fal CDN and returns it as base64:
198​
199```typescript
200import { generateSpeech } from "@tanstack/ai";
201import { falSpeech } from "@tanstack/ai-fal";
202​
203const result = await generateSpeech({
204 adapter: falSpeech("fal-ai/gemini-3.1-flash-tts"),
205 text: "[warm, enthusiastic] Welcome to TanStack AI! [pause] Let's build something great.",
206 threadId: "thread-1",
207 voice: "Kore",
208});
209​
210console.log(result.format, result.contentType);
211```
212​
213`fal-ai/gemini-3.1-flash-tts` is the TTS model of Google. It supports 80+ languages. You can put speaker tags and style tags, such as `[pause]`, in the text. Its `modelOptions` have no autocomplete yet.
214​
215Other models put the voice in `modelOptions`:
216​
217```typescript
218import { generateSpeech } from "@tanstack/ai";
219import { falSpeech } from "@tanstack/ai-fal";
220​
221const result = await generateSpeech({
222 adapter: falSpeech("fal-ai/elevenlabs/tts/eleven-v3"),
223 text: "Welcome to TanStack AI.",
224 threadId: "thread-1",
225 modelOptions: {
226 voice: "Rachel",
227 stability: 0.5,
228 },
229});
230​
231console.log(result.audio); // Base64-encoded audio
232```
233​
234See [Text-to-Speech](../media/text-to-speech).
235​
236## Transcription
237​
238```typescript
239import { generateTranscription } from "@tanstack/ai";
240import { falTranscription } from "@tanstack/ai-fal";
241​
242const result = await generateTranscription({
243 adapter: falTranscription("fal-ai/whisper"),
244 audio: "https://example.com/recording.mp3",
245 language: "en",
246 threadId: "thread-1",
247});
248​
249console.log(result.text);
250console.log(result.language);
251​
252// When the model returns timestamps, they are in result.segments
253for (const segment of result.segments ?? []) {
254 console.log(`[${segment.start}s to ${segment.end}s] ${segment.text}`);
256```
257​
258`audio` takes a URL string, a `Blob`, a `File`, or an `ArrayBuffer`. The adapter wraps an `ArrayBuffer` in a `Blob` for the upload.
259​
260## Music and sound effects
261​
262`falAudio` returns a URL in `result.audio.url`. If you need the bytes, fetch the URL:
263​
264```typescript
265import { generateAudio } from "@tanstack/ai";
266import { falAudio } from "@tanstack/ai-fal";
267​
268const music = await generateAudio({
269 adapter: falAudio("fal-ai/minimax-music/v2.6"),
270 prompt: "City Pop, 80s retro, groovy synth bass, warm female vocal, 104 BPM, nostalgic urban night",
271 threadId: "thread-1",
272});
273​
274const sfx = await generateAudio({
275 adapter: falAudio("fal-ai/elevenlabs/sound-effects/v2"),
276 prompt: "Thunderclap with rain",
277 threadId: "thread-1",
278 duration: 5,
279});
280​
281console.log(music.audio.url, sfx.audio.url);
282```
283​
284Some music models take lyrics in `modelOptions`:
285​
286```typescript
287import { generateAudio } from "@tanstack/ai";
288import { falAudio } from "@tanstack/ai-fal";
289​
290const song = await generateAudio({
291 adapter: falAudio("fal-ai/diffrhythm"),
292 prompt: "An upbeat electronic track with synths",
293 threadId: "thread-1",
294 modelOptions: {
295 lyrics: "[verse]\nHello world\n[chorus]\nLa la la",
296 },
297});
298​
299console.log(song.audio.url);
300```
301​
302See [Audio Generation](../media/audio-generation).
303​
304## Files
305​
306`falFiles` uploads media to fal storage, so a request can point to the file by URL. fal storage is upload-only. See [Files API](../advanced/files-api).
307​
308## Models and options
309​
310fal has hundreds of models. These are popular picks. Any fal model id works.
311​
312### Image models
313​
314| Model | Description |
315|-------|-------------|
316| `fal-ai/nano-banana-pro` | Fast, high-quality images, up to 4K |
317| `fal-ai/flux-2/klein/9b` | Realistic images, clear text |
318| `fal-ai/z-image/turbo` | A very fast 6B-parameter model |
319| `xai/grok-imagine-image` | xAI images with prompt enhancement |
320​
321### Video models
322​
323| Model | Mode | Description |
324|-------|------|-------------|
325| `fal-ai/kling-video/v2.6/pro/text-to-video` | Text-to-video | High-quality text-to-video |
326| `fal-ai/kling-video/v2.6/pro/image-to-video` | Image-to-video | Animate images with Kling |
327| `fal-ai/veo3.1` | Text-to-video | Google Veo text-to-video |
328| `fal-ai/veo3.1/image-to-video` | Image-to-video | Google Veo image-to-video |
329| `xai/grok-imagine-video/text-to-video` | Text-to-video | xAI video from text |
330| `xai/grok-imagine-video/image-to-video` | Image-to-video | xAI video from an image |
331| `fal-ai/ltx-2/text-to-video/fast` | Text-to-video | Fast text-to-video |
332| `fal-ai/ltx-2/image-to-video/fast` | Image-to-video | Fast image-to-video |
333​
334### Live models
335​
336| Model | Description |
337|-------|-------------|
338| `minimax/h3-max/director` | A live stream that you can steer. Use `falLiveVideo()` with `generateLiveVideo()`. |
339​
340### Text-to-speech models
341​
342| Model | Description |
343|-------|-------------|
344| `fal-ai/gemini-3.1-flash-tts` | Google TTS with 80+ languages and style tags |
345| `fal-ai/elevenlabs/tts/eleven-v3` | ElevenLabs v3, expressive, several voices |
346| `fal-ai/elevenlabs/tts/turbo-v2.5` | ElevenLabs, low latency |
347| `fal-ai/minimax/speech-2.6-hd` | MiniMax HD speech |
348| `fal-ai/minimax/speech-2.6-turbo` | MiniMax, low latency |
349| `fal-ai/kokoro/american-english` | Kokoro. Also `british-english`, `french`, `spanish`, `italian`, `japanese`, `mandarin-chinese`, `hindi`, `brazilian-portuguese` |
350| `fal-ai/inworld-tts` | Inworld TTS-1.5 Max |
351| `fal-ai/chatterbox/text-to-speech/multilingual` | Chatterbox, many languages |
352| `fal-ai/dia-tts` | Dia, expressive dialogue |
353| `fal-ai/orpheus-tts` | Orpheus, open source |
354| `fal-ai/f5-tts` | F5-TTS, voice cloning |
355| `fal-ai/vibevoice/7b` | VibeVoice 7B, conversation |
356​
357### Transcription models
358​
359| Model | Description |
360|-------|-------------|
361| `fal-ai/whisper` | OpenAI Whisper on fal |
362| `fal-ai/wizper` | A faster Whisper with word timestamps |
363| `fal-ai/speech-to-text/turbo` | Fast speech-to-text with speaker labels |
364| `fal-ai/elevenlabs/speech-to-text` | ElevenLabs speech-to-text |
365​
366### Music and audio models
367​
368| Model | Mode | Description |
369|-------|------|-------------|
370| `fal-ai/minimax-music/v2.6` | Music | MiniMax Music 2.6, vocals and instruments from a prompt |
371| `fal-ai/minimax-music/v2.5` | Music | MiniMax Music 2.5 |
372| `fal-ai/minimax-music/v2` | Music | MiniMax Music v2, takes `lyrics_prompt` |
373| `fal-ai/diffrhythm` | Music | DiffRhythm, prompt and lyrics |
374| `fal-ai/lyria2` | Music | Google Lyria 2 |
375| `fal-ai/stable-audio-25/text-to-audio` | Music or audio | Stability AI Stable Audio 2.5 |
376| `fal-ai/mmaudio-v2/text-to-audio` | Audio | MMAudio v2 |
377| `fal-ai/elevenlabs/sound-effects/v2` | Sound effects | ElevenLabs sound effects |
378| `fal-ai/beatoven/sound-effect-generation` | Sound effects | Beatoven sound effects |
379| `fal-ai/thinksound` | Audio | Thinksound audio |
380​
381Some very new models, for example `fal-ai/gemini-3.1-flash-tts`, `fal-ai/minimax-music/v2.6`, and `fal-ai/beatoven/sound-effect-generation`, are not in the type map of `@fal-ai/client` yet. They work as plain string ids, with no autocomplete for `modelOptions`.
382​
383## Advanced
384​
385### Image sizes
386​
387`size` maps to `image_size`, or to `aspect_ratio` and `resolution`:
388​
389| Form | `size` | Sent to fal as |
390|--------|---------|---------|
391| Named | `"landscape_16_9"` | `image_size: "landscape_16_9"` |
392| Width x height | `"1536x1024"` | `image_size: "1536x1024"` |
393| Ratio and resolution | `"16:9_4K"` | `aspect_ratio: "16:9"`, `resolution: "4K"` |
394| Ratio only | `"16:9"` | `aspect_ratio: "16:9"` |
395​
396Named sizes change by model.
397​
398### Video durations
399​
400`duration` gets its type for each model from the `EndpointTypeMap` of `@fal-ai/client`. Popular models also have `availableDurations()` and `snapDuration()`, for a UI slider:
401​
402| Model | `duration` type | `availableDurations()` |
403| --- | --- | --- |
404| `fal-ai/kling-video/v1.6/{standard,pro}/text-to-video`, `fal-ai/kling-video/v2.6/pro/{text,image}-to-video` | `"5"` or `"10"` | discrete |
405| `fal-ai/kling-video/v3/pro/{text,image}-to-video` | `"3"` to `"15"` | discrete |
406| `fal-ai/pika/v2.2/text-to-video` | `"5"` or `"10"` | discrete |
407| `fal-ai/ltx-2.3/{text,image}-to-video` (and `/fast`) | `"6"`, `"8"`, or `"10"` | discrete |
408| `fal-ai/luma-dream-machine/ray-2` | `"5s"` or `"9s"` | discrete |
409| `fal-ai/veo3.1`, `fal-ai/veo3.1/fast` (and `/image-to-video`), `fal-ai/veo3` (and `/image-to-video`) | `"4s"`, `"6s"`, or `"8s"` | discrete |
410| `fal-ai/wan-25-preview/text-to-video` | `"2"` to `"15"` | discrete |
411| `fal-ai/minimax/video-01` | not accepted | `{ kind: "none" }` |
412| `fal-ai/hunyuan-video-v1.5/text-to-video` | not accepted (uses `num_frames`) | `{ kind: "none" }` |
413​
414```typescript
415import { generateVideo } from "@tanstack/ai";
416import { falVideo } from "@tanstack/ai-fal";
417​
418const adapter = falVideo("fal-ai/veo3.1");
419adapter.availableDurations(); // { kind: "discrete", values: ["4s", "6s", "8s"] }
420adapter.snapDuration(7); // "6s"
421​
422await generateVideo({
423 adapter,
424 prompt: "A timelapse of a city skyline at dusk",
425 threadId: "thread-1",
426 duration: adapter.snapDuration(7),
427});
428```
429​
430Other models still get the `duration` type from the SDK when the endpoint has the field. For these models, `availableDurations()` returns `{ kind: "none" }`.
431​
432### Configuration
433​
434Each factory takes an optional `FalClientConfig`:
435​
436- `apiKey`: your fal key. If you do not set a config, the adapter reads `FAL_KEY`.
437- `proxyUrl`: a proxy URL on your server, for calls from the browser.
438- `fetch`: a custom `fetch` for the fal requests. The adapter wraps it to read the billed units.
439​
440```typescript
441import { falImage } from "@tanstack/ai-fal";
442​
443const adapter = falImage("fal-ai/nano-banana-pro", {
444 apiKey: process.env.FAL_KEY!,
445 proxyUrl: "https://your-server.com/api/fal/proxy",
446});
447```
448​
449### Live video proxy
450​
451`generateLiveVideo()` returns the WMA app id on `result.model` (`fal-ai/minimax-h3-max-director`). In the browser:
452​
453- Open that id with `wma(live.model)` through a proxy on your server. The proxy attaches `FAL_KEY`.
454- Do not send `live.token` as `Key` credentials.
455- In the proxy, call `allowedFalLiveVideoProxyTarget()`. It lets the proxy forward only to WMA `/ice`, `/session`, `/session/heartbeat`, and Director `/ice`.
456​
457### API reference
458​
459Each factory takes `model` first and an optional `config` (`apiKey`, `proxyUrl`, `fetch`). Without `apiKey`, it reads `FAL_KEY`.
460​
461| Factory | Returns | Use it with |
462| --- | --- | --- |
463| `falImage(model, config?)` | `FalImageAdapter` | `generateImage()` |
464| `falVideo(model, config?)` | `FalVideoAdapter` | `generateVideo()`, `getVideoJobStatus()` |
465| `falLiveVideo(model, config?)` / `createFalLiveVideo(model, apiKey, config?)` | `FalLiveVideoAdapter` | `generateLiveVideo()` |
466| `falSpeech(model, config?)` | `FalSpeechAdapter` | `generateSpeech()`. The audio comes back as base64 in `result.audio`. |
467| `falTranscription(model, config?)` | `FalTranscriptionAdapter` | `generateTranscription()` |
468| `falAudio(model, config?)` | `FalAudioAdapter` | `generateAudio()`. The result has a URL at `result.audio.url`. |
469| `falFiles(config?)` | `FalFilesAdapter` | The [Files API](../advanced/files-api) |
470​
471Helpers:
472​
473- `getFalApiKeyFromEnv()`: reads `FAL_KEY`. Throws if it is not set.
474- `configureFalClient(config?)`: configures `@fal-ai/client`. The adapter constructors call it for you. It sets the credentials from the API key, and the proxy when you set `proxyUrl`.