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