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

gemini.md

1,016 lines36.8 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​
42To set how hard Gemini 3.8 Flash thinks, pass `reasoning: "low"`, `"medium"`, or `"high"` to `chat()`. It has no `minimal` level. See [Reasoning](#reasoning).
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​
99This adapter ignores [`wrapFetch`](../advanced/middleware#change-the-http-requests-of-a-call), because the `@google/genai` SDK does not take a custom fetch.
100​
101## Example: Chat Completion
102​
103```typescript
104import { chat, toServerSentEventsResponse } from "@tanstack/ai";
105import { geminiText } from "@tanstack/ai-gemini";
106​
107export async function POST(request: Request) {
108 const { messages } = await request.json();
109​
110 const stream = chat({
111 adapter: geminiText("gemini-3.1-pro-preview"),
112 messages,
113 });
114​
115 return toServerSentEventsResponse(stream);
117```
118​
119## Example: With Tools
120​
121```typescript
122import { chat, toServerSentEventsResponse, toolDefinition } from "@tanstack/ai";
123import { geminiText } from "@tanstack/ai-gemini";
124import { z } from "zod";
125​
126const getCalendarEventsDef = toolDefinition({
127 name: "get_calendar_events",
128 description: "Get calendar events for a date",
129 inputSchema: z.object({
130 date: z.string(),
131 }),
132});
133​
134const getCalendarEvents = getCalendarEventsDef.server(async ({ date }) => {
135 // Fetch calendar events
136 return { events: [] };
137});
138​
139export async function POST(request: Request) {
140 const { messages } = await request.json();
141​
142 const stream = chat({
143 adapter: geminiText("gemini-3.1-pro-preview"),
144 messages,
145 tools: [getCalendarEvents],
146 });
147​
148 return toServerSentEventsResponse(stream);
150```
151​
152## Video Understanding
153​
154Ask questions about a video: "what happens at 0:30?", "summarize the demo", "list every product shown". Upload the file once, then chat about it.
155​
156Video 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.
157​
158```typescript
159import { chat, toServerSentEventsResponse } from "@tanstack/ai";
160import { geminiText, uploadGeminiFile, geminiVideoPart } from "@tanstack/ai-gemini";
161​
162export async function POST(request: Request) {
163 const file = await uploadGeminiFile("./demo.mp4", { mimeType: "video/mp4" });
164​
165 const stream = chat({
166 adapter: geminiText("gemini-3.8-flash"),
167 messages: [
168 {
169 role: "user",
170 content: [
171 { type: "text", content: "Summarize this video and cite timestamps." },
172 geminiVideoPart(file),
173 ],
174 },
175 ],
176 });
177​
178 return toServerSentEventsResponse(stream);
180```
181​
182By default Gemini samples the video at 1 frame per second. Tune that single-pass sampling through the part metadata:
183​
184```typescript ignore
185// Watch a 30s-90s clip at half a frame per second.
186geminiVideoPart(file, { fps: 0.5, startOffset: "30s", endOffset: "90s" });
187```
188​
189### Agentic understanding
190​
191Single-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:
192​
193- `gemini-3.8-flash`
194- `gemini-3.7-flash`
195- `gemini-3.6-flash`
196- `gemini-3.5-flash-lite`
197​
198```typescript ignore
199geminiVideoPart(file, { processing: "agentic" });
200```
201​
202With `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.
203​
204## Stateful Conversations — Interactions API (Experimental)
205​
206Gemini'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.
207​
208The `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.
209​
210> **⚠️ 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.
211​
212### Basic Usage
213​
214```typescript ignore
215import { chat } from "@tanstack/ai";
216import { geminiTextInteractions } from "@tanstack/ai-gemini/experimental";
217​
218// Turn 1: introduce yourself, capture the interaction id.
219let interactionId: string | undefined;
220​
221for await (const chunk of chat({
222 adapter: geminiTextInteractions("gemini-3.5-flash"),
223 messages: [{ role: "user", content: "Hi, my name is Amir." }],
224})) {
225 if (
226 chunk.type === "CUSTOM" &&
227 chunk.name === "gemini.interactionId" &&
228 chunk.value &&
229 typeof chunk.value === "object" &&
230 "interactionId" in chunk.value
231 ) {
232 interactionId = String(chunk.value.interactionId);
233 }
235​
236// Turn 2: only send the new turn's content — the server has the history.
237for await (const chunk of chat({
238 adapter: geminiTextInteractions("gemini-3.5-flash"),
239 messages: [{ role: "user", content: "What is my name?" }],
240 modelOptions: {
241 previous_interaction_id: interactionId,
242 },
243})) {
244 // ...stream "Your name is Amir." back to the client.
246```
247​
248### Wiring with `useChat` (React)
249​
250The 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:
251​
252**Server route** (e.g. TanStack Start handler):
253​
254```typescript
255import {
256 chat,
257 chatParamsFromRequestBody,
258 toServerSentEventsResponse,
259} from "@tanstack/ai";
260import { geminiTextInteractions } from "@tanstack/ai-gemini/experimental";
261​
262export async function POST({ request }: { request: Request }) {
263 const params = await chatParamsFromRequestBody(await request.json());
264​
265 // The client sends body.previousInteractionId; AG-UI maps `body` into
266 // `forwardedProps` on the wire.
267 const previousInteractionId =
268 typeof params.forwardedProps.previousInteractionId === "string"
269 ? params.forwardedProps.previousInteractionId
270 : undefined;
271​
272 const stream = chat({
273 adapter: geminiTextInteractions("gemini-3.5-flash"),
274 messages: params.messages,
275 modelOptions: {
276 previous_interaction_id: previousInteractionId,
277 store: true, // required for chaining on the next turn
278 },
279 });
280​
281 return toServerSentEventsResponse(stream);
283```
284​
285**React client**:
286​
287```tsx
288import { useEffect, useMemo, useState } from "react";
289import { fetchServerSentEvents, useChat } from "@tanstack/ai-react";
290​
291function GeminiChat() {
292 const [interactionId, setInteractionId] = useState<string | undefined>();
293​
294 const body = useMemo(
295 () => (interactionId ? { previousInteractionId: interactionId } : {}),
296 [interactionId],
297 );
298​
299 const { messages, setMessages, sendMessage } = useChat({
300 connection: fetchServerSentEvents("/api/chat"),
301 body,
302 onCustomEvent: (eventType, data) => {
303 if (
304 eventType === "gemini.interactionId" &&
305 typeof data === "object" &&
306 data !== null &&
307 "interactionId" in data
308 ) {
309 setInteractionId(String(data.interactionId));
310 }
311 },
312 });
313​
314 // Switching provider/model resets the server-side chain — drop the id
315 // AND the local message history together, otherwise the next turn
316 // ships multi-turn messages with no previous_interaction_id and the
317 // adapter errors out.
318 const [provider, setProvider] = useState("gemini-interactions");
319 useEffect(() => {
320 setInteractionId(undefined);
321 setMessages([]);
322 }, [provider]);
323​
324 // ...render messages, call sendMessage(input)
326```
327​
328The 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.
329​
330### How it differs from `geminiText`
331​
332| Concern | `geminiText` | `geminiTextInteractions` |
333| --- | --- | --- |
334| Underlying endpoint | `models:generateContent` | `interactions:create` |
335| Conversation state | Stateless — send full history each turn | Stateful — server retains transcript via `previous_interaction_id` |
336| Provider options shape | camelCase (`stopSequences`, `responseModalities`, `safetySettings`) | snake_case (`generation_config`, `response_modalities`, `previous_interaction_id`) |
337| 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) |
338| Stability | GA | Experimental (Google Beta) |
339​
340### Provider Options
341​
342The adapter exposes Interactions-specific options on `modelOptions`:
343​
344```typescript
345import { chat } from "@tanstack/ai";
346import { geminiTextInteractions } from "@tanstack/ai-gemini/experimental";
347​
348const stream = chat({
349 adapter: geminiTextInteractions("gemini-3.5-flash"),
350 messages: [{ role: "user", content: "Hello!" }],
351 // Goes out as generation_config.thinking_level and thinking_summaries.
352 reasoning: "low",
353 modelOptions: {
354 // Stateful chaining — passed only on turn 2+.
355 previous_interaction_id: "int_abc123",
356​
357 // Persist the interaction server-side (default true). Must be true for
358 // previous_interaction_id to work on the *next* turn.
359 store: true,
360​
361 // Per-request system instruction (interaction-scoped — re-specify each turn).
362 system_instruction: "You are a helpful assistant.",
363​
364 // snake_case generation config distinct from geminiText's camelCase one.
365 generation_config: {
366 stop_sequences: ["<done>"],
367 },
368​
369 response_modalities: ["text"],
370 },
371});
372```
373​
374### Reading the interaction id
375​
376The server's interaction id arrives as an AG-UI `CUSTOM` event emitted just before `RUN_FINISHED`:
377​
378```typescript ignore
379for await (const chunk of stream) {
380 if (
381 chunk.type === "CUSTOM" &&
382 chunk.name === "gemini.interactionId" &&
383 typeof chunk.value === "object" &&
384 chunk.value !== null &&
385 "interactionId" in chunk.value
386 ) {
387 const id = String(chunk.value.interactionId);
388 // Persist `id` wherever you store per-user conversation pointers —
389 // pass it back on the next turn as `previous_interaction_id`.
390 }
392```
393​
394### Caveats
395​
396- **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.
397- **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.
398- `store: false` is incompatible with `previous_interaction_id` (no state to recall) and with `background: true`.
399- 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.
400- 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.
401- `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`.
402- 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.
403​
404## Model Options
405​
406Gemini supports various model-specific options. Sampling parameters live here too — `temperature`, `topP`, and `maxOutputTokens` — rather than as root-level props on `chat()`:
407​
408```typescript
409import { chat } from "@tanstack/ai";
410import { geminiText } from "@tanstack/ai-gemini";
411​
412const stream = chat({
413 adapter: geminiText("gemini-3.1-pro-preview"),
414 messages: [{ role: "user", content: "Hello!" }],
415 modelOptions: {
416 maxOutputTokens: 2048,
417 temperature: 0.7,
418 topP: 0.9,
419 topK: 40,
420 stopSequences: ["END"],
421 },
422});
423```
424​
425> If you previously passed `temperature` / `topP` / `maxTokens` at the root of `chat()`, see [Moving Sampling Options into modelOptions](../migration/sampling-options-to-model-options).
426​
427### Reasoning
428​
429Want Gemini to think harder? Set `reasoning` on `chat()`:
430​
431```typescript
432import { chat } from "@tanstack/ai";
433import { geminiText } from "@tanstack/ai-gemini";
434​
435const stream = chat({
436 adapter: geminiText("gemini-3.8-flash"),
437 messages: [{ role: "user", content: "Plan a database migration." }],
438 reasoning: "high",
439});
440```
441​
442What goes on the wire:
443​
444- Gemini 3 models: `thinkingConfig.thinkingLevel`.
445- Gemini 2.5 models: `thinkingConfig.thinkingBudget`. Set it with `budgetTokens`, or the level picks it. `off` sends a budget of `0`.
446- `summary` sets `thinkingConfig.includeThoughts`, so the thinking text streams.
447- `geminiTextInteractions`: `generation_config.thinking_level` and `thinking_summaries`.
448​
449The levels of each model:
450​
451| Model | Levels | `budgetTokens` |
452| --- | --- | --- |
453| `gemini-3.8-flash`, `gemini-3.7-flash`, `gemini-3.1-pro-preview` | `low`, `medium`, `high` | no |
454| `gemini-3.6-flash`, `gemini-3.5-flash`, `gemini-3.5-flash-lite`, `gemini-3.1-flash-lite`, `gemini-3.1-flash-lite-preview`, `gemini-3-flash-preview` | `minimal` to `high` | no |
455| `gemini-2.5-pro` | `minimal` to `high` | yes |
456| `gemini-2.5-flash`, `gemini-2.5-flash-lite` | `off`, `high` | yes |
457​
458A Gemini 2.5 budget:
459​
460```typescript
461import { chat } from "@tanstack/ai";
462import { geminiText } from "@tanstack/ai-gemini";
463​
464const stream = chat({
465 adapter: geminiText("gemini-2.5-pro"),
466 messages: [{ role: "user", content: "Check this proof." }],
467 reasoning: { level: "high", budgetTokens: 8000 },
468});
469```
470​
471Image models keep their own `thinkingConfig` in `modelOptions`. See [Image Model Options](#image-model-options).
472​
473### Structured Output
474​
475Configure structured output format:
476​
477```typescript ignore
478modelOptions: {
479 responseMimeType: "application/json",
481```
482​
483## Summarization
484​
485Summarize long text content:
486​
487```typescript
488import { summarize } from "@tanstack/ai";
489import { geminiSummarize } from "@tanstack/ai-gemini";
490​
491const result = await summarize({
492 adapter: geminiSummarize("gemini-3.1-pro-preview"),
493 text: "Your long text to summarize...",
494 maxLength: 100,
495 style: "concise", // "concise" | "bullet-points" | "paragraph"
496});
497​
498console.log(result.summary);
499```
500​
501## Embeddings
502​
503Generate embedding vectors with gemini-embedding-001:
504​
505```typescript
506import { embed } from "@tanstack/ai";
507import { geminiEmbedding } from "@tanstack/ai-gemini";
508​
509const result = await embed({
510 adapter: geminiEmbedding("gemini-embedding-001"),
511 input: "a red guitar",
512 dimensions: 1536,
513 modelOptions: {
514 taskType: "RETRIEVAL_DOCUMENT",
515 },
516});
517​
518console.log(result.embeddings[0]?.vector);
519```
520​
521> The Gemini API's embedding endpoint does not report token usage, so
522> `result.usage` is absent. The Vertex-only multimodal embedding model
523> (`multimodalembedding@001`) is not supported by this adapter.
524​
525See the [Embeddings guide](../embeddings.md) for the full API.
526​
527## Image Generation
528​
529The Gemini adapter has two image model groups:
530​
531- **Gemini native image models** (NanoBanana). A model such as `gemini-3.1-flash-image` uses the Interactions API. You set an aspect ratio. Some models also take a resolution tier (`512`, `1K`, `2K`, or `4K`). TypeScript checks the set for the model.
532- **Imagen models**. A model such as `imagen-4.0-generate-001` uses `generateImages`. You set the size as WIDTHxHEIGHT.
533​
534When the model is in `GEMINI_NATIVE_IMAGE_MODELS`, the adapter uses the Interactions API. An Imagen model uses `generateImages`. An unknown id uses `generateImages`. Import the list or `isGeminiNativeImageModel` from `@tanstack/ai-gemini`.
535​
536### Example: Gemini Native Image Generation (NanoBanana)
537​
538From the [media generation example app](https://github.com/TanStack/ai/tree/main/examples/ts-react-media):
539​
540```typescript
541import { generateImage } from "@tanstack/ai";
542import { geminiImage } from "@tanstack/ai-gemini";
543​
544const result = await generateImage({
545 adapter: geminiImage("gemini-3.1-flash-image"),
546 prompt: "A futuristic cityscape at sunset",
547 numberOfImages: 1,
548 size: "16:9_4K",
549});
550​
551console.log(result.images);
552```
553​
554### Edit a Gemini native image
555​
556You have an image from a Gemini native model. You want to change that image without a second upload of that image.
557​
558Pass the last `id` back. Write only the change in `prompt`:
559​
560```typescript
561import { generateImage } from "@tanstack/ai";
562import { geminiImage } from "@tanstack/ai-gemini";
563​
564const adapter = geminiImage("gemini-3.1-flash-image");
565​
566const first = await generateImage({
567 adapter,
568 prompt: "A red bicycle on a quiet street",
569});
570​
571const edited = await generateImage({
572 adapter,
573 prompt: "Make the bicycle blue",
574 modelOptions: { previous_interaction_id: first.id },
575});
576```
577​
5781. Generate the first image.
5792. Call `generateImage` again with `previous_interaction_id` set to `first.id`.
5803. Read `edited.images` for the new picture.
581​
582`edited.id` is the id for the next edit.
583​
584Keep the interaction so the next edit can run:
585​
5861. Leave `store` unset.
5872. If you set `store` to `false`, a later call cannot use that id.
588​
589The API default for `store` is `true`.
590​
591A free tier keeps a stored interaction for 1 day. A paid tier keeps it for 55 days.
592​
593If the model is Imagen, do not pass `previous_interaction_id`. The call throws.
594​
595If this edit needs a new reference image, add that image part on this call. Do not send the image from `first`.
596​
597The Interactions API is in Beta.
598​
599The same steps are in [Image Generation](../media/image-generation#edit-a-gemini-native-image).
600​
601### Example: Imagen
602​
603```typescript
604import { generateImage } from "@tanstack/ai";
605import { geminiImage } from "@tanstack/ai-gemini";
606​
607const result = await generateImage({
608 adapter: geminiImage("imagen-4.0-generate-001"),
609 prompt: "A futuristic cityscape at sunset",
610 numberOfImages: 1,
611});
612​
613console.log(result.images);
614```
615​
616### Image Size Options
617​
618#### Gemini Native Models (NanoBanana)
619​
620Gemini native image models use a template literal size format combining aspect ratio and resolution tier:
621​
622```typescript ignore
623// Format: "aspectRatio_resolution"
624size: "16:9_4K"
625size: "1:1_2K"
626size: "9:16_1K"
627```
628​
629The accepted set differs per model, and each model's `size` is narrowed to its own set at compile time:
630​
631| Model | Aspect ratios | Resolutions |
632|-------|---------------|-------------|
633| `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` |
634| `gemini-3.1-flash-lite-image` | same 14 as above (see note) | `1K` only |
635| `gemini-nano-banana-2.1` | same 14 as above | `1K`, `2K`, `4K` |
636| `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` |
637| `gemini-2.5-flash-image` | same 10 as above | none — pass the bare ratio, e.g. `size: "16:9"` |
638​
639The `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`.
640​
641> **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.
642​
643#### Imagen Models
644​
645Imagen models use WIDTHxHEIGHT format, which maps to aspect ratios internally:
646​
647| Size | Aspect Ratio |
648|------|-------------|
649| `1024x1024` | 1:1 |
650| `1920x1080` | 16:9 |
651| `1080x1920` | 9:16 |
652​
653Alternatively, you can specify the aspect ratio directly in Model Options:
654​
655```typescript
656import { generateImage } from "@tanstack/ai";
657import { geminiImage } from "@tanstack/ai-gemini";
658​
659const result = await generateImage({
660 adapter: geminiImage("imagen-4.0-generate-001"),
661 prompt: "A landscape photo",
662 modelOptions: {
663 aspectRatio: "16:9",
664 },
665});
666```
667​
668### Image Model Options
669​
670`modelOptions` is typed per model family, because the two families hit different APIs.
671​
672Imagen models (`generateImages`) take `GenerateImagesConfig` fields:
673​
674```typescript ignore
675import { generateImage } from "@tanstack/ai";
676import { geminiImage } from "@tanstack/ai-gemini";
677​
678const result = await generateImage({
679 adapter: geminiImage("imagen-4.0-generate-001"),
680 prompt: "...",
681 modelOptions: {
682 aspectRatio: "16:9", // "1:1" | "3:4" | "4:3" | "9:16" | "16:9"
683 personGeneration: "DONT_ALLOW", // Control person generation
684 safetyFilterLevel: "BLOCK_SOME", // Safety filtering
685 },
686});
687```
688​
689#### Gemini native models
690​
691Set native image options on `modelOptions`:
692​
693```typescript
694import { generateImage } from "@tanstack/ai";
695import { geminiImage, ThinkingLevel } from "@tanstack/ai-gemini";
696​
697const result = await generateImage({
698 adapter: geminiImage("gemini-3.1-flash-image"),
699 prompt: "A beautiful garden",
700 size: "16:9_4K",
701 modelOptions: {
702 thinkingConfig: { thinkingLevel: ThinkingLevel.LOW },
703 // imageConfig replaces one field from size. The 16:9 ratio from size stays.
704 // imageConfig accepts only aspectRatio and imageSize.
705 imageConfig: { imageSize: "2K" },
706 },
707});
708```
709​
710Set `thinkingConfig.thinkingLevel` to one of these values:
711​
712- `ThinkingLevel.MINIMAL`
713- `ThinkingLevel.LOW`
714- `ThinkingLevel.MEDIUM`
715- `ThinkingLevel.HIGH`
716​
717`thinkingConfig.thinkingBudget` throws.
718​
719If `systemInstruction` contains an image, a file, or a tool call, the call throws.
720​
721Pass the last result `id` as `previous_interaction_id`. Read [Edit a Gemini native image](#edit-a-gemini-native-image) for the edit steps.
722​
723See [Image Generation](../media/image-generation) for the full native option list.
724​
725## Text-to-Speech (Experimental)
726​
727> **Note:** Gemini TTS is experimental and may require the Live API for full functionality.
728​
729Generate speech from text:
730​
731```typescript
732import { generateSpeech } from "@tanstack/ai";
733import { geminiSpeech } from "@tanstack/ai-gemini";
734​
735const result = await generateSpeech({
736 adapter: geminiSpeech("gemini-3.1-flash-tts-preview"),
737 text: "Hello from Gemini TTS!",
738});
739​
740console.log(result.audio); // Base64 encoded audio
741```
742​
743Gemini names speakers in the prompt and maps each name to a voice. Pass `turns`
744and the adapter does both for you, using the voice name as the speaker label:
745​
746```typescript
747import { generateSpeech } from "@tanstack/ai";
748import { geminiSpeech } from "@tanstack/ai-gemini";
749​
750const result = await generateSpeech({
751 adapter: geminiSpeech("gemini-3.1-flash-tts-preview"),
752 turns: [
753 { text: "Hey, how is it going?", voice: "Puck" },
754 { text: "Not bad, you?", voice: "Kore" },
755 ],
756});
757```
758​
759Gemini accepts **two distinct voices** per request, and a third is rejected
760before the call is made. Each voice must be one of the prebuilt Gemini voices.
761Gemini reports no timings, so `timestamps: true` is rejected on this adapter.
762​
763## Environment Variables
764​
765Set your API key in environment variables:
766​
767```bash
768GEMINI_API_KEY=your-api-key-here
769# or
770GOOGLE_API_KEY=your-api-key-here
771```
772​
773## Getting an API Key
774​
7751. Go to [Google AI Studio](https://aistudio.google.com/apikey)
7762. Create a new API key
7773. Add it to your environment variables
778​
779## Popular Image Models
780​
781### Gemini Native Image Models (NanoBanana)
782​
783These models use the Interactions API. Each model has its own resolution tiers.
784​
785| Model | Description |
786|-------|-------------|
787| `gemini-3.1-flash-image` | Nano Banana 2 — latest and fastest Gemini native image generation (512/1K/2K/4K) |
788| `gemini-3.1-flash-lite-image` | Nano Banana 2 Lite — ultra-low-latency, low-cost image generation (1K only) |
789| `gemini-nano-banana-2.1` | Nano Banana 2.1 (1K/2K/4K, no 512 tier) |
790| `gemini-3-pro-image` | Nano Banana Pro — higher quality Gemini native image generation (1K/2K/4K) |
791| `gemini-2.5-flash-image` | Nano Banana — legacy; shuts down 2026-10-02. Takes a bare aspect ratio |
792​
793The `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.
794​
795### Imagen Models
796​
797These models use the dedicated `generateImages` API.
798​
799| Model | Description |
800|-------|-------------|
801| `imagen-4.0-ultra-generate-001` | Best quality Imagen image generation |
802| `imagen-4.0-generate-001` | High quality Imagen image generation |
803| `imagen-4.0-fast-generate-001` | Fast Imagen image generation |
804​
805## API Reference
806​
807Every 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.
808​
809### `geminiText(model, config?)` / `createGeminiChat(model, apiKey, config?)`
810​
811Creates a Gemini text/chat adapter.
812​
813`adapter.inputModalities` lists the input kinds of the selected model. It is `undefined` for a model that this package does not know. See [Check what a model accepts](../advanced/extend-adapter#check-what-a-model-accepts).
814​
815**Parameters:**
816​
817- `model` - Gemini chat model id (e.g. `"gemini-3.1-pro-preview"`)
818- `config?.baseURL` - Custom base URL (optional)
819​
820### `geminiTextInteractions(model, config?)` / `createGeminiTextInteractions(model, apiKey, config?)` (experimental)
821​
822Creates a Gemini Interactions API text adapter. Backs the stateful conversation pattern via `previous_interaction_id`. Exported from `@tanstack/ai-gemini/experimental`.
823​
824**Parameters:**
825​
826- `model` - Gemini chat model id (e.g. `"gemini-3.5-flash"`)
827- `config?.baseURL` - Custom base URL (optional)
828​
829### `geminiSummarize(model, config?)` / `createGeminiSummarize(model, apiKey, config?)`
830​
831Creates a Gemini summarization adapter.
832​
833### `geminiImage(model, config?)` / `createGeminiImage(model, apiKey, config?)`
834​
835Creates a Gemini image adapter. When the model is in `GEMINI_NATIVE_IMAGE_MODELS`, the call uses the Interactions API. `result.id` is the interaction id. An Imagen model uses `generateImages`. An unknown id uses `generateImages`.
836​
837### `geminiSpeech(model, config?)` / `createGeminiSpeech(model, apiKey, config?)`
838​
839Creates a Gemini text-to-speech adapter. _Experimental._
840​
841### `geminiAudio(model, config?)` / `createGeminiAudio(model, apiKey, config?)`
842​
843Creates a Gemini Lyria music generation adapter. _Experimental._
844​
845## Next Steps
846​
847- [Image Generation Guide](../media/image-generation) - Learn more about image generation
848- [Media Generation Example](https://github.com/TanStack/ai/tree/main/examples/ts-react-media) - Full working example with Gemini and fal.ai
849- [Getting Started](../getting-started/quick-start) - Learn the basics
850- [Tools Guide](../tools/tools) - Learn about tools
851- [Other Adapters](./openai) - Explore other providers
852​
853## Provider Tools
854​
855Google Gemini exposes several native tools beyond user-defined function calls.
856Import them from `@tanstack/ai-gemini/tools` and pass them into
857`chat({ tools: [...] })`.
858​
859> For the full concept, a comparison matrix, and type-gating details, see
860> [Provider Tools](../tools/provider-tools.md).
861​
862### `codeExecutionTool`
863​
864Enables Gemini to execute Python code in a sandboxed environment and return
865results inline. Takes no arguments — include it in the `tools` array to
866activate code execution.
867​
868```typescript
869import { chat } from "@tanstack/ai";
870import { geminiText } from "@tanstack/ai-gemini";
871import { codeExecutionTool } from "@tanstack/ai-gemini/tools";
872​
873const stream = chat({
874 adapter: geminiText("gemini-3.1-pro-preview"),
875 messages: [{ role: "user", content: "Calculate the first 10 Fibonacci numbers" }],
876 tools: [codeExecutionTool()],
877});
878```
879​
880**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).
881​
882### `fileSearchTool`
883​
884Searches files that have been uploaded to the Gemini File API. Pass a
885`FileSearch` config object with the corpus and file IDs to scope the search.
886​
887```typescript
888import { chat } from "@tanstack/ai";
889import { geminiText } from "@tanstack/ai-gemini";
890import { fileSearchTool } from "@tanstack/ai-gemini/tools";
891​
892const stream = chat({
893 adapter: geminiText("gemini-3.1-pro-preview"),
894 messages: [{ role: "user", content: "Find the quarterly revenue figures" }],
895 tools: [
896 fileSearchTool({
897 fileSearchStoreNames: ["fileSearchStores/my-file-search-store-123"],
898 }),
899 ],
900});
901```
902​
903**Supported models:** Gemini 2.x and above. See [Provider Tools](../tools/provider-tools.md#which-models-support-which-tools).
904​
905### `googleSearchTool`
906​
907Enables Gemini to query Google Search and incorporate grounded search results
908into its response. Pass an optional `GoogleSearch` config or call with no
909arguments to use defaults.
910​
911```typescript
912import { chat } from "@tanstack/ai";
913import { geminiText } from "@tanstack/ai-gemini";
914import { googleSearchTool } from "@tanstack/ai-gemini/tools";
915​
916const stream = chat({
917 adapter: geminiText("gemini-3.1-pro-preview"),
918 messages: [{ role: "user", content: "What's the weather in Tokyo right now?" }],
919 tools: [googleSearchTool()],
920});
921```
922​
923**Supported models:** Gemini 1.5 Pro, Gemini 2.x, Gemini 2.5. See [Provider Tools](../tools/provider-tools.md#which-models-support-which-tools).
924​
925When Google Search returns grounding data, the assistant tool-call part
926includes `metadata.providerExecuted: true` and the normalized
927`metadata.sources` array. Gemini's raw `groundingMetadata` stays under
928`metadata.gemini`. The agent loop does not execute this call in your
929application.
930​
931### `googleSearchRetrievalTool`
932​
933A retrieval-augmented variant of Google Search that returns ranked passages
934from the web with configurable dynamic retrieval mode. Pass an optional
935`GoogleSearchRetrieval` config.
936​
937```typescript ignore
938import { chat } from "@tanstack/ai";
939import { geminiText } from "@tanstack/ai-gemini";
940import { googleSearchRetrievalTool } from "@tanstack/ai-gemini/tools";
941​
942const stream = chat({
943 adapter: geminiText("gemini-3.1-pro-preview"),
944 messages: [{ role: "user", content: "Explain the latest JavaScript proposals" }],
945 tools: [
946 googleSearchRetrievalTool({
947 dynamicRetrievalConfig: { mode: "MODE_DYNAMIC", dynamicThreshold: 0.7 },
948 }),
949 ],
950});
951```
952​
953**Supported models:** Gemini 1.5 Pro and above. See [Provider Tools](../tools/provider-tools.md#which-models-support-which-tools).
954​
955### `googleMapsTool`
956​
957Connects Gemini to the Google Maps API for location-aware queries such as
958directions, place search, and geocoding. Pass an optional `GoogleMaps` config
959or call with no arguments.
960​
961```typescript
962import { chat } from "@tanstack/ai";
963import { geminiText } from "@tanstack/ai-gemini";
964import { googleMapsTool } from "@tanstack/ai-gemini/tools";
965​
966const stream = chat({
967 adapter: geminiText("gemini-2.5-pro"),
968 messages: [{ role: "user", content: "Find coffee shops near Union Square, SF" }],
969 tools: [googleMapsTool()],
970});
971```
972​
973**Supported models:** Gemini 2.5 and above. See [Provider Tools](../tools/provider-tools.md#which-models-support-which-tools).
974​
975### `urlContextTool`
976​
977Fetches and includes the content of URLs mentioned in the conversation so
978Gemini can reason over live web pages. Takes no arguments.
979​
980```typescript
981import { chat } from "@tanstack/ai";
982import { geminiText } from "@tanstack/ai-gemini";
983import { urlContextTool } from "@tanstack/ai-gemini/tools";
984​
985const stream = chat({
986 adapter: geminiText("gemini-3.1-pro-preview"),
987 messages: [{ role: "user", content: "Summarise https://example.com/article" }],
988 tools: [urlContextTool()],
989});
990```
991​
992**Supported models:** Gemini 2.x and above. See [Provider Tools](../tools/provider-tools.md#which-models-support-which-tools).
993​
994### `computerUseTool`
995​
996Allows Gemini to observe a virtual desktop via screenshots and interact with
997it using predefined computer-use functions. Provide the `environment` and
998optionally restrict callable functions via `excludedPredefinedFunctions`.
999​
1000```typescript ignore
1001import { chat } from "@tanstack/ai";
1002import { geminiText } from "@tanstack/ai-gemini";
1003import { computerUseTool } from "@tanstack/ai-gemini/tools";
1004​
1005const stream = chat({
1006 adapter: geminiText("gemini-3.1-pro-preview"),
1007 messages: [{ role: "user", content: "Navigate to example.com in the browser" }],
1008 tools: [
1009 computerUseTool({
1010 environment: "browser",
1011 }),
1012 ],
1013});
1014```
1015​
1016**Supported models:** Gemini 2.5 and above. See [Provider Tools](../tools/provider-tools.md#which-models-support-which-tools).