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

image.ts

529 lines16.1 KB

1import {
2 fileReferenceFor,
3 isFileSource,
4 resolveMediaPrompt,
5} from '@tanstack/ai'
6import { BaseImageAdapter } from '@tanstack/ai/adapters'
7import { createGeminiClient, getGeminiApiKeyFromEnv } from '../utils'
8import { flattenModalityTokenCounts, hasModalityTokens } from '../usage'
9import {
10 parseNativeImageSize,
11 validatePrompt,
12} from '../image/image-provider-options'
13import type { GeminiImageModels } from '../model-meta'
14import type {
15 GeminiImageModelInputModalitiesByName,
16 GeminiImageModelProviderOptionsByName,
17 GeminiImageModelSizeByName,
18 GeminiNativeImageProviderOptions,
19} from '../image/image-provider-options'
20import type {
21 GeneratedImage,
22 ImageGenerationOptions,
23 ImageGenerationResult,
24 ImagePart,
25 MediaInputMetadata,
26 ResolvedMediaPrompt,
27 TokenUsage,
28} from '@tanstack/ai'
29import { ThinkingLevel } from '@google/genai'
30import type {
31 Content,
32 ContentUnion,
33 GoogleGenAI,
34 Interactions,
35 Part,
36 SafetySetting,
37 ThinkingConfig,
38} from '@google/genai'
39import type { GeminiClientConfig } from '../utils/client'
40​
41/**
42 * Configuration for Gemini image adapter
43 */
44export interface GeminiImageConfig extends GeminiClientConfig {}
45​
46/** Model type for Gemini Image */
47export type GeminiImageModel = GeminiImageModels
48​
49/**
50 * Gemini Image Generation Adapter
51 *
52 * Tree-shakeable adapter for Gemini image generation functionality.
53 * Supports Gemini native image models like Nano Banana 2 via the
54 * Interactions API.
55 *
56 * Features:
57 * - Aspect ratio-based image sizing
58 * - Safety filtering
59 * - Extended resolution tiers (Nano Banana 2)
60 */
61export class GeminiImageAdapter<
62 TModel extends GeminiImageModel,
63> extends BaseImageAdapter<
64 TModel,
65 GeminiNativeImageProviderOptions,
66 GeminiImageModelProviderOptionsByName,
67 GeminiImageModelSizeByName,
68 GeminiImageModelInputModalitiesByName
69> {
70 override readonly kind = 'image' as const
71 readonly name = 'gemini' as const
72 // Consumes Gemini Files API references (geminiFiles()) as interaction image URIs.
73 override readonly supportsFileSources = true
74​
75 // Type-only property - never assigned at runtime
76 declare '~types': {
77 providerOptions: GeminiNativeImageProviderOptions
78 modelProviderOptionsByName: GeminiImageModelProviderOptionsByName
79 modelSizeByName: GeminiImageModelSizeByName
80 modelInputModalitiesByName: GeminiImageModelInputModalitiesByName
81 }
82​
83 private readonly client: GoogleGenAI
84​
85 constructor(config: GeminiImageConfig, model: TModel) {
86 super(model, config)
87 this.client = createGeminiClient(config)
88 }
89​
90 async generateImages(
91 options: ImageGenerationOptions<GeminiNativeImageProviderOptions>,
92 ): Promise<ImageGenerationResult> {
93 const { model, logger } = options
94​
95 logger.request(
96 `activity=generateImage provider=gemini model=${this.model}`,
97 {
98 provider: 'gemini',
99 model: this.model,
100 },
101 )
102​
103 try {
104 const resolved = resolveMediaPrompt(options.prompt)
105​
106 // Image-only prompts are allowed (the image inputs carry the intent);
107 // a prompt with neither text nor images is always an error.
108 if (resolved.images.length === 0) {
109 validatePrompt({ prompt: resolved.text, model })
110 }
111​
112 if (resolved.videos.length > 0) {
113 throw new Error(
114 `${this.name}.generateImages does not support video prompt parts (model: ${model}).`,
115 )
116 }
117 if (resolved.audios.length > 0) {
118 throw new Error(
119 `${this.name}.generateImages does not support audio prompt parts (model: ${model}).`,
120 )
121 }
122​
123 return await this.generateWithGeminiApi(options, resolved)
124 } catch (error) {
125 logger.errors('gemini.generateImage fatal', {
126 error,
127 source: 'gemini.generateImage',
128 })
129 throw error
130 }
131 }
132​
133 private async generateWithGeminiApi(
134 options: ImageGenerationOptions<GeminiNativeImageProviderOptions>,
135 resolved: ResolvedMediaPrompt,
136 ): Promise<ImageGenerationResult> {
137 const { model, size, numberOfImages, modelOptions } = options
138​
139 const parsedSize = size ? parseNativeImageSize(size) : undefined
140 // Named picks, never a wholesale spread of imageConfig. The portable
141 // `size` is the baseline; modelOptions.imageConfig wins per field.
142 const aspectRatio =
143 modelOptions?.imageConfig?.aspectRatio ?? parsedSize?.aspectRatio
144 const imageSize = interactionImageSize(
145 modelOptions?.imageConfig?.imageSize ?? parsedSize?.resolution,
146 )
147​
148 const thinking = modelOptions?.thinkingConfig
149 if (thinking?.thinkingBudget !== undefined) {
150 throw new Error(
151 `${this.name}: thinkingConfig.thinkingBudget is not supported on the Interactions image API. Set thinkingConfig.thinkingLevel ('minimal' | 'low' | 'medium' | 'high') instead.`,
152 )
153 }
154​
155 const generationConfig: Interactions.GenerationConfig = {
156 ...(modelOptions?.seed !== undefined && { seed: modelOptions.seed }),
157 ...interactionThinking(thinking),
158 }
159​
160 // safety_settings is not on the SDK param type. Assign it after the
161 // object is built so the JSON body still carries it.
162 const request = {
163 model,
164 input: this.buildInteractionInput(resolved, numberOfImages),
165 stream: false as const,
166 response_format: {
167 type: 'image' as const,
168 ...(aspectRatio !== undefined && { aspect_ratio: aspectRatio }),
169 ...(imageSize !== undefined && { image_size: imageSize }),
170 },
171 ...(modelOptions?.systemInstruction !== undefined && {
172 system_instruction: systemInstructionText(
173 modelOptions.systemInstruction,
174 ),
175 }),
176 ...(Object.keys(generationConfig).length > 0 && {
177 generation_config: generationConfig,
178 }),
179 ...(modelOptions?.previous_interaction_id && {
180 previous_interaction_id: modelOptions.previous_interaction_id,
181 }),
182 ...(modelOptions?.store !== undefined && { store: modelOptions.store }),
183 }
184 if (
185 modelOptions?.safetySettings !== undefined &&
186 modelOptions.safetySettings.length > 0
187 ) {
188 Object.assign(request, {
189 safety_settings: modelOptions.safetySettings.map(interactionSafety),
190 })
191 }
192​
193 const interaction = options.abortSignal
194 ? await this.client.interactions.create(request, {
195 signal: options.abortSignal,
196 })
197 : await this.client.interactions.create(request)
198​
199 return this.transformInteractionResponse(model, interaction)
200 }
201​
202 /**
203 * Text-only prompts pass through as a string. Prompts with image parts
204 * become content blocks in prompt order. The Interactions API has no
205 * image count, so more than one image appends an instruction.
206 */
207 private buildInteractionInput(
208 resolved: ResolvedMediaPrompt,
209 numberOfImages: number | undefined,
210 ): string | Array<Interactions.Content> {
211 const countInstruction =
212 numberOfImages && numberOfImages > 1
213 ? `Generate ${numberOfImages} distinct images.`
214 : undefined
215​
216 if (resolved.images.length === 0) {
217 return countInstruction
218 ? `${resolved.text} ${countInstruction}`
219 : resolved.text
220 }
221​
222 const blocks: Array<Interactions.Content> = resolved.parts.map((part) => {
223 if (part.type === 'text') {
224 return { type: 'text', text: part.content }
225 }
226 if (part.type === 'image') {
227 return this.imagePartToInteraction(part)
228 }
229 throw new Error(
230 `gemini: unsupported prompt part type "${part.type}" in image generation.`,
231 )
232 })
233 if (countInstruction) {
234 blocks.push({ type: 'text', text: countInstruction })
235 }
236 return blocks
237 }
238​
239 private imagePartToInteraction(
240 part: ImagePart<MediaInputMetadata>,
241 ): Interactions.ImageContent {
242 if (part.source.type === 'data') {
243 return {
244 type: 'image',
245 data: part.source.value,
246 mime_type: part.source.mimeType || 'image/png',
247 }
248 }
249 // URL and Files API sources pass through as `uri`. Gemini fetches them.
250 // Fetching locally and inlining as base64 OOMs on constrained runtimes.
251 const uri = isFileSource(part.source)
252 ? fileReferenceFor(part.source, this.name)
253 : part.source.value
254 return {
255 type: 'image',
256 uri,
257 mime_type: part.source.mimeType ?? 'image/jpeg',
258 }
259 }
260​
261 private transformInteractionResponse(
262 model: string,
263 interaction: Interactions.Interaction,
264 ): ImageGenerationResult {
265 if (interaction.status !== 'completed') {
266 throw new Error(
267 `Gemini ${model} image interaction ended with status "${interaction.status}".`,
268 )
269 }
270 if (!interaction.id) {
271 throw new Error(`Gemini ${model} image interaction returned no id.`)
272 }
273​
274 const images: Array<GeneratedImage> = []
275 const textParts: Array<string> = []
276 for (const step of interaction.steps ?? []) {
277 if (step.type !== 'model_output') continue
278 for (const block of step.content ?? []) {
279 if (block.type === 'image') {
280 const image = generatedImageFromBlock(block)
281 if (image) images.push(image)
282 } else if (block.type === 'text' && block.text.length > 0) {
283 textParts.push(block.text)
284 }
285 }
286 }
287 if (images.length === 0 && interaction.output_image) {
288 const image = generatedImageFromBlock(interaction.output_image)
289 if (image) images.push(image)
290 }
291​
292 if (images.length === 0) {
293 if (textParts.length === 0 && interaction.output_text) {
294 textParts.push(interaction.output_text)
295 }
296 const reason =
297 textParts.length > 0
298 ? `: ${textParts.join(' ').trim()}`
299 : ' (no image was returned).'
300 throw new Error(`Gemini ${model} returned no images${reason}`)
301 }
302​
303 const usage = interactionImageUsage(interaction.usage)
304 return {
305 id: interaction.id,
306 model,
307 images,
308 ...(usage ? { usage } : {}),
309 }
310 }
312/**
313 * Creates a Gemini image adapter with explicit API key.
314 * Type resolution happens here at the call site.
315 *
316 * @param model - The model name (e.g., 'gemini-3.1-flash-image')
317 * @param apiKey - Your Google API key
318 * @param config - Optional additional configuration
319 * @returns Configured Gemini image adapter instance with resolved types
320 *
321 * @example
322 * ```typescript
323 * const adapter = createGeminiImage('gemini-3.1-flash-image', "your-api-key");
324 *
325 * const result = await generateImage({
326 * adapter,
327 * prompt: 'A cute baby sea otter'
328 * });
329 * ```
330 */
331export function createGeminiImage<TModel extends GeminiImageModel>(
332 model: TModel,
333 apiKey: string,
334 config?: Omit<GeminiImageConfig, 'apiKey'>,
335): GeminiImageAdapter<TModel> {
336 return new GeminiImageAdapter({ apiKey, ...config }, model)
338​
339/**
340 * Creates a Gemini image adapter with automatic API key detection from environment variables.
341 * Type resolution happens here at the call site.
342 *
343 * Looks for `GOOGLE_API_KEY` or `GEMINI_API_KEY` in:
344 * - `process.env` (Node.js)
345 * - `window.env` (Browser with injected env)
346 *
347 * @param model - The model name (e.g., 'gemini-3.1-flash-image')
348 * @param config - Optional configuration (excluding apiKey which is auto-detected)
349 * @returns Configured Gemini image adapter instance with resolved types
350 * @throws Error if GOOGLE_API_KEY or GEMINI_API_KEY is not found in environment
351 *
352 * @example
353 * ```typescript
354 * // Automatically uses GOOGLE_API_KEY from environment
355 * const adapter = geminiImage('gemini-3.1-flash-image');
356 *
357 * const result = await generateImage({
358 * adapter,
359 * prompt: 'A beautiful sunset over mountains'
360 * });
361 * ```
362 */
363export function geminiImage<TModel extends GeminiImageModel>(
364 model: TModel,
365 config?: Omit<GeminiImageConfig, 'apiKey'>,
366): GeminiImageAdapter<TModel> {
367 const apiKey = getGeminiApiKeyFromEnv()
368 return createGeminiImage(model, apiKey, config)
370​
371function interactionThinking(
372 thinking: ThinkingConfig | undefined,
373): Pick<
374 Interactions.GenerationConfig,
375 'thinking_level' | 'thinking_summaries'
376> {
377 if (!thinking) return {}
378 const level = interactionThinkingLevel(thinking.thinkingLevel)
379 return {
380 ...(level !== undefined && { thinking_level: level }),
381 ...(thinking.includeThoughts !== undefined && {
382 thinking_summaries: thinking.includeThoughts ? 'auto' : 'none',
383 }),
384 }
386​
387function interactionImageSize(
388 value: string | undefined,
389): '512' | '1K' | '2K' | '4K' | undefined {
390 if (value === '512' || value === '1K' || value === '2K' || value === '4K') {
391 return value
392 }
393 return undefined
395​
396function interactionThinkingLevel(
397 level: ThinkingConfig['thinkingLevel'],
398): 'minimal' | 'low' | 'medium' | 'high' | undefined {
399 switch (level) {
400 case ThinkingLevel.MINIMAL:
401 return 'minimal'
402 case ThinkingLevel.LOW:
403 return 'low'
404 case ThinkingLevel.MEDIUM:
405 return 'medium'
406 case ThinkingLevel.HIGH:
407 return 'high'
408 case ThinkingLevel.THINKING_LEVEL_UNSPECIFIED:
409 case undefined:
410 return undefined
411 }
413​
414function interactionSafety(setting: SafetySetting): {
415 type: string
416 threshold: string
417} {
418 const category = setting.category
419 const threshold = setting.threshold
420 if (!category || category === 'HARM_CATEGORY_UNSPECIFIED') {
421 throw new Error(
422 'gemini: safetySettings.category is required on the Interactions image API.',
423 )
424 }
425 if (!threshold || threshold === 'HARM_BLOCK_THRESHOLD_UNSPECIFIED') {
426 throw new Error(
427 'gemini: safetySettings.threshold is required on the Interactions image API.',
428 )
429 }
430 return {
431 type: category.replace(/^HARM_CATEGORY_/, '').toLowerCase(),
432 threshold: threshold.toLowerCase(),
433 }
435​
436function systemInstructionText(instruction: ContentUnion): string {
437 if (typeof instruction === 'string') return instruction
438 if (Array.isArray(instruction)) {
439 return instruction.map(partUnionText).join('')
440 }
441 if (isPart(instruction)) return partUnionText(instruction)
442 const parts = instruction.parts
443 if (!parts || parts.length === 0) {
444 throw new Error(
445 'gemini: systemInstruction on the Interactions image API must be text.',
446 )
447 }
448 return parts.map(partUnionText).join('')
450​
451function isPart(value: Content | Part): value is Part {
452 return !('parts' in value)
454​
455function partUnionText(part: Part | string): string {
456 if (typeof part === 'string') return part
457 if (
458 part.inlineData ||
459 part.fileData ||
460 part.functionCall ||
461 part.functionResponse
462 ) {
463 throw new Error(
464 'gemini: systemInstruction on the Interactions image API must be text. Inline media is not supported.',
465 )
466 }
467 if (typeof part.text !== 'string') {
468 throw new Error(
469 'gemini: systemInstruction on the Interactions image API must be text.',
470 )
471 }
472 return part.text
474​
475function generatedImageFromBlock(block: {
476 data?: string
477 uri?: string
478}): GeneratedImage | undefined {
479 if (typeof block.data === 'string' && block.data.length > 0) {
480 return { b64Json: block.data }
481 }
482 if (typeof block.uri === 'string' && block.uri.length > 0) {
483 return { url: block.uri }
484 }
485 return undefined
487​
488function interactionImageUsage(
489 usage: Interactions.Interaction['usage'],
490): TokenUsage | undefined {
491 if (!usage) return undefined
492 const promptTokens = usage.total_input_tokens ?? 0
493 const completionTokens = usage.total_output_tokens ?? 0
494 const promptModalities = flattenModalityTokenCounts(
495 usage.input_tokens_by_modality?.map((item) => ({
496 modality: item.modality,
497 tokenCount: item.tokens,
498 })),
499 )
500 const completionModalities = flattenModalityTokenCounts(
501 usage.output_tokens_by_modality?.map((item) => ({
502 modality: item.modality,
503 tokenCount: item.tokens,
504 })),
505 )
506 const promptTokensDetails = {
507 ...(hasModalityTokens(promptModalities) ? promptModalities : {}),
508 ...(usage.total_cached_tokens
509 ? { cachedTokens: usage.total_cached_tokens }
510 : {}),
511 }
512 const completionTokensDetails = {
513 ...(hasModalityTokens(completionModalities) ? completionModalities : {}),
514 ...(usage.total_thought_tokens
515 ? { reasoningTokens: usage.total_thought_tokens }
516 : {}),
517 }
518 return {
519 promptTokens,
520 completionTokens,
521 totalTokens: usage.total_tokens ?? promptTokens + completionTokens,
522 ...(Object.keys(promptTokensDetails).length > 0
523 ? { promptTokensDetails }
524 : {}),
525 ...(Object.keys(completionTokensDetails).length > 0
526 ? { completionTokensDetails }
527 : {}),
528 }