Open History to see the last commit
1---
2title: Image Generation
3id: image-generation
4order: 5
5description: "Generate and edit images with OpenAI, Gemini, BytePlus Seedream, Grok, OpenRouter, and fal.ai through one generateImage() call and the useGenerateImage hook."
6keywords:
7 - tanstack ai
8 - image generation
9 - generateImage
10 - dall-e
11 - imagen
12 - nano banana
13 - flux
14 - fal.ai
15---
16
17`generateImage()` sends a text prompt to an image model and returns the images. `useGenerateImage` shows them in the browser.
18
19## Generate an image
20
21You need a React app with a server route, and an OpenAI API key. This takes about 5 minutes.
22
231. Install the packages:
24
25<!-- ::start:tabs variant="package-manager" mode="install" -->
26
27react: @tanstack/ai @tanstack/ai-react @tanstack/ai-openai
28
29<!-- ::end:tabs -->
30
312. Put your key in `.env`:
32
33```bash
34OPENAI_API_KEY=sk-...
35```
36
373. Add a `POST` route at `/api/generate/image`:
38
39```typescript
40import {
41 generateImage,
42 generationParamsFromRequest,
43 toServerSentEventsResponse,
44} from '@tanstack/ai'
45import { openaiImage } from '@tanstack/ai-openai'
46
47export async function POST(request: Request) {
48 const { input, threadId } = await generationParamsFromRequest('image', request)
49 if (typeof input.prompt !== 'string') {
50 return new Response('Send a text prompt.', { status: 400 })
51 }
52
53 const stream = generateImage({
54 adapter: openaiImage('gpt-image-2.5-flare'),
55 prompt: input.prompt,
56 threadId,
57 size: '1024x1024',
58 stream: true,
59 })
60 return toServerSentEventsResponse(stream)
61}
62```
63
644. Call the route from a component:
65
66```tsx
67import { useState } from 'react'
68import { fetchServerSentEvents, useGenerateImage } from '@tanstack/ai-react'
69
70export function ImageGenerator() {
71 const [prompt, setPrompt] = useState('')
72 const { generate, result, isLoading, error } = useGenerateImage({
73 connection: fetchServerSentEvents('/api/generate/image'),
74 threadId: 'image-studio',
75 })
76
77 return (
78 <div>
79 <input
80 value={prompt}
81 onChange={(e) => setPrompt(e.target.value)}
82 placeholder="Describe an image..."
83 />
84 <button
85 onClick={() => generate({ prompt })}
86 disabled={isLoading || !prompt.trim()}
87 >
88 {isLoading ? 'Generating...' : 'Generate'}
89 </button>
90 {error && <p role="alert">{error.message}</p>}
91 {result?.images.map((img, i) => (
92 <img
93 key={i}
94 src={img.url || `data:image/png;base64,${img.b64Json}`}
95 alt={img.revisedPrompt || 'Generated image'}
96 />
97 ))}
98 </div>
99 )
100}
101```
102
103Type a prompt and click **Generate**. The image shows up below the button.
104
105For a full React and TanStack Start walkthrough with OpenRouter, open [Generate Image](../tutorials/generate-image).
106
107## How it works
108
109- `generateImage()` sends the prompt to the model that the adapter names.
110- The result has an `images` array. Each image has a `url`, or base64 bytes in `b64Json`, depending on the provider.
111- With `stream: true`, the route sends the result to the hook as Server-Sent Events. The hook stores it on `result`.
112
113You can also call `generateImage()` without the hook, for example in a script:
114
115```typescript
116import { generateImage } from '@tanstack/ai'
117import { openaiImage } from '@tanstack/ai-openai'
118
119const result = await generateImage({
120 adapter: openaiImage('gpt-image-2.5-flare'),
121 prompt: 'A beautiful sunset over mountains',
122 threadId: 'thread-1',
123})
124
125console.log(result.images[0]?.b64Json)
126```
127
128The shared model for every generation (transports, events, errors) is in [Generations](./generations). The hook options and return values are in [Generation Hooks](./generation-hooks#options). To keep images after a reload, or after the provider URLs expire, add [Generation Persistence](../persistence/generation-persistence).
129
130## Options
131
132| Option | Type | Description |
133| --- | --- | --- |
134| `adapter` | `ImageAdapter` | The image adapter and model (required) |
135| `prompt` | `string \| MediaPromptPart[]` | What to draw (required). An array of text and image parts works on models that take reference images. See [Image-conditioned generation](#image-conditioned-generation). |
136| `numberOfImages` | `number` | How many images to make |
137| `size` | `string` | Image size. The format depends on the model. |
138| `modelOptions` | `object` | Model-specific options, typed per model |
139
140## Pick a provider
141
142Change the adapter. The rest of the code stays the same.
143
144| Provider | Adapter | Package | Newest model | Key |
145| --- | --- | --- | --- | --- |
146| OpenAI | `openaiImage` | `@tanstack/ai-openai` | `gpt-image-2.5-flare` | `OPENAI_API_KEY` |
147| Gemini | `geminiImage` | `@tanstack/ai-gemini` | `gemini-nano-banana-2.1` | `GOOGLE_API_KEY` or `GEMINI_API_KEY` |
148| BytePlus | `byteplusImage` | `@tanstack/ai-byteplus` | `dola-seedream-5-0-pro-260628` | `ARK_API_KEY` or `BYTEPLUS_API_KEY` |
149| Grok | `grokImage` | `@tanstack/ai-grok` | `grok-imagine-image-2.0` | `XAI_API_KEY` |
150| OpenRouter | `openRouterImage` | `@tanstack/ai-openrouter` | `google/gemini-nano-banana-2.1` | `OPENROUTER_API_KEY` |
151| fal.ai | `falImage` | `@tanstack/ai-fal` | Any of 600+ fal endpoints, for example `fal-ai/flux/dev` | `FAL_KEY` |
152
153Anthropic has no image generation API.
154
155### Gemini
156
157Gemini has two groups of image models:
158
159- **Native models (Nano Banana)**, such as `gemini-nano-banana-2.1`. They use the Interactions API. `size` is `"<aspectRatio>_<resolution>"`.
160- **Imagen models**, such as `imagen-4.0-generate-001`. They use the `generateImages` API. `size` is `WIDTHxHEIGHT`.
161
162```typescript
163import { generateImage } from '@tanstack/ai'
164import { geminiImage } from '@tanstack/ai-gemini'
165
166const native = await generateImage({
167 adapter: geminiImage('gemini-nano-banana-2.1'),
168 prompt: 'A futuristic cityscape at night',
169 threadId: 'thread-1',
170 size: '16:9_4K',
171})
172
173const imagen = await generateImage({
174 adapter: geminiImage('imagen-4.0-generate-001'),
175 prompt: 'A futuristic cityscape at night',
176 threadId: 'thread-1',
177})
178
179console.log(native.images[0]?.b64Json)
180```
181
182### BytePlus
183
184Seedream `size` takes a token (`1K`, `2K`, `4K`) or explicit pixels (`2048x2048`). Do not mix the two.
185
186```typescript
187import { generateImage } from '@tanstack/ai'
188import { byteplusImage } from '@tanstack/ai-byteplus'
189
190const result = await generateImage({
191 adapter: byteplusImage('dola-seedream-5-0-pro-260628'),
192 prompt: 'A futuristic cityscape at night',
193 threadId: 'thread-1',
194 size: '2K',
195 modelOptions: { watermark: false },
196})
197
198console.log(result.images[0]?.url)
199```
200
201Seedream works differently from the other providers in three ways:
202
203- **`watermark` is `true` by default.** BytePlus puts "AI generated" in the corner. Set it to `false` to remove it.
204- **`numberOfImages` is a maximum.** Seedream has no `n` parameter. A request for four images can return two.
205- **Image URLs expire after 24 hours.** For inline bytes, pass `response_format: 'b64_json'` in `modelOptions`.
206
207See the [BytePlus adapter](../adapters/byteplus#image-generation-seedream) for more.
208
209## Edit a Gemini native image
210
211You have an image from a Gemini native model. You want to change it, without a second upload of that image.
212
2131. Generate the first image.
2142. Call `generateImage` again. Set `previous_interaction_id` to `first.id`, and write only the change in `prompt`.
2153. Read `edited.images` for the new picture.
216
217```typescript
218import { generateImage } from '@tanstack/ai'
219import { geminiImage } from '@tanstack/ai-gemini'
220
221const adapter = geminiImage('gemini-nano-banana-2.1')
222
223const first = await generateImage({
224 adapter,
225 prompt: 'A red bicycle on a quiet street',
226 threadId: 'thread-1',
227})
228
229const edited = await generateImage({
230 adapter,
231 prompt: 'Make the bicycle blue',
232 threadId: 'thread-1',
233 modelOptions: { previous_interaction_id: first.id },
234})
235```
236
237`edited.images` holds the new picture. `edited.id` is the id for the next edit.
238
239Rules for the edit:
240
241- Leave `store` unset. The API default is `true`. If you set `store` to `false`, a later call cannot use that id.
242- A free tier keeps a stored interaction for 1 day. A paid tier keeps it for 55 days.
243- If the edit needs a new reference image, add that image part on this call. Do not send the image from `first` again.
244- If the model is Imagen, do not pass `previous_interaction_id`. The call throws.
245
246The Interactions API is in Beta.
247
248## Image-conditioned generation
249
250You want a new image that starts from an image you have: a restyle, an edit, or a mix of references. Pass `prompt` as an ordered array of text and image parts:
251
252```typescript
253import { generateImage } from '@tanstack/ai'
254import { openaiImage } from '@tanstack/ai-openai'
255
256await generateImage({
257 adapter: openaiImage('gpt-image-2.5-flare'),
258 prompt: [
259 { type: 'text', content: 'Turn this into a cinematic product photo' },
260 {
261 type: 'image',
262 source: { type: 'url', value: 'https://example.com/product.png' },
263 },
264 ],
265 threadId: 'thread-1',
266})
267```
268
269What to know:
270
271- **Part order matters.** Gemini native models and OpenRouter get the parts in the same order, so text can refer to the image next to it. OpenAI, fal, and xAI take the image parts out and join the text parts into one prompt.
272- **Types check the model.** An image part on a text-only model (for example `dall-e-3` or Imagen) is a type error.
273- **Unsupported adapters throw.** An adapter that cannot take image inputs throws a runtime error. It does not drop the images.
274
275Masks, roles, URL rules, and per-provider limits are in [Image Generation: Advanced](./image-generation-advanced#role-hints-with-metadatarole).
276
277### Referencing images from your prompt
278
279The SDK sends your prompt text as you wrote it. It never adds or changes reference markers. To point at a specific input image, use the convention of the provider:
280
281| Provider | Convention | Example |
282| --- | --- | --- |
283| **OpenAI** (gpt-image) | Numbered prose, from the OpenAI prompting guide | `"apply the style of image 2 to image 1"` |
284| **FLUX.2 on fal / BFL** | Numbered prose (BFL reads `image N`) | `"subject from image 1, style from image 2"` |
285| **Gemini** (native models) | Describe the reference by its content or role | `"using the attached fabric sample as the texture"` |
286| **fal Kling / Seedance endpoints** | `@` tags, counted from 1 in input order | `"Put @Image1 in the style of @Image2"` |
287| **xAI grok-imagine** | No syntax. xAI uses the request order. | `"render the product in the style of the second image"` |
288
289To remember which part is "image 2", you can add a `metadata.tag` label. The SDK ignores it:
290
291```typescript
292import type { MediaPromptPart } from '@tanstack/ai'
293
294const productUrl = 'https://example.com/product.png'
295const styleUrl = 'https://example.com/style.png'
296
297const prompt: Array<MediaPromptPart> = [
298 { type: 'text', content: 'Put @Image1 in the style of @Image2' },
299 {
300 type: 'image',
301 source: { type: 'url', value: productUrl },
302 metadata: { tag: 'product' },
303 },
304 {
305 type: 'image',
306 source: { type: 'url', value: styleUrl },
307 metadata: { tag: 'style' },
308 },
309]
310```
311
312## Advanced
313
314Sizes per model, every model option, masks and role hints, URL inputs, provider limits, the result shape, cost tracking, errors, and explicit API keys are in [Image Generation: Advanced](./image-generation-advanced).