@ai-sdk/google 0.0.0-01d6317c-20260129172110

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 (45) hide show
  1. package/CHANGELOG.md +2353 -0
  2. package/LICENSE +13 -0
  3. package/README.md +35 -0
  4. package/dist/index.d.mts +331 -0
  5. package/dist/index.d.ts +331 -0
  6. package/dist/index.js +1972 -0
  7. package/dist/index.js.map +1 -0
  8. package/dist/index.mjs +2007 -0
  9. package/dist/index.mjs.map +1 -0
  10. package/dist/internal/index.d.mts +262 -0
  11. package/dist/internal/index.d.ts +262 -0
  12. package/dist/internal/index.js +1621 -0
  13. package/dist/internal/index.js.map +1 -0
  14. package/dist/internal/index.mjs +1629 -0
  15. package/dist/internal/index.mjs.map +1 -0
  16. package/docs/15-google-generative-ai.mdx +1195 -0
  17. package/internal.d.ts +1 -0
  18. package/package.json +83 -0
  19. package/src/convert-google-generative-ai-usage.ts +51 -0
  20. package/src/convert-json-schema-to-openapi-schema.ts +158 -0
  21. package/src/convert-to-google-generative-ai-messages.ts +232 -0
  22. package/src/get-model-path.ts +3 -0
  23. package/src/google-error.ts +26 -0
  24. package/src/google-generative-ai-embedding-model.ts +159 -0
  25. package/src/google-generative-ai-embedding-options.ts +52 -0
  26. package/src/google-generative-ai-image-model.ts +184 -0
  27. package/src/google-generative-ai-image-settings.ts +12 -0
  28. package/src/google-generative-ai-language-model.ts +1009 -0
  29. package/src/google-generative-ai-options.ts +193 -0
  30. package/src/google-generative-ai-prompt.ts +38 -0
  31. package/src/google-prepare-tools.ts +264 -0
  32. package/src/google-provider.ts +201 -0
  33. package/src/google-supported-file-url.ts +20 -0
  34. package/src/google-tools.ts +71 -0
  35. package/src/index.ts +11 -0
  36. package/src/internal/index.ts +3 -0
  37. package/src/map-google-generative-ai-finish-reason.ts +29 -0
  38. package/src/tool/code-execution.ts +35 -0
  39. package/src/tool/enterprise-web-search.ts +18 -0
  40. package/src/tool/file-search.ts +51 -0
  41. package/src/tool/google-maps.ts +14 -0
  42. package/src/tool/google-search.ts +40 -0
  43. package/src/tool/url-context.ts +16 -0
  44. package/src/tool/vertex-rag-store.ts +31 -0
  45. package/src/version.ts +6 -0
package/dist/index.js ADDED
@@ -0,0 +1,1972 @@
1
+ "use strict";
2
+ var __defProp = Object.defineProperty;
3
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
4
+ var __getOwnPropNames = Object.getOwnPropertyNames;
5
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
6
+ var __export = (target, all) => {
7
+ for (var name in all)
8
+ __defProp(target, name, { get: all[name], enumerable: true });
9
+ };
10
+ var __copyProps = (to, from, except, desc) => {
11
+ if (from && typeof from === "object" || typeof from === "function") {
12
+ for (let key of __getOwnPropNames(from))
13
+ if (!__hasOwnProp.call(to, key) && key !== except)
14
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
15
+ }
16
+ return to;
17
+ };
18
+ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
19
+
20
+ // src/index.ts
21
+ var src_exports = {};
22
+ __export(src_exports, {
23
+ VERSION: () => VERSION,
24
+ createGoogleGenerativeAI: () => createGoogleGenerativeAI,
25
+ google: () => google
26
+ });
27
+ module.exports = __toCommonJS(src_exports);
28
+
29
+ // src/google-provider.ts
30
+ var import_provider_utils15 = require("@ai-sdk/provider-utils");
31
+
32
+ // src/version.ts
33
+ var VERSION = true ? "0.0.0-01d6317c-20260129172110" : "0.0.0-test";
34
+
35
+ // src/google-generative-ai-embedding-model.ts
36
+ var import_provider = require("@ai-sdk/provider");
37
+ var import_provider_utils3 = require("@ai-sdk/provider-utils");
38
+ var import_v43 = require("zod/v4");
39
+
40
+ // src/google-error.ts
41
+ var import_provider_utils = require("@ai-sdk/provider-utils");
42
+ var import_v4 = require("zod/v4");
43
+ var googleErrorDataSchema = (0, import_provider_utils.lazySchema)(
44
+ () => (0, import_provider_utils.zodSchema)(
45
+ import_v4.z.object({
46
+ error: import_v4.z.object({
47
+ code: import_v4.z.number().nullable(),
48
+ message: import_v4.z.string(),
49
+ status: import_v4.z.string()
50
+ })
51
+ })
52
+ )
53
+ );
54
+ var googleFailedResponseHandler = (0, import_provider_utils.createJsonErrorResponseHandler)({
55
+ errorSchema: googleErrorDataSchema,
56
+ errorToMessage: (data) => data.error.message
57
+ });
58
+
59
+ // src/google-generative-ai-embedding-options.ts
60
+ var import_provider_utils2 = require("@ai-sdk/provider-utils");
61
+ var import_v42 = require("zod/v4");
62
+ var googleGenerativeAIEmbeddingProviderOptions = (0, import_provider_utils2.lazySchema)(
63
+ () => (0, import_provider_utils2.zodSchema)(
64
+ import_v42.z.object({
65
+ /**
66
+ * Optional. Optional reduced dimension for the output embedding.
67
+ * If set, excessive values in the output embedding are truncated from the end.
68
+ */
69
+ outputDimensionality: import_v42.z.number().optional(),
70
+ /**
71
+ * Optional. Specifies the task type for generating embeddings.
72
+ * Supported task types:
73
+ * - SEMANTIC_SIMILARITY: Optimized for text similarity.
74
+ * - CLASSIFICATION: Optimized for text classification.
75
+ * - CLUSTERING: Optimized for clustering texts based on similarity.
76
+ * - RETRIEVAL_DOCUMENT: Optimized for document retrieval.
77
+ * - RETRIEVAL_QUERY: Optimized for query-based retrieval.
78
+ * - QUESTION_ANSWERING: Optimized for answering questions.
79
+ * - FACT_VERIFICATION: Optimized for verifying factual information.
80
+ * - CODE_RETRIEVAL_QUERY: Optimized for retrieving code blocks based on natural language queries.
81
+ */
82
+ taskType: import_v42.z.enum([
83
+ "SEMANTIC_SIMILARITY",
84
+ "CLASSIFICATION",
85
+ "CLUSTERING",
86
+ "RETRIEVAL_DOCUMENT",
87
+ "RETRIEVAL_QUERY",
88
+ "QUESTION_ANSWERING",
89
+ "FACT_VERIFICATION",
90
+ "CODE_RETRIEVAL_QUERY"
91
+ ]).optional()
92
+ })
93
+ )
94
+ );
95
+
96
+ // src/google-generative-ai-embedding-model.ts
97
+ var GoogleGenerativeAIEmbeddingModel = class {
98
+ constructor(modelId, config) {
99
+ this.specificationVersion = "v3";
100
+ this.maxEmbeddingsPerCall = 2048;
101
+ this.supportsParallelCalls = true;
102
+ this.modelId = modelId;
103
+ this.config = config;
104
+ }
105
+ get provider() {
106
+ return this.config.provider;
107
+ }
108
+ async doEmbed({
109
+ values,
110
+ headers,
111
+ abortSignal,
112
+ providerOptions
113
+ }) {
114
+ const googleOptions = await (0, import_provider_utils3.parseProviderOptions)({
115
+ provider: "google",
116
+ providerOptions,
117
+ schema: googleGenerativeAIEmbeddingProviderOptions
118
+ });
119
+ if (values.length > this.maxEmbeddingsPerCall) {
120
+ throw new import_provider.TooManyEmbeddingValuesForCallError({
121
+ provider: this.provider,
122
+ modelId: this.modelId,
123
+ maxEmbeddingsPerCall: this.maxEmbeddingsPerCall,
124
+ values
125
+ });
126
+ }
127
+ const mergedHeaders = (0, import_provider_utils3.combineHeaders)(
128
+ await (0, import_provider_utils3.resolve)(this.config.headers),
129
+ headers
130
+ );
131
+ if (values.length === 1) {
132
+ const {
133
+ responseHeaders: responseHeaders2,
134
+ value: response2,
135
+ rawValue: rawValue2
136
+ } = await (0, import_provider_utils3.postJsonToApi)({
137
+ url: `${this.config.baseURL}/models/${this.modelId}:embedContent`,
138
+ headers: mergedHeaders,
139
+ body: {
140
+ model: `models/${this.modelId}`,
141
+ content: {
142
+ parts: [{ text: values[0] }]
143
+ },
144
+ outputDimensionality: googleOptions == null ? void 0 : googleOptions.outputDimensionality,
145
+ taskType: googleOptions == null ? void 0 : googleOptions.taskType
146
+ },
147
+ failedResponseHandler: googleFailedResponseHandler,
148
+ successfulResponseHandler: (0, import_provider_utils3.createJsonResponseHandler)(
149
+ googleGenerativeAISingleEmbeddingResponseSchema
150
+ ),
151
+ abortSignal,
152
+ fetch: this.config.fetch
153
+ });
154
+ return {
155
+ warnings: [],
156
+ embeddings: [response2.embedding.values],
157
+ usage: void 0,
158
+ response: { headers: responseHeaders2, body: rawValue2 }
159
+ };
160
+ }
161
+ const {
162
+ responseHeaders,
163
+ value: response,
164
+ rawValue
165
+ } = await (0, import_provider_utils3.postJsonToApi)({
166
+ url: `${this.config.baseURL}/models/${this.modelId}:batchEmbedContents`,
167
+ headers: mergedHeaders,
168
+ body: {
169
+ requests: values.map((value) => ({
170
+ model: `models/${this.modelId}`,
171
+ content: { role: "user", parts: [{ text: value }] },
172
+ outputDimensionality: googleOptions == null ? void 0 : googleOptions.outputDimensionality,
173
+ taskType: googleOptions == null ? void 0 : googleOptions.taskType
174
+ }))
175
+ },
176
+ failedResponseHandler: googleFailedResponseHandler,
177
+ successfulResponseHandler: (0, import_provider_utils3.createJsonResponseHandler)(
178
+ googleGenerativeAITextEmbeddingResponseSchema
179
+ ),
180
+ abortSignal,
181
+ fetch: this.config.fetch
182
+ });
183
+ return {
184
+ warnings: [],
185
+ embeddings: response.embeddings.map((item) => item.values),
186
+ usage: void 0,
187
+ response: { headers: responseHeaders, body: rawValue }
188
+ };
189
+ }
190
+ };
191
+ var googleGenerativeAITextEmbeddingResponseSchema = (0, import_provider_utils3.lazySchema)(
192
+ () => (0, import_provider_utils3.zodSchema)(
193
+ import_v43.z.object({
194
+ embeddings: import_v43.z.array(import_v43.z.object({ values: import_v43.z.array(import_v43.z.number()) }))
195
+ })
196
+ )
197
+ );
198
+ var googleGenerativeAISingleEmbeddingResponseSchema = (0, import_provider_utils3.lazySchema)(
199
+ () => (0, import_provider_utils3.zodSchema)(
200
+ import_v43.z.object({
201
+ embedding: import_v43.z.object({ values: import_v43.z.array(import_v43.z.number()) })
202
+ })
203
+ )
204
+ );
205
+
206
+ // src/google-generative-ai-language-model.ts
207
+ var import_provider_utils6 = require("@ai-sdk/provider-utils");
208
+ var import_v45 = require("zod/v4");
209
+
210
+ // src/convert-google-generative-ai-usage.ts
211
+ function convertGoogleGenerativeAIUsage(usage) {
212
+ var _a, _b, _c, _d;
213
+ if (usage == null) {
214
+ return {
215
+ inputTokens: {
216
+ total: void 0,
217
+ noCache: void 0,
218
+ cacheRead: void 0,
219
+ cacheWrite: void 0
220
+ },
221
+ outputTokens: {
222
+ total: void 0,
223
+ text: void 0,
224
+ reasoning: void 0
225
+ },
226
+ raw: void 0
227
+ };
228
+ }
229
+ const promptTokens = (_a = usage.promptTokenCount) != null ? _a : 0;
230
+ const candidatesTokens = (_b = usage.candidatesTokenCount) != null ? _b : 0;
231
+ const cachedContentTokens = (_c = usage.cachedContentTokenCount) != null ? _c : 0;
232
+ const thoughtsTokens = (_d = usage.thoughtsTokenCount) != null ? _d : 0;
233
+ return {
234
+ inputTokens: {
235
+ total: promptTokens,
236
+ noCache: promptTokens - cachedContentTokens,
237
+ cacheRead: cachedContentTokens,
238
+ cacheWrite: void 0
239
+ },
240
+ outputTokens: {
241
+ total: candidatesTokens + thoughtsTokens,
242
+ text: candidatesTokens,
243
+ reasoning: thoughtsTokens
244
+ },
245
+ raw: usage
246
+ };
247
+ }
248
+
249
+ // src/convert-json-schema-to-openapi-schema.ts
250
+ function convertJSONSchemaToOpenAPISchema(jsonSchema, isRoot = true) {
251
+ if (jsonSchema == null) {
252
+ return void 0;
253
+ }
254
+ if (isEmptyObjectSchema(jsonSchema)) {
255
+ if (isRoot) {
256
+ return void 0;
257
+ }
258
+ if (typeof jsonSchema === "object" && jsonSchema.description) {
259
+ return { type: "object", description: jsonSchema.description };
260
+ }
261
+ return { type: "object" };
262
+ }
263
+ if (typeof jsonSchema === "boolean") {
264
+ return { type: "boolean", properties: {} };
265
+ }
266
+ const {
267
+ type,
268
+ description,
269
+ required,
270
+ properties,
271
+ items,
272
+ allOf,
273
+ anyOf,
274
+ oneOf,
275
+ format,
276
+ const: constValue,
277
+ minLength,
278
+ enum: enumValues
279
+ } = jsonSchema;
280
+ const result = {};
281
+ if (description) result.description = description;
282
+ if (required) result.required = required;
283
+ if (format) result.format = format;
284
+ if (constValue !== void 0) {
285
+ result.enum = [constValue];
286
+ }
287
+ if (type) {
288
+ if (Array.isArray(type)) {
289
+ const hasNull = type.includes("null");
290
+ const nonNullTypes = type.filter((t) => t !== "null");
291
+ if (nonNullTypes.length === 0) {
292
+ result.type = "null";
293
+ } else {
294
+ result.anyOf = nonNullTypes.map((t) => ({ type: t }));
295
+ if (hasNull) {
296
+ result.nullable = true;
297
+ }
298
+ }
299
+ } else {
300
+ result.type = type;
301
+ }
302
+ }
303
+ if (enumValues !== void 0) {
304
+ result.enum = enumValues;
305
+ }
306
+ if (properties != null) {
307
+ result.properties = Object.entries(properties).reduce(
308
+ (acc, [key, value]) => {
309
+ acc[key] = convertJSONSchemaToOpenAPISchema(value, false);
310
+ return acc;
311
+ },
312
+ {}
313
+ );
314
+ }
315
+ if (items) {
316
+ result.items = Array.isArray(items) ? items.map((item) => convertJSONSchemaToOpenAPISchema(item, false)) : convertJSONSchemaToOpenAPISchema(items, false);
317
+ }
318
+ if (allOf) {
319
+ result.allOf = allOf.map(
320
+ (item) => convertJSONSchemaToOpenAPISchema(item, false)
321
+ );
322
+ }
323
+ if (anyOf) {
324
+ if (anyOf.some(
325
+ (schema) => typeof schema === "object" && (schema == null ? void 0 : schema.type) === "null"
326
+ )) {
327
+ const nonNullSchemas = anyOf.filter(
328
+ (schema) => !(typeof schema === "object" && (schema == null ? void 0 : schema.type) === "null")
329
+ );
330
+ if (nonNullSchemas.length === 1) {
331
+ const converted = convertJSONSchemaToOpenAPISchema(
332
+ nonNullSchemas[0],
333
+ false
334
+ );
335
+ if (typeof converted === "object") {
336
+ result.nullable = true;
337
+ Object.assign(result, converted);
338
+ }
339
+ } else {
340
+ result.anyOf = nonNullSchemas.map(
341
+ (item) => convertJSONSchemaToOpenAPISchema(item, false)
342
+ );
343
+ result.nullable = true;
344
+ }
345
+ } else {
346
+ result.anyOf = anyOf.map(
347
+ (item) => convertJSONSchemaToOpenAPISchema(item, false)
348
+ );
349
+ }
350
+ }
351
+ if (oneOf) {
352
+ result.oneOf = oneOf.map(
353
+ (item) => convertJSONSchemaToOpenAPISchema(item, false)
354
+ );
355
+ }
356
+ if (minLength !== void 0) {
357
+ result.minLength = minLength;
358
+ }
359
+ return result;
360
+ }
361
+ function isEmptyObjectSchema(jsonSchema) {
362
+ return jsonSchema != null && typeof jsonSchema === "object" && jsonSchema.type === "object" && (jsonSchema.properties == null || Object.keys(jsonSchema.properties).length === 0) && !jsonSchema.additionalProperties;
363
+ }
364
+
365
+ // src/convert-to-google-generative-ai-messages.ts
366
+ var import_provider2 = require("@ai-sdk/provider");
367
+ var import_provider_utils4 = require("@ai-sdk/provider-utils");
368
+ function convertToGoogleGenerativeAIMessages(prompt, options) {
369
+ var _a, _b, _c;
370
+ const systemInstructionParts = [];
371
+ const contents = [];
372
+ let systemMessagesAllowed = true;
373
+ const isGemmaModel = (_a = options == null ? void 0 : options.isGemmaModel) != null ? _a : false;
374
+ const providerOptionsName = (_b = options == null ? void 0 : options.providerOptionsName) != null ? _b : "google";
375
+ for (const { role, content } of prompt) {
376
+ switch (role) {
377
+ case "system": {
378
+ if (!systemMessagesAllowed) {
379
+ throw new import_provider2.UnsupportedFunctionalityError({
380
+ functionality: "system messages are only supported at the beginning of the conversation"
381
+ });
382
+ }
383
+ systemInstructionParts.push({ text: content });
384
+ break;
385
+ }
386
+ case "user": {
387
+ systemMessagesAllowed = false;
388
+ const parts = [];
389
+ for (const part of content) {
390
+ switch (part.type) {
391
+ case "text": {
392
+ parts.push({ text: part.text });
393
+ break;
394
+ }
395
+ case "file": {
396
+ const mediaType = part.mediaType === "image/*" ? "image/jpeg" : part.mediaType;
397
+ parts.push(
398
+ part.data instanceof URL ? {
399
+ fileData: {
400
+ mimeType: mediaType,
401
+ fileUri: part.data.toString()
402
+ }
403
+ } : {
404
+ inlineData: {
405
+ mimeType: mediaType,
406
+ data: (0, import_provider_utils4.convertToBase64)(part.data)
407
+ }
408
+ }
409
+ );
410
+ break;
411
+ }
412
+ }
413
+ }
414
+ contents.push({ role: "user", parts });
415
+ break;
416
+ }
417
+ case "assistant": {
418
+ systemMessagesAllowed = false;
419
+ contents.push({
420
+ role: "model",
421
+ parts: content.map((part) => {
422
+ var _a2;
423
+ const providerOpts = (_a2 = part.providerOptions) == null ? void 0 : _a2[providerOptionsName];
424
+ const thoughtSignature = (providerOpts == null ? void 0 : providerOpts.thoughtSignature) != null ? String(providerOpts.thoughtSignature) : void 0;
425
+ switch (part.type) {
426
+ case "text": {
427
+ return part.text.length === 0 ? void 0 : {
428
+ text: part.text,
429
+ thoughtSignature
430
+ };
431
+ }
432
+ case "reasoning": {
433
+ return part.text.length === 0 ? void 0 : {
434
+ text: part.text,
435
+ thought: true,
436
+ thoughtSignature
437
+ };
438
+ }
439
+ case "file": {
440
+ if (part.data instanceof URL) {
441
+ throw new import_provider2.UnsupportedFunctionalityError({
442
+ functionality: "File data URLs in assistant messages are not supported"
443
+ });
444
+ }
445
+ return {
446
+ inlineData: {
447
+ mimeType: part.mediaType,
448
+ data: (0, import_provider_utils4.convertToBase64)(part.data)
449
+ },
450
+ thoughtSignature
451
+ };
452
+ }
453
+ case "tool-call": {
454
+ return {
455
+ functionCall: {
456
+ name: part.toolName,
457
+ args: part.input
458
+ },
459
+ thoughtSignature
460
+ };
461
+ }
462
+ }
463
+ }).filter((part) => part !== void 0)
464
+ });
465
+ break;
466
+ }
467
+ case "tool": {
468
+ systemMessagesAllowed = false;
469
+ const parts = [];
470
+ for (const part of content) {
471
+ if (part.type === "tool-approval-response") {
472
+ continue;
473
+ }
474
+ const output = part.output;
475
+ if (output.type === "content") {
476
+ for (const contentPart of output.value) {
477
+ switch (contentPart.type) {
478
+ case "text":
479
+ parts.push({
480
+ functionResponse: {
481
+ name: part.toolName,
482
+ response: {
483
+ name: part.toolName,
484
+ content: contentPart.text
485
+ }
486
+ }
487
+ });
488
+ break;
489
+ case "image-data":
490
+ parts.push(
491
+ {
492
+ inlineData: {
493
+ mimeType: contentPart.mediaType,
494
+ data: contentPart.data
495
+ }
496
+ },
497
+ {
498
+ text: "Tool executed successfully and returned this image as a response"
499
+ }
500
+ );
501
+ break;
502
+ default:
503
+ parts.push({ text: JSON.stringify(contentPart) });
504
+ break;
505
+ }
506
+ }
507
+ } else {
508
+ parts.push({
509
+ functionResponse: {
510
+ name: part.toolName,
511
+ response: {
512
+ name: part.toolName,
513
+ content: output.type === "execution-denied" ? (_c = output.reason) != null ? _c : "Tool execution denied." : output.value
514
+ }
515
+ }
516
+ });
517
+ }
518
+ }
519
+ contents.push({
520
+ role: "user",
521
+ parts
522
+ });
523
+ break;
524
+ }
525
+ }
526
+ }
527
+ if (isGemmaModel && systemInstructionParts.length > 0 && contents.length > 0 && contents[0].role === "user") {
528
+ const systemText = systemInstructionParts.map((part) => part.text).join("\n\n");
529
+ contents[0].parts.unshift({ text: systemText + "\n\n" });
530
+ }
531
+ return {
532
+ systemInstruction: systemInstructionParts.length > 0 && !isGemmaModel ? { parts: systemInstructionParts } : void 0,
533
+ contents
534
+ };
535
+ }
536
+
537
+ // src/get-model-path.ts
538
+ function getModelPath(modelId) {
539
+ return modelId.includes("/") ? modelId : `models/${modelId}`;
540
+ }
541
+
542
+ // src/google-generative-ai-options.ts
543
+ var import_provider_utils5 = require("@ai-sdk/provider-utils");
544
+ var import_v44 = require("zod/v4");
545
+ var googleGenerativeAIProviderOptions = (0, import_provider_utils5.lazySchema)(
546
+ () => (0, import_provider_utils5.zodSchema)(
547
+ import_v44.z.object({
548
+ responseModalities: import_v44.z.array(import_v44.z.enum(["TEXT", "IMAGE"])).optional(),
549
+ thinkingConfig: import_v44.z.object({
550
+ thinkingBudget: import_v44.z.number().optional(),
551
+ includeThoughts: import_v44.z.boolean().optional(),
552
+ // https://ai.google.dev/gemini-api/docs/gemini-3?thinking=high#thinking_level
553
+ thinkingLevel: import_v44.z.enum(["minimal", "low", "medium", "high"]).optional()
554
+ }).optional(),
555
+ /**
556
+ * Optional.
557
+ * The name of the cached content used as context to serve the prediction.
558
+ * Format: cachedContents/{cachedContent}
559
+ */
560
+ cachedContent: import_v44.z.string().optional(),
561
+ /**
562
+ * Optional. Enable structured output. Default is true.
563
+ *
564
+ * This is useful when the JSON Schema contains elements that are
565
+ * not supported by the OpenAPI schema version that
566
+ * Google Generative AI uses. You can use this to disable
567
+ * structured outputs if you need to.
568
+ */
569
+ structuredOutputs: import_v44.z.boolean().optional(),
570
+ /**
571
+ * Optional. A list of unique safety settings for blocking unsafe content.
572
+ */
573
+ safetySettings: import_v44.z.array(
574
+ import_v44.z.object({
575
+ category: import_v44.z.enum([
576
+ "HARM_CATEGORY_UNSPECIFIED",
577
+ "HARM_CATEGORY_HATE_SPEECH",
578
+ "HARM_CATEGORY_DANGEROUS_CONTENT",
579
+ "HARM_CATEGORY_HARASSMENT",
580
+ "HARM_CATEGORY_SEXUALLY_EXPLICIT",
581
+ "HARM_CATEGORY_CIVIC_INTEGRITY"
582
+ ]),
583
+ threshold: import_v44.z.enum([
584
+ "HARM_BLOCK_THRESHOLD_UNSPECIFIED",
585
+ "BLOCK_LOW_AND_ABOVE",
586
+ "BLOCK_MEDIUM_AND_ABOVE",
587
+ "BLOCK_ONLY_HIGH",
588
+ "BLOCK_NONE",
589
+ "OFF"
590
+ ])
591
+ })
592
+ ).optional(),
593
+ threshold: import_v44.z.enum([
594
+ "HARM_BLOCK_THRESHOLD_UNSPECIFIED",
595
+ "BLOCK_LOW_AND_ABOVE",
596
+ "BLOCK_MEDIUM_AND_ABOVE",
597
+ "BLOCK_ONLY_HIGH",
598
+ "BLOCK_NONE",
599
+ "OFF"
600
+ ]).optional(),
601
+ /**
602
+ * Optional. Enables timestamp understanding for audio-only files.
603
+ *
604
+ * https://cloud.google.com/vertex-ai/generative-ai/docs/multimodal/audio-understanding
605
+ */
606
+ audioTimestamp: import_v44.z.boolean().optional(),
607
+ /**
608
+ * Optional. Defines labels used in billing reports. Available on Vertex AI only.
609
+ *
610
+ * https://cloud.google.com/vertex-ai/generative-ai/docs/multimodal/add-labels-to-api-calls
611
+ */
612
+ labels: import_v44.z.record(import_v44.z.string(), import_v44.z.string()).optional(),
613
+ /**
614
+ * Optional. If specified, the media resolution specified will be used.
615
+ *
616
+ * https://ai.google.dev/api/generate-content#MediaResolution
617
+ */
618
+ mediaResolution: import_v44.z.enum([
619
+ "MEDIA_RESOLUTION_UNSPECIFIED",
620
+ "MEDIA_RESOLUTION_LOW",
621
+ "MEDIA_RESOLUTION_MEDIUM",
622
+ "MEDIA_RESOLUTION_HIGH"
623
+ ]).optional(),
624
+ /**
625
+ * Optional. Configures the image generation aspect ratio for Gemini models.
626
+ *
627
+ * https://ai.google.dev/gemini-api/docs/image-generation#aspect_ratios
628
+ */
629
+ imageConfig: import_v44.z.object({
630
+ aspectRatio: import_v44.z.enum([
631
+ "1:1",
632
+ "2:3",
633
+ "3:2",
634
+ "3:4",
635
+ "4:3",
636
+ "4:5",
637
+ "5:4",
638
+ "9:16",
639
+ "16:9",
640
+ "21:9"
641
+ ]).optional(),
642
+ imageSize: import_v44.z.enum(["1K", "2K", "4K"]).optional()
643
+ }).optional(),
644
+ /**
645
+ * Optional. Configuration for grounding retrieval.
646
+ * Used to provide location context for Google Maps and Google Search grounding.
647
+ *
648
+ * https://cloud.google.com/vertex-ai/generative-ai/docs/grounding/grounding-with-google-maps
649
+ */
650
+ retrievalConfig: import_v44.z.object({
651
+ latLng: import_v44.z.object({
652
+ latitude: import_v44.z.number(),
653
+ longitude: import_v44.z.number()
654
+ }).optional()
655
+ }).optional()
656
+ })
657
+ )
658
+ );
659
+
660
+ // src/google-prepare-tools.ts
661
+ var import_provider3 = require("@ai-sdk/provider");
662
+ function prepareTools({
663
+ tools,
664
+ toolChoice,
665
+ modelId
666
+ }) {
667
+ var _a;
668
+ tools = (tools == null ? void 0 : tools.length) ? tools : void 0;
669
+ const toolWarnings = [];
670
+ const isLatest = [
671
+ "gemini-flash-latest",
672
+ "gemini-flash-lite-latest",
673
+ "gemini-pro-latest"
674
+ ].some((id) => id === modelId);
675
+ const isGemini2orNewer = modelId.includes("gemini-2") || modelId.includes("gemini-3") || isLatest;
676
+ const supportsDynamicRetrieval = modelId.includes("gemini-1.5-flash") && !modelId.includes("-8b");
677
+ const supportsFileSearch = modelId.includes("gemini-2.5") || modelId.includes("gemini-3");
678
+ if (tools == null) {
679
+ return { tools: void 0, toolConfig: void 0, toolWarnings };
680
+ }
681
+ const hasFunctionTools = tools.some((tool) => tool.type === "function");
682
+ const hasProviderTools = tools.some((tool) => tool.type === "provider");
683
+ if (hasFunctionTools && hasProviderTools) {
684
+ toolWarnings.push({
685
+ type: "unsupported",
686
+ feature: `combination of function and provider-defined tools`
687
+ });
688
+ }
689
+ if (hasProviderTools) {
690
+ const googleTools2 = [];
691
+ const ProviderTools = tools.filter((tool) => tool.type === "provider");
692
+ ProviderTools.forEach((tool) => {
693
+ switch (tool.id) {
694
+ case "google.google_search":
695
+ if (isGemini2orNewer) {
696
+ googleTools2.push({ googleSearch: {} });
697
+ } else if (supportsDynamicRetrieval) {
698
+ googleTools2.push({
699
+ googleSearchRetrieval: {
700
+ dynamicRetrievalConfig: {
701
+ mode: tool.args.mode,
702
+ dynamicThreshold: tool.args.dynamicThreshold
703
+ }
704
+ }
705
+ });
706
+ } else {
707
+ googleTools2.push({ googleSearchRetrieval: {} });
708
+ }
709
+ break;
710
+ case "google.enterprise_web_search":
711
+ if (isGemini2orNewer) {
712
+ googleTools2.push({ enterpriseWebSearch: {} });
713
+ } else {
714
+ toolWarnings.push({
715
+ type: "unsupported",
716
+ feature: `provider-defined tool ${tool.id}`,
717
+ details: "Enterprise Web Search requires Gemini 2.0 or newer."
718
+ });
719
+ }
720
+ break;
721
+ case "google.url_context":
722
+ if (isGemini2orNewer) {
723
+ googleTools2.push({ urlContext: {} });
724
+ } else {
725
+ toolWarnings.push({
726
+ type: "unsupported",
727
+ feature: `provider-defined tool ${tool.id}`,
728
+ details: "The URL context tool is not supported with other Gemini models than Gemini 2."
729
+ });
730
+ }
731
+ break;
732
+ case "google.code_execution":
733
+ if (isGemini2orNewer) {
734
+ googleTools2.push({ codeExecution: {} });
735
+ } else {
736
+ toolWarnings.push({
737
+ type: "unsupported",
738
+ feature: `provider-defined tool ${tool.id}`,
739
+ details: "The code execution tools is not supported with other Gemini models than Gemini 2."
740
+ });
741
+ }
742
+ break;
743
+ case "google.file_search":
744
+ if (supportsFileSearch) {
745
+ googleTools2.push({ fileSearch: { ...tool.args } });
746
+ } else {
747
+ toolWarnings.push({
748
+ type: "unsupported",
749
+ feature: `provider-defined tool ${tool.id}`,
750
+ details: "The file search tool is only supported with Gemini 2.5 models and Gemini 3 models."
751
+ });
752
+ }
753
+ break;
754
+ case "google.vertex_rag_store":
755
+ if (isGemini2orNewer) {
756
+ googleTools2.push({
757
+ retrieval: {
758
+ vertex_rag_store: {
759
+ rag_resources: {
760
+ rag_corpus: tool.args.ragCorpus
761
+ },
762
+ similarity_top_k: tool.args.topK
763
+ }
764
+ }
765
+ });
766
+ } else {
767
+ toolWarnings.push({
768
+ type: "unsupported",
769
+ feature: `provider-defined tool ${tool.id}`,
770
+ details: "The RAG store tool is not supported with other Gemini models than Gemini 2."
771
+ });
772
+ }
773
+ break;
774
+ case "google.google_maps":
775
+ if (isGemini2orNewer) {
776
+ googleTools2.push({ googleMaps: {} });
777
+ } else {
778
+ toolWarnings.push({
779
+ type: "unsupported",
780
+ feature: `provider-defined tool ${tool.id}`,
781
+ details: "The Google Maps grounding tool is not supported with Gemini models other than Gemini 2 or newer."
782
+ });
783
+ }
784
+ break;
785
+ default:
786
+ toolWarnings.push({
787
+ type: "unsupported",
788
+ feature: `provider-defined tool ${tool.id}`
789
+ });
790
+ break;
791
+ }
792
+ });
793
+ return {
794
+ tools: googleTools2.length > 0 ? googleTools2 : void 0,
795
+ toolConfig: void 0,
796
+ toolWarnings
797
+ };
798
+ }
799
+ const functionDeclarations = [];
800
+ for (const tool of tools) {
801
+ switch (tool.type) {
802
+ case "function":
803
+ functionDeclarations.push({
804
+ name: tool.name,
805
+ description: (_a = tool.description) != null ? _a : "",
806
+ parameters: convertJSONSchemaToOpenAPISchema(tool.inputSchema)
807
+ });
808
+ break;
809
+ default:
810
+ toolWarnings.push({
811
+ type: "unsupported",
812
+ feature: `function tool ${tool.name}`
813
+ });
814
+ break;
815
+ }
816
+ }
817
+ if (toolChoice == null) {
818
+ return {
819
+ tools: [{ functionDeclarations }],
820
+ toolConfig: void 0,
821
+ toolWarnings
822
+ };
823
+ }
824
+ const type = toolChoice.type;
825
+ switch (type) {
826
+ case "auto":
827
+ return {
828
+ tools: [{ functionDeclarations }],
829
+ toolConfig: { functionCallingConfig: { mode: "AUTO" } },
830
+ toolWarnings
831
+ };
832
+ case "none":
833
+ return {
834
+ tools: [{ functionDeclarations }],
835
+ toolConfig: { functionCallingConfig: { mode: "NONE" } },
836
+ toolWarnings
837
+ };
838
+ case "required":
839
+ return {
840
+ tools: [{ functionDeclarations }],
841
+ toolConfig: { functionCallingConfig: { mode: "ANY" } },
842
+ toolWarnings
843
+ };
844
+ case "tool":
845
+ return {
846
+ tools: [{ functionDeclarations }],
847
+ toolConfig: {
848
+ functionCallingConfig: {
849
+ mode: "ANY",
850
+ allowedFunctionNames: [toolChoice.toolName]
851
+ }
852
+ },
853
+ toolWarnings
854
+ };
855
+ default: {
856
+ const _exhaustiveCheck = type;
857
+ throw new import_provider3.UnsupportedFunctionalityError({
858
+ functionality: `tool choice type: ${_exhaustiveCheck}`
859
+ });
860
+ }
861
+ }
862
+ }
863
+
864
+ // src/map-google-generative-ai-finish-reason.ts
865
+ function mapGoogleGenerativeAIFinishReason({
866
+ finishReason,
867
+ hasToolCalls
868
+ }) {
869
+ switch (finishReason) {
870
+ case "STOP":
871
+ return hasToolCalls ? "tool-calls" : "stop";
872
+ case "MAX_TOKENS":
873
+ return "length";
874
+ case "IMAGE_SAFETY":
875
+ case "RECITATION":
876
+ case "SAFETY":
877
+ case "BLOCKLIST":
878
+ case "PROHIBITED_CONTENT":
879
+ case "SPII":
880
+ return "content-filter";
881
+ case "MALFORMED_FUNCTION_CALL":
882
+ return "error";
883
+ case "FINISH_REASON_UNSPECIFIED":
884
+ case "OTHER":
885
+ default:
886
+ return "other";
887
+ }
888
+ }
889
+
890
+ // src/google-generative-ai-language-model.ts
891
+ var GoogleGenerativeAILanguageModel = class {
892
+ constructor(modelId, config) {
893
+ this.specificationVersion = "v3";
894
+ var _a;
895
+ this.modelId = modelId;
896
+ this.config = config;
897
+ this.generateId = (_a = config.generateId) != null ? _a : import_provider_utils6.generateId;
898
+ }
899
+ get provider() {
900
+ return this.config.provider;
901
+ }
902
+ get supportedUrls() {
903
+ var _a, _b, _c;
904
+ return (_c = (_b = (_a = this.config).supportedUrls) == null ? void 0 : _b.call(_a)) != null ? _c : {};
905
+ }
906
+ async getArgs({
907
+ prompt,
908
+ maxOutputTokens,
909
+ temperature,
910
+ topP,
911
+ topK,
912
+ frequencyPenalty,
913
+ presencePenalty,
914
+ stopSequences,
915
+ responseFormat,
916
+ seed,
917
+ tools,
918
+ toolChoice,
919
+ providerOptions
920
+ }) {
921
+ var _a;
922
+ const warnings = [];
923
+ const providerOptionsName = this.config.provider.includes("vertex") ? "vertex" : "google";
924
+ let googleOptions = await (0, import_provider_utils6.parseProviderOptions)({
925
+ provider: providerOptionsName,
926
+ providerOptions,
927
+ schema: googleGenerativeAIProviderOptions
928
+ });
929
+ if (googleOptions == null && providerOptionsName !== "google") {
930
+ googleOptions = await (0, import_provider_utils6.parseProviderOptions)({
931
+ provider: "google",
932
+ providerOptions,
933
+ schema: googleGenerativeAIProviderOptions
934
+ });
935
+ }
936
+ if ((tools == null ? void 0 : tools.some(
937
+ (tool) => tool.type === "provider" && tool.id === "google.vertex_rag_store"
938
+ )) && !this.config.provider.startsWith("google.vertex.")) {
939
+ warnings.push({
940
+ type: "other",
941
+ message: `The 'vertex_rag_store' tool is only supported with the Google Vertex provider and might not be supported or could behave unexpectedly with the current Google provider (${this.config.provider}).`
942
+ });
943
+ }
944
+ const isGemmaModel = this.modelId.toLowerCase().startsWith("gemma-");
945
+ const { contents, systemInstruction } = convertToGoogleGenerativeAIMessages(
946
+ prompt,
947
+ { isGemmaModel, providerOptionsName }
948
+ );
949
+ const {
950
+ tools: googleTools2,
951
+ toolConfig: googleToolConfig,
952
+ toolWarnings
953
+ } = prepareTools({
954
+ tools,
955
+ toolChoice,
956
+ modelId: this.modelId
957
+ });
958
+ return {
959
+ args: {
960
+ generationConfig: {
961
+ // standardized settings:
962
+ maxOutputTokens,
963
+ temperature,
964
+ topK,
965
+ topP,
966
+ frequencyPenalty,
967
+ presencePenalty,
968
+ stopSequences,
969
+ seed,
970
+ // response format:
971
+ responseMimeType: (responseFormat == null ? void 0 : responseFormat.type) === "json" ? "application/json" : void 0,
972
+ responseSchema: (responseFormat == null ? void 0 : responseFormat.type) === "json" && responseFormat.schema != null && // Google GenAI does not support all OpenAPI Schema features,
973
+ // so this is needed as an escape hatch:
974
+ // TODO convert into provider option
975
+ ((_a = googleOptions == null ? void 0 : googleOptions.structuredOutputs) != null ? _a : true) ? convertJSONSchemaToOpenAPISchema(responseFormat.schema) : void 0,
976
+ ...(googleOptions == null ? void 0 : googleOptions.audioTimestamp) && {
977
+ audioTimestamp: googleOptions.audioTimestamp
978
+ },
979
+ // provider options:
980
+ responseModalities: googleOptions == null ? void 0 : googleOptions.responseModalities,
981
+ thinkingConfig: googleOptions == null ? void 0 : googleOptions.thinkingConfig,
982
+ ...(googleOptions == null ? void 0 : googleOptions.mediaResolution) && {
983
+ mediaResolution: googleOptions.mediaResolution
984
+ },
985
+ ...(googleOptions == null ? void 0 : googleOptions.imageConfig) && {
986
+ imageConfig: googleOptions.imageConfig
987
+ }
988
+ },
989
+ contents,
990
+ systemInstruction: isGemmaModel ? void 0 : systemInstruction,
991
+ safetySettings: googleOptions == null ? void 0 : googleOptions.safetySettings,
992
+ tools: googleTools2,
993
+ toolConfig: (googleOptions == null ? void 0 : googleOptions.retrievalConfig) ? {
994
+ ...googleToolConfig,
995
+ retrievalConfig: googleOptions.retrievalConfig
996
+ } : googleToolConfig,
997
+ cachedContent: googleOptions == null ? void 0 : googleOptions.cachedContent,
998
+ labels: googleOptions == null ? void 0 : googleOptions.labels
999
+ },
1000
+ warnings: [...warnings, ...toolWarnings],
1001
+ providerOptionsName
1002
+ };
1003
+ }
1004
+ async doGenerate(options) {
1005
+ var _a, _b, _c, _d, _e, _f, _g, _h, _i;
1006
+ const { args, warnings, providerOptionsName } = await this.getArgs(options);
1007
+ const mergedHeaders = (0, import_provider_utils6.combineHeaders)(
1008
+ await (0, import_provider_utils6.resolve)(this.config.headers),
1009
+ options.headers
1010
+ );
1011
+ const {
1012
+ responseHeaders,
1013
+ value: response,
1014
+ rawValue: rawResponse
1015
+ } = await (0, import_provider_utils6.postJsonToApi)({
1016
+ url: `${this.config.baseURL}/${getModelPath(
1017
+ this.modelId
1018
+ )}:generateContent`,
1019
+ headers: mergedHeaders,
1020
+ body: args,
1021
+ failedResponseHandler: googleFailedResponseHandler,
1022
+ successfulResponseHandler: (0, import_provider_utils6.createJsonResponseHandler)(responseSchema),
1023
+ abortSignal: options.abortSignal,
1024
+ fetch: this.config.fetch
1025
+ });
1026
+ const candidate = response.candidates[0];
1027
+ const content = [];
1028
+ const parts = (_b = (_a = candidate.content) == null ? void 0 : _a.parts) != null ? _b : [];
1029
+ const usageMetadata = response.usageMetadata;
1030
+ let lastCodeExecutionToolCallId;
1031
+ for (const part of parts) {
1032
+ if ("executableCode" in part && ((_c = part.executableCode) == null ? void 0 : _c.code)) {
1033
+ const toolCallId = this.config.generateId();
1034
+ lastCodeExecutionToolCallId = toolCallId;
1035
+ content.push({
1036
+ type: "tool-call",
1037
+ toolCallId,
1038
+ toolName: "code_execution",
1039
+ input: JSON.stringify(part.executableCode),
1040
+ providerExecuted: true
1041
+ });
1042
+ } else if ("codeExecutionResult" in part && part.codeExecutionResult) {
1043
+ content.push({
1044
+ type: "tool-result",
1045
+ // Assumes a result directly follows its corresponding call part.
1046
+ toolCallId: lastCodeExecutionToolCallId,
1047
+ toolName: "code_execution",
1048
+ result: {
1049
+ outcome: part.codeExecutionResult.outcome,
1050
+ output: part.codeExecutionResult.output
1051
+ }
1052
+ });
1053
+ lastCodeExecutionToolCallId = void 0;
1054
+ } else if ("text" in part && part.text != null && part.text.length > 0) {
1055
+ content.push({
1056
+ type: part.thought === true ? "reasoning" : "text",
1057
+ text: part.text,
1058
+ providerMetadata: part.thoughtSignature ? {
1059
+ [providerOptionsName]: {
1060
+ thoughtSignature: part.thoughtSignature
1061
+ }
1062
+ } : void 0
1063
+ });
1064
+ } else if ("functionCall" in part) {
1065
+ content.push({
1066
+ type: "tool-call",
1067
+ toolCallId: this.config.generateId(),
1068
+ toolName: part.functionCall.name,
1069
+ input: JSON.stringify(part.functionCall.args),
1070
+ providerMetadata: part.thoughtSignature ? {
1071
+ [providerOptionsName]: {
1072
+ thoughtSignature: part.thoughtSignature
1073
+ }
1074
+ } : void 0
1075
+ });
1076
+ } else if ("inlineData" in part) {
1077
+ content.push({
1078
+ type: "file",
1079
+ data: part.inlineData.data,
1080
+ mediaType: part.inlineData.mimeType,
1081
+ providerMetadata: part.thoughtSignature ? {
1082
+ [providerOptionsName]: {
1083
+ thoughtSignature: part.thoughtSignature
1084
+ }
1085
+ } : void 0
1086
+ });
1087
+ }
1088
+ }
1089
+ const sources = (_d = extractSources({
1090
+ groundingMetadata: candidate.groundingMetadata,
1091
+ generateId: this.config.generateId
1092
+ })) != null ? _d : [];
1093
+ for (const source of sources) {
1094
+ content.push(source);
1095
+ }
1096
+ return {
1097
+ content,
1098
+ finishReason: {
1099
+ unified: mapGoogleGenerativeAIFinishReason({
1100
+ finishReason: candidate.finishReason,
1101
+ // Only count client-executed tool calls for finish reason determination.
1102
+ hasToolCalls: content.some(
1103
+ (part) => part.type === "tool-call" && !part.providerExecuted
1104
+ )
1105
+ }),
1106
+ raw: (_e = candidate.finishReason) != null ? _e : void 0
1107
+ },
1108
+ usage: convertGoogleGenerativeAIUsage(usageMetadata),
1109
+ warnings,
1110
+ providerMetadata: {
1111
+ [providerOptionsName]: {
1112
+ promptFeedback: (_f = response.promptFeedback) != null ? _f : null,
1113
+ groundingMetadata: (_g = candidate.groundingMetadata) != null ? _g : null,
1114
+ urlContextMetadata: (_h = candidate.urlContextMetadata) != null ? _h : null,
1115
+ safetyRatings: (_i = candidate.safetyRatings) != null ? _i : null,
1116
+ usageMetadata: usageMetadata != null ? usageMetadata : null
1117
+ }
1118
+ },
1119
+ request: { body: args },
1120
+ response: {
1121
+ // TODO timestamp, model id, id
1122
+ headers: responseHeaders,
1123
+ body: rawResponse
1124
+ }
1125
+ };
1126
+ }
1127
+ async doStream(options) {
1128
+ const { args, warnings, providerOptionsName } = await this.getArgs(options);
1129
+ const headers = (0, import_provider_utils6.combineHeaders)(
1130
+ await (0, import_provider_utils6.resolve)(this.config.headers),
1131
+ options.headers
1132
+ );
1133
+ const { responseHeaders, value: response } = await (0, import_provider_utils6.postJsonToApi)({
1134
+ url: `${this.config.baseURL}/${getModelPath(
1135
+ this.modelId
1136
+ )}:streamGenerateContent?alt=sse`,
1137
+ headers,
1138
+ body: args,
1139
+ failedResponseHandler: googleFailedResponseHandler,
1140
+ successfulResponseHandler: (0, import_provider_utils6.createEventSourceResponseHandler)(chunkSchema),
1141
+ abortSignal: options.abortSignal,
1142
+ fetch: this.config.fetch
1143
+ });
1144
+ let finishReason = {
1145
+ unified: "other",
1146
+ raw: void 0
1147
+ };
1148
+ let usage = void 0;
1149
+ let providerMetadata = void 0;
1150
+ const generateId3 = this.config.generateId;
1151
+ let hasToolCalls = false;
1152
+ let currentTextBlockId = null;
1153
+ let currentReasoningBlockId = null;
1154
+ let blockCounter = 0;
1155
+ const emittedSourceUrls = /* @__PURE__ */ new Set();
1156
+ let lastCodeExecutionToolCallId;
1157
+ return {
1158
+ stream: response.pipeThrough(
1159
+ new TransformStream({
1160
+ start(controller) {
1161
+ controller.enqueue({ type: "stream-start", warnings });
1162
+ },
1163
+ transform(chunk, controller) {
1164
+ var _a, _b, _c, _d, _e, _f, _g;
1165
+ if (options.includeRawChunks) {
1166
+ controller.enqueue({ type: "raw", rawValue: chunk.rawValue });
1167
+ }
1168
+ if (!chunk.success) {
1169
+ controller.enqueue({ type: "error", error: chunk.error });
1170
+ return;
1171
+ }
1172
+ const value = chunk.value;
1173
+ const usageMetadata = value.usageMetadata;
1174
+ if (usageMetadata != null) {
1175
+ usage = usageMetadata;
1176
+ }
1177
+ const candidate = (_a = value.candidates) == null ? void 0 : _a[0];
1178
+ if (candidate == null) {
1179
+ return;
1180
+ }
1181
+ const content = candidate.content;
1182
+ const sources = extractSources({
1183
+ groundingMetadata: candidate.groundingMetadata,
1184
+ generateId: generateId3
1185
+ });
1186
+ if (sources != null) {
1187
+ for (const source of sources) {
1188
+ if (source.sourceType === "url" && !emittedSourceUrls.has(source.url)) {
1189
+ emittedSourceUrls.add(source.url);
1190
+ controller.enqueue(source);
1191
+ }
1192
+ }
1193
+ }
1194
+ if (content != null) {
1195
+ const parts = (_b = content.parts) != null ? _b : [];
1196
+ for (const part of parts) {
1197
+ if ("executableCode" in part && ((_c = part.executableCode) == null ? void 0 : _c.code)) {
1198
+ const toolCallId = generateId3();
1199
+ lastCodeExecutionToolCallId = toolCallId;
1200
+ controller.enqueue({
1201
+ type: "tool-call",
1202
+ toolCallId,
1203
+ toolName: "code_execution",
1204
+ input: JSON.stringify(part.executableCode),
1205
+ providerExecuted: true
1206
+ });
1207
+ } else if ("codeExecutionResult" in part && part.codeExecutionResult) {
1208
+ const toolCallId = lastCodeExecutionToolCallId;
1209
+ if (toolCallId) {
1210
+ controller.enqueue({
1211
+ type: "tool-result",
1212
+ toolCallId,
1213
+ toolName: "code_execution",
1214
+ result: {
1215
+ outcome: part.codeExecutionResult.outcome,
1216
+ output: part.codeExecutionResult.output
1217
+ }
1218
+ });
1219
+ lastCodeExecutionToolCallId = void 0;
1220
+ }
1221
+ } else if ("text" in part && part.text != null && part.text.length > 0) {
1222
+ if (part.thought === true) {
1223
+ if (currentTextBlockId !== null) {
1224
+ controller.enqueue({
1225
+ type: "text-end",
1226
+ id: currentTextBlockId
1227
+ });
1228
+ currentTextBlockId = null;
1229
+ }
1230
+ if (currentReasoningBlockId === null) {
1231
+ currentReasoningBlockId = String(blockCounter++);
1232
+ controller.enqueue({
1233
+ type: "reasoning-start",
1234
+ id: currentReasoningBlockId,
1235
+ providerMetadata: part.thoughtSignature ? {
1236
+ [providerOptionsName]: {
1237
+ thoughtSignature: part.thoughtSignature
1238
+ }
1239
+ } : void 0
1240
+ });
1241
+ }
1242
+ controller.enqueue({
1243
+ type: "reasoning-delta",
1244
+ id: currentReasoningBlockId,
1245
+ delta: part.text,
1246
+ providerMetadata: part.thoughtSignature ? {
1247
+ [providerOptionsName]: {
1248
+ thoughtSignature: part.thoughtSignature
1249
+ }
1250
+ } : void 0
1251
+ });
1252
+ } else {
1253
+ if (currentReasoningBlockId !== null) {
1254
+ controller.enqueue({
1255
+ type: "reasoning-end",
1256
+ id: currentReasoningBlockId
1257
+ });
1258
+ currentReasoningBlockId = null;
1259
+ }
1260
+ if (currentTextBlockId === null) {
1261
+ currentTextBlockId = String(blockCounter++);
1262
+ controller.enqueue({
1263
+ type: "text-start",
1264
+ id: currentTextBlockId,
1265
+ providerMetadata: part.thoughtSignature ? {
1266
+ [providerOptionsName]: {
1267
+ thoughtSignature: part.thoughtSignature
1268
+ }
1269
+ } : void 0
1270
+ });
1271
+ }
1272
+ controller.enqueue({
1273
+ type: "text-delta",
1274
+ id: currentTextBlockId,
1275
+ delta: part.text,
1276
+ providerMetadata: part.thoughtSignature ? {
1277
+ [providerOptionsName]: {
1278
+ thoughtSignature: part.thoughtSignature
1279
+ }
1280
+ } : void 0
1281
+ });
1282
+ }
1283
+ } else if ("inlineData" in part) {
1284
+ controller.enqueue({
1285
+ type: "file",
1286
+ mediaType: part.inlineData.mimeType,
1287
+ data: part.inlineData.data
1288
+ });
1289
+ }
1290
+ }
1291
+ const toolCallDeltas = getToolCallsFromParts({
1292
+ parts: content.parts,
1293
+ generateId: generateId3,
1294
+ providerOptionsName
1295
+ });
1296
+ if (toolCallDeltas != null) {
1297
+ for (const toolCall of toolCallDeltas) {
1298
+ controller.enqueue({
1299
+ type: "tool-input-start",
1300
+ id: toolCall.toolCallId,
1301
+ toolName: toolCall.toolName,
1302
+ providerMetadata: toolCall.providerMetadata
1303
+ });
1304
+ controller.enqueue({
1305
+ type: "tool-input-delta",
1306
+ id: toolCall.toolCallId,
1307
+ delta: toolCall.args,
1308
+ providerMetadata: toolCall.providerMetadata
1309
+ });
1310
+ controller.enqueue({
1311
+ type: "tool-input-end",
1312
+ id: toolCall.toolCallId,
1313
+ providerMetadata: toolCall.providerMetadata
1314
+ });
1315
+ controller.enqueue({
1316
+ type: "tool-call",
1317
+ toolCallId: toolCall.toolCallId,
1318
+ toolName: toolCall.toolName,
1319
+ input: toolCall.args,
1320
+ providerMetadata: toolCall.providerMetadata
1321
+ });
1322
+ hasToolCalls = true;
1323
+ }
1324
+ }
1325
+ }
1326
+ if (candidate.finishReason != null) {
1327
+ finishReason = {
1328
+ unified: mapGoogleGenerativeAIFinishReason({
1329
+ finishReason: candidate.finishReason,
1330
+ hasToolCalls
1331
+ }),
1332
+ raw: candidate.finishReason
1333
+ };
1334
+ providerMetadata = {
1335
+ [providerOptionsName]: {
1336
+ promptFeedback: (_d = value.promptFeedback) != null ? _d : null,
1337
+ groundingMetadata: (_e = candidate.groundingMetadata) != null ? _e : null,
1338
+ urlContextMetadata: (_f = candidate.urlContextMetadata) != null ? _f : null,
1339
+ safetyRatings: (_g = candidate.safetyRatings) != null ? _g : null
1340
+ }
1341
+ };
1342
+ if (usageMetadata != null) {
1343
+ providerMetadata[providerOptionsName].usageMetadata = usageMetadata;
1344
+ }
1345
+ }
1346
+ },
1347
+ flush(controller) {
1348
+ if (currentTextBlockId !== null) {
1349
+ controller.enqueue({
1350
+ type: "text-end",
1351
+ id: currentTextBlockId
1352
+ });
1353
+ }
1354
+ if (currentReasoningBlockId !== null) {
1355
+ controller.enqueue({
1356
+ type: "reasoning-end",
1357
+ id: currentReasoningBlockId
1358
+ });
1359
+ }
1360
+ controller.enqueue({
1361
+ type: "finish",
1362
+ finishReason,
1363
+ usage: convertGoogleGenerativeAIUsage(usage),
1364
+ providerMetadata
1365
+ });
1366
+ }
1367
+ })
1368
+ ),
1369
+ response: { headers: responseHeaders },
1370
+ request: { body: args }
1371
+ };
1372
+ }
1373
+ };
1374
+ function getToolCallsFromParts({
1375
+ parts,
1376
+ generateId: generateId3,
1377
+ providerOptionsName
1378
+ }) {
1379
+ const functionCallParts = parts == null ? void 0 : parts.filter(
1380
+ (part) => "functionCall" in part
1381
+ );
1382
+ return functionCallParts == null || functionCallParts.length === 0 ? void 0 : functionCallParts.map((part) => ({
1383
+ type: "tool-call",
1384
+ toolCallId: generateId3(),
1385
+ toolName: part.functionCall.name,
1386
+ args: JSON.stringify(part.functionCall.args),
1387
+ providerMetadata: part.thoughtSignature ? {
1388
+ [providerOptionsName]: {
1389
+ thoughtSignature: part.thoughtSignature
1390
+ }
1391
+ } : void 0
1392
+ }));
1393
+ }
1394
+ function extractSources({
1395
+ groundingMetadata,
1396
+ generateId: generateId3
1397
+ }) {
1398
+ var _a, _b, _c, _d, _e;
1399
+ if (!(groundingMetadata == null ? void 0 : groundingMetadata.groundingChunks)) {
1400
+ return void 0;
1401
+ }
1402
+ const sources = [];
1403
+ for (const chunk of groundingMetadata.groundingChunks) {
1404
+ if (chunk.web != null) {
1405
+ sources.push({
1406
+ type: "source",
1407
+ sourceType: "url",
1408
+ id: generateId3(),
1409
+ url: chunk.web.uri,
1410
+ title: (_a = chunk.web.title) != null ? _a : void 0
1411
+ });
1412
+ } else if (chunk.retrievedContext != null) {
1413
+ const uri = chunk.retrievedContext.uri;
1414
+ const fileSearchStore = chunk.retrievedContext.fileSearchStore;
1415
+ if (uri && (uri.startsWith("http://") || uri.startsWith("https://"))) {
1416
+ sources.push({
1417
+ type: "source",
1418
+ sourceType: "url",
1419
+ id: generateId3(),
1420
+ url: uri,
1421
+ title: (_b = chunk.retrievedContext.title) != null ? _b : void 0
1422
+ });
1423
+ } else if (uri) {
1424
+ const title = (_c = chunk.retrievedContext.title) != null ? _c : "Unknown Document";
1425
+ let mediaType = "application/octet-stream";
1426
+ let filename = void 0;
1427
+ if (uri.endsWith(".pdf")) {
1428
+ mediaType = "application/pdf";
1429
+ filename = uri.split("/").pop();
1430
+ } else if (uri.endsWith(".txt")) {
1431
+ mediaType = "text/plain";
1432
+ filename = uri.split("/").pop();
1433
+ } else if (uri.endsWith(".docx")) {
1434
+ mediaType = "application/vnd.openxmlformats-officedocument.wordprocessingml.document";
1435
+ filename = uri.split("/").pop();
1436
+ } else if (uri.endsWith(".doc")) {
1437
+ mediaType = "application/msword";
1438
+ filename = uri.split("/").pop();
1439
+ } else if (uri.match(/\.(md|markdown)$/)) {
1440
+ mediaType = "text/markdown";
1441
+ filename = uri.split("/").pop();
1442
+ } else {
1443
+ filename = uri.split("/").pop();
1444
+ }
1445
+ sources.push({
1446
+ type: "source",
1447
+ sourceType: "document",
1448
+ id: generateId3(),
1449
+ mediaType,
1450
+ title,
1451
+ filename
1452
+ });
1453
+ } else if (fileSearchStore) {
1454
+ const title = (_d = chunk.retrievedContext.title) != null ? _d : "Unknown Document";
1455
+ sources.push({
1456
+ type: "source",
1457
+ sourceType: "document",
1458
+ id: generateId3(),
1459
+ mediaType: "application/octet-stream",
1460
+ title,
1461
+ filename: fileSearchStore.split("/").pop()
1462
+ });
1463
+ }
1464
+ } else if (chunk.maps != null) {
1465
+ if (chunk.maps.uri) {
1466
+ sources.push({
1467
+ type: "source",
1468
+ sourceType: "url",
1469
+ id: generateId3(),
1470
+ url: chunk.maps.uri,
1471
+ title: (_e = chunk.maps.title) != null ? _e : void 0
1472
+ });
1473
+ }
1474
+ }
1475
+ }
1476
+ return sources.length > 0 ? sources : void 0;
1477
+ }
1478
+ var getGroundingMetadataSchema = () => import_v45.z.object({
1479
+ webSearchQueries: import_v45.z.array(import_v45.z.string()).nullish(),
1480
+ retrievalQueries: import_v45.z.array(import_v45.z.string()).nullish(),
1481
+ searchEntryPoint: import_v45.z.object({ renderedContent: import_v45.z.string() }).nullish(),
1482
+ groundingChunks: import_v45.z.array(
1483
+ import_v45.z.object({
1484
+ web: import_v45.z.object({ uri: import_v45.z.string(), title: import_v45.z.string().nullish() }).nullish(),
1485
+ retrievedContext: import_v45.z.object({
1486
+ uri: import_v45.z.string().nullish(),
1487
+ title: import_v45.z.string().nullish(),
1488
+ text: import_v45.z.string().nullish(),
1489
+ fileSearchStore: import_v45.z.string().nullish()
1490
+ }).nullish(),
1491
+ maps: import_v45.z.object({
1492
+ uri: import_v45.z.string().nullish(),
1493
+ title: import_v45.z.string().nullish(),
1494
+ text: import_v45.z.string().nullish(),
1495
+ placeId: import_v45.z.string().nullish()
1496
+ }).nullish()
1497
+ })
1498
+ ).nullish(),
1499
+ groundingSupports: import_v45.z.array(
1500
+ import_v45.z.object({
1501
+ segment: import_v45.z.object({
1502
+ startIndex: import_v45.z.number().nullish(),
1503
+ endIndex: import_v45.z.number().nullish(),
1504
+ text: import_v45.z.string().nullish()
1505
+ }),
1506
+ segment_text: import_v45.z.string().nullish(),
1507
+ groundingChunkIndices: import_v45.z.array(import_v45.z.number()).nullish(),
1508
+ supportChunkIndices: import_v45.z.array(import_v45.z.number()).nullish(),
1509
+ confidenceScores: import_v45.z.array(import_v45.z.number()).nullish(),
1510
+ confidenceScore: import_v45.z.array(import_v45.z.number()).nullish()
1511
+ })
1512
+ ).nullish(),
1513
+ retrievalMetadata: import_v45.z.union([
1514
+ import_v45.z.object({
1515
+ webDynamicRetrievalScore: import_v45.z.number()
1516
+ }),
1517
+ import_v45.z.object({})
1518
+ ]).nullish()
1519
+ });
1520
+ var getContentSchema = () => import_v45.z.object({
1521
+ parts: import_v45.z.array(
1522
+ import_v45.z.union([
1523
+ // note: order matters since text can be fully empty
1524
+ import_v45.z.object({
1525
+ functionCall: import_v45.z.object({
1526
+ name: import_v45.z.string(),
1527
+ args: import_v45.z.unknown()
1528
+ }),
1529
+ thoughtSignature: import_v45.z.string().nullish()
1530
+ }),
1531
+ import_v45.z.object({
1532
+ inlineData: import_v45.z.object({
1533
+ mimeType: import_v45.z.string(),
1534
+ data: import_v45.z.string()
1535
+ }),
1536
+ thoughtSignature: import_v45.z.string().nullish()
1537
+ }),
1538
+ import_v45.z.object({
1539
+ executableCode: import_v45.z.object({
1540
+ language: import_v45.z.string(),
1541
+ code: import_v45.z.string()
1542
+ }).nullish(),
1543
+ codeExecutionResult: import_v45.z.object({
1544
+ outcome: import_v45.z.string(),
1545
+ output: import_v45.z.string()
1546
+ }).nullish(),
1547
+ text: import_v45.z.string().nullish(),
1548
+ thought: import_v45.z.boolean().nullish(),
1549
+ thoughtSignature: import_v45.z.string().nullish()
1550
+ })
1551
+ ])
1552
+ ).nullish()
1553
+ });
1554
+ var getSafetyRatingSchema = () => import_v45.z.object({
1555
+ category: import_v45.z.string().nullish(),
1556
+ probability: import_v45.z.string().nullish(),
1557
+ probabilityScore: import_v45.z.number().nullish(),
1558
+ severity: import_v45.z.string().nullish(),
1559
+ severityScore: import_v45.z.number().nullish(),
1560
+ blocked: import_v45.z.boolean().nullish()
1561
+ });
1562
+ var usageSchema = import_v45.z.object({
1563
+ cachedContentTokenCount: import_v45.z.number().nullish(),
1564
+ thoughtsTokenCount: import_v45.z.number().nullish(),
1565
+ promptTokenCount: import_v45.z.number().nullish(),
1566
+ candidatesTokenCount: import_v45.z.number().nullish(),
1567
+ totalTokenCount: import_v45.z.number().nullish(),
1568
+ // https://cloud.google.com/vertex-ai/generative-ai/docs/reference/rest/v1/GenerateContentResponse#TrafficType
1569
+ trafficType: import_v45.z.string().nullish()
1570
+ });
1571
+ var getUrlContextMetadataSchema = () => import_v45.z.object({
1572
+ urlMetadata: import_v45.z.array(
1573
+ import_v45.z.object({
1574
+ retrievedUrl: import_v45.z.string(),
1575
+ urlRetrievalStatus: import_v45.z.string()
1576
+ })
1577
+ )
1578
+ });
1579
+ var responseSchema = (0, import_provider_utils6.lazySchema)(
1580
+ () => (0, import_provider_utils6.zodSchema)(
1581
+ import_v45.z.object({
1582
+ candidates: import_v45.z.array(
1583
+ import_v45.z.object({
1584
+ content: getContentSchema().nullish().or(import_v45.z.object({}).strict()),
1585
+ finishReason: import_v45.z.string().nullish(),
1586
+ safetyRatings: import_v45.z.array(getSafetyRatingSchema()).nullish(),
1587
+ groundingMetadata: getGroundingMetadataSchema().nullish(),
1588
+ urlContextMetadata: getUrlContextMetadataSchema().nullish()
1589
+ })
1590
+ ),
1591
+ usageMetadata: usageSchema.nullish(),
1592
+ promptFeedback: import_v45.z.object({
1593
+ blockReason: import_v45.z.string().nullish(),
1594
+ safetyRatings: import_v45.z.array(getSafetyRatingSchema()).nullish()
1595
+ }).nullish()
1596
+ })
1597
+ )
1598
+ );
1599
+ var chunkSchema = (0, import_provider_utils6.lazySchema)(
1600
+ () => (0, import_provider_utils6.zodSchema)(
1601
+ import_v45.z.object({
1602
+ candidates: import_v45.z.array(
1603
+ import_v45.z.object({
1604
+ content: getContentSchema().nullish(),
1605
+ finishReason: import_v45.z.string().nullish(),
1606
+ safetyRatings: import_v45.z.array(getSafetyRatingSchema()).nullish(),
1607
+ groundingMetadata: getGroundingMetadataSchema().nullish(),
1608
+ urlContextMetadata: getUrlContextMetadataSchema().nullish()
1609
+ })
1610
+ ).nullish(),
1611
+ usageMetadata: usageSchema.nullish(),
1612
+ promptFeedback: import_v45.z.object({
1613
+ blockReason: import_v45.z.string().nullish(),
1614
+ safetyRatings: import_v45.z.array(getSafetyRatingSchema()).nullish()
1615
+ }).nullish()
1616
+ })
1617
+ )
1618
+ );
1619
+
1620
+ // src/tool/code-execution.ts
1621
+ var import_provider_utils7 = require("@ai-sdk/provider-utils");
1622
+ var import_v46 = require("zod/v4");
1623
+ var codeExecution = (0, import_provider_utils7.createProviderToolFactoryWithOutputSchema)({
1624
+ id: "google.code_execution",
1625
+ inputSchema: import_v46.z.object({
1626
+ language: import_v46.z.string().describe("The programming language of the code."),
1627
+ code: import_v46.z.string().describe("The code to be executed.")
1628
+ }),
1629
+ outputSchema: import_v46.z.object({
1630
+ outcome: import_v46.z.string().describe('The outcome of the execution (e.g., "OUTCOME_OK").'),
1631
+ output: import_v46.z.string().describe("The output from the code execution.")
1632
+ })
1633
+ });
1634
+
1635
+ // src/tool/enterprise-web-search.ts
1636
+ var import_provider_utils8 = require("@ai-sdk/provider-utils");
1637
+ var import_v47 = require("zod/v4");
1638
+ var enterpriseWebSearch = (0, import_provider_utils8.createProviderToolFactory)({
1639
+ id: "google.enterprise_web_search",
1640
+ inputSchema: (0, import_provider_utils8.lazySchema)(() => (0, import_provider_utils8.zodSchema)(import_v47.z.object({})))
1641
+ });
1642
+
1643
+ // src/tool/file-search.ts
1644
+ var import_provider_utils9 = require("@ai-sdk/provider-utils");
1645
+ var import_v48 = require("zod/v4");
1646
+ var fileSearchArgsBaseSchema = import_v48.z.object({
1647
+ /** The names of the file_search_stores to retrieve from.
1648
+ * Example: `fileSearchStores/my-file-search-store-123`
1649
+ */
1650
+ fileSearchStoreNames: import_v48.z.array(import_v48.z.string()).describe(
1651
+ "The names of the file_search_stores to retrieve from. Example: `fileSearchStores/my-file-search-store-123`"
1652
+ ),
1653
+ /** The number of file search retrieval chunks to retrieve. */
1654
+ topK: import_v48.z.number().int().positive().describe("The number of file search retrieval chunks to retrieve.").optional(),
1655
+ /** Metadata filter to apply to the file search retrieval documents.
1656
+ * See https://google.aip.dev/160 for the syntax of the filter expression.
1657
+ */
1658
+ metadataFilter: import_v48.z.string().describe(
1659
+ "Metadata filter to apply to the file search retrieval documents. See https://google.aip.dev/160 for the syntax of the filter expression."
1660
+ ).optional()
1661
+ }).passthrough();
1662
+ var fileSearchArgsSchema = (0, import_provider_utils9.lazySchema)(
1663
+ () => (0, import_provider_utils9.zodSchema)(fileSearchArgsBaseSchema)
1664
+ );
1665
+ var fileSearch = (0, import_provider_utils9.createProviderToolFactory)({
1666
+ id: "google.file_search",
1667
+ inputSchema: fileSearchArgsSchema
1668
+ });
1669
+
1670
+ // src/tool/google-maps.ts
1671
+ var import_provider_utils10 = require("@ai-sdk/provider-utils");
1672
+ var import_v49 = require("zod/v4");
1673
+ var googleMaps = (0, import_provider_utils10.createProviderToolFactory)({
1674
+ id: "google.google_maps",
1675
+ inputSchema: (0, import_provider_utils10.lazySchema)(() => (0, import_provider_utils10.zodSchema)(import_v49.z.object({})))
1676
+ });
1677
+
1678
+ // src/tool/google-search.ts
1679
+ var import_provider_utils11 = require("@ai-sdk/provider-utils");
1680
+ var import_v410 = require("zod/v4");
1681
+ var googleSearch = (0, import_provider_utils11.createProviderToolFactory)({
1682
+ id: "google.google_search",
1683
+ inputSchema: (0, import_provider_utils11.lazySchema)(
1684
+ () => (0, import_provider_utils11.zodSchema)(
1685
+ import_v410.z.object({
1686
+ mode: import_v410.z.enum(["MODE_DYNAMIC", "MODE_UNSPECIFIED"]).default("MODE_UNSPECIFIED"),
1687
+ dynamicThreshold: import_v410.z.number().default(1)
1688
+ })
1689
+ )
1690
+ )
1691
+ });
1692
+
1693
+ // src/tool/url-context.ts
1694
+ var import_provider_utils12 = require("@ai-sdk/provider-utils");
1695
+ var import_v411 = require("zod/v4");
1696
+ var urlContext = (0, import_provider_utils12.createProviderToolFactory)({
1697
+ id: "google.url_context",
1698
+ inputSchema: (0, import_provider_utils12.lazySchema)(() => (0, import_provider_utils12.zodSchema)(import_v411.z.object({})))
1699
+ });
1700
+
1701
+ // src/tool/vertex-rag-store.ts
1702
+ var import_provider_utils13 = require("@ai-sdk/provider-utils");
1703
+ var import_v412 = require("zod/v4");
1704
+ var vertexRagStore = (0, import_provider_utils13.createProviderToolFactory)({
1705
+ id: "google.vertex_rag_store",
1706
+ inputSchema: import_v412.z.object({
1707
+ ragCorpus: import_v412.z.string(),
1708
+ topK: import_v412.z.number().optional()
1709
+ })
1710
+ });
1711
+
1712
+ // src/google-tools.ts
1713
+ var googleTools = {
1714
+ /**
1715
+ * Creates a Google search tool that gives Google direct access to real-time web content.
1716
+ * Must have name "google_search".
1717
+ */
1718
+ googleSearch,
1719
+ /**
1720
+ * Creates an Enterprise Web Search tool for grounding responses using a compliance-focused web index.
1721
+ * Designed for highly-regulated industries (finance, healthcare, public sector).
1722
+ * Does not log customer data and supports VPC service controls.
1723
+ * Must have name "enterprise_web_search".
1724
+ *
1725
+ * @note Only available on Vertex AI. Requires Gemini 2.0 or newer.
1726
+ *
1727
+ * @see https://cloud.google.com/vertex-ai/generative-ai/docs/grounding/web-grounding-enterprise
1728
+ */
1729
+ enterpriseWebSearch,
1730
+ /**
1731
+ * Creates a Google Maps grounding tool that gives the model access to Google Maps data.
1732
+ * Must have name "google_maps".
1733
+ *
1734
+ * @see https://ai.google.dev/gemini-api/docs/maps-grounding
1735
+ * @see https://cloud.google.com/vertex-ai/generative-ai/docs/grounding/grounding-with-google-maps
1736
+ */
1737
+ googleMaps,
1738
+ /**
1739
+ * Creates a URL context tool that gives Google direct access to real-time web content.
1740
+ * Must have name "url_context".
1741
+ */
1742
+ urlContext,
1743
+ /**
1744
+ * Enables Retrieval Augmented Generation (RAG) via the Gemini File Search tool.
1745
+ * Must have name "file_search".
1746
+ *
1747
+ * @param fileSearchStoreNames - Fully-qualified File Search store resource names.
1748
+ * @param metadataFilter - Optional filter expression to restrict the files that can be retrieved.
1749
+ * @param topK - Optional result limit for the number of chunks returned from File Search.
1750
+ *
1751
+ * @see https://ai.google.dev/gemini-api/docs/file-search
1752
+ */
1753
+ fileSearch,
1754
+ /**
1755
+ * A tool that enables the model to generate and run Python code.
1756
+ * Must have name "code_execution".
1757
+ *
1758
+ * @note Ensure the selected model supports Code Execution.
1759
+ * Multi-tool usage with the code execution tool is typically compatible with Gemini >=2 models.
1760
+ *
1761
+ * @see https://ai.google.dev/gemini-api/docs/code-execution (Google AI)
1762
+ * @see https://cloud.google.com/vertex-ai/generative-ai/docs/model-reference/code-execution-api (Vertex AI)
1763
+ */
1764
+ codeExecution,
1765
+ /**
1766
+ * Creates a Vertex RAG Store tool that enables the model to perform RAG searches against a Vertex RAG Store.
1767
+ * Must have name "vertex_rag_store".
1768
+ */
1769
+ vertexRagStore
1770
+ };
1771
+
1772
+ // src/google-generative-ai-image-model.ts
1773
+ var import_provider_utils14 = require("@ai-sdk/provider-utils");
1774
+ var import_v413 = require("zod/v4");
1775
+ var GoogleGenerativeAIImageModel = class {
1776
+ constructor(modelId, settings, config) {
1777
+ this.modelId = modelId;
1778
+ this.settings = settings;
1779
+ this.config = config;
1780
+ this.specificationVersion = "v3";
1781
+ }
1782
+ get maxImagesPerCall() {
1783
+ var _a;
1784
+ return (_a = this.settings.maxImagesPerCall) != null ? _a : 4;
1785
+ }
1786
+ get provider() {
1787
+ return this.config.provider;
1788
+ }
1789
+ async doGenerate(options) {
1790
+ var _a, _b, _c;
1791
+ const {
1792
+ prompt,
1793
+ n = 1,
1794
+ size,
1795
+ aspectRatio = "1:1",
1796
+ seed,
1797
+ providerOptions,
1798
+ headers,
1799
+ abortSignal,
1800
+ files,
1801
+ mask
1802
+ } = options;
1803
+ const warnings = [];
1804
+ if (files != null && files.length > 0) {
1805
+ throw new Error(
1806
+ "Google Generative AI does not support image editing. Use Google Vertex AI (@ai-sdk/google-vertex) for image editing capabilities."
1807
+ );
1808
+ }
1809
+ if (mask != null) {
1810
+ throw new Error(
1811
+ "Google Generative AI does not support image editing with masks. Use Google Vertex AI (@ai-sdk/google-vertex) for image editing capabilities."
1812
+ );
1813
+ }
1814
+ if (size != null) {
1815
+ warnings.push({
1816
+ type: "unsupported",
1817
+ feature: "size",
1818
+ details: "This model does not support the `size` option. Use `aspectRatio` instead."
1819
+ });
1820
+ }
1821
+ if (seed != null) {
1822
+ warnings.push({
1823
+ type: "unsupported",
1824
+ feature: "seed",
1825
+ details: "This model does not support the `seed` option through this provider."
1826
+ });
1827
+ }
1828
+ const googleOptions = await (0, import_provider_utils14.parseProviderOptions)({
1829
+ provider: "google",
1830
+ providerOptions,
1831
+ schema: googleImageProviderOptionsSchema
1832
+ });
1833
+ const currentDate = (_c = (_b = (_a = this.config._internal) == null ? void 0 : _a.currentDate) == null ? void 0 : _b.call(_a)) != null ? _c : /* @__PURE__ */ new Date();
1834
+ const parameters = {
1835
+ sampleCount: n
1836
+ };
1837
+ if (aspectRatio != null) {
1838
+ parameters.aspectRatio = aspectRatio;
1839
+ }
1840
+ if (googleOptions) {
1841
+ Object.assign(parameters, googleOptions);
1842
+ }
1843
+ const body = {
1844
+ instances: [{ prompt }],
1845
+ parameters
1846
+ };
1847
+ const { responseHeaders, value: response } = await (0, import_provider_utils14.postJsonToApi)({
1848
+ url: `${this.config.baseURL}/models/${this.modelId}:predict`,
1849
+ headers: (0, import_provider_utils14.combineHeaders)(await (0, import_provider_utils14.resolve)(this.config.headers), headers),
1850
+ body,
1851
+ failedResponseHandler: googleFailedResponseHandler,
1852
+ successfulResponseHandler: (0, import_provider_utils14.createJsonResponseHandler)(
1853
+ googleImageResponseSchema
1854
+ ),
1855
+ abortSignal,
1856
+ fetch: this.config.fetch
1857
+ });
1858
+ return {
1859
+ images: response.predictions.map(
1860
+ (p) => p.bytesBase64Encoded
1861
+ ),
1862
+ warnings: warnings != null ? warnings : [],
1863
+ providerMetadata: {
1864
+ google: {
1865
+ images: response.predictions.map((prediction) => ({
1866
+ // Add any prediction-specific metadata here
1867
+ }))
1868
+ }
1869
+ },
1870
+ response: {
1871
+ timestamp: currentDate,
1872
+ modelId: this.modelId,
1873
+ headers: responseHeaders
1874
+ }
1875
+ };
1876
+ }
1877
+ };
1878
+ var googleImageResponseSchema = (0, import_provider_utils14.lazySchema)(
1879
+ () => (0, import_provider_utils14.zodSchema)(
1880
+ import_v413.z.object({
1881
+ predictions: import_v413.z.array(import_v413.z.object({ bytesBase64Encoded: import_v413.z.string() })).default([])
1882
+ })
1883
+ )
1884
+ );
1885
+ var googleImageProviderOptionsSchema = (0, import_provider_utils14.lazySchema)(
1886
+ () => (0, import_provider_utils14.zodSchema)(
1887
+ import_v413.z.object({
1888
+ personGeneration: import_v413.z.enum(["dont_allow", "allow_adult", "allow_all"]).nullish(),
1889
+ aspectRatio: import_v413.z.enum(["1:1", "3:4", "4:3", "9:16", "16:9"]).nullish()
1890
+ })
1891
+ )
1892
+ );
1893
+
1894
+ // src/google-provider.ts
1895
+ function createGoogleGenerativeAI(options = {}) {
1896
+ var _a, _b;
1897
+ const baseURL = (_a = (0, import_provider_utils15.withoutTrailingSlash)(options.baseURL)) != null ? _a : "https://generativelanguage.googleapis.com/v1beta";
1898
+ const providerName = (_b = options.name) != null ? _b : "google.generative-ai";
1899
+ const getHeaders = () => (0, import_provider_utils15.withUserAgentSuffix)(
1900
+ {
1901
+ "x-goog-api-key": (0, import_provider_utils15.loadApiKey)({
1902
+ apiKey: options.apiKey,
1903
+ environmentVariableName: "GOOGLE_GENERATIVE_AI_API_KEY",
1904
+ description: "Google Generative AI"
1905
+ }),
1906
+ ...options.headers
1907
+ },
1908
+ `ai-sdk/google/${VERSION}`
1909
+ );
1910
+ const createChatModel = (modelId) => {
1911
+ var _a2;
1912
+ return new GoogleGenerativeAILanguageModel(modelId, {
1913
+ provider: providerName,
1914
+ baseURL,
1915
+ headers: getHeaders,
1916
+ generateId: (_a2 = options.generateId) != null ? _a2 : import_provider_utils15.generateId,
1917
+ supportedUrls: () => ({
1918
+ "*": [
1919
+ // Google Generative Language "files" endpoint
1920
+ // e.g. https://generativelanguage.googleapis.com/v1beta/files/...
1921
+ new RegExp(`^${baseURL}/files/.*$`),
1922
+ // YouTube URLs (public or unlisted videos)
1923
+ new RegExp(
1924
+ `^https://(?:www\\.)?youtube\\.com/watch\\?v=[\\w-]+(?:&[\\w=&.-]*)?$`
1925
+ ),
1926
+ new RegExp(`^https://youtu\\.be/[\\w-]+(?:\\?[\\w=&.-]*)?$`)
1927
+ ]
1928
+ }),
1929
+ fetch: options.fetch
1930
+ });
1931
+ };
1932
+ const createEmbeddingModel = (modelId) => new GoogleGenerativeAIEmbeddingModel(modelId, {
1933
+ provider: providerName,
1934
+ baseURL,
1935
+ headers: getHeaders,
1936
+ fetch: options.fetch
1937
+ });
1938
+ const createImageModel = (modelId, settings = {}) => new GoogleGenerativeAIImageModel(modelId, settings, {
1939
+ provider: providerName,
1940
+ baseURL,
1941
+ headers: getHeaders,
1942
+ fetch: options.fetch
1943
+ });
1944
+ const provider = function(modelId) {
1945
+ if (new.target) {
1946
+ throw new Error(
1947
+ "The Google Generative AI model function cannot be called with the new keyword."
1948
+ );
1949
+ }
1950
+ return createChatModel(modelId);
1951
+ };
1952
+ provider.specificationVersion = "v3";
1953
+ provider.languageModel = createChatModel;
1954
+ provider.chat = createChatModel;
1955
+ provider.generativeAI = createChatModel;
1956
+ provider.embedding = createEmbeddingModel;
1957
+ provider.embeddingModel = createEmbeddingModel;
1958
+ provider.textEmbedding = createEmbeddingModel;
1959
+ provider.textEmbeddingModel = createEmbeddingModel;
1960
+ provider.image = createImageModel;
1961
+ provider.imageModel = createImageModel;
1962
+ provider.tools = googleTools;
1963
+ return provider;
1964
+ }
1965
+ var google = createGoogleGenerativeAI();
1966
+ // Annotate the CommonJS export names for ESM import in node:
1967
+ 0 && (module.exports = {
1968
+ VERSION,
1969
+ createGoogleGenerativeAI,
1970
+ google
1971
+ });
1972
+ //# sourceMappingURL=index.js.map