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

gemini.md

919 lines33.2 KB

1---
2title: Google Gemini
3id: gemini-adapter
4order: 3
5description: "Use Google Gemini with TanStack AI — text, image generation via Imagen and Gemini native (NanoBanana), and experimental TTS via @tanstack/ai-gemini."
6keywords:
7 - tanstack ai
8 - gemini
9 - google gemini
10 - imagen
11 - nano banana
12 - image generation
13 - adapter
14 - google ai
15---
16​
17The Google Gemini adapter provides access to Google's Gemini models, including text generation, image generation with both Imagen and Gemini native image models (NanoBanana), and experimental text-to-speech.
18​
19For a full working example with image generation, see the [media generation example app](https://github.com/TanStack/ai/tree/main/examples/ts-react-media).
20​
21## Installation
22​
23<!-- ::start:tabs variant="package-manager" mode="install" -->
24​
25react: @tanstack/ai-gemini
26vue: @tanstack/ai-gemini
27solid: @tanstack/ai-gemini
28svelte: @tanstack/ai-gemini
29preact: @tanstack/ai-gemini
30angular: @tanstack/ai-gemini
31vanilla: @tanstack/ai-gemini
32octane: @tanstack/ai-gemini
33​
34<!-- ::end:tabs -->
35​
36Need Gemini on Vertex AI (regional endpoints and Google Cloud credentials)? Use the [Vertex adapter](./vertex).
37​
38## Basic Usage
39​
40Use `gemini-3.8-flash` for chat with multimodal input, thinking, and built-in tools. It also supports structured output and caching.
41​
42For Gemini 3.8 Flash, set `modelOptions.thinkingConfig.thinkingLevel` to `LOW`, `MEDIUM`, or `HIGH`. The Interactions adapter uses `modelOptions.generation_config.thinking_level` with `low`, `medium`, or `high`. Gemini 3.8 Flash does not accept the `minimal` thinking level.
43​
44```typescript
45import { chat } from "@tanstack/ai";
46import { geminiText } from "@tanstack/ai-gemini";
47​
48const stream = chat({
49 adapter: geminiText("gemini-3.8-flash"),
50 messages: [{ role: "user", content: "Hello!" }],
51});
52```
53​
54## Basic Usage - Custom API Key
55​
56```typescript
57import { chat } from "@tanstack/ai";
58import { createGeminiChat } from "@tanstack/ai-gemini";
59​
60const adapter = createGeminiChat("gemini-3.1-pro-preview", process.env.GEMINI_API_KEY!, {
61 // ... your config options
62});
63​
64const stream = chat({
65 adapter,
66 messages: [{ role: "user", content: "Hello!" }],
67});
68```
69​
70## Configuration
71​
72```typescript
73import { createGeminiChat, type GeminiTextConfig } from "@tanstack/ai-gemini";
74​
75const config: Omit<GeminiTextConfig, "apiKey"> = {
76 baseURL: "https://generativelanguage.googleapis.com/v1beta", // Optional
77 defaultHeaders: { "X-Custom-Header": "value" }, // Optional
78};
79​
80const adapter = createGeminiChat("gemini-3.1-pro-preview", process.env.GEMINI_API_KEY!, config);
81```
83​
84## Behind a proxy
85​
86Route every request through a gateway, such as Cloudflare AI Gateway or a corporate proxy, with `baseURL` and `defaultHeaders`. These two option names are the same on every TanStack AI adapter, so one gateway config works for all of them.
87​
88```typescript
89import { createGeminiChat } from "@tanstack/ai-gemini";
90​
91const adapter = createGeminiChat("gemini-3.8-flash", process.env.GEMINI_API_KEY!, {
92 baseURL: "https://gateway.example.com/google-ai-studio",
93 defaultHeaders: { "cf-aig-authorization": `Bearer ${process.env.GATEWAY_TOKEN}` },
94});
95```
96​
97`baseURL` sets `httpOptions.baseUrl` and `defaultHeaders` sets `httpOptions.headers`. If you set both forms, `baseURL` and `defaultHeaders` win.
98​
99## Example: Chat Completion
100​
101```typescript
102import { chat, toServerSentEventsResponse } from "@tanstack/ai";
103import { geminiText } from "@tanstack/ai-gemini";
104​
105export async function POST(request: Request) {
106 const { messages } = await request.json();
107​
108 const stream = chat({
109 adapter: geminiText("gemini-3.1-pro-preview"),
110 messages,
111 });
112​
113 return toServerSentEventsResponse(stream);
115```
116​
117## Example: With Tools
118​
119```typescript
120import { chat, toServerSentEventsResponse, toolDefinition } from "@tanstack/ai";
121import { geminiText } from "@tanstack/ai-gemini";
122import { z } from "zod";
123​
124const getCalendarEventsDef = toolDefinition({
125 name: "get_calendar_events",
126 description: "Get calendar events for a date",
127 inputSchema: z.object({
128 date: z.string(),
129 }),
130});
131​
132const getCalendarEvents = getCalendarEventsDef.server(async ({ date }) => {
133 // Fetch calendar events
134 return { events: [] };
135});
136​
137export async function POST(request: Request) {
138 const { messages } = await request.json();
139​
140 const stream = chat({
141 adapter: geminiText("gemini-3.1-pro-preview"),
142 messages,
143 tools: [getCalendarEvents],
144 });
145​
146 return toServerSentEventsResponse(stream);
148```
149​
150## Video Understanding
151​
152Ask questions about a video: "what happens at 0:30?", "summarize the demo", "list every product shown". Upload the file once, then chat about it.
153​
154Video is too large to inline as base64, so upload it to the Gemini Files API first. `uploadGeminiFile()` uploads the file and waits until it is ready to use. `geminiVideoPart()` turns that upload into a message content part.
155​
156```typescript
157import { chat, toServerSentEventsResponse } from "@tanstack/ai";
158import { geminiText, uploadGeminiFile, geminiVideoPart } from "@tanstack/ai-gemini";
159​
160export async function POST(request: Request) {
161 const file = await uploadGeminiFile("./demo.mp4", { mimeType: "video/mp4" });
162​
163 const stream = chat({
164 adapter: geminiText("gemini-3.8-flash"),
165 messages: [
166 {
167 role: "user",
168 content: [
169 { type: "text", content: "Summarize this video and cite timestamps." },
170 geminiVideoPart(file),
171 ],
172 },
173 ],
174 });
175​
176 return toServerSentEventsResponse(stream);
178```
179​
180By default Gemini samples the video at 1 frame per second. Tune that single-pass sampling through the part metadata:
181​
182```typescript ignore
183// Watch a 30s-90s clip at half a frame per second.
184geminiVideoPart(file, { fps: 0.5, startOffset: "30s", endOffset: "90s" });
185```
186​
187### Agentic understanding
188​
189Single-pass sampling can miss detail in long or fast-moving videos. Set `processing: "agentic"` to let the model drive: it navigates the timeline and pulls frames, transcripts, and audio on demand. Supported models:
190​
191- `gemini-3.8-flash`
192- `gemini-3.7-flash`
193- `gemini-3.6-flash`
194- `gemini-3.5-flash-lite`
195​
196```typescript ignore
197geminiVideoPart(file, { processing: "agentic" });
198```
199​
200With `agentic`, the adapter routes the request through Gemini's Interactions API, and you express the sampling rate in your prompt ("watch it at 2 fps") instead of through `fps`. It is deeper but slower, since it re-analyzes the video on each turn.
201​
202## Stateful Conversations — Interactions API (Experimental)
203​
204Gemini's [Interactions API](https://ai.google.dev/gemini-api/docs/interactions) (currently in Beta) offers server-side conversation state — the Gemini equivalent of OpenAI's Responses API. Instead of replaying the full message history on every turn, you pass a `previous_interaction_id` and the server retains the transcript. This also improves cache hit rates for repeated prefixes.
205​
206The `geminiTextInteractions` adapter routes through `client.interactions.create` and surfaces the server-assigned interaction id via an AG-UI `CUSTOM` event (`name: 'gemini.interactionId'`) emitted just before `RUN_FINISHED`, so you can chain turns.
207​
208> **⚠️ Experimental.** Google marks the Interactions API as Beta and explicitly flags possible breaking changes until it reaches general availability. The adapter is exported from the `@tanstack/ai-gemini/experimental` subpath so the experimental status is load-bearing in your editor and bundle. Text output, function tools, and the built-in tools `google_search`, `code_execution`, `url_context`, `file_search`, and `computer_use` are supported. `google_search_retrieval`, `google_maps`, and `mcp_server` still throw on this adapter — use `geminiText()` for those or wait for follow-up work.
209​
210### Basic Usage
211​
212```typescript ignore
213import { chat } from "@tanstack/ai";
214import { geminiTextInteractions } from "@tanstack/ai-gemini/experimental";
215​
216// Turn 1: introduce yourself, capture the interaction id.
217let interactionId: string | undefined;
218​
219for await (const chunk of chat({
220 adapter: geminiTextInteractions("gemini-3.5-flash"),
221 messages: [{ role: "user", content: "Hi, my name is Amir." }],
222})) {
223 if (
224 chunk.type === "CUSTOM" &&
225 chunk.name === "gemini.interactionId" &&
226 chunk.value &&
227 typeof chunk.value === "object" &&
228 "interactionId" in chunk.value
229 ) {
230 interactionId = String(chunk.value.interactionId);
231 }
233​
234// Turn 2: only send the new turn's content — the server has the history.
235for await (const chunk of chat({
236 adapter: geminiTextInteractions("gemini-3.5-flash"),
237 messages: [{ role: "user", content: "What is my name?" }],
238 modelOptions: {
239 previous_interaction_id: interactionId,
240 },
241})) {
242 // ...stream "Your name is Amir." back to the client.
244```
245​
246### Wiring with `useChat` (React)
247​
248The Interactions API is stateful and **does not accept multi-turn history without a `previous_interaction_id`** — if a chat client sends `[user, assistant, user]` to a fresh interaction the adapter throws `cannot send prior conversation history on a fresh interaction`. To make `useChat` work, persist the server-assigned id and send it back on the next turn:
249​
250**Server route** (e.g. TanStack Start handler):
251​
252```typescript
253import {
254 chat,
255 chatParamsFromRequestBody,
256 toServerSentEventsResponse,
257} from "@tanstack/ai";
258import { geminiTextInteractions } from "@tanstack/ai-gemini/experimental";
259​
260export async function POST({ request }: { request: Request }) {
261 const params = await chatParamsFromRequestBody(await request.json());
262​
263 // The client sends body.previousInteractionId; AG-UI maps `body` into
264 // `forwardedProps` on the wire.
265 const previousInteractionId =
266 typeof params.forwardedProps.previousInteractionId === "string"
267 ? params.forwardedProps.previousInteractionId
268 : undefined;
269​
270 const stream = chat({
271 adapter: geminiTextInteractions("gemini-3.5-flash"),
272 messages: params.messages,
273 modelOptions: {
274 previous_interaction_id: previousInteractionId,
275 store: true, // required for chaining on the next turn
276 },
277 });
278​
279 return toServerSentEventsResponse(stream);
281```
282​
283**React client**:
284​
285```tsx
286import { useEffect, useMemo, useState } from "react";
287import { fetchServerSentEvents, useChat } from "@tanstack/ai-react";
288​
289function GeminiChat() {
290 const [interactionId, setInteractionId] = useState<string | undefined>();
291​
292 const body = useMemo(
293 () => (interactionId ? { previousInteractionId: interactionId } : {}),
294 [interactionId],
295 );
296​
297 const { messages, setMessages, sendMessage } = useChat({
298 connection: fetchServerSentEvents("/api/chat"),
299 body,
300 onCustomEvent: (eventType, data) => {
301 if (
302 eventType === "gemini.interactionId" &&
303 typeof data === "object" &&
304 data !== null &&
305 "interactionId" in data
306 ) {
307 setInteractionId(String(data.interactionId));
308 }
309 },
310 });
311​
312 // Switching provider/model resets the server-side chain — drop the id
313 // AND the local message history together, otherwise the next turn
314 // ships multi-turn messages with no previous_interaction_id and the
315 // adapter errors out.
316 const [provider, setProvider] = useState("gemini-interactions");
317 useEffect(() => {
318 setInteractionId(undefined);
319 setMessages([]);
320 }, [provider]);
321​
322 // ...render messages, call sendMessage(input)
324```
325​
326The full working example is in [`examples/ts-react-chat`](https://github.com/TanStack/ai/tree/main/examples/ts-react-chat) — see `src/routes/index.tsx` for the client and `src/routes/api.tanchat.ts` for the route.
327​
328### How it differs from `geminiText`
329​
330| Concern | `geminiText` | `geminiTextInteractions` |
331| --- | --- | --- |
332| Underlying endpoint | `models:generateContent` | `interactions:create` |
333| Conversation state | Stateless — send full history each turn | Stateful — server retains transcript via `previous_interaction_id` |
334| Provider options shape | camelCase (`stopSequences`, `responseModalities`, `safetySettings`) | snake_case (`generation_config`, `response_modalities`, `previous_interaction_id`) |
335| Built-in tools | `google_search`, `code_execution`, `url_context`, `file_search`, `google_maps`, `google_search_retrieval`, `computer_use` | `google_search`, `code_execution`, `url_context`, `file_search`, `computer_use` (only the first four stream `CUSTOM` event activity; `computer_use` is accepted in the request but does not currently emit per-delta events) |
336| Stability | GA | Experimental (Google Beta) |
337​
338### Provider Options
339​
340The adapter exposes Interactions-specific options on `modelOptions`:
341​
342```typescript
343import { chat } from "@tanstack/ai";
344import { geminiTextInteractions } from "@tanstack/ai-gemini/experimental";
345​
346const stream = chat({
347 adapter: geminiTextInteractions("gemini-3.5-flash"),
348 messages: [{ role: "user", content: "Hello!" }],
349 modelOptions: {
350 // Stateful chaining — passed only on turn 2+.
351 previous_interaction_id: "int_abc123",
352​
353 // Persist the interaction server-side (default true). Must be true for
354 // previous_interaction_id to work on the *next* turn.
355 store: true,
356​
357 // Per-request system instruction (interaction-scoped — re-specify each turn).
358 system_instruction: "You are a helpful assistant.",
359​
360 // snake_case generation config distinct from geminiText's camelCase one.
361 generation_config: {
362 thinking_level: "low",
363 thinking_summaries: "auto",
364 stop_sequences: ["<done>"],
365 },
366​
367 response_modalities: ["text"],
368 },
369});
370```
371​
372### Reading the interaction id
373​
374The server's interaction id arrives as an AG-UI `CUSTOM` event emitted just before `RUN_FINISHED`:
375​
376```typescript ignore
377for await (const chunk of stream) {
378 if (
379 chunk.type === "CUSTOM" &&
380 chunk.name === "gemini.interactionId" &&
381 typeof chunk.value === "object" &&
382 chunk.value !== null &&
383 "interactionId" in chunk.value
384 ) {
385 const id = String(chunk.value.interactionId);
386 // Persist `id` wherever you store per-user conversation pointers —
387 // pass it back on the next turn as `previous_interaction_id`.
388 }
390```
391​
392### Caveats
393​
394- **Multi-turn history requires `previous_interaction_id`.** The Interactions API has no stateless replay path — sending more than one message in `messages` without a `previous_interaction_id` throws. Chat UIs that maintain local history must capture the server-assigned id and chain (see [Wiring with `useChat`](#wiring-with-usechat-react)). On provider/model switch, also clear the local message buffer.
395- **Tools, `system_instruction`, and `generation_config` are interaction-scoped.** Per Google's docs these are NOT inherited from a prior interaction via `previous_interaction_id` — pass them again on every turn you need them.
396- `store: false` is incompatible with `previous_interaction_id` (no state to recall) and with `background: true`.
397- Retention (as of the time of writing): **55 days on the Paid Tier, 1 day on the Free Tier.** See [Google's Interactions API docs](https://ai.google.dev/gemini-api/docs/interactions) for current retention policy.
398- Built-in tools in scope (`google_search`, `code_execution`, `url_context`, `file_search`, `computer_use`) are wired through as request tools. Per-delta activity for the four search/exec tools streams back as AG-UI `CUSTOM` events — `gemini.googleSearchCall` / `gemini.googleSearchResult` (and the matching `codeExecutionCall`/`Result`, `urlContextCall`/`Result`, `fileSearchCall`/`Result`) — carrying the raw Interactions delta. `computer_use` is accepted in the request but the Interactions API does not currently emit per-delta `CUSTOM` events for it. Function-tool `TOOL_CALL_*` events are unchanged, and `finishReason` stays `stop` when only built-in tools ran.
399- `google_search_retrieval`, `google_maps`, and `mcp_server` still throw a targeted error on this adapter. Use `geminiText()` for the first two, or wait for a dedicated follow-up for `mcp_server`.
400- Image and audio output via Interactions aren't routed through this adapter yet — it's text-only. Use `geminiImage` / `geminiSpeech` for non-text generation for now.
401​
402## Model Options
403​
404Gemini supports various model-specific options. Sampling parameters live here too — `temperature`, `topP`, and `maxOutputTokens` — rather than as root-level props on `chat()`:
405​
406```typescript
407import { chat } from "@tanstack/ai";
408import { geminiText } from "@tanstack/ai-gemini";
409​
410const stream = chat({
411 adapter: geminiText("gemini-3.1-pro-preview"),
412 messages: [{ role: "user", content: "Hello!" }],
413 modelOptions: {
414 maxOutputTokens: 2048,
415 temperature: 0.7,
416 topP: 0.9,
417 topK: 40,
418 stopSequences: ["END"],
419 },
420});
421```
422​
423> If you previously passed `temperature` / `topP` / `maxTokens` at the root of `chat()`, see [Moving Sampling Options into modelOptions](../migration/sampling-options-to-model-options).
424​
425### Thinking
426​
427Enable thinking for models that support it:
428​
429```typescript ignore
430modelOptions: {
431 thinking: {
432 includeThoughts: true,
433 },
435```
436​
437### Structured Output
438​
439Configure structured output format:
440​
441```typescript ignore
442modelOptions: {
443 responseMimeType: "application/json",
445```
446​
447## Summarization
448​
449Summarize long text content:
450​
451```typescript
452import { summarize } from "@tanstack/ai";
453import { geminiSummarize } from "@tanstack/ai-gemini";
454​
455const result = await summarize({
456 adapter: geminiSummarize("gemini-3.1-pro-preview"),
457 text: "Your long text to summarize...",
458 maxLength: 100,
459 style: "concise", // "concise" | "bullet-points" | "paragraph"
460});
461​
462console.log(result.summary);
463```
464​
465## Embeddings
466​
467Generate embedding vectors with gemini-embedding-001:
468​
469```typescript
470import { embed } from "@tanstack/ai";
471import { geminiEmbedding } from "@tanstack/ai-gemini";
472​
473const result = await embed({
474 adapter: geminiEmbedding("gemini-embedding-001"),
475 input: "a red guitar",
476 dimensions: 1536,
477 modelOptions: {
478 taskType: "RETRIEVAL_DOCUMENT",
479 },
480});
481​
482console.log(result.embeddings[0]?.vector);
483```
484​
485> The Gemini API's embedding endpoint does not report token usage, so
486> `result.usage` is absent. The Vertex-only multimodal embedding model
487> (`multimodalembedding@001`) is not supported by this adapter.
488​
489See the [Embeddings guide](../embeddings.md) for the full API.
490​
491## Image Generation
492​
493The Gemini adapter supports two types of image generation:
494​
495- **Gemini native image models** (NanoBanana) — Use the `generateContent` API with models like `gemini-3.1-flash-image`. These support aspect ratio control plus resolution tiers (`512`, `1K`, `2K`, `4K`); which ratios and tiers are accepted varies per model and is enforced at compile time.
496- **Imagen models** — Use the `generateImages` API with models like `imagen-4.0-generate-001`. These are dedicated image generation models with WIDTHxHEIGHT sizing.
497​
498The adapter routes to `generateContent` when the model is in
499`GEMINI_NATIVE_IMAGE_MODELS`. Imagen models, and any id this package does not
500know, use `generateImages`. Import the list or `isGeminiNativeImageModel`
501from `@tanstack/ai-gemini`.
502​
503### Example: Gemini Native Image Generation (NanoBanana)
504​
505From the [media generation example app](https://github.com/TanStack/ai/tree/main/examples/ts-react-media):
506​
507```typescript
508import { generateImage } from "@tanstack/ai";
509import { geminiImage } from "@tanstack/ai-gemini";
510​
511const result = await generateImage({
512 adapter: geminiImage("gemini-3.1-flash-image"),
513 prompt: "A futuristic cityscape at sunset",
514 numberOfImages: 1,
515 size: "16:9_4K",
516});
517​
518console.log(result.images);
519```
520​
521### Example: Imagen
522​
523```typescript
524import { generateImage } from "@tanstack/ai";
525import { geminiImage } from "@tanstack/ai-gemini";
526​
527const result = await generateImage({
528 adapter: geminiImage("imagen-4.0-generate-001"),
529 prompt: "A futuristic cityscape at sunset",
530 numberOfImages: 1,
531});
532​
533console.log(result.images);
534```
535​
536### Image Size Options
537​
538#### Gemini Native Models (NanoBanana)
539​
540Gemini native image models use a template literal size format combining aspect ratio and resolution tier:
541​
542```typescript ignore
543// Format: "aspectRatio_resolution"
544size: "16:9_4K"
545size: "1:1_2K"
546size: "9:16_1K"
547```
548​
549The accepted set differs per model, and each model's `size` is narrowed to its own set at compile time:
550​
551| Model | Aspect ratios | Resolutions |
552|-------|---------------|-------------|
553| `gemini-3.1-flash-image` | `1:1`, `2:3`, `3:2`, `3:4`, `4:3`, `4:5`, `5:4`, `9:16`, `16:9`, `21:9`, `1:4`, `4:1`, `1:8`, `8:1` | `512`, `1K`, `2K`, `4K` |
554| `gemini-3.1-flash-lite-image` | same 14 as above (see note) | `1K` only |
555| `gemini-3-pro-image` | `1:1`, `2:3`, `3:2`, `3:4`, `4:3`, `4:5`, `5:4`, `9:16`, `16:9`, `21:9` | `1K`, `2K`, `4K` |
556| `gemini-2.5-flash-image` | same 10 as above | none — pass the bare ratio, e.g. `size: "16:9"` |
557​
558The `K` is case-sensitive (`1k` is rejected by the API), the smallest tier's token is `512` (not `512px` or `0.5K`), and `9:21` is Vertex/Cloud-only so it is not accepted here. Google documents no `image_size` for `gemini-2.5-flash-image`, so that model takes a bare aspect ratio and the adapter sends no `imageSize`.
559​
560> **Note on `gemini-3.1-flash-lite-image`.** The four extreme banner ratios (`1:4`, `4:1`, `1:8`, `8:1`) are partially inferred for this model. Unlike the other three, Flash Lite has no per-model ratio table in Google's Gemini API guide; the 14-value set comes from the Cloud model page's explicit enumeration plus the guide's bare "a discrete set of 14 aspect ratios" assertion. The only Gemini-API enumeration for it is a 10-item bullet headed "New aspect ratios", which we read as a what's-new list rather than an exhaustive one. If the API rejects those four in practice, prefer the 10 standard ratios on this model.
561​
562#### Imagen Models
563​
564Imagen models use WIDTHxHEIGHT format, which maps to aspect ratios internally:
565​
566| Size | Aspect Ratio |
567|------|-------------|
568| `1024x1024` | 1:1 |
569| `1920x1080` | 16:9 |
570| `1080x1920` | 9:16 |
571​
572Alternatively, you can specify the aspect ratio directly in Model Options:
573​
574```typescript
575import { generateImage } from "@tanstack/ai";
576import { geminiImage } from "@tanstack/ai-gemini";
577​
578const result = await generateImage({
579 adapter: geminiImage("imagen-4.0-generate-001"),
580 prompt: "A landscape photo",
581 modelOptions: {
582 aspectRatio: "16:9",
583 },
584});
585```
586​
587### Image Model Options
588​
589`modelOptions` is typed per model family, because the two families hit different APIs.
590​
591Imagen models (`generateImages`) take `GenerateImagesConfig` fields:
592​
593```typescript ignore
594import { generateImage } from "@tanstack/ai";
595import { geminiImage } from "@tanstack/ai-gemini";
596​
597const result = await generateImage({
598 adapter: geminiImage("imagen-4.0-generate-001"),
599 prompt: "...",
600 modelOptions: {
601 aspectRatio: "16:9", // "1:1" | "3:4" | "4:3" | "9:16" | "16:9"
602 personGeneration: "DONT_ALLOW", // Control person generation
603 safetyFilterLevel: "BLOCK_SOME", // Safety filtering
604 },
605});
606```
607​
608Gemini native models (`generateContent`) take `seed`, `safetySettings`,
609`thinkingConfig`, `imageConfig`, and `systemInstruction`.
610`imageConfig` accepts only `aspectRatio` and `imageSize` on the Gemini
611Developer API.
612​
613```typescript
614import { generateImage } from "@tanstack/ai";
615import { geminiImage } from "@tanstack/ai-gemini";
616​
617const result = await generateImage({
618 adapter: geminiImage("gemini-3.1-flash-image"),
619 prompt: "...",
620 size: "16:9_4K",
621 modelOptions: {
622 thinkingConfig: { thinkingBudget: 512 },
623 // Merged over the imageConfig derived from `size`, per field.
624 imageConfig: { imageSize: "2K" },
625 },
626});
627```
628​
629See [Image Generation](../media/image-generation) for the full native option list.
630​
631## Text-to-Speech (Experimental)
632​
633> **Note:** Gemini TTS is experimental and may require the Live API for full functionality.
634​
635Generate speech from text:
636​
637```typescript
638import { generateSpeech } from "@tanstack/ai";
639import { geminiSpeech } from "@tanstack/ai-gemini";
640​
641const result = await generateSpeech({
642 adapter: geminiSpeech("gemini-3.1-flash-tts-preview"),
643 text: "Hello from Gemini TTS!",
644});
645​
646console.log(result.audio); // Base64 encoded audio
647```
648​
649Gemini names speakers in the prompt and maps each name to a voice. Pass `turns`
650and the adapter does both for you, using the voice name as the speaker label:
651​
652```typescript
653import { generateSpeech } from "@tanstack/ai";
654import { geminiSpeech } from "@tanstack/ai-gemini";
655​
656const result = await generateSpeech({
657 adapter: geminiSpeech("gemini-3.1-flash-tts-preview"),
658 turns: [
659 { text: "Hey, how is it going?", voice: "Puck" },
660 { text: "Not bad, you?", voice: "Kore" },
661 ],
662});
663```
664​
665Gemini accepts **two distinct voices** per request, and a third is rejected
666before the call is made. Each voice must be one of the prebuilt Gemini voices.
667Gemini reports no timings, so `timestamps: true` is rejected on this adapter.
668​
669## Environment Variables
670​
671Set your API key in environment variables:
672​
673```bash
674GEMINI_API_KEY=your-api-key-here
675# or
676GOOGLE_API_KEY=your-api-key-here
677```
678​
679## Getting an API Key
680​
6811. Go to [Google AI Studio](https://aistudio.google.com/apikey)
6822. Create a new API key
6833. Add it to your environment variables
684​
685## Popular Image Models
686​
687### Gemini Native Image Models (NanoBanana)
688​
689These models use the `generateContent` API and support per-model resolution tiers.
690​
691| Model | Description |
692|-------|-------------|
693| `gemini-3.1-flash-image` | Nano Banana 2 — latest and fastest Gemini native image generation (512/1K/2K/4K) |
694| `gemini-3.1-flash-lite-image` | Nano Banana 2 Lite — ultra-low-latency, low-cost image generation (1K only) |
695| `gemini-3-pro-image` | Nano Banana Pro — higher quality Gemini native image generation (1K/2K/4K) |
696| `gemini-2.5-flash-image` | Nano Banana — legacy; shuts down 2026-10-02. Takes a bare aspect ratio |
697​
698The `gemini-3.1-flash-image-preview` and `gemini-3-pro-image-preview` ids were shut down on 2026-06-25. They remain in the type union as deprecated aliases so existing code compiles, but calls to them fail — use the GA ids above.
699​
700### Imagen Models
701​
702These models use the dedicated `generateImages` API.
703​
704| Model | Description |
705|-------|-------------|
706| `imagen-4.0-ultra-generate-001` | Best quality Imagen image generation |
707| `imagen-4.0-generate-001` | High quality Imagen image generation |
708| `imagen-4.0-fast-generate-001` | Fast Imagen image generation |
709​
710## API Reference
711​
712Every factory pair follows the same shape: the short factory (`geminiText`, `geminiImage`, …) reads `GEMINI_API_KEY` (or `GOOGLE_API_KEY`) from the environment, while the `create*` variant takes an explicit API key. Both take `model` as the first argument.
713​
714### `geminiText(model, config?)` / `createGeminiChat(model, apiKey, config?)`
715​
716Creates a Gemini text/chat adapter.
717​
718**Parameters:**
719​
720- `model` - Gemini chat model id (e.g. `"gemini-3.1-pro-preview"`)
721- `config?.baseURL` - Custom base URL (optional)
722​
723### `geminiTextInteractions(model, config?)` / `createGeminiTextInteractions(model, apiKey, config?)` (experimental)
724​
725Creates a Gemini Interactions API text adapter. Backs the stateful conversation pattern via `previous_interaction_id`. Exported from `@tanstack/ai-gemini/experimental`.
726​
727**Parameters:**
728​
729- `model` - Gemini chat model id (e.g. `"gemini-3.5-flash"`)
730- `config?.baseURL` - Custom base URL (optional)
731​
732### `geminiSummarize(model, config?)` / `createGeminiSummarize(model, apiKey, config?)`
733​
734Creates a Gemini summarization adapter.
735​
736### `geminiImage(model, config?)` / `createGeminiImage(model, apiKey, config?)`
737​
738Creates a Gemini image adapter. Models in `GEMINI_NATIVE_IMAGE_MODELS` use `generateContent`. Imagen models, and any unknown id, use `generateImages`.
739​
740### `geminiSpeech(model, config?)` / `createGeminiSpeech(model, apiKey, config?)`
741​
742Creates a Gemini text-to-speech adapter. _Experimental._
743​
744### `geminiAudio(model, config?)` / `createGeminiAudio(model, apiKey, config?)`
745​
746Creates a Gemini Lyria music generation adapter. _Experimental._
747​
748## Next Steps
749​
750- [Image Generation Guide](../media/image-generation) - Learn more about image generation
751- [Media Generation Example](https://github.com/TanStack/ai/tree/main/examples/ts-react-media) - Full working example with Gemini and fal.ai
752- [Getting Started](../getting-started/quick-start) - Learn the basics
753- [Tools Guide](../tools/tools) - Learn about tools
754- [Other Adapters](./openai) - Explore other providers
755​
756## Provider Tools
757​
758Google Gemini exposes several native tools beyond user-defined function calls.
759Import them from `@tanstack/ai-gemini/tools` and pass them into
760`chat({ tools: [...] })`.
761​
762> For the full concept, a comparison matrix, and type-gating details, see
763> [Provider Tools](../tools/provider-tools.md).
764​
765### `codeExecutionTool`
766​
767Enables Gemini to execute Python code in a sandboxed environment and return
768results inline. Takes no arguments — include it in the `tools` array to
769activate code execution.
770​
771```typescript
772import { chat } from "@tanstack/ai";
773import { geminiText } from "@tanstack/ai-gemini";
774import { codeExecutionTool } from "@tanstack/ai-gemini/tools";
775​
776const stream = chat({
777 adapter: geminiText("gemini-3.1-pro-preview"),
778 messages: [{ role: "user", content: "Calculate the first 10 Fibonacci numbers" }],
779 tools: [codeExecutionTool()],
780});
781```
782​
783**Supported models:** Gemini 1.5 Pro, Gemini 2.x, Gemini 2.5 and above. See [Provider Tools](../tools/provider-tools.md#which-models-support-which-tools).
784​
785### `fileSearchTool`
786​
787Searches files that have been uploaded to the Gemini File API. Pass a
788`FileSearch` config object with the corpus and file IDs to scope the search.
789​
790```typescript
791import { chat } from "@tanstack/ai";
792import { geminiText } from "@tanstack/ai-gemini";
793import { fileSearchTool } from "@tanstack/ai-gemini/tools";
794​
795const stream = chat({
796 adapter: geminiText("gemini-3.1-pro-preview"),
797 messages: [{ role: "user", content: "Find the quarterly revenue figures" }],
798 tools: [
799 fileSearchTool({
800 fileSearchStoreNames: ["fileSearchStores/my-file-search-store-123"],
801 }),
802 ],
803});
804```
805​
806**Supported models:** Gemini 2.x and above. See [Provider Tools](../tools/provider-tools.md#which-models-support-which-tools).
807​
808### `googleSearchTool`
809​
810Enables Gemini to query Google Search and incorporate grounded search results
811into its response. Pass an optional `GoogleSearch` config or call with no
812arguments to use defaults.
813​
814```typescript
815import { chat } from "@tanstack/ai";
816import { geminiText } from "@tanstack/ai-gemini";
817import { googleSearchTool } from "@tanstack/ai-gemini/tools";
818​
819const stream = chat({
820 adapter: geminiText("gemini-3.1-pro-preview"),
821 messages: [{ role: "user", content: "What's the weather in Tokyo right now?" }],
822 tools: [googleSearchTool()],
823});
824```
825​
826**Supported models:** Gemini 1.5 Pro, Gemini 2.x, Gemini 2.5. See [Provider Tools](../tools/provider-tools.md#which-models-support-which-tools).
827​
828When Google Search returns grounding data, the assistant tool-call part
829includes `metadata.providerExecuted: true` and the normalized
830`metadata.sources` array. Gemini's raw `groundingMetadata` stays under
831`metadata.gemini`. The agent loop does not execute this call in your
832application.
833​
834### `googleSearchRetrievalTool`
835​
836A retrieval-augmented variant of Google Search that returns ranked passages
837from the web with configurable dynamic retrieval mode. Pass an optional
838`GoogleSearchRetrieval` config.
839​
840```typescript ignore
841import { chat } from "@tanstack/ai";
842import { geminiText } from "@tanstack/ai-gemini";
843import { googleSearchRetrievalTool } from "@tanstack/ai-gemini/tools";
844​
845const stream = chat({
846 adapter: geminiText("gemini-3.1-pro-preview"),
847 messages: [{ role: "user", content: "Explain the latest JavaScript proposals" }],
848 tools: [
849 googleSearchRetrievalTool({
850 dynamicRetrievalConfig: { mode: "MODE_DYNAMIC", dynamicThreshold: 0.7 },
851 }),
852 ],
853});
854```
855​
856**Supported models:** Gemini 1.5 Pro and above. See [Provider Tools](../tools/provider-tools.md#which-models-support-which-tools).
857​
858### `googleMapsTool`
859​
860Connects Gemini to the Google Maps API for location-aware queries such as
861directions, place search, and geocoding. Pass an optional `GoogleMaps` config
862or call with no arguments.
863​
864```typescript
865import { chat } from "@tanstack/ai";
866import { geminiText } from "@tanstack/ai-gemini";
867import { googleMapsTool } from "@tanstack/ai-gemini/tools";
868​
869const stream = chat({
870 adapter: geminiText("gemini-2.5-pro"),
871 messages: [{ role: "user", content: "Find coffee shops near Union Square, SF" }],
872 tools: [googleMapsTool()],
873});
874```
875​
876**Supported models:** Gemini 2.5 and above. See [Provider Tools](../tools/provider-tools.md#which-models-support-which-tools).
877​
878### `urlContextTool`
879​
880Fetches and includes the content of URLs mentioned in the conversation so
881Gemini can reason over live web pages. Takes no arguments.
882​
883```typescript
884import { chat } from "@tanstack/ai";
885import { geminiText } from "@tanstack/ai-gemini";
886import { urlContextTool } from "@tanstack/ai-gemini/tools";
887​
888const stream = chat({
889 adapter: geminiText("gemini-3.1-pro-preview"),
890 messages: [{ role: "user", content: "Summarise https://example.com/article" }],
891 tools: [urlContextTool()],
892});
893```
894​
895**Supported models:** Gemini 2.x and above. See [Provider Tools](../tools/provider-tools.md#which-models-support-which-tools).
896​
897### `computerUseTool`
898​
899Allows Gemini to observe a virtual desktop via screenshots and interact with
900it using predefined computer-use functions. Provide the `environment` and
901optionally restrict callable functions via `excludedPredefinedFunctions`.
902​
903```typescript ignore
904import { chat } from "@tanstack/ai";
905import { geminiText } from "@tanstack/ai-gemini";
906import { computerUseTool } from "@tanstack/ai-gemini/tools";
907​
908const stream = chat({
909 adapter: geminiText("gemini-3.1-pro-preview"),
910 messages: [{ role: "user", content: "Navigate to example.com in the browser" }],
911 tools: [
912 computerUseTool({
913 environment: "browser",
914 }),
915 ],
916});
917```
918​
919**Supported models:** Gemini 2.5 and above. See [Provider Tools](../tools/provider-tools.md#which-models-support-which-tools).