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

image-generation.md

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