Open History to see the last commit
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-2.5-flash-image, "nano-banana") 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 }
476}
477
478/** @deprecated Shut down 2026-06-25. Use `gemini-3.1-flash-image`. */
479export function createGeminiImage(
480 model: 'gemini-3.1-flash-image-preview',
481 apiKey: string,
482 config?: Omit<GeminiImageConfig, 'apiKey'>,
483): GeminiImageAdapter<'gemini-3.1-flash-image-preview'>
484/** @deprecated Shut down 2026-06-25. Use `gemini-3-pro-image`. */
485export function createGeminiImage(
486 model: 'gemini-3-pro-image-preview',
487 apiKey: string,
488 config?: Omit<GeminiImageConfig, 'apiKey'>,
489): GeminiImageAdapter<'gemini-3-pro-image-preview'>
490/**
491 * Creates a Gemini image adapter with explicit API key.
492 * Type resolution happens here at the call site.
493 *
494 * @param model - The model name (e.g., 'imagen-4.0-generate-001')
495 * @param apiKey - Your Google API key
496 * @param config - Optional additional configuration
497 * @returns Configured Gemini image adapter instance with resolved types
498 *
499 * @example
500 * ```typescript
501 * const adapter = createGeminiImage('imagen-4.0-generate-001', "your-api-key");
502 *
503 * const result = await generateImage({
504 * adapter,
505 * prompt: 'A cute baby sea otter'
506 * });
507 * ```
508 */
509export function createGeminiImage<TModel extends GeminiImageModel>(
510 model: TModel,
511 apiKey: string,
512 config?: Omit<GeminiImageConfig, 'apiKey'>,
513): GeminiImageAdapter<TModel>
514export function createGeminiImage<TModel extends GeminiImageModel>(
515 model: TModel,
516 apiKey: string,
517 config?: Omit<GeminiImageConfig, 'apiKey'>,
518): GeminiImageAdapter<TModel> {
519 return new GeminiImageAdapter({ apiKey, ...config }, model)
520}
521
522/** @deprecated Shut down 2026-06-25. Use `gemini-3.1-flash-image`. */
523export function geminiImage(
524 model: 'gemini-3.1-flash-image-preview',
525 config?: Omit<GeminiImageConfig, 'apiKey'>,
526): GeminiImageAdapter<'gemini-3.1-flash-image-preview'>
527/** @deprecated Shut down 2026-06-25. Use `gemini-3-pro-image`. */
528export function geminiImage(
529 model: 'gemini-3-pro-image-preview',
530 config?: Omit<GeminiImageConfig, 'apiKey'>,
531): GeminiImageAdapter<'gemini-3-pro-image-preview'>
532/**
533 * Creates a Gemini image adapter with automatic API key detection from environment variables.
534 * Type resolution happens here at the call site.
535 *
536 * Looks for `GOOGLE_API_KEY` or `GEMINI_API_KEY` in:
537 * - `process.env` (Node.js)
538 * - `window.env` (Browser with injected env)
539 *
540 * @param model - The model name (e.g., 'imagen-4.0-generate-001')
541 * @param config - Optional configuration (excluding apiKey which is auto-detected)
542 * @returns Configured Gemini image adapter instance with resolved types
543 * @throws Error if GOOGLE_API_KEY or GEMINI_API_KEY is not found in environment
544 *
545 * @example
546 * ```typescript
547 * // Automatically uses GOOGLE_API_KEY from environment
548 * const adapter = geminiImage('imagen-4.0-generate-001');
549 *
550 * const result = await generateImage({
551 * adapter,
552 * prompt: 'A beautiful sunset over mountains'
553 * });
554 * ```
555 */
556export function geminiImage<TModel extends GeminiImageModel>(
557 model: TModel,
558 config?: Omit<GeminiImageConfig, 'apiKey'>,
559): GeminiImageAdapter<TModel>
560export function geminiImage<TModel extends GeminiImageModel>(
561 model: TModel,
562 config?: Omit<GeminiImageConfig, 'apiKey'>,
563): GeminiImageAdapter<TModel> {
564 const apiKey = getGeminiApiKeyFromEnv()
565 return createGeminiImage(model, apiKey, config)
566}
567
568function interactionThinking(
569 thinking: ThinkingConfig | undefined,
570): Pick<
571 Interactions.GenerationConfig,
572 'thinking_level' | 'thinking_summaries'
573> {
574 if (!thinking) return {}
575 const level = interactionThinkingLevel(thinking.thinkingLevel)
576 return {
577 ...(level !== undefined && { thinking_level: level }),
578 ...(thinking.includeThoughts !== undefined && {
579 thinking_summaries: thinking.includeThoughts ? 'auto' : 'none',
580 }),
581 }
582}
583
584function interactionImageSize(
585 value: string | undefined,
586): '512' | '1K' | '2K' | '4K' | undefined {
587 if (value === '512' || value === '1K' || value === '2K' || value === '4K') {
588 return value
589 }
590 return undefined
591}
592
593function interactionThinkingLevel(
594 level: ThinkingConfig['thinkingLevel'],
595): 'minimal' | 'low' | 'medium' | 'high' | undefined {
596 switch (level) {
597 case ThinkingLevel.MINIMAL:
598 return 'minimal'
599 case ThinkingLevel.LOW:
600 return 'low'
601 case ThinkingLevel.MEDIUM:
602 return 'medium'
603 case ThinkingLevel.HIGH:
604 return 'high'
605 case ThinkingLevel.THINKING_LEVEL_UNSPECIFIED:
606 case undefined:
607 return undefined
608 }
609}
610
611function interactionSafety(setting: SafetySetting): {
612 type: string
613 threshold: string
614} {
615 const category = setting.category
616 const threshold = setting.threshold
617 if (!category || category === 'HARM_CATEGORY_UNSPECIFIED') {
618 throw new Error(
619 'gemini: safetySettings.category is required on the Interactions image API.',
620 )
621 }
622 if (!threshold || threshold === 'HARM_BLOCK_THRESHOLD_UNSPECIFIED') {
623 throw new Error(
624 'gemini: safetySettings.threshold is required on the Interactions image API.',
625 )
626 }
627 return {
628 type: category.replace(/^HARM_CATEGORY_/, '').toLowerCase(),
629 threshold: threshold.toLowerCase(),
630 }
631}
632
633function systemInstructionText(instruction: ContentUnion): string {
634 if (typeof instruction === 'string') return instruction
635 if (Array.isArray(instruction)) {
636 return instruction.map(partUnionText).join('')
637 }
638 if (isPart(instruction)) return partUnionText(instruction)
639 const parts = instruction.parts
640 if (!parts || parts.length === 0) {
641 throw new Error(
642 'gemini: systemInstruction on the Interactions image API must be text.',
643 )
644 }
645 return parts.map(partUnionText).join('')
646}
647
648function isPart(value: Content | Part): value is Part {
649 return !('parts' in value)
650}
651
652function partUnionText(part: Part | string): string {
653 if (typeof part === 'string') return part
654 if (
655 part.inlineData ||
656 part.fileData ||
657 part.functionCall ||
658 part.functionResponse
659 ) {
660 throw new Error(
661 'gemini: systemInstruction on the Interactions image API must be text. Inline media is not supported.',
662 )
663 }
664 if (typeof part.text !== 'string') {
665 throw new Error(
666 'gemini: systemInstruction on the Interactions image API must be text.',
667 )
668 }
669 return part.text
670}
671
672function generatedImageFromBlock(block: {
673 data?: string
674 uri?: string
675}): GeneratedImage | undefined {
676 if (typeof block.data === 'string' && block.data.length > 0) {
677 return { b64Json: block.data }
678 }
679 if (typeof block.uri === 'string' && block.uri.length > 0) {
680 return { url: block.uri }
681 }
682 return undefined
683}
684
685function interactionImageUsage(
686 usage: Interactions.Interaction['usage'],
687): TokenUsage | undefined {
688 if (!usage) return undefined
689 const promptTokens = usage.total_input_tokens ?? 0
690 const completionTokens = usage.total_output_tokens ?? 0
691 const promptModalities = flattenModalityTokenCounts(
692 usage.input_tokens_by_modality?.map((item) => ({
693 modality: item.modality,
694 tokenCount: item.tokens,
695 })),
696 )
697 const completionModalities = flattenModalityTokenCounts(
698 usage.output_tokens_by_modality?.map((item) => ({
699 modality: item.modality,
700 tokenCount: item.tokens,
701 })),
702 )
703 const promptTokensDetails = {
704 ...(hasModalityTokens(promptModalities) ? promptModalities : {}),
705 ...(usage.total_cached_tokens
706 ? { cachedTokens: usage.total_cached_tokens }
707 : {}),
708 }
709 const completionTokensDetails = {
710 ...(hasModalityTokens(completionModalities) ? completionModalities : {}),
711 ...(usage.total_thought_tokens
712 ? { reasoningTokens: usage.total_thought_tokens }
713 : {}),
714 }
715 return {
716 promptTokens,
717 completionTokens,
718 totalTokens: usage.total_tokens ?? promptTokens + completionTokens,
719 ...(Object.keys(promptTokensDetails).length > 0
720 ? { promptTokensDetails }
721 : {}),
722 ...(Object.keys(completionTokensDetails).length > 0
723 ? { completionTokensDetails }
724 : {}),
725 }
726}