Open History to see the last commit
1---
2title: Generations
3id: generations
4order: 1
5description: "One shape for image, speech, transcription, summarization and video: a server function, a route, and a hook. Copy the snippets and pick a transport."
6keywords:
7 - tanstack ai
8 - generations
9 - media generation
10 - image generation
11 - transcription
12 - tts
13 - video generation
14---
15
16You want an image, some speech, a transcript, a video, or a live stream, not a conversation. Every one
17of those is a **generation**: one request, one result. They all share the same shape, so
18learning one teaches you the rest.
19
20For a live, prompt-steerable stream that does not end as a file, see [Live Generation](./live-generation) or [World Generation](./world-generation).
21
22## The fastest path
23
24A server route that streams the result:
25
26```typescript ignore
27import { generateImage, toServerSentEventsResponse } from '@tanstack/ai'
28import { openaiImage } from '@tanstack/ai-openai'
29
30export async function POST(request: Request) {
31 const { prompt } = await request.json()
32 const stream = generateImage({
33 adapter: openaiImage('dall-e-3'),
34 prompt: typeof prompt === 'string' ? prompt : '',
35 stream: true,
36 })
37 return toServerSentEventsResponse(stream)
38}
39```
40
41A hook that calls it:
42
43```tsx
44import { fetchServerSentEvents, useGenerateImage } from '@tanstack/ai-react'
45
46function ImageGenerator() {
47 const { generate, result, isLoading, error } = useGenerateImage({
48 connection: fetchServerSentEvents('/api/generate/image'),
49 })
50
51 return (
52 <div>
53 <button onClick={() => generate({ prompt: 'A sunset over mountains' })}>
54 {isLoading ? 'Generating…' : 'Generate'}
55 </button>
56 {error && <p role="alert">{error.message}</p>}
57 {result?.images.map((img, i) => (
58 <img key={i} src={img.url || `data:image/png;base64,${img.b64Json}`} />
59 ))}
60 </div>
61 )
62}
63```
64
65That is the whole loop. Swap `generateImage` and `useGenerateImage` for any other pair
66in the table below and nothing else changes.
67
68For a React + Start walkthrough with OpenRouter, open [Generate Image](../tutorials/generate-image).
69
70## Which transport?
71
72| Transport | Use it when | How |
73| --- | --- | --- |
74| **Streaming route** | You have an API route. The default, and what the snippets above use. | `stream: true` plus `toServerSentEventsResponse`, and `connection:` on the hook |
75| **Direct** | You call a server function and want plain JSON back. Simplest, no streaming. | Return the result from the function, and pass `fetcher:` on the hook |
76| **Server function that streams** | You use TanStack Start server functions and want typed input plus streaming. | Return `toServerSentEventsResponse(...)` from the function, and pass `fetcher:` |
77
78The third one is the best of both when you are on Start: input is fully typed and the
79streaming is handled for you. All three are written out in
80[Transports in full](#transports-in-full).
81
82## Available Generations
83
84| Activity | Server Function | Client Hook (React) | Guide |
85|----------|----------------|---------------------|-------|
86| Image generation | `generateImage()` | `useGenerateImage()` | [Image Generation](./image-generation) |
87| Audio generation | `generateAudio()` | `useGenerateAudio()` | [Audio Generation](./audio-generation) |
88| Text-to-speech | `generateSpeech()` | `useGenerateSpeech()` | [Text-to-Speech](./text-to-speech) |
89| Transcription | `generateTranscription()` | `useTranscription()` | [Transcription](./transcription) |
90| Voice creation | `generateVoice()` | - | [Voice Creation](./voice-creation) |
91| Summarization | `summarize()` | `useSummarize()` | - |
92| Video generation | `generateVideo()` | `useGenerateVideo()` | [Video Generation](./video-generation) |
93| Live generation | `generateLiveVideo()` | - | [Live Generation](./live-generation) |
94| World generation | `generateWorld()` | - | [World Generation](./world-generation) |
95
96> **Note:** Video adapters use a jobs/polling architecture. The `useGenerateVideo` hook additionally exposes `jobId`, `videoStatus`, `onJobCreated`, and `onStatusUpdate` for tracking the polling lifecycle. Live adapters mint a session token. World Labs world jobs return a viewer URL and asset links.
97
98## Advanced
99
100### Transports in full
101
102#### Streaming Mode (Connection Adapter)
103
104The server passes `stream: true` to the generation function and sends the result as SSE. The client uses `fetchServerSentEvents()` to consume the stream.
105
106**Server:**
107
108```typescript ignore
109import { generateImage, toServerSentEventsResponse } from '@tanstack/ai'
110import { openaiImage } from '@tanstack/ai-openai'
111
112// In your API route handler
113const stream = generateImage({
114 adapter: openaiImage('dall-e-3'),
115 prompt: 'A sunset over mountains',
116 stream: true,
117})
118
119return toServerSentEventsResponse(stream)
120```
121
122**Client:**
123
124```tsx
125import { useGenerateImage, fetchServerSentEvents } from '@tanstack/ai-react'
126
127const { generate, result, isLoading } = useGenerateImage({
128 connection: fetchServerSentEvents('/api/generate/image'),
129})
130```
131
132#### Direct Mode (Fetcher)
133
134The client calls a server function directly and receives the result as JSON. No streaming protocol needed.
135
136**Server:**
137
138```typescript ignore
139import { createServerFn } from '@tanstack/react-start'
140import { generateImage } from '@tanstack/ai'
141import { openaiImage } from '@tanstack/ai-openai'
142
143export const generateImageFn = createServerFn({ method: 'POST' })
144 .inputValidator((data: { prompt: string }) => data)
145 .handler(async ({ data }) => {
146 return generateImage({
147 adapter: openaiImage('dall-e-3'),
148 prompt: data.prompt,
149 })
150 })
151```
152
153**Client:**
154
155```tsx
156import { useGenerateImage } from '@tanstack/ai-react'
157import { generateImageFn } from '../lib/server-functions'
158
159const { generate, result, isLoading } = useGenerateImage({
160 fetcher: (input) => generateImageFn({ data: input }),
161})
162```
163
164#### Server Function Streaming (Fetcher + Response)
165
166Combines the best of both: **type-safe input** from the fetcher pattern with **streaming** from a server function that returns an SSE `Response`. When the fetcher returns a `Response` object (instead of a plain result), the client automatically parses it as an SSE stream.
167
168**Server:**
169
170```typescript ignore
171import { createServerFn } from '@tanstack/react-start'
172import { generateImage, toServerSentEventsResponse } from '@tanstack/ai'
173import { openaiImage } from '@tanstack/ai-openai'
174
175export const generateImageStreamFn = createServerFn({ method: 'POST' })
176 .inputValidator((data: { prompt: string }) => data)
177 .handler(({ data }) => {
178 return toServerSentEventsResponse(
179 generateImage({
180 adapter: openaiImage('dall-e-3'),
181 prompt: data.prompt,
182 stream: true,
183 }),
184 )
185 })
186```
187
188**Client:**
189
190```tsx
191import { useGenerateImage } from '@tanstack/ai-react'
192import { generateImageStreamFn } from '../lib/server-functions'
193
194const { generate, result, isLoading } = useGenerateImage({
195 fetcher: (input) => generateImageStreamFn({ data: input }),
196})
197```
198
199This is the recommended approach when using TanStack Start server functions, the input is fully typed (e.g., `ImageGenerateInput`), and the streaming protocol is handled transparently.
200
201
202### How Streaming Works
203
204When you pass `stream: true` to any generation function, it returns an async iterable of `StreamChunk` events instead of a plain result:
205
206```
2071. RUN_STARTED → Client sets status to 'generating'
2082. CUSTOM → Client receives the result
209 name: 'generation:result'
210 value: <your result>
2113. RUN_FINISHED → Client sets status to 'success'
212```
213
214If the function throws, a `RUN_ERROR` event is emitted instead:
215
216```
2171. RUN_STARTED → Client sets status to 'generating'
2182. RUN_ERROR → Client sets error + status to 'error'
219 error: { message: '...' }
220```
221
222This is the same event protocol used by chat streaming, so the same transport layer (`toServerSentEventsResponse`, `fetchServerSentEvents`) works for both.
223
224When the server emits `RUN_ERROR`, the client surfaces it on `error` (and sets `status` to `'error'`). Use the `onError` callback to react, and render `error?.message` in your UI:
225
226```tsx
227import { useGenerateImage, fetchServerSentEvents } from '@tanstack/ai-react'
228
229function ImageGenerator() {
230 const { generate, result, error, status } = useGenerateImage({
231 connection: fetchServerSentEvents('/api/generate/image'),
232 onError: (err) => console.error('Generation failed:', err.message),
233 })
234
235 return (
236 <div>
237 <button onClick={() => generate({ prompt: 'A sunset over mountains' })}>
238 Generate
239 </button>
240 {status === 'error' && <p role="alert">Error: {error?.message}</p>}
241 {result?.images.map((img, i) => (
242 <img key={i} src={img.url || `data:image/png;base64,${img.b64Json}`} />
243 ))}
244 </div>
245 )
246}
247```
248
249
250### Common Hook API
251
252All generation hooks share the same interface:
253
254| Option | Type | Description |
255|--------|------|-------------|
256| `connection` | `ConnectionAdapter` | Streaming transport (SSE, HTTP stream, custom) |
257| `fetcher` | `(input) => Promise<Result \| Response>` | Direct async function, or server function returning an SSE `Response` |
258| `threadId` | `string` | Stable scope for this generation. Required when `persistence` is on. Optional for ephemeral runs. |
259| `body` | `Record<string, any>` | Additional body parameters (connection mode) |
260| `onResult` | `(result) => T \| null \| void` | Transform or react to the result |
261| `onError` | `(error) => void` | Error callback |
262| `onProgress` | `(progress, message?) => void` | Progress updates (0-100) |
263
264| Return | Type | Description |
265|--------|------|-------------|
266| `generate` | `(input) => Promise<void>` | Trigger generation |
267| `result` | `T \| null` | The result (optionally transformed), or null |
268| `isLoading` | `boolean` | Whether generation is in progress |
269| `error` | `Error \| undefined` | Current error, if any |
270| `status` | `GenerationClientState` | `'idle'` \| `'generating'` \| `'success'` \| `'error'` |
271| `stop` | `() => void` | Abort the current generation |
272| `reset` | `() => void` | Clear all state, return to idle |
273
274#### Result Transform
275
276The `onResult` callback can optionally transform the stored result:
277
278- Return a **non-null value**, replaces the stored result with the transformed value
279- Return **`null`**, keeps the previous result unchanged (useful for filtering)
280- Return **nothing** (`void`), stores the raw result as-is
281
282TypeScript automatically infers the result type from your `onResult` return value, no explicit generic parameter needed.
283
284```tsx
285import { useGenerateSpeech, fetchServerSentEvents } from '@tanstack/ai-react'
286import type { TTSResult } from '@tanstack/ai'
287
288function SpeechPlayer() {
289 const { result } = useGenerateSpeech({
290 connection: fetchServerSentEvents('/api/generate/speech'),
291 onResult: (raw: TTSResult) => ({
292 audioUrl: `data:${raw.contentType};base64,${raw.audio}`,
293 duration: raw.duration,
294 }),
295 })
296 // result is typed as { audioUrl: string; duration?: number } | null
297}
298```
299
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
333The key insight: **every generation activity on the server is just an async function that returns a result**. By passing `stream: true`, the function returns a `StreamChunk` iterable instead of a plain result, which the client already knows how to consume.
334