@tanstack/ai-gemini 0.20.0 → 0.21.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (62) hide show
  1. package/README.md +15 -1
  2. package/dist/esm/adapters/audio.js +113 -61
  3. package/dist/esm/adapters/audio.js.map +1 -1
  4. package/dist/esm/adapters/image.js +224 -225
  5. package/dist/esm/adapters/image.js.map +1 -1
  6. package/dist/esm/adapters/summarize.js +33 -12
  7. package/dist/esm/adapters/summarize.js.map +1 -1
  8. package/dist/esm/adapters/text.js +574 -650
  9. package/dist/esm/adapters/text.js.map +1 -1
  10. package/dist/esm/adapters/tts.js +197 -178
  11. package/dist/esm/adapters/tts.js.map +1 -1
  12. package/dist/esm/adapters/video.js +456 -409
  13. package/dist/esm/adapters/video.js.map +1 -1
  14. package/dist/esm/experimental/index.js +1 -6
  15. package/dist/esm/experimental/text-interactions/adapter.js +877 -1014
  16. package/dist/esm/experimental/text-interactions/adapter.js.map +1 -1
  17. package/dist/esm/image/image-provider-options.js +74 -54
  18. package/dist/esm/image/image-provider-options.js.map +1 -1
  19. package/dist/esm/index.js +4 -36
  20. package/dist/esm/model-meta.d.ts +53 -5
  21. package/dist/esm/model-meta.js +733 -129
  22. package/dist/esm/model-meta.js.map +1 -1
  23. package/dist/esm/realtime/adapter.js +242 -228
  24. package/dist/esm/realtime/adapter.js.map +1 -1
  25. package/dist/esm/realtime/client.js +314 -381
  26. package/dist/esm/realtime/client.js.map +1 -1
  27. package/dist/esm/realtime/index.js +3 -0
  28. package/dist/esm/realtime/token.js +50 -36
  29. package/dist/esm/realtime/token.js.map +1 -1
  30. package/dist/esm/realtime/utils.js +202 -245
  31. package/dist/esm/realtime/utils.js.map +1 -1
  32. package/dist/esm/tools/code-execution-tool.js +11 -13
  33. package/dist/esm/tools/code-execution-tool.js.map +1 -1
  34. package/dist/esm/tools/computer-use-tool.js +18 -28
  35. package/dist/esm/tools/computer-use-tool.js.map +1 -1
  36. package/dist/esm/tools/file-search-tool.js +11 -14
  37. package/dist/esm/tools/file-search-tool.js.map +1 -1
  38. package/dist/esm/tools/function-declaration-tool.js +11 -25
  39. package/dist/esm/tools/function-declaration-tool.js.map +1 -1
  40. package/dist/esm/tools/google-maps-tool.js +11 -14
  41. package/dist/esm/tools/google-maps-tool.js.map +1 -1
  42. package/dist/esm/tools/google-search-retriveal-tool.js +11 -14
  43. package/dist/esm/tools/google-search-retriveal-tool.js.map +1 -1
  44. package/dist/esm/tools/google-search-tool.js +11 -14
  45. package/dist/esm/tools/google-search-tool.js.map +1 -1
  46. package/dist/esm/tools/index.js +2 -13
  47. package/dist/esm/tools/tool-converter.js +64 -57
  48. package/dist/esm/tools/tool-converter.js.map +1 -1
  49. package/dist/esm/tools/url-context-tool.js +11 -13
  50. package/dist/esm/tools/url-context-tool.js.map +1 -1
  51. package/dist/esm/usage.js +81 -87
  52. package/dist/esm/usage.js.map +1 -1
  53. package/dist/esm/utils/client.js +31 -24
  54. package/dist/esm/utils/client.js.map +1 -1
  55. package/dist/esm/utils/index.js +2 -0
  56. package/dist/esm/video/video-provider-options.js +73 -20
  57. package/dist/esm/video/video-provider-options.js.map +1 -1
  58. package/package.json +7 -7
  59. package/src/model-meta.ts +120 -10
  60. package/dist/esm/experimental/index.js.map +0 -1
  61. package/dist/esm/index.js.map +0 -1
  62. package/dist/esm/tools/index.js.map +0 -1
@@ -1 +1 @@
1
- {"version":3,"file":"adapter.js","sources":["../../../../src/experimental/text-interactions/adapter.ts"],"sourcesContent":["import { EventType } from '@tanstack/ai'\nimport { BaseTextAdapter } from '@tanstack/ai/adapters'\nimport { parse as parsePartialJSON } from 'partial-json'\nimport {\n createGeminiClient,\n generateId,\n getGeminiApiKeyFromEnv,\n} from '../../utils/client'\nimport type { InternalLogger } from '@tanstack/ai/adapter-internals'\nimport type {\n GeminiChatModelToolCapabilitiesByName,\n GeminiModelInputModalitiesByName,\n GeminiModels,\n} from '../../model-meta'\nimport type {\n StructuredOutputOptions,\n StructuredOutputResult,\n} from '@tanstack/ai/adapters'\nimport type { GoogleGenAI, Interactions } from '@google/genai'\nimport type {\n ContentPart,\n Modality,\n ModelMessage,\n StreamChunk,\n TextOptions,\n Tool,\n} from '@tanstack/ai'\n\nimport type {\n GeminiInteractionsCustomEvent,\n GeminiInteractionsCustomEventValue,\n GeminiInteractionsStream,\n} from './events'\nimport type { ExternalTextInteractionsProviderOptions } from './provider-options'\nimport type { GeminiMessageMetadataByModality } from '../../message-types'\nimport type { GeminiClientConfig } from '../../utils/client'\n\ntype Interaction = Interactions.Interaction\ntype InteractionSSEEvent = Interactions.InteractionSSEEvent\n\nexport type GeminiTextInteractionsConfig = GeminiClientConfig\n\nexport type GeminiTextInteractionsProviderOptions =\n ExternalTextInteractionsProviderOptions\n\ntype InteractionsTool = NonNullable<\n Interactions.CreateModelInteractionParamsStreaming['tools']\n>[number]\n\ntype ContentBlock = Interactions.Content\n\n// The Interactions API takes `input` as a list of *Steps* (not a list of\n// content blocks, and not a list of `Turn`s — the SDK's type union is\n// misleading on both counts). The live API enforces the Step envelope —\n// raw content arrays produce `invalid_request` / \"value at top-level\n// must be a list\". The wire discriminator is snake_case\n// (`user_input` / `function_result`); see\n// https://ai.google.dev/api/interactions-api for the full Step union.\ntype UserInputStep = {\n type: 'user_input'\n content: Array<ContentBlock>\n}\ntype FunctionResultStep = {\n type: 'function_result'\n call_id: string\n name?: string\n result: string\n}\ntype InteractionsStep = UserInputStep | FunctionResultStep\ntype InteractionsRequestInput = Array<InteractionsStep>\n\n// Concrete wire shape we send to `client.interactions.create`. The SDK's\n// own param union types `input` as `string | Content[] | Turn[] | ...`\n// which is wrong for the live API (see the InteractionsRequestInput\n// comment above), so we type `input` ourselves and cast just once at the\n// SDK boundary instead of casting every field through.\ntype GeminiInteractionsRequestBody = Omit<\n Interactions.CreateModelInteractionParamsStreaming,\n 'input' | 'stream'\n> & {\n input: InteractionsRequestInput\n stream?: boolean\n}\n\ntype ToolCallState = {\n name: string\n // Accumulated args as a parsed object. Kept here in object form so a\n // garbled delta can't corrupt previously-merged fragments (the prior\n // string-then-reparse pipeline replaced the whole accumulator on any\n // parse failure). Stringified only when emitting AG-UI events.\n args: Record<string, unknown>\n index: number\n started: boolean\n ended: boolean\n}\n\n// ===========================\n// Type Resolution Helpers\n// ===========================\n\n/**\n * Resolve provider options for a specific model. The Interactions API's\n * request shape is the same across all chat-capable Gemini models — the\n * SDK doesn't expose a per-model param union — so this currently falls\n * through to the flat `GeminiTextInteractionsProviderOptions` for every\n * model. The alias exists for parity with `GeminiTextAdapter`, so a\n * per-model map can be slotted in later without changing the adapter\n * signature.\n */\ntype ResolveProviderOptions = GeminiTextInteractionsProviderOptions\n\n/**\n * Resolve input modalities for a specific model. Reuses the chat-model\n * modality map from `model-meta.ts`: passing a `document` content block\n * to a model that doesn't support it is a compile error, matching the\n * sibling `GeminiTextAdapter`.\n */\ntype ResolveInputModalities<TModel extends string> =\n TModel extends keyof GeminiModelInputModalitiesByName\n ? GeminiModelInputModalitiesByName[TModel]\n : readonly ['text', 'image', 'audio', 'video', 'document']\n\n/**\n * Resolve tool capabilities for a specific model. Reuses the chat-model\n * capability map: `google_maps` / `google_search_retrieval` /\n * `mcp_server` are rejected at runtime by `convertToolsToInteractionsFormat`,\n * but per-model gating happens here at compile time.\n */\ntype ResolveToolCapabilities<TModel extends string> =\n TModel extends keyof GeminiChatModelToolCapabilitiesByName\n ? NonNullable<GeminiChatModelToolCapabilitiesByName[TModel]>\n : readonly []\n\n/**\n * Tree-shakeable adapter for Gemini's stateful Interactions API. Routes\n * through `client.interactions.create` and surfaces the server-assigned\n * `interactionId` via an AG-UI `CUSTOM` event with\n * `name: 'gemini.interactionId'` emitted just before `RUN_FINISHED`; pass\n * that id back on the next turn via `modelOptions.previous_interaction_id`\n * to continue the conversation without resending history.\n *\n * The Interactions API does NOT support stateless multi-turn replay —\n * passing more than one message in `messages` without a\n * `previous_interaction_id` throws. For a chat UI that maintains local\n * history (e.g. `useChat`), see the \"Wiring with `useChat`\" section of\n * `docs/adapters/gemini.md` for the canonical client/server pattern.\n *\n * Supports user-defined function tools and the built-in tools\n * `google_search`, `code_execution`, `url_context`, `file_search`, and\n * `computer_use`. Built-in tool *activity* for the four search/exec\n * variants is surfaced via `CUSTOM` events\n * (`gemini.googleSearchCall` / `gemini.googleSearchResult` and the\n * corresponding per-tool variants) carrying the raw Interactions delta;\n * see {@link GeminiInteractionsCustomEvent}. `computer_use` is accepted\n * in the request but the Interactions API does not currently stream\n * per-delta CUSTOM events for it. `google_search_retrieval`,\n * `google_maps`, and `mcp_server` are not supported on this adapter.\n *\n * @experimental Interactions API is in Beta per Google; shapes may change.\n * @see https://ai.google.dev/gemini-api/docs/interactions\n */\nexport class GeminiTextInteractionsAdapter<\n TModel extends GeminiModels,\n TProviderOptions extends Record<string, any> = ResolveProviderOptions,\n TInputModalities extends ReadonlyArray<Modality> =\n ResolveInputModalities<TModel>,\n TToolCapabilities extends ReadonlyArray<string> =\n ResolveToolCapabilities<TModel>,\n> extends BaseTextAdapter<\n TModel,\n TProviderOptions,\n TInputModalities,\n GeminiMessageMetadataByModality,\n TToolCapabilities\n> {\n override readonly kind = 'text' as const\n override readonly name = 'gemini-text-interactions' as const\n\n private readonly client: GoogleGenAI\n // Tracks the most recent server-assigned interaction id per threadId\n // so the adapter can chain follow-up calls on the same thread without\n // the caller having to thread the id manually. Two callers rely on\n // this:\n // 1. The agent loop's tool-call iterations (each iteration is a new\n // `chatStream` call with accumulated tool messages).\n // 2. The agentic-structured composition: a `chatStream` run followed\n // by `structuredOutput` on the accumulated messages.\n // Cross-request chaining is the caller's job via\n // `modelOptions.previous_interaction_id`. To keep stale ids from\n // chaining a brand-new turn, `chatStream` evicts at the START when\n // the caller signals fresh-turn intent (no caller-provided id AND a\n // single user message — anything else is a follow-up). Errors evict\n // immediately so a failed turn never chains into the next one.\n private readonly interactionIdByThread = new Map<string, string>()\n\n constructor(config: GeminiTextInteractionsConfig, model: TModel) {\n super({}, model)\n this.client = createGeminiClient(config)\n }\n\n async *chatStream(\n options: TextOptions<GeminiTextInteractionsProviderOptions>,\n ): AsyncIterable<StreamChunk> {\n const runId = options.runId ?? generateId(this.name)\n const threadId = options.threadId ?? generateId(this.name)\n const timestamp = Date.now()\n const { logger } = options\n\n // Fresh-turn intent: caller didn't thread an id AND only a single\n // user message is queued. Drop any stale captured id so we don't\n // silently chain off a prior turn the caller doesn't know about.\n // Multi-message inputs are follow-ups (agent-loop iteration or\n // structuredOutput composition) and keep the Map entry.\n if (\n !options.modelOptions?.previous_interaction_id &&\n options.messages.length === 1 &&\n options.messages[0]?.role === 'user'\n ) {\n this.interactionIdByThread.delete(threadId)\n }\n\n // Resolve `previous_interaction_id`. Caller-provided wins; otherwise\n // fall back to the id we captured during a prior iteration of this\n // same agent-loop run (matched by threadId).\n const effectivePreviousInteractionId =\n options.modelOptions?.previous_interaction_id ??\n this.interactionIdByThread.get(threadId)\n\n let sawTerminalEvent = false\n // Sentinel for the `.return()` abandonment path. Set to `true` only at\n // the bottom of the `try` block — so a consumer-initiated close (via\n // upstream `break` or abort) leaves it `false`, distinguishing\n // abandonment from normal completion. This is the only signal that\n // catches abandonment AFTER a `RUN_FINISHED(tool_calls)`, where\n // `sawTerminalEvent` is `true` but the in-loop deliberately kept the\n // map entry for an agent-loop iteration that will now never run.\n let completedTryBlock = false\n try {\n const request = buildInteractionsRequest({\n ...options,\n modelOptions: {\n ...options.modelOptions,\n previous_interaction_id: effectivePreviousInteractionId,\n },\n })\n logger.request(\n `activity=chat provider=gemini-text-interactions model=${this.model} messages=${options.messages.length} tools=${options.tools?.length ?? 0} stream=true`,\n {\n provider: 'gemini-text-interactions',\n model: this.model,\n request,\n },\n )\n const stream = (await this.client.interactions.create(\n { ...request, stream: true } as GeminiInteractionsRequestBody &\n Parameters<typeof this.client.interactions.create>[0],\n { signal: options.abortController?.signal },\n )) as AsyncIterable<InteractionSSEEvent>\n\n for await (const chunk of translateInteractionEvents(\n stream,\n options.model,\n runId,\n threadId,\n options.parentRunId,\n timestamp,\n this.name,\n logger,\n )) {\n // Capture the server-assigned id so the next agent-loop\n // iteration on this thread can chain off it. The CUSTOM event\n // is also yielded downstream as usual — callers consume it via\n // `onCustomEvent` for cross-request chaining.\n //\n // The yield type can't be narrowed to GeminiInteractionsStream\n // here without fighting zod-passthrough variance (StreamChunk's\n // CustomEvent variant carries `[k: string]: unknown`), so we\n // narrow via the literal `name` and trust the typed\n // construction inside `translateInteractionEvents`.\n if (\n chunk.type === EventType.CUSTOM &&\n chunk.name === 'gemini.interactionId'\n ) {\n const value =\n chunk.value as GeminiInteractionsCustomEventValue<'gemini.interactionId'>\n this.interactionIdByThread.set(threadId, value.interactionId)\n }\n if (chunk.type === EventType.RUN_FINISHED) {\n sawTerminalEvent = true\n // Keep the captured id for follow-ups (next agent-loop\n // iteration OR a structuredOutput call composing this turn).\n // The next *fresh* chatStream call evicts at the top via the\n // fresh-turn guard.\n } else if (chunk.type === EventType.RUN_ERROR) {\n sawTerminalEvent = true\n this.interactionIdByThread.delete(threadId)\n }\n yield chunk\n }\n\n if (!sawTerminalEvent) {\n // SDK stream ended without either `interaction.complete` or\n // `error` — surface the truncation rather than silently leaving\n // downstream consumers waiting on a `RUN_FINISHED` that will\n // never come.\n this.interactionIdByThread.delete(threadId)\n const message =\n 'Gemini Interactions stream ended without a terminal event (no interaction.complete or error)'\n logger.errors('gemini-text-interactions.chatStream truncated', {\n source: 'gemini-text-interactions.chatStream',\n runId,\n threadId,\n })\n yield {\n type: EventType.RUN_ERROR,\n runId,\n model: options.model,\n timestamp,\n message,\n error: { message },\n }\n }\n completedTryBlock = true\n } catch (error) {\n this.interactionIdByThread.delete(threadId)\n const message =\n error instanceof Error\n ? error.message\n : 'An unknown error occurred during the interactions stream.'\n logger.errors('gemini-text-interactions.chatStream fatal', {\n error,\n source: 'gemini-text-interactions.chatStream',\n })\n yield {\n type: EventType.RUN_ERROR,\n runId,\n model: options.model,\n timestamp,\n message,\n error: { message },\n }\n } finally {\n // Abandonment cleanup — consumer `.return()` (upstream `break` /\n // abort) bypasses both the truncation guard and the catch handler.\n // `completedTryBlock` is the sentinel that distinguishes natural\n // completion from abandonment; on abandonment we evict so a stale\n // id from a half-finished turn can't chain into a follow-up. The\n // catch handler also lands here with the flag false; its explicit\n // delete is harmless to repeat.\n if (!completedTryBlock) {\n this.interactionIdByThread.delete(threadId)\n }\n }\n }\n\n async structuredOutput(\n options: StructuredOutputOptions<GeminiTextInteractionsProviderOptions>,\n ): Promise<StructuredOutputResult<unknown>> {\n const { chatOptions, outputSchema } = options\n const { logger } = chatOptions\n const threadId = chatOptions.threadId\n\n // Mirror the chatStream fallback: the agentic-structured flow runs\n // the chat loop first and then calls structuredOutput with the\n // accumulated `messages`. If any tool ran during the loop, the\n // messages include assistant/tool turns; without a chained\n // previous_interaction_id those would throw \"cannot send prior\n // conversation history on a fresh interaction\".\n const effectivePreviousInteractionId =\n chatOptions.modelOptions?.previous_interaction_id ??\n (threadId ? this.interactionIdByThread.get(threadId) : undefined)\n\n const baseRequest = buildInteractionsRequest({\n ...chatOptions,\n modelOptions: {\n ...chatOptions.modelOptions,\n previous_interaction_id: effectivePreviousInteractionId,\n },\n })\n\n // SDK 2.x: `response_mime_type` has been removed and `response_format`\n // is now polymorphic — each entry has a `type` discriminator and the\n // mime type lives inside the entry. See:\n // https://ai.google.dev/gemini-api/docs/interactions-breaking-changes-may-2026\n const request: GeminiInteractionsRequestBody = {\n ...baseRequest,\n response_format: {\n type: 'text',\n mime_type: 'application/json',\n schema: outputSchema,\n },\n }\n\n try {\n logger.request(\n `activity=chat provider=gemini-text-interactions model=${this.model} messages=${chatOptions.messages.length} tools=${chatOptions.tools?.length ?? 0} stream=false`,\n {\n provider: 'gemini-text-interactions',\n model: this.model,\n request,\n },\n )\n const result = (await this.client.interactions.create(\n request as Parameters<typeof this.client.interactions.create>[0],\n { signal: chatOptions.abortController?.signal },\n )) as Interaction\n\n const rawText = extractTextFromInteraction(result)\n\n if (!rawText) {\n throw new Error(\n `Gemini Interactions returned no text output for structured-output request (status: ${result.status}). The model may have produced only tool calls or non-text content.`,\n )\n }\n\n let parsed: unknown\n try {\n parsed = JSON.parse(rawText)\n } catch {\n throw new Error(\n `Failed to parse structured output as JSON. Content: ${rawText.slice(0, 200)}${rawText.length > 200 ? '...' : ''}`,\n )\n }\n\n return { data: parsed, rawText }\n } catch (error) {\n logger.errors('gemini-text-interactions.structuredOutput fatal', {\n error,\n source: 'gemini-text-interactions.structuredOutput',\n })\n // Preserve the original error as `cause` so the stack trace and any\n // SDK-attached status/code/headers survive for Sentry dedup.\n throw new Error(\n error instanceof Error\n ? error.message\n : 'An unknown error occurred during structured output generation.',\n { cause: error },\n )\n }\n }\n}\n\n/** @experimental Interactions API is in Beta. */\nexport function createGeminiTextInteractions<TModel extends GeminiModels>(\n model: TModel,\n apiKey: string,\n config?: Omit<GeminiTextInteractionsConfig, 'apiKey'>,\n): GeminiTextInteractionsAdapter<\n TModel,\n ResolveProviderOptions,\n ResolveInputModalities<TModel>,\n ResolveToolCapabilities<TModel>\n> {\n return new GeminiTextInteractionsAdapter({ apiKey, ...config }, model)\n}\n\n/** @experimental Interactions API is in Beta. */\nexport function geminiTextInteractions<TModel extends GeminiModels>(\n model: TModel,\n config?: Omit<GeminiTextInteractionsConfig, 'apiKey'>,\n): GeminiTextInteractionsAdapter<\n TModel,\n ResolveProviderOptions,\n ResolveInputModalities<TModel>,\n ResolveToolCapabilities<TModel>\n> {\n const apiKey = getGeminiApiKeyFromEnv()\n return createGeminiTextInteractions(model, apiKey, config)\n}\n\nfunction buildInteractionsRequest(\n options: TextOptions<GeminiTextInteractionsProviderOptions>,\n): GeminiInteractionsRequestBody {\n const modelOpts = options.modelOptions\n\n const systemInstruction =\n modelOpts?.system_instruction ?? options.systemPrompts?.join('\\n')\n\n const generationConfig: Interactions.GenerationConfig = {\n ...modelOpts?.generation_config,\n }\n\n const hasGenerationConfig = Object.keys(generationConfig).length > 0\n\n const input = convertMessagesToInteractionsInput(\n options.messages,\n modelOpts?.previous_interaction_id !== undefined,\n )\n\n return {\n model: options.model,\n input,\n previous_interaction_id: modelOpts?.previous_interaction_id,\n system_instruction: systemInstruction,\n tools: convertToolsToInteractionsFormat(options.tools),\n generation_config: hasGenerationConfig ? generationConfig : undefined,\n store: modelOpts?.store,\n background: modelOpts?.background,\n response_modalities: modelOpts?.response_modalities,\n response_format: modelOpts?.response_format,\n }\n}\n\n// Google's Interactions API takes `input` as `Array<Step>`. Each Step\n// is `{type: 'user_input' | 'function_result' | ..., ...}` — content\n// blocks (text/image/etc.) live nested inside a Step's `content` array,\n// they are NOT valid at the top level. Sending raw `Array<Content>`\n// produces `invalid_request` / \"value at top-level must be a list\",\n// because the API is looking for a Step list at the top level and\n// gets content objects instead. The SDK's type union\n// (`string | Array<Content> | Array<Turn> | ...`) is misleading; see\n// https://ai.google.dev/api/interactions-api for the real Step union.\n//\n// When `hasPreviousInteraction` is true the server holds the transcript\n// up through the last assistant turn, so we only send the steps that\n// come after it (a new `user_input`, one or more `function_result`s\n// continuing a tool call, etc.). Otherwise the conversation is fresh\n// and only the latest user turn is supported — multi-turn replay\n// without `previous_interaction_id` is not part of the API contract.\nfunction convertMessagesToInteractionsInput(\n messages: Array<ModelMessage>,\n hasPreviousInteraction: boolean,\n): InteractionsRequestInput {\n const toolCallIdToName = new Map<string, string>()\n for (const msg of messages) {\n if (msg.role === 'assistant' && msg.toolCalls) {\n for (const tc of msg.toolCalls) {\n toolCallIdToName.set(tc.id, tc.function.name)\n }\n }\n }\n\n const source = hasPreviousInteraction\n ? messagesAfterLastAssistant(messages)\n : messages\n\n if (hasPreviousInteraction && source.length === 0) {\n throw new Error(\n 'Gemini Interactions adapter: modelOptions.previous_interaction_id was provided but no new messages were found after the last assistant turn. Append at least one user or tool message before chaining.',\n )\n }\n\n if (!hasPreviousInteraction) {\n const [only, ...rest] = source\n if (!only) {\n throw new Error('Gemini Interactions adapter: no messages to send.')\n }\n if (rest.length > 0) {\n throw new Error(\n 'Gemini Interactions adapter: cannot send prior conversation history on a fresh interaction. Either set modelOptions.previous_interaction_id to chain prior turns server-side, or trim the message list to a single new user turn. See docs/adapters/gemini.md (\"Wiring with useChat\") for the canonical client/server pattern.',\n )\n }\n if (only.role !== 'user') {\n throw new Error(\n `Gemini Interactions adapter: the first message of a fresh interaction must be a user turn (got role=\"${only.role}\"). Set modelOptions.previous_interaction_id to continue an existing interaction.`,\n )\n }\n const content = messageToContentBlocks(only)\n if (content.length === 0) {\n throw new Error(\n 'Gemini Interactions adapter: the user message produced no content blocks to send.',\n )\n }\n return [{ type: 'user_input', content }]\n }\n\n // Chained path: each post-assistant message becomes one Step. A user\n // reply maps to `user_input`; a tool reply maps to `function_result`.\n // Assistant turns shouldn't appear here (sliced off above) — if one\n // somehow does we skip it rather than letting it shape the wire.\n const steps: Array<InteractionsStep> = []\n for (const msg of source) {\n if (msg.role === 'tool' && msg.toolCallId) {\n const result = serializeToolResultContent(msg.content)\n steps.push({\n type: 'function_result',\n call_id: msg.toolCallId,\n name: toolCallIdToName.get(msg.toolCallId),\n result,\n })\n } else if (msg.role === 'user') {\n const content = messageToContentBlocks(msg)\n if (content.length > 0) {\n steps.push({ type: 'user_input', content })\n }\n }\n }\n if (steps.length === 0) {\n throw new Error(\n 'Gemini Interactions adapter: messages after the last assistant turn produced no steps to send.',\n )\n }\n return steps\n}\n\n// The Interactions API's `function_result.result` field is a string. We\n// fail loudly on non-string tool content rather than silently coercing\n// to `''` — silent coercion meant the model lost the entire tool\n// output for callers that returned content as an array (e.g. image +\n// text) or `null`. If you need to send structured tool output, encode\n// it yourself before passing.\nfunction serializeToolResultContent(\n content: ModelMessage['content'] | undefined,\n): string {\n if (typeof content === 'string') return content\n if (content === null || content === undefined) {\n throw new Error(\n 'Gemini Interactions adapter: tool message has no content. The Interactions API requires a string `result` on function_result steps — return a string from your tool implementation (encode JSON/multimodal output yourself).',\n )\n }\n throw new Error(\n 'Gemini Interactions adapter: tool message content must be a string (got an array of content parts). The Interactions API requires a string `result` on function_result steps — stringify multimodal tool output before returning it from your tool.',\n )\n}\n\n// Extracts the content blocks (text / image / audio / video / document)\n// from a single message. Tool calls and tool results live one level up\n// as Steps, not as content, so they are NOT emitted here.\nfunction messageToContentBlocks(msg: ModelMessage): Array<ContentBlock> {\n const blocks: Array<ContentBlock> = []\n\n if (Array.isArray(msg.content)) {\n for (const part of msg.content) {\n blocks.push(contentPartToBlock(part))\n }\n } else if (\n typeof msg.content === 'string' &&\n msg.content &&\n msg.role !== 'tool'\n ) {\n blocks.push({ type: 'text', text: msg.content })\n }\n\n return blocks\n}\n\nfunction messagesAfterLastAssistant(\n messages: Array<ModelMessage>,\n): Array<ModelMessage> {\n for (let i = messages.length - 1; i >= 0; i--) {\n if (messages[i]?.role === 'assistant') {\n return messages.slice(i + 1)\n }\n }\n return messages\n}\n\n// Leniently parse the *accumulated* streamed tool-call argument buffer.\n// Streamed `arguments_delta` fragments are individually incomplete JSON, so\n// a strict `JSON.parse` would throw (and log noise) on every fragment until\n// the final one. `partial-json` recovers a best-effort object from a\n// truncated buffer instead. Returns `undefined` when nothing usable could be\n// parsed, so callers can keep the last good value rather than clobber\n// previously-merged args with `{}`.\nfunction parsePartialToolArguments(\n raw: string,\n): Record<string, unknown> | undefined {\n if (!raw) return undefined\n try {\n const parsed = parsePartialJSON(raw)\n return parsed && typeof parsed === 'object' && !Array.isArray(parsed)\n ? (parsed as Record<string, unknown>)\n : undefined\n } catch {\n return undefined\n }\n}\n\n// `satisfies` pins these arrays to the SDK's narrow mime-type unions: if\n// Google removes a format the build breaks, and if they add one ours keeps\n// working (we just won't accept the new one until added here).\nconst IMAGE_MIME_TYPES = [\n 'image/png',\n 'image/jpeg',\n 'image/webp',\n 'image/heic',\n 'image/heif',\n] as const satisfies ReadonlyArray<\n NonNullable<Interactions.ImageContent['mime_type']>\n>\n\nconst AUDIO_MIME_TYPES = [\n 'audio/wav',\n 'audio/mp3',\n 'audio/aiff',\n 'audio/aac',\n 'audio/ogg',\n 'audio/flac',\n] as const satisfies ReadonlyArray<\n NonNullable<Interactions.AudioContent['mime_type']>\n>\n\nconst VIDEO_MIME_TYPES = [\n 'video/mp4',\n 'video/mpeg',\n 'video/mpg',\n 'video/mov',\n 'video/avi',\n 'video/x-flv',\n 'video/webm',\n 'video/wmv',\n 'video/3gpp',\n] as const satisfies ReadonlyArray<\n NonNullable<Interactions.VideoContent['mime_type']>\n>\n\nconst DOCUMENT_MIME_TYPES = [\n 'application/pdf',\n] as const satisfies ReadonlyArray<\n NonNullable<Interactions.DocumentContent['mime_type']>\n>\n\nfunction validateMime<T extends string>(\n allowed: ReadonlyArray<T>,\n value: string | undefined,\n kind: string,\n): T | undefined {\n if (value === undefined) return undefined\n if ((allowed as ReadonlyArray<string>).includes(value)) {\n return value as T\n }\n throw new Error(\n `Unsupported ${kind} mime type \"${value}\" for the Gemini Interactions API. Allowed: ${allowed.join(', ')}.`,\n )\n}\n\nfunction contentPartToBlock(part: ContentPart): ContentBlock {\n if (part.type === 'text') {\n return { type: 'text', text: part.content }\n }\n const isData = part.source.type === 'data'\n switch (part.type) {\n case 'image': {\n const mime_type = validateMime(\n IMAGE_MIME_TYPES,\n part.source.mimeType,\n 'image',\n )\n return isData\n ? { type: 'image', data: part.source.value, mime_type }\n : { type: 'image', uri: part.source.value, mime_type }\n }\n case 'audio': {\n const mime_type = validateMime(\n AUDIO_MIME_TYPES,\n part.source.mimeType,\n 'audio',\n )\n return isData\n ? { type: 'audio', data: part.source.value, mime_type }\n : { type: 'audio', uri: part.source.value, mime_type }\n }\n case 'video': {\n const mime_type = validateMime(\n VIDEO_MIME_TYPES,\n part.source.mimeType,\n 'video',\n )\n return isData\n ? { type: 'video', data: part.source.value, mime_type }\n : { type: 'video', uri: part.source.value, mime_type }\n }\n case 'document': {\n const mime_type = validateMime(\n DOCUMENT_MIME_TYPES,\n part.source.mimeType,\n 'document',\n )\n return isData\n ? { type: 'document', data: part.source.value, mime_type }\n : { type: 'document', uri: part.source.value, mime_type }\n }\n }\n}\n\n// Built-in Gemini tools use snake_case field names in the Interactions API\n// that differ from the camelCase fields used on `client.models.generateContent`\n// (e.g. `fileSearchStoreNames` vs `file_search_store_names`). Translate\n// explicitly so callers keep using the same tool factories across adapters.\nfunction convertToolsToInteractionsFormat<TTool extends Tool>(\n tools: Array<TTool> | undefined,\n): Array<InteractionsTool> | undefined {\n if (!tools || tools.length === 0) return undefined\n\n const result: Array<InteractionsTool> = []\n\n for (const tool of tools) {\n switch (tool.name) {\n case 'google_search': {\n const metadata = (tool.metadata ?? {}) as {\n search_types?: Array<'web_search' | 'image_search'>\n }\n result.push({\n type: 'google_search',\n ...(metadata.search_types\n ? { search_types: metadata.search_types }\n : {}),\n })\n break\n }\n case 'code_execution': {\n result.push({ type: 'code_execution' })\n break\n }\n case 'url_context': {\n result.push({ type: 'url_context' })\n break\n }\n case 'file_search': {\n const metadata = (tool.metadata ?? {}) as {\n fileSearchStoreNames?: Array<string>\n topK?: number\n metadataFilter?: string\n }\n result.push({\n type: 'file_search',\n ...(metadata.fileSearchStoreNames\n ? { file_search_store_names: metadata.fileSearchStoreNames }\n : {}),\n ...(metadata.topK !== undefined ? { top_k: metadata.topK } : {}),\n ...(metadata.metadataFilter !== undefined\n ? { metadata_filter: metadata.metadataFilter }\n : {}),\n })\n break\n }\n case 'computer_use': {\n const metadata = (tool.metadata ?? {}) as {\n environment?: string\n excludedPredefinedFunctions?: Array<string>\n }\n if (metadata.environment && metadata.environment !== 'browser') {\n throw new Error(\n `computer_use environment \"${metadata.environment}\" is not supported on the Gemini Interactions API. Only \"browser\" is accepted.`,\n )\n }\n result.push({\n type: 'computer_use',\n ...(metadata.environment\n ? { environment: metadata.environment as 'browser' }\n : {}),\n ...(metadata.excludedPredefinedFunctions\n ? {\n excludedPredefinedFunctions:\n metadata.excludedPredefinedFunctions,\n }\n : {}),\n })\n break\n }\n case 'google_search_retrieval':\n throw new Error(\n '`google_search_retrieval` is not supported on the Gemini Interactions API. Use `googleSearchTool()` (`google_search`) with `geminiTextInteractions()`, or call `geminiText()` for the legacy retrieval tool.',\n )\n case 'google_maps':\n throw new Error(\n '`google_maps` is not yet supported on the Gemini Interactions API. Use `geminiText()` for Google Maps grounding.',\n )\n case 'mcp_server':\n throw new Error(\n '`mcp_server` is not yet supported on the `geminiTextInteractions()` adapter.',\n )\n default: {\n if (!tool.description) {\n throw new Error(\n `Tool ${tool.name} requires a description for the Gemini Interactions adapter`,\n )\n }\n result.push({\n type: 'function',\n name: tool.name,\n description: tool.description,\n parameters: sanitizeToolParameters(\n tool.inputSchema ?? { type: 'object', properties: {} },\n ),\n })\n }\n }\n }\n\n return result\n}\n\n// Map of API-level status values onto the AG-UI `finishReason` field.\n// `requires_action` is the Interactions API's signal that the model\n// produced one or more function calls and is waiting for results — we\n// always map that to 'tool_calls' regardless of whether deltas were\n// observed (a function_call may have arrived in a single delta with no\n// other content). `incomplete` is the truncation signal (max_tokens\n// exceeded etc.) — map to 'length'. `completed` is normal stop.\nfunction statusToFinishReason(\n status: Interaction['status'] | undefined,\n sawFunctionCall: boolean,\n): 'stop' | 'length' | 'tool_calls' | null {\n if (status === 'requires_action') return 'tool_calls'\n if (status === 'incomplete') return 'length'\n if (sawFunctionCall) return 'tool_calls'\n return 'stop'\n}\n\n// Statuses that mean the interaction did not produce a usable result.\n// `failed`/`cancelled` map to RUN_ERROR. `incomplete` is the model\n// hitting a stop condition (max_tokens etc.) and is reported via\n// `finishReason: 'length'` on RUN_FINISHED so callers can decide how to\n// react without it looking like a hard error.\nfunction statusIsError(\n status: Interaction['status'] | undefined,\n): status is 'failed' | 'cancelled' {\n return status === 'failed' || status === 'cancelled'\n}\n\nasync function* translateInteractionEvents(\n stream: AsyncIterable<InteractionSSEEvent>,\n model: string,\n runId: string,\n threadId: string,\n parentRunId: string | undefined,\n timestamp: number,\n adapterName: string,\n logger: InternalLogger,\n): AsyncIterable<StreamChunk> {\n const messageId = generateId(adapterName)\n let hasEmittedRunStarted = false\n let hasEmittedTextMessageStart = false\n let textAccumulated = ''\n let interactionId: string | undefined\n let sawFunctionCall = false\n const toolCalls = new Map<string, ToolCallState>()\n let nextToolIndex = 0\n let thinkingStepId: string | null = null\n let thinkingAccumulated = ''\n let reasoningMessageId: string | null = null\n let hasClosedReasoning = false\n // SDK 2.x routes events by step `index`, not by content id. We need to\n // map the index of an in-flight `function_call` step back to the tool\n // call id so subsequent `step.delta` (arguments_delta) and `step.stop`\n // events can update / close the right TOOL_CALL_*.\n const indexToToolCallId = new Map<number, string>()\n // Function-call arguments now stream as partial JSON fragments\n // (`StepDelta.ArgumentsDelta.arguments`) rather than as pre-parsed\n // object deltas. Buffer the raw strings per tool call so we can\n // attempt one JSON parse per delta and recover gracefully if the\n // fragment isn't yet syntactically complete.\n const argStringByToolCallId = new Map<string, string>()\n\n const closeReasoningIfNeeded = function* (): Generator<StreamChunk> {\n if (reasoningMessageId && !hasClosedReasoning) {\n hasClosedReasoning = true\n yield {\n type: EventType.REASONING_MESSAGE_END,\n messageId: reasoningMessageId,\n model,\n timestamp,\n }\n yield {\n type: EventType.REASONING_END,\n messageId: reasoningMessageId,\n model,\n timestamp,\n }\n // Reset so that a later `thought_summary` delta (the API\n // interleaves text → thought → text on some models) opens a\n // fresh reasoning block instead of re-using an already-ended\n // messageId, which would violate AG-UI ordering.\n thinkingStepId = null\n reasoningMessageId = null\n hasClosedReasoning = false\n }\n }\n\n // Seals any in-flight messages and tool calls. Called both on the\n // normal terminal path (`interaction.complete`) and on the error path\n // (`error` SSE event + premature EOF) so the StreamProcessor never\n // sees orphan TEXT_MESSAGE_START / TOOL_CALL_START / REASONING_*\n // events on RUN_ERROR.\n const closeOpenState = function* (): Generator<StreamChunk> {\n yield* closeReasoningIfNeeded()\n for (const [toolCallId, state] of toolCalls) {\n if (state.ended) continue\n state.ended = true\n yield {\n type: EventType.TOOL_CALL_END,\n toolCallId,\n toolName: state.name,\n model,\n timestamp,\n input: state.args,\n }\n }\n if (hasEmittedTextMessageStart) {\n hasEmittedTextMessageStart = false\n yield {\n type: EventType.TEXT_MESSAGE_END,\n messageId,\n model,\n timestamp,\n }\n }\n }\n\n const emitRunStartedIfNeeded = function* (): Generator<StreamChunk> {\n if (!hasEmittedRunStarted) {\n hasEmittedRunStarted = true\n yield {\n type: EventType.RUN_STARTED,\n runId,\n threadId,\n model,\n timestamp,\n parentRunId,\n }\n }\n }\n\n for await (const event of stream) {\n logger.provider(`provider=gemini-text-interactions`, { event })\n switch (event.event_type) {\n case 'interaction.created': {\n interactionId = event.interaction.id\n yield* emitRunStartedIfNeeded()\n break\n }\n\n case 'step.start': {\n yield* emitRunStartedIfNeeded()\n const step = event.step\n const index = event.index\n switch (step.type) {\n case 'function_call': {\n yield* closeReasoningIfNeeded()\n sawFunctionCall = true\n const toolCallId = step.id\n indexToToolCallId.set(index, toolCallId)\n // `step.arguments` is required on FunctionCallStep but may\n // be an empty `{}` placeholder when streaming, where the\n // real args arrive as `arguments_delta` events. Treat both\n // uniformly: stash whatever we got, stringify once.\n const initialArgs = step.arguments\n const state: ToolCallState = {\n name: step.name,\n args: { ...initialArgs },\n index: nextToolIndex++,\n started: true,\n ended: false,\n }\n toolCalls.set(toolCallId, state)\n argStringByToolCallId.set(\n toolCallId,\n Object.keys(initialArgs).length > 0\n ? JSON.stringify(initialArgs)\n : '',\n )\n yield {\n type: EventType.TOOL_CALL_START,\n toolCallId,\n toolCallName: state.name,\n toolName: state.name,\n // Bind the tool call to the same assistant message id the\n // eventual TEXT_MESSAGE_START uses so the message id stays\n // stable when a function_call arrives before any text (#477).\n parentMessageId: messageId,\n model,\n timestamp,\n index: state.index,\n }\n if (Object.keys(initialArgs).length > 0) {\n const argsJson = JSON.stringify(initialArgs)\n yield {\n type: EventType.TOOL_CALL_ARGS,\n toolCallId,\n model,\n timestamp,\n delta: argsJson,\n args: argsJson,\n }\n }\n break\n }\n case 'thought': {\n // Open the reasoning block lazily — content lands here via\n // `step.delta { thought_summary }` events. If the server\n // ships a non-empty `summary` array up-front (rare, unary\n // responses), surface it immediately.\n if (thinkingStepId === null || reasoningMessageId === null) {\n thinkingStepId = generateId(adapterName)\n reasoningMessageId = generateId(adapterName)\n yield {\n type: EventType.REASONING_START,\n messageId: reasoningMessageId,\n model,\n timestamp,\n }\n yield {\n type: EventType.REASONING_MESSAGE_START,\n messageId: reasoningMessageId,\n role: 'reasoning',\n model,\n timestamp,\n }\n yield {\n type: EventType.STEP_STARTED,\n stepName: thinkingStepId,\n stepId: thinkingStepId,\n model,\n timestamp,\n stepType: 'thinking',\n }\n }\n for (const part of step.summary ?? []) {\n if (part.type !== 'text' || !part.text) continue\n thinkingAccumulated += part.text\n yield {\n type: EventType.REASONING_MESSAGE_CONTENT,\n messageId: reasoningMessageId,\n delta: part.text,\n model,\n timestamp,\n }\n yield {\n type: EventType.STEP_FINISHED,\n stepName: thinkingStepId,\n stepId: thinkingStepId,\n model,\n timestamp,\n delta: part.text,\n content: thinkingAccumulated,\n }\n }\n break\n }\n case 'model_output': {\n yield* closeReasoningIfNeeded()\n // Some servers ship an initial `content` array on\n // `step.start` (notably non-streaming and ahead-of-stream\n // unary completions). Treat any prefilled text content the\n // same way a `text` step.delta would.\n for (const part of step.content ?? []) {\n if (part.type !== 'text' || !part.text) continue\n if (!hasEmittedTextMessageStart) {\n hasEmittedTextMessageStart = true\n yield {\n type: EventType.TEXT_MESSAGE_START,\n messageId,\n model,\n timestamp,\n role: 'assistant',\n }\n }\n textAccumulated += part.text\n yield {\n type: EventType.TEXT_MESSAGE_CONTENT,\n messageId,\n model,\n timestamp,\n delta: part.text,\n content: textAccumulated,\n }\n }\n break\n }\n case 'google_search_call': {\n yield* closeReasoningIfNeeded()\n yield {\n type: EventType.CUSTOM,\n name: 'gemini.googleSearchCall',\n value: step,\n model,\n timestamp,\n }\n break\n }\n case 'google_search_result': {\n yield* closeReasoningIfNeeded()\n yield {\n type: EventType.CUSTOM,\n name: 'gemini.googleSearchResult',\n value: step,\n model,\n timestamp,\n }\n break\n }\n case 'code_execution_call': {\n yield* closeReasoningIfNeeded()\n yield {\n type: EventType.CUSTOM,\n name: 'gemini.codeExecutionCall',\n value: step,\n model,\n timestamp,\n }\n break\n }\n case 'code_execution_result': {\n yield* closeReasoningIfNeeded()\n yield {\n type: EventType.CUSTOM,\n name: 'gemini.codeExecutionResult',\n value: step,\n model,\n timestamp,\n }\n break\n }\n case 'url_context_call': {\n yield* closeReasoningIfNeeded()\n yield {\n type: EventType.CUSTOM,\n name: 'gemini.urlContextCall',\n value: step,\n model,\n timestamp,\n }\n break\n }\n case 'url_context_result': {\n yield* closeReasoningIfNeeded()\n yield {\n type: EventType.CUSTOM,\n name: 'gemini.urlContextResult',\n value: step,\n model,\n timestamp,\n }\n break\n }\n case 'file_search_call': {\n yield* closeReasoningIfNeeded()\n yield {\n type: EventType.CUSTOM,\n name: 'gemini.fileSearchCall',\n value: step,\n model,\n timestamp,\n }\n break\n }\n case 'file_search_result': {\n yield* closeReasoningIfNeeded()\n yield {\n type: EventType.CUSTOM,\n name: 'gemini.fileSearchResult',\n value: step,\n model,\n timestamp,\n }\n break\n }\n // Unhandled step types (user_input on GET timelines,\n // mcp_server_*, google_maps_*, function_result) fall through\n // to the observability default so SDK drift is visible.\n case 'user_input':\n case 'mcp_server_tool_call':\n case 'mcp_server_tool_result':\n case 'google_maps_call':\n case 'google_maps_result':\n case 'function_result':\n default:\n logger.provider(`gemini-text-interactions unhandled step.start`, {\n step,\n })\n break\n }\n break\n }\n\n case 'step.delta': {\n yield* emitRunStartedIfNeeded()\n const delta = event.delta\n const index = event.index\n switch (delta.type) {\n case 'text': {\n yield* closeReasoningIfNeeded()\n if (!hasEmittedTextMessageStart) {\n hasEmittedTextMessageStart = true\n yield {\n type: EventType.TEXT_MESSAGE_START,\n messageId,\n model,\n timestamp,\n role: 'assistant',\n }\n }\n textAccumulated += delta.text\n yield {\n type: EventType.TEXT_MESSAGE_CONTENT,\n messageId,\n model,\n timestamp,\n delta: delta.text,\n content: textAccumulated,\n }\n break\n }\n case 'arguments_delta': {\n // Streamed function-call arguments. Identity (id, name) was\n // delivered on the matching `step.start` and recorded in\n // indexToToolCallId.\n const toolCallId = indexToToolCallId.get(index)\n if (!toolCallId) {\n logger.provider(\n `gemini-text-interactions arguments_delta for unknown step index`,\n { index, delta },\n )\n break\n }\n const state = toolCalls.get(toolCallId)\n if (!state) break\n const fragment = delta.arguments ?? ''\n const buffer =\n (argStringByToolCallId.get(toolCallId) ?? '') + fragment\n argStringByToolCallId.set(toolCallId, buffer)\n // Parse the accumulated buffer leniently: streamed arg fragments\n // are individually incomplete JSON, so use a partial-JSON parser\n // that tolerates truncation rather than logging a parse error per\n // fragment. Only overwrite `state.args` when we actually recovered\n // an object, so a momentarily-unparseable fragment can't reset\n // previously-merged args back to `{}`.\n const parsed = parsePartialToolArguments(buffer)\n if (parsed) state.args = parsed\n yield {\n type: EventType.TOOL_CALL_ARGS,\n toolCallId,\n model,\n timestamp,\n delta: fragment,\n args: buffer,\n }\n break\n }\n case 'thought_summary': {\n const thoughtText =\n delta.content && 'text' in delta.content ? delta.content.text : ''\n if (!thoughtText) break\n if (thinkingStepId === null || reasoningMessageId === null) {\n thinkingStepId = generateId(adapterName)\n reasoningMessageId = generateId(adapterName)\n yield {\n type: EventType.REASONING_START,\n messageId: reasoningMessageId,\n model,\n timestamp,\n }\n yield {\n type: EventType.REASONING_MESSAGE_START,\n messageId: reasoningMessageId,\n role: 'reasoning',\n model,\n timestamp,\n }\n yield {\n type: EventType.STEP_STARTED,\n stepName: thinkingStepId,\n stepId: thinkingStepId,\n model,\n timestamp,\n stepType: 'thinking',\n }\n }\n thinkingAccumulated += thoughtText\n yield {\n type: EventType.REASONING_MESSAGE_CONTENT,\n messageId: reasoningMessageId,\n delta: thoughtText,\n model,\n timestamp,\n }\n yield {\n type: EventType.STEP_FINISHED,\n stepName: thinkingStepId,\n stepId: thinkingStepId,\n model,\n timestamp,\n delta: thoughtText,\n content: thinkingAccumulated,\n }\n break\n }\n // The remaining StepDelta variants (image/audio/video/document\n // for output modalities a text adapter shouldn't see, tool\n // call/result deltas which are surfaced via step.start in this\n // adapter, thought_signature, annotation deltas, mcp/google\n // maps variants) fall through to the observability default.\n case 'image':\n case 'audio':\n case 'video':\n case 'document':\n case 'thought_signature':\n case 'text_annotation_delta':\n case 'code_execution_call':\n case 'code_execution_result':\n case 'url_context_call':\n case 'url_context_result':\n case 'google_search_call':\n case 'google_search_result':\n case 'file_search_call':\n case 'file_search_result':\n case 'mcp_server_tool_call':\n case 'mcp_server_tool_result':\n case 'google_maps_call':\n case 'google_maps_result':\n case 'function_result':\n default:\n logger.provider(\n `gemini-text-interactions unhandled step.delta type`,\n { delta },\n )\n break\n }\n break\n }\n\n case 'step.stop': {\n // Close any open function_call so downstream consumers get the\n // matching TOOL_CALL_END once the arguments are complete. Other\n // step types don't carry adapter-level open state.\n const toolCallId = indexToToolCallId.get(event.index)\n if (toolCallId) {\n const state = toolCalls.get(toolCallId)\n if (state && !state.ended) {\n state.ended = true\n yield {\n type: EventType.TOOL_CALL_END,\n toolCallId,\n toolName: state.name,\n model,\n timestamp,\n input: state.args,\n }\n }\n indexToToolCallId.delete(event.index)\n }\n break\n }\n\n case 'interaction.status_update': {\n break\n }\n\n case 'interaction.completed': {\n if (event.interaction.id) {\n interactionId = event.interaction.id\n }\n\n yield* closeOpenState()\n\n const status = event.interaction.status\n if (statusIsError(status)) {\n const message = `Gemini Interactions ${status}: the interaction ended without a usable response.`\n logger.errors(\n 'gemini-text-interactions.translateInteractionEvents non-success status',\n {\n source: 'gemini-text-interactions.chatStream',\n status,\n interactionId,\n },\n )\n yield {\n type: EventType.RUN_ERROR,\n runId,\n model,\n timestamp,\n message,\n code: status,\n error: { message, code: status },\n }\n return\n }\n\n const usage = event.interaction.usage\n const finishReason = statusToFinishReason(status, sawFunctionCall)\n\n if (interactionId) {\n yield {\n type: EventType.CUSTOM,\n name: 'gemini.interactionId',\n value: { interactionId },\n model,\n timestamp,\n }\n }\n\n yield {\n type: EventType.RUN_FINISHED,\n runId,\n threadId,\n model,\n timestamp,\n finishReason,\n usage: usage\n ? {\n promptTokens: usage.total_input_tokens ?? 0,\n completionTokens: usage.total_output_tokens ?? 0,\n totalTokens: usage.total_tokens ?? 0,\n }\n : undefined,\n }\n return\n }\n\n case 'error': {\n // Close any in-flight TEXT_MESSAGE_START / TOOL_CALL_START /\n // REASONING_* so downstream consumers don't see orphan open\n // state after RUN_ERROR.\n yield* closeOpenState()\n const rawMessage = event.error?.message\n const message =\n typeof rawMessage === 'string' && rawMessage.length > 0\n ? rawMessage\n : `Gemini Interactions error (no message): ${JSON.stringify(event.error ?? {})}`\n const rawCode = event.error?.code\n const code =\n typeof rawCode === 'string' || typeof rawCode === 'number'\n ? String(rawCode)\n : undefined\n yield {\n type: EventType.RUN_ERROR,\n runId,\n model,\n timestamp,\n message,\n code,\n error: { message, code },\n }\n return\n }\n\n default:\n logger.provider(`gemini-text-interactions unhandled event_type`, {\n event,\n })\n break\n }\n }\n\n // Stream ended without `interaction.complete` or `error` (both `return`\n // out of the loop). Seal any in-flight TEXT/TOOL/REASONING blocks here\n // so the truncation-fallback RUN_ERROR yielded by `chatStream` doesn't\n // leave orphan `*_START` events open downstream.\n yield* closeOpenState()\n}\n\nfunction extractTextFromInteraction(interaction: Interaction): string {\n // SDK 2.x: the response carries a `steps` array; `output_text` is a\n // convenience the SDK derives from the last model output. Prefer the\n // SDK sugar when it's populated, then fall back to walking\n // model_output steps for adapters / responses that don't get the\n // sugar (e.g. older SDK builds).\n if (typeof interaction.output_text === 'string' && interaction.output_text) {\n return interaction.output_text\n }\n let text = ''\n for (const step of interaction.steps ?? []) {\n if (step.type !== 'model_output' || !step.content) continue\n for (const part of step.content) {\n if (part.type === 'text') {\n text += part.text\n }\n }\n }\n return text\n}\n\n// The live Interactions API rejects tool parameter schemas that contain\n// an empty `required: []` array with the misleading top-level error\n// `\"value at top-level must be a list\"`. Empty `properties: {}` and\n// `parameters: {}` are both fine — only the empty `required` array is\n// poison. The Zod -> JSON Schema converter (and many hand-written\n// schemas) emit `required: []` whenever a tool has zero required\n// parameters, so we strip those instances recursively before sending.\n// Non-empty `required` arrays are passed through unchanged.\nfunction sanitizeToolParameters(schema: unknown): unknown {\n if (!schema || typeof schema !== 'object') return schema\n if (Array.isArray(schema)) return schema.map(sanitizeToolParameters)\n const out: Record<string, unknown> = {}\n for (const [key, value] of Object.entries(schema)) {\n if (key === 'required' && Array.isArray(value) && value.length === 0) {\n continue\n }\n out[key] = sanitizeToolParameters(value)\n }\n return out\n}\n\n// Re-export the stream type so consumers can import it alongside the\n// adapter from a single path: `import type { GeminiInteractionsStream }\n// from '@tanstack/ai-gemini/experimental'`.\nexport type { GeminiInteractionsStream }\n"],"names":["parsePartialJSON"],"mappings":";;;;AAiKO,MAAM,sCAOH,gBAMR;AAAA,EACkB,OAAO;AAAA,EACP,OAAO;AAAA,EAER;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAeA,4CAA4B,IAAA;AAAA,EAE7C,YAAY,QAAsC,OAAe;AAC/D,UAAM,CAAA,GAAI,KAAK;AACf,SAAK,SAAS,mBAAmB,MAAM;AAAA,EACzC;AAAA,EAEA,OAAO,WACL,SAC4B;AAC5B,UAAM,QAAQ,QAAQ,SAAS,WAAW,KAAK,IAAI;AACnD,UAAM,WAAW,QAAQ,YAAY,WAAW,KAAK,IAAI;AACzD,UAAM,YAAY,KAAK,IAAA;AACvB,UAAM,EAAE,WAAW;AAOnB,QACE,CAAC,QAAQ,cAAc,2BACvB,QAAQ,SAAS,WAAW,KAC5B,QAAQ,SAAS,CAAC,GAAG,SAAS,QAC9B;AACA,WAAK,sBAAsB,OAAO,QAAQ;AAAA,IAC5C;AAKA,UAAM,iCACJ,QAAQ,cAAc,2BACtB,KAAK,sBAAsB,IAAI,QAAQ;AAEzC,QAAI,mBAAmB;AAQvB,QAAI,oBAAoB;AACxB,QAAI;AACF,YAAM,UAAU,yBAAyB;AA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AS,kBAAkB,CAAC,KAAK,QAAS;AACnD,eAAW,QAAQ,KAAK,SAAS;AAC/B,UAAI,KAAK,SAAS,QAAQ;AACxB,gBAAQ,KAAK;AAAA,MACf;AAAA,IACF;AAAA,EACF;AACA,SAAO;AACT;AAUA,SAAS,uBAAuB,QAA0B;AACxD,MAAI,CAAC,UAAU,OAAO,WAAW,SAAU,QAAO;AAClD,MAAI,MAAM,QAAQ,MAAM,EAAG,QAAO,OAAO,IAAI,sBAAsB;AACnE,QAAM,MAA+B,CAAA;AACrC,aAAW,CAAC,KAAK,KAAK,KAAK,OAAO,QAAQ,MAAM,GAAG;AACjD,QAAI,QAAQ,cAAc,MAAM,QAAQ,KAAK,KAAK,MAAM,WAAW,GAAG;AACpE;AAAA,IACF;AACA,QAAI,GAAG,IAAI,uBAAuB,KAAK;AAAA,EACzC;AACA,SAAO;AACT;"}
1
+ {"version":3,"file":"adapter.js","names":[],"sources":["../../../../src/experimental/text-interactions/adapter.ts"],"sourcesContent":["import { EventType } from '@tanstack/ai'\nimport { BaseTextAdapter } from '@tanstack/ai/adapters'\nimport { parse as parsePartialJSON } from 'partial-json'\nimport {\n createGeminiClient,\n generateId,\n getGeminiApiKeyFromEnv,\n} from '../../utils/client'\nimport type { InternalLogger } from '@tanstack/ai/adapter-internals'\nimport type {\n GeminiChatModelToolCapabilitiesByName,\n GeminiModelInputModalitiesByName,\n GeminiModels,\n} from '../../model-meta'\nimport type {\n StructuredOutputOptions,\n StructuredOutputResult,\n} from '@tanstack/ai/adapters'\nimport type { GoogleGenAI, Interactions } from '@google/genai'\nimport type {\n ContentPart,\n Modality,\n ModelMessage,\n StreamChunk,\n TextOptions,\n Tool,\n} from '@tanstack/ai'\n\nimport type {\n GeminiInteractionsCustomEvent,\n GeminiInteractionsCustomEventValue,\n GeminiInteractionsStream,\n} from './events'\nimport type { ExternalTextInteractionsProviderOptions } from './provider-options'\nimport type { GeminiMessageMetadataByModality } from '../../message-types'\nimport type { GeminiClientConfig } from '../../utils/client'\n\ntype Interaction = Interactions.Interaction\ntype InteractionSSEEvent = Interactions.InteractionSSEEvent\n\nexport type GeminiTextInteractionsConfig = GeminiClientConfig\n\nexport type GeminiTextInteractionsProviderOptions =\n ExternalTextInteractionsProviderOptions\n\ntype InteractionsTool = NonNullable<\n Interactions.CreateModelInteractionParamsStreaming['tools']\n>[number]\n\ntype ContentBlock = Interactions.Content\n\n// The Interactions API takes `input` as a list of *Steps* (not a list of\n// content blocks, and not a list of `Turn`s — the SDK's type union is\n// misleading on both counts). The live API enforces the Step envelope —\n// raw content arrays produce `invalid_request` / \"value at top-level\n// must be a list\". The wire discriminator is snake_case\n// (`user_input` / `function_result`); see\n// https://ai.google.dev/api/interactions-api for the full Step union.\ntype UserInputStep = {\n type: 'user_input'\n content: Array<ContentBlock>\n}\ntype FunctionResultStep = {\n type: 'function_result'\n call_id: string\n name?: string\n result: string\n}\ntype InteractionsStep = UserInputStep | FunctionResultStep\ntype InteractionsRequestInput = Array<InteractionsStep>\n\n// Concrete wire shape we send to `client.interactions.create`. The SDK's\n// own param union types `input` as `string | Content[] | Turn[] | ...`\n// which is wrong for the live API (see the InteractionsRequestInput\n// comment above), so we type `input` ourselves and cast just once at the\n// SDK boundary instead of casting every field through.\ntype GeminiInteractionsRequestBody = Omit<\n Interactions.CreateModelInteractionParamsStreaming,\n 'input' | 'stream'\n> & {\n input: InteractionsRequestInput\n stream?: boolean\n}\n\ntype ToolCallState = {\n name: string\n // Accumulated args as a parsed object. Kept here in object form so a\n // garbled delta can't corrupt previously-merged fragments (the prior\n // string-then-reparse pipeline replaced the whole accumulator on any\n // parse failure). Stringified only when emitting AG-UI events.\n args: Record<string, unknown>\n index: number\n started: boolean\n ended: boolean\n}\n\n// ===========================\n// Type Resolution Helpers\n// ===========================\n\n/**\n * Resolve provider options for a specific model. The Interactions API's\n * request shape is the same across all chat-capable Gemini models — the\n * SDK doesn't expose a per-model param union — so this currently falls\n * through to the flat `GeminiTextInteractionsProviderOptions` for every\n * model. The alias exists for parity with `GeminiTextAdapter`, so a\n * per-model map can be slotted in later without changing the adapter\n * signature.\n */\ntype ResolveProviderOptions = GeminiTextInteractionsProviderOptions\n\n/**\n * Resolve input modalities for a specific model. Reuses the chat-model\n * modality map from `model-meta.ts`: passing a `document` content block\n * to a model that doesn't support it is a compile error, matching the\n * sibling `GeminiTextAdapter`.\n */\ntype ResolveInputModalities<TModel extends string> =\n TModel extends keyof GeminiModelInputModalitiesByName\n ? GeminiModelInputModalitiesByName[TModel]\n : readonly ['text', 'image', 'audio', 'video', 'document']\n\n/**\n * Resolve tool capabilities for a specific model. Reuses the chat-model\n * capability map: `google_maps` / `google_search_retrieval` /\n * `mcp_server` are rejected at runtime by `convertToolsToInteractionsFormat`,\n * but per-model gating happens here at compile time.\n */\ntype ResolveToolCapabilities<TModel extends string> =\n TModel extends keyof GeminiChatModelToolCapabilitiesByName\n ? NonNullable<GeminiChatModelToolCapabilitiesByName[TModel]>\n : readonly []\n\n/**\n * Tree-shakeable adapter for Gemini's stateful Interactions API. Routes\n * through `client.interactions.create` and surfaces the server-assigned\n * `interactionId` via an AG-UI `CUSTOM` event with\n * `name: 'gemini.interactionId'` emitted just before `RUN_FINISHED`; pass\n * that id back on the next turn via `modelOptions.previous_interaction_id`\n * to continue the conversation without resending history.\n *\n * The Interactions API does NOT support stateless multi-turn replay —\n * passing more than one message in `messages` without a\n * `previous_interaction_id` throws. For a chat UI that maintains local\n * history (e.g. `useChat`), see the \"Wiring with `useChat`\" section of\n * `docs/adapters/gemini.md` for the canonical client/server pattern.\n *\n * Supports user-defined function tools and the built-in tools\n * `google_search`, `code_execution`, `url_context`, `file_search`, and\n * `computer_use`. Built-in tool *activity* for the four search/exec\n * variants is surfaced via `CUSTOM` events\n * (`gemini.googleSearchCall` / `gemini.googleSearchResult` and the\n * corresponding per-tool variants) carrying the raw Interactions delta;\n * see {@link GeminiInteractionsCustomEvent}. `computer_use` is accepted\n * in the request but the Interactions API does not currently stream\n * per-delta CUSTOM events for it. `google_search_retrieval`,\n * `google_maps`, and `mcp_server` are not supported on this adapter.\n *\n * @experimental Interactions API is in Beta per Google; shapes may change.\n * @see https://ai.google.dev/gemini-api/docs/interactions\n */\nexport class GeminiTextInteractionsAdapter<\n TModel extends GeminiModels,\n TProviderOptions extends Record<string, any> = ResolveProviderOptions,\n TInputModalities extends ReadonlyArray<Modality> =\n ResolveInputModalities<TModel>,\n TToolCapabilities extends ReadonlyArray<string> =\n ResolveToolCapabilities<TModel>,\n> extends BaseTextAdapter<\n TModel,\n TProviderOptions,\n TInputModalities,\n GeminiMessageMetadataByModality,\n TToolCapabilities\n> {\n override readonly kind = 'text' as const\n override readonly name = 'gemini-text-interactions' as const\n\n private readonly client: GoogleGenAI\n // Tracks the most recent server-assigned interaction id per threadId\n // so the adapter can chain follow-up calls on the same thread without\n // the caller having to thread the id manually. Two callers rely on\n // this:\n // 1. The agent loop's tool-call iterations (each iteration is a new\n // `chatStream` call with accumulated tool messages).\n // 2. The agentic-structured composition: a `chatStream` run followed\n // by `structuredOutput` on the accumulated messages.\n // Cross-request chaining is the caller's job via\n // `modelOptions.previous_interaction_id`. To keep stale ids from\n // chaining a brand-new turn, `chatStream` evicts at the START when\n // the caller signals fresh-turn intent (no caller-provided id AND a\n // single user message — anything else is a follow-up). Errors evict\n // immediately so a failed turn never chains into the next one.\n private readonly interactionIdByThread = new Map<string, string>()\n\n constructor(config: GeminiTextInteractionsConfig, model: TModel) {\n super({}, model)\n this.client = createGeminiClient(config)\n }\n\n async *chatStream(\n options: TextOptions<GeminiTextInteractionsProviderOptions>,\n ): AsyncIterable<StreamChunk> {\n const runId = options.runId ?? generateId(this.name)\n const threadId = options.threadId ?? generateId(this.name)\n const timestamp = Date.now()\n const { logger } = options\n\n // Fresh-turn intent: caller didn't thread an id AND only a single\n // user message is queued. Drop any stale captured id so we don't\n // silently chain off a prior turn the caller doesn't know about.\n // Multi-message inputs are follow-ups (agent-loop iteration or\n // structuredOutput composition) and keep the Map entry.\n if (\n !options.modelOptions?.previous_interaction_id &&\n options.messages.length === 1 &&\n options.messages[0]?.role === 'user'\n ) {\n this.interactionIdByThread.delete(threadId)\n }\n\n // Resolve `previous_interaction_id`. Caller-provided wins; otherwise\n // fall back to the id we captured during a prior iteration of this\n // same agent-loop run (matched by threadId).\n const effectivePreviousInteractionId =\n options.modelOptions?.previous_interaction_id ??\n this.interactionIdByThread.get(threadId)\n\n let sawTerminalEvent = false\n // Sentinel for the `.return()` abandonment path. Set to `true` only at\n // the bottom of the `try` block — so a consumer-initiated close (via\n // upstream `break` or abort) leaves it `false`, distinguishing\n // abandonment from normal completion. This is the only signal that\n // catches abandonment AFTER a `RUN_FINISHED(tool_calls)`, where\n // `sawTerminalEvent` is `true` but the in-loop deliberately kept the\n // map entry for an agent-loop iteration that will now never run.\n let completedTryBlock = false\n try {\n const request = buildInteractionsRequest({\n ...options,\n modelOptions: {\n ...options.modelOptions,\n previous_interaction_id: effectivePreviousInteractionId,\n },\n })\n logger.request(\n `activity=chat provider=gemini-text-interactions model=${this.model} messages=${options.messages.length} tools=${options.tools?.length ?? 0} stream=true`,\n {\n provider: 'gemini-text-interactions',\n model: this.model,\n request,\n },\n )\n const stream = (await this.client.interactions.create(\n { ...request, stream: true } as GeminiInteractionsRequestBody &\n Parameters<typeof this.client.interactions.create>[0],\n { signal: options.abortController?.signal },\n )) as AsyncIterable<InteractionSSEEvent>\n\n for await (const chunk of translateInteractionEvents(\n stream,\n options.model,\n runId,\n threadId,\n options.parentRunId,\n timestamp,\n this.name,\n logger,\n )) {\n // Capture the server-assigned id so the next agent-loop\n // iteration on this thread can chain off it. The CUSTOM event\n // is also yielded downstream as usual — callers consume it via\n // `onCustomEvent` for cross-request chaining.\n //\n // The yield type can't be narrowed to GeminiInteractionsStream\n // here without fighting zod-passthrough variance (StreamChunk's\n // CustomEvent variant carries `[k: string]: unknown`), so we\n // narrow via the literal `name` and trust the typed\n // construction inside `translateInteractionEvents`.\n if (\n chunk.type === EventType.CUSTOM &&\n chunk.name === 'gemini.interactionId'\n ) {\n const value =\n chunk.value as GeminiInteractionsCustomEventValue<'gemini.interactionId'>\n this.interactionIdByThread.set(threadId, value.interactionId)\n }\n if (chunk.type === EventType.RUN_FINISHED) {\n sawTerminalEvent = true\n // Keep the captured id for follow-ups (next agent-loop\n // iteration OR a structuredOutput call composing this turn).\n // The next *fresh* chatStream call evicts at the top via the\n // fresh-turn guard.\n } else if (chunk.type === EventType.RUN_ERROR) {\n sawTerminalEvent = true\n this.interactionIdByThread.delete(threadId)\n }\n yield chunk\n }\n\n if (!sawTerminalEvent) {\n // SDK stream ended without either `interaction.complete` or\n // `error` — surface the truncation rather than silently leaving\n // downstream consumers waiting on a `RUN_FINISHED` that will\n // never come.\n this.interactionIdByThread.delete(threadId)\n const message =\n 'Gemini Interactions stream ended without a terminal event (no interaction.complete or error)'\n logger.errors('gemini-text-interactions.chatStream truncated', {\n source: 'gemini-text-interactions.chatStream',\n runId,\n threadId,\n })\n yield {\n type: EventType.RUN_ERROR,\n runId,\n model: options.model,\n timestamp,\n message,\n error: { message },\n }\n }\n completedTryBlock = true\n } catch (error) {\n this.interactionIdByThread.delete(threadId)\n const message =\n error instanceof Error\n ? error.message\n : 'An unknown error occurred during the interactions stream.'\n logger.errors('gemini-text-interactions.chatStream fatal', {\n error,\n source: 'gemini-text-interactions.chatStream',\n })\n yield {\n type: EventType.RUN_ERROR,\n runId,\n model: options.model,\n timestamp,\n message,\n error: { message },\n }\n } finally {\n // Abandonment cleanup — consumer `.return()` (upstream `break` /\n // abort) bypasses both the truncation guard and the catch handler.\n // `completedTryBlock` is the sentinel that distinguishes natural\n // completion from abandonment; on abandonment we evict so a stale\n // id from a half-finished turn can't chain into a follow-up. The\n // catch handler also lands here with the flag false; its explicit\n // delete is harmless to repeat.\n if (!completedTryBlock) {\n this.interactionIdByThread.delete(threadId)\n }\n }\n }\n\n async structuredOutput(\n options: StructuredOutputOptions<GeminiTextInteractionsProviderOptions>,\n ): Promise<StructuredOutputResult<unknown>> {\n const { chatOptions, outputSchema } = options\n const { logger } = chatOptions\n const threadId = chatOptions.threadId\n\n // Mirror the chatStream fallback: the agentic-structured flow runs\n // the chat loop first and then calls structuredOutput with the\n // accumulated `messages`. If any tool ran during the loop, the\n // messages include assistant/tool turns; without a chained\n // previous_interaction_id those would throw \"cannot send prior\n // conversation history on a fresh interaction\".\n const effectivePreviousInteractionId =\n chatOptions.modelOptions?.previous_interaction_id ??\n (threadId ? this.interactionIdByThread.get(threadId) : undefined)\n\n const baseRequest = buildInteractionsRequest({\n ...chatOptions,\n modelOptions: {\n ...chatOptions.modelOptions,\n previous_interaction_id: effectivePreviousInteractionId,\n },\n })\n\n // SDK 2.x: `response_mime_type` has been removed and `response_format`\n // is now polymorphic — each entry has a `type` discriminator and the\n // mime type lives inside the entry. See:\n // https://ai.google.dev/gemini-api/docs/interactions-breaking-changes-may-2026\n const request: GeminiInteractionsRequestBody = {\n ...baseRequest,\n response_format: {\n type: 'text',\n mime_type: 'application/json',\n schema: outputSchema,\n },\n }\n\n try {\n logger.request(\n `activity=chat provider=gemini-text-interactions model=${this.model} messages=${chatOptions.messages.length} tools=${chatOptions.tools?.length ?? 0} stream=false`,\n {\n provider: 'gemini-text-interactions',\n model: this.model,\n request,\n },\n )\n const result = (await this.client.interactions.create(\n request as Parameters<typeof this.client.interactions.create>[0],\n { signal: chatOptions.abortController?.signal },\n )) as Interaction\n\n const rawText = extractTextFromInteraction(result)\n\n if (!rawText) {\n throw new Error(\n `Gemini Interactions returned no text output for structured-output request (status: ${result.status}). The model may have produced only tool calls or non-text content.`,\n )\n }\n\n let parsed: unknown\n try {\n parsed = JSON.parse(rawText)\n } catch {\n throw new Error(\n `Failed to parse structured output as JSON. Content: ${rawText.slice(0, 200)}${rawText.length > 200 ? '...' : ''}`,\n )\n }\n\n return { data: parsed, rawText }\n } catch (error) {\n logger.errors('gemini-text-interactions.structuredOutput fatal', {\n error,\n source: 'gemini-text-interactions.structuredOutput',\n })\n // Preserve the original error as `cause` so the stack trace and any\n // SDK-attached status/code/headers survive for Sentry dedup.\n throw new Error(\n error instanceof Error\n ? error.message\n : 'An unknown error occurred during structured output generation.',\n { cause: error },\n )\n }\n }\n}\n\n/** @experimental Interactions API is in Beta. */\nexport function createGeminiTextInteractions<TModel extends GeminiModels>(\n model: TModel,\n apiKey: string,\n config?: Omit<GeminiTextInteractionsConfig, 'apiKey'>,\n): GeminiTextInteractionsAdapter<\n TModel,\n ResolveProviderOptions,\n ResolveInputModalities<TModel>,\n ResolveToolCapabilities<TModel>\n> {\n return new GeminiTextInteractionsAdapter({ apiKey, ...config }, model)\n}\n\n/** @experimental Interactions API is in Beta. */\nexport function geminiTextInteractions<TModel extends GeminiModels>(\n model: TModel,\n config?: Omit<GeminiTextInteractionsConfig, 'apiKey'>,\n): GeminiTextInteractionsAdapter<\n TModel,\n ResolveProviderOptions,\n ResolveInputModalities<TModel>,\n ResolveToolCapabilities<TModel>\n> {\n const apiKey = getGeminiApiKeyFromEnv()\n return createGeminiTextInteractions(model, apiKey, config)\n}\n\nfunction buildInteractionsRequest(\n options: TextOptions<GeminiTextInteractionsProviderOptions>,\n): GeminiInteractionsRequestBody {\n const modelOpts = options.modelOptions\n\n const systemInstruction =\n modelOpts?.system_instruction ?? options.systemPrompts?.join('\\n')\n\n const generationConfig: Interactions.GenerationConfig = {\n ...modelOpts?.generation_config,\n }\n\n const hasGenerationConfig = Object.keys(generationConfig).length > 0\n\n const input = convertMessagesToInteractionsInput(\n options.messages,\n modelOpts?.previous_interaction_id !== undefined,\n )\n\n return {\n model: options.model,\n input,\n previous_interaction_id: modelOpts?.previous_interaction_id,\n system_instruction: systemInstruction,\n tools: convertToolsToInteractionsFormat(options.tools),\n generation_config: hasGenerationConfig ? generationConfig : undefined,\n store: modelOpts?.store,\n background: modelOpts?.background,\n response_modalities: modelOpts?.response_modalities,\n response_format: modelOpts?.response_format,\n }\n}\n\n// Google's Interactions API takes `input` as `Array<Step>`. Each Step\n// is `{type: 'user_input' | 'function_result' | ..., ...}` — content\n// blocks (text/image/etc.) live nested inside a Step's `content` array,\n// they are NOT valid at the top level. Sending raw `Array<Content>`\n// produces `invalid_request` / \"value at top-level must be a list\",\n// because the API is looking for a Step list at the top level and\n// gets content objects instead. The SDK's type union\n// (`string | Array<Content> | Array<Turn> | ...`) is misleading; see\n// https://ai.google.dev/api/interactions-api for the real Step union.\n//\n// When `hasPreviousInteraction` is true the server holds the transcript\n// up through the last assistant turn, so we only send the steps that\n// come after it (a new `user_input`, one or more `function_result`s\n// continuing a tool call, etc.). Otherwise the conversation is fresh\n// and only the latest user turn is supported — multi-turn replay\n// without `previous_interaction_id` is not part of the API contract.\nfunction convertMessagesToInteractionsInput(\n messages: Array<ModelMessage>,\n hasPreviousInteraction: boolean,\n): InteractionsRequestInput {\n const toolCallIdToName = new Map<string, string>()\n for (const msg of messages) {\n if (msg.role === 'assistant' && msg.toolCalls) {\n for (const tc of msg.toolCalls) {\n toolCallIdToName.set(tc.id, tc.function.name)\n }\n }\n }\n\n const source = hasPreviousInteraction\n ? messagesAfterLastAssistant(messages)\n : messages\n\n if (hasPreviousInteraction && source.length === 0) {\n throw new Error(\n 'Gemini Interactions adapter: modelOptions.previous_interaction_id was provided but no new messages were found after the last assistant turn. Append at least one user or tool message before chaining.',\n )\n }\n\n if (!hasPreviousInteraction) {\n const [only, ...rest] = source\n if (!only) {\n throw new Error('Gemini Interactions adapter: no messages to send.')\n }\n if (rest.length > 0) {\n throw new Error(\n 'Gemini Interactions adapter: cannot send prior conversation history on a fresh interaction. Either set modelOptions.previous_interaction_id to chain prior turns server-side, or trim the message list to a single new user turn. See docs/adapters/gemini.md (\"Wiring with useChat\") for the canonical client/server pattern.',\n )\n }\n if (only.role !== 'user') {\n throw new Error(\n `Gemini Interactions adapter: the first message of a fresh interaction must be a user turn (got role=\"${only.role}\"). Set modelOptions.previous_interaction_id to continue an existing interaction.`,\n )\n }\n const content = messageToContentBlocks(only)\n if (content.length === 0) {\n throw new Error(\n 'Gemini Interactions adapter: the user message produced no content blocks to send.',\n )\n }\n return [{ type: 'user_input', content }]\n }\n\n // Chained path: each post-assistant message becomes one Step. A user\n // reply maps to `user_input`; a tool reply maps to `function_result`.\n // Assistant turns shouldn't appear here (sliced off above) — if one\n // somehow does we skip it rather than letting it shape the wire.\n const steps: Array<InteractionsStep> = []\n for (const msg of source) {\n if (msg.role === 'tool' && msg.toolCallId) {\n const result = serializeToolResultContent(msg.content)\n steps.push({\n type: 'function_result',\n call_id: msg.toolCallId,\n name: toolCallIdToName.get(msg.toolCallId),\n result,\n })\n } else if (msg.role === 'user') {\n const content = messageToContentBlocks(msg)\n if (content.length > 0) {\n steps.push({ type: 'user_input', content })\n }\n }\n }\n if (steps.length === 0) {\n throw new Error(\n 'Gemini Interactions adapter: messages after the last assistant turn produced no steps to send.',\n )\n }\n return steps\n}\n\n// The Interactions API's `function_result.result` field is a string. We\n// fail loudly on non-string tool content rather than silently coercing\n// to `''` — silent coercion meant the model lost the entire tool\n// output for callers that returned content as an array (e.g. image +\n// text) or `null`. If you need to send structured tool output, encode\n// it yourself before passing.\nfunction serializeToolResultContent(\n content: ModelMessage['content'] | undefined,\n): string {\n if (typeof content === 'string') return content\n if (content === null || content === undefined) {\n throw new Error(\n 'Gemini Interactions adapter: tool message has no content. The Interactions API requires a string `result` on function_result steps — return a string from your tool implementation (encode JSON/multimodal output yourself).',\n )\n }\n throw new Error(\n 'Gemini Interactions adapter: tool message content must be a string (got an array of content parts). The Interactions API requires a string `result` on function_result steps — stringify multimodal tool output before returning it from your tool.',\n )\n}\n\n// Extracts the content blocks (text / image / audio / video / document)\n// from a single message. Tool calls and tool results live one level up\n// as Steps, not as content, so they are NOT emitted here.\nfunction messageToContentBlocks(msg: ModelMessage): Array<ContentBlock> {\n const blocks: Array<ContentBlock> = []\n\n if (Array.isArray(msg.content)) {\n for (const part of msg.content) {\n blocks.push(contentPartToBlock(part))\n }\n } else if (\n typeof msg.content === 'string' &&\n msg.content &&\n msg.role !== 'tool'\n ) {\n blocks.push({ type: 'text', text: msg.content })\n }\n\n return blocks\n}\n\nfunction messagesAfterLastAssistant(\n messages: Array<ModelMessage>,\n): Array<ModelMessage> {\n for (let i = messages.length - 1; i >= 0; i--) {\n if (messages[i]?.role === 'assistant') {\n return messages.slice(i + 1)\n }\n }\n return messages\n}\n\n// Leniently parse the *accumulated* streamed tool-call argument buffer.\n// Streamed `arguments_delta` fragments are individually incomplete JSON, so\n// a strict `JSON.parse` would throw (and log noise) on every fragment until\n// the final one. `partial-json` recovers a best-effort object from a\n// truncated buffer instead. Returns `undefined` when nothing usable could be\n// parsed, so callers can keep the last good value rather than clobber\n// previously-merged args with `{}`.\nfunction parsePartialToolArguments(\n raw: string,\n): Record<string, unknown> | undefined {\n if (!raw) return undefined\n try {\n const parsed = parsePartialJSON(raw)\n return parsed && typeof parsed === 'object' && !Array.isArray(parsed)\n ? (parsed as Record<string, unknown>)\n : undefined\n } catch {\n return undefined\n }\n}\n\n// `satisfies` pins these arrays to the SDK's narrow mime-type unions: if\n// Google removes a format the build breaks, and if they add one ours keeps\n// working (we just won't accept the new one until added here).\nconst IMAGE_MIME_TYPES = [\n 'image/png',\n 'image/jpeg',\n 'image/webp',\n 'image/heic',\n 'image/heif',\n] as const satisfies ReadonlyArray<\n NonNullable<Interactions.ImageContent['mime_type']>\n>\n\nconst AUDIO_MIME_TYPES = [\n 'audio/wav',\n 'audio/mp3',\n 'audio/aiff',\n 'audio/aac',\n 'audio/ogg',\n 'audio/flac',\n] as const satisfies ReadonlyArray<\n NonNullable<Interactions.AudioContent['mime_type']>\n>\n\nconst VIDEO_MIME_TYPES = [\n 'video/mp4',\n 'video/mpeg',\n 'video/mpg',\n 'video/mov',\n 'video/avi',\n 'video/x-flv',\n 'video/webm',\n 'video/wmv',\n 'video/3gpp',\n] as const satisfies ReadonlyArray<\n NonNullable<Interactions.VideoContent['mime_type']>\n>\n\nconst DOCUMENT_MIME_TYPES = [\n 'application/pdf',\n] as const satisfies ReadonlyArray<\n NonNullable<Interactions.DocumentContent['mime_type']>\n>\n\nfunction validateMime<T extends string>(\n allowed: ReadonlyArray<T>,\n value: string | undefined,\n kind: string,\n): T | undefined {\n if (value === undefined) return undefined\n if ((allowed as ReadonlyArray<string>).includes(value)) {\n return value as T\n }\n throw new Error(\n `Unsupported ${kind} mime type \"${value}\" for the Gemini Interactions API. Allowed: ${allowed.join(', ')}.`,\n )\n}\n\nfunction contentPartToBlock(part: ContentPart): ContentBlock {\n if (part.type === 'text') {\n return { type: 'text', text: part.content }\n }\n const isData = part.source.type === 'data'\n switch (part.type) {\n case 'image': {\n const mime_type = validateMime(\n IMAGE_MIME_TYPES,\n part.source.mimeType,\n 'image',\n )\n return isData\n ? { type: 'image', data: part.source.value, mime_type }\n : { type: 'image', uri: part.source.value, mime_type }\n }\n case 'audio': {\n const mime_type = validateMime(\n AUDIO_MIME_TYPES,\n part.source.mimeType,\n 'audio',\n )\n return isData\n ? { type: 'audio', data: part.source.value, mime_type }\n : { type: 'audio', uri: part.source.value, mime_type }\n }\n case 'video': {\n const mime_type = validateMime(\n VIDEO_MIME_TYPES,\n part.source.mimeType,\n 'video',\n )\n return isData\n ? { type: 'video', data: part.source.value, mime_type }\n : { type: 'video', uri: part.source.value, mime_type }\n }\n case 'document': {\n const mime_type = validateMime(\n DOCUMENT_MIME_TYPES,\n part.source.mimeType,\n 'document',\n )\n return isData\n ? { type: 'document', data: part.source.value, mime_type }\n : { type: 'document', uri: part.source.value, mime_type }\n }\n }\n}\n\n// Built-in Gemini tools use snake_case field names in the Interactions API\n// that differ from the camelCase fields used on `client.models.generateContent`\n// (e.g. `fileSearchStoreNames` vs `file_search_store_names`). Translate\n// explicitly so callers keep using the same tool factories across adapters.\nfunction convertToolsToInteractionsFormat<TTool extends Tool>(\n tools: Array<TTool> | undefined,\n): Array<InteractionsTool> | undefined {\n if (!tools || tools.length === 0) return undefined\n\n const result: Array<InteractionsTool> = []\n\n for (const tool of tools) {\n switch (tool.name) {\n case 'google_search': {\n const metadata = (tool.metadata ?? {}) as {\n search_types?: Array<'web_search' | 'image_search'>\n }\n result.push({\n type: 'google_search',\n ...(metadata.search_types\n ? { search_types: metadata.search_types }\n : {}),\n })\n break\n }\n case 'code_execution': {\n result.push({ type: 'code_execution' })\n break\n }\n case 'url_context': {\n result.push({ type: 'url_context' })\n break\n }\n case 'file_search': {\n const metadata = (tool.metadata ?? {}) as {\n fileSearchStoreNames?: Array<string>\n topK?: number\n metadataFilter?: string\n }\n result.push({\n type: 'file_search',\n ...(metadata.fileSearchStoreNames\n ? { file_search_store_names: metadata.fileSearchStoreNames }\n : {}),\n ...(metadata.topK !== undefined ? { top_k: metadata.topK } : {}),\n ...(metadata.metadataFilter !== undefined\n ? { metadata_filter: metadata.metadataFilter }\n : {}),\n })\n break\n }\n case 'computer_use': {\n const metadata = (tool.metadata ?? {}) as {\n environment?: string\n excludedPredefinedFunctions?: Array<string>\n }\n if (metadata.environment && metadata.environment !== 'browser') {\n throw new Error(\n `computer_use environment \"${metadata.environment}\" is not supported on the Gemini Interactions API. Only \"browser\" is accepted.`,\n )\n }\n result.push({\n type: 'computer_use',\n ...(metadata.environment\n ? { environment: metadata.environment as 'browser' }\n : {}),\n ...(metadata.excludedPredefinedFunctions\n ? {\n excludedPredefinedFunctions:\n metadata.excludedPredefinedFunctions,\n }\n : {}),\n })\n break\n }\n case 'google_search_retrieval':\n throw new Error(\n '`google_search_retrieval` is not supported on the Gemini Interactions API. Use `googleSearchTool()` (`google_search`) with `geminiTextInteractions()`, or call `geminiText()` for the legacy retrieval tool.',\n )\n case 'google_maps':\n throw new Error(\n '`google_maps` is not yet supported on the Gemini Interactions API. Use `geminiText()` for Google Maps grounding.',\n )\n case 'mcp_server':\n throw new Error(\n '`mcp_server` is not yet supported on the `geminiTextInteractions()` adapter.',\n )\n default: {\n if (!tool.description) {\n throw new Error(\n `Tool ${tool.name} requires a description for the Gemini Interactions adapter`,\n )\n }\n result.push({\n type: 'function',\n name: tool.name,\n description: tool.description,\n parameters: sanitizeToolParameters(\n tool.inputSchema ?? { type: 'object', properties: {} },\n ),\n })\n }\n }\n }\n\n return result\n}\n\n// Map of API-level status values onto the AG-UI `finishReason` field.\n// `requires_action` is the Interactions API's signal that the model\n// produced one or more function calls and is waiting for results — we\n// always map that to 'tool_calls' regardless of whether deltas were\n// observed (a function_call may have arrived in a single delta with no\n// other content). `incomplete` is the truncation signal (max_tokens\n// exceeded etc.) — map to 'length'. `completed` is normal stop.\nfunction statusToFinishReason(\n status: Interaction['status'] | undefined,\n sawFunctionCall: boolean,\n): 'stop' | 'length' | 'tool_calls' | null {\n if (status === 'requires_action') return 'tool_calls'\n if (status === 'incomplete') return 'length'\n if (sawFunctionCall) return 'tool_calls'\n return 'stop'\n}\n\n// Statuses that mean the interaction did not produce a usable result.\n// `failed`/`cancelled` map to RUN_ERROR. `incomplete` is the model\n// hitting a stop condition (max_tokens etc.) and is reported via\n// `finishReason: 'length'` on RUN_FINISHED so callers can decide how to\n// react without it looking like a hard error.\nfunction statusIsError(\n status: Interaction['status'] | undefined,\n): status is 'failed' | 'cancelled' {\n return status === 'failed' || status === 'cancelled'\n}\n\nasync function* translateInteractionEvents(\n stream: AsyncIterable<InteractionSSEEvent>,\n model: string,\n runId: string,\n threadId: string,\n parentRunId: string | undefined,\n timestamp: number,\n adapterName: string,\n logger: InternalLogger,\n): AsyncIterable<StreamChunk> {\n const messageId = generateId(adapterName)\n let hasEmittedRunStarted = false\n let hasEmittedTextMessageStart = false\n let textAccumulated = ''\n let interactionId: string | undefined\n let sawFunctionCall = false\n const toolCalls = new Map<string, ToolCallState>()\n let nextToolIndex = 0\n let thinkingStepId: string | null = null\n let thinkingAccumulated = ''\n let reasoningMessageId: string | null = null\n let hasClosedReasoning = false\n // SDK 2.x routes events by step `index`, not by content id. We need to\n // map the index of an in-flight `function_call` step back to the tool\n // call id so subsequent `step.delta` (arguments_delta) and `step.stop`\n // events can update / close the right TOOL_CALL_*.\n const indexToToolCallId = new Map<number, string>()\n // Function-call arguments now stream as partial JSON fragments\n // (`StepDelta.ArgumentsDelta.arguments`) rather than as pre-parsed\n // object deltas. Buffer the raw strings per tool call so we can\n // attempt one JSON parse per delta and recover gracefully if the\n // fragment isn't yet syntactically complete.\n const argStringByToolCallId = new Map<string, string>()\n\n const closeReasoningIfNeeded = function* (): Generator<StreamChunk> {\n if (reasoningMessageId && !hasClosedReasoning) {\n hasClosedReasoning = true\n yield {\n type: EventType.REASONING_MESSAGE_END,\n messageId: reasoningMessageId,\n model,\n timestamp,\n }\n yield {\n type: EventType.REASONING_END,\n messageId: reasoningMessageId,\n model,\n timestamp,\n }\n // Reset so that a later `thought_summary` delta (the API\n // interleaves text → thought → text on some models) opens a\n // fresh reasoning block instead of re-using an already-ended\n // messageId, which would violate AG-UI ordering.\n thinkingStepId = null\n reasoningMessageId = null\n hasClosedReasoning = false\n }\n }\n\n // Seals any in-flight messages and tool calls. Called both on the\n // normal terminal path (`interaction.complete`) and on the error path\n // (`error` SSE event + premature EOF) so the StreamProcessor never\n // sees orphan TEXT_MESSAGE_START / TOOL_CALL_START / REASONING_*\n // events on RUN_ERROR.\n const closeOpenState = function* (): Generator<StreamChunk> {\n yield* closeReasoningIfNeeded()\n for (const [toolCallId, state] of toolCalls) {\n if (state.ended) continue\n state.ended = true\n yield {\n type: EventType.TOOL_CALL_END,\n toolCallId,\n toolName: state.name,\n model,\n timestamp,\n input: state.args,\n }\n }\n if (hasEmittedTextMessageStart) {\n hasEmittedTextMessageStart = false\n yield {\n type: EventType.TEXT_MESSAGE_END,\n messageId,\n model,\n timestamp,\n }\n }\n }\n\n const emitRunStartedIfNeeded = function* (): Generator<StreamChunk> {\n if (!hasEmittedRunStarted) {\n hasEmittedRunStarted = true\n yield {\n type: EventType.RUN_STARTED,\n runId,\n threadId,\n model,\n timestamp,\n parentRunId,\n }\n }\n }\n\n for await (const event of stream) {\n logger.provider(`provider=gemini-text-interactions`, { event })\n switch (event.event_type) {\n case 'interaction.created': {\n interactionId = event.interaction.id\n yield* emitRunStartedIfNeeded()\n break\n }\n\n case 'step.start': {\n yield* emitRunStartedIfNeeded()\n const step = event.step\n const index = event.index\n switch (step.type) {\n case 'function_call': {\n yield* closeReasoningIfNeeded()\n sawFunctionCall = true\n const toolCallId = step.id\n indexToToolCallId.set(index, toolCallId)\n // `step.arguments` is required on FunctionCallStep but may\n // be an empty `{}` placeholder when streaming, where the\n // real args arrive as `arguments_delta` events. Treat both\n // uniformly: stash whatever we got, stringify once.\n const initialArgs = step.arguments\n const state: ToolCallState = {\n name: step.name,\n args: { ...initialArgs },\n index: nextToolIndex++,\n started: true,\n ended: false,\n }\n toolCalls.set(toolCallId, state)\n argStringByToolCallId.set(\n toolCallId,\n Object.keys(initialArgs).length > 0\n ? JSON.stringify(initialArgs)\n : '',\n )\n yield {\n type: EventType.TOOL_CALL_START,\n toolCallId,\n toolCallName: state.name,\n toolName: state.name,\n // Bind the tool call to the same assistant message id the\n // eventual TEXT_MESSAGE_START uses so the message id stays\n // stable when a function_call arrives before any text (#477).\n parentMessageId: messageId,\n model,\n timestamp,\n index: state.index,\n }\n if (Object.keys(initialArgs).length > 0) {\n const argsJson = JSON.stringify(initialArgs)\n yield {\n type: EventType.TOOL_CALL_ARGS,\n toolCallId,\n model,\n timestamp,\n delta: argsJson,\n args: argsJson,\n }\n }\n break\n }\n case 'thought': {\n // Open the reasoning block lazily — content lands here via\n // `step.delta { thought_summary }` events. If the server\n // ships a non-empty `summary` array up-front (rare, unary\n // responses), surface it immediately.\n if (thinkingStepId === null || reasoningMessageId === null) {\n thinkingStepId = generateId(adapterName)\n reasoningMessageId = generateId(adapterName)\n yield {\n type: EventType.REASONING_START,\n messageId: reasoningMessageId,\n model,\n timestamp,\n }\n yield {\n type: EventType.REASONING_MESSAGE_START,\n messageId: reasoningMessageId,\n role: 'reasoning',\n model,\n timestamp,\n }\n yield {\n type: EventType.STEP_STARTED,\n stepName: thinkingStepId,\n stepId: thinkingStepId,\n model,\n timestamp,\n stepType: 'thinking',\n }\n }\n for (const part of step.summary ?? []) {\n if (part.type !== 'text' || !part.text) continue\n thinkingAccumulated += part.text\n yield {\n type: EventType.REASONING_MESSAGE_CONTENT,\n messageId: reasoningMessageId,\n delta: part.text,\n model,\n timestamp,\n }\n yield {\n type: EventType.STEP_FINISHED,\n stepName: thinkingStepId,\n stepId: thinkingStepId,\n model,\n timestamp,\n delta: part.text,\n content: thinkingAccumulated,\n }\n }\n break\n }\n case 'model_output': {\n yield* closeReasoningIfNeeded()\n // Some servers ship an initial `content` array on\n // `step.start` (notably non-streaming and ahead-of-stream\n // unary completions). Treat any prefilled text content the\n // same way a `text` step.delta would.\n for (const part of step.content ?? []) {\n if (part.type !== 'text' || !part.text) continue\n if (!hasEmittedTextMessageStart) {\n hasEmittedTextMessageStart = true\n yield {\n type: EventType.TEXT_MESSAGE_START,\n messageId,\n model,\n timestamp,\n role: 'assistant',\n }\n }\n textAccumulated += part.text\n yield {\n type: EventType.TEXT_MESSAGE_CONTENT,\n messageId,\n model,\n timestamp,\n delta: part.text,\n content: textAccumulated,\n }\n }\n break\n }\n case 'google_search_call': {\n yield* closeReasoningIfNeeded()\n yield {\n type: EventType.CUSTOM,\n name: 'gemini.googleSearchCall',\n value: step,\n model,\n timestamp,\n }\n break\n }\n case 'google_search_result': {\n yield* closeReasoningIfNeeded()\n yield {\n type: EventType.CUSTOM,\n name: 'gemini.googleSearchResult',\n value: step,\n model,\n timestamp,\n }\n break\n }\n case 'code_execution_call': {\n yield* closeReasoningIfNeeded()\n yield {\n type: EventType.CUSTOM,\n name: 'gemini.codeExecutionCall',\n value: step,\n model,\n timestamp,\n }\n break\n }\n case 'code_execution_result': {\n yield* closeReasoningIfNeeded()\n yield {\n type: EventType.CUSTOM,\n name: 'gemini.codeExecutionResult',\n value: step,\n model,\n timestamp,\n }\n break\n }\n case 'url_context_call': {\n yield* closeReasoningIfNeeded()\n yield {\n type: EventType.CUSTOM,\n name: 'gemini.urlContextCall',\n value: step,\n model,\n timestamp,\n }\n break\n }\n case 'url_context_result': {\n yield* closeReasoningIfNeeded()\n yield {\n type: EventType.CUSTOM,\n name: 'gemini.urlContextResult',\n value: step,\n model,\n timestamp,\n }\n break\n }\n case 'file_search_call': {\n yield* closeReasoningIfNeeded()\n yield {\n type: EventType.CUSTOM,\n name: 'gemini.fileSearchCall',\n value: step,\n model,\n timestamp,\n }\n break\n }\n case 'file_search_result': {\n yield* closeReasoningIfNeeded()\n yield {\n type: EventType.CUSTOM,\n name: 'gemini.fileSearchResult',\n value: step,\n model,\n timestamp,\n }\n break\n }\n // Unhandled step types (user_input on GET timelines,\n // mcp_server_*, google_maps_*, function_result) fall through\n // to the observability default so SDK drift is visible.\n case 'user_input':\n case 'mcp_server_tool_call':\n case 'mcp_server_tool_result':\n case 'google_maps_call':\n case 'google_maps_result':\n case 'function_result':\n default:\n logger.provider(`gemini-text-interactions unhandled step.start`, {\n step,\n })\n break\n }\n break\n }\n\n case 'step.delta': {\n yield* emitRunStartedIfNeeded()\n const delta = event.delta\n const index = event.index\n switch (delta.type) {\n case 'text': {\n yield* closeReasoningIfNeeded()\n if (!hasEmittedTextMessageStart) {\n hasEmittedTextMessageStart = true\n yield {\n type: EventType.TEXT_MESSAGE_START,\n messageId,\n model,\n timestamp,\n role: 'assistant',\n }\n }\n textAccumulated += delta.text\n yield {\n type: EventType.TEXT_MESSAGE_CONTENT,\n messageId,\n model,\n timestamp,\n delta: delta.text,\n content: textAccumulated,\n }\n break\n }\n case 'arguments_delta': {\n // Streamed function-call arguments. Identity (id, name) was\n // delivered on the matching `step.start` and recorded in\n // indexToToolCallId.\n const toolCallId = indexToToolCallId.get(index)\n if (!toolCallId) {\n logger.provider(\n `gemini-text-interactions arguments_delta for unknown step index`,\n { index, delta },\n )\n break\n }\n const state = toolCalls.get(toolCallId)\n if (!state) break\n const fragment = delta.arguments ?? ''\n const buffer =\n (argStringByToolCallId.get(toolCallId) ?? '') + fragment\n argStringByToolCallId.set(toolCallId, buffer)\n // Parse the accumulated buffer leniently: streamed arg fragments\n // are individually incomplete JSON, so use a partial-JSON parser\n // that tolerates truncation rather than logging a parse error per\n // fragment. Only overwrite `state.args` when we actually recovered\n // an object, so a momentarily-unparseable fragment can't reset\n // previously-merged args back to `{}`.\n const parsed = parsePartialToolArguments(buffer)\n if (parsed) state.args = parsed\n yield {\n type: EventType.TOOL_CALL_ARGS,\n toolCallId,\n model,\n timestamp,\n delta: fragment,\n args: buffer,\n }\n break\n }\n case 'thought_summary': {\n const thoughtText =\n delta.content && 'text' in delta.content ? delta.content.text : ''\n if (!thoughtText) break\n if (thinkingStepId === null || reasoningMessageId === null) {\n thinkingStepId = generateId(adapterName)\n reasoningMessageId = generateId(adapterName)\n yield {\n type: EventType.REASONING_START,\n messageId: reasoningMessageId,\n model,\n timestamp,\n }\n yield {\n type: EventType.REASONING_MESSAGE_START,\n messageId: reasoningMessageId,\n role: 'reasoning',\n model,\n timestamp,\n }\n yield {\n type: EventType.STEP_STARTED,\n stepName: thinkingStepId,\n stepId: thinkingStepId,\n model,\n timestamp,\n stepType: 'thinking',\n }\n }\n thinkingAccumulated += thoughtText\n yield {\n type: EventType.REASONING_MESSAGE_CONTENT,\n messageId: reasoningMessageId,\n delta: thoughtText,\n model,\n timestamp,\n }\n yield {\n type: EventType.STEP_FINISHED,\n stepName: thinkingStepId,\n stepId: thinkingStepId,\n model,\n timestamp,\n delta: thoughtText,\n content: thinkingAccumulated,\n }\n break\n }\n // The remaining StepDelta variants (image/audio/video/document\n // for output modalities a text adapter shouldn't see, tool\n // call/result deltas which are surfaced via step.start in this\n // adapter, thought_signature, annotation deltas, mcp/google\n // maps variants) fall through to the observability default.\n case 'image':\n case 'audio':\n case 'video':\n case 'document':\n case 'thought_signature':\n case 'text_annotation_delta':\n case 'code_execution_call':\n case 'code_execution_result':\n case 'url_context_call':\n case 'url_context_result':\n case 'google_search_call':\n case 'google_search_result':\n case 'file_search_call':\n case 'file_search_result':\n case 'mcp_server_tool_call':\n case 'mcp_server_tool_result':\n case 'google_maps_call':\n case 'google_maps_result':\n case 'function_result':\n default:\n logger.provider(\n `gemini-text-interactions unhandled step.delta type`,\n { delta },\n )\n break\n }\n break\n }\n\n case 'step.stop': {\n // Close any open function_call so downstream consumers get the\n // matching TOOL_CALL_END once the arguments are complete. Other\n // step types don't carry adapter-level open state.\n const toolCallId = indexToToolCallId.get(event.index)\n if (toolCallId) {\n const state = toolCalls.get(toolCallId)\n if (state && !state.ended) {\n state.ended = true\n yield {\n type: EventType.TOOL_CALL_END,\n toolCallId,\n toolName: state.name,\n model,\n timestamp,\n input: state.args,\n }\n }\n indexToToolCallId.delete(event.index)\n }\n break\n }\n\n case 'interaction.status_update': {\n break\n }\n\n case 'interaction.completed': {\n if (event.interaction.id) {\n interactionId = event.interaction.id\n }\n\n yield* closeOpenState()\n\n const status = event.interaction.status\n if (statusIsError(status)) {\n const message = `Gemini Interactions ${status}: the interaction ended without a usable response.`\n logger.errors(\n 'gemini-text-interactions.translateInteractionEvents non-success status',\n {\n source: 'gemini-text-interactions.chatStream',\n status,\n interactionId,\n },\n )\n yield {\n type: EventType.RUN_ERROR,\n runId,\n model,\n timestamp,\n message,\n code: status,\n error: { message, code: status },\n }\n return\n }\n\n const usage = event.interaction.usage\n const finishReason = statusToFinishReason(status, sawFunctionCall)\n\n if (interactionId) {\n yield {\n type: EventType.CUSTOM,\n name: 'gemini.interactionId',\n value: { interactionId },\n model,\n timestamp,\n }\n }\n\n yield {\n type: EventType.RUN_FINISHED,\n runId,\n threadId,\n model,\n timestamp,\n finishReason,\n usage: usage\n ? {\n promptTokens: usage.total_input_tokens ?? 0,\n completionTokens: usage.total_output_tokens ?? 0,\n totalTokens: usage.total_tokens ?? 0,\n }\n : undefined,\n }\n return\n }\n\n case 'error': {\n // Close any in-flight TEXT_MESSAGE_START / TOOL_CALL_START /\n // REASONING_* so downstream consumers don't see orphan open\n // state after RUN_ERROR.\n yield* closeOpenState()\n const rawMessage = event.error?.message\n const message =\n typeof rawMessage === 'string' && rawMessage.length > 0\n ? rawMessage\n : `Gemini Interactions error (no message): ${JSON.stringify(event.error ?? {})}`\n const rawCode = event.error?.code\n const code =\n typeof rawCode === 'string' || typeof rawCode === 'number'\n ? String(rawCode)\n : undefined\n yield {\n type: EventType.RUN_ERROR,\n runId,\n model,\n timestamp,\n message,\n code,\n error: { message, code },\n }\n return\n }\n\n default:\n logger.provider(`gemini-text-interactions unhandled event_type`, {\n event,\n })\n break\n }\n }\n\n // Stream ended without `interaction.complete` or `error` (both `return`\n // out of the loop). Seal any in-flight TEXT/TOOL/REASONING blocks here\n // so the truncation-fallback RUN_ERROR yielded by `chatStream` doesn't\n // leave orphan `*_START` events open downstream.\n yield* closeOpenState()\n}\n\nfunction extractTextFromInteraction(interaction: Interaction): string {\n // SDK 2.x: the response carries a `steps` array; `output_text` is a\n // convenience the SDK derives from the last model output. Prefer the\n // SDK sugar when it's populated, then fall back to walking\n // model_output steps for adapters / responses that don't get the\n // sugar (e.g. older SDK builds).\n if (typeof interaction.output_text === 'string' && interaction.output_text) {\n return interaction.output_text\n }\n let text = ''\n for (const step of interaction.steps ?? []) {\n if (step.type !== 'model_output' || !step.content) continue\n for (const part of step.content) {\n if (part.type === 'text') {\n text += part.text\n }\n }\n }\n return text\n}\n\n// The live Interactions API rejects tool parameter schemas that contain\n// an empty `required: []` array with the misleading top-level error\n// `\"value at top-level must be a list\"`. Empty `properties: {}` and\n// `parameters: {}` are both fine — only the empty `required` array is\n// poison. The Zod -> JSON Schema converter (and many hand-written\n// schemas) emit `required: []` whenever a tool has zero required\n// parameters, so we strip those instances recursively before sending.\n// Non-empty `required` arrays are passed through unchanged.\nfunction sanitizeToolParameters(schema: unknown): unknown {\n if (!schema || typeof schema !== 'object') return schema\n if (Array.isArray(schema)) return schema.map(sanitizeToolParameters)\n const out: Record<string, unknown> = {}\n for (const [key, value] of Object.entries(schema)) {\n if (key === 'required' && Array.isArray(value) && value.length === 0) {\n continue\n }\n out[key] = sanitizeToolParameters(value)\n }\n return out\n}\n\n// Re-export the stream type so consumers can import it alongside the\n// adapter from a single path: `import type { GeminiInteractionsStream }\n// from '@tanstack/ai-gemini/experimental'`.\nexport type { GeminiInteractionsStream }\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAiKA,IAAa,gCAAb,cAOU,gBAMR;CACA,OAAyB;CACzB,OAAyB;CAEzB;CAeA,wCAAyC,IAAI,IAAoB;CAEjE,YAAY,QAAsC,OAAe;EAC/D,MAAM,CAAC,GAAG,KAAK;EACf,KAAK,SAAS,mBAAmB,MAAM;CACzC;CAEA,OAAO,WACL,SAC4B;EAC5B,MAAM,QAAQ,QAAQ,SAAS,WAAW,KAAK,IAAI;EACnD,MAAM,WAAW,QAAQ,YAAY,WAAW,KAAK,IAAI;EACzD,MAAM,YAAY,KAAK,IAAI;EAC3B,MAAM,EAAE,WAAW;EAOnB,IACE,CAAC,QAAQ,cAAc,2BACvB,QAAQ,SAAS,WAAW,KAC5B,QAAQ,SAAS,EAAE,EAAE,SAAS,QAE9B,KAAK,sBAAsB,OAAO,QAAQ;EAM5C,MAAM,iCACJ,QAAQ,cAAc,2BACtB,KAAK,sBAAsB,IAAI,QAAQ;EAEzC,IAAI,mBAAmB;EAQvB,IAAI,oBAAoB;EACxB,IAAI;GACF,MAAM,UAAU,yBAAyB;IACvC,GAAG;IACH,cAAc;KACZ,GAAG,QAAQ;KACX,yBAAyB;IAC3B;GACF,CAAC;GACD,OAAO,QACL,yDAAyD,KAAK,MAAM,YAAY,QAAQ,SAAS,OAAO,SAAS,QAAQ,OAAO,UAAU,EAAE,eAC5I;IACE,UAAU;IACV,OAAO,KAAK;IACZ;GACF,CACF;GACA,MAAM,SAAU,MAAM,KAAK,OAAO,aAAa,OAC7C;IAAE,GAAG;IAAS,QAAQ;GAAK,GAE3B,EAAE,QAAQ,QAAQ,iBAAiB,OAAO,CAC5C;GAEA,WAAW,MAAM,SAAS,2BACxB,QACA,QAAQ,OACR,OACA,UACA,QAAQ,aACR,WACA,KAAK,MACL,MACF,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AChB,QAAQ,KAAK;CAGnB;CACA,OAAO;AACT;AAUA,SAAS,uBAAuB,QAA0B;CACxD,IAAI,CAAC,UAAU,OAAO,WAAW,UAAU,OAAO;CAClD,IAAI,MAAM,QAAQ,MAAM,GAAG,OAAO,OAAO,IAAI,sBAAsB;CACnE,MAAM,MAA+B,CAAC;CACtC,KAAK,MAAM,CAAC,KAAK,UAAU,OAAO,QAAQ,MAAM,GAAG;EACjD,IAAI,QAAQ,cAAc,MAAM,QAAQ,KAAK,KAAK,MAAM,WAAW,GACjE;EAEF,IAAI,OAAO,uBAAuB,KAAK;CACzC;CACA,OAAO;AACT"}
@@ -1,66 +1,86 @@
1
- const GEMINI_SIZE_TO_ASPECT_RATIO = {
2
- // Square
3
- "1024x1024": "1:1",
4
- "512x512": "1:1",
5
- // Landscape
6
- "1024x768": "4:3",
7
- "1536x1024": "4:3",
8
- "1792x1024": "16:9",
9
- "1920x1080": "16:9",
10
- // Portrait
11
- "768x1024": "3:4",
12
- "1024x1536": "3:4",
13
- // Inverted
14
- "1024x1792": "9:16",
15
- "1080x1920": "9:16"
1
+ //#region src/image/image-provider-options.ts
2
+ /**
3
+ * Valid sizes for Gemini Imagen models
4
+ * Gemini uses aspect ratios, but we map common WIDTHxHEIGHT formats to aspect ratios
5
+ * These are approximate mappings based on common image dimensions
6
+ */
7
+ var GEMINI_SIZE_TO_ASPECT_RATIO = {
8
+ "1024x1024": "1:1",
9
+ "512x512": "1:1",
10
+ "1024x768": "4:3",
11
+ "1536x1024": "4:3",
12
+ "1792x1024": "16:9",
13
+ "1920x1080": "16:9",
14
+ "768x1024": "3:4",
15
+ "1024x1536": "3:4",
16
+ "1024x1792": "9:16",
17
+ "1080x1920": "9:16"
16
18
  };
19
+ /**
20
+ * Maps a WIDTHxHEIGHT size string to a Gemini aspect ratio
21
+ * Returns undefined if the size cannot be mapped
22
+ */
17
23
  function sizeToAspectRatio(size) {
18
- if (!size) return void 0;
19
- return GEMINI_SIZE_TO_ASPECT_RATIO[size];
24
+ if (!size) return void 0;
25
+ return GEMINI_SIZE_TO_ASPECT_RATIO[size];
20
26
  }
27
+ /**
28
+ * Validates that the provided size can be mapped to an aspect ratio
29
+ * Throws an error if the size is invalid
30
+ */
21
31
  function validateImageSize(model, size) {
22
- if (!size) return;
23
- const aspectRatio = sizeToAspectRatio(size);
24
- if (!aspectRatio) {
25
- const validSizes = Object.keys(GEMINI_SIZE_TO_ASPECT_RATIO);
26
- throw new Error(
27
- `Invalid size "${size}" for model "${model}". Gemini Imagen uses aspect ratios. Valid sizes that map to aspect ratios: ${validSizes.join(", ")}. Alternatively, use providerOptions.aspectRatio directly with values: 1:1, 3:4, 4:3, 9:16, 16:9, 9:21, 21:9`
28
- );
29
- }
32
+ if (!size) return;
33
+ if (!sizeToAspectRatio(size)) {
34
+ const validSizes = Object.keys(GEMINI_SIZE_TO_ASPECT_RATIO);
35
+ throw new Error(`Invalid size "${size}" for model "${model}". Gemini Imagen uses aspect ratios. Valid sizes that map to aspect ratios: ${validSizes.join(", ")}. Alternatively, use providerOptions.aspectRatio directly with values: 1:1, 3:4, 4:3, 9:16, 16:9, 9:21, 21:9`);
36
+ }
30
37
  }
31
- const IMAGEN_MAX_IMAGES_BY_MODEL = {
32
- "imagen-4.0-generate-001": 4,
33
- "imagen-4.0-ultra-generate-001": 4,
34
- "imagen-4.0-fast-generate-001": 4
38
+ /**
39
+ * Per-model caps on images per request.
40
+ * The Imagen 4 family all support up to 4 images per request via the Gemini
41
+ * API (the rumored 8-image tier is Vertex-only and isn't reachable through
42
+ * @google/genai today). Unknown models fall through to the shared cap
43
+ * defined below.
44
+ *
45
+ * @see https://ai.google.dev/gemini-api/docs/imagen
46
+ */
47
+ var IMAGEN_MAX_IMAGES_BY_MODEL = {
48
+ "imagen-4.0-generate-001": 4,
49
+ "imagen-4.0-ultra-generate-001": 4,
50
+ "imagen-4.0-fast-generate-001": 4
35
51
  };
36
- const DEFAULT_IMAGEN_MAX_IMAGES = 4;
52
+ var DEFAULT_IMAGEN_MAX_IMAGES = 4;
53
+ /**
54
+ * Validates the number of images requested against the model's known cap.
55
+ * Uses a per-model table where available and falls back to the shared
56
+ * default otherwise — no more "some support up to 8" comments that don't
57
+ * match the error message.
58
+ */
37
59
  function validateNumberOfImages(model, numberOfImages) {
38
- if (numberOfImages === void 0) return;
39
- const maxImages = IMAGEN_MAX_IMAGES_BY_MODEL[model] ?? DEFAULT_IMAGEN_MAX_IMAGES;
40
- if (numberOfImages < 1 || numberOfImages > maxImages) {
41
- throw new Error(
42
- `Invalid numberOfImages "${numberOfImages}" for model "${model}". Must be between 1 and ${maxImages}.`
43
- );
44
- }
60
+ if (numberOfImages === void 0) return;
61
+ const maxImages = IMAGEN_MAX_IMAGES_BY_MODEL[model] ?? DEFAULT_IMAGEN_MAX_IMAGES;
62
+ if (numberOfImages < 1 || numberOfImages > maxImages) throw new Error(`Invalid numberOfImages "${numberOfImages}" for model "${model}". Must be between 1 and ${maxImages}.`);
45
63
  }
64
+ /**
65
+ * Validates the prompt is not empty
66
+ */
46
67
  function validatePrompt(options) {
47
- const { prompt, model } = options;
48
- if (!prompt || prompt.trim().length === 0) {
49
- throw new Error(`Prompt cannot be empty for model "${model}".`);
50
- }
68
+ const { prompt, model } = options;
69
+ if (!prompt || prompt.trim().length === 0) throw new Error(`Prompt cannot be empty for model "${model}".`);
51
70
  }
71
+ /**
72
+ * Parses a Gemini native image size string into its components.
73
+ * Format: "aspectRatio_resolution" e.g. "16:9_4K" → { aspectRatio: "16:9", resolution: "4K" }
74
+ */
52
75
  function parseNativeImageSize(size) {
53
- const match = size.match(/^(\d+:\d+)_(.+)$/);
54
- const [, aspectRatio, resolution] = match ?? [];
55
- if (aspectRatio === void 0 || resolution === void 0) return void 0;
56
- return { aspectRatio, resolution };
76
+ const [, aspectRatio, resolution] = size.match(/^(\d+:\d+)_(.+)$/) ?? [];
77
+ if (aspectRatio === void 0 || resolution === void 0) return void 0;
78
+ return {
79
+ aspectRatio,
80
+ resolution
81
+ };
57
82
  }
58
- export {
59
- GEMINI_SIZE_TO_ASPECT_RATIO,
60
- parseNativeImageSize,
61
- sizeToAspectRatio,
62
- validateImageSize,
63
- validateNumberOfImages,
64
- validatePrompt
65
- };
66
- //# sourceMappingURL=image-provider-options.js.map
83
+ //#endregion
84
+ export { GEMINI_SIZE_TO_ASPECT_RATIO, parseNativeImageSize, sizeToAspectRatio, validateImageSize, validateNumberOfImages, validatePrompt };
85
+
86
+ //# sourceMappingURL=image-provider-options.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"image-provider-options.js","sources":["../../../src/image/image-provider-options.ts"],"sourcesContent":["import type { GeminiImageModels } from '../model-meta'\nimport type {\n ImagePromptLanguage,\n PersonGeneration,\n SafetyFilterLevel,\n} from '@google/genai'\n\n// Re-export SDK types so users can use them directly\nexport type { ImagePromptLanguage, PersonGeneration, SafetyFilterLevel }\n\n/**\n * Gemini Imagen aspect ratio options\n * Controls the aspect ratio of generated images\n */\nexport type GeminiAspectRatio =\n | '1:1'\n | '3:4'\n | '4:3'\n | '9:16'\n | '16:9'\n | '9:21'\n | '21:9'\n\n/**\n * Provider options for Gemini image generation\n * These options match the @google/genai GenerateImagesConfig interface\n * and can be spread directly into the API request.\n */\nexport interface GeminiImageProviderOptions {\n /**\n * The aspect ratio of generated images\n * @default '1:1'\n */\n aspectRatio?: GeminiAspectRatio\n\n /**\n * Controls whether people can appear in generated images\n * Use PersonGeneration enum values: DONT_ALLOW, ALLOW_ADULT, ALLOW_ALL\n * @default 'ALLOW_ADULT'\n */\n personGeneration?: PersonGeneration\n\n /**\n * Safety filter level for content filtering\n * Use SafetyFilterLevel enum values\n */\n safetyFilterLevel?: SafetyFilterLevel\n\n /**\n * Optional seed for reproducible image generation\n * When the same seed is used with the same prompt and settings,\n * you should get similar (though not identical) results\n */\n seed?: number\n\n /**\n * Whether to add a SynthID watermark to generated images\n * SynthID helps identify AI-generated content\n * @default true\n */\n addWatermark?: boolean\n\n /**\n * Language of the prompt\n * Use ImagePromptLanguage enum values\n */\n language?: ImagePromptLanguage\n\n /**\n * Negative prompt - what to avoid in the generated image\n * Not all models support negative prompts\n */\n negativePrompt?: string\n\n /**\n * Output MIME type for the generated image\n * @default 'image/png'\n */\n outputMimeType?: 'image/png' | 'image/jpeg' | 'image/webp'\n\n /**\n * Compression quality for JPEG outputs (0-100)\n * Higher values mean better quality but larger file sizes\n * @default 75\n */\n outputCompressionQuality?: number\n\n /**\n * Controls how much the model adheres to the text prompt\n * Large values increase output and prompt alignment,\n * but may compromise image quality\n */\n guidanceScale?: number\n\n /**\n * Whether to use the prompt rewriting logic\n */\n enhancePrompt?: boolean\n\n /**\n * Whether to report the safety scores of each generated image\n * and the positive prompt in the response\n */\n includeSafetyAttributes?: boolean\n\n /**\n * Whether to include the Responsible AI filter reason\n * if the image is filtered out of the response\n */\n includeRaiReason?: boolean\n\n /**\n * Cloud Storage URI used to store the generated images\n */\n outputGcsUri?: string\n\n /**\n * User specified labels to track billing usage\n */\n labels?: Record<string, string>\n}\n\n/**\n * Model-specific provider options mapping\n * Currently all Imagen models use the same options structure\n */\nexport type GeminiImageModelProviderOptionsByName = {\n [K in GeminiImageModels]: GeminiImageProviderOptions\n}\n\n/**\n * Supported size strings for Gemini Imagen models\n * These map to aspect ratios internally\n */\nexport type GeminiImageSize =\n | '1024x1024'\n | '512x512'\n | '1024x768'\n | '1536x1024'\n | '1792x1024'\n | '1920x1080'\n | '768x1024'\n | '1024x1536'\n | '1024x1792'\n | '1080x1920'\n\n/**\n * Aspect ratios supported by Gemini native image models (via generateContent API).\n * Matches the SDK's ImageConfig.aspectRatio values.\n */\nexport type GeminiNativeImageAspectRatio =\n | '1:1'\n | '2:3'\n | '3:2'\n | '3:4'\n | '4:3'\n | '9:16'\n | '16:9'\n | '21:9'\n\n/**\n * Resolution tiers for Gemini native image models.\n * Matches the SDK's ImageConfig.imageSize values.\n */\nexport type GeminiNativeImageResolution = '1K' | '2K' | '4K'\n\n/**\n * Template literal size type for Gemini native image models: \"16:9_4K\", \"1:1_2K\", etc.\n */\nexport type GeminiNativeImageSize =\n `${GeminiNativeImageAspectRatio}_${GeminiNativeImageResolution}`\n\n/**\n * Gemini native image models that use the generateContent API path.\n * These models support template literal sizes (aspectRatio_resolution).\n */\nexport type GeminiNativeImageModels =\n | 'gemini-3.1-flash-image-preview'\n | 'gemini-3.1-flash-lite-image'\n | 'gemini-3-pro-image-preview'\n | 'gemini-2.5-flash-image'\n\n/**\n * Model-specific size options mapping.\n * Gemini native image models use template literal sizes, Imagen models use pixel sizes.\n */\nexport type GeminiImageModelSizeByName = {\n [K in GeminiNativeImageModels]: GeminiNativeImageSize\n} & {\n [K in Exclude<GeminiImageModels, GeminiNativeImageModels>]: GeminiImageSize\n}\n\n/**\n * Per-model prompt input modalities. Gemini-native image models accept image\n * parts in the multimodal prompt (image-conditioned generation via\n * generateContent); Imagen models are strictly text-to-image, so their\n * `prompt` is constrained to text at compile time.\n */\nexport type GeminiImageModelInputModalitiesByName = {\n [K in GeminiNativeImageModels]: readonly ['image']\n} & {\n [K in Exclude<GeminiImageModels, GeminiNativeImageModels>]: readonly []\n}\n\n/**\n * Valid sizes for Gemini Imagen models\n * Gemini uses aspect ratios, but we map common WIDTHxHEIGHT formats to aspect ratios\n * These are approximate mappings based on common image dimensions\n */\nexport const GEMINI_SIZE_TO_ASPECT_RATIO: Record<string, GeminiAspectRatio> = {\n // Square\n '1024x1024': '1:1',\n '512x512': '1:1',\n // Landscape\n '1024x768': '4:3',\n '1536x1024': '4:3',\n '1792x1024': '16:9',\n '1920x1080': '16:9',\n // Portrait\n '768x1024': '3:4',\n '1024x1536': '3:4', // Inverted\n '1024x1792': '9:16',\n '1080x1920': '9:16',\n}\n\n/**\n * Maps a WIDTHxHEIGHT size string to a Gemini aspect ratio\n * Returns undefined if the size cannot be mapped\n */\nexport function sizeToAspectRatio(\n size: string | undefined,\n): GeminiAspectRatio | undefined {\n if (!size) return undefined\n return GEMINI_SIZE_TO_ASPECT_RATIO[size]\n}\n\n/**\n * Validates that the provided size can be mapped to an aspect ratio\n * Throws an error if the size is invalid\n */\nexport function validateImageSize(\n model: string,\n size: string | undefined,\n): void {\n if (!size) return\n\n const aspectRatio = sizeToAspectRatio(size)\n if (!aspectRatio) {\n const validSizes = Object.keys(GEMINI_SIZE_TO_ASPECT_RATIO)\n throw new Error(\n `Invalid size \"${size}\" for model \"${model}\". ` +\n `Gemini Imagen uses aspect ratios. Valid sizes that map to aspect ratios: ${validSizes.join(', ')}. ` +\n `Alternatively, use providerOptions.aspectRatio directly with values: 1:1, 3:4, 4:3, 9:16, 16:9, 9:21, 21:9`,\n )\n }\n}\n\n/**\n * Per-model caps on images per request.\n * The Imagen 4 family all support up to 4 images per request via the Gemini\n * API (the rumored 8-image tier is Vertex-only and isn't reachable through\n * @google/genai today). Unknown models fall through to the shared cap\n * defined below.\n *\n * @see https://ai.google.dev/gemini-api/docs/imagen\n */\nconst IMAGEN_MAX_IMAGES_BY_MODEL: Record<string, number> = {\n 'imagen-4.0-generate-001': 4,\n 'imagen-4.0-ultra-generate-001': 4,\n 'imagen-4.0-fast-generate-001': 4,\n}\n\nconst DEFAULT_IMAGEN_MAX_IMAGES = 4\n\n/**\n * Validates the number of images requested against the model's known cap.\n * Uses a per-model table where available and falls back to the shared\n * default otherwise — no more \"some support up to 8\" comments that don't\n * match the error message.\n */\nexport function validateNumberOfImages(\n model: string,\n numberOfImages: number | undefined,\n): void {\n if (numberOfImages === undefined) return\n\n const maxImages =\n IMAGEN_MAX_IMAGES_BY_MODEL[model] ?? DEFAULT_IMAGEN_MAX_IMAGES\n if (numberOfImages < 1 || numberOfImages > maxImages) {\n throw new Error(\n `Invalid numberOfImages \"${numberOfImages}\" for model \"${model}\". ` +\n `Must be between 1 and ${maxImages}.`,\n )\n }\n}\n\n/**\n * Validates the prompt is not empty\n */\nexport function validatePrompt(options: {\n prompt: string\n model: string\n}): void {\n const { prompt, model } = options\n if (!prompt || prompt.trim().length === 0) {\n throw new Error(`Prompt cannot be empty for model \"${model}\".`)\n }\n}\n\n/**\n * Parses a Gemini native image size string into its components.\n * Format: \"aspectRatio_resolution\" e.g. \"16:9_4K\" → { aspectRatio: \"16:9\", resolution: \"4K\" }\n */\nexport function parseNativeImageSize(\n size: string,\n): { aspectRatio: string; resolution: string } | undefined {\n const match = size.match(/^(\\d+:\\d+)_(.+)$/)\n const [, aspectRatio, resolution] = match ?? []\n if (aspectRatio === undefined || resolution === undefined) return undefined\n return { aspectRatio, resolution }\n}\n"],"names":[],"mappings":"AAiNO,MAAM,8BAAiE;AAAA;AAAA,EAE5E,aAAa;AAAA,EACb,WAAW;AAAA;AAAA,EAEX,YAAY;AAAA,EACZ,aAAa;AAAA,EACb,aAAa;AAAA,EACb,aAAa;AAAA;AAAA,EAEb,YAAY;AAAA,EACZ,aAAa;AAAA;AAAA,EACb,aAAa;AAAA,EACb,aAAa;AACf;AAMO,SAAS,kBACd,MAC+B;AAC/B,MAAI,CAAC,KAAM,QAAO;AAClB,SAAO,4BAA4B,IAAI;AACzC;AAMO,SAAS,kBACd,OACA,MACM;AACN,MAAI,CAAC,KAAM;AAEX,QAAM,cAAc,kBAAkB,IAAI;AAC1C,MAAI,CAAC,aAAa;AAChB,UAAM,aAAa,OAAO,KAAK,2BAA2B;AAC1D,UAAM,IAAI;AAAA,MACR,iBAAiB,IAAI,gBAAgB,KAAK,+EACoC,WAAW,KAAK,IAAI,CAAC;AAAA,IAAA;AAAA,EAGvG;AACF;AAWA,MAAM,6BAAqD;AAAA,EACzD,2BAA2B;AAAA,EAC3B,iCAAiC;AAAA,EACjC,gCAAgC;AAClC;AAEA,MAAM,4BAA4B;AAQ3B,SAAS,uBACd,OACA,gBACM;AACN,MAAI,mBAAmB,OAAW;AAElC,QAAM,YACJ,2BAA2B,KAAK,KAAK;AACvC,MAAI,iBAAiB,KAAK,iBAAiB,WAAW;AACpD,UAAM,IAAI;AAAA,MACR,2BAA2B,cAAc,gBAAgB,KAAK,4BACnC,SAAS;AAAA,IAAA;AAAA,EAExC;AACF;AAKO,SAAS,eAAe,SAGtB;AACP,QAAM,EAAE,QAAQ,MAAA,IAAU;AAC1B,MAAI,CAAC,UAAU,OAAO,KAAA,EAAO,WAAW,GAAG;AACzC,UAAM,IAAI,MAAM,qCAAqC,KAAK,IAAI;AAAA,EAChE;AACF;AAMO,SAAS,qBACd,MACyD;AACzD,QAAM,QAAQ,KAAK,MAAM,kBAAkB;AAC3C,QAAM,GAAG,aAAa,UAAU,IAAI,SAAS,CAAA;AAC7C,MAAI,gBAAgB,UAAa,eAAe,OAAW,QAAO;AAClE,SAAO,EAAE,aAAa,WAAA;AACxB;"}
1
+ {"version":3,"file":"image-provider-options.js","names":[],"sources":["../../../src/image/image-provider-options.ts"],"sourcesContent":["import type { GeminiImageModels } from '../model-meta'\nimport type {\n ImagePromptLanguage,\n PersonGeneration,\n SafetyFilterLevel,\n} from '@google/genai'\n\n// Re-export SDK types so users can use them directly\nexport type { ImagePromptLanguage, PersonGeneration, SafetyFilterLevel }\n\n/**\n * Gemini Imagen aspect ratio options\n * Controls the aspect ratio of generated images\n */\nexport type GeminiAspectRatio =\n | '1:1'\n | '3:4'\n | '4:3'\n | '9:16'\n | '16:9'\n | '9:21'\n | '21:9'\n\n/**\n * Provider options for Gemini image generation\n * These options match the @google/genai GenerateImagesConfig interface\n * and can be spread directly into the API request.\n */\nexport interface GeminiImageProviderOptions {\n /**\n * The aspect ratio of generated images\n * @default '1:1'\n */\n aspectRatio?: GeminiAspectRatio\n\n /**\n * Controls whether people can appear in generated images\n * Use PersonGeneration enum values: DONT_ALLOW, ALLOW_ADULT, ALLOW_ALL\n * @default 'ALLOW_ADULT'\n */\n personGeneration?: PersonGeneration\n\n /**\n * Safety filter level for content filtering\n * Use SafetyFilterLevel enum values\n */\n safetyFilterLevel?: SafetyFilterLevel\n\n /**\n * Optional seed for reproducible image generation\n * When the same seed is used with the same prompt and settings,\n * you should get similar (though not identical) results\n */\n seed?: number\n\n /**\n * Whether to add a SynthID watermark to generated images\n * SynthID helps identify AI-generated content\n * @default true\n */\n addWatermark?: boolean\n\n /**\n * Language of the prompt\n * Use ImagePromptLanguage enum values\n */\n language?: ImagePromptLanguage\n\n /**\n * Negative prompt - what to avoid in the generated image\n * Not all models support negative prompts\n */\n negativePrompt?: string\n\n /**\n * Output MIME type for the generated image\n * @default 'image/png'\n */\n outputMimeType?: 'image/png' | 'image/jpeg' | 'image/webp'\n\n /**\n * Compression quality for JPEG outputs (0-100)\n * Higher values mean better quality but larger file sizes\n * @default 75\n */\n outputCompressionQuality?: number\n\n /**\n * Controls how much the model adheres to the text prompt\n * Large values increase output and prompt alignment,\n * but may compromise image quality\n */\n guidanceScale?: number\n\n /**\n * Whether to use the prompt rewriting logic\n */\n enhancePrompt?: boolean\n\n /**\n * Whether to report the safety scores of each generated image\n * and the positive prompt in the response\n */\n includeSafetyAttributes?: boolean\n\n /**\n * Whether to include the Responsible AI filter reason\n * if the image is filtered out of the response\n */\n includeRaiReason?: boolean\n\n /**\n * Cloud Storage URI used to store the generated images\n */\n outputGcsUri?: string\n\n /**\n * User specified labels to track billing usage\n */\n labels?: Record<string, string>\n}\n\n/**\n * Model-specific provider options mapping\n * Currently all Imagen models use the same options structure\n */\nexport type GeminiImageModelProviderOptionsByName = {\n [K in GeminiImageModels]: GeminiImageProviderOptions\n}\n\n/**\n * Supported size strings for Gemini Imagen models\n * These map to aspect ratios internally\n */\nexport type GeminiImageSize =\n | '1024x1024'\n | '512x512'\n | '1024x768'\n | '1536x1024'\n | '1792x1024'\n | '1920x1080'\n | '768x1024'\n | '1024x1536'\n | '1024x1792'\n | '1080x1920'\n\n/**\n * Aspect ratios supported by Gemini native image models (via generateContent API).\n * Matches the SDK's ImageConfig.aspectRatio values.\n */\nexport type GeminiNativeImageAspectRatio =\n | '1:1'\n | '2:3'\n | '3:2'\n | '3:4'\n | '4:3'\n | '9:16'\n | '16:9'\n | '21:9'\n\n/**\n * Resolution tiers for Gemini native image models.\n * Matches the SDK's ImageConfig.imageSize values.\n */\nexport type GeminiNativeImageResolution = '1K' | '2K' | '4K'\n\n/**\n * Template literal size type for Gemini native image models: \"16:9_4K\", \"1:1_2K\", etc.\n */\nexport type GeminiNativeImageSize =\n `${GeminiNativeImageAspectRatio}_${GeminiNativeImageResolution}`\n\n/**\n * Gemini native image models that use the generateContent API path.\n * These models support template literal sizes (aspectRatio_resolution).\n */\nexport type GeminiNativeImageModels =\n | 'gemini-3.1-flash-image-preview'\n | 'gemini-3.1-flash-lite-image'\n | 'gemini-3-pro-image-preview'\n | 'gemini-2.5-flash-image'\n\n/**\n * Model-specific size options mapping.\n * Gemini native image models use template literal sizes, Imagen models use pixel sizes.\n */\nexport type GeminiImageModelSizeByName = {\n [K in GeminiNativeImageModels]: GeminiNativeImageSize\n} & {\n [K in Exclude<GeminiImageModels, GeminiNativeImageModels>]: GeminiImageSize\n}\n\n/**\n * Per-model prompt input modalities. Gemini-native image models accept image\n * parts in the multimodal prompt (image-conditioned generation via\n * generateContent); Imagen models are strictly text-to-image, so their\n * `prompt` is constrained to text at compile time.\n */\nexport type GeminiImageModelInputModalitiesByName = {\n [K in GeminiNativeImageModels]: readonly ['image']\n} & {\n [K in Exclude<GeminiImageModels, GeminiNativeImageModels>]: readonly []\n}\n\n/**\n * Valid sizes for Gemini Imagen models\n * Gemini uses aspect ratios, but we map common WIDTHxHEIGHT formats to aspect ratios\n * These are approximate mappings based on common image dimensions\n */\nexport const GEMINI_SIZE_TO_ASPECT_RATIO: Record<string, GeminiAspectRatio> = {\n // Square\n '1024x1024': '1:1',\n '512x512': '1:1',\n // Landscape\n '1024x768': '4:3',\n '1536x1024': '4:3',\n '1792x1024': '16:9',\n '1920x1080': '16:9',\n // Portrait\n '768x1024': '3:4',\n '1024x1536': '3:4', // Inverted\n '1024x1792': '9:16',\n '1080x1920': '9:16',\n}\n\n/**\n * Maps a WIDTHxHEIGHT size string to a Gemini aspect ratio\n * Returns undefined if the size cannot be mapped\n */\nexport function sizeToAspectRatio(\n size: string | undefined,\n): GeminiAspectRatio | undefined {\n if (!size) return undefined\n return GEMINI_SIZE_TO_ASPECT_RATIO[size]\n}\n\n/**\n * Validates that the provided size can be mapped to an aspect ratio\n * Throws an error if the size is invalid\n */\nexport function validateImageSize(\n model: string,\n size: string | undefined,\n): void {\n if (!size) return\n\n const aspectRatio = sizeToAspectRatio(size)\n if (!aspectRatio) {\n const validSizes = Object.keys(GEMINI_SIZE_TO_ASPECT_RATIO)\n throw new Error(\n `Invalid size \"${size}\" for model \"${model}\". ` +\n `Gemini Imagen uses aspect ratios. Valid sizes that map to aspect ratios: ${validSizes.join(', ')}. ` +\n `Alternatively, use providerOptions.aspectRatio directly with values: 1:1, 3:4, 4:3, 9:16, 16:9, 9:21, 21:9`,\n )\n }\n}\n\n/**\n * Per-model caps on images per request.\n * The Imagen 4 family all support up to 4 images per request via the Gemini\n * API (the rumored 8-image tier is Vertex-only and isn't reachable through\n * @google/genai today). Unknown models fall through to the shared cap\n * defined below.\n *\n * @see https://ai.google.dev/gemini-api/docs/imagen\n */\nconst IMAGEN_MAX_IMAGES_BY_MODEL: Record<string, number> = {\n 'imagen-4.0-generate-001': 4,\n 'imagen-4.0-ultra-generate-001': 4,\n 'imagen-4.0-fast-generate-001': 4,\n}\n\nconst DEFAULT_IMAGEN_MAX_IMAGES = 4\n\n/**\n * Validates the number of images requested against the model's known cap.\n * Uses a per-model table where available and falls back to the shared\n * default otherwise — no more \"some support up to 8\" comments that don't\n * match the error message.\n */\nexport function validateNumberOfImages(\n model: string,\n numberOfImages: number | undefined,\n): void {\n if (numberOfImages === undefined) return\n\n const maxImages =\n IMAGEN_MAX_IMAGES_BY_MODEL[model] ?? DEFAULT_IMAGEN_MAX_IMAGES\n if (numberOfImages < 1 || numberOfImages > maxImages) {\n throw new Error(\n `Invalid numberOfImages \"${numberOfImages}\" for model \"${model}\". ` +\n `Must be between 1 and ${maxImages}.`,\n )\n }\n}\n\n/**\n * Validates the prompt is not empty\n */\nexport function validatePrompt(options: {\n prompt: string\n model: string\n}): void {\n const { prompt, model } = options\n if (!prompt || prompt.trim().length === 0) {\n throw new Error(`Prompt cannot be empty for model \"${model}\".`)\n }\n}\n\n/**\n * Parses a Gemini native image size string into its components.\n * Format: \"aspectRatio_resolution\" e.g. \"16:9_4K\" → { aspectRatio: \"16:9\", resolution: \"4K\" }\n */\nexport function parseNativeImageSize(\n size: string,\n): { aspectRatio: string; resolution: string } | undefined {\n const match = size.match(/^(\\d+:\\d+)_(.+)$/)\n const [, aspectRatio, resolution] = match ?? []\n if (aspectRatio === undefined || resolution === undefined) return undefined\n return { aspectRatio, resolution }\n}\n"],"mappings":";;;;;;AAiNA,IAAa,8BAAiE;CAE5E,aAAa;CACb,WAAW;CAEX,YAAY;CACZ,aAAa;CACb,aAAa;CACb,aAAa;CAEb,YAAY;CACZ,aAAa;CACb,aAAa;CACb,aAAa;AACf;;;;;AAMA,SAAgB,kBACd,MAC+B;CAC/B,IAAI,CAAC,MAAM,OAAO,KAAA;CAClB,OAAO,4BAA4B;AACrC;;;;;AAMA,SAAgB,kBACd,OACA,MACM;CACN,IAAI,CAAC,MAAM;CAGX,IAAI,CADgB,kBAAkB,IACjC,GAAa;EAChB,MAAM,aAAa,OAAO,KAAK,2BAA2B;EAC1D,MAAM,IAAI,MACR,iBAAiB,KAAK,eAAe,MAAM,8EACmC,WAAW,KAAK,IAAI,EAAE,6GAEtG;CACF;AACF;;;;;;;;;;AAWA,IAAM,6BAAqD;CACzD,2BAA2B;CAC3B,iCAAiC;CACjC,gCAAgC;AAClC;AAEA,IAAM,4BAA4B;;;;;;;AAQlC,SAAgB,uBACd,OACA,gBACM;CACN,IAAI,mBAAmB,KAAA,GAAW;CAElC,MAAM,YACJ,2BAA2B,UAAU;CACvC,IAAI,iBAAiB,KAAK,iBAAiB,WACzC,MAAM,IAAI,MACR,2BAA2B,eAAe,eAAe,MAAM,2BACpC,UAAU,EACvC;AAEJ;;;;AAKA,SAAgB,eAAe,SAGtB;CACP,MAAM,EAAE,QAAQ,UAAU;CAC1B,IAAI,CAAC,UAAU,OAAO,KAAK,CAAC,CAAC,WAAW,GACtC,MAAM,IAAI,MAAM,qCAAqC,MAAM,GAAG;AAElE;;;;;AAMA,SAAgB,qBACd,MACyD;CAEzD,MAAM,GAAG,aAAa,cADR,KAAK,MAAM,kBACW,KAAS,CAAC;CAC9C,IAAI,gBAAgB,KAAA,KAAa,eAAe,KAAA,GAAW,OAAO,KAAA;CAClE,OAAO;EAAE;EAAa;CAAW;AACnC"}