Skip to content
Source
Sign inSign up
TanStack/ai
Open History to see the last commit

image-generation.md

887 lines38.3 KB

1---
2title: Image Generation
3id: image-generation
4order: 5
5description: "Generate images with OpenAI DALL-E, Gemini NanoBanana and Imagen, BytePlus Seedream, and fal.ai models via TanStack AI's unified generateImage() API."
6keywords:
7 - tanstack ai
8 - image generation
9 - generateImage
10 - dall-e
11 - imagen
12 - nano banana
13 - flux
14 - fal.ai
15---
16​
17TanStack AI provides support for image generation through dedicated image adapters. This guide covers how to use the image generation functionality with OpenAI and Gemini providers.
18​
19## Overview
20​
21Image generation is handled by image adapters that follow the same tree-shakeable architecture as other adapters in TanStack AI. The image adapters support:
22​
23- **OpenAI**: DALL-E 2, DALL-E 3, GPT-Image-1, GPT-Image-1-Mini, and GPT-Image-2 models
24- **Gemini**: Gemini native image models (NanoBanana) and Imagen 3/4 models
25- **BytePlus**: Seedream 5.0, 4.5, and 4.0 models
26- **fal.ai**: 600+ models including Nano Banana Pro, FLUX, and more
27​
28## Basic Usage
29​
30### OpenAI Image Generation
31​
32```typescript
33import { generateImage } from "@tanstack/ai";
34import { openaiImage } from "@tanstack/ai-openai";
35​
36// Generate an image (the adapter uses OPENAI_API_KEY from environment)
37const result = await generateImage({
38 adapter: openaiImage("dall-e-3"),
39 prompt: "A beautiful sunset over mountains",
40});
41​
42console.log(result.images[0]?.url); // URL to the generated image
43```
44​
45### Gemini Image Generation
46​
47Gemini has two image model groups. Gemini native models (NanoBanana) use the Interactions API. Imagen models use `generateImages`.
48​
49```typescript
50import { generateImage } from "@tanstack/ai";
51import { geminiImage } from "@tanstack/ai-gemini";
52​
53// Gemini native model (NanoBanana). Uses the Interactions API.
54const result = await generateImage({
55 adapter: geminiImage("gemini-3.1-flash-image"),
56 prompt: "A futuristic cityscape at night",
57 size: "16:9_4K",
58});
59​
60// Imagen model. Uses the generateImages API.
61const result2 = await generateImage({
62 adapter: geminiImage("imagen-4.0-generate-001"),
63 prompt: "A futuristic cityscape at night",
64});
65​
66console.log(result.images[0]?.b64Json); // Base64 encoded image
67```
68​
69#### Edit a Gemini native image
70​
71You have an image from a Gemini native model. You want to change that image without a second upload of that image.
72​
73Pass the last `id` back. Write only the change in `prompt`:
74​
75```typescript
76import { generateImage } from "@tanstack/ai";
77import { geminiImage } from "@tanstack/ai-gemini";
78​
79const adapter = geminiImage("gemini-3.1-flash-image");
80​
81const first = await generateImage({
82 adapter,
83 prompt: "A red bicycle on a quiet street",
84});
85​
86const edited = await generateImage({
87 adapter,
88 prompt: "Make the bicycle blue",
89 modelOptions: { previous_interaction_id: first.id },
90});
91```
92​
931. Generate the first image.
942. Call `generateImage` again with `previous_interaction_id` set to `first.id`.
953. Read `edited.images` for the new picture.
96​
97Keep the interaction so the next edit can run:
98​
991. Leave `store` unset.
1002. If you set `store` to `false`, a later call cannot use that id.
101​
102The API default for `store` is `true`.
103​
104A free tier keeps a stored interaction for 1 day. A paid tier keeps it for 55 days.
105​
106If the model is Imagen, do not pass `previous_interaction_id`. The call throws.
107​
108If this edit needs a new reference image, add that image part on this call. Do not send the image from `first`.
109​
110The Interactions API is in Beta.
111​
112`edited.images` holds the new picture. `edited.id` is the id for the next edit.
113​
114### BytePlus Image Generation
115​
116Seedream sizes take either a token (`1K`, `2K`, `4K`) or explicit pixels (`2048x2048`) — never a mix of the two.
117​
118```typescript
119import { generateImage } from "@tanstack/ai";
120import { byteplusImage } from "@tanstack/ai-byteplus";
121​
122const result = await generateImage({
123 adapter: byteplusImage("dola-seedream-5-0-pro-260628"),
124 prompt: "A futuristic cityscape at night",
125 size: "2K",
126 modelOptions: { watermark: false },
127});
128​
129console.log(result.images[0]?.url);
130```
131​
132Two Seedream behaviours differ from the other providers:
133​
134- **`watermark` defaults to `true`** — BytePlus stamps "AI generated" into the corner unless you turn it off.
135- **`numberOfImages` is an upper bound, not a count.** Seedream has no `n` parameter, so more than one image maps onto its group-image mode and the model decides how many the prompt warrants. A request for four can return two.
136​
137Image URLs expire after 24 hours; pass `response_format: 'b64_json'` in `modelOptions` for inline bytes. See the [BytePlus adapter](../adapters/byteplus#image-generation-seedream) for details.
138​
139## Options
140​
141### Common Options
142​
143All image adapters support these common options:
144​
145| Option | Type | Description |
146| ---------------- | ----------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
147| `adapter` | `ImageAdapter` | Image adapter instance with model (required) |
148| `prompt` | `string \| MediaPromptPart[]` | Description of the image to generate (required). A plain string, or — on models that support image-conditioned generation — an ordered array of content parts interleaving text with image inputs. See [Image-Conditioned Generation](#image-conditioned-generation) below. |
149| `numberOfImages` | `number` | Number of images to generate |
150| `size` | `string` | Size of the generated image in WIDTHxHEIGHT format |
151| `modelOptions?` | `object` | Model-specific options (renamed from `providerOptions`) |
152​
153### Size Options
154​
155#### OpenAI Models
156​
157| Model | Supported Sizes |
158| ------------------------ | --------------------------------------------- |
159| `gpt-image-2.5-flare` | `1024x1024`, `1536x1024`, `1024x1536`, `auto` |
160| `gpt-image-2.5-sunburst` | `1024x1024`, `1536x1024`, `1024x1536`, `auto` |
161| `gpt-image-2` | `1024x1024`, `1536x1024`, `1024x1536`, `auto` |
162| `gpt-image-1` | `1024x1024`, `1536x1024`, `1024x1536`, `auto` |
163| `gpt-image-1-mini` | `1024x1024`, `1536x1024`, `1024x1536`, `auto` |
164| `dall-e-3` | `1024x1024`, `1792x1024`, `1024x1792` |
165| `dall-e-2` | `256x256`, `512x512`, `1024x1024` |
166​
167#### Gemini Native Models (NanoBanana)
168​
169Gemini native image models use a template literal size format: `"aspectRatio_resolution"`. Each model accepts its own set, narrowed at compile time:
170​
171| Model | Aspect Ratios | Resolutions |
172| ----------------------------- | ------------------------------------------------------------------------------------------------------ | ----------------------- |
173| `gemini-3.1-flash-image` | `1:1`, `2:3`, `3:2`, `3:4`, `4:3`, `4:5`, `5:4`, `9:16`, `16:9`, `21:9`, `1:4`, `4:1`, `1:8`, `8:1` | `512`, `1K`, `2K`, `4K` |
174| `gemini-3.1-flash-lite-image` | same 14 as above (see note) | `1K` |
175| `gemini-nano-banana-2.1` | same 14 as above | `1K`, `2K`, `4K` |
176| `gemini-3-pro-image` | `1:1`, `2:3`, `3:2`, `3:4`, `4:3`, `4:5`, `5:4`, `9:16`, `16:9`, `21:9` | `1K`, `2K`, `4K` |
177| `gemini-2.5-flash-image` | same 10 as above | none — bare ratio |
178​
179```typescript ignore
180// Examples
181size: "16:9_4K"; // Widescreen at 4K resolution
182size: "1:1_2K"; // Square at 2K resolution
183size: "1:8_512"; // Tall banner at the 512 (0.5K) tier — Flash Image only
184size: "16:9"; // gemini-2.5-flash-image: bare ratio, no resolution suffix
185```
186​
187The `K` is case-sensitive (`1k` is rejected by the API), the smallest tier's token is `512` (not `512px` or `0.5K`), and `9:21` is Vertex/Cloud-only so it is not accepted. Google documents no `image_size` for `gemini-2.5-flash-image`, so that model takes a bare aspect ratio and the adapter sends no `imageSize`.
188​
189> **Note on `gemini-3.1-flash-lite-image`.** The four extreme banner ratios (`1:4`, `4:1`, `1:8`, `8:1`) are partially inferred for this model. Unlike the other three, Flash Lite has no per-model ratio table in Google's Gemini API guide; the 14-value set comes from the Cloud model page's explicit enumeration plus the guide's bare "a discrete set of 14 aspect ratios" assertion. The only Gemini-API enumeration for it is a 10-item bullet headed "New aspect ratios", which we read as a what's-new list rather than an exhaustive one. If the API rejects those four in practice, prefer the 10 standard ratios on this model.
190​
191#### Gemini Imagen Models
192​
193Imagen models accept WIDTHxHEIGHT format, which maps to aspect ratios internally:
194​
195| Size | Aspect Ratio |
196| ----------- | ------------ |
197| `1024x1024` | 1:1 |
198| `1920x1080` | 16:9 |
199| `1080x1920` | 9:16 |
200​
201Alternatively, you can specify the aspect ratio directly in Model Options:
202​
203```typescript
204import { generateImage } from "@tanstack/ai";
205import { geminiImage } from "@tanstack/ai-gemini";
206​
207const result = await generateImage({
208 adapter: geminiImage("imagen-4.0-generate-001"),
209 prompt: "A landscape photo",
210 modelOptions: {
211 aspectRatio: "16:9",
212 },
213});
214```
215​
216## Image-Conditioned Generation
217​
218For image-to-image, reference-guided, multi-reference, and edit / inpaint
219flows, pass the `prompt` as an ordered array of content parts — the same
220`TextPart` / `ImagePart` shapes used elsewhere for multimodal content:
221​
222```typescript
223import { generateImage } from "@tanstack/ai";
224import { openaiImage } from "@tanstack/ai-openai";
225​
226await generateImage({
227 adapter: openaiImage("gpt-image-2"),
228 prompt: [
229 { type: "text", content: "Turn this into a cinematic product photo" },
230 {
231 type: "image",
232 source: { type: "url", value: "https://example.com/product.png" },
233 },
234 ],
235});
236```
237​
238Part order is meaningful. Providers with natively multimodal prompts
239(Gemini image models, OpenRouter) receive the parts exactly as written, so
240text can refer to its neighbouring images:
241​
242```typescript
243import { generateImage } from "@tanstack/ai";
244import { geminiImage } from "@tanstack/ai-gemini";
245import { badExampleUrl, goodExampleUrl } from "./urls";
246​
247await generateImage({
248 adapter: geminiImage("gemini-3.1-flash-image"),
249 prompt: [
250 { type: "text", content: "Not like this" },
251 { type: "image", source: { type: "url", value: badExampleUrl } },
252 { type: "text", content: "more like this" },
253 { type: "image", source: { type: "url", value: goodExampleUrl } },
254 ],
255});
256```
257​
258Providers with named request fields (OpenAI, fal, xAI) extract the image
259parts and flatten the text (text parts are joined verbatim, paragraph
260separated).
261​
262The accepted part types are narrowed **per model at compile time**: passing
263an image part to a text-only model (e.g. `dall-e-3`, Imagen) is a type
264error, not just a runtime throw.
265​
266### Referencing images from your prompt
267​
268**Your prompt text is always sent verbatim — the SDK never injects or
269rewrites referencing markers.** When you want the text to refer to specific
270input images, write the provider's own convention yourself:
271​
272| Provider | Convention | Example |
273| ---------------------------------- | ------------------------------------------------------- | ------------------------------------------------------- |
274| **OpenAI** (gpt-image) | Indexed prose, per OpenAI's prompting guide | `"apply the style of image 2 to image 1"` |
275| **FLUX.2 on fal / BFL** | Indexed prose (BFL's docs parse `image N`) | `"subject from image 1, style from image 2"` |
276| **Gemini** (native image models) | Describe the reference by content/role | `"using the attached fabric sample as the texture"` |
277| **fal Kling / Seedance endpoints** | `@`-tags, 1-indexed by input order | `"Put @Image1 in the style of @Image2"` |
278| **xAI grok-imagine** | No in-prompt syntax — images addressed in request order | `"render the product in the style of the second image"` |
279​
280To keep track of which part you meant by "image 2" or `@Image2`, you can
281label parts with the informational `metadata.tag` field — the SDK ignores
282it, but it keeps your code self-documenting:
283​
284```typescript ignore
285prompt: [
286 { type: "text", content: "Put @Image1 in the style of @Image2" },
287 {
288 type: "image",
289 source: { type: "url", value: productUrl },
290 metadata: { tag: "product" },
291 },
292 {
293 type: "image",
294 source: { type: "url", value: styleUrl },
295 metadata: { tag: "style" },
296 },
297];
298```
299​
300### Source format
301​
302`ImagePart.source` is a discriminated union supporting both URLs and inline
303base64 data — pass whichever you have:
304​
305```typescript ignore
306// URL source
307{ type: 'image', source: { type: 'url', value: 'https://example.com/img.png' } }
308​
309// Inline base64 data (mimeType required)
310{ type: 'image', source: { type: 'data', value: base64String, mimeType: 'image/png' } }
311```
312​
313Gemini native image generation does not download a URL in your runtime. The adapter sends the URL as `uri`. Gemini reads that URL. These sources work:
314​
315- A public HTTPS URL
316- A [Files API](https://ai.google.dev/gemini-api/docs/files) URI
317- A `gs://` reference
318​
319Two paths have no URL passthrough and must upload real bytes:
320​
321- OpenAI's `/images/edits`, and Sora `input_reference`.
322- Gemini **Veo**: its predict API accepts only inline bytes or a `gs://`
323 reference.
324​
325For these, an HTTP(S) URL input would have to be downloaded and buffered in
326memory, which can OOM memory-constrained runtimes (e.g. Cloudflare Workers). So
327by default they **throw** on an HTTP(S) URL image input rather than fetch it.
328Pass a `data:` URI (or a `gs://` reference for Veo), or opt into fetching with
329`allowUrlFetch`:
330​
331```typescript ignore
332import { createOpenaiImage } from "@tanstack/ai-openai";
333​
334// Opt into downloading + buffering HTTP(S) URL image inputs (server runtimes
335// with headroom). data: URIs always work without this flag.
336const adapter = createOpenaiImage("gpt-image-2", apiKey, {
337 allowUrlFetch: true,
338});
339```
340​
341The same `allowUrlFetch` option exists on `createOpenaiVideo` and
342`createGeminiVideo`.
343​
344### Role hints via `metadata.role`
345​
346When a generation has multiple inputs with different roles (mask vs reference
347vs start/end frame), set `metadata.role` on each part. Adapters route by role
348to the provider-specific field; parts without a role fall back to positional
349mapping.
350​
351| Role | Maps to |
352| --------------- | -------------------------------------------------------------------------------- |
353| `'reference'` | fal `reference_image_urls`; Gemini multimodal part; positional fallback |
354| `'character'` | Same as `'reference'`; Veo `referenceImages` slot (planned — no Veo adapter yet) |
355| `'mask'` | OpenAI `mask` (gpt-image-2, gpt-image-1, dall-e-2); fal `mask_url` |
356| `'control'` | fal `control_image_url` (ControlNet / depth / pose conditioning) |
357| `'start_frame'` | fal `start_image_url`; Veo `image` (planned) (used by `generateVideo`) |
358| `'end_frame'` | fal `end_image_url`; Veo `lastFrame` (planned) (used by `generateVideo`) |
359​
360#### Inpaint / edit with a mask
361​
362```typescript
363import { generateImage } from "@tanstack/ai";
364import { openaiImage } from "@tanstack/ai-openai";
365import { photoUrl, maskUrl } from "./urls";
366​
367await generateImage({
368 adapter: openaiImage("gpt-image-2"),
369 prompt: [
370 { type: "text", content: "Replace the masked region with a tree" },
371 {
372 type: "image",
373 source: { type: "url", value: photoUrl },
374 },
375 {
376 type: "image",
377 source: { type: "url", value: maskUrl },
378 metadata: { role: "mask" },
379 },
380 ],
381});
382```
383​
384#### Multi-reference composition
385​
386```typescript
387import { generateImage } from "@tanstack/ai";
388import { geminiImage } from "@tanstack/ai-gemini";
389​
390await generateImage({
391 adapter: geminiImage("gemini-3.1-flash-image"),
392 prompt: [
393 {
394 type: "text",
395 content:
396 "Generate a new image of the product using the style of the second reference",
397 },
398 {
399 type: "image",
400 source: { type: "url", value: "https://example.com/product.png" },
401 },
402 {
403 type: "image",
404 source: { type: "url", value: "https://example.com/style.png" },
405 },
406 ],
407});
408```
409​
410### Provider support
411​
412| Provider | Behavior |
413| -------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
414| **OpenAI** | `gpt-image-2.5-flare` / `gpt-image-2.5-sunburst` / `gpt-image-2` / `gpt-image-1` / `gpt-image-1-mini` → routes to `images.edit()`, up to 16 source images plus optional mask.<br>`dall-e-2` → `images.edit()` with 1 source image only.<br>`dall-e-3` → throws (no edit support). |
415| **Gemini** | Native models send each prompt part as an Interactions content block, in the same order. Up to 14 input images. The SDK does not enforce that limit.<br>To edit the last image, pass `result.id` as `modelOptions.previous_interaction_id`. Do not send that image again. A new image part on that call is an extra reference. See [Edit a Gemini native image](#edit-a-gemini-native-image).<br>Imagen throws on an image part. Imagen does not chain. |
416| **fal.ai** | Field names resolve per endpoint from a map generated from the fal SDK's endpoint types (e.g. nano-banana edit gets `image_urls`, Fooocus masks get `mask_image_url`). Defaults for unknown endpoints: 1 input → `image_url`; multiple → `image_urls`; `role: 'mask'` → `mask_url`; `role: 'control'` → `control_image_url`; `role: 'reference'` / `'character'` → `reference_image_urls`. Override with `modelOptions` for endpoint-specific fields. |
417| **Grok** | grok-imagine models → xAI's `/v1/images/edits` (up to 3 source images, addressed by xAI in request order; prompt sent verbatim). `role: 'mask'` / `'control'` throw (no Imagine API equivalent). |
418| **OpenRouter** | Prompt parts map 1:1 onto multimodal `image_url` / `text` content parts, preserving interleaved order, and are forwarded to the underlying image model. `modelOptions.strength` (0.0–1.0) controls image-to-image influence on models that document it (e.g. Recraft). One image per request — `numberOfImages > 1` throws (the gateway ignores count keys). |
419| **BytePlus** | Seedream models → every input image is a plain reference on the `image` field (up to 14, or 10 on `dola-seedream-5-0-pro-260628`). There is no mask, control or frame channel, so any role other than `'reference'` / `'character'` throws rather than being silently flattened. |
420| **Anthropic** | n/a — no image generation API. |
421​
422Adapters that don't support image-conditioned generation throw a clear
423runtime error so calls fail fast rather than silently dropping the inputs.
424​
425## Full-Stack Usage
426​
427For a React + Start walkthrough with OpenRouter, open [Generate Image](../tutorials/generate-image).
428​
429TanStack AI provides React hooks and server-side streaming helpers to build full-stack image generation with minimal boilerplate.
430​
431> **Note:** To keep a batch across reloads, or to keep the images after the
432> provider's URLs expire, add [Generation Persistence](../persistence/generation-persistence).
433​
434### Streaming Mode (Server Route + Client Hook)
435​
436**Server** — Create an API route that wraps `generateImage` as a streaming response:
437​
438```typescript ignore
439// routes/api/generate/image.ts
440import { generateImage, toServerSentEventsResponse } from "@tanstack/ai";
441import { openaiImage } from "@tanstack/ai-openai";
442import { createFileRoute } from "@tanstack/react-router";
443​
444export const Route = createFileRoute("/api/generate/image")({
445 server: {
446 handlers: {
447 POST: async ({ request }) => {
448 const body = await request.json();
449 const { prompt, size, model, numberOfImages } = body.data;
450​
451 const stream = generateImage({
452 adapter: openaiImage(model ?? "dall-e-3"),
453 prompt,
454 size,
455 numberOfImages,
456 stream: true,
457 });
458​
459 return toServerSentEventsResponse(stream);
460 },
461 },
462 },
463});
464```
465​
466**Client** — Use the `useGenerateImage` hook with a connection adapter:
467​
468```tsx
469import { useGenerateImage, fetchServerSentEvents } from "@tanstack/ai-react";
470​
471function ImageGenerator() {
472 const { generate, result, isLoading, error, reset } = useGenerateImage({
473 connection: fetchServerSentEvents("/api/generate/image"),
474 });
475​
476 return (
477 <div>
478 <button
479 onClick={() => generate({ prompt: "A sunset over mountains" })}
480 disabled={isLoading}
481 >
482 {isLoading ? "Generating..." : "Generate"}
483 </button>
484 {error && <p>Error: {error.message}</p>}
485 {result?.images.map((img, i) => (
486 <img
487 key={i}
488 src={img.url || `data:image/png;base64,${img.b64Json}`}
489 alt={img.revisedPrompt || "Generated image"}
490 />
491 ))}
492 {result && <button onClick={reset}>Clear</button>}
493 </div>
494 );
496```
497​
498The other two transports (a server function returning JSON, or one returning an
499SSE `Response`) work the same way here. They are in
500[Advanced: other transports](#other-transports), and explained once in
501[Generations](./generations#transports-in-full).
502​
503### Hook API
504​
505The `useGenerateImage` hook accepts:
506​
507| Option | Type | Description |
508| ------------ | ------------------------------------------------------- | ---------------------------------------------------------------------------------------------- |
509| `connection` | `ConnectionAdapter` | Streaming transport (SSE, HTTP stream, custom) |
510| `fetcher` | `(input) => Promise<ImageGenerationResult \| Response>` | Direct async function, or server function returning an SSE `Response` |
511| `threadId` | `string` | Stable scope for this generation. Required when `persistence` is on. Optional for ephemeral runs. |
512| `body` | `Record<string, any>` | Additional body parameters (connection mode) |
513| `onResult` | `(result) => TOutput \| null \| void` | Callback when images are generated. Optionally return a transformed value to store as `result` |
514| `onError` | `(error) => void` | Callback on error |
515| `onProgress` | `(progress, message?) => void` | Progress updates (0-100) |
516​
517And returns:
518​
519| Property | Type | Description |
520| ----------- | ---------------------------------------------- | ------------------------------------------------------ |
521| `generate` | `(input: ImageGenerateInput) => Promise<void>` | Trigger generation |
522| `result` | `ImageGenerationResult \| null` | The result, or null |
523| `isLoading` | `boolean` | Whether generation is in progress |
524| `error` | `Error \| undefined` | Current error, if any |
525| `status` | `GenerationClientState` | `'idle'` \| `'generating'` \| `'success'` \| `'error'` |
526| `stop` | `() => void` | Abort the current generation |
527| `reset` | `() => void` | Clear result, error, and return to idle |
528​
529> **Tip:** To trigger image generation from your React, Vue, or Svelte app with loading states and error handling, see [Generation Hooks](./generation-hooks).
530​
531## Advanced
532​
533Reference detail you do not need to get this working.
534​
535### Other transports
536​
537#### Direct Mode (Server Function + Fetcher)
538​
539For non-streaming usage with TanStack Start server functions:
540​
541```typescript ignore
542// lib/server-functions.ts
543import { createServerFn } from "@tanstack/react-start";
544import { generateImage } from "@tanstack/ai";
545import { openaiImage } from "@tanstack/ai-openai";
546​
547export const generateImageFn = createServerFn({ method: "POST" })
548 .inputValidator((data: { prompt: string; model?: string }) => data)
549 .handler(async ({ data }) => {
550 return generateImage({
551 adapter: openaiImage(data.model ?? "dall-e-3"),
552 prompt: data.prompt,
553 });
554 });
555```
556​
557```tsx
558// components/ImageGenerator.tsx
559import { useGenerateImage } from "@tanstack/ai-react";
560import { generateImageFn } from "../lib/server-functions";
561​
562function ImageGenerator() {
563 const { generate, result, isLoading } = useGenerateImage({
564 fetcher: (data) => generateImageFn({ data }),
565 });
566​
567 return (
568 <div>
569 <button
570 onClick={() => generate({ prompt: "A sunset over mountains" })}
571 disabled={isLoading}
572 >
573 Generate
574 </button>
575 {result?.images.map((img, i) => (
576 <img key={i} src={img.url || `data:image/png;base64,${img.b64Json}`} />
577 ))}
578 </div>
579 );
581```
582​
583#### Server Function Streaming (Fetcher + Response)
584​
585For TanStack Start server functions that stream results. The fetcher receives type-safe input and returns an SSE `Response` — the client parses it automatically:
586​
587```typescript ignore
588// lib/server-functions.ts
589import { createServerFn } from "@tanstack/react-start";
590import { generateImage, toServerSentEventsResponse } from "@tanstack/ai";
591import { openaiImage } from "@tanstack/ai-openai";
592​
593export const generateImageStreamFn = createServerFn({ method: "POST" })
594 .inputValidator((data: { prompt: string; model?: string }) => data)
595 .handler(({ data }) => {
596 return toServerSentEventsResponse(
597 generateImage({
598 adapter: openaiImage(data.model ?? "dall-e-3"),
599 prompt: data.prompt,
600 stream: true,
601 }),
602 );
603 });
604```
605​
606```tsx
607import { useGenerateImage } from "@tanstack/ai-react";
608import { generateImageStreamFn } from "../lib/server-functions";
609​
610function ImageGenerator() {
611 const { generate, result, isLoading } = useGenerateImage({
612 fetcher: (input) => generateImageStreamFn({ data: input }),
613 });
614​
615 return (
616 <div>
617 <button
618 onClick={() => generate({ prompt: "A sunset over mountains" })}
619 disabled={isLoading}
620 >
621 Generate
622 </button>
623 {result?.images.map((img, i) => (
624 <img key={i} src={img.url || `data:image/png;base64,${img.b64Json}`} />
625 ))}
626 </div>
627 );
629```
630​
631### Model Options
632​
633#### OpenAI Model Options
634​
635OpenAI models support model-specific Model Options:
636​
637##### GPT-Image-2 / GPT-Image-1 / GPT-Image-1-Mini
638​
639```typescript
640import { generateImage } from "@tanstack/ai";
641import { openaiImage } from "@tanstack/ai-openai";
642​
643const result = await generateImage({
644 adapter: openaiImage("gpt-image-2"),
645 prompt: "A cat wearing a hat",
646 modelOptions: {
647 quality: "high", // 'high' | 'medium' | 'low' | 'auto'
648 background: "transparent", // 'transparent' | 'opaque' | 'auto'
649 output_format: "png", // 'png' | 'jpeg' | 'webp'
650 moderation: "low", // 'low' | 'auto'
651 },
652});
653```
654​
655`gpt-image-2.5-flare` and `gpt-image-2.5-sunburst` also take `quality: "xhigh"` and `quality: "max"`.
656​
657##### DALL-E 3
658​
659```typescript
660import { generateImage } from "@tanstack/ai";
661import { openaiImage } from "@tanstack/ai-openai";
662​
663const result = await generateImage({
664 adapter: openaiImage("dall-e-3"),
665 prompt: "A futuristic car",
666 modelOptions: {
667 quality: "hd", // 'hd' | 'standard'
668 style: "vivid", // 'vivid' | 'natural'
669 },
670});
671```
672​
673#### Gemini Imagen Model Options
674​
675```typescript ignore
676import { generateImage } from "@tanstack/ai";
677import { geminiImage } from "@tanstack/ai-gemini";
678​
679const result = await generateImage({
680 adapter: geminiImage("imagen-4.0-generate-001"),
681 prompt: "A beautiful garden",
682 modelOptions: {
683 aspectRatio: "16:9",
684 // personGeneration accepts PersonGeneration enum values: 'DONT_ALLOW' | 'ALLOW_ADULT' | 'ALLOW_ALL'
685 personGeneration: "ALLOW_ADULT",
686 negativePrompt: "blurry, low quality",
687 addWatermark: true,
688 outputMimeType: "image/png", // 'image/png' | 'image/jpeg' | 'image/webp'
689 },
690});
691```
692​
693#### Gemini Native Model Options (NanoBanana)
694​
695Set native image options on `modelOptions`:
696​
697```typescript
698import { generateImage } from "@tanstack/ai";
699import { geminiImage, ThinkingLevel } from "@tanstack/ai-gemini";
700​
701const result = await generateImage({
702 adapter: geminiImage("gemini-3.1-flash-image"),
703 prompt: "A beautiful garden",
704 size: "16:9_4K",
705 modelOptions: {
706 seed: 42,
707 thinkingConfig: { thinkingLevel: ThinkingLevel.LOW },
708 systemInstruction: "Always render in watercolor.",
709 // imageConfig replaces one field from size. The 16:9 ratio from size stays.
710 // imageConfig accepts only aspectRatio and imageSize.
711 imageConfig: { imageSize: "2K" },
712 },
713});
714```
715​
716Set `thinkingConfig.thinkingLevel` to one of these values:
717​
718- `ThinkingLevel.MINIMAL`
719- `ThinkingLevel.LOW`
720- `ThinkingLevel.MEDIUM`
721- `ThinkingLevel.HIGH`
722​
723`thinkingConfig.thinkingBudget` throws.
724​
725If `systemInstruction` contains an image, a file, or a tool call, the call throws.
726​
727Pass the last result `id` as `previous_interaction_id`. Read [Edit a Gemini native image](#edit-a-gemini-native-image) for the edit steps.
728​
729`safetySettings` takes the SDK's `HarmCategory` / `HarmBlockThreshold` enums, so plain strings won't type-check. Both are re-exported from `@tanstack/ai-gemini` — you don't need `@google/genai` in your own dependencies:
730​
731```typescript
732import { generateImage } from "@tanstack/ai";
733import {
734 HarmBlockThreshold,
735 HarmCategory,
736 geminiImage,
737} from "@tanstack/ai-gemini";
738​
739const result = await generateImage({
740 adapter: geminiImage("gemini-3.1-flash-image"),
741 prompt: "A beautiful garden",
742 modelOptions: {
743 safetySettings: [
744 {
745 category: HarmCategory.HARM_CATEGORY_HATE_SPEECH,
746 threshold: HarmBlockThreshold.BLOCK_ONLY_HIGH,
747 },
748 ],
749 },
750});
751```
752​
753The adapter always requests an image.
754​
755### Response Format
756​
757The image generation result includes:
758​
759```typescript
760import type { TokenUsage } from "@tanstack/ai";
761​
762interface ImageGenerationResult {
763 id: string; // Unique identifier for this generation
764 model: string; // The model used
765 images: GeneratedImage[]; // Array of generated images
766 // Canonical TokenUsage (same shape as chat). Token-billed models also surface
767 // a per-modality breakdown on `promptTokensDetails` (e.g. text vs image input
768 // tokens for gpt-image-1). Usage-billed providers (fal) instead surface
769 // `usage.billed` ({ quantity, unit }) — see the note below.
770 usage?: TokenUsage;
772​
773interface GeneratedImage {
774 b64Json?: string; // Base64 encoded image data
775 url?: string; // URL to the image (OpenAI only)
776 revisedPrompt?: string; // Revised prompt (OpenAI only)
778```
779​
780On a Gemini native image model, `id` is the interaction id. Pass that id as `previous_interaction_id` on the next edit.
781​
782> **Cost tracking (fal):** fal bills by usage-based units rather than tokens. The
783> fal image adapter surfaces the real billed quantity as `usage.billed` —
784> `{ quantity, unit: 'units' }`, read from fal's `x-fal-billable-units` result
785> header. Multiply the quantity by the endpoint's unit price from
786> `GET https://api.fal.ai/v1/models/pricing?endpoint_id=…` for the exact cost —
787> no `fetch` interceptor needed.
788​
789```typescript
790import { generateImage } from "@tanstack/ai";
791import { falImage } from "@tanstack/ai-fal";
792import { unitPrice } from "./pricing";
793​
794const result = await generateImage({
795 adapter: falImage("fal-ai/flux/dev"),
796 prompt: "a serene mountain lake",
797});
798​
799if (result.usage?.billed) {
800 const { quantity, unit } = result.usage.billed;
801 const cost = quantity * unitPrice; // unitPrice from fal pricing API
802 console.log(`Billed ${quantity} ${unit} (~$${cost})`);
804```
805​
806### Model Availability
807​
808#### OpenAI Models
809​
810| Model | Images per Request |
811| ------------------------ | ------------------ |
812| `gpt-image-2.5-flare` | 1-10 |
813| `gpt-image-2.5-sunburst` | 1-10 |
814| `gpt-image-2` | 1-10 |
815| `gpt-image-1` | 1-10 |
816| `gpt-image-1-mini` | 1-10 |
817| `dall-e-3` | 1 |
818| `dall-e-2` | 1-10 |
819​
820#### Gemini Native Models (NanoBanana)
821​
822| Model | Description |
823| ----------------------------- | -------------------------------------------------------------------------- |
824| `gemini-3.1-flash-image` | Nano Banana 2 — latest and fastest Gemini native image generation |
825| `gemini-3.1-flash-lite-image` | Nano Banana 2 Lite — ultra-low-latency, low-cost image generation |
826| `gemini-nano-banana-2.1` | Nano Banana 2.1 (1K/2K/4K, no 512 tier) |
827| `gemini-3-pro-image` | Nano Banana Pro — higher quality Gemini native image generation |
828| `gemini-2.5-flash-image` | Nano Banana — legacy; shuts down 2026-10-02 |
829​
830The `gemini-3.1-flash-image-preview` and `gemini-3-pro-image-preview` ids were shut down on 2026-06-25. They remain in the type union as deprecated aliases so existing code compiles, but calls to them fail — use the GA ids above.
831​
832#### Gemini Imagen Models
833​
834| Model | Images per Request |
835| ------------------------------- | ------------------ |
836| `imagen-4.0-ultra-generate-001` | 1-4 |
837| `imagen-4.0-generate-001` | 1-4 |
838| `imagen-4.0-fast-generate-001` | 1-4 |
839​
840### Error Handling
841​
842Image generation can fail for various reasons. The adapters validate inputs before making API calls:
843​
844```typescript ignore
845import { generateImage } from "@tanstack/ai";
846import { openaiImage } from "@tanstack/ai-openai";
847​
848try {
849 const result = await generateImage({
850 adapter: openaiImage("dall-e-3"),
851 prompt: "A cat",
852 size: "512x512", // Invalid size for DALL-E 3 — throws at runtime
853 });
854} catch (error) {
855 if (error instanceof Error) {
856 console.error(error.message);
857 // "Size "512x512" is not supported by model "dall-e-3".
858 // Supported sizes: 1024x1024, 1792x1024, 1024x1792"
859 }
861```
862​
863### Environment Variables
864​
865The image adapters use the same environment variables as the text adapters:
866​
867- **OpenAI**: `OPENAI_API_KEY`
868- **Gemini** (including NanoBanana): `GOOGLE_API_KEY` or `GEMINI_API_KEY`
869- **BytePlus** (Seedream): `ARK_API_KEY` or `BYTEPLUS_API_KEY`
870​
871### Explicit API Keys
872​
873For production use or when you need explicit control:
874​
875```typescript
876import { createOpenaiImage } from "@tanstack/ai-openai";
877import { createGeminiImage } from "@tanstack/ai-gemini";
878​
879// OpenAI
880const openaiAdapter = createOpenaiImage("dall-e-3", "your-openai-api-key");
881​
882// Gemini
883const geminiAdapter = createGeminiImage(
884 "imagen-4.0-generate-001",
885 "your-google-api-key",
886);
887```