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

image.ts

695 lines22.2 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 { flattenModalityTokenCounts, hasModalityTokens } 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 TokenUsage,
37} from '@tanstack/ai'
38import { ThinkingLevel } from '@google/genai'
39import type {
40 Content,
41 ContentUnion,
42 GenerateImagesConfig,
43 GenerateImagesResponse,
44 GoogleGenAI,
45 Interactions,
46 Part,
47 SafetySetting,
48 ThinkingConfig,
49} from '@google/genai'
50import type { GeminiClientConfig } from '../utils/client'
51​
52/**
53 * Configuration for Gemini image adapter
54 */
55export interface GeminiImageConfig extends GeminiClientConfig {}
56​
57/** Model type for Gemini Image */
58export type GeminiImageModel = GeminiImageModels
59​
60/**
61 * Gemini Image Generation Adapter
62 *
63 * Tree-shakeable adapter for Gemini image generation functionality.
64 * Supports Imagen 3/4 models (via generateImages API) and Gemini native
65 * image models like Nano Banana 2 (via the Interactions API).
66 *
67 * Features:
68 * - Aspect ratio-based image sizing
69 * - Person generation controls
70 * - Safety filtering
71 * - Watermark options
72 * - Extended resolution tiers (Nano Banana 2)
73 */
74export class GeminiImageAdapter<
75 TModel extends GeminiImageModel,
76> extends BaseImageAdapter<
77 TModel,
78 GeminiAnyImageProviderOptions,
79 GeminiImageModelProviderOptionsByName,
80 GeminiImageModelSizeByName,
81 GeminiImageModelInputModalitiesByName
82> {
83 override readonly kind = 'image' as const
84 readonly name = 'gemini' as const
85 // Consumes Gemini Files API references (geminiFiles()) as interaction image URIs.
86 override readonly supportsFileSources = true
87​
88 // Type-only property - never assigned at runtime
89 declare '~types': {
90 providerOptions: GeminiAnyImageProviderOptions
91 modelProviderOptionsByName: GeminiImageModelProviderOptionsByName
92 modelSizeByName: GeminiImageModelSizeByName
93 modelInputModalitiesByName: GeminiImageModelInputModalitiesByName
94 }
95​
96 private readonly client: GoogleGenAI
97​
98 constructor(config: GeminiImageConfig, model: TModel) {
99 super(model, config)
100 this.client = createGeminiClient(config)
101 }
102​
103 async generateImages(
104 options: ImageGenerationOptions<GeminiAnyImageProviderOptions>,
105 ): Promise<ImageGenerationResult> {
106 const { model, logger } = options
107​
108 logger.request(
109 `activity=generateImage provider=gemini model=${this.model}`,
110 {
111 provider: 'gemini',
112 model: this.model,
113 },
114 )
115​
116 try {
117 const resolved = resolveMediaPrompt(options.prompt)
118​
119 // Image-only prompts are allowed (the image inputs carry the intent);
120 // a prompt with neither text nor images is always an error.
121 if (resolved.images.length === 0) {
122 validatePrompt({ prompt: resolved.text, model })
123 }
124​
125 if (resolved.videos.length > 0) {
126 throw new Error(
127 `${this.name}.generateImages does not support video prompt parts (model: ${model}).`,
128 )
129 }
130 if (resolved.audios.length > 0) {
131 throw new Error(
132 `${this.name}.generateImages does not support audio prompt parts (model: ${model}).`,
133 )
134 }
135​
136 if (isGeminiNativeImageModel(model)) {
137 return await this.generateWithGeminiApi(options, resolved)
138 }
139​
140 // Imagen does not accept image inputs — it's strictly text-to-image.
141 if (resolved.images.length > 0) {
142 throw new Error(
143 `${this.name}: model "${model}" (Imagen) does not support image prompt parts. ` +
144 `Use a Gemini-native image model (e.g. gemini-3.1-flash-image) for image-conditioned generation.`,
145 )
146 }
147​
148 if (options.modelOptions?.previous_interaction_id) {
149 throw new Error(
150 `${this.name}: previous_interaction_id is only supported on Gemini-native image models.`,
151 )
152 }
153​
154 // Imagen models path (generateImages API)
155 validateImageSize(model, options.size)
156 validateNumberOfImages(model, options.numberOfImages)
157​
158 const config = this.buildImagenConfig(options)
159​
160 const response = await this.client.models.generateImages({
161 model,
162 prompt: resolved.text,
163 config,
164 })
165​
166 return this.transformImagenResponse(model, response)
167 } catch (error) {
168 logger.errors('gemini.generateImage fatal', {
169 error,
170 source: 'gemini.generateImage',
171 })
172 throw error
173 }
174 }
175​
176 private async generateWithGeminiApi(
177 options: ImageGenerationOptions<GeminiNativeImageProviderOptions>,
178 resolved: ResolvedMediaPrompt,
179 ): Promise<ImageGenerationResult> {
180 const { model, size, numberOfImages, modelOptions } = options
181​
182 const parsedSize = size ? parseNativeImageSize(size) : undefined
183 // Named picks, never a wholesale spread of imageConfig. The portable
184 // `size` is the baseline; modelOptions.imageConfig wins per field.
185 const aspectRatio =
186 modelOptions?.imageConfig?.aspectRatio ?? parsedSize?.aspectRatio
187 const imageSize = interactionImageSize(
188 modelOptions?.imageConfig?.imageSize ?? parsedSize?.resolution,
189 )
190​
191 const thinking = modelOptions?.thinkingConfig
192 if (thinking?.thinkingBudget !== undefined) {
193 throw new Error(
194 `${this.name}: thinkingConfig.thinkingBudget is not supported on the Interactions image API. Set thinkingConfig.thinkingLevel ('minimal' | 'low' | 'medium' | 'high') instead.`,
195 )
196 }
197​
198 const generationConfig: Interactions.GenerationConfig = {
199 ...(modelOptions?.seed !== undefined && { seed: modelOptions.seed }),
200 ...interactionThinking(thinking),
201 }
202​
203 // safety_settings is not on the SDK param type. Assign it after the
204 // object is built so the JSON body still carries it.
205 const request = {
206 model,
207 input: this.buildInteractionInput(resolved, numberOfImages),
208 stream: false as const,
209 response_format: {
210 type: 'image' as const,
211 ...(aspectRatio !== undefined && { aspect_ratio: aspectRatio }),
212 ...(imageSize !== undefined && { image_size: imageSize }),
213 },
214 ...(modelOptions?.systemInstruction !== undefined && {
215 system_instruction: systemInstructionText(
216 modelOptions.systemInstruction,
217 ),
218 }),
219 ...(Object.keys(generationConfig).length > 0 && {
220 generation_config: generationConfig,
221 }),
222 ...(modelOptions?.previous_interaction_id && {
223 previous_interaction_id: modelOptions.previous_interaction_id,
224 }),
225 ...(modelOptions?.store !== undefined && { store: modelOptions.store }),
226 }
227 if (
228 modelOptions?.safetySettings !== undefined &&
229 modelOptions.safetySettings.length > 0
230 ) {
231 Object.assign(request, {
232 safety_settings: modelOptions.safetySettings.map(interactionSafety),
233 })
234 }
235​
236 const interaction = options.abortSignal
237 ? await this.client.interactions.create(request, {
238 signal: options.abortSignal,
239 })
240 : await this.client.interactions.create(request)
241​
242 return this.transformInteractionResponse(model, interaction)
243 }
244​
245 /**
246 * Text-only prompts pass through as a string. Prompts with image parts
247 * become content blocks in prompt order. The Interactions API has no
248 * image count, so more than one image appends an instruction.
249 */
250 private buildInteractionInput(
251 resolved: ResolvedMediaPrompt,
252 numberOfImages: number | undefined,
253 ): string | Array<Interactions.Content> {
254 const countInstruction =
255 numberOfImages && numberOfImages > 1
256 ? `Generate ${numberOfImages} distinct images.`
257 : undefined
258​
259 if (resolved.images.length === 0) {
260 return countInstruction
261 ? `${resolved.text} ${countInstruction}`
262 : resolved.text
263 }
264​
265 const blocks: Array<Interactions.Content> = resolved.parts.map((part) => {
266 if (part.type === 'text') {
267 return { type: 'text', text: part.content }
268 }
269 if (part.type === 'image') {
270 return this.imagePartToInteraction(part)
271 }
272 throw new Error(
273 `gemini: unsupported prompt part type "${part.type}" in image generation.`,
274 )
275 })
276 if (countInstruction) {
277 blocks.push({ type: 'text', text: countInstruction })
278 }
279 return blocks
280 }
281​
282 private imagePartToInteraction(
283 part: ImagePart<MediaInputMetadata>,
284 ): Interactions.ImageContent {
285 if (part.source.type === 'data') {
286 return {
287 type: 'image',
288 data: part.source.value,
289 mime_type: part.source.mimeType || 'image/png',
290 }
291 }
292 // URL and Files API sources pass through as `uri`. Gemini fetches them.
293 // Fetching locally and inlining as base64 OOMs on constrained runtimes.
294 const uri = isFileSource(part.source)
295 ? fileReferenceFor(part.source, this.name)
296 : part.source.value
297 return {
298 type: 'image',
299 uri,
300 mime_type: part.source.mimeType ?? 'image/jpeg',
301 }
302 }
303​
304 private transformInteractionResponse(
305 model: string,
306 interaction: Interactions.Interaction,
307 ): ImageGenerationResult {
308 if (interaction.status !== 'completed') {
309 throw new Error(
310 `Gemini ${model} image interaction ended with status "${interaction.status}".`,
311 )
312 }
313 if (!interaction.id) {
314 throw new Error(`Gemini ${model} image interaction returned no id.`)
315 }
316​
317 const images: Array<GeneratedImage> = []
318 const textParts: Array<string> = []
319 for (const step of interaction.steps ?? []) {
320 if (step.type !== 'model_output') continue
321 for (const block of step.content ?? []) {
322 if (block.type === 'image') {
323 const image = generatedImageFromBlock(block)
324 if (image) images.push(image)
325 } else if (block.type === 'text' && block.text.length > 0) {
326 textParts.push(block.text)
327 }
328 }
329 }
330 if (images.length === 0 && interaction.output_image) {
331 const image = generatedImageFromBlock(interaction.output_image)
332 if (image) images.push(image)
333 }
334​
335 if (images.length === 0) {
336 if (textParts.length === 0 && interaction.output_text) {
337 textParts.push(interaction.output_text)
338 }
339 const reason =
340 textParts.length > 0
341 ? `: ${textParts.join(' ').trim()}`
342 : ' (no image was returned).'
343 throw new Error(`Gemini ${model} returned no images${reason}`)
344 }
345​
346 const usage = interactionImageUsage(interaction.usage)
347 return {
348 id: interaction.id,
349 model,
350 images,
351 ...(usage ? { usage } : {}),
352 }
353 }
354​
355 private buildImagenConfig(
356 options: ImageGenerationOptions<GeminiAnyImageProviderOptions>,
357 ): GenerateImagesConfig {
358 const { size, numberOfImages, modelOptions } = options
359​
360 // Build with conditional spreads — under exactOptionalPropertyTypes the
361 // vendor `GenerateImagesConfig` fields are `field?: T` (no `| undefined`),
362 // so we can only assign the property when we actually have a value.
363 const sizeAspectRatio = size ? sizeToAspectRatio(size) : undefined
364​
365 // Named picks, never a wholesale spread — the mirror image of the native
366 // path below. A native-only field (safetySettings, thinkingConfig,
367 // imageConfig, systemInstruction) belongs to GenerateContentConfig and is
368 // rejected by generateImages with 400 INVALID_ARGUMENT, so it must not be
369 // able to reach here even when the caller's `modelOptions` was typed
370 // against both shapes at once (e.g. an adapter inferred from a union of
371 // model names).
372 return {
373 numberOfImages: numberOfImages ?? 1,
374 // Map size to aspect ratio if provided; modelOptions.aspectRatio,
375 // picked after it, overrides.
376 ...(sizeAspectRatio !== undefined && { aspectRatio: sizeAspectRatio }),
377 ...(modelOptions?.aspectRatio !== undefined && {
378 aspectRatio: modelOptions.aspectRatio,
379 }),
380 ...(modelOptions?.personGeneration !== undefined && {
381 personGeneration: modelOptions.personGeneration,
382 }),
383 ...(modelOptions?.safetyFilterLevel !== undefined && {
384 safetyFilterLevel: modelOptions.safetyFilterLevel,
385 }),
386 ...(modelOptions?.seed !== undefined && { seed: modelOptions.seed }),
387 ...(modelOptions?.addWatermark !== undefined && {
388 addWatermark: modelOptions.addWatermark,
389 }),
390 ...(modelOptions?.language !== undefined && {
391 language: modelOptions.language,
392 }),
393 ...(modelOptions?.negativePrompt !== undefined && {
394 negativePrompt: modelOptions.negativePrompt,
395 }),
396 ...(modelOptions?.outputMimeType !== undefined && {
397 outputMimeType: modelOptions.outputMimeType,
398 }),
399 ...(modelOptions?.outputCompressionQuality !== undefined && {
400 outputCompressionQuality: modelOptions.outputCompressionQuality,
401 }),
402 ...(modelOptions?.guidanceScale !== undefined && {
403 guidanceScale: modelOptions.guidanceScale,
404 }),
405 ...(modelOptions?.enhancePrompt !== undefined && {
406 enhancePrompt: modelOptions.enhancePrompt,
407 }),
408 ...(modelOptions?.includeSafetyAttributes !== undefined && {
409 includeSafetyAttributes: modelOptions.includeSafetyAttributes,
410 }),
411 ...(modelOptions?.includeRaiReason !== undefined && {
412 includeRaiReason: modelOptions.includeRaiReason,
413 }),
414 ...(modelOptions?.outputGcsUri !== undefined && {
415 outputGcsUri: modelOptions.outputGcsUri,
416 }),
417 ...(modelOptions?.labels !== undefined && {
418 labels: modelOptions.labels,
419 }),
420 }
421 }
422​
423 private transformImagenResponse(
424 model: string,
425 response: GenerateImagesResponse,
426 ): ImageGenerationResult {
427 const entries = response.generatedImages ?? []
428 const images: Array<GeneratedImage> = []
429 const filterReasons: Array<string> = []
430​
431 for (const item of entries) {
432 const b64Json = item.image?.imageBytes
433 if (b64Json) {
434 images.push({
435 b64Json,
436 ...(item.enhancedPrompt !== undefined && {
437 revisedPrompt: item.enhancedPrompt,
438 }),
439 })
440 continue
441 }
442 // Imagen can drop individual entries with a raiFilteredReason when
443 // Responsible-AI filters fire. Preserve the reason so callers can
444 // surface it instead of silently getting back fewer images.
445 const reason = (item as { raiFilteredReason?: string }).raiFilteredReason
446 if (reason) {
447 filterReasons.push(reason)
448 }
449 }
450​
451 // Every entry was filtered — no usable images to return. Throw rather
452 // than resolve to an empty array so the caller is forced to handle the
453 // failure mode explicitly.
454 if (entries.length > 0 && images.length === 0) {
455 const joined = filterReasons.length > 0 ? filterReasons.join('; ') : ''
456 throw new Error(
457 `Imagen ${model} returned no images: all ${entries.length} generated image(s) were filtered by Responsible-AI${joined ? ` (${joined})` : ''}.`,
458 )
459 }
460​
461 // Partial filter: surface via console.warn since ImageGenerationResult
462 // has no warnings field. Callers that care can still inspect the count
463 // mismatch between requested and returned images.
464 if (filterReasons.length > 0 && typeof console !== 'undefined') {
465 console.warn(
466 `[gemini-image] ${filterReasons.length} of ${entries.length} images from ${model} were filtered by Responsible-AI: ${filterReasons.join('; ')}`,
467 )
468 }
469​
470 return {
471 id: generateId(this.name),
472 model,
473 images,
474 }
475 }
477​
478/**
479 * Creates a Gemini image adapter with explicit API key.
480 * Type resolution happens here at the call site.
481 *
482 * @param model - The model name (e.g., 'imagen-4.0-generate-001')
483 * @param apiKey - Your Google API key
484 * @param config - Optional additional configuration
485 * @returns Configured Gemini image adapter instance with resolved types
486 *
487 * @example
488 * ```typescript
489 * const adapter = createGeminiImage('imagen-4.0-generate-001', "your-api-key");
490 *
491 * const result = await generateImage({
492 * adapter,
493 * prompt: 'A cute baby sea otter'
494 * });
495 * ```
496 */
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/**
506 * Creates a Gemini image adapter with automatic API key detection from environment variables.
507 * Type resolution happens here at the call site.
508 *
509 * Looks for `GOOGLE_API_KEY` or `GEMINI_API_KEY` in:
510 * - `process.env` (Node.js)
511 * - `window.env` (Browser with injected env)
512 *
513 * @param model - The model name (e.g., 'imagen-4.0-generate-001')
514 * @param config - Optional configuration (excluding apiKey which is auto-detected)
515 * @returns Configured Gemini image adapter instance with resolved types
516 * @throws Error if GOOGLE_API_KEY or GEMINI_API_KEY is not found in environment
517 *
518 * @example
519 * ```typescript
520 * // Automatically uses GOOGLE_API_KEY from environment
521 * const adapter = geminiImage('imagen-4.0-generate-001');
522 *
523 * const result = await generateImage({
524 * adapter,
525 * prompt: 'A beautiful sunset over mountains'
526 * });
527 * ```
528 */
529export function geminiImage<TModel extends GeminiImageModel>(
530 model: TModel,
531 config?: Omit<GeminiImageConfig, 'apiKey'>,
532): GeminiImageAdapter<TModel> {
533 const apiKey = getGeminiApiKeyFromEnv()
534 return createGeminiImage(model, apiKey, config)
536​
537function interactionThinking(
538 thinking: ThinkingConfig | undefined,
539): Pick<
540 Interactions.GenerationConfig,
541 'thinking_level' | 'thinking_summaries'
542> {
543 if (!thinking) return {}
544 const level = interactionThinkingLevel(thinking.thinkingLevel)
545 return {
546 ...(level !== undefined && { thinking_level: level }),
547 ...(thinking.includeThoughts !== undefined && {
548 thinking_summaries: thinking.includeThoughts ? 'auto' : 'none',
549 }),
550 }
552​
553function interactionImageSize(
554 value: string | undefined,
555): '512' | '1K' | '2K' | '4K' | undefined {
556 if (value === '512' || value === '1K' || value === '2K' || value === '4K') {
557 return value
558 }
559 return undefined
561​
562function interactionThinkingLevel(
563 level: ThinkingConfig['thinkingLevel'],
564): 'minimal' | 'low' | 'medium' | 'high' | undefined {
565 switch (level) {
566 case ThinkingLevel.MINIMAL:
567 return 'minimal'
568 case ThinkingLevel.LOW:
569 return 'low'
570 case ThinkingLevel.MEDIUM:
571 return 'medium'
572 case ThinkingLevel.HIGH:
573 return 'high'
574 case ThinkingLevel.THINKING_LEVEL_UNSPECIFIED:
575 case undefined:
576 return undefined
577 }
579​
580function interactionSafety(setting: SafetySetting): {
581 type: string
582 threshold: string
583} {
584 const category = setting.category
585 const threshold = setting.threshold
586 if (!category || category === 'HARM_CATEGORY_UNSPECIFIED') {
587 throw new Error(
588 'gemini: safetySettings.category is required on the Interactions image API.',
589 )
590 }
591 if (!threshold || threshold === 'HARM_BLOCK_THRESHOLD_UNSPECIFIED') {
592 throw new Error(
593 'gemini: safetySettings.threshold is required on the Interactions image API.',
594 )
595 }
596 return {
597 type: category.replace(/^HARM_CATEGORY_/, '').toLowerCase(),
598 threshold: threshold.toLowerCase(),
599 }
601​
602function systemInstructionText(instruction: ContentUnion): string {
603 if (typeof instruction === 'string') return instruction
604 if (Array.isArray(instruction)) {
605 return instruction.map(partUnionText).join('')
606 }
607 if (isPart(instruction)) return partUnionText(instruction)
608 const parts = instruction.parts
609 if (!parts || parts.length === 0) {
610 throw new Error(
611 'gemini: systemInstruction on the Interactions image API must be text.',
612 )
613 }
614 return parts.map(partUnionText).join('')
616​
617function isPart(value: Content | Part): value is Part {
618 return !('parts' in value)
620​
621function partUnionText(part: Part | string): string {
622 if (typeof part === 'string') return part
623 if (
624 part.inlineData ||
625 part.fileData ||
626 part.functionCall ||
627 part.functionResponse
628 ) {
629 throw new Error(
630 'gemini: systemInstruction on the Interactions image API must be text. Inline media is not supported.',
631 )
632 }
633 if (typeof part.text !== 'string') {
634 throw new Error(
635 'gemini: systemInstruction on the Interactions image API must be text.',
636 )
637 }
638 return part.text
640​
641function generatedImageFromBlock(block: {
642 data?: string
643 uri?: string
644}): GeneratedImage | undefined {
645 if (typeof block.data === 'string' && block.data.length > 0) {
646 return { b64Json: block.data }
647 }
648 if (typeof block.uri === 'string' && block.uri.length > 0) {
649 return { url: block.uri }
650 }
651 return undefined
653​
654function interactionImageUsage(
655 usage: Interactions.Interaction['usage'],
656): TokenUsage | undefined {
657 if (!usage) return undefined
658 const promptTokens = usage.total_input_tokens ?? 0
659 const completionTokens = usage.total_output_tokens ?? 0
660 const promptModalities = flattenModalityTokenCounts(
661 usage.input_tokens_by_modality?.map((item) => ({
662 modality: item.modality,
663 tokenCount: item.tokens,
664 })),
665 )
666 const completionModalities = flattenModalityTokenCounts(
667 usage.output_tokens_by_modality?.map((item) => ({
668 modality: item.modality,
669 tokenCount: item.tokens,
670 })),
671 )
672 const promptTokensDetails = {
673 ...(hasModalityTokens(promptModalities) ? promptModalities : {}),
674 ...(usage.total_cached_tokens
675 ? { cachedTokens: usage.total_cached_tokens }
676 : {}),
677 }
678 const completionTokensDetails = {
679 ...(hasModalityTokens(completionModalities) ? completionModalities : {}),
680 ...(usage.total_thought_tokens
681 ? { reasoningTokens: usage.total_thought_tokens }
682 : {}),
683 }
684 return {
685 promptTokens,
686 completionTokens,
687 totalTokens: usage.total_tokens ?? promptTokens + completionTokens,
688 ...(Object.keys(promptTokensDetails).length > 0
689 ? { promptTokensDetails }
690 : {}),
691 ...(Object.keys(completionTokensDetails).length > 0
692 ? { completionTokensDetails }
693 : {}),
694 }