@depup/ai-sdk__google 3.0.43-depup.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 (48) hide show
  1. package/CHANGELOG.md +2531 -0
  2. package/LICENSE +13 -0
  3. package/README.md +25 -0
  4. package/changes.json +5 -0
  5. package/dist/index.d.mts +367 -0
  6. package/dist/index.d.ts +367 -0
  7. package/dist/index.js +2404 -0
  8. package/dist/index.js.map +1 -0
  9. package/dist/index.mjs +2454 -0
  10. package/dist/index.mjs.map +1 -0
  11. package/dist/internal/index.d.mts +283 -0
  12. package/dist/internal/index.d.ts +283 -0
  13. package/dist/internal/index.js +1670 -0
  14. package/dist/internal/index.js.map +1 -0
  15. package/dist/internal/index.mjs +1678 -0
  16. package/dist/internal/index.mjs.map +1 -0
  17. package/docs/15-google-generative-ai.mdx +1298 -0
  18. package/internal.d.ts +1 -0
  19. package/package.json +96 -0
  20. package/src/convert-google-generative-ai-usage.ts +51 -0
  21. package/src/convert-json-schema-to-openapi-schema.ts +158 -0
  22. package/src/convert-to-google-generative-ai-messages.ts +236 -0
  23. package/src/get-model-path.ts +3 -0
  24. package/src/google-error.ts +26 -0
  25. package/src/google-generative-ai-embedding-model.ts +159 -0
  26. package/src/google-generative-ai-embedding-options.ts +51 -0
  27. package/src/google-generative-ai-image-model.ts +359 -0
  28. package/src/google-generative-ai-image-settings.ts +17 -0
  29. package/src/google-generative-ai-language-model.ts +1056 -0
  30. package/src/google-generative-ai-options.ts +198 -0
  31. package/src/google-generative-ai-prompt.ts +38 -0
  32. package/src/google-generative-ai-video-model.ts +374 -0
  33. package/src/google-generative-ai-video-settings.ts +8 -0
  34. package/src/google-prepare-tools.ts +254 -0
  35. package/src/google-provider.ts +227 -0
  36. package/src/google-supported-file-url.ts +20 -0
  37. package/src/google-tools.ts +71 -0
  38. package/src/index.ts +29 -0
  39. package/src/internal/index.ts +3 -0
  40. package/src/map-google-generative-ai-finish-reason.ts +29 -0
  41. package/src/tool/code-execution.ts +35 -0
  42. package/src/tool/enterprise-web-search.ts +18 -0
  43. package/src/tool/file-search.ts +51 -0
  44. package/src/tool/google-maps.ts +14 -0
  45. package/src/tool/google-search.ts +43 -0
  46. package/src/tool/url-context.ts +16 -0
  47. package/src/tool/vertex-rag-store.ts +31 -0
  48. package/src/version.ts +6 -0
@@ -0,0 +1,1298 @@
1
+ ---
2
+ title: Google Generative AI
3
+ description: Learn how to use Google Generative AI Provider.
4
+ ---
5
+
6
+ # Google Generative AI Provider
7
+
8
+ The [Google Generative AI](https://ai.google.dev) provider contains language and embedding model support for
9
+ the [Google Generative AI](https://ai.google.dev/api/rest) APIs.
10
+
11
+ ## Setup
12
+
13
+ The Google provider is available in the `@ai-sdk/google` module. You can install it with
14
+
15
+ <Tabs items={['pnpm', 'npm', 'yarn', 'bun']}>
16
+ <Tab>
17
+ <Snippet text="pnpm add @ai-sdk/google" dark />
18
+ </Tab>
19
+ <Tab>
20
+ <Snippet text="npm install @ai-sdk/google" dark />
21
+ </Tab>
22
+ <Tab>
23
+ <Snippet text="yarn add @ai-sdk/google" dark />
24
+ </Tab>
25
+
26
+ <Tab>
27
+ <Snippet text="bun add @ai-sdk/google" dark />
28
+ </Tab>
29
+ </Tabs>
30
+
31
+ ## Provider Instance
32
+
33
+ You can import the default provider instance `google` from `@ai-sdk/google`:
34
+
35
+ ```ts
36
+ import { google } from '@ai-sdk/google';
37
+ ```
38
+
39
+ If you need a customized setup, you can import `createGoogleGenerativeAI` from `@ai-sdk/google` and create a provider instance with your settings:
40
+
41
+ ```ts
42
+ import { createGoogleGenerativeAI } from '@ai-sdk/google';
43
+
44
+ const google = createGoogleGenerativeAI({
45
+ // custom settings
46
+ });
47
+ ```
48
+
49
+ You can use the following optional settings to customize the Google Generative AI provider instance:
50
+
51
+ - **baseURL** _string_
52
+
53
+ Use a different URL prefix for API calls, e.g. to use proxy servers.
54
+ The default prefix is `https://generativelanguage.googleapis.com/v1beta`.
55
+
56
+ - **apiKey** _string_
57
+
58
+ API key that is being sent using the `x-goog-api-key` header.
59
+ It defaults to the `GOOGLE_GENERATIVE_AI_API_KEY` environment variable.
60
+
61
+ - **headers** _Record&lt;string,string&gt;_
62
+
63
+ Custom headers to include in the requests.
64
+
65
+ - **fetch** _(input: RequestInfo, init?: RequestInit) => Promise&lt;Response&gt;_
66
+
67
+ Custom [fetch](https://developer.mozilla.org/en-US/docs/Web/API/fetch) implementation.
68
+ Defaults to the global `fetch` function.
69
+ You can use it as a middleware to intercept requests,
70
+ or to provide a custom fetch implementation for e.g. testing.
71
+
72
+ - **generateId** _() => string_
73
+
74
+ Optional function to generate unique IDs for each request.
75
+ Defaults to the SDK's built-in ID generator.
76
+
77
+ - **name** _string_
78
+
79
+ Custom provider name.
80
+ Defaults to `'google.generative-ai'`.
81
+
82
+ ## Language Models
83
+
84
+ You can create models that call the [Google Generative AI API](https://ai.google.dev/api/rest) using the provider instance.
85
+ The first argument is the model id, e.g. `gemini-2.5-flash`.
86
+ The models support tool calls and some have multi-modal capabilities.
87
+
88
+ ```ts
89
+ const model = google('gemini-2.5-flash');
90
+ ```
91
+
92
+ You can use Google Generative AI language models to generate text with the `generateText` function:
93
+
94
+ ```ts
95
+ import { google } from '@ai-sdk/google';
96
+ import { generateText } from 'ai';
97
+
98
+ const { text } = await generateText({
99
+ model: google('gemini-2.5-flash'),
100
+ prompt: 'Write a vegetarian lasagna recipe for 4 people.',
101
+ });
102
+ ```
103
+
104
+ Google Generative AI language models can also be used in the `streamText` function
105
+ and support structured data generation with [`Output`](/docs/reference/ai-sdk-core/output)
106
+ (see [AI SDK Core](/docs/ai-sdk-core)).
107
+
108
+ Google Generative AI also supports some model specific settings that are not part of the [standard call settings](/docs/ai-sdk-core/settings).
109
+ You can pass them as an options argument:
110
+
111
+ ```ts
112
+ import { google, type GoogleLanguageModelOptions } from '@ai-sdk/google';
113
+
114
+ const model = google('gemini-2.5-flash');
115
+
116
+ await generateText({
117
+ model,
118
+ providerOptions: {
119
+ google: {
120
+ safetySettings: [
121
+ {
122
+ category: 'HARM_CATEGORY_UNSPECIFIED',
123
+ threshold: 'BLOCK_LOW_AND_ABOVE',
124
+ },
125
+ ],
126
+ } satisfies GoogleLanguageModelOptions,
127
+ },
128
+ });
129
+ ```
130
+
131
+ The following optional provider options are available for Google Generative AI models:
132
+
133
+ - **cachedContent** _string_
134
+
135
+ Optional. The name of the cached content used as context to serve the prediction.
136
+ Format: cachedContents/\{cachedContent\}
137
+
138
+ - **structuredOutputs** _boolean_
139
+
140
+ Optional. Enable structured output. Default is true.
141
+
142
+ This is useful when the JSON Schema contains elements that are
143
+ not supported by the OpenAPI schema version that
144
+ Google Generative AI uses. You can use this to disable
145
+ structured outputs if you need to.
146
+
147
+ See [Troubleshooting: Schema Limitations](#schema-limitations) for more details.
148
+
149
+ - **safetySettings** _Array\<\{ category: string; threshold: string \}\>_
150
+
151
+ Optional. Safety settings for the model.
152
+
153
+ - **category** _string_
154
+
155
+ The category of the safety setting. Can be one of the following:
156
+
157
+ - `HARM_CATEGORY_UNSPECIFIED`
158
+ - `HARM_CATEGORY_HATE_SPEECH`
159
+ - `HARM_CATEGORY_DANGEROUS_CONTENT`
160
+ - `HARM_CATEGORY_HARASSMENT`
161
+ - `HARM_CATEGORY_SEXUALLY_EXPLICIT`
162
+ - `HARM_CATEGORY_CIVIC_INTEGRITY`
163
+
164
+ - **threshold** _string_
165
+
166
+ The threshold of the safety setting. Can be one of the following:
167
+
168
+ - `HARM_BLOCK_THRESHOLD_UNSPECIFIED`
169
+ - `BLOCK_LOW_AND_ABOVE`
170
+ - `BLOCK_MEDIUM_AND_ABOVE`
171
+ - `BLOCK_ONLY_HIGH`
172
+ - `BLOCK_NONE`
173
+ - `OFF`
174
+
175
+ - **responseModalities** _string[]_
176
+ The modalities to use for the response. The following modalities are supported: `TEXT`, `IMAGE`. When not defined or empty, the model defaults to returning only text.
177
+
178
+ - **thinkingConfig** _\{ thinkingLevel?: 'minimal' | 'low' | 'medium' | 'high'; thinkingBudget?: number; includeThoughts?: boolean \}_
179
+
180
+ Optional. Configuration for the model's thinking process. Only supported by specific [Google Generative AI models](https://ai.google.dev/gemini-api/docs/thinking).
181
+
182
+ - **thinkingLevel** _'minimal' | 'low' | 'medium' | 'high'_
183
+
184
+ Optional. Controls the thinking depth for Gemini 3 models. Gemini 3.1 Pro supports 'low', 'medium', and 'high', Gemini 3 Pro supports 'low' and 'high', while Gemini 3 Flash supports all four levels: 'minimal', 'low', 'medium', and 'high'. Only supported by Gemini 3 models.
185
+
186
+ - **thinkingBudget** _number_
187
+
188
+ Optional. Gives the model guidance on the number of thinking tokens it can use when generating a response. Setting it to 0 disables thinking, if the model supports it.
189
+ For more information about the possible value ranges for each model see [Google Generative AI thinking documentation](https://ai.google.dev/gemini-api/docs/thinking#set-budget).
190
+
191
+ <Note>
192
+ This option is for Gemini 2.5 models. Gemini 3 models should use
193
+ `thinkingLevel` instead.
194
+ </Note>
195
+
196
+ - **includeThoughts** _boolean_
197
+
198
+ Optional. If set to true, thought summaries are returned, which are synthesized versions of the model's raw thoughts and offer insights into the model's internal reasoning process.
199
+
200
+ - **imageConfig** _\{ aspectRatio?: string, imageSize?: string \}_
201
+
202
+ Optional. Configuration for the models image generation. Only supported by specific [Google Generative AI models](https://ai.google.dev/gemini-api/docs/image-generation).
203
+
204
+ - **aspectRatio** _string_
205
+
206
+ Model defaults to generate 1:1 squares, or to matching the output image size to that of your input image. Can be one of the following:
207
+
208
+ - 1:1
209
+ - 2:3
210
+ - 3:2
211
+ - 3:4
212
+ - 4:3
213
+ - 4:5
214
+ - 5:4
215
+ - 9:16
216
+ - 16:9
217
+ - 21:9
218
+
219
+ - **imageSize** _string_
220
+
221
+ Controls the output image resolution. Defaults to 1K. Can be one of the following:
222
+
223
+ - 1K
224
+ - 2K
225
+ - 4K
226
+
227
+ - **audioTimestamp** _boolean_
228
+
229
+ Optional. Enables timestamp understanding for audio-only files.
230
+ See [Google Cloud audio understanding documentation](https://cloud.google.com/vertex-ai/generative-ai/docs/multimodal/audio-understanding).
231
+
232
+ - **mediaResolution** _string_
233
+
234
+ Optional. If specified, the media resolution specified will be used. Can be one of the following:
235
+
236
+ - `MEDIA_RESOLUTION_UNSPECIFIED`
237
+ - `MEDIA_RESOLUTION_LOW`
238
+ - `MEDIA_RESOLUTION_MEDIUM`
239
+ - `MEDIA_RESOLUTION_HIGH`
240
+
241
+ See [Google API MediaResolution documentation](https://ai.google.dev/api/generate-content#MediaResolution).
242
+
243
+ - **labels** _Record&lt;string, string&gt;_
244
+
245
+ Optional. Defines labels used in billing reports. Available on Vertex AI only.
246
+ See [Google Cloud labels documentation](https://cloud.google.com/vertex-ai/generative-ai/docs/multimodal/add-labels-to-api-calls).
247
+
248
+ - **threshold** _string_
249
+
250
+ Optional. Standalone threshold setting that can be used independently of `safetySettings`.
251
+ Uses the same values as the `safetySettings` threshold.
252
+
253
+ ### Thinking
254
+
255
+ The Gemini 2.5 and Gemini 3 series models use an internal "thinking process" that significantly improves their reasoning and multi-step planning abilities, making them highly effective for complex tasks such as coding, advanced mathematics, and data analysis. For more information see [Google Generative AI thinking documentation](https://ai.google.dev/gemini-api/docs/thinking).
256
+
257
+ #### Gemini 3 Models
258
+
259
+ For Gemini 3 models, use the `thinkingLevel` parameter to control the depth of reasoning:
260
+
261
+ ```ts
262
+ import { google, GoogleLanguageModelOptions } from '@ai-sdk/google';
263
+ import { generateText } from 'ai';
264
+
265
+ const model = google('gemini-3.1-pro-preview');
266
+
267
+ const { text, reasoning } = await generateText({
268
+ model: model,
269
+ prompt: 'What is the sum of the first 10 prime numbers?',
270
+ providerOptions: {
271
+ google: {
272
+ thinkingConfig: {
273
+ thinkingLevel: 'high',
274
+ includeThoughts: true,
275
+ },
276
+ } satisfies GoogleLanguageModelOptions,
277
+ },
278
+ });
279
+
280
+ console.log(text);
281
+
282
+ console.log(reasoning); // Reasoning summary
283
+ ```
284
+
285
+ #### Gemini 2.5 Models
286
+
287
+ For Gemini 2.5 models, use the `thinkingBudget` parameter to control the number of thinking tokens:
288
+
289
+ ```ts
290
+ import { google, GoogleLanguageModelOptions } from '@ai-sdk/google';
291
+ import { generateText } from 'ai';
292
+
293
+ const model = google('gemini-2.5-flash');
294
+
295
+ const { text, reasoning } = await generateText({
296
+ model: model,
297
+ prompt: 'What is the sum of the first 10 prime numbers?',
298
+ providerOptions: {
299
+ google: {
300
+ thinkingConfig: {
301
+ thinkingBudget: 8192,
302
+ includeThoughts: true,
303
+ },
304
+ } satisfies GoogleLanguageModelOptions,
305
+ },
306
+ });
307
+
308
+ console.log(text);
309
+
310
+ console.log(reasoning); // Reasoning summary
311
+ ```
312
+
313
+ ### File Inputs
314
+
315
+ The Google Generative AI provider supports file inputs, e.g. PDF files.
316
+
317
+ ```ts
318
+ import { google } from '@ai-sdk/google';
319
+ import { generateText } from 'ai';
320
+
321
+ const result = await generateText({
322
+ model: google('gemini-2.5-flash'),
323
+ messages: [
324
+ {
325
+ role: 'user',
326
+ content: [
327
+ {
328
+ type: 'text',
329
+ text: 'What is an embedding model according to this document?',
330
+ },
331
+ {
332
+ type: 'file',
333
+ data: fs.readFileSync('./data/ai.pdf'),
334
+ mediaType: 'application/pdf',
335
+ },
336
+ ],
337
+ },
338
+ ],
339
+ });
340
+ ```
341
+
342
+ You can also use YouTube URLs directly:
343
+
344
+ ```ts
345
+ import { google } from '@ai-sdk/google';
346
+ import { generateText } from 'ai';
347
+
348
+ const result = await generateText({
349
+ model: google('gemini-2.5-flash'),
350
+ messages: [
351
+ {
352
+ role: 'user',
353
+ content: [
354
+ {
355
+ type: 'text',
356
+ text: 'Summarize this video',
357
+ },
358
+ {
359
+ type: 'file',
360
+ data: 'https://www.youtube.com/watch?v=dQw4w9WgXcQ',
361
+ mediaType: 'video/mp4',
362
+ },
363
+ ],
364
+ },
365
+ ],
366
+ });
367
+ ```
368
+
369
+ <Note>
370
+ The AI SDK will automatically download URLs if you pass them as data, except
371
+ for `https://generativelanguage.googleapis.com/v1beta/files/` and YouTube
372
+ URLs. You can use the Google Generative AI Files API to upload larger files to
373
+ that location. YouTube URLs (public or unlisted videos) are supported directly
374
+ - you can specify one YouTube video URL per request.
375
+ </Note>
376
+
377
+ See [File Parts](/docs/foundations/prompts#file-parts) for details on how to use files in prompts.
378
+
379
+ ### Cached Content
380
+
381
+ Google Generative AI supports both explicit and implicit caching to help reduce costs on repetitive content.
382
+
383
+ #### Implicit Caching
384
+
385
+ Gemini 2.5 models automatically provide cache cost savings without needing to create an explicit cache. When you send requests that share common prefixes with previous requests, you'll receive a 75% token discount on cached content.
386
+
387
+ To maximize cache hits with implicit caching:
388
+
389
+ - Keep content at the beginning of requests consistent
390
+ - Add variable content (like user questions) at the end of prompts
391
+ - Ensure requests meet minimum token requirements:
392
+ - Gemini 2.5 Flash: 1024 tokens minimum
393
+ - Gemini 2.5 Pro: 2048 tokens minimum
394
+
395
+ ```ts
396
+ import { google } from '@ai-sdk/google';
397
+ import { generateText } from 'ai';
398
+
399
+ // Structure prompts with consistent content at the beginning
400
+ const baseContext =
401
+ 'You are a cooking assistant with expertise in Italian cuisine. Here are 1000 lasagna recipes for reference...';
402
+
403
+ const { text: veggieLasagna } = await generateText({
404
+ model: google('gemini-2.5-pro'),
405
+ prompt: `${baseContext}\n\nWrite a vegetarian lasagna recipe for 4 people.`,
406
+ });
407
+
408
+ // Second request with same prefix - eligible for cache hit
409
+ const { text: meatLasagna, providerMetadata } = await generateText({
410
+ model: google('gemini-2.5-pro'),
411
+ prompt: `${baseContext}\n\nWrite a meat lasagna recipe for 12 people.`,
412
+ });
413
+
414
+ // Check cached token count in usage metadata
415
+ console.log('Cached tokens:', providerMetadata.google);
416
+ // e.g.
417
+ // {
418
+ // groundingMetadata: null,
419
+ // safetyRatings: null,
420
+ // usageMetadata: {
421
+ // cachedContentTokenCount: 2027,
422
+ // thoughtsTokenCount: 702,
423
+ // promptTokenCount: 2152,
424
+ // candidatesTokenCount: 710,
425
+ // totalTokenCount: 3564
426
+ // }
427
+ // }
428
+ ```
429
+
430
+ <Note>
431
+ Usage metadata was added to `providerMetadata` in `@ai-sdk/google@1.2.23`. If
432
+ you are using an older version, usage metadata is available in the raw HTTP
433
+ `response` body returned as part of the return value from `generateText`.
434
+ </Note>
435
+
436
+ #### Explicit Caching
437
+
438
+ For guaranteed cost savings, you can still use explicit caching with Gemini 2.5 and 2.0 models. See the [models page](https://ai.google.dev/gemini-api/docs/models) to check if caching is supported for the used model:
439
+
440
+ ```ts
441
+ import { google, type GoogleLanguageModelOptions } from '@ai-sdk/google';
442
+ import { GoogleGenAI } from '@google/genai';
443
+ import { generateText } from 'ai';
444
+
445
+ const ai = new GoogleGenAI({
446
+ apiKey: process.env.GOOGLE_GENERATIVE_AI_API_KEY,
447
+ });
448
+
449
+ const model = 'gemini-2.5-pro';
450
+
451
+ // Create a cache with the content you want to reuse
452
+ const cache = await ai.caches.create({
453
+ model,
454
+ config: {
455
+ contents: [
456
+ {
457
+ role: 'user',
458
+ parts: [{ text: '1000 Lasagna Recipes...' }],
459
+ },
460
+ ],
461
+ ttl: '300s', // Cache expires after 5 minutes
462
+ },
463
+ });
464
+
465
+ const { text: veggieLasagnaRecipe } = await generateText({
466
+ model: google(model),
467
+ prompt: 'Write a vegetarian lasagna recipe for 4 people.',
468
+ providerOptions: {
469
+ google: {
470
+ cachedContent: cache.name,
471
+ } satisfies GoogleLanguageModelOptions,
472
+ },
473
+ });
474
+
475
+ const { text: meatLasagnaRecipe } = await generateText({
476
+ model: google(model),
477
+ prompt: 'Write a meat lasagna recipe for 12 people.',
478
+ providerOptions: {
479
+ google: {
480
+ cachedContent: cache.name,
481
+ } satisfies GoogleLanguageModelOptions,
482
+ },
483
+ });
484
+ ```
485
+
486
+ ### Code Execution
487
+
488
+ With [Code Execution](https://ai.google.dev/gemini-api/docs/code-execution), certain models can generate and execute Python code to perform calculations, solve problems, or provide more accurate information.
489
+
490
+ You can enable code execution by adding the `code_execution` tool to your request.
491
+
492
+ ```ts
493
+ import { google } from '@ai-sdk/google';
494
+ import { googleTools } from '@ai-sdk/google/internal';
495
+ import { generateText } from 'ai';
496
+
497
+ const { text, toolCalls, toolResults } = await generateText({
498
+ model: google('gemini-2.5-pro'),
499
+ tools: { code_execution: google.tools.codeExecution({}) },
500
+ prompt: 'Use python to calculate the 20th fibonacci number.',
501
+ });
502
+ ```
503
+
504
+ The response will contain the tool calls and results from the code execution.
505
+
506
+ ### Google Search
507
+
508
+ With [Google Search grounding](https://ai.google.dev/gemini-api/docs/google-search),
509
+ the model has access to the latest information using Google Search.
510
+
511
+ ```ts highlight="8,17-20"
512
+ import { google } from '@ai-sdk/google';
513
+ import { GoogleGenerativeAIProviderMetadata } from '@ai-sdk/google';
514
+ import { generateText } from 'ai';
515
+
516
+ const { text, sources, providerMetadata } = await generateText({
517
+ model: google('gemini-2.5-flash'),
518
+ tools: {
519
+ google_search: google.tools.googleSearch({}),
520
+ },
521
+ prompt:
522
+ 'List the top 5 San Francisco news from the past week.' +
523
+ 'You must include the date of each article.',
524
+ });
525
+
526
+ // access the grounding metadata. Casting to the provider metadata type
527
+ // is optional but provides autocomplete and type safety.
528
+ const metadata = providerMetadata?.google as
529
+ | GoogleGenerativeAIProviderMetadata
530
+ | undefined;
531
+ const groundingMetadata = metadata?.groundingMetadata;
532
+ const safetyRatings = metadata?.safetyRatings;
533
+ ```
534
+
535
+ The `googleSearch` tool accepts the following optional configuration options:
536
+
537
+ - **searchTypes** _object_
538
+
539
+ Enables specific search types. Both can be combined.
540
+
541
+ - `webSearch`: Enable web search grounding (pass `{}` to enable). This is the default.
542
+ - `imageSearch`: Enable [image search grounding](https://ai.google.dev/gemini-api/docs/image-generation#image-search) (pass `{}` to enable).
543
+
544
+ - **timeRangeFilter** _object_
545
+
546
+ Restricts search results to a specific time range. Both `startTime` and `endTime` are required.
547
+
548
+ - `startTime`: Start time in ISO 8601 format (e.g. `'2025-01-01T00:00:00Z'`).
549
+ - `endTime`: End time in ISO 8601 format (e.g. `'2025-12-31T23:59:59Z'`).
550
+
551
+ ```ts
552
+ google.tools.googleSearch({
553
+ searchTypes: { webSearch: {} },
554
+ timeRangeFilter: {
555
+ startTime: '2025-01-01T00:00:00Z',
556
+ endTime: '2025-12-31T23:59:59Z',
557
+ },
558
+ });
559
+ ```
560
+
561
+ When Google Search grounding is enabled, the model will include sources in the response.
562
+
563
+ Additionally, the grounding metadata includes detailed information about how search results were used to ground the model's response. Here are the available fields:
564
+
565
+ - **`webSearchQueries`** (`string[] | null`)
566
+
567
+ - Array of search queries used to retrieve information
568
+ - Example: `["What's the weather in Chicago this weekend?"]`
569
+
570
+ - **`searchEntryPoint`** (`{ renderedContent: string } | null`)
571
+
572
+ - Contains the main search result content used as an entry point
573
+ - The `renderedContent` field contains the formatted content
574
+
575
+ - **`groundingSupports`** (Array of support objects | null)
576
+ - Contains details about how specific response parts are supported by search results
577
+ - Each support object includes:
578
+ - **`segment`**: Information about the grounded text segment
579
+ - `text`: The actual text segment
580
+ - `startIndex`: Starting position in the response
581
+ - `endIndex`: Ending position in the response
582
+ - **`groundingChunkIndices`**: References to supporting search result chunks
583
+ - **`confidenceScores`**: Confidence scores (0-1) for each supporting chunk
584
+
585
+ Example response:
586
+
587
+ ```json
588
+ {
589
+ "groundingMetadata": {
590
+ "webSearchQueries": ["What's the weather in Chicago this weekend?"],
591
+ "searchEntryPoint": {
592
+ "renderedContent": "..."
593
+ },
594
+ "groundingSupports": [
595
+ {
596
+ "segment": {
597
+ "startIndex": 0,
598
+ "endIndex": 65,
599
+ "text": "Chicago weather changes rapidly, so layers let you adjust easily."
600
+ },
601
+ "groundingChunkIndices": [0],
602
+ "confidenceScores": [0.99]
603
+ }
604
+ ]
605
+ }
606
+ }
607
+ ```
608
+
609
+ ### Enterprise Web Search
610
+
611
+ With [Enterprise Web Search](https://cloud.google.com/vertex-ai/generative-ai/docs/grounding/web-grounding-enterprise),
612
+ the model has access to a compliance-focused web index designed for highly-regulated industries such as finance, healthcare, and public sector.
613
+
614
+ <Note>
615
+ Enterprise Web Search is only available on Vertex AI. You must use the Google
616
+ Vertex provider (`@ai-sdk/google-vertex`) instead of the standard Google
617
+ provider (`@ai-sdk/google`) to use this feature. Requires Gemini 2.0 or newer
618
+ models.
619
+ </Note>
620
+
621
+ ```ts
622
+ import { createVertex } from '@ai-sdk/google-vertex';
623
+ import { generateText } from 'ai';
624
+
625
+ const vertex = createVertex({
626
+ project: 'my-project',
627
+ location: 'us-central1',
628
+ });
629
+
630
+ const { text, sources, providerMetadata } = await generateText({
631
+ model: vertex('gemini-2.5-flash'),
632
+ tools: {
633
+ enterprise_web_search: vertex.tools.enterpriseWebSearch({}),
634
+ },
635
+ prompt: 'What are the latest regulatory updates for financial services?',
636
+ });
637
+ ```
638
+
639
+ Enterprise Web Search provides the following benefits:
640
+
641
+ - Does not log customer data
642
+ - Supports VPC service controls
643
+ - Compliance-focused web index for regulated industries
644
+
645
+ ### File Search
646
+
647
+ The [File Search tool](https://ai.google.dev/gemini-api/docs/file-search) lets Gemini retrieve context from your own documents that you have indexed in File Search stores. Only Gemini 2.5 and Gemini 3 models support this feature.
648
+
649
+ ```ts highlight="9-13"
650
+ import { google } from '@ai-sdk/google';
651
+ import { generateText } from 'ai';
652
+
653
+ const { text, sources } = await generateText({
654
+ model: google('gemini-2.5-pro'),
655
+ tools: {
656
+ file_search: google.tools.fileSearch({
657
+ fileSearchStoreNames: [
658
+ 'projects/my-project/locations/us/fileSearchStores/my-store',
659
+ ],
660
+ metadataFilter: 'author = "Robert Graves"',
661
+ topK: 8,
662
+ }),
663
+ },
664
+ prompt: "Summarise the key themes of 'I, Claudius'.",
665
+ });
666
+ ```
667
+
668
+ File Search responses include citations via the normal `sources` field and expose raw [grounding metadata](#google-search) in `providerMetadata.google.groundingMetadata`.
669
+
670
+ ### URL Context
671
+
672
+ Google provides a provider-defined URL context tool.
673
+
674
+ The URL context tool allows you to provide specific URLs that you want the model to analyze directly in from the prompt.
675
+
676
+ ```ts highlight="9,13-17"
677
+ import { google } from '@ai-sdk/google';
678
+ import { generateText } from 'ai';
679
+
680
+ const { text, sources, providerMetadata } = await generateText({
681
+ model: google('gemini-2.5-flash'),
682
+ prompt: `Based on the document: https://ai.google.dev/gemini-api/docs/url-context.
683
+ Answer this question: How many links we can consume in one request?`,
684
+ tools: {
685
+ url_context: google.tools.urlContext({}),
686
+ },
687
+ });
688
+
689
+ const metadata = providerMetadata?.google as
690
+ | GoogleGenerativeAIProviderMetadata
691
+ | undefined;
692
+ const groundingMetadata = metadata?.groundingMetadata;
693
+ const urlContextMetadata = metadata?.urlContextMetadata;
694
+ ```
695
+
696
+ The URL context metadata includes detailed information about how the model used the URL context to generate the response. Here are the available fields:
697
+
698
+ - **`urlMetadata`** (`{ retrievedUrl: string; urlRetrievalStatus: string; }[] | null`)
699
+
700
+ - Array of URL context metadata
701
+ - Each object includes:
702
+ - **`retrievedUrl`**: The URL of the context
703
+ - **`urlRetrievalStatus`**: The status of the URL retrieval
704
+
705
+ Example response:
706
+
707
+ ```json
708
+ {
709
+ "urlMetadata": [
710
+ {
711
+ "retrievedUrl": "https://ai-sdk.dev/providers/ai-sdk-providers/google-generative-ai",
712
+ "urlRetrievalStatus": "URL_RETRIEVAL_STATUS_SUCCESS"
713
+ }
714
+ ]
715
+ }
716
+ ```
717
+
718
+ With the URL context tool, you will also get the `groundingMetadata`.
719
+
720
+ ```json
721
+ "groundingMetadata": {
722
+ "groundingChunks": [
723
+ {
724
+ "web": {
725
+ "uri": "https://ai-sdk.dev/providers/ai-sdk-providers/google-generative-ai",
726
+ "title": "Google Generative AI - AI SDK Providers"
727
+ }
728
+ }
729
+ ],
730
+ "groundingSupports": [
731
+ {
732
+ "segment": {
733
+ "startIndex": 67,
734
+ "endIndex": 157,
735
+ "text": "**Installation**: Install the `@ai-sdk/google` module using your preferred package manager"
736
+ },
737
+ "groundingChunkIndices": [
738
+ 0
739
+ ]
740
+ },
741
+ ]
742
+ }
743
+ ```
744
+
745
+ <Note>You can add up to 20 URLs per request.</Note>
746
+
747
+ <Note>
748
+ The URL context tool is only supported for Gemini 2.0 Flash models and above.
749
+ Check the [supported models for URL context
750
+ tool](https://ai.google.dev/gemini-api/docs/url-context#supported-models).
751
+ </Note>
752
+
753
+ #### Combine URL Context with Search Grounding
754
+
755
+ You can combine the URL context tool with search grounding to provide the model with the latest information from the web.
756
+
757
+ ```ts highlight="9-10"
758
+ import { google } from '@ai-sdk/google';
759
+ import { generateText } from 'ai';
760
+
761
+ const { text, sources, providerMetadata } = await generateText({
762
+ model: google('gemini-2.5-flash'),
763
+ prompt: `Based on this context: https://ai-sdk.dev/providers/ai-sdk-providers/google-generative-ai, tell me how to use Gemini with AI SDK.
764
+ Also, provide the latest news about AI SDK V5.`,
765
+ tools: {
766
+ google_search: google.tools.googleSearch({}),
767
+ url_context: google.tools.urlContext({}),
768
+ },
769
+ });
770
+
771
+ const metadata = providerMetadata?.google as
772
+ | GoogleGenerativeAIProviderMetadata
773
+ | undefined;
774
+ const groundingMetadata = metadata?.groundingMetadata;
775
+ const urlContextMetadata = metadata?.urlContextMetadata;
776
+ ```
777
+
778
+ ### Google Maps Grounding
779
+
780
+ With [Google Maps grounding](https://ai.google.dev/gemini-api/docs/maps-grounding),
781
+ the model has access to Google Maps data for location-aware responses. This enables providing local data and geospatial context, such as finding nearby restaurants.
782
+
783
+ ```ts highlight="7-16"
784
+ import { google, type GoogleLanguageModelOptions } from '@ai-sdk/google';
785
+ import { GoogleGenerativeAIProviderMetadata } from '@ai-sdk/google';
786
+ import { generateText } from 'ai';
787
+
788
+ const { text, sources, providerMetadata } = await generateText({
789
+ model: google('gemini-2.5-flash'),
790
+ tools: {
791
+ google_maps: google.tools.googleMaps({}),
792
+ },
793
+ providerOptions: {
794
+ google: {
795
+ retrievalConfig: {
796
+ latLng: { latitude: 34.090199, longitude: -117.881081 },
797
+ },
798
+ } satisfies GoogleLanguageModelOptions,
799
+ },
800
+ prompt:
801
+ 'What are the best Italian restaurants within a 15-minute walk from here?',
802
+ });
803
+
804
+ const metadata = providerMetadata?.google as
805
+ | GoogleGenerativeAIProviderMetadata
806
+ | undefined;
807
+ const groundingMetadata = metadata?.groundingMetadata;
808
+ ```
809
+
810
+ The optional `retrievalConfig.latLng` provider option provides location context for queries about nearby places. This configuration applies to any grounding tools that support location context, including Google Maps and Google Search.
811
+
812
+ When Google Maps grounding is enabled, the model's response will include sources pointing to Google Maps URLs. The grounding metadata includes `maps` chunks with place information:
813
+
814
+ ```json
815
+ {
816
+ "groundingMetadata": {
817
+ "groundingChunks": [
818
+ {
819
+ "maps": {
820
+ "uri": "https://maps.google.com/?cid=12345",
821
+ "title": "Restaurant Name",
822
+ "placeId": "places/ChIJ..."
823
+ }
824
+ }
825
+ ]
826
+ }
827
+ }
828
+ ```
829
+
830
+ <Note>Google Maps grounding is supported on Gemini 2.0 and newer models.</Note>
831
+
832
+ ### RAG Engine Grounding
833
+
834
+ With [RAG Engine Grounding](https://cloud.google.com/vertex-ai/generative-ai/docs/rag-engine/use-vertexai-search#generate-content-using-gemini-api),
835
+ the model has access to your custom knowledge base using the Vertex RAG Engine.
836
+ This enables the model to provide answers based on your specific data sources and documents.
837
+
838
+ <Note>
839
+ RAG Engine Grounding is only supported with Vertex Gemini models. You must use
840
+ the Google Vertex provider (`@ai-sdk/google-vertex`) instead of the standard
841
+ Google provider (`@ai-sdk/google`) to use this feature.
842
+ </Note>
843
+
844
+ ```ts highlight="8,17-20"
845
+ import { createVertex } from '@ai-sdk/google-vertex';
846
+ import { GoogleGenerativeAIProviderMetadata } from '@ai-sdk/google';
847
+ import { generateText } from 'ai';
848
+
849
+ const vertex = createVertex({
850
+ project: 'my-project',
851
+ location: 'us-central1',
852
+ });
853
+
854
+ const { text, sources, providerMetadata } = await generateText({
855
+ model: vertex('gemini-2.5-flash'),
856
+ tools: {
857
+ vertex_rag_store: vertex.tools.vertexRagStore({
858
+ ragCorpus:
859
+ 'projects/my-project/locations/us-central1/ragCorpora/my-rag-corpus',
860
+ topK: 5,
861
+ }),
862
+ },
863
+ prompt:
864
+ 'What are the key features of our product according to our documentation?',
865
+ });
866
+
867
+ // access the grounding metadata. Casting to the provider metadata type
868
+ // is optional but provides autocomplete and type safety.
869
+ const metadata = providerMetadata?.google as
870
+ | GoogleGenerativeAIProviderMetadata
871
+ | undefined;
872
+ const groundingMetadata = metadata?.groundingMetadata;
873
+ const safetyRatings = metadata?.safetyRatings;
874
+ ```
875
+
876
+ When RAG Engine Grounding is enabled, the model will include sources from your RAG corpus in the response.
877
+
878
+ Additionally, the grounding metadata includes detailed information about how RAG results were used to ground the model's response. Here are the available fields:
879
+
880
+ - **`groundingChunks`** (Array of chunk objects | null)
881
+
882
+ - Contains the retrieved context chunks from your RAG corpus
883
+ - Each chunk includes:
884
+ - **`retrievedContext`**: Information about the retrieved context
885
+ - `uri`: The URI or identifier of the source document
886
+ - `title`: The title of the source document (optional)
887
+ - `text`: The actual text content of the chunk
888
+
889
+ - **`groundingSupports`** (Array of support objects | null)
890
+
891
+ - Contains details about how specific response parts are supported by RAG results
892
+ - Each support object includes:
893
+ - **`segment`**: Information about the grounded text segment
894
+ - `text`: The actual text segment
895
+ - `startIndex`: Starting position in the response
896
+ - `endIndex`: Ending position in the response
897
+ - **`groundingChunkIndices`**: References to supporting RAG result chunks
898
+ - **`confidenceScores`**: Confidence scores (0-1) for each supporting chunk
899
+
900
+ Example response:
901
+
902
+ ```json
903
+ {
904
+ "groundingMetadata": {
905
+ "groundingChunks": [
906
+ {
907
+ "retrievedContext": {
908
+ "uri": "gs://my-bucket/docs/product-guide.pdf",
909
+ "title": "Product User Guide",
910
+ "text": "Our product includes advanced AI capabilities, real-time processing, and enterprise-grade security features."
911
+ }
912
+ }
913
+ ],
914
+ "groundingSupports": [
915
+ {
916
+ "segment": {
917
+ "startIndex": 0,
918
+ "endIndex": 45,
919
+ "text": "Our product includes advanced AI capabilities and real-time processing."
920
+ },
921
+ "groundingChunkIndices": [0],
922
+ "confidenceScores": [0.95]
923
+ }
924
+ ]
925
+ }
926
+ }
927
+ ```
928
+
929
+ #### Configuration Options
930
+
931
+ The `vertexRagStore` tool accepts the following configuration options:
932
+
933
+ - **`ragCorpus`** (`string`, required)
934
+
935
+ - The RagCorpus resource name in the format: `projects/{project}/locations/{location}/ragCorpora/{rag_corpus}`
936
+ - This identifies your specific RAG corpus to search against
937
+
938
+ - **`topK`** (`number`, optional)
939
+
940
+ - The number of top contexts to retrieve from your RAG corpus
941
+ - Defaults to the corpus configuration if not specified
942
+
943
+ ### Image Outputs
944
+
945
+ Gemini models with image generation capabilities (e.g. `gemini-2.5-flash-image`) support generating images as part of a multimodal response. Images are exposed as files in the response.
946
+
947
+ ```ts
948
+ import { google } from '@ai-sdk/google';
949
+ import { generateText } from 'ai';
950
+
951
+ const result = await generateText({
952
+ model: google('gemini-2.5-flash-image'),
953
+ prompt:
954
+ 'Create a picture of a nano banana dish in a fancy restaurant with a Gemini theme',
955
+ });
956
+
957
+ for (const file of result.files) {
958
+ if (file.mediaType.startsWith('image/')) {
959
+ console.log('Generated image:', file);
960
+ }
961
+ }
962
+ ```
963
+
964
+ <Note>
965
+ If you primarily want to generate images without text output, you can also use
966
+ Gemini image models with the `generateImage()` function. See [Gemini Image
967
+ Models](#gemini-image-models) for details.
968
+ </Note>
969
+
970
+ ### Safety Ratings
971
+
972
+ The safety ratings provide insight into the safety of the model's response.
973
+ See [Google AI documentation on safety settings](https://ai.google.dev/gemini-api/docs/safety-settings).
974
+
975
+ Example response excerpt:
976
+
977
+ ```json
978
+ {
979
+ "safetyRatings": [
980
+ {
981
+ "category": "HARM_CATEGORY_HATE_SPEECH",
982
+ "probability": "NEGLIGIBLE",
983
+ "probabilityScore": 0.11027937,
984
+ "severity": "HARM_SEVERITY_LOW",
985
+ "severityScore": 0.28487435
986
+ },
987
+ {
988
+ "category": "HARM_CATEGORY_DANGEROUS_CONTENT",
989
+ "probability": "HIGH",
990
+ "blocked": true,
991
+ "probabilityScore": 0.95422274,
992
+ "severity": "HARM_SEVERITY_MEDIUM",
993
+ "severityScore": 0.43398145
994
+ },
995
+ {
996
+ "category": "HARM_CATEGORY_HARASSMENT",
997
+ "probability": "NEGLIGIBLE",
998
+ "probabilityScore": 0.11085559,
999
+ "severity": "HARM_SEVERITY_NEGLIGIBLE",
1000
+ "severityScore": 0.19027223
1001
+ },
1002
+ {
1003
+ "category": "HARM_CATEGORY_SEXUALLY_EXPLICIT",
1004
+ "probability": "NEGLIGIBLE",
1005
+ "probabilityScore": 0.22901751,
1006
+ "severity": "HARM_SEVERITY_NEGLIGIBLE",
1007
+ "severityScore": 0.09089675
1008
+ }
1009
+ ]
1010
+ }
1011
+ ```
1012
+
1013
+ ### Troubleshooting
1014
+
1015
+ #### Schema Limitations
1016
+
1017
+ The Google Generative AI API uses a subset of the OpenAPI 3.0 schema,
1018
+ which does not support features such as unions.
1019
+ The errors that you get in this case look like this:
1020
+
1021
+ `GenerateContentRequest.generation_config.response_schema.properties[occupation].type: must be specified`
1022
+
1023
+ By default, structured outputs are enabled (and for tool calling they are required).
1024
+ You can disable structured outputs for object generation as a workaround:
1025
+
1026
+ ```ts highlight="3,8"
1027
+ const { output } = await generateText({
1028
+ model: google('gemini-2.5-flash'),
1029
+ providerOptions: {
1030
+ google: {
1031
+ structuredOutputs: false,
1032
+ } satisfies GoogleLanguageModelOptions,
1033
+ },
1034
+ output: Output.object({
1035
+ schema: z.object({
1036
+ name: z.string(),
1037
+ age: z.number(),
1038
+ contact: z.union([
1039
+ z.object({
1040
+ type: z.literal('email'),
1041
+ value: z.string(),
1042
+ }),
1043
+ z.object({
1044
+ type: z.literal('phone'),
1045
+ value: z.string(),
1046
+ }),
1047
+ ]),
1048
+ }),
1049
+ }),
1050
+ prompt: 'Generate an example person for testing.',
1051
+ });
1052
+ ```
1053
+
1054
+ The following Zod features are known to not work with Google Generative AI:
1055
+
1056
+ - `z.union`
1057
+ - `z.record`
1058
+
1059
+ ### Model Capabilities
1060
+
1061
+ | Model | Image Input | Object Generation | Tool Usage | Tool Streaming | Google Search | URL Context |
1062
+ | ------------------------------------- | ------------------- | ------------------- | ------------------- | ------------------- | ------------------- | ------------------- |
1063
+ | `gemini-3.1-pro-preview` | <Check size={18} /> | <Check size={18} /> | <Check size={18} /> | <Check size={18} /> | <Check size={18} /> | <Check size={18} /> |
1064
+ | `gemini-3.1-flash-image-preview` | <Check size={18} /> | <Check size={18} /> | <Check size={18} /> | <Check size={18} /> | <Check size={18} /> | <Check size={18} /> |
1065
+ | `gemini-3.1-flash-lite-preview` | <Check size={18} /> | <Check size={18} /> | <Check size={18} /> | <Check size={18} /> | <Check size={18} /> | <Check size={18} /> |
1066
+ | `gemini-3-pro-preview` | <Check size={18} /> | <Check size={18} /> | <Check size={18} /> | <Check size={18} /> | <Check size={18} /> | <Check size={18} /> |
1067
+ | `gemini-3-pro-image-preview` | <Check size={18} /> | <Check size={18} /> | <Check size={18} /> | <Check size={18} /> | <Check size={18} /> | <Check size={18} /> |
1068
+ | `gemini-3-flash-preview` | <Check size={18} /> | <Check size={18} /> | <Check size={18} /> | <Check size={18} /> | <Check size={18} /> | <Check size={18} /> |
1069
+ | `gemini-2.5-pro` | <Check size={18} /> | <Check size={18} /> | <Check size={18} /> | <Check size={18} /> | <Check size={18} /> | <Check size={18} /> |
1070
+ | `gemini-2.5-flash` | <Check size={18} /> | <Check size={18} /> | <Check size={18} /> | <Check size={18} /> | <Check size={18} /> | <Check size={18} /> |
1071
+ | `gemini-2.5-flash-lite` | <Check size={18} /> | <Check size={18} /> | <Check size={18} /> | <Check size={18} /> | <Check size={18} /> | <Check size={18} /> |
1072
+ | `gemini-2.5-flash-lite-preview-06-17` | <Check size={18} /> | <Check size={18} /> | <Check size={18} /> | <Check size={18} /> | <Check size={18} /> | <Check size={18} /> |
1073
+ | `gemini-2.0-flash` | <Check size={18} /> | <Check size={18} /> | <Check size={18} /> | <Check size={18} /> | <Check size={18} /> | <Check size={18} /> |
1074
+
1075
+ <Note>
1076
+ The table above lists popular models. Please see the [Google Generative AI
1077
+ docs](https://ai.google.dev/gemini-api/docs/models/) for a full list of
1078
+ available models. The table above lists popular models. You can also pass any
1079
+ available provider model ID as a string if needed.
1080
+ </Note>
1081
+
1082
+ ## Gemma Models
1083
+
1084
+ You can use [Gemma models](https://deepmind.google/models/gemma/) with the Google Generative AI API.
1085
+ The following Gemma models are available:
1086
+
1087
+ - `gemma-3-27b-it`
1088
+ - `gemma-3-12b-it`
1089
+
1090
+ Gemma models don't natively support the `systemInstruction` parameter, but the provider automatically handles system instructions by prepending them to the first user message. This allows you to use system instructions with Gemma models seamlessly:
1091
+
1092
+ ```ts
1093
+ import { google } from '@ai-sdk/google';
1094
+ import { generateText } from 'ai';
1095
+
1096
+ const { text } = await generateText({
1097
+ model: google('gemma-3-27b-it'),
1098
+ system: 'You are a helpful assistant that responds concisely.',
1099
+ prompt: 'What is machine learning?',
1100
+ });
1101
+ ```
1102
+
1103
+ The system instruction is automatically formatted and included in the conversation, so Gemma models can follow the guidance without any additional configuration.
1104
+
1105
+ ## Embedding Models
1106
+
1107
+ You can create models that call the [Google Generative AI embeddings API](https://ai.google.dev/gemini-api/docs/embeddings)
1108
+ using the `.embedding()` factory method.
1109
+
1110
+ ```ts
1111
+ const model = google.embedding('gemini-embedding-001');
1112
+ ```
1113
+
1114
+ The Google Generative AI provider sends API calls to the right endpoint based on the type of embedding:
1115
+
1116
+ - **Single embeddings**: When embedding a single value with `embed()`, the provider uses the single `:embedContent` endpoint, which typically has higher rate limits compared to the batch endpoint.
1117
+ - **Batch embeddings**: When embedding multiple values with `embedMany()` or multiple values in `embed()`, the provider uses the `:batchEmbedContents` endpoint.
1118
+
1119
+ Google Generative AI embedding models support additional settings. You can pass them as an options argument:
1120
+
1121
+ ```ts
1122
+ import { google, type GoogleEmbeddingModelOptions } from '@ai-sdk/google';
1123
+ import { embed } from 'ai';
1124
+
1125
+ const model = google.embedding('gemini-embedding-001');
1126
+
1127
+ const { embedding } = await embed({
1128
+ model,
1129
+ value: 'sunny day at the beach',
1130
+ providerOptions: {
1131
+ google: {
1132
+ outputDimensionality: 512, // optional, number of dimensions for the embedding
1133
+ taskType: 'SEMANTIC_SIMILARITY', // optional, specifies the task type for generating embeddings
1134
+ } satisfies GoogleEmbeddingModelOptions,
1135
+ },
1136
+ });
1137
+ ```
1138
+
1139
+ The following optional provider options are available for Google Generative AI embedding models:
1140
+
1141
+ - **outputDimensionality**: _number_
1142
+
1143
+ Optional reduced dimension for the output embedding. If set, excessive values in the output embedding are truncated from the end.
1144
+
1145
+ - **taskType**: _string_
1146
+
1147
+ Optional. Specifies the task type for generating embeddings. Supported task types include:
1148
+
1149
+ - `SEMANTIC_SIMILARITY`: Optimized for text similarity.
1150
+ - `CLASSIFICATION`: Optimized for text classification.
1151
+ - `CLUSTERING`: Optimized for clustering texts based on similarity.
1152
+ - `RETRIEVAL_DOCUMENT`: Optimized for document retrieval.
1153
+ - `RETRIEVAL_QUERY`: Optimized for query-based retrieval.
1154
+ - `QUESTION_ANSWERING`: Optimized for answering questions.
1155
+ - `FACT_VERIFICATION`: Optimized for verifying factual information.
1156
+ - `CODE_RETRIEVAL_QUERY`: Optimized for retrieving code blocks based on natural language queries.
1157
+
1158
+ ### Model Capabilities
1159
+
1160
+ | Model | Default Dimensions | Custom Dimensions |
1161
+ | ---------------------- | ------------------ | ------------------- |
1162
+ | `gemini-embedding-001` | 3072 | <Check size={18} /> |
1163
+
1164
+ ## Image Models
1165
+
1166
+ You can create image models that call the Google Generative AI API using the `.image()` factory method.
1167
+ For more on image generation with the AI SDK see [generateImage()](/docs/reference/ai-sdk-core/generate-image).
1168
+
1169
+ The Google provider supports two types of image models:
1170
+
1171
+ - **Imagen models**: Dedicated image generation models using the `:predict` API
1172
+ - **Gemini image models**: Multimodal language models with image output capabilities using the `:generateContent` API
1173
+
1174
+ ### Imagen Models
1175
+
1176
+ [Imagen](https://ai.google.dev/gemini-api/docs/imagen) models are dedicated image generation models.
1177
+
1178
+ ```ts
1179
+ import { google } from '@ai-sdk/google';
1180
+ import { generateImage } from 'ai';
1181
+
1182
+ const { image } = await generateImage({
1183
+ model: google.image('imagen-4.0-generate-001'),
1184
+ prompt: 'A futuristic cityscape at sunset',
1185
+ aspectRatio: '16:9',
1186
+ });
1187
+ ```
1188
+
1189
+ Further configuration can be done using Google provider options. You can validate the provider options using the `GoogleImageModelOptions` type.
1190
+
1191
+ ```ts
1192
+ import { google } from '@ai-sdk/google';
1193
+ import { GoogleImageModelOptions } from '@ai-sdk/google';
1194
+ import { generateImage } from 'ai';
1195
+
1196
+ const { image } = await generateImage({
1197
+ model: google.image('imagen-4.0-generate-001'),
1198
+ providerOptions: {
1199
+ google: {
1200
+ personGeneration: 'dont_allow',
1201
+ } satisfies GoogleImageModelOptions,
1202
+ },
1203
+ // ...
1204
+ });
1205
+ ```
1206
+
1207
+ The following provider options are available for Imagen models:
1208
+
1209
+ - **personGeneration** `allow_adult` | `allow_all` | `dont_allow`
1210
+ Whether to allow person generation. Defaults to `allow_adult`.
1211
+
1212
+ <Note>
1213
+ Imagen models do not support the `size` parameter. Use the `aspectRatio`
1214
+ parameter instead.
1215
+ </Note>
1216
+
1217
+ #### Imagen Model Capabilities
1218
+
1219
+ | Model | Aspect Ratios |
1220
+ | ------------------------------- | ------------------------- |
1221
+ | `imagen-4.0-generate-001` | 1:1, 3:4, 4:3, 9:16, 16:9 |
1222
+ | `imagen-4.0-ultra-generate-001` | 1:1, 3:4, 4:3, 9:16, 16:9 |
1223
+ | `imagen-4.0-fast-generate-001` | 1:1, 3:4, 4:3, 9:16, 16:9 |
1224
+
1225
+ ### Gemini Image Models
1226
+
1227
+ [Gemini image models](https://ai.google.dev/gemini-api/docs/image-generation) (e.g. `gemini-2.5-flash-image`) are technically multimodal output language models, but they can be used with the `generateImage()` function for a simpler image generation experience. Internally, the provider calls the language model API with `responseModalities: ['IMAGE']`.
1228
+
1229
+ ```ts
1230
+ import { google } from '@ai-sdk/google';
1231
+ import { generateImage } from 'ai';
1232
+
1233
+ const { image } = await generateImage({
1234
+ model: google.image('gemini-2.5-flash-image'),
1235
+ prompt: 'A photorealistic image of a cat wearing a wizard hat',
1236
+ aspectRatio: '1:1',
1237
+ });
1238
+ ```
1239
+
1240
+ Gemini image models also support image editing by providing input images:
1241
+
1242
+ ```ts
1243
+ import { google } from '@ai-sdk/google';
1244
+ import { generateImage } from 'ai';
1245
+ import fs from 'node:fs';
1246
+
1247
+ const sourceImage = fs.readFileSync('./cat.png');
1248
+
1249
+ const { image } = await generateImage({
1250
+ model: google.image('gemini-2.5-flash-image'),
1251
+ prompt: {
1252
+ text: 'Add a small wizard hat to this cat',
1253
+ images: [sourceImage],
1254
+ },
1255
+ });
1256
+ ```
1257
+
1258
+ You can also use URLs for input images:
1259
+
1260
+ ```ts
1261
+ import { google } from '@ai-sdk/google';
1262
+ import { generateImage } from 'ai';
1263
+
1264
+ const { image } = await generateImage({
1265
+ model: google.image('gemini-2.5-flash-image'),
1266
+ prompt: {
1267
+ text: 'Add a small wizard hat to this cat',
1268
+ images: ['https://example.com/cat.png'],
1269
+ },
1270
+ });
1271
+ ```
1272
+
1273
+ <Note>
1274
+ Gemini image models do not support the `size` or `n` parameters. Use
1275
+ `aspectRatio` instead of `size`. Mask-based inpainting is also not supported.
1276
+ </Note>
1277
+
1278
+ <Note>
1279
+ For more advanced use cases where you need both text and image outputs, or
1280
+ want more control over the generation process, you can use Gemini image models
1281
+ directly with `generateText()`. See [Image Outputs](#image-outputs) for
1282
+ details.
1283
+ </Note>
1284
+
1285
+ #### Gemini Image Model Capabilities
1286
+
1287
+ | Model | Image Generation | Image Editing | Aspect Ratios |
1288
+ | -------------------------------- | ------------------- | ------------------- | --------------------------------------------------- |
1289
+ | `gemini-2.5-flash-image` | <Check size={18} /> | <Check size={18} /> | 1:1, 2:3, 3:2, 3:4, 4:3, 4:5, 5:4, 9:16, 16:9, 21:9 |
1290
+ | `gemini-3-pro-image-preview` | <Check size={18} /> | <Check size={18} /> | 1:1, 2:3, 3:2, 3:4, 4:3, 4:5, 5:4, 9:16, 16:9, 21:9 |
1291
+ | `gemini-3.1-flash-image-preview` | <Check size={18} /> | <Check size={18} /> | 1:1, 2:3, 3:2, 3:4, 4:3, 4:5, 5:4, 9:16, 16:9, 21:9 |
1292
+
1293
+ <Note>
1294
+ `gemini-3-pro-image-preview` supports additional features including up to 14
1295
+ reference images for editing (6 objects, 5 humans), resolution options (1K,
1296
+ 2K, 4K via `providerOptions.google.imageConfig.imageSize`), and Google Search
1297
+ grounding.
1298
+ </Note>