Open History to see the last commit
1---
2title: Generation Hooks
3id: generation-hooks
4order: 7
5description: "Client hooks for every media generation: image, audio, speech, transcription, summarization, and video. One shape for loading, errors, and results in every framework."
6keywords:
7 - tanstack ai
8 - generation hooks
9 - useGenerateImage
10 - useGenerateAudio
11 - useGenerateSpeech
12 - useTranscription
13 - useSummarize
14 - useGenerateVideo
15 - react hooks
16---
17
18A generation hook tracks the request, the loading state, the error, and the result for one media call.
19
20## Quick setup
21
22This connects a React component to an image route. It takes about 5 minutes.
23
241. Install the packages:
25
26<!-- ::start:tabs variant="package-manager" mode="install" -->
27
28react: @tanstack/ai @tanstack/ai-react @tanstack/ai-openai
29
30<!-- ::end:tabs -->
31
322. Add a `POST` route at `/api/generate/image`. It reads `OPENAI_API_KEY` from the environment:
33
34```typescript
35import {
36 generateImage,
37 generationParamsFromRequest,
38 toServerSentEventsResponse,
39} from '@tanstack/ai'
40import { openaiImage } from '@tanstack/ai-openai'
41
42export async function POST(request: Request) {
43 const { input, threadId } = await generationParamsFromRequest('image', request)
44 if (typeof input.prompt !== 'string') {
45 return new Response('Send a text prompt.', { status: 400 })
46 }
47
48 const stream = generateImage({
49 adapter: openaiImage('gpt-image-2.5-flare'),
50 prompt: input.prompt,
51 threadId,
52 size: '1024x1024',
53 stream: true,
54 })
55 return toServerSentEventsResponse(stream)
56}
57```
58
593. Add the hook to a component:
60
61```tsx
62import { useState } from 'react'
63import { fetchServerSentEvents, useGenerateImage } from '@tanstack/ai-react'
64
65export function ImageGenerator() {
66 const [prompt, setPrompt] = useState('')
67 const { generate, result, isLoading, error, reset } = useGenerateImage({
68 connection: fetchServerSentEvents('/api/generate/image'),
69 threadId: 'image-studio',
70 })
71
72 return (
73 <div>
74 <input
75 value={prompt}
76 onChange={(e) => setPrompt(e.target.value)}
77 placeholder="Describe an image..."
78 />
79 <button
80 onClick={() => generate({ prompt })}
81 disabled={isLoading || !prompt.trim()}
82 >
83 {isLoading ? 'Generating...' : 'Generate'}
84 </button>
85
86 {error && <p role="alert">Error: {error.message}</p>}
87
88 {result?.images.map((img, i) => (
89 <img
90 key={i}
91 src={img.url || `data:image/png;base64,${img.b64Json}`}
92 alt={img.revisedPrompt || 'Generated image'}
93 />
94 ))}
95
96 {result && <button onClick={reset}>Clear</button>}
97 </div>
98 )
99}
100```
101
102Type a prompt and click **Generate**. The button shows the loading state, then the image appears. **Clear** resets the hook.
103
104## How it works
105
106Every generation hook does the same job:
107
1081. `generate(input)` sends the input to your server.
1092. While the server works, `isLoading` is `true` and `status` is `'generating'`.
1103. When the result arrives, the hook stores it on `result`. If the server fails, the hook stores the failure on `error`.
111
112You give the hook one transport:
113
114- `connection`: a streaming transport, such as `fetchServerSentEvents('/api/...')`. Use it with an API route.
115- `fetcher`: an async function, such as a TanStack Start server function. It can return the result, or an SSE `Response`.
116
117The server half and the three transports are explained in [Generations](./generations).
118
119| Hook | Input | Result |
120| --- | --- | --- |
121| `useGenerateImage` | `ImageGenerateInput` | `ImageGenerationResult` |
122| `useGenerateAudio` | `AudioGenerateInput` | `AudioGenerationResult` |
123| `useGenerateSpeech` | `SpeechGenerateInput` | `TTSResult` |
124| `useTranscription` | `TranscriptionGenerateInput` | `TranscriptionResult` |
125| `useSummarize` | `SummarizeGenerateInput` | `SummarizationResult` |
126| `useGenerateVideo` | `VideoGenerateInput` | `VideoGenerateResult` |
127| `useGeneration` | Your own `TInput` | Your own `TResult` |
128
129Every hook returns `generate`, `result`, `isLoading`, `error`, `status`, `stop`, `reset`, and `runId`. The full tables are in [Options](#options) and [Return value](#return-value).
130
131## Hooks by media type
132
133Each section lists what `generate()` accepts. The linked guide shows the server route and the provider options.
134
135### useGenerateImage
136
137Makes one or more images. Guide: [Image Generation](./image-generation).
138
139| Field | Type | Description |
140| --- | --- | --- |
141| `prompt` | `string \| MediaPromptPart[]` | What to draw (required). An array of text and image parts works on models that take reference images. |
142| `numberOfImages` | `number` | How many images to make |
143| `size` | `string` | Image size, for example `"1024x1024"` |
144| `modelOptions` | `Record<string, any>` | Model-specific options |
145
146### useGenerateAudio
147
148Makes music or sound effects from a prompt. Guide: [Audio Generation](./audio-generation).
149
150| Field | Type | Description |
151| --- | --- | --- |
152| `prompt` | `string` | What the audio sounds like (required) |
153| `duration` | `number` | Length in seconds |
154| `modelOptions` | `Record<string, any>` | Model-specific options |
155
156This example also shows a `fetcher` with Bring Your Own Key (BYOK). The user's key goes in `x-byok-*` headers. With a `fetcher`, spread `headers` from the second argument onto your request so the keys reach the server:
157
158```tsx
159import { useGenerateAudio } from '@tanstack/ai-react'
160import { defineByok, defaultByokStorage } from '@tanstack/ai-client/byok'
161
162const byok = defineByok({ storage: defaultByokStorage() })
163const threadId = 'audio'
164
165export function AudioGenerator() {
166 const { generate, result, isLoading, error } = useGenerateAudio({
167 byok,
168 byokProvider: () => 'fal',
169 fetcher: (input, { threadId, signal, headers }) =>
170 fetch('/api/generate/audio', {
171 method: 'POST',
172 headers: { 'Content-Type': 'application/json', ...headers },
173 body: JSON.stringify({ ...input, threadId }),
174 signal,
175 }),
176 threadId,
177 })
178
179 return (
180 <div>
181 <button
182 onClick={() => generate({ prompt: 'An upbeat electronic track' })}
183 disabled={isLoading}
184 >
185 {isLoading ? 'Generating...' : 'Generate'}
186 </button>
187 {error && <p role="alert">Error: {error.message}</p>}
188 {result?.audio.url && <audio src={result.audio.url} controls />}
189 </div>
190 )
191}
192```
193
194On the server, read the key from the header, then run `generateAudio`:
195
196```typescript
197import { generateAudio, toServerSentEventsResponse } from '@tanstack/ai'
198import { falAudio } from '@tanstack/ai-fal'
199import { falByok } from '@tanstack/ai-fal/byok'
200import { byokMissing, getByokKey } from '@tanstack/ai/byok/server'
201
202export async function POST(request: Request) {
203 const apiKey = getByokKey(request, falByok)
204 if (!apiKey) return byokMissing(falByok)
205
206 const body: unknown = await request.json()
207 if (
208 typeof body !== 'object' ||
209 body === null ||
210 !('prompt' in body) ||
211 !('threadId' in body)
212 ) {
213 return new Response('Bad request', { status: 400 })
214 }
215 const { prompt, threadId } = body
216 if (typeof prompt !== 'string' || typeof threadId !== 'string') {
217 return new Response('Bad request', { status: 400 })
218 }
219
220 const stream = generateAudio({
221 adapter: falAudio('fal-ai/minimax-music/v2.6', { apiKey }),
222 prompt,
223 threadId,
224 stream: true,
225 })
226 return toServerSentEventsResponse(stream)
227}
228```
229
230The fetcher posts the input and the `threadId`, so this route reads `prompt` and `threadId` from the top of the body. For `defineByok` and a UI to save keys, see [Bring Your Own Key](../advanced/byok).
231
232### useGenerateSpeech
233
234Turns text into spoken audio. Guide: [Text-to-Speech](./text-to-speech).
235
236| Field | Type | Description |
237| --- | --- | --- |
238| `text` | `string` | The text to speak. Leave it out when you send `turns`. |
239| `turns` | `Array<TTSTurn>` | Dialogue turns with more than one voice. Only for adapters that support more than one speaker. |
240| `timestamps` | `boolean` | Ask for `alignment` and `segments` on the result. Only for adapters that support timestamps. |
241| `voice` | `string` | The voice, for example `"alloy"` |
242| `format` | `'mp3' \| 'opus' \| 'aac' \| 'flac' \| 'wav' \| 'pcm'` | Output audio format |
243| `speed` | `number` | Speed, from 0.25 to 4.0 |
244| `modelOptions` | `Record<string, any>` | Model-specific options |
245
246`TTSResult` holds `audio` (base64) and `format`. It can also hold `duration`, `contentType`, `alignment`, and `segments`. To play it:
247
248```tsx
249import { fetchServerSentEvents, useGenerateSpeech } from '@tanstack/ai-react'
250
251export function SpeechPlayer() {
252 const { generate, result, isLoading } = useGenerateSpeech({
253 connection: fetchServerSentEvents('/api/generate/speech'),
254 threadId: 'speech',
255 })
256
257 return (
258 <div>
259 <button
260 onClick={() => generate({ text: 'Hello from TanStack AI!', voice: 'alloy' })}
261 disabled={isLoading}
262 >
263 Speak
264 </button>
265 {result && (
266 <audio
267 src={`data:audio/${result.format};base64,${result.audio}`}
268 controls
269 autoPlay
270 />
271 )}
272 </div>
273 )
274}
275```
276
277### useTranscription
278
279Turns recorded audio into text. Guide: [Transcription](./transcription).
280
281| Field | Type | Description |
282| --- | --- | --- |
283| `audio` | `string \| File \| Blob \| ArrayBuffer` | The audio (required). Over a `connection`, send a base64 string or a data URL. |
284| `language` | `string` | Language in ISO-639-1 format, for example `"en"` |
285| `prompt` | `string` | A hint that guides the transcription |
286| `responseFormat` | `'json' \| 'text' \| 'srt' \| 'verbose_json' \| 'vtt'` | Output format |
287| `modelOptions` | `Record<string, any>` | Model-specific options |
288
289`TranscriptionResult` holds `text`. It can also hold `language`, `duration`, `segments`, and `words`.
290
291### useSummarize
292
293Makes a summary of long text. There is no separate guide, so the full example is here.
294
295```tsx
296import { useState } from 'react'
297import { fetchServerSentEvents, useSummarize } from '@tanstack/ai-react'
298
299export function Summarizer() {
300 const [text, setText] = useState('')
301 const { generate, result, isLoading, error } = useSummarize({
302 connection: fetchServerSentEvents('/api/summarize'),
303 threadId: 'summary',
304 })
305
306 return (
307 <div>
308 <textarea
309 value={text}
310 onChange={(e) => setText(e.target.value)}
311 placeholder="Paste text to summarize..."
312 rows={8}
313 />
314 <button
315 onClick={() => generate({ text, style: 'bullet-points', maxLength: 200 })}
316 disabled={isLoading || !text.trim()}
317 >
318 {isLoading ? 'Summarizing...' : 'Summarize'}
319 </button>
320 {error && <p role="alert">Error: {error.message}</p>}
321 {result && <p>{result.summary}</p>}
322 </div>
323 )
324}
325```
326
327| Field | Type | Description |
328| --- | --- | --- |
329| `text` | `string` | The text to summarize (required) |
330| `maxLength` | `number` | Maximum length of the summary |
331| `style` | `'bullet-points' \| 'paragraph' \| 'concise'` | Summary style |
332| `focus` | `Array<string>` | Topics to focus on |
333| `modelOptions` | `Record<string, any>` | Model-specific options |
334
335On the server, call `summarize()` with `stream: true` and return `toServerSentEventsResponse()`. `generationParamsFromRequest` has no `summarize` kind, so read the envelope yourself. The hook sends its input in `forwardedProps`, and `threadId` and `runId` at the top of the body:
336
337```typescript
338import { summarize, toServerSentEventsResponse } from '@tanstack/ai'
339import { openaiSummarize } from '@tanstack/ai-openai'
340
341export async function POST(request: Request) {
342 const body: unknown = await request.json()
343 if (
344 typeof body !== 'object' ||
345 body === null ||
346 !('threadId' in body) ||
347 !('forwardedProps' in body)
348 ) {
349 return new Response('Bad request', { status: 400 })
350 }
351 const { threadId, forwardedProps } = body
352 if (
353 typeof threadId !== 'string' ||
354 typeof forwardedProps !== 'object' ||
355 forwardedProps === null ||
356 !('text' in forwardedProps) ||
357 typeof forwardedProps.text !== 'string'
358 ) {
359 return new Response('Bad request', { status: 400 })
360 }
361 const runId =
362 'runId' in body && typeof body.runId === 'string' ? body.runId : undefined
363
364 const stream = summarize({
365 adapter: openaiSummarize('gpt-5.5'),
366 text: forwardedProps.text,
367 style: 'bullet-points',
368 maxLength: 200,
369 threadId,
370 runId,
371 stream: true,
372 })
373 return toServerSentEventsResponse(stream)
374}
375```
376
377### useGenerateVideo
378
379Makes a video. A video runs as a job: the server starts it, then polls the provider until it is done. Guide: [Video Generation](./video-generation).
380
381| Field | Type | Description |
382| --- | --- | --- |
383| `prompt` | `string \| MediaPromptPart[]` | What the video shows (required). An array of text and image parts works on models that take a start frame or references. |
384| `size` | `string` | Video size. The format depends on the provider, for example `"16:9"` or `"1280x720"`. |
385| `duration` | `number` | Length in seconds |
386| `modelOptions` | `Record<string, any>` | Model-specific options |
387
388`useGenerateVideo` returns two more values, so you can show progress:
389
390| Property | Type | Description |
391| --- | --- | --- |
392| `jobId` | `string \| null` | The job id. Set when the server creates the job. |
393| `videoStatus` | `VideoStatusInfo \| null` | The last status update: `status`, `progress`, and `jobId` |
394
395```typescript
396interface VideoStatusInfo {
397 jobId: string
398 status: 'pending' | 'processing' | 'completed' | 'failed'
399 progress?: number // 0-100
400 url?: string // set when completed
401 error?: string // set when failed
402}
403```
404
405It also takes two more callbacks: `onJobCreated(jobId)` and `onStatusUpdate(status)`.
406
407## Framework variants
408
409Every framework has the same hooks with the same options. Only the names and the reactive values change.
410
411| Generation | React, Vue, Solid, Octane | Svelte, Remix | Angular |
412| --- | --- | --- | --- |
413| Image | `useGenerateImage` | `createGenerateImage` | `injectGenerateImage` |
414| Audio | `useGenerateAudio` | `createGenerateAudio` | `injectGenerateAudio` |
415| Speech | `useGenerateSpeech` | `createGenerateSpeech` | `injectGenerateSpeech` |
416| Transcription | `useTranscription` | `createTranscription` | `injectTranscription` |
417| Summarization | `useSummarize` | `createSummarize` | `injectSummarize` |
418| Video | `useGenerateVideo` | `createGenerateVideo` | `injectGenerateVideo` |
419| Base (custom) | `useGeneration` | `createGeneration` | `injectGeneration` |
420
421How to read the values in each framework:
422
423- **Vue** (`@tanstack/ai-vue`): values are `DeepReadonly<ShallowRef<>>`. Read them with `.value` in `<script>` and in `<template>`.
424- **Solid** (`@tanstack/ai-solid`): values are accessors. Call them, for example `result()`.
425- **Svelte** (`@tanstack/ai-svelte`): values are Svelte 5 `$state`.
426- **Angular** (`@tanstack/ai-angular`): values are read-only signals. Call them, for example `result()`.
427- **Remix** (`@tanstack/ai-remix`): pass the component `handle` as the first argument, for example `createGenerateImage(handle, options)`.
428
429Every package re-exports `fetchServerSentEvents` and `fetchHttpStream` from `@tanstack/ai-client`. For full samples, see the API pages for [Vue](../api/ai-vue), [Solid](../api/ai-solid), [Svelte](../api/ai-svelte), [Angular](../api/ai-angular), [Octane](../api/ai-octane), and [Remix](../api/ai-remix).
430
431## Advanced
432
433### Options
434
435Every hook takes these options:
436
437| Option | Type | Description |
438| --- | --- | --- |
439| `connection` | `ConnectConnectionAdapter` | Streaming transport (SSE, HTTP stream, or custom) |
440| `fetcher` | `(input, options) => Promise<Result \| Response>` | An async function, or a server function that returns an SSE `Response`. `options` holds `signal`, `threadId`, `runId`, and `headers`. |
441| `body` | `Record<string, any>` | Extra fields sent with each `connection` request |
442| `threadId` | `string` | Required. A stable name for this generation slot. |
443| `persistence` | `boolean` | `true` restores the last run for `threadId` from the server when the component mounts |
444| `onResult` | `(result) => TOutput \| null \| void` | React to the result, or change what is stored. See [Result transforms](#result-transforms). |
445| `onError` | `(error: Error) => void` | Called when the run fails |
446| `onProgress` | `(progress: number, message?: string) => void` | Progress updates, from 0 to 100 |
447
448Options for special cases:
449
450| Option | Type | Description |
451| --- | --- | --- |
452| `byok` | `ByokClient` | A keyring. Keys go in `x-byok-*` headers, never in the body. |
453| `byokProvider` | `() => ProviderId \| undefined` | The provider slug. If it returns a slug, only that key is sent. Otherwise the hook uses `body.provider`. If no slug resolves, `generate` throws. |
454| `onChunk` | `(chunk: StreamChunk) => void` | Called for each stream event. Only with `connection`. |
455| `hydrateGeneration` | handler | Restores the last run when the `connection` has no restore handler, for example next to a `fetcher` |
456| `joinRun` | handler | Re-attaches to a run that is still going after a reload. Without it, a restored running run shows as an error. |
457| `devtools` | `AIDevtoolsDisplayOptions` | How the run shows in TanStack AI Devtools |
458
459### Return value
460
461| Property | Type | Description |
462| --- | --- | --- |
463| `generate` | `(input) => Promise<void>` | Start a generation |
464| `result` | `TOutput \| null` | The result, after any transform. `null` before the first result. |
465| `isLoading` | `boolean` | `true` while a generation runs |
466| `error` | `Error \| undefined` | The current error, if any |
467| `status` | `GenerationClientState` | `'idle'`, `'generating'`, `'success'`, or `'error'` |
468| `stop` | `() => void` | Abort the current generation |
469| `reset` | `() => void` | Clear the result and the error, and go back to `'idle'` |
470| `runId` | `string \| null` | The id of the run in progress, or `null` |
471
472`stop()` only aborts the local stream. Work that already runs on the provider continues. To cancel or poll that provider job, send `runId` to your own endpoint.
473
474### Result transforms
475
476`onResult` can change what the hook stores on `result`:
477
478- Return a value that is not `null`: the hook stores that value.
479- Return `null`: the hook keeps the previous result. Use this to filter results.
480- Return nothing: the hook stores the raw result.
481
482TypeScript infers the type of `result` from what `onResult` returns. You do not need a generic parameter.
483
484```tsx
485import { fetchServerSentEvents, useGenerateSpeech } from '@tanstack/ai-react'
486import type { TTSResult } from '@tanstack/ai'
487
488export function SpeechPlayer() {
489 const { result } = useGenerateSpeech({
490 connection: fetchServerSentEvents('/api/generate/speech'),
491 threadId: 'speech',
492 onResult: (raw: TTSResult) => ({
493 audioUrl: `data:${raw.contentType};base64,${raw.audio}`,
494 duration: raw.duration,
495 }),
496 })
497 // result is { audioUrl: string; duration?: number } | null
498}
499```
500
501### Keep results after a reload
502
503Every generation hook takes the same `persistence` option that `useChat` takes. With it, the status and the result of a long run come back after a page reload or a dropped connection.
504
505The hook restores by `threadId`. For a generation, `threadId` names the slot that successive runs fill, for example `product-7-hero`. It does not name a conversation. See [Id map](../persistence/id-map). The setup is in [Generation Persistence](../persistence/generation-persistence).
506
507### Custom generations with useGeneration
508
509All the hooks above use `useGeneration` internally. Use it directly for a generation type that has no built-in hook:
510
511```tsx
512import { fetchServerSentEvents, useGeneration } from '@tanstack/ai-react'
513
514interface EmbeddingInput {
515 text: string
516 model?: string
517}
518
519interface EmbeddingResult {
520 embedding: Array<number>
521 model: string
522 usage: { totalTokens: number }
523}
524
525export function EmbeddingGenerator() {
526 const { generate, result, isLoading } = useGeneration<
527 EmbeddingInput,
528 EmbeddingResult
529 >({
530 connection: fetchServerSentEvents('/api/generate/embedding'),
531 threadId: 'generation',
532 })
533
534 return (
535 <div>
536 <button onClick={() => generate({ text: 'Hello world' })} disabled={isLoading}>
537 Generate embedding
538 </button>
539 {result && <p>Dimensions: {result.embedding.length}</p>}
540 </div>
541 )
542}
543```
544
545`useGeneration` takes the same [options](#options) and returns the same [values](#return-value) as the other hooks.