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

image.ts

549 lines19.0 KB

1import {
2 fileReferenceFor,
3 isFileSource,
4 resolveMediaPrompt,
5} from '@tanstack/ai'
6import { BaseImageAdapter } from '@tanstack/ai/adapters'
7import {
8 createGeminiClient,
9 generateId,
10 getGeminiApiKeyFromEnv,
11} from '../utils'
12import { buildGeminiUsage } from '../usage'
13import {
14 isGeminiNativeImageModel,
15 parseNativeImageSize,
16 sizeToAspectRatio,
17 validateImageSize,
18 validateNumberOfImages,
19 validatePrompt,
20} from '../image/image-provider-options'
21import type { GeminiImageModels } from '../model-meta'
22import type {
23 GeminiAnyImageProviderOptions,
24 GeminiImageModelInputModalitiesByName,
25 GeminiImageModelProviderOptionsByName,
26 GeminiImageModelSizeByName,
27 GeminiNativeImageProviderOptions,
28} from '../image/image-provider-options'
29import type {
30 GeneratedImage,
31 ImageGenerationOptions,
32 ImageGenerationResult,
33 ImagePart,
34 MediaInputMetadata,
35 ResolvedMediaPrompt,
36} from '@tanstack/ai'
37import type {
38 Content,
39 GenerateContentConfig,
40 GenerateContentResponse,
41 GenerateImagesConfig,
42 GenerateImagesResponse,
43 GoogleGenAI,
44 ImageConfig,
45 Part,
46} from '@google/genai'
47import type { GeminiClientConfig } from '../utils/client'
48​
49/**
50 * Configuration for Gemini image adapter
51 */
52export interface GeminiImageConfig extends GeminiClientConfig {}
53​
54/** Model type for Gemini Image */
55export type GeminiImageModel = GeminiImageModels
56​
57/**
58 * Gemini Image Generation Adapter
59 *
60 * Tree-shakeable adapter for Gemini image generation functionality.
61 * Supports Imagen 3/4 models (via generateImages API) and Gemini native
62 * image models like Nano Banana 2 (via generateContent API).
63 *
64 * Features:
65 * - Aspect ratio-based image sizing
66 * - Person generation controls
67 * - Safety filtering
68 * - Watermark options
69 * - Extended resolution tiers (Nano Banana 2)
70 */
71export class GeminiImageAdapter<
72 TModel extends GeminiImageModel,
73> extends BaseImageAdapter<
74 TModel,
75 GeminiAnyImageProviderOptions,
76 GeminiImageModelProviderOptionsByName,
77 GeminiImageModelSizeByName,
78 GeminiImageModelInputModalitiesByName
79> {
80 override readonly kind = 'image' as const
81 readonly name = 'gemini' as const
82 // Consumes Gemini Files API references (geminiFiles()) as fileData.fileUri.
83 override readonly supportsFileSources = true
84​
85 // Type-only property - never assigned at runtime
86 declare '~types': {
87 providerOptions: GeminiAnyImageProviderOptions
88 modelProviderOptionsByName: GeminiImageModelProviderOptionsByName
89 modelSizeByName: GeminiImageModelSizeByName
90 modelInputModalitiesByName: GeminiImageModelInputModalitiesByName
91 }
92​
93 private readonly client: GoogleGenAI
94​
95 constructor(config: GeminiImageConfig, model: TModel) {
96 super(model, config)
97 this.client = createGeminiClient(config)
98 }
99​
100 async generateImages(
101 options: ImageGenerationOptions<GeminiAnyImageProviderOptions>,
102 ): Promise<ImageGenerationResult> {
103 const { model, logger } = options
104​
105 logger.request(
106 `activity=generateImage provider=gemini model=${this.model}`,
107 {
108 provider: 'gemini',
109 model: this.model,
110 },
111 )
112​
113 try {
114 const resolved = resolveMediaPrompt(options.prompt)
115​
116 // Image-only prompts are allowed (the image inputs carry the intent);
117 // a prompt with neither text nor images is always an error.
118 if (resolved.images.length === 0) {
119 validatePrompt({ prompt: resolved.text, model })
120 }
121​
122 if (resolved.videos.length > 0) {
123 throw new Error(
124 `${this.name}.generateImages does not support video prompt parts (model: ${model}).`,
125 )
126 }
127 if (resolved.audios.length > 0) {
128 throw new Error(
129 `${this.name}.generateImages does not support audio prompt parts (model: ${model}).`,
130 )
131 }
132​
133 if (isGeminiNativeImageModel(model)) {
134 return await this.generateWithGeminiApi(options, resolved)
135 }
136​
137 // Imagen does not accept image inputs — it's strictly text-to-image.
138 if (resolved.images.length > 0) {
139 throw new Error(
140 `${this.name}: model "${model}" (Imagen) does not support image prompt parts. ` +
141 `Use a Gemini-native image model (e.g. gemini-2.5-flash-image, "nano-banana") for image-conditioned generation.`,
142 )
143 }
144​
145 // Imagen models path (generateImages API)
146 validateImageSize(model, options.size)
147 validateNumberOfImages(model, options.numberOfImages)
148​
149 const config = this.buildImagenConfig(options)
150​
151 const response = await this.client.models.generateImages({
152 model,
153 prompt: resolved.text,
154 config,
155 })
156​
157 return this.transformImagenResponse(model, response)
158 } catch (error) {
159 logger.errors('gemini.generateImage fatal', {
160 error,
161 source: 'gemini.generateImage',
162 })
163 throw error
164 }
165 }
166​
167 private async generateWithGeminiApi(
168 options: ImageGenerationOptions<GeminiNativeImageProviderOptions>,
169 resolved: ResolvedMediaPrompt,
170 ): Promise<ImageGenerationResult> {
171 const { model, size, numberOfImages, modelOptions } = options
172​
173 const parsedSize = size ? parseNativeImageSize(size) : undefined
174​
175 // The portable `size` option is the baseline; modelOptions.imageConfig is
176 // the provider escape hatch and wins per field, so a caller passing only
177 // `imageConfig.imageSize` keeps the aspectRatio derived from `size`.
178 const imageConfig: ImageConfig = {
179 ...(parsedSize?.aspectRatio && { aspectRatio: parsedSize.aspectRatio }),
180 ...(parsedSize?.resolution && { imageSize: parsedSize.resolution }),
181 ...modelOptions?.imageConfig,
182 }
183​
184 // Named picks, never a wholesale spread: the Imagen-shaped fields of
185 // GeminiImageProviderOptions (personGeneration, safetyFilterLevel,
186 // addWatermark, outputMimeType, …) are only valid on GenerateImagesConfig
187 // and would be rejected by generateContent. Picking by name means no
188 // Imagen field can reach this path even if one slips past the per-model
189 // provider-options map.
190 const nativeConfig: GenerateContentConfig = {
191 ...(modelOptions?.seed !== undefined && { seed: modelOptions.seed }),
192 ...(modelOptions?.safetySettings !== undefined && {
193 safetySettings: modelOptions.safetySettings,
194 }),
195 ...(modelOptions?.thinkingConfig !== undefined && {
196 thinkingConfig: modelOptions.thinkingConfig,
197 }),
198 ...(modelOptions?.systemInstruction !== undefined && {
199 systemInstruction: modelOptions.systemInstruction,
200 }),
201 }
202​
203 const config: GenerateContentConfig = {
204 ...nativeConfig,
205 // Include TEXT so the model can interleave descriptions between images.
206 // IMPORTANT: responseModalities is a protected default — set it AFTER
207 // nativeConfig so nothing can silently disable image output.
208 responseModalities: ['TEXT', 'IMAGE'],
209 ...(Object.keys(imageConfig).length > 0 && { imageConfig }),
210 }
211​
212 const contents = this.buildContents(resolved, numberOfImages)
213​
214 const response = await this.client.models.generateContent({
215 model,
216 contents,
217 config,
218 })
219​
220 return this.transformGeminiResponse(model, response)
221 }
222​
223 /**
224 * Build the multimodal `contents` payload. Text-only prompts pass through
225 * as a plain string (the SDK accepts it directly); prompts with image
226 * parts become a single user `Content` whose `parts` mirror the prompt's
227 * interleaved order — position is meaningful to Gemini ("not like this
228 * *(image)*, more like this *(image)*").
229 *
230 * The generateContent API has no numberOfImages parameter, so when more
231 * than one image is requested a trailing instruction is appended.
232 */
233 private buildContents(
234 resolved: ResolvedMediaPrompt,
235 numberOfImages: number | undefined,
236 ): string | Array<Content> {
237 const countInstruction =
238 numberOfImages && numberOfImages > 1
239 ? `Generate ${numberOfImages} distinct images.`
240 : undefined
241​
242 if (resolved.images.length === 0) {
243 return countInstruction
244 ? `${resolved.text} ${countInstruction}`
245 : resolved.text
246 }
247​
248 const parts: Array<Part> = resolved.parts.map((part) => {
249 if (part.type === 'text') {
250 return { text: part.content }
251 }
252 if (part.type === 'image') {
253 return this.imagePartToGeminiPart(part)
254 }
255 // Video / audio parts were rejected in generateImages above.
256 throw new Error(
257 `gemini: unsupported prompt part type "${part.type}" in image generation.`,
258 )
259 })
260 if (countInstruction) {
261 parts.push({ text: countInstruction })
262 }
263 return [{ role: 'user', parts }]
264 }
265​
266 private imagePartToGeminiPart(part: ImagePart<MediaInputMetadata>): Part {
267 if (part.source.type === 'data') {
268 return {
269 inlineData: {
270 mimeType: part.source.mimeType || 'image/png',
271 data: part.source.value,
272 },
273 }
274 }
275 // URL sources (public HTTPS, Files API URIs, gs://) pass through as
276 // `fileData` and Gemini fetches them server-side — same as the chat
277 // adapter. Fetching locally and inlining as base64 double-buffers the
278 // image and OOMs on memory-constrained runtimes (e.g. Cloudflare
279 // Workers). A file source's handle is the file URI (throws when another
280 // provider issued it).
281 const fileUri = isFileSource(part.source)
282 ? fileReferenceFor(part.source, this.name)
283 : part.source.value
284 return {
285 fileData: {
286 fileUri,
287 mimeType: part.source.mimeType ?? 'image/jpeg',
288 },
289 }
290 }
291​
292 private transformGeminiResponse(
293 model: string,
294 response: GenerateContentResponse,
295 ): ImageGenerationResult {
296 const images: Array<GeneratedImage> = []
297 const textParts: Array<string> = []
298 const parts = response.candidates?.[0]?.content?.parts ?? []
299​
300 for (const part of parts) {
301 if (
302 part.inlineData?.data &&
303 typeof part.inlineData.data === 'string' &&
304 part.inlineData.data.length > 0
305 ) {
306 images.push({ b64Json: part.inlineData.data })
307 } else if (typeof part.text === 'string' && part.text.length > 0) {
308 textParts.push(part.text)
309 }
310 }
311​
312 // If the model returned only text parts (for example a safety refusal
313 // or a "can't do that" message), surface the text instead of silently
314 // resolving to an empty images array — otherwise callers can't tell a
315 // generation failure apart from a genuine empty response.
316 if (images.length === 0) {
317 const reason =
318 textParts.length > 0
319 ? `: ${textParts.join(' ').trim()}`
320 : ' (no inline image or text parts were returned).'
321 throw new Error(`Gemini ${model} returned no images${reason}`)
322 }
323​
324 return {
325 id: generateId(this.name),
326 model,
327 images,
328 // Surface token usage (with per-modality breakdown) when the model
329 // reports it (e.g. Nano Banana via generateContent). Conditionally spread
330 // to satisfy exactOptionalPropertyTypes — only include usage when
331 // present. See #330.
332 ...(response.usageMetadata
333 ? { usage: buildGeminiUsage(response.usageMetadata) }
334 : {}),
335 }
336 }
337​
338 private buildImagenConfig(
339 options: ImageGenerationOptions<GeminiAnyImageProviderOptions>,
340 ): GenerateImagesConfig {
341 const { size, numberOfImages, modelOptions } = options
342​
343 // Build with conditional spreads — under exactOptionalPropertyTypes the
344 // vendor `GenerateImagesConfig` fields are `field?: T` (no `| undefined`),
345 // so we can only assign the property when we actually have a value.
346 const sizeAspectRatio = size ? sizeToAspectRatio(size) : undefined
347​
348 // Named picks, never a wholesale spread — the mirror image of the native
349 // path below. A native-only field (safetySettings, thinkingConfig,
350 // imageConfig, systemInstruction) belongs to GenerateContentConfig and is
351 // rejected by generateImages with 400 INVALID_ARGUMENT, so it must not be
352 // able to reach here even when the caller's `modelOptions` was typed
353 // against both shapes at once (e.g. an adapter inferred from a union of
354 // model names).
355 return {
356 numberOfImages: numberOfImages ?? 1,
357 // Map size to aspect ratio if provided; modelOptions.aspectRatio,
358 // picked after it, overrides.
359 ...(sizeAspectRatio !== undefined && { aspectRatio: sizeAspectRatio }),
360 ...(modelOptions?.aspectRatio !== undefined && {
361 aspectRatio: modelOptions.aspectRatio,
362 }),
363 ...(modelOptions?.personGeneration !== undefined && {
364 personGeneration: modelOptions.personGeneration,
365 }),
366 ...(modelOptions?.safetyFilterLevel !== undefined && {
367 safetyFilterLevel: modelOptions.safetyFilterLevel,
368 }),
369 ...(modelOptions?.seed !== undefined && { seed: modelOptions.seed }),
370 ...(modelOptions?.addWatermark !== undefined && {
371 addWatermark: modelOptions.addWatermark,
372 }),
373 ...(modelOptions?.language !== undefined && {
374 language: modelOptions.language,
375 }),
376 ...(modelOptions?.negativePrompt !== undefined && {
377 negativePrompt: modelOptions.negativePrompt,
378 }),
379 ...(modelOptions?.outputMimeType !== undefined && {
380 outputMimeType: modelOptions.outputMimeType,
381 }),
382 ...(modelOptions?.outputCompressionQuality !== undefined && {
383 outputCompressionQuality: modelOptions.outputCompressionQuality,
384 }),
385 ...(modelOptions?.guidanceScale !== undefined && {
386 guidanceScale: modelOptions.guidanceScale,
387 }),
388 ...(modelOptions?.enhancePrompt !== undefined && {
389 enhancePrompt: modelOptions.enhancePrompt,
390 }),
391 ...(modelOptions?.includeSafetyAttributes !== undefined && {
392 includeSafetyAttributes: modelOptions.includeSafetyAttributes,
393 }),
394 ...(modelOptions?.includeRaiReason !== undefined && {
395 includeRaiReason: modelOptions.includeRaiReason,
396 }),
397 ...(modelOptions?.outputGcsUri !== undefined && {
398 outputGcsUri: modelOptions.outputGcsUri,
399 }),
400 ...(modelOptions?.labels !== undefined && {
401 labels: modelOptions.labels,
402 }),
403 }
404 }
405​
406 private transformImagenResponse(
407 model: string,
408 response: GenerateImagesResponse,
409 ): ImageGenerationResult {
410 const entries = response.generatedImages ?? []
411 const images: Array<GeneratedImage> = []
412 const filterReasons: Array<string> = []
413​
414 for (const item of entries) {
415 const b64Json = item.image?.imageBytes
416 if (b64Json) {
417 images.push({
418 b64Json,
419 ...(item.enhancedPrompt !== undefined && {
420 revisedPrompt: item.enhancedPrompt,
421 }),
422 })
423 continue
424 }
425 // Imagen can drop individual entries with a raiFilteredReason when
426 // Responsible-AI filters fire. Preserve the reason so callers can
427 // surface it instead of silently getting back fewer images.
428 const reason = (item as { raiFilteredReason?: string }).raiFilteredReason
429 if (reason) {
430 filterReasons.push(reason)
431 }
432 }
433​
434 // Every entry was filtered — no usable images to return. Throw rather
435 // than resolve to an empty array so the caller is forced to handle the
436 // failure mode explicitly.
437 if (entries.length > 0 && images.length === 0) {
438 const joined = filterReasons.length > 0 ? filterReasons.join('; ') : ''
439 throw new Error(
440 `Imagen ${model} returned no images: all ${entries.length} generated image(s) were filtered by Responsible-AI${joined ? ` (${joined})` : ''}.`,
441 )
442 }
443​
444 // Partial filter: surface via console.warn since ImageGenerationResult
445 // has no warnings field. Callers that care can still inspect the count
446 // mismatch between requested and returned images.
447 if (filterReasons.length > 0 && typeof console !== 'undefined') {
448 console.warn(
449 `[gemini-image] ${filterReasons.length} of ${entries.length} images from ${model} were filtered by Responsible-AI: ${filterReasons.join('; ')}`,
450 )
451 }
452​
453 return {
454 id: generateId(this.name),
455 model,
456 images,
457 }
458 }
460​
461/** @deprecated Shut down 2026-06-25. Use `gemini-3.1-flash-image`. */
462export function createGeminiImage(
463 model: 'gemini-3.1-flash-image-preview',
464 apiKey: string,
465 config?: Omit<GeminiImageConfig, 'apiKey'>,
466): GeminiImageAdapter<'gemini-3.1-flash-image-preview'>
467/** @deprecated Shut down 2026-06-25. Use `gemini-3-pro-image`. */
468export function createGeminiImage(
469 model: 'gemini-3-pro-image-preview',
470 apiKey: string,
471 config?: Omit<GeminiImageConfig, 'apiKey'>,
472): GeminiImageAdapter<'gemini-3-pro-image-preview'>
473/**
474 * Creates a Gemini image adapter with explicit API key.
475 * Type resolution happens here at the call site.
476 *
477 * @param model - The model name (e.g., 'imagen-4.0-generate-001')
478 * @param apiKey - Your Google API key
479 * @param config - Optional additional configuration
480 * @returns Configured Gemini image adapter instance with resolved types
481 *
482 * @example
483 * ```typescript
484 * const adapter = createGeminiImage('imagen-4.0-generate-001', "your-api-key");
485 *
486 * const result = await generateImage({
487 * adapter,
488 * prompt: 'A cute baby sea otter'
489 * });
490 * ```
491 */
492export function createGeminiImage<TModel extends GeminiImageModel>(
493 model: TModel,
494 apiKey: string,
495 config?: Omit<GeminiImageConfig, 'apiKey'>,
496): GeminiImageAdapter<TModel>
497export function createGeminiImage<TModel extends GeminiImageModel>(
498 model: TModel,
499 apiKey: string,
500 config?: Omit<GeminiImageConfig, 'apiKey'>,
501): GeminiImageAdapter<TModel> {
502 return new GeminiImageAdapter({ apiKey, ...config }, model)
504​
505/** @deprecated Shut down 2026-06-25. Use `gemini-3.1-flash-image`. */
506export function geminiImage(
507 model: 'gemini-3.1-flash-image-preview',
508 config?: Omit<GeminiImageConfig, 'apiKey'>,
509): GeminiImageAdapter<'gemini-3.1-flash-image-preview'>
510/** @deprecated Shut down 2026-06-25. Use `gemini-3-pro-image`. */
511export function geminiImage(
512 model: 'gemini-3-pro-image-preview',
513 config?: Omit<GeminiImageConfig, 'apiKey'>,
514): GeminiImageAdapter<'gemini-3-pro-image-preview'>
515/**
516 * Creates a Gemini image adapter with automatic API key detection from environment variables.
517 * Type resolution happens here at the call site.
518 *
519 * Looks for `GOOGLE_API_KEY` or `GEMINI_API_KEY` in:
520 * - `process.env` (Node.js)
521 * - `window.env` (Browser with injected env)
522 *
523 * @param model - The model name (e.g., 'imagen-4.0-generate-001')
524 * @param config - Optional configuration (excluding apiKey which is auto-detected)
525 * @returns Configured Gemini image adapter instance with resolved types
526 * @throws Error if GOOGLE_API_KEY or GEMINI_API_KEY is not found in environment
527 *
528 * @example
529 * ```typescript
530 * // Automatically uses GOOGLE_API_KEY from environment
531 * const adapter = geminiImage('imagen-4.0-generate-001');
532 *
533 * const result = await generateImage({
534 * adapter,
535 * prompt: 'A beautiful sunset over mountains'
536 * });
537 * ```
538 */
539export function geminiImage<TModel extends GeminiImageModel>(
540 model: TModel,
541 config?: Omit<GeminiImageConfig, 'apiKey'>,
542): GeminiImageAdapter<TModel>
543export function geminiImage<TModel extends GeminiImageModel>(
544 model: TModel,
545 config?: Omit<GeminiImageConfig, 'apiKey'>,
546): GeminiImageAdapter<TModel> {
547 const apiKey = getGeminiApiKeyFromEnv()
548 return createGeminiImage(model, apiKey, config)