Open History to see the last commit
1---
2title: Generations
3id: generations
4order: 1
5description: "Make an image, speech, a transcript, music, or a video with one server call and one client hook. Every media type uses the same three parts."
6keywords:
7 - tanstack ai
8 - generations
9 - media generation
10 - image generation
11 - transcription
12 - tts
13 - video generation
14---
15
16A generation is one request and one result: an image, a voice clip, a transcript, or a video. It does not keep a conversation.
17
18Every generation uses the same three parts. When you know how to make one image, you know how to make all of them.
19
20## Generate your first image
21
22You need a React app with a server route, and an OpenAI API key. This 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. Put your key in `.env`:
33
34```bash
35OPENAI_API_KEY=sk-...
36```
37
383. Add a `POST` route at `/api/generate/image`:
39
40```typescript
41import {
42 generateImage,
43 generationParamsFromRequest,
44 toServerSentEventsResponse,
45} from '@tanstack/ai'
46import { openaiImage } from '@tanstack/ai-openai'
47
48export async function POST(request: Request) {
49 const { input, threadId } = await generationParamsFromRequest('image', request)
50 if (typeof input.prompt !== 'string') {
51 return new Response('Send a text prompt.', { status: 400 })
52 }
53
54 const stream = generateImage({
55 adapter: openaiImage('gpt-image-2.5-flare'),
56 prompt: input.prompt,
57 threadId,
58 stream: true,
59 })
60 return toServerSentEventsResponse(stream)
61}
62```
63
644. Call the route from a component:
65
66```tsx
67import { fetchServerSentEvents, useGenerateImage } from '@tanstack/ai-react'
68
69export function ImageGenerator() {
70 const { generate, result, isLoading, error } = useGenerateImage({
71 connection: fetchServerSentEvents('/api/generate/image'),
72 threadId: 'image-studio',
73 })
74
75 return (
76 <div>
77 <button
78 onClick={() => generate({ prompt: 'A sunset over mountains' })}
79 disabled={isLoading}
80 >
81 {isLoading ? 'Generating...' : 'Generate'}
82 </button>
83 {error && <p role="alert">{error.message}</p>}
84 {result?.images.map((img, i) => (
85 <img
86 key={i}
87 src={img.url || `data:image/png;base64,${img.b64Json}`}
88 alt="Generated image"
89 />
90 ))}
91 </div>
92 )
93}
94```
95
96Click the button. The image shows up below it.
97
98For a full React and TanStack Start walkthrough with OpenRouter, open [Generate Image](../tutorials/generate-image).
99
100## How it works
101
102The loop has three parts:
103
104- **The server function.** `generateImage()` calls the provider. With `stream: true`, it returns a stream of events instead of a plain result.
105- **The response helper.** `toServerSentEventsResponse()` sends those events to the browser as Server-Sent Events (SSE).
106- **The hook.** `useGenerateImage()` posts the input, reads the events, and gives you `result`, `isLoading`, and `error`.
107
108To make a different media type, swap the server function and the hook for another pair from the table. Nothing else changes.
109
110| Activity | Server function | React hook | Guide |
111| --- | --- | --- | --- |
112| Image generation | `generateImage()` | `useGenerateImage()` | [Image Generation](./image-generation) |
113| Audio generation | `generateAudio()` | `useGenerateAudio()` | [Audio Generation](./audio-generation) |
114| Text-to-speech | `generateSpeech()` | `useGenerateSpeech()` | [Text-to-Speech](./text-to-speech) |
115| Transcription | `generateTranscription()` | `useTranscription()` | [Transcription](./transcription) |
116| Voice creation | `generateVoice()` | - | [Voice Creation](./voice-creation) |
117| Summarization | `summarize()` | `useSummarize()` | - |
118| Video generation | `generateVideo()` | `useGenerateVideo()` | [Video Generation](./video-generation) |
119| Live generation | `generateLiveVideo()` | - | [Live Generation](./live-generation) |
120| World generation | `generateWorld()` | - | [World Generation](./world-generation) |
121
122Three types work a little differently:
123
124- **Video** runs as a job. The server starts the job and polls it until the video is ready. The hook also gives you the job status. See [Video Generation](./video-generation).
125- **Live** and **world** generation return a session token. The browser uses the token to connect to the provider. See [Live Generation](./live-generation) and [World Generation](./world-generation).
126
127The hooks for Vue, Solid, Svelte, Angular, and the other frameworks are in [Generation Hooks](./generation-hooks). To keep a result after a page reload, add [Generation Persistence](../persistence/generation-persistence).
128
129## Pick a transport
130
131The quick setup uses a streaming route. You can also call a server function:
132
133| Transport | Use it when | How |
134| --- | --- | --- |
135| **Streaming route** | You have an API route. This is the default. | `stream: true` and `toServerSentEventsResponse()` on the server. `connection:` on the hook. |
136| **Direct** | You call a server function and want plain JSON back. No streaming. | Return the result from the function. `fetcher:` on the hook. |
137| **Server function that streams** | You use TanStack Start server functions and want typed input and streaming. | Return `toServerSentEventsResponse(...)` from the function. `fetcher:` on the hook. |
138
139On TanStack Start, the third transport gives you both: the input is typed and the hook still reads a stream. All three are written out in [Transports in full](#transports-in-full).
140
141## Advanced
142
143### Transports in full
144
145#### Streaming route (connection)
146
147The server passes `stream: true` to the generation function and sends the events as SSE. The hook reads them with `fetchServerSentEvents()`. This is the quick setup above.
148
149The hook sends its input inside an AG-UI request body. `generationParamsFromRequest(kind, request)` reads that body and returns `{ input, threadId, runId }`. The `kind` is one of `'image'`, `'audio'`, `'tts'`, `'voice'`, `'video'`, `'transcription'`, `'world'`, or `'liveVideo'`.
150
151#### Direct (fetcher)
152
153The hook calls a server function and gets the result back as JSON. There is no stream.
154
155Server:
156
157```typescript ignore
158import { createServerFn } from '@tanstack/react-start'
159import { generateImage } from '@tanstack/ai'
160import { openaiImage } from '@tanstack/ai-openai'
161
162export const generateImageFn = createServerFn({ method: 'POST' })
163 .inputValidator((data: { prompt: string; threadId: string }) => data)
164 .handler(async ({ data }) => {
165 return generateImage({
166 adapter: openaiImage('gpt-image-2.5-flare'),
167 prompt: data.prompt,
168 threadId: data.threadId,
169 })
170 })
171```
172
173Client:
174
175```tsx
176import { useGenerateImage } from '@tanstack/ai-react'
177import { generateImageFn } from '../lib/server-functions'
178
179const threadId = 'image-studio'
180
181export function ImageGenerator() {
182 const { generate, result, isLoading } = useGenerateImage({
183 fetcher: (input, { threadId }) =>
184 generateImageFn({ data: { ...input, threadId } }),
185 threadId,
186 })
187 // Render the same way as in the quick setup.
188}
189```
190
191#### Server function that streams (fetcher + Response)
192
193The server function returns an SSE `Response`. When a fetcher returns a `Response`, the hook reads it as an SSE stream. You get typed input from the fetcher and streaming from the response.
194
195Server:
196
197```typescript ignore
198import { createServerFn } from '@tanstack/react-start'
199import { generateImage, toServerSentEventsResponse } from '@tanstack/ai'
200import { openaiImage } from '@tanstack/ai-openai'
201
202export const generateImageStreamFn = createServerFn({ method: 'POST' })
203 .inputValidator((data: { prompt: string; threadId: string }) => data)
204 .handler(({ data }) => {
205 return toServerSentEventsResponse(
206 generateImage({
207 adapter: openaiImage('gpt-image-2.5-flare'),
208 prompt: data.prompt,
209 threadId: data.threadId,
210 stream: true,
211 }),
212 )
213 })
214```
215
216Client:
217
218```tsx
219import { useGenerateImage } from '@tanstack/ai-react'
220import { generateImageStreamFn } from '../lib/server-functions'
221
222const threadId = 'image-studio'
223
224export function ImageGenerator() {
225 const { generate, result, isLoading } = useGenerateImage({
226 fetcher: (input, { threadId }) =>
227 generateImageStreamFn({ data: { ...input, threadId } }),
228 threadId,
229 })
230 // Render the same way as in the quick setup.
231}
232```
233
234How the client closes the response:
235
236- If the client stops reading before the response ends, it cancels the response body.
237- A `RUN_ERROR` event also closes the unfinished response.
238- Custom cancellation hooks do not delay the error or loading state on the client.
239- The client releases the reader lock, even if cancellation fails or stays pending.
240
241### How streaming works
242
243With `stream: true`, every generation function returns an async iterable of `StreamChunk` events instead of a plain result. A successful run sends these events:
244
245```
2461. RUN_STARTED -> the hook sets status to 'generating'
2472. CUSTOM -> the hook stores the result
248 name: 'generation:result'
249 value: <your result>
2503. RUN_FINISHED -> the hook sets status to 'success'
251```
252
253If the function throws, the run sends `RUN_ERROR` instead:
254
255```
2561. RUN_STARTED -> the hook sets status to 'generating'
2572. RUN_ERROR -> the hook sets error, and status to 'error'
258 message: '...'
259```
260
261If [Generation Persistence](../persistence/generation-persistence) stores the generated files, a `CUSTOM` event named `generation:artifacts` comes before `generation:result`. It carries the stored file references.
262
263Chat streaming uses the same event protocol. As a result, `toServerSentEventsResponse()` and `fetchServerSentEvents()` work for chat and for generations.
264
265### Show errors
266
267The hook puts a `RUN_ERROR` on `error` and sets `status` to `'error'`. Use `onError` to log it, and show `error.message` in your UI:
268
269```tsx
270import { fetchServerSentEvents, useGenerateImage } from '@tanstack/ai-react'
271
272export function ImageGenerator() {
273 const { generate, result, error, status } = useGenerateImage({
274 connection: fetchServerSentEvents('/api/generate/image'),
275 threadId: 'image-studio',
276 onError: (err) => console.error('Generation failed:', err.message),
277 })
278
279 return (
280 <div>
281 <button onClick={() => generate({ prompt: 'A sunset over mountains' })}>
282 Generate
283 </button>
284 {status === 'error' && <p role="alert">Error: {error?.message}</p>}
285 {result?.images.map((img, i) => (
286 <img
287 key={i}
288 src={img.url || `data:image/png;base64,${img.b64Json}`}
289 alt="Generated image"
290 />
291 ))}
292 </div>
293 )
294}
295```
296
297### Hook options and return values
298
299All generation hooks share one set of options and one return shape. The full tables, result transforms, and the framework variants are in [Generation Hooks](./generation-hooks).
300
301### Architecture
302
303```mermaid
304flowchart TB
305 subgraph Server ["Server"]
306 direction TB
307 activities["generateImage({ ..., stream: true })
308generateSpeech({ ..., stream: true })
309generateTranscription({ ..., stream: true })
310summarize({ ..., stream: true })
311generateVideo({ ..., stream: true })"]
312 transport["toServerSentEventsResponse()"]
313 activities --> transport
314 end
315
316 transport -- "StreamChunks via SSE
317RUN_STARTED, generation:result, RUN_FINISHED" --> adapter
318
319 subgraph Client ["Client"]
320 direction TB
321 adapter["fetchServerSentEvents('/api/...')"]
322 gc["GenerationClient
323(state machine)"]
324 hooks["Framework hooks
325useGenerateImage(), useGenerateSpeech(),
326useGenerateVideo(), useSummarize(),
327useTranscription()"]
328 adapter --> gc
329 gc -- "result, isLoading, error, status" --> hooks
330 end
331```
332
333On the server, every generation is an async function that returns a result. With `stream: true`, the same function returns a `StreamChunk` iterable. The client already knows how to read that iterable, because chat uses it too.