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

gemini.md

374 lines12.4 KB

1---
2title: Google Gemini
3id: gemini-adapter
4order: 3
5description: "Use Google Gemini in TanStack AI with @tanstack/ai-gemini: multimodal chat with thinking, native and Imagen images, speech, embeddings, video understanding, and Google tools."
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 Gemini adapter calls Gemini for multimodal chat, thinking, and Google tools. It also calls image, speech, embedding, music, and video models.
18​
19Need Gemini on Vertex AI, for regional endpoints and Google Cloud credentials? Use the [Vertex adapter](./vertex).
20​
21## 1. Install
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​
36## 2. Set the API key
37​
381. Open [Google AI Studio](https://aistudio.google.com/apikey).
392. Create an API key.
403. Put the key in the environment of your server:
41​
42```bash
43GEMINI_API_KEY=your-api-key-here
44```
45​
46The short factories (`geminiText`, `geminiImage`, and the others) read `GOOGLE_API_KEY` first, then `GEMINI_API_KEY`. To pass the key in code, use the `create*` factory of the same adapter:
47​
48```typescript
49import { createGeminiChat } from "@tanstack/ai-gemini";
50​
51const adapter = createGeminiChat("gemini-3.8-flash", process.env.GEMINI_API_KEY!);
52```
53​
54## 3. Stream a chat from the server
55​
56```typescript
57import {
58 chat,
59 chatParamsFromRequest,
60 toServerSentEventsResponse,
61} from "@tanstack/ai";
62import { geminiText } from "@tanstack/ai-gemini";
63​
64export async function POST(request: Request) {
65 const { messages, threadId, runId } = await chatParamsFromRequest(request);
66​
67 const stream = chat({
68 adapter: geminiText("gemini-3.8-flash"),
69 messages,
70 threadId,
71 runId,
72 });
73​
74 return toServerSentEventsResponse(stream);
76```
77​
78`gemini-3.8-flash` takes text, images, audio, video, and documents. It supports thinking, built-in tools, structured output, and caching.
79​
80## 4. Render the chat
81​
82The client is the same for every provider. Point `useChat` at your route:
83​
84```tsx
85import { useState } from "react";
86import { useChat, fetchServerSentEvents } from "@tanstack/ai-react";
87​
88export function Chat() {
89 const [input, setInput] = useState("");
90 const { messages, sendMessage } = useChat({
91 connection: fetchServerSentEvents("/api/chat"),
92 threadId: "support-chat",
93 });
94​
95 return (
96 <form
97 onSubmit={(event) => {
98 event.preventDefault();
99 sendMessage(input);
100 setInput("");
101 }}
102 >
103 {messages.map((message) => (
104 <p key={message.id}>
105 {message.parts
106 .map((part) => (part.type === "text" ? part.content : ""))
107 .join("")}
108 </p>
109 ))}
110 <input value={input} onChange={(event) => setInput(event.target.value)} />
111 </form>
112 );
114```
115​
116For Vue, Solid, Svelte, Angular, and the other frameworks, see [Quick Start](../getting-started/quick-start#3-render-the-chat).
117​
118You now have a streaming Gemini chat. [Tools](../tools/tools) and [Structured Outputs](../structured-outputs/overview) work the same as with every adapter.
119​
120## Images
121​
122`geminiImage` takes two model groups:
123​
124- **Gemini native image models** (Nano Banana), such as `gemini-nano-banana-2.1`. You set an aspect ratio and a resolution tier in `size`, for example `"16:9_4K"`. You can edit the last image with a short prompt.
125- **Imagen models**, such as `imagen-4.0-generate-001`. You set `size` as WIDTHxHEIGHT.
126​
127```typescript
128import { generateImage } from "@tanstack/ai";
129import { geminiImage } from "@tanstack/ai-gemini";
130​
131const result = await generateImage({
132 adapter: geminiImage("gemini-nano-banana-2.1"),
133 prompt: "A futuristic cityscape at sunset",
134 threadId: "thread-1",
135 numberOfImages: 1,
136 size: "16:9_4K",
137});
138​
139console.log(result.images);
140```
141​
142The sizes of each model, image edits, and the image options are on [Gemini: Advanced](./gemini-advanced#images). For a full app, see the [media generation example](https://github.com/TanStack/ai/tree/main/examples/ts-react-media).
143​
144## Video understanding
145​
146Ask questions about a video: "what happens at 0:30?", "summarize the demo", "list every product shown". A video is too large to send inline, so upload it to the Gemini Files API first:
147​
148- `uploadGeminiFile()` uploads the file and waits until it is ready.
149- `geminiVideoPart()` turns that upload into a content part for a message.
150​
151```typescript
152import { chat, toServerSentEventsResponse } from "@tanstack/ai";
153import { geminiText, uploadGeminiFile, geminiVideoPart } from "@tanstack/ai-gemini";
154​
155export async function POST(request: Request) {
156 const file = await uploadGeminiFile("./demo.mp4", { mimeType: "video/mp4" });
157​
158 const stream = chat({
159 adapter: geminiText("gemini-3.8-flash"),
160 messages: [
161 {
162 role: "user",
163 content: [
164 { type: "text", content: "Summarize this video and cite timestamps." },
165 geminiVideoPart(file),
166 ],
167 },
168 ],
169 threadId: "thread-1",
170 });
171​
172 return toServerSentEventsResponse(stream);
174```
175​
176To change the frame rate, cut a clip, or let the model explore the video, see [Video understanding options](./gemini-advanced#video-understanding-options).
177​
178## Speech
179​
180Gemini speech is experimental.
181​
182```typescript
183import { generateSpeech } from "@tanstack/ai";
184import { geminiSpeech } from "@tanstack/ai-gemini";
185​
186const result = await generateSpeech({
187 adapter: geminiSpeech("gemini-3.1-flash-tts-preview"),
188 text: "Hello from Gemini TTS!",
189 threadId: "thread-1",
190});
191​
192console.log(result.audio); // Base64 encoded audio
193```
194​
195For a dialogue with two voices, see [Speech with two speakers](./gemini-advanced#speech-with-two-speakers).
196​
197## Embeddings
198​
199```typescript
200import { embed } from "@tanstack/ai";
201import { geminiEmbedding } from "@tanstack/ai-gemini";
202​
203const result = await embed({
204 adapter: geminiEmbedding("gemini-embedding-001"),
205 input: "a red guitar",
206 dimensions: 1536,
207 modelOptions: {
208 taskType: "RETRIEVAL_DOCUMENT",
209 },
210});
211​
212console.log(result.embeddings[0]?.vector);
213```
214​
215- The embedding endpoint of the Gemini API does not report token usage, so `result.usage` is absent.
216- This adapter does not support `multimodalembedding@001`, which is a Vertex-only model.
217​
218See the [Embeddings guide](../embeddings.md).
219​
220## Summarization
221​
222```typescript
223import { summarize } from "@tanstack/ai";
224import { geminiSummarize } from "@tanstack/ai-gemini";
225​
226const result = await summarize({
227 adapter: geminiSummarize("gemini-3.1-pro-preview"),
228 text: "Your long text to summarize...",
229 threadId: "thread-1",
230 maxLength: 100,
231 style: "concise", // "concise" | "bullet-points" | "paragraph"
232});
233​
234console.log(result.summary);
235```
236​
237## Music, video, voice, and files
238​
239- **Music**: `geminiAudio` makes music with the Lyria models. Experimental. See [Audio Generation](../media/audio-generation).
240- **Video**: `geminiVideo` makes videos with Veo and Gemini Omni. Experimental. See [Video Generation](../media/video-generation).
241- **Realtime voice**: `geminiRealtime` and `geminiRealtimeToken` run a live voice chat. See [Realtime Voice Chat](../media/realtime-chat).
242- **Files**: `geminiFiles` uploads media to the Gemini Files API. See [Files API](../advanced/files-api).
243​
244## Provider tools
245​
246Gemini runs some tools itself, such as Google Search and a code sandbox. Import them from `@tanstack/ai-gemini/tools` and add them to `tools`:
247​
248```typescript
249import { chat } from "@tanstack/ai";
250import { geminiText } from "@tanstack/ai-gemini";
251import { googleSearchTool } from "@tanstack/ai-gemini/tools";
252​
253const stream = chat({
254 adapter: geminiText("gemini-3.8-flash"),
255 messages: [{ role: "user", content: "What's the weather in Tokyo right now?" }],
256 threadId: "thread-1",
257 tools: [googleSearchTool()],
258});
259```
260​
261Tools that search or read:
262​
263- `googleSearchTool` and `googleSearchRetrievalTool`: search Google.
264- `googleMapsTool`: find places and directions.
265- `urlContextTool`: read the URLs in the conversation.
266- `fileSearchTool`: search files in Gemini file search stores.
267​
268Tools that act:
269​
270- `codeExecutionTool`: run Python in a sandbox.
271- `computerUseTool`: control a virtual desktop.
272​
273Each tool, with a full sample, is on [Gemini: Advanced](./gemini-advanced#provider-tools). For which models take which tool, see [Provider Tools](../tools/provider-tools.md).
274​
275## Models and options
276​
277### Model options
278​
279Provider options go in `modelOptions`, with the camelCase names of the Gemini SDK. This includes the sampling options `temperature`, `topP`, and `maxOutputTokens`:
280​
281```typescript
282import { chat } from "@tanstack/ai";
283import { geminiText } from "@tanstack/ai-gemini";
284​
285const stream = chat({
286 adapter: geminiText("gemini-3.8-flash"),
287 messages: [{ role: "user", content: "Hello!" }],
288 threadId: "thread-1",
289 modelOptions: {
290 maxOutputTokens: 2048,
291 temperature: 0.7,
292 topP: 0.9,
293 topK: 40,
294 stopSequences: ["END"],
295 },
296});
297```
298​
299- For JSON output, set `responseMimeType: "application/json"`. For typed output, use [Structured Outputs](../structured-outputs/overview).
300- Sampling options do not go at the root of `chat()`. See [Moving Sampling Options into modelOptions](../migration/sampling-options-to-model-options).
301​
302### Reasoning
303​
304Want Gemini to think harder? Set `reasoning` on `chat()`:
305​
306```typescript
307import { chat } from "@tanstack/ai";
308import { geminiText } from "@tanstack/ai-gemini";
309​
310const stream = chat({
311 adapter: geminiText("gemini-3.8-flash"),
312 messages: [{ role: "user", content: "Plan a database migration." }],
313 threadId: "thread-1",
314 reasoning: "high",
315});
316```
317​
318What goes to Gemini:
319​
320- Gemini 3 models: `thinkingConfig.thinkingLevel`.
321- Gemini 2.5 models: `thinkingConfig.thinkingBudget`. Set it with `budgetTokens`, or the level picks it. `off` sends a budget of `0`.
322- `summary` sets `thinkingConfig.includeThoughts`, so the thinking text streams.
323- `geminiTextInteractions`: `generation_config.thinking_level` and `thinking_summaries`.
324​
325The levels of each model:
326​
327| Model | Levels | `budgetTokens` |
328| --- | --- | --- |
329| `gemini-3.8-flash`, `gemini-3.7-flash`, `gemini-3.1-pro-preview` | `low`, `medium`, `high` | no |
330| `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 |
331| `gemini-2.5-pro` | `minimal` to `high` | yes |
332| `gemini-2.5-flash`, `gemini-2.5-flash-lite` | `off`, `high` | yes |
333​
334A Gemini 2.5 budget:
335​
336```typescript
337import { chat } from "@tanstack/ai";
338import { geminiText } from "@tanstack/ai-gemini";
339​
340const stream = chat({
341 adapter: geminiText("gemini-2.5-pro"),
342 messages: [{ role: "user", content: "Check this proof." }],
343 threadId: "thread-1",
344 reasoning: { level: "high", budgetTokens: 8000 },
345});
346```
347​
348Image models keep their own `thinkingConfig` in `modelOptions`. See [Image model options](./gemini-advanced#image-model-options).
349​
350### Models
351​
352Newest first. The package exports the full lists, for example `GeminiTextModels`.
353​
354| Activity | Factory | Models |
355| --- | --- | --- |
356| Chat | `geminiText` | `gemini-3.8-flash`, `gemini-3.7-flash`, `gemini-3.6-flash`, `gemini-3.5-flash`, `gemini-3.5-flash-lite`, `gemini-3.1-pro-preview`, `gemini-3-flash-preview`, `gemini-3.1-flash-lite`, `gemini-3.1-flash-lite-preview`, `gemini-2.5-pro`, `gemini-2.5-flash`, `gemini-2.5-flash-lite` |
357| Images (native) | `geminiImage` | `gemini-nano-banana-2.1`, `gemini-3.1-flash-image`, `gemini-3.1-flash-lite-image`, `gemini-3-pro-image` |
358| Images (Imagen) | `geminiImage` | `imagen-4.0-ultra-generate-001`, `imagen-4.0-generate-001`, `imagen-4.0-fast-generate-001` |
359| Speech | `geminiSpeech` | `gemini-3.1-flash-tts-preview`, `gemini-2.5-flash-preview-tts`, `gemini-2.5-pro-preview-tts` |
360| Music | `geminiAudio` | `lyria-3-pro-preview`, `lyria-3-clip-preview` |
361| Video | `geminiVideo` | `veo-3.1-generate-preview`, `veo-3.1-fast-generate-preview`, `veo-3.1-lite-generate-preview`, `gemini-omni-1.1-flash` |
362| Embeddings | `geminiEmbedding` | `gemini-embedding-001` |
363​
364`adapter.inputModalities` lists the input kinds of the selected model. See [Check what a model accepts](../advanced/extend-adapter#check-what-a-model-accepts).
365​
366## Advanced
367​
368These topics are on [Gemini: Advanced](./gemini-advanced):
369​
370- Configuration and a proxy or gateway.
371- Stateful conversations with the Interactions API (experimental).
372- Image sizes, image edits, and image options.
373- Video understanding options and speech with two speakers.
374- Every provider tool, with a full sample, and the API reference.