Open History to see the last commit
1import { FinishReason } from '@google/genai'
2import {
3 EventType,
4 fileReferenceFor,
5 isFileSource,
6 normalizeSystemPrompts,
7} from '@tanstack/ai'
8import { toRunErrorRawEvent } from '@tanstack/ai/adapter-internals'
9import { BaseTextAdapter } from '@tanstack/ai/adapters'
10import { convertToolsToProviderFormat } from '../tools/tool-converter'
11import { buildGeminiUsage } from '../usage'
12import {
13 createGeminiClient,
14 generateId,
15 getGeminiApiKeyFromEnv,
16} from '../utils'
17import { GEMINI_COMBINED_TOOLS_AND_SCHEMA_MODELS } from '../model-meta'
18import type {
19 GEMINI_MODELS,
20 GeminiChatModelProviderOptionsByName,
21 GeminiChatModelToolCapabilitiesByName,
22 GeminiModelInputModalitiesByName,
23} from '../model-meta'
24import type {
25 StructuredOutputOptions,
26 StructuredOutputResult,
27} from '@tanstack/ai/adapters'
28import type { InternalLogger } from '@tanstack/ai/adapter-internals'
29import type {
30 Content,
31 GenerateContentParameters,
32 GenerateContentResponse,
33 GoogleGenAI,
34 GroundingMetadata,
35 Part,
36 ThinkingLevel,
37 VideoMetadata,
38} from '@google/genai'
39import type {
40 ContentPart,
41 Modality,
42 ModelMessage,
43 AdapterYieldChunk,
44 ProviderExecutedToolSource,
45 TextOptions,
46} from '@tanstack/ai'
47import type { ExternalTextProviderOptions } from '../text/text-provider-options'
48import type {
49 GeminiMessageMetadataByModality,
50 GeminiToolCallMetadata,
51 GeminiVideoMetadata,
52 GeminiVideoProcessing,
53} from '../message-types'
54import type { GeminiClientConfig } from '../utils/client'
55
56/**
57 * Fallback MIME types for URL-sourced media parts that don't specify one.
58 */
59const DEFAULT_MEDIA_MIME_TYPES = {
60 image: 'image/jpeg',
61 audio: 'audio/mp3',
62 video: 'video/mp4',
63 document: 'application/pdf',
64} as const
65
66function getGroundingSources(
67 metadata: GroundingMetadata,
68): Array<ProviderExecutedToolSource> {
69 const sources = new Map<string, ProviderExecutedToolSource>()
70 for (const chunk of metadata.groundingChunks ?? []) {
71 const url = chunk.web?.uri
72 if (!url) continue
73 const existing = sources.get(url)
74 if (existing) {
75 if (!existing.title && chunk.web?.title) existing.title = chunk.web.title
76 continue
77 }
78 sources.set(url, {
79 url,
80 ...(chunk.web?.title ? { title: chunk.web.title } : {}),
81 })
82 }
83 return [...sources.values()]
84}
85
86/**
87 * Content block shape for an Interactions API `input` step. The installed
88 * @google/genai types predate the video `processing` field, so we model the
89 * subset we emit and cast at the call site.
90 */
91type InteractionContent =
92 | { type: 'text'; text: string }
93 | {
94 type: 'video'
95 uri?: string
96 data?: string
97 mime_type?: string
98 processing?: GeminiVideoProcessing
99 }
100 | {
101 type: 'image' | 'audio' | 'document'
102 uri?: string
103 data?: string
104 mime_type?: string
105 }
106
107interface InteractionStep {
108 type: 'user_input' | 'model_output'
109 content: Array<InteractionContent>
110}
111
112/** True when any message carries a video part requesting agentic processing. */
113function hasAgenticVideo(messages: Array<ModelMessage>): boolean {
114 return messages.some(
115 (msg) =>
116 Array.isArray(msg.content) &&
117 msg.content.some(
118 (part) =>
119 part.type === 'video' &&
120 (part.metadata as GeminiVideoMetadata | undefined)?.processing ===
121 'agentic',
122 ),
123 )
124}
125
126/** Convert a single content part to an Interactions API content block. */
127function contentPartToInteraction(part: ContentPart): InteractionContent {
128 if (part.type === 'text') {
129 return { type: 'text', text: part.content }
130 }
131
132 const source = part.source
133 const mimeType =
134 source.type === 'data'
135 ? source.mimeType
136 : (source.mimeType ?? DEFAULT_MEDIA_MIME_TYPES[part.type])
137 // A Gemini Files API handle maps to the `uri` field, same as a public URL;
138 // `fileReferenceFor` throws when another provider issued it.
139 const base = isFileSource(source)
140 ? { uri: fileReferenceFor(source, 'gemini'), mime_type: mimeType }
141 : source.type === 'data'
142 ? { data: source.value, mime_type: mimeType }
143 : { uri: source.value, mime_type: mimeType }
144
145 if (part.type === 'video') {
146 const processing = (part.metadata as GeminiVideoMetadata | undefined)
147 ?.processing
148 return { type: 'video', ...base, ...(processing && { processing }) }
149 }
150 return { type: part.type, ...base }
151}
152
153/**
154 * Build the Interactions API `input` from chat messages. Each user/assistant
155 * message becomes a `user_input` / `model_output` step wrapping its content
156 * blocks — the wrapping the Python SDK performs implicitly but the JS SDK
157 * does not. Tool messages are skipped (unsupported on this path).
158 */
159function buildInteractionsInput(
160 messages: Array<ModelMessage>,
161): Array<InteractionStep> {
162 const steps: Array<InteractionStep> = []
163 for (const msg of messages) {
164 if (msg.role === 'tool') continue
165 const stepType = msg.role === 'assistant' ? 'model_output' : 'user_input'
166 const content: Array<InteractionContent> = []
167 if (Array.isArray(msg.content)) {
168 for (const part of msg.content) {
169 content.push(contentPartToInteraction(part))
170 }
171 } else if (msg.content) {
172 content.push({ type: 'text', text: msg.content })
173 }
174 if (content.length > 0) {
175 steps.push({ type: stepType, content })
176 }
177 }
178 return steps
179}
180
181/**
182 * Configuration for Gemini text adapter
183 */
184export interface GeminiTextConfig extends GeminiClientConfig {}
185
186/**
187 * Gemini-specific provider options for text/chat
188 */
189export type GeminiTextProviderOptions = ExternalTextProviderOptions
190
191// ===========================
192// Type Resolution Helpers
193// ===========================
194
195/**
196 * Resolve provider options for a specific model.
197 * If the model has explicit options in the map, use those; otherwise use base options.
198 */
199type ResolveProviderOptions<TModel extends string> =
200 TModel extends keyof GeminiChatModelProviderOptionsByName
201 ? GeminiChatModelProviderOptionsByName[TModel]
202 : GeminiTextProviderOptions
203
204/**
205 * Resolve input modalities for a specific model.
206 * If the model has explicit modalities in the map, use those; otherwise use all modalities.
207 */
208type ResolveInputModalities<TModel extends string> =
209 TModel extends keyof GeminiModelInputModalitiesByName
210 ? GeminiModelInputModalitiesByName[TModel]
211 : readonly ['text', 'image', 'audio', 'video', 'document']
212
213/**
214 * Resolve tool capabilities for a specific model.
215 * If the model has explicit tools in the map, use those; otherwise use empty tuple.
216 */
217type ResolveToolCapabilities<TModel extends string> =
218 TModel extends keyof GeminiChatModelToolCapabilitiesByName
219 ? NonNullable<GeminiChatModelToolCapabilitiesByName[TModel]>
220 : readonly []
221
222// ===========================
223// Adapter Implementation
224// ===========================
225
226/**
227 * Gemini Text (Chat) Adapter
228 *
229 * Tree-shakeable adapter for Gemini chat/text completion functionality.
230 * Import only what you need for smaller bundle sizes.
231 */
232export class GeminiTextAdapter<
233 TModel extends (typeof GEMINI_MODELS)[number],
234 TProviderOptions extends Record<string, any> = ResolveProviderOptions<TModel>,
235 TInputModalities extends ReadonlyArray<Modality> =
236 ResolveInputModalities<TModel>,
237 TToolCapabilities extends ReadonlyArray<string> =
238 ResolveToolCapabilities<TModel>,
239> extends BaseTextAdapter<
240 TModel,
241 TProviderOptions,
242 TInputModalities,
243 GeminiMessageMetadataByModality,
244 TToolCapabilities,
245 GeminiToolCallMetadata
246> {
247 override readonly kind = 'text' as const
248 readonly name = 'gemini' as const
249 // Consumes Gemini Files API references (geminiFiles()) as fileData.fileUri.
250 override readonly supportsFileSources = true
251
252 private readonly client: GoogleGenAI
253
254 constructor(config: GeminiTextConfig, model: TModel) {
255 super({}, model)
256 this.client = createGeminiClient(config)
257 }
258
259 async *chatStream(
260 options: TextOptions<GeminiTextProviderOptions>,
261 ): AsyncIterable<AdapterYieldChunk> {
262 // Agentic video understanding is only exposed through the Interactions API,
263 // not generateContent. Detect it and take that path instead.
264 if (hasAgenticVideo(options.messages)) {
265 yield* this.interactionsStream(options)
266 return
267 }
268
269 const mappedOptions = this.mapCommonOptionsToGemini(options)
270 const { logger } = options
271
272 try {
273 logger.request(
274 `activity=chat provider=gemini model=${this.model} messages=${options.messages.length} tools=${options.tools?.length ?? 0} stream=true`,
275 { provider: 'gemini', model: this.model },
276 )
277 const result =
278 await this.client.models.generateContentStream(mappedOptions)
279
280 yield* this.processStreamChunks(result, options, logger)
281 } catch (error) {
282 const rawEvent = toRunErrorRawEvent(error)
283 logger.errors('gemini.chatStream fatal', {
284 error,
285 source: 'gemini.chatStream',
286 })
287 yield {
288 type: EventType.RUN_ERROR,
289 model: options.model,
290 timestamp: Date.now(),
291 message:
292 error instanceof Error
293 ? error.message
294 : 'An unknown error occurred during the chat stream.',
295 // Forward the provider's structured error body when present (see
296 // toRunErrorRawEvent); omitted otherwise.
297 ...(rawEvent !== undefined && { rawEvent }),
298 error: {
299 message:
300 error instanceof Error
301 ? error.message
302 : 'An unknown error occurred during the chat stream.',
303 },
304 }
305 }
306 }
307
308 /**
309 * Agentic video-understanding path via the Interactions API.
310 *
311 * The Interactions API (unlike `generateContent`) requires message parts to
312 * be wrapped in `user_input` / `model_output` steps, and it accepts the
313 * `processing: 'agentic'` video flag. This is a non-streaming call whose
314 * single text result is re-emitted as AG-UI stream chunks.
315 */
316 private async *interactionsStream(
317 options: TextOptions<GeminiTextProviderOptions>,
318 ): AsyncIterable<AdapterYieldChunk> {
319 const model = options.model
320 const { logger } = options
321 const runId = options.runId ?? generateId(this.name)
322 const threadId = options.threadId ?? generateId(this.name)
323 const messageId = generateId(this.name)
324
325 try {
326 logger.request(
327 `activity=chat provider=gemini model=${model} messages=${options.messages.length} mode=interactions-agentic-video`,
328 { provider: 'gemini', model },
329 )
330
331 const normalizedPrompts = normalizeSystemPrompts(options.systemPrompts)
332 const systemInstruction =
333 normalizedPrompts.length > 0
334 ? normalizedPrompts.map((p) => p.content).join('\n')
335 : undefined
336
337 const input = buildInteractionsInput(options.messages)
338
339 // The installed @google/genai (2.10.0) Interactions `VideoContent` type
340 // predates the `processing` field, so the structurally-built input is
341 // cast at the call boundary. The SDK forwards it to the wire unchanged.
342 const interaction = await this.client.interactions.create({
343 model,
344 ...(systemInstruction !== undefined && {
345 system_instruction: systemInstruction,
346 }),
347 input: input as never,
348 })
349
350 const text = interaction.output_text ?? ''
351
352 yield {
353 type: EventType.RUN_STARTED,
354 runId,
355 threadId,
356 model,
357 timestamp: Date.now(),
358 parentRunId: options.parentRunId,
359 }
360 yield {
361 type: EventType.TEXT_MESSAGE_START,
362 messageId,
363 model,
364 timestamp: Date.now(),
365 role: 'assistant',
366 }
367 if (text) {
368 yield {
369 type: EventType.TEXT_MESSAGE_CONTENT,
370 messageId,
371 model,
372 timestamp: Date.now(),
373 delta: text,
374 content: text,
375 }
376 }
377 yield {
378 type: EventType.TEXT_MESSAGE_END,
379 messageId,
380 model,
381 timestamp: Date.now(),
382 }
383 yield {
384 type: EventType.RUN_FINISHED,
385 runId,
386 threadId,
387 model,
388 timestamp: Date.now(),
389 finishReason: 'stop',
390 }
391 } catch (error) {
392 const rawEvent = toRunErrorRawEvent(error)
393 logger.errors('gemini.interactionsStream fatal', {
394 error,
395 source: 'gemini.interactionsStream',
396 })
397 yield {
398 type: EventType.RUN_ERROR,
399 model,
400 timestamp: Date.now(),
401 message:
402 error instanceof Error
403 ? error.message
404 : 'An unknown error occurred during the chat stream.',
405 ...(rawEvent !== undefined && { rawEvent }),
406 error: {
407 message:
408 error instanceof Error
409 ? error.message
410 : 'An unknown error occurred during the chat stream.',
411 },
412 }
413 }
414 }
415
416 /**
417 * Generate structured output using Gemini's native JSON response format.
418 * Uses responseMimeType: 'application/json' and responseSchema for structured output.
419 * The outputSchema is already JSON Schema (converted in the ai layer).
420 */
421 async structuredOutput(
422 options: StructuredOutputOptions<GeminiTextProviderOptions>,
423 ): Promise<StructuredOutputResult<unknown>> {
424 const { chatOptions, outputSchema } = options
425 const { logger } = chatOptions
426
427 const mappedOptions = this.mapCommonOptionsToGemini(chatOptions)
428
429 try {
430 logger.request(
431 `activity=chat provider=gemini model=${this.model} messages=${chatOptions.messages.length} tools=${chatOptions.tools?.length ?? 0} stream=false`,
432 { provider: 'gemini', model: this.model },
433 )
434 // Add structured output configuration
435 const result = await this.client.models.generateContent({
436 ...mappedOptions,
437 config: {
438 ...mappedOptions.config,
439 responseMimeType: 'application/json',
440 responseSchema: outputSchema,
441 },
442 })
443
444 // Extract text content from the response
445 const rawText = this.extractTextFromResponse(result)
446
447 // Parse the JSON response
448 let parsed: unknown
449 try {
450 parsed = JSON.parse(rawText)
451 } catch {
452 throw new Error(jsonContentParseError(rawText, 'structured output'))
453 }
454
455 return {
456 data: parsed,
457 rawText,
458 usage: result.usageMetadata
459 ? buildGeminiUsage(result.usageMetadata)
460 : undefined,
461 }
462 } catch (error) {
463 logger.errors('gemini.structuredOutput fatal', {
464 error,
465 source: 'gemini.structuredOutput',
466 })
467 throw new Error(
468 error instanceof Error
469 ? error.message
470 : 'An unknown error occurred during structured output generation.',
471 )
472 }
473 }
474
475 /**
476 * Stream schema-constrained JSON from Gemini natively.
477 *
478 * `chat({ outputSchema, stream: true })` calls this when the adapter
479 * implements it. Without it, the engine buffers `structuredOutput()` and
480 * emits one synthetic delta.
481 */
482 async *structuredOutputStream(
483 options: StructuredOutputOptions<GeminiTextProviderOptions>,
484 ): AsyncIterable<AdapterYieldChunk> {
485 const { chatOptions: requestedChatOptions, outputSchema } = options
486 const chatOptions = {
487 ...requestedChatOptions,
488 runId: requestedChatOptions.runId ?? generateId(this.name),
489 }
490 const mappedOptions = this.mapCommonOptionsToGemini(chatOptions)
491
492 try {
493 chatOptions.logger.request(
494 `activity=structuredOutputStream provider=gemini model=${this.model} messages=${chatOptions.messages.length}`,
495 { provider: 'gemini', model: this.model },
496 )
497 const result = await this.client.models.generateContentStream({
498 ...mappedOptions,
499 config: {
500 ...mappedOptions.config,
501 responseMimeType: 'application/json',
502 responseSchema: outputSchema,
503 },
504 })
505
506 let rawText = ''
507 let finished:
508 | Extract<AdapterYieldChunk, { type: typeof EventType.RUN_FINISHED }>
509 | undefined
510 let failed = false
511 for await (const chunk of this.processStreamChunks(
512 result,
513 chatOptions,
514 chatOptions.logger,
515 )) {
516 if (chunk.type === EventType.TEXT_MESSAGE_CONTENT) {
517 rawText += chunk.delta
518 }
519 if (chunk.type === EventType.RUN_ERROR) failed = true
520 if (chunk.type === EventType.RUN_FINISHED) {
521 finished = chunk
522 } else {
523 yield chunk
524 }
525 }
526
527 if (failed) return
528 if (!finished) {
529 yield structuredStreamError(
530 chatOptions,
531 'Gemini structured-output stream ended without a terminal event',
532 'truncated-stream',
533 )
534 return
535 }
536 if (!rawText) {
537 yield structuredStreamError(
538 chatOptions,
539 'Gemini structured-output stream contained no content',
540 'empty-response',
541 )
542 return
543 }
544
545 let object: unknown
546 try {
547 object = JSON.parse(rawText)
548 } catch {
549 yield structuredStreamError(
550 chatOptions,
551 jsonContentParseError(rawText, 'Gemini structured-output stream'),
552 'parse-error',
553 )
554 return
555 }
556
557 yield {
558 type: EventType.CUSTOM,
559 name: 'structured-output.complete',
560 value: { object, raw: rawText },
561 model: chatOptions.model,
562 timestamp: Date.now(),
563 }
564 yield { ...finished, timestamp: Date.now() }
565 } catch (error) {
566 const rawEvent = toRunErrorRawEvent(error)
567 const message =
568 error instanceof Error
569 ? error.message
570 : 'An unknown error occurred during structured output streaming.'
571 chatOptions.logger.errors('gemini.structuredOutputStream fatal', {
572 error,
573 source: 'gemini.structuredOutputStream',
574 })
575 yield {
576 ...structuredStreamError(chatOptions, message, 'provider-error'),
577 ...(rawEvent !== undefined && { rawEvent }),
578 }
579 }
580 }
581
582 /**
583 * Extract text content from a non-streaming response
584 */
585 private extractTextFromResponse(response: GenerateContentResponse): string {
586 let textContent = ''
587
588 if (response.candidates?.[0]?.content?.parts) {
589 for (const part of response.candidates[0].content.parts) {
590 if (part.text) {
591 textContent += part.text
592 }
593 }
594 }
595
596 return textContent
597 }
598
599 private async *processStreamChunks(
600 result: AsyncGenerator<GenerateContentResponse, unknown, unknown>,
601 options: TextOptions<GeminiTextProviderOptions>,
602 logger: InternalLogger,
603 ): AsyncIterable<AdapterYieldChunk> {
604 const model = options.model
605 let accumulatedContent = ''
606 let accumulatedThinking = ''
607 const toolCallMap = new Map<
608 string,
609 {
610 name: string
611 args: string
612 index: number
613 started: boolean
614 thoughtSignature?: string
615 }
616 >()
617 let nextToolIndex = 0
618
619 // AG-UI lifecycle tracking
620 const runId = options.runId ?? generateId(this.name)
621 const threadId = options.threadId ?? generateId(this.name)
622 const messageId = generateId(this.name)
623 let stepId: string | null = null
624 let reasoningMessageId: string | null = null
625 let hasClosedReasoning = false
626 let hasEmittedRunStarted = false
627 let hasEmittedTextMessageStart = false
628 let hasEmittedStepStarted = false
629 let groundingMetadata: GroundingMetadata | undefined
630 let groundingCallEmitted = false
631 const adapterName = this.name
632
633 const emitGroundingToolCall = function* (): Generator<AdapterYieldChunk> {
634 if (!groundingMetadata || groundingCallEmitted) return
635 const sources = getGroundingSources(groundingMetadata)
636 const hasGoogleSearchEvidence =
637 sources.length > 0 ||
638 (groundingMetadata.webSearchQueries?.length ?? 0) > 0 ||
639 groundingMetadata.searchEntryPoint !== undefined
640 if (!hasGoogleSearchEvidence) return
641
642 groundingCallEmitted = true
643 const toolCallId = generateId(adapterName)
644 const metadata: GeminiToolCallMetadata = {
645 providerExecuted: true,
646 sources,
647 gemini: { groundingMetadata },
648 }
649 yield {
650 type: EventType.TOOL_CALL_START,
651 toolCallId,
652 toolCallName: 'google_search',
653 toolName: 'google_search',
654 parentMessageId: messageId,
655 model,
656 timestamp: Date.now(),
657 index: toolCallMap.size,
658 metadata,
659 }
660 yield {
661 type: EventType.TOOL_CALL_END,
662 toolCallId,
663 toolCallName: 'google_search',
664 toolName: 'google_search',
665 model,
666 timestamp: Date.now(),
667 input: {
668 ...(groundingMetadata.webSearchQueries && {
669 queries: groundingMetadata.webSearchQueries,
670 }),
671 },
672 }
673 }
674
675 for await (const chunk of result) {
676 logger.provider(`provider=gemini`, { chunk })
677 // Emit RUN_STARTED on first chunk
678 if (!hasEmittedRunStarted) {
679 hasEmittedRunStarted = true
680 yield {
681 type: EventType.RUN_STARTED,
682 runId,
683 threadId,
684 model,
685 timestamp: Date.now(),
686 parentRunId: options.parentRunId,
687 }
688 }
689
690 if (chunk.candidates?.[0]?.groundingMetadata) {
691 groundingMetadata = chunk.candidates[0].groundingMetadata
692 }
693
694 if (chunk.candidates?.[0]?.content?.parts) {
695 const parts = chunk.candidates[0].content.parts
696
697 for (const part of parts) {
698 if (part.text) {
699 if (part.thought) {
700 // Emit STEP_STARTED and REASONING events on first thinking content
701 if (!hasEmittedStepStarted) {
702 hasEmittedStepStarted = true
703 stepId = generateId(this.name)
704 reasoningMessageId = generateId(this.name)
705
706 // Spec REASONING events
707 yield {
708 type: EventType.REASONING_START,
709 messageId: reasoningMessageId,
710 model,
711 timestamp: Date.now(),
712 }
713 yield {
714 type: EventType.REASONING_MESSAGE_START,
715 messageId: reasoningMessageId,
716 role: 'reasoning' as const,
717 model,
718 timestamp: Date.now(),
719 }
720
721 // Legacy STEP events (kept during transition)
722 yield {
723 type: EventType.STEP_STARTED,
724 stepName: stepId,
725 stepId,
726 model,
727 timestamp: Date.now(),
728 stepType: 'thinking',
729 }
730 }
731
732 accumulatedThinking += part.text
733
734 // Spec REASONING content event — reasoningMessageId is set in the
735 // hasEmittedStepStarted block above (entered on the same `part.thought` path)
736 if (!reasoningMessageId) continue
737 yield {
738 type: EventType.REASONING_MESSAGE_CONTENT,
739 messageId: reasoningMessageId,
740 delta: part.text,
741 model,
742 timestamp: Date.now(),
743 }
744
745 // Legacy STEP event
746 yield {
747 type: EventType.STEP_FINISHED,
748 stepName: stepId || generateId(this.name),
749 stepId: stepId || generateId(this.name),
750 model,
751 timestamp: Date.now(),
752 delta: part.text,
753 content: accumulatedThinking,
754 }
755 } else if (part.text.trim()) {
756 // Close reasoning before text starts
757 if (reasoningMessageId && !hasClosedReasoning) {
758 hasClosedReasoning = true
759 yield {
760 type: EventType.REASONING_MESSAGE_END,
761 messageId: reasoningMessageId,
762 model,
763 timestamp: Date.now(),
764 }
765 yield {
766 type: EventType.REASONING_END,
767 messageId: reasoningMessageId,
768 model,
769 timestamp: Date.now(),
770 }
771 }
772
773 // Skip whitespace-only text parts (e.g. "\n" during auto-continuation)
774 // Emit TEXT_MESSAGE_START on first text content
775 if (!hasEmittedTextMessageStart) {
776 hasEmittedTextMessageStart = true
777 yield {
778 type: EventType.TEXT_MESSAGE_START,
779 messageId,
780 model,
781 timestamp: Date.now(),
782 role: 'assistant',
783 }
784 }
785
786 accumulatedContent += part.text
787 yield {
788 type: EventType.TEXT_MESSAGE_CONTENT,
789 messageId,
790 model,
791 timestamp: Date.now(),
792 delta: part.text,
793 content: accumulatedContent,
794 }
795 }
796 }
797
798 const functionCall = part.functionCall
799 if (functionCall) {
800 const toolCallId =
801 functionCall.id ||
802 `${functionCall.name}_${Date.now()}_${nextToolIndex}`
803 const functionArgs = functionCall.args || {}
804
805 // Gemini emits thoughtSignature as a Part-level sibling of
806 // functionCall (per @google/genai Part type), not nested inside
807 // functionCall itself.
808 const partThoughtSignature = part.thoughtSignature || undefined
809
810 let toolCallData = toolCallMap.get(toolCallId)
811 if (!toolCallData) {
812 toolCallData = {
813 name: functionCall.name || '',
814 args:
815 typeof functionArgs === 'string'
816 ? functionArgs
817 : JSON.stringify(functionArgs),
818 index: nextToolIndex++,
819 started: false,
820 // Only set thoughtSignature when present — under EOPT, the
821 // optional field cannot accept an explicit `undefined`.
822 ...(partThoughtSignature !== undefined && {
823 thoughtSignature: partThoughtSignature,
824 }),
825 }
826 toolCallMap.set(toolCallId, toolCallData)
827 } else {
828 if (!toolCallData.thoughtSignature && partThoughtSignature) {
829 toolCallData.thoughtSignature = partThoughtSignature
830 }
831 try {
832 const existingArgs = JSON.parse(toolCallData.args)
833 const newArgs =
834 typeof functionArgs === 'string'
835 ? JSON.parse(functionArgs)
836 : functionArgs
837 const mergedArgs = { ...existingArgs, ...newArgs }
838 toolCallData.args = JSON.stringify(mergedArgs)
839 } catch {
840 toolCallData.args =
841 typeof functionArgs === 'string'
842 ? functionArgs
843 : JSON.stringify(functionArgs)
844 }
845 }
846
847 // Emit TOOL_CALL_START if not already started
848 if (!toolCallData.started) {
849 toolCallData.started = true
850 yield {
851 type: EventType.TOOL_CALL_START,
852 toolCallId,
853 toolCallName: toolCallData.name,
854 toolName: toolCallData.name,
855 parentMessageId: messageId,
856 model,
857 timestamp: Date.now(),
858 index: toolCallData.index,
859 ...(toolCallData.thoughtSignature && {
860 metadata: {
861 thoughtSignature: toolCallData.thoughtSignature,
862 } satisfies GeminiToolCallMetadata,
863 }),
864 }
865 }
866
867 // Emit TOOL_CALL_ARGS
868 yield {
869 type: EventType.TOOL_CALL_ARGS,
870 toolCallId,
871 model,
872 timestamp: Date.now(),
873 delta: toolCallData.args,
874 args: toolCallData.args,
875 }
876 }
877 }
878 } else if (chunk.data && chunk.data.trim()) {
879 // Skip whitespace-only data (e.g. "\n" during auto-continuation)
880 // Emit TEXT_MESSAGE_START on first text content
881 if (!hasEmittedTextMessageStart) {
882 hasEmittedTextMessageStart = true
883 yield {
884 type: EventType.TEXT_MESSAGE_START,
885 messageId,
886 model,
887 timestamp: Date.now(),
888 role: 'assistant',
889 }
890 }
891
892 accumulatedContent += chunk.data
893 yield {
894 type: EventType.TEXT_MESSAGE_CONTENT,
895 messageId,
896 model,
897 timestamp: Date.now(),
898 delta: chunk.data,
899 content: accumulatedContent,
900 }
901 }
902
903 if (chunk.candidates?.[0]?.finishReason) {
904 yield* emitGroundingToolCall()
905 const finishReason = chunk.candidates[0].finishReason
906
907 // Emit TOOL_CALL_END for all tracked tool calls. functionCall parts on
908 // this chunk (including UNEXPECTED_TOOL_CALL finishes) were already
909 // registered and started by the per-part loop above.
910 for (const [toolCallId, toolCallData] of toolCallMap.entries()) {
911 let parsedInput: unknown = {}
912 try {
913 const parsed = JSON.parse(toolCallData.args)
914 parsedInput = parsed && typeof parsed === 'object' ? parsed : {}
915 } catch {
916 parsedInput = {}
917 }
918
919 yield {
920 type: EventType.TOOL_CALL_END,
921 toolCallId,
922 toolCallName: toolCallData.name,
923 toolName: toolCallData.name,
924 model,
925 timestamp: Date.now(),
926 input: parsedInput,
927 }
928 }
929
930 // Reset so a new TEXT_MESSAGE_START is emitted if text follows tool calls
931 if (toolCallMap.size > 0) {
932 hasEmittedTextMessageStart = false
933 }
934
935 if (finishReason === FinishReason.MAX_TOKENS) {
936 yield {
937 type: EventType.RUN_ERROR,
938 runId,
939 model,
940 timestamp: Date.now(),
941 message:
942 'The response was cut off because the maximum token limit was reached.',
943 code: 'max_tokens',
944 error: {
945 message:
946 'The response was cut off because the maximum token limit was reached.',
947 code: 'max_tokens',
948 },
949 }
950 }
951
952 // Close reasoning events if still open
953 if (reasoningMessageId && !hasClosedReasoning) {
954 hasClosedReasoning = true
955 yield {
956 type: EventType.REASONING_MESSAGE_END,
957 messageId: reasoningMessageId,
958 model,
959 timestamp: Date.now(),
960 }
961 yield {
962 type: EventType.REASONING_END,
963 messageId: reasoningMessageId,
964 model,
965 timestamp: Date.now(),
966 }
967 }
968
969 // Emit TEXT_MESSAGE_END if we had text content
970 if (hasEmittedTextMessageStart) {
971 yield {
972 type: EventType.TEXT_MESSAGE_END,
973 messageId,
974 model,
975 timestamp: Date.now(),
976 }
977 }
978
979 yield {
980 type: EventType.RUN_FINISHED,
981 runId,
982 threadId,
983 model,
984 timestamp: Date.now(),
985 finishReason: toolCallMap.size > 0 ? 'tool_calls' : 'stop',
986 // RunFinishedEvent.usage is `usage?: {...}` (no `| undefined`) under
987 // exactOptionalPropertyTypes; only include it when usageMetadata is
988 // present rather than assigning an explicit `undefined`.
989 ...(chunk.usageMetadata && {
990 usage: buildGeminiUsage(chunk.usageMetadata),
991 }),
992 }
993 }
994 }
995
996 yield* emitGroundingToolCall()
997 }
998
999 private convertContentPartToGemini(part: ContentPart): Part {
1000 switch (part.type) {
1001 case 'text':
1002 return { text: part.content }
1003 case 'image':
1004 case 'audio':
1005 case 'video':
1006 case 'document': {
1007 // File references (Gemini Files API) and public URLs both pass
1008 // through as `fileData`; Gemini fetches the URI server-side. A
1009 // file source's handle is the file URI (throws when another provider
1010 // issued it).
1011 const fileUri = isFileSource(part.source)
1012 ? fileReferenceFor(part.source, this.name)
1013 : part.source.value
1014 const geminiPart: Part =
1015 part.source.type === 'data'
1016 ? {
1017 inlineData: {
1018 data: part.source.value,
1019 mimeType: part.source.mimeType,
1020 },
1021 }
1022 : {
1023 fileData: {
1024 fileUri,
1025 // For URL sources, use provided mimeType or fall back to
1026 // reasonable defaults.
1027 mimeType:
1028 part.source.mimeType ?? DEFAULT_MEDIA_MIME_TYPES[part.type],
1029 },
1030 }
1031
1032 // Apply single-pass video sampling controls (fps / clip offsets) from
1033 // the part metadata. `processing: 'agentic'` is handled separately via
1034 // the Interactions API and never reaches this generateContent path.
1035 if (part.type === 'video') {
1036 const meta = part.metadata as GeminiVideoMetadata | undefined
1037 const videoMetadata: VideoMetadata = {
1038 ...(meta?.fps !== undefined && { fps: meta.fps }),
1039 ...(meta?.startOffset !== undefined && {
1040 startOffset: meta.startOffset,
1041 }),
1042 ...(meta?.endOffset !== undefined && { endOffset: meta.endOffset }),
1043 }
1044 if (Object.keys(videoMetadata).length > 0) {
1045 geminiPart.videoMetadata = videoMetadata
1046 }
1047 }
1048
1049 return geminiPart
1050 }
1051 default: {
1052 const _exhaustiveCheck: never = part
1053 throw new Error(
1054 `Unsupported content part type: ${(_exhaustiveCheck as ContentPart).type}`,
1055 )
1056 }
1057 }
1058 }
1059
1060 private formatMessages(
1061 messages: Array<ModelMessage>,
1062 ): GenerateContentParameters['contents'] {
1063 // Build a lookup from toolCallId → function name so functionResponse uses the
1064 // correct name instead of the raw call ID.
1065 const toolCallIdToName = new Map<string, string>()
1066 for (const msg of messages) {
1067 if (msg.role === 'assistant' && msg.toolCalls) {
1068 for (const tc of msg.toolCalls) {
1069 toolCallIdToName.set(tc.id, tc.function.name)
1070 }
1071 }
1072 }
1073
1074 const formatted = messages.map((msg) => {
1075 const role: 'user' | 'model' = msg.role === 'assistant' ? 'model' : 'user'
1076 const parts: Array<Part> = []
1077
1078 if (Array.isArray(msg.content)) {
1079 for (const contentPart of msg.content) {
1080 parts.push(this.convertContentPartToGemini(contentPart))
1081 }
1082 } else if (msg.content && msg.role !== 'tool') {
1083 parts.push({ text: msg.content })
1084 }
1085
1086 if (msg.role === 'assistant' && msg.toolCalls?.length) {
1087 for (const toolCall of msg.toolCalls) {
1088 const metadata = toolCall.metadata as
1089 | GeminiToolCallMetadata
1090 | undefined
1091 if (metadata?.providerExecuted) continue
1092
1093 let parsedArgs: Record<string, unknown> = {}
1094 try {
1095 parsedArgs = toolCall.function.arguments
1096 ? (JSON.parse(toolCall.function.arguments) as Record<
1097 string,
1098 unknown
1099 >)
1100 : {}
1101 } catch {
1102 parsedArgs = {}
1103 }
1104
1105 const thoughtSignature = metadata?.thoughtSignature
1106 // Gemini requires thoughtSignature at the Part level (sibling of
1107 // functionCall), not nested inside functionCall. Nesting it causes
1108 // the API to reject the next turn with
1109 // "Function call is missing a thought_signature".
1110 const part: Part = {
1111 functionCall: {
1112 id: toolCall.id,
1113 name: toolCall.function.name,
1114 args: parsedArgs,
1115 },
1116 }
1117 if (thoughtSignature) {
1118 part.thoughtSignature = thoughtSignature
1119 }
1120 parts.push(part)
1121 }
1122 }
1123
1124 if (msg.role === 'tool' && msg.toolCallId) {
1125 const functionName =
1126 toolCallIdToName.get(msg.toolCallId) || msg.toolCallId
1127 const toolContent = msg.content
1128 if (Array.isArray(toolContent)) {
1129 const textChunks: Array<string> = []
1130 const mediaParts: Array<Part> = []
1131 for (const part of toolContent) {
1132 if (part.type === 'text') {
1133 textChunks.push(part.content)
1134 } else if (part.source.type === 'data') {
1135 mediaParts.push({
1136 inlineData: {
1137 data: part.source.value,
1138 mimeType: part.source.mimeType,
1139 },
1140 })
1141 } else {
1142 const fileUri = isFileSource(part.source)
1143 ? fileReferenceFor(part.source, this.name)
1144 : part.source.value
1145 const defaultMimeType = {
1146 image: 'image/jpeg',
1147 audio: 'audio/mp3',
1148 video: 'video/mp4',
1149 document: 'application/pdf',
1150 }[part.type]
1151 mediaParts.push({
1152 fileData: {
1153 fileUri,
1154 mimeType: part.source.mimeType ?? defaultMimeType,
1155 },
1156 })
1157 }
1158 }
1159 parts.push({
1160 functionResponse: {
1161 id: msg.toolCallId,
1162 name: functionName,
1163 response: { content: textChunks.join('\n') },
1164 ...(mediaParts.length > 0 && { parts: mediaParts }),
1165 },
1166 })
1167 } else {
1168 parts.push({
1169 functionResponse: {
1170 id: msg.toolCallId,
1171 name: functionName,
1172 response: { content: toolContent || '' },
1173 },
1174 })
1175 }
1176 }
1177
1178 return {
1179 role,
1180 parts: parts.length > 0 ? parts : [{ text: '' }],
1181 }
1182 })
1183
1184 // Post-process: Gemini requires strictly alternating user/model roles.
1185 // Tool results are mapped to role:'user', which can create consecutive
1186 // user messages when followed by a new user message. Merge them.
1187 return this.mergeConsecutiveSameRoleMessages(formatted)
1188 }
1189
1190 /**
1191 * Merge consecutive messages of the same role into a single message.
1192 * Gemini's API requires strictly alternating user/model roles.
1193 * Tool results are mapped to role:'user', which can collide with actual
1194 * user messages in multi-turn conversations.
1195 *
1196 * Also filters out empty model messages (e.g., from a previous failed request)
1197 * and deduplicates functionResponse parts with the same id (tool call ID).
1198 */
1199 private mergeConsecutiveSameRoleMessages(
1200 messages: Array<Content>,
1201 ): Array<Content> {
1202 const merged: Array<Content> = []
1203
1204 for (const msg of messages) {
1205 const parts = msg.parts || []
1206
1207 // Skip empty model messages (no parts or only empty text)
1208 if (msg.role === 'model') {
1209 const hasContent =
1210 parts.length > 0 &&
1211 !parts.every(
1212 (p) => 'text' in p && (p as { text: string }).text === '',
1213 )
1214 if (!hasContent) {
1215 continue
1216 }
1217 }
1218
1219 const prev = merged[merged.length - 1]
1220 if (prev && prev.role === msg.role) {
1221 // Merge parts arrays
1222 prev.parts = [...(prev.parts || []), ...parts]
1223 } else {
1224 merged.push({ ...msg, parts: [...parts] })
1225 }
1226 }
1227
1228 // Deduplicate functionResponse parts with the same id (tool call ID).
1229 // Two parallel calls to the *same* tool share a `name` but have distinct
1230 // `id`s — keying on `name` dropped every response but the first for
1231 // same-tool parallel calls, leaving Gemini with fewer response parts
1232 // than call parts and a 400 on the next request.
1233 for (const msg of merged) {
1234 if (!msg.parts) continue
1235 const seenFunctionResponseIds = new Set<string>()
1236 msg.parts = msg.parts.filter((part) => {
1237 if ('functionResponse' in part && part.functionResponse?.id) {
1238 if (seenFunctionResponseIds.has(part.functionResponse.id)) {
1239 return false
1240 }
1241 seenFunctionResponseIds.add(part.functionResponse.id)
1242 }
1243 return true
1244 })
1245 }
1246
1247 return merged
1248 }
1249
1250 private mapCommonOptionsToGemini(
1251 options: TextOptions<GeminiTextProviderOptions>,
1252 ) {
1253 // Separate `thinkingConfig` from the other model options so the loose
1254 // local `thinkingLevel?: keyof typeof ThinkingLevel` type doesn't leak
1255 // into the SDK config object via the `...modelOpts` spread — we re-add a
1256 // properly-typed `ThinkingConfig` below.
1257 const { thinkingConfig, ...modelOpts } = options.modelOptions ?? {}
1258 // Build the thinkingConfig payload only when the caller actually supplied
1259 // one. Our local `thinkingLevel` is typed as `keyof typeof ThinkingLevel`
1260 // (string union) so users can pass plain strings; the SDK target is the
1261 // `ThinkingLevel` enum, and every field is `field?: T` under EOPT — so we
1262 // re-emit fields via conditional spreads.
1263 const mappedThinkingConfig = thinkingConfig
1264 ? {
1265 ...(thinkingConfig.includeThoughts !== undefined && {
1266 includeThoughts: thinkingConfig.includeThoughts,
1267 }),
1268 ...(thinkingConfig.thinkingBudget !== undefined && {
1269 thinkingBudget: thinkingConfig.thinkingBudget,
1270 }),
1271 ...(thinkingConfig.thinkingLevel
1272 ? {
1273 thinkingLevel: thinkingConfig.thinkingLevel as ThinkingLevel,
1274 }
1275 : {}),
1276 }
1277 : undefined
1278
1279 const normalizedPrompts = normalizeSystemPrompts(options.systemPrompts)
1280 const systemInstruction =
1281 normalizedPrompts.length > 0
1282 ? normalizedPrompts.map((p) => p.content).join('\n')
1283 : undefined
1284
1285 // Native combined mode (issue #605): when the engine threads
1286 // `outputSchema` through TextOptions, the adapter declared
1287 // `supportsCombinedToolsAndSchema` (Gemini 3.x only). The schema is
1288 // already JSON Schema (pre-converted at the activity boundary). Wire
1289 // it into `config.responseSchema` + `responseMimeType: 'application/json'`
1290 // alongside any `tools` — the model emits function calls during the
1291 // agent loop and the schema-constrained JSON on its natural final
1292 // turn, so the engine can harvest it without the separate
1293 // `structuredOutput` finalization round-trip.
1294 const combinedSchema = options.outputSchema as
1295 | Record<string, unknown>
1296 | undefined
1297 const combinedSchemaConfig = combinedSchema
1298 ? {
1299 responseMimeType: 'application/json' as const,
1300 responseSchema: combinedSchema,
1301 }
1302 : undefined
1303
1304 // Vendor `GenerateContentConfig` fields are `field?: T` (no `| undefined`)
1305 // under EOPT, so spread each common option only when present rather than
1306 // emitting `field: undefined`s into the wire payload.
1307 const requestOptions: GenerateContentParameters = {
1308 model: options.model,
1309 contents: this.formatMessages(options.messages),
1310 config: {
1311 ...modelOpts,
1312 ...(mappedThinkingConfig !== undefined && {
1313 thinkingConfig: mappedThinkingConfig,
1314 }),
1315 ...(systemInstruction !== undefined && { systemInstruction }),
1316 tools: convertToolsToProviderFormat(options.tools),
1317 ...(combinedSchemaConfig ?? {}),
1318 // Forward the caller's abort signal so cancellation reaches the SDK
1319 // request, matching the OpenAI-compatible adapters (issue #1374).
1320 ...(options.request?.signal != null && {
1321 abortSignal: options.request.signal,
1322 }),
1323 },
1324 }
1325
1326 return requestOptions
1327 }
1328
1329 /**
1330 * Gemini 3.x natively combines `tools` + `responseSchema` in a single
1331 * streaming `generateContentStream` call (issue #605). Gemini 2.x is
1332 * documented as brittle for the combination and keeps the engine's
1333 * legacy finalization path.
1334 */
1335 supportsCombinedToolsAndSchema(): boolean {
1336 return GEMINI_COMBINED_TOOLS_AND_SCHEMA_MODELS.has(this.model)
1337 }
1338}
1339
1340function jsonContentParseError(rawText: string, label: string) {
1341 const snippet = rawText.slice(0, 200)
1342 const ellipsis = rawText.length > 200 ? '...' : ''
1343 return `Failed to parse ${label} as JSON. Content: ${snippet}${ellipsis}`
1344}
1345
1346function structuredStreamError(
1347 options: TextOptions<GeminiTextProviderOptions>,
1348 message: string,
1349 code: string,
1350): Extract<AdapterYieldChunk, { type: typeof EventType.RUN_ERROR }> {
1351 return {
1352 type: EventType.RUN_ERROR,
1353 runId: options.runId,
1354 model: options.model,
1355 timestamp: Date.now(),
1356 message,
1357 code,
1358 error: { message, code },
1359 }
1360}
1361
1362/**
1363 * Creates a Gemini text adapter with explicit API key.
1364 * Type resolution happens here at the call site.
1365 */
1366export function createGeminiChat<TModel extends (typeof GEMINI_MODELS)[number]>(
1367 model: TModel,
1368 apiKey: string,
1369 config?: Omit<GeminiTextConfig, 'apiKey'>,
1370): GeminiTextAdapter<
1371 TModel,
1372 ResolveProviderOptions<TModel>,
1373 ResolveInputModalities<TModel>,
1374 ResolveToolCapabilities<TModel>
1375> {
1376 return new GeminiTextAdapter({ apiKey, ...config }, model)
1377}
1378
1379/**
1380 * Creates a Gemini text adapter with automatic API key detection.
1381 * Type resolution happens here at the call site.
1382 */
1383export function geminiText<TModel extends (typeof GEMINI_MODELS)[number]>(
1384 model: TModel,
1385 config?: Omit<GeminiTextConfig, 'apiKey'>,
1386): GeminiTextAdapter<
1387 TModel,
1388 ResolveProviderOptions<TModel>,
1389 ResolveInputModalities<TModel>,
1390 ResolveToolCapabilities<TModel>
1391> {
1392 const apiKey = getGeminiApiKeyFromEnv()
1393 return createGeminiChat(model, apiKey, config)
1394}