Open History to see the last commit
1---
2title: Generation Hooks
3id: generation-hooks
4order: 7
5description: "Framework hooks for every TanStack AI media generation type — useGenerateImage, useGenerateAudio, useGenerateSpeech, useTranscription, useSummarize, useGenerateVideo."
6keywords:
7 - tanstack ai
8 - generation hooks
9 - useGenerateImage
10 - useGenerateAudio
11 - useGenerateSpeech
12 - useTranscription
13 - useSummarize
14 - useGenerateVideo
15 - react hooks
16---
17
18TanStack AI provides framework hooks for every generation type: image, audio, speech, transcription, summarization, and video. Each hook connects to a server endpoint and manages loading, error, and result state for you.
19
20> **Surviving reloads and dropped connections:** every generation hook takes the
21> same `persistence` option `useChat` does, so a long run's status and result
22> come back after a page reload or a dropped connection. It restores by
23> `threadId`, which for a generation names the slot successive runs fill
24> (`product-7-hero`) rather than a conversation. See
25> [Id map](../persistence/id-map). Setup is in
26> [Generation Persistence](../persistence/generation-persistence).
27
28## Overview
29
30Generation hooks share a consistent API across all media types:
31
32| Hook | Input | Result Type |
33|------|-------|-------------|
34| `useGenerateImage` | `ImageGenerateInput` | `ImageGenerationResult` |
35| `useGenerateAudio` | `AudioGenerateInput` | `AudioGenerationResult` |
36| `useGenerateSpeech` | `SpeechGenerateInput` | `TTSResult` |
37| `useTranscription` | `TranscriptionGenerateInput` | `TranscriptionResult` |
38| `useSummarize` | `SummarizeGenerateInput` | `SummarizationResult` |
39| `useGenerateVideo` | `VideoGenerateInput` | `VideoGenerateResult` |
40| `useGeneration` | Generic `TInput` | Generic `TResult` |
41
42Every hook returns the same core shape: `generate`, `result`, `isLoading`, `error`, `status`, `stop`, `reset`, and `runId` (the id of the job in flight, or `null`). You provide either a `connection` (streaming transport) or a `fetcher` (direct async call).
43
44## Server Setup
45
46Before using hooks on the client, you need a server endpoint that runs the generation and returns the result as SSE. Here's a minimal image generation endpoint:
47
48```typescript
49// routes/api/generate/image.ts
50import { generateImage, toServerSentEventsResponse } from '@tanstack/ai'
51import { openaiImage } from '@tanstack/ai-openai'
52
53export async function POST(req: Request) {
54 const { prompt, size, numberOfImages } = await req.json()
55
56 const stream = generateImage({
57 adapter: openaiImage('dall-e-3'),
58 prompt,
59 size,
60 numberOfImages,
61 stream: true,
62 })
63
64 return toServerSentEventsResponse(stream)
65}
66```
67
68The same pattern applies to image, speech, transcription, summarize, and video. Live and world generation mint a session token. Connect in the browser. See [Live Generation](./live-generation) and [World Generation](./world-generation).
69
70## useGenerateImage
71
72Trigger image generation and render the results.
73
74For a React + Start walkthrough with OpenRouter, open [Generate Image](../tutorials/generate-image).
75
76```tsx
77import { useGenerateImage, fetchServerSentEvents } from '@tanstack/ai-react'
78import { useState } from 'react'
79
80function ImageGenerator() {
81 const [prompt, setPrompt] = useState('')
82 const { generate, result, isLoading, error, reset } = useGenerateImage({
83 connection: fetchServerSentEvents('/api/generate/image'),
84 })
85
86 return (
87 <div>
88 <input
89 value={prompt}
90 onChange={(e) => setPrompt(e.target.value)}
91 placeholder="Describe an image..."
92 />
93 <button
94 onClick={() => generate({ prompt })}
95 disabled={isLoading || !prompt.trim()}
96 >
97 {isLoading ? 'Generating...' : 'Generate'}
98 </button>
99
100 {error && <p>Error: {error.message}</p>}
101
102 {result?.images.map((img, i) => (
103 <img
104 key={i}
105 src={img.url || `data:image/png;base64,${img.b64Json}`}
106 alt={img.revisedPrompt || 'Generated image'}
107 />
108 ))}
109
110 {result && <button onClick={reset}>Clear</button>}
111 </div>
112 )
113}
114```
115
116The `generate` function accepts an `ImageGenerateInput`:
117
118| Field | Type | Description |
119|-------|------|-------------|
120| `prompt` | `string` | Text description of the desired image (required) |
121| `numberOfImages` | `number` | Number of images to generate |
122| `size` | `string` | Image size in WIDTHxHEIGHT format (e.g., `"1024x1024"`) |
123| `modelOptions` | `Record<string, any>` | Model-specific options |
124
125## useGenerateAudio
126
127Generate music or sound effects from a text prompt.
128
129When you use a `fetcher`, spread `options.headers` onto the POST. Pass `byok` so those headers include `x-byok-*` keys.
130
131```tsx
132import { useGenerateAudio } from '@tanstack/ai-react'
133import { defineByok, defaultByokStorage } from '@tanstack/ai-client/byok'
134
135const byok = defineByok({ storage: defaultByokStorage() })
136
137function AudioGenerator() {
138 const { generate, result, isLoading, error } = useGenerateAudio({
139 byok,
140 byokProvider: () => 'fal',
141 fetcher: async (input, options) => {
142 return fetch('/api/generate/audio', {
143 method: 'POST',
144 headers: {
145 'Content-Type': 'application/json',
146 ...options?.headers,
147 },
148 body: JSON.stringify(input),
149 signal: options?.signal,
150 })
151 },
152 })
153
154 return (
155 <div>
156 <button
157 onClick={() => generate({ prompt: 'An upbeat electronic track' })}
158 disabled={isLoading}
159 >
160 {isLoading ? 'Generating...' : 'Generate'}
161 </button>
162 {error && <p>Error: {error.message}</p>}
163 {result?.audio.url && <audio src={result.audio.url} controls />}
164 </div>
165 )
166}
167```
168
169Server: read the header (or env), then run `generateAudio`.
170
171```typescript
172import { generateAudio, toServerSentEventsResponse } from '@tanstack/ai'
173import { falAudio } from '@tanstack/ai-fal'
174import { falByok } from '@tanstack/ai-fal/byok'
175import { byokMissing, getByokKey } from '@tanstack/ai/byok/server'
176
177export async function POST(request: Request) {
178 const apiKey = getByokKey(request, falByok)
179 if (!apiKey) return byokMissing(falByok)
180
181 const body: unknown = await request.json()
182 if (typeof body !== 'object' || body === null || !('prompt' in body)) {
183 return new Response('Bad request', { status: 400 })
184 }
185 const prompt = body.prompt
186 if (typeof prompt !== 'string') {
187 return new Response('Bad request', { status: 400 })
188 }
189
190 const stream = generateAudio({
191 adapter: falAudio('fal-ai/minimax-music/v2.6', { apiKey }),
192 prompt,
193 stream: true,
194 })
195 return toServerSentEventsResponse(stream)
196}
197```
198
199The `generate` function accepts an `AudioGenerateInput`:
200
201| Field | Type | Description |
202|-------|------|-------------|
203| `prompt` | `string` | Text description of the desired audio (required) |
204| `duration` | `number` | Desired duration in seconds |
205| `modelOptions` | `Record<string, any>` | Model-specific options |
206
207See [Bring Your Own Key](../advanced/byok) for `defineByok` and a save UI.
208
209## useGenerateSpeech
210
211Convert text to speech and play it back.
212
213```tsx
214import { useGenerateSpeech, fetchServerSentEvents } from '@tanstack/ai-react'
215import { useRef } from 'react'
216
217function SpeechGenerator() {
218 const audioRef = useRef<HTMLAudioElement>(null)
219 const { generate, result, isLoading, error } = useGenerateSpeech({
220 connection: fetchServerSentEvents('/api/generate/speech'),
221 })
222
223 return (
224 <div>
225 <button
226 onClick={() => generate({ text: 'Hello, welcome to TanStack AI!', voice: 'alloy' })}
227 disabled={isLoading}
228 >
229 {isLoading ? 'Generating...' : 'Generate Speech'}
230 </button>
231
232 {error && <p>Error: {error.message}</p>}
233
234 {result && (
235 <audio
236 ref={audioRef}
237 src={`data:audio/${result.format};base64,${result.audio}`}
238 controls
239 autoPlay
240 />
241 )}
242 </div>
243 )
244}
245```
246
247The `generate` function accepts a `SpeechGenerateInput`:
248
249| Field | Type | Description |
250|-------|------|-------------|
251| `text` | `string` | The text to convert to speech (required) |
252| `voice` | `string` | The voice to use (e.g., `"alloy"`, `"echo"`) |
253| `format` | `'mp3' \| 'opus' \| 'aac' \| 'flac' \| 'wav' \| 'pcm'` | Output audio format |
254| `speed` | `number` | Audio speed (0.25 to 4.0) |
255| `modelOptions` | `Record<string, any>` | Model-specific options |
256
257The `TTSResult` contains `audio` (base64-encoded), `format`, and optionally `duration` and `contentType`.
258
259## useTranscription
260
261Transcribe audio files to text.
262
263```tsx
264import { useTranscription, fetchServerSentEvents } from '@tanstack/ai-react'
265
266function Transcriber() {
267 const { generate, result, isLoading, error } = useTranscription({
268 connection: fetchServerSentEvents('/api/transcribe'),
269 })
270
271 const handleFile = (e: React.ChangeEvent<HTMLInputElement>) => {
272 const file = e.target.files?.[0]
273 if (file) {
274 const reader = new FileReader()
275 reader.onload = () => {
276 generate({ audio: reader.result as string, language: 'en' })
277 }
278 reader.readAsDataURL(file)
279 }
280 }
281
282 return (
283 <div>
284 <input type="file" accept="audio/*" onChange={handleFile} />
285
286 {isLoading && <p>Transcribing...</p>}
287 {error && <p>Error: {error.message}</p>}
288
289 {result && (
290 <div>
291 <h3>Transcription</h3>
292 <p>{result.text}</p>
293 {result.language && <p>Language: {result.language}</p>}
294 {result.duration && <p>Duration: {result.duration}s</p>}
295 </div>
296 )}
297 </div>
298 )
299}
300```
301
302The `generate` function accepts a `TranscriptionGenerateInput`:
303
304| Field | Type | Description |
305|-------|------|-------------|
306| `audio` | `string \| File \| Blob \| ArrayBuffer` | Audio data -- base64 string, File, Blob, or ArrayBuffer (required) |
307| `language` | `string` | Language in ISO-639-1 format (e.g., `"en"`) |
308| `prompt` | `string` | Optional prompt to guide the transcription |
309| `responseFormat` | `'json' \| 'text' \| 'srt' \| 'verbose_json' \| 'vtt'` | Common output format |
310| `modelOptions` | `Record<string, any>` | Model-specific options |
311
312## useSummarize
313
314Summarize long text with configurable output styles.
315
316```tsx
317import { useSummarize, fetchServerSentEvents } from '@tanstack/ai-react'
318import { useState } from 'react'
319
320function Summarizer() {
321 const [text, setText] = useState('')
322 const { generate, result, isLoading, error } = useSummarize({
323 connection: fetchServerSentEvents('/api/summarize'),
324 })
325
326 return (
327 <div>
328 <textarea
329 value={text}
330 onChange={(e) => setText(e.target.value)}
331 placeholder="Paste text to summarize..."
332 rows={8}
333 />
334 <button
335 onClick={() => generate({ text, style: 'bullet-points', maxLength: 200 })}
336 disabled={isLoading || !text.trim()}
337 >
338 {isLoading ? 'Summarizing...' : 'Summarize'}
339 </button>
340
341 {error && <p>Error: {error.message}</p>}
342
343 {result && (
344 <div>
345 <h3>Summary</h3>
346 <p>{result.summary}</p>
347 </div>
348 )}
349 </div>
350 )
351}
352```
353
354The `generate` function accepts a `SummarizeGenerateInput`:
355
356| Field | Type | Description |
357|-------|------|-------------|
358| `text` | `string` | The text to summarize (required) |
359| `maxLength` | `number` | Maximum length of the summary |
360| `style` | `'bullet-points' \| 'paragraph' \| 'concise'` | Summary style |
361| `focus` | `Array<string>` | Topics to focus on |
362| `modelOptions` | `Record<string, any>` | Model-specific options |
363
364## useGenerateVideo
365
366Video generation is asynchronous -- a job is created on the server, then polled for status until completion. The hook manages the full lifecycle and exposes `jobId` and `videoStatus` so you can show progress.
367
368```tsx
369import { useGenerateVideo, fetchServerSentEvents } from '@tanstack/ai-react'
370
371function VideoGenerator() {
372 const { generate, result, jobId, videoStatus, isLoading, error } =
373 useGenerateVideo({
374 connection: fetchServerSentEvents('/api/generate/video'),
375 onStatusUpdate: (status) => {
376 console.log(`Video ${status.jobId}: ${status.status} (${status.progress}%)`)
377 },
378 })
379
380 return (
381 <div>
382 <button
383 onClick={() => generate({ prompt: 'A flying car over a city', duration: 5 })}
384 disabled={isLoading}
385 >
386 {isLoading ? 'Generating...' : 'Generate Video'}
387 </button>
388
389 {isLoading && videoStatus && (
390 <div>
391 <p>Job: {jobId}</p>
392 <p>Status: {videoStatus.status}</p>
393 {videoStatus.progress != null && (
394 <progress value={videoStatus.progress} max={100} />
395 )}
396 </div>
397 )}
398
399 {error && <p>Error: {error.message}</p>}
400
401 {result && (
402 <video src={result.url} controls autoPlay style={{ maxWidth: '100%' }} />
403 )}
404 </div>
405 )
406}
407```
408
409The `generate` function accepts a `VideoGenerateInput`:
410
411| Field | Type | Description |
412|-------|------|-------------|
413| `prompt` | `string` | Text description of the desired video (required) |
414| `size` | `string` | Video size -- format depends on provider (e.g., `"16:9"`, `"1280x720"`) |
415| `duration` | `number` | Video duration in seconds |
416| `modelOptions` | `Record<string, any>` | Model-specific options |
417
418`useGenerateVideo` returns two extra properties beyond the standard set:
419
420| Property | Type | Description |
421|----------|------|-------------|
422| `jobId` | `string \| null` | The current job ID, set when the server creates a video job |
423| `videoStatus` | `VideoStatusInfo \| null` | Live status updates with `status`, `progress`, and `jobId` |
424
425The `VideoStatusInfo` type:
426
427```typescript
428interface VideoStatusInfo {
429 jobId: string
430 status: 'pending' | 'processing' | 'completed' | 'failed'
431 progress?: number // 0-100
432 url?: string // Set when completed
433 error?: string // Set when failed
434}
435```
436
437The hook also accepts `onJobCreated` and `onStatusUpdate` callbacks for fine-grained tracking.
438
439## Base Hook: useGeneration
440
441All specialized hooks are built on `useGeneration`. Use it directly when you have a custom generation type that doesn't fit the built-in hooks.
442
443```tsx
444import { useGeneration, fetchServerSentEvents } from '@tanstack/ai-react'
445
446interface EmbeddingInput {
447 text: string
448 model?: string
449}
450
451interface EmbeddingResult {
452 embedding: Array<number>
453 model: string
454 usage: { totalTokens: number }
455}
456
457function EmbeddingGenerator() {
458 const { generate, result, isLoading, error } = useGeneration<
459 EmbeddingInput,
460 EmbeddingResult
461 >({
462 connection: fetchServerSentEvents('/api/generate/embedding'),
463 })
464
465 return (
466 <div>
467 <button onClick={() => generate({ text: 'Hello world' })} disabled={isLoading}>
468 Generate Embedding
469 </button>
470 {result && <p>Dimensions: {result.embedding.length}</p>}
471 </div>
472 )
473}
474```
475
476### Options
477
478`UseGenerationOptions<TInput, TResult>` accepts:
479
480| Option | Type | Description |
481|--------|------|-------------|
482| `connection` | `ConnectConnectionAdapter` | Streaming transport (SSE, HTTP stream, custom) |
483| `fetcher` | `GenerationFetcher<TInput, TResult>` | Direct async function (no streaming protocol needed) |
484| `byok` | `ByokClient` | Optional keyring. Keys go in `x-byok-*` headers, never the body |
485| `byokProvider` | `() => ProviderId \| undefined` | Optional provider slug. If it returns a slug, only that key is sent. Otherwise `body.provider`. If no slug resolves, generate throws |
486| `threadId` | `string` | Stable scope for this generation. Required when `persistence` is on. Optional for ephemeral runs. |
487| `body` | `Record<string, any>` | Additional body parameters sent with connection requests |
488| `onResult` | `(result: TResult) => TOutput \| null \| void` | Transform or react to results |
489| `onError` | `(error: Error) => void` | Error callback |
490| `onProgress` | `(progress: number, message?: string) => void` | Progress updates (0-100) |
491| `onChunk` | `(chunk: StreamChunk) => void` | Per-chunk callback (connection mode only) |
492
493### Return Value
494
495`UseGenerationReturn<TOutput>` provides:
496
497| Property | Type | Description |
498|----------|------|-------------|
499| `generate` | `(input: TInput) => Promise<void>` | Trigger a generation request |
500| `result` | `TOutput \| null` | The generation result, or null |
501| `isLoading` | `boolean` | Whether a generation is in progress |
502| `error` | `Error \| undefined` | Current error, if any |
503| `status` | `GenerationClientState` | `'idle'` \| `'generating'` \| `'success'` \| `'error'` |
504| `stop` | `() => void` | Abort the current generation |
505| `reset` | `() => void` | Clear result, error, and return to idle |
506
507### Result Transforms
508
509The `onResult` callback can transform what gets stored in `result`:
510
511```tsx
512import { useGenerateImage, fetchServerSentEvents } from '@tanstack/ai-react'
513import type { ImageGenerationResult } from '@tanstack/ai'
514
515const { result } = useGenerateImage({
516 connection: fetchServerSentEvents('/api/generate/image'),
517 onResult: (raw: ImageGenerationResult) => raw.images.map((img) => img.url || img.b64Json),
518})
519// result is now string[] instead of ImageGenerationResult
520```
521
522## Framework Variants
523
524All generation hooks are available across React, Vue, and Svelte with the same capabilities. The API shapes are identical -- only the naming convention and reactive primitives differ.
525
526| Generation Type | React (`@tanstack/ai-react`) | Vue (`@tanstack/ai-vue`) | Svelte (`@tanstack/ai-svelte`) |
527|----------------|------------------------------|--------------------------|-------------------------------|
528| Image | `useGenerateImage` | `useGenerateImage` | `createGenerateImage` |
529| Audio | `useGenerateAudio` | `useGenerateAudio` | `createGenerateAudio` |
530| Speech | `useGenerateSpeech` | `useGenerateSpeech` | `createGenerateSpeech` |
531| Transcription | `useTranscription` | `useTranscription` | `createTranscription` |
532| Summarization | `useSummarize` | `useSummarize` | `createSummarize` |
533| Video | `useGenerateVideo` | `useGenerateVideo` | `createGenerateVideo` |
534| Base (generic) | `useGeneration` | `useGeneration` | `createGeneration` |
535
536All three packages re-export `fetchServerSentEvents`, `fetchHttpStream`, and `stream` from `@tanstack/ai-client` for convenience.
537
538**Vue note:** Return values are wrapped in `DeepReadonly<ShallowRef<>>` -- access them with `.value` in both `<script>` and `<template>`.
539
540**Svelte note:** Functions use the `create*` naming convention and return Svelte 5 reactive state via `$state`.
541
542## Next Steps
543
544- [Image Generation](./image-generation) -- Provider-specific options, sizes, and model availability
545- [Text-to-Speech](./text-to-speech) -- Voice options, audio formats, and streaming audio
546- [Transcription](./transcription) -- File formats, language detection, and word-level timestamps
547- [Video Generation](./video-generation) -- Job lifecycle, polling, and provider setup
548- [Generations Overview](./generations) -- Architecture and server-side streaming patterns