@ai-sdk/google 0.0.0-64aae7dd-20260114144918

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.
@@ -0,0 +1,1621 @@
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;
247
+ const providerOpts = (_a2 = part.providerOptions) == null ? void 0 : _a2[providerOptionsName];
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 googleGenerativeAIProviderOptions = (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
+ ]).optional(),
485
+ imageSize: import_v42.z.enum(["1K", "2K", "4K"]).optional()
486
+ }).optional(),
487
+ /**
488
+ * Optional. Configuration for grounding retrieval.
489
+ * Used to provide location context for Google Maps and Google Search grounding.
490
+ *
491
+ * https://cloud.google.com/vertex-ai/generative-ai/docs/grounding/grounding-with-google-maps
492
+ */
493
+ retrievalConfig: import_v42.z.object({
494
+ latLng: import_v42.z.object({
495
+ latitude: import_v42.z.number(),
496
+ longitude: import_v42.z.number()
497
+ }).optional()
498
+ }).optional()
499
+ })
500
+ )
501
+ );
502
+
503
+ // src/google-prepare-tools.ts
504
+ var import_provider2 = require("@ai-sdk/provider");
505
+ function prepareTools({
506
+ tools,
507
+ toolChoice,
508
+ modelId
509
+ }) {
510
+ var _a;
511
+ tools = (tools == null ? void 0 : tools.length) ? tools : void 0;
512
+ const toolWarnings = [];
513
+ const isLatest = [
514
+ "gemini-flash-latest",
515
+ "gemini-flash-lite-latest",
516
+ "gemini-pro-latest"
517
+ ].some((id) => id === modelId);
518
+ const isGemini2orNewer = modelId.includes("gemini-2") || modelId.includes("gemini-3") || isLatest;
519
+ const supportsDynamicRetrieval = modelId.includes("gemini-1.5-flash") && !modelId.includes("-8b");
520
+ const supportsFileSearch = modelId.includes("gemini-2.5") || modelId.includes("gemini-3");
521
+ if (tools == null) {
522
+ return { tools: void 0, toolConfig: void 0, toolWarnings };
523
+ }
524
+ const hasFunctionTools = tools.some((tool) => tool.type === "function");
525
+ const hasProviderTools = tools.some((tool) => tool.type === "provider");
526
+ if (hasFunctionTools && hasProviderTools) {
527
+ toolWarnings.push({
528
+ type: "unsupported",
529
+ feature: `combination of function and provider-defined tools`
530
+ });
531
+ }
532
+ if (hasProviderTools) {
533
+ const googleTools2 = [];
534
+ const ProviderTools = tools.filter((tool) => tool.type === "provider");
535
+ ProviderTools.forEach((tool) => {
536
+ switch (tool.id) {
537
+ case "google.google_search":
538
+ if (isGemini2orNewer) {
539
+ googleTools2.push({ googleSearch: {} });
540
+ } else if (supportsDynamicRetrieval) {
541
+ googleTools2.push({
542
+ googleSearchRetrieval: {
543
+ dynamicRetrievalConfig: {
544
+ mode: tool.args.mode,
545
+ dynamicThreshold: tool.args.dynamicThreshold
546
+ }
547
+ }
548
+ });
549
+ } else {
550
+ googleTools2.push({ googleSearchRetrieval: {} });
551
+ }
552
+ break;
553
+ case "google.enterprise_web_search":
554
+ if (isGemini2orNewer) {
555
+ googleTools2.push({ enterpriseWebSearch: {} });
556
+ } else {
557
+ toolWarnings.push({
558
+ type: "unsupported",
559
+ feature: `provider-defined tool ${tool.id}`,
560
+ details: "Enterprise Web Search requires Gemini 2.0 or newer."
561
+ });
562
+ }
563
+ break;
564
+ case "google.url_context":
565
+ if (isGemini2orNewer) {
566
+ googleTools2.push({ urlContext: {} });
567
+ } else {
568
+ toolWarnings.push({
569
+ type: "unsupported",
570
+ feature: `provider-defined tool ${tool.id}`,
571
+ details: "The URL context tool is not supported with other Gemini models than Gemini 2."
572
+ });
573
+ }
574
+ break;
575
+ case "google.code_execution":
576
+ if (isGemini2orNewer) {
577
+ googleTools2.push({ codeExecution: {} });
578
+ } else {
579
+ toolWarnings.push({
580
+ type: "unsupported",
581
+ feature: `provider-defined tool ${tool.id}`,
582
+ details: "The code execution tools is not supported with other Gemini models than Gemini 2."
583
+ });
584
+ }
585
+ break;
586
+ case "google.file_search":
587
+ if (supportsFileSearch) {
588
+ googleTools2.push({ fileSearch: { ...tool.args } });
589
+ } else {
590
+ toolWarnings.push({
591
+ type: "unsupported",
592
+ feature: `provider-defined tool ${tool.id}`,
593
+ details: "The file search tool is only supported with Gemini 2.5 models and Gemini 3 models."
594
+ });
595
+ }
596
+ break;
597
+ case "google.vertex_rag_store":
598
+ if (isGemini2orNewer) {
599
+ googleTools2.push({
600
+ retrieval: {
601
+ vertex_rag_store: {
602
+ rag_resources: {
603
+ rag_corpus: tool.args.ragCorpus
604
+ },
605
+ similarity_top_k: tool.args.topK
606
+ }
607
+ }
608
+ });
609
+ } else {
610
+ toolWarnings.push({
611
+ type: "unsupported",
612
+ feature: `provider-defined tool ${tool.id}`,
613
+ details: "The RAG store tool is not supported with other Gemini models than Gemini 2."
614
+ });
615
+ }
616
+ break;
617
+ case "google.google_maps":
618
+ if (isGemini2orNewer) {
619
+ googleTools2.push({ googleMaps: {} });
620
+ } else {
621
+ toolWarnings.push({
622
+ type: "unsupported",
623
+ feature: `provider-defined tool ${tool.id}`,
624
+ details: "The Google Maps grounding tool is not supported with Gemini models other than Gemini 2 or newer."
625
+ });
626
+ }
627
+ break;
628
+ default:
629
+ toolWarnings.push({
630
+ type: "unsupported",
631
+ feature: `provider-defined tool ${tool.id}`
632
+ });
633
+ break;
634
+ }
635
+ });
636
+ return {
637
+ tools: googleTools2.length > 0 ? googleTools2 : void 0,
638
+ toolConfig: void 0,
639
+ toolWarnings
640
+ };
641
+ }
642
+ const functionDeclarations = [];
643
+ for (const tool of tools) {
644
+ switch (tool.type) {
645
+ case "function":
646
+ functionDeclarations.push({
647
+ name: tool.name,
648
+ description: (_a = tool.description) != null ? _a : "",
649
+ parameters: convertJSONSchemaToOpenAPISchema(tool.inputSchema)
650
+ });
651
+ break;
652
+ default:
653
+ toolWarnings.push({
654
+ type: "unsupported",
655
+ feature: `function tool ${tool.name}`
656
+ });
657
+ break;
658
+ }
659
+ }
660
+ if (toolChoice == null) {
661
+ return {
662
+ tools: [{ functionDeclarations }],
663
+ toolConfig: void 0,
664
+ toolWarnings
665
+ };
666
+ }
667
+ const type = toolChoice.type;
668
+ switch (type) {
669
+ case "auto":
670
+ return {
671
+ tools: [{ functionDeclarations }],
672
+ toolConfig: { functionCallingConfig: { mode: "AUTO" } },
673
+ toolWarnings
674
+ };
675
+ case "none":
676
+ return {
677
+ tools: [{ functionDeclarations }],
678
+ toolConfig: { functionCallingConfig: { mode: "NONE" } },
679
+ toolWarnings
680
+ };
681
+ case "required":
682
+ return {
683
+ tools: [{ functionDeclarations }],
684
+ toolConfig: { functionCallingConfig: { mode: "ANY" } },
685
+ toolWarnings
686
+ };
687
+ case "tool":
688
+ return {
689
+ tools: [{ functionDeclarations }],
690
+ toolConfig: {
691
+ functionCallingConfig: {
692
+ mode: "ANY",
693
+ allowedFunctionNames: [toolChoice.toolName]
694
+ }
695
+ },
696
+ toolWarnings
697
+ };
698
+ default: {
699
+ const _exhaustiveCheck = type;
700
+ throw new import_provider2.UnsupportedFunctionalityError({
701
+ functionality: `tool choice type: ${_exhaustiveCheck}`
702
+ });
703
+ }
704
+ }
705
+ }
706
+
707
+ // src/map-google-generative-ai-finish-reason.ts
708
+ function mapGoogleGenerativeAIFinishReason({
709
+ finishReason,
710
+ hasToolCalls
711
+ }) {
712
+ switch (finishReason) {
713
+ case "STOP":
714
+ return hasToolCalls ? "tool-calls" : "stop";
715
+ case "MAX_TOKENS":
716
+ return "length";
717
+ case "IMAGE_SAFETY":
718
+ case "RECITATION":
719
+ case "SAFETY":
720
+ case "BLOCKLIST":
721
+ case "PROHIBITED_CONTENT":
722
+ case "SPII":
723
+ return "content-filter";
724
+ case "MALFORMED_FUNCTION_CALL":
725
+ return "error";
726
+ case "FINISH_REASON_UNSPECIFIED":
727
+ case "OTHER":
728
+ default:
729
+ return "other";
730
+ }
731
+ }
732
+
733
+ // src/google-generative-ai-language-model.ts
734
+ var GoogleGenerativeAILanguageModel = class {
735
+ constructor(modelId, config) {
736
+ this.specificationVersion = "v3";
737
+ var _a;
738
+ this.modelId = modelId;
739
+ this.config = config;
740
+ this.generateId = (_a = config.generateId) != null ? _a : import_provider_utils4.generateId;
741
+ }
742
+ get provider() {
743
+ return this.config.provider;
744
+ }
745
+ get supportedUrls() {
746
+ var _a, _b, _c;
747
+ return (_c = (_b = (_a = this.config).supportedUrls) == null ? void 0 : _b.call(_a)) != null ? _c : {};
748
+ }
749
+ async getArgs({
750
+ prompt,
751
+ maxOutputTokens,
752
+ temperature,
753
+ topP,
754
+ topK,
755
+ frequencyPenalty,
756
+ presencePenalty,
757
+ stopSequences,
758
+ responseFormat,
759
+ seed,
760
+ tools,
761
+ toolChoice,
762
+ providerOptions
763
+ }) {
764
+ var _a;
765
+ const warnings = [];
766
+ const providerOptionsName = this.config.provider.includes("vertex") ? "vertex" : "google";
767
+ let googleOptions = await (0, import_provider_utils4.parseProviderOptions)({
768
+ provider: providerOptionsName,
769
+ providerOptions,
770
+ schema: googleGenerativeAIProviderOptions
771
+ });
772
+ if (googleOptions == null && providerOptionsName !== "google") {
773
+ googleOptions = await (0, import_provider_utils4.parseProviderOptions)({
774
+ provider: "google",
775
+ providerOptions,
776
+ schema: googleGenerativeAIProviderOptions
777
+ });
778
+ }
779
+ if ((tools == null ? void 0 : tools.some(
780
+ (tool) => tool.type === "provider" && tool.id === "google.vertex_rag_store"
781
+ )) && !this.config.provider.startsWith("google.vertex.")) {
782
+ warnings.push({
783
+ type: "other",
784
+ 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}).`
785
+ });
786
+ }
787
+ const isGemmaModel = this.modelId.toLowerCase().startsWith("gemma-");
788
+ const { contents, systemInstruction } = convertToGoogleGenerativeAIMessages(
789
+ prompt,
790
+ { isGemmaModel, providerOptionsName }
791
+ );
792
+ const {
793
+ tools: googleTools2,
794
+ toolConfig: googleToolConfig,
795
+ toolWarnings
796
+ } = prepareTools({
797
+ tools,
798
+ toolChoice,
799
+ modelId: this.modelId
800
+ });
801
+ return {
802
+ args: {
803
+ generationConfig: {
804
+ // standardized settings:
805
+ maxOutputTokens,
806
+ temperature,
807
+ topK,
808
+ topP,
809
+ frequencyPenalty,
810
+ presencePenalty,
811
+ stopSequences,
812
+ seed,
813
+ // response format:
814
+ responseMimeType: (responseFormat == null ? void 0 : responseFormat.type) === "json" ? "application/json" : void 0,
815
+ responseSchema: (responseFormat == null ? void 0 : responseFormat.type) === "json" && responseFormat.schema != null && // Google GenAI does not support all OpenAPI Schema features,
816
+ // so this is needed as an escape hatch:
817
+ // TODO convert into provider option
818
+ ((_a = googleOptions == null ? void 0 : googleOptions.structuredOutputs) != null ? _a : true) ? convertJSONSchemaToOpenAPISchema(responseFormat.schema) : void 0,
819
+ ...(googleOptions == null ? void 0 : googleOptions.audioTimestamp) && {
820
+ audioTimestamp: googleOptions.audioTimestamp
821
+ },
822
+ // provider options:
823
+ responseModalities: googleOptions == null ? void 0 : googleOptions.responseModalities,
824
+ thinkingConfig: googleOptions == null ? void 0 : googleOptions.thinkingConfig,
825
+ ...(googleOptions == null ? void 0 : googleOptions.mediaResolution) && {
826
+ mediaResolution: googleOptions.mediaResolution
827
+ },
828
+ ...(googleOptions == null ? void 0 : googleOptions.imageConfig) && {
829
+ imageConfig: googleOptions.imageConfig
830
+ }
831
+ },
832
+ contents,
833
+ systemInstruction: isGemmaModel ? void 0 : systemInstruction,
834
+ safetySettings: googleOptions == null ? void 0 : googleOptions.safetySettings,
835
+ tools: googleTools2,
836
+ toolConfig: (googleOptions == null ? void 0 : googleOptions.retrievalConfig) ? {
837
+ ...googleToolConfig,
838
+ retrievalConfig: googleOptions.retrievalConfig
839
+ } : googleToolConfig,
840
+ cachedContent: googleOptions == null ? void 0 : googleOptions.cachedContent,
841
+ labels: googleOptions == null ? void 0 : googleOptions.labels
842
+ },
843
+ warnings: [...warnings, ...toolWarnings],
844
+ providerOptionsName
845
+ };
846
+ }
847
+ async doGenerate(options) {
848
+ var _a, _b, _c, _d, _e, _f, _g, _h, _i;
849
+ const { args, warnings, providerOptionsName } = await this.getArgs(options);
850
+ const mergedHeaders = (0, import_provider_utils4.combineHeaders)(
851
+ await (0, import_provider_utils4.resolve)(this.config.headers),
852
+ options.headers
853
+ );
854
+ const {
855
+ responseHeaders,
856
+ value: response,
857
+ rawValue: rawResponse
858
+ } = await (0, import_provider_utils4.postJsonToApi)({
859
+ url: `${this.config.baseURL}/${getModelPath(
860
+ this.modelId
861
+ )}:generateContent`,
862
+ headers: mergedHeaders,
863
+ body: args,
864
+ failedResponseHandler: googleFailedResponseHandler,
865
+ successfulResponseHandler: (0, import_provider_utils4.createJsonResponseHandler)(responseSchema),
866
+ abortSignal: options.abortSignal,
867
+ fetch: this.config.fetch
868
+ });
869
+ const candidate = response.candidates[0];
870
+ const content = [];
871
+ const parts = (_b = (_a = candidate.content) == null ? void 0 : _a.parts) != null ? _b : [];
872
+ const usageMetadata = response.usageMetadata;
873
+ let lastCodeExecutionToolCallId;
874
+ for (const part of parts) {
875
+ if ("executableCode" in part && ((_c = part.executableCode) == null ? void 0 : _c.code)) {
876
+ const toolCallId = this.config.generateId();
877
+ lastCodeExecutionToolCallId = toolCallId;
878
+ content.push({
879
+ type: "tool-call",
880
+ toolCallId,
881
+ toolName: "code_execution",
882
+ input: JSON.stringify(part.executableCode),
883
+ providerExecuted: true
884
+ });
885
+ } else if ("codeExecutionResult" in part && part.codeExecutionResult) {
886
+ content.push({
887
+ type: "tool-result",
888
+ // Assumes a result directly follows its corresponding call part.
889
+ toolCallId: lastCodeExecutionToolCallId,
890
+ toolName: "code_execution",
891
+ result: {
892
+ outcome: part.codeExecutionResult.outcome,
893
+ output: part.codeExecutionResult.output
894
+ }
895
+ });
896
+ lastCodeExecutionToolCallId = void 0;
897
+ } else if ("text" in part && part.text != null && part.text.length > 0) {
898
+ content.push({
899
+ type: part.thought === true ? "reasoning" : "text",
900
+ text: part.text,
901
+ providerMetadata: part.thoughtSignature ? {
902
+ [providerOptionsName]: {
903
+ thoughtSignature: part.thoughtSignature
904
+ }
905
+ } : void 0
906
+ });
907
+ } else if ("functionCall" in part) {
908
+ content.push({
909
+ type: "tool-call",
910
+ toolCallId: this.config.generateId(),
911
+ toolName: part.functionCall.name,
912
+ input: JSON.stringify(part.functionCall.args),
913
+ providerMetadata: part.thoughtSignature ? {
914
+ [providerOptionsName]: {
915
+ thoughtSignature: part.thoughtSignature
916
+ }
917
+ } : void 0
918
+ });
919
+ } else if ("inlineData" in part) {
920
+ content.push({
921
+ type: "file",
922
+ data: part.inlineData.data,
923
+ mediaType: part.inlineData.mimeType,
924
+ providerMetadata: part.thoughtSignature ? {
925
+ [providerOptionsName]: {
926
+ thoughtSignature: part.thoughtSignature
927
+ }
928
+ } : void 0
929
+ });
930
+ }
931
+ }
932
+ const sources = (_d = extractSources({
933
+ groundingMetadata: candidate.groundingMetadata,
934
+ generateId: this.config.generateId
935
+ })) != null ? _d : [];
936
+ for (const source of sources) {
937
+ content.push(source);
938
+ }
939
+ return {
940
+ content,
941
+ finishReason: {
942
+ unified: mapGoogleGenerativeAIFinishReason({
943
+ finishReason: candidate.finishReason,
944
+ // Only count client-executed tool calls for finish reason determination.
945
+ hasToolCalls: content.some(
946
+ (part) => part.type === "tool-call" && !part.providerExecuted
947
+ )
948
+ }),
949
+ raw: (_e = candidate.finishReason) != null ? _e : void 0
950
+ },
951
+ usage: convertGoogleGenerativeAIUsage(usageMetadata),
952
+ warnings,
953
+ providerMetadata: {
954
+ [providerOptionsName]: {
955
+ promptFeedback: (_f = response.promptFeedback) != null ? _f : null,
956
+ groundingMetadata: (_g = candidate.groundingMetadata) != null ? _g : null,
957
+ urlContextMetadata: (_h = candidate.urlContextMetadata) != null ? _h : null,
958
+ safetyRatings: (_i = candidate.safetyRatings) != null ? _i : null,
959
+ usageMetadata: usageMetadata != null ? usageMetadata : null
960
+ }
961
+ },
962
+ request: { body: args },
963
+ response: {
964
+ // TODO timestamp, model id, id
965
+ headers: responseHeaders,
966
+ body: rawResponse
967
+ }
968
+ };
969
+ }
970
+ async doStream(options) {
971
+ const { args, warnings, providerOptionsName } = await this.getArgs(options);
972
+ const headers = (0, import_provider_utils4.combineHeaders)(
973
+ await (0, import_provider_utils4.resolve)(this.config.headers),
974
+ options.headers
975
+ );
976
+ const { responseHeaders, value: response } = await (0, import_provider_utils4.postJsonToApi)({
977
+ url: `${this.config.baseURL}/${getModelPath(
978
+ this.modelId
979
+ )}:streamGenerateContent?alt=sse`,
980
+ headers,
981
+ body: args,
982
+ failedResponseHandler: googleFailedResponseHandler,
983
+ successfulResponseHandler: (0, import_provider_utils4.createEventSourceResponseHandler)(chunkSchema),
984
+ abortSignal: options.abortSignal,
985
+ fetch: this.config.fetch
986
+ });
987
+ let finishReason = {
988
+ unified: "other",
989
+ raw: void 0
990
+ };
991
+ let usage = void 0;
992
+ let providerMetadata = void 0;
993
+ const generateId2 = this.config.generateId;
994
+ let hasToolCalls = false;
995
+ let currentTextBlockId = null;
996
+ let currentReasoningBlockId = null;
997
+ let blockCounter = 0;
998
+ const emittedSourceUrls = /* @__PURE__ */ new Set();
999
+ let lastCodeExecutionToolCallId;
1000
+ return {
1001
+ stream: response.pipeThrough(
1002
+ new TransformStream({
1003
+ start(controller) {
1004
+ controller.enqueue({ type: "stream-start", warnings });
1005
+ },
1006
+ transform(chunk, controller) {
1007
+ var _a, _b, _c, _d, _e, _f, _g;
1008
+ if (options.includeRawChunks) {
1009
+ controller.enqueue({ type: "raw", rawValue: chunk.rawValue });
1010
+ }
1011
+ if (!chunk.success) {
1012
+ controller.enqueue({ type: "error", error: chunk.error });
1013
+ return;
1014
+ }
1015
+ const value = chunk.value;
1016
+ const usageMetadata = value.usageMetadata;
1017
+ if (usageMetadata != null) {
1018
+ usage = usageMetadata;
1019
+ }
1020
+ const candidate = (_a = value.candidates) == null ? void 0 : _a[0];
1021
+ if (candidate == null) {
1022
+ return;
1023
+ }
1024
+ const content = candidate.content;
1025
+ const sources = extractSources({
1026
+ groundingMetadata: candidate.groundingMetadata,
1027
+ generateId: generateId2
1028
+ });
1029
+ if (sources != null) {
1030
+ for (const source of sources) {
1031
+ if (source.sourceType === "url" && !emittedSourceUrls.has(source.url)) {
1032
+ emittedSourceUrls.add(source.url);
1033
+ controller.enqueue(source);
1034
+ }
1035
+ }
1036
+ }
1037
+ if (content != null) {
1038
+ const parts = (_b = content.parts) != null ? _b : [];
1039
+ for (const part of parts) {
1040
+ if ("executableCode" in part && ((_c = part.executableCode) == null ? void 0 : _c.code)) {
1041
+ const toolCallId = generateId2();
1042
+ lastCodeExecutionToolCallId = toolCallId;
1043
+ controller.enqueue({
1044
+ type: "tool-call",
1045
+ toolCallId,
1046
+ toolName: "code_execution",
1047
+ input: JSON.stringify(part.executableCode),
1048
+ providerExecuted: true
1049
+ });
1050
+ } else if ("codeExecutionResult" in part && part.codeExecutionResult) {
1051
+ const toolCallId = lastCodeExecutionToolCallId;
1052
+ if (toolCallId) {
1053
+ controller.enqueue({
1054
+ type: "tool-result",
1055
+ toolCallId,
1056
+ toolName: "code_execution",
1057
+ result: {
1058
+ outcome: part.codeExecutionResult.outcome,
1059
+ output: part.codeExecutionResult.output
1060
+ }
1061
+ });
1062
+ lastCodeExecutionToolCallId = void 0;
1063
+ }
1064
+ } else if ("text" in part && part.text != null && part.text.length > 0) {
1065
+ if (part.thought === true) {
1066
+ if (currentTextBlockId !== null) {
1067
+ controller.enqueue({
1068
+ type: "text-end",
1069
+ id: currentTextBlockId
1070
+ });
1071
+ currentTextBlockId = null;
1072
+ }
1073
+ if (currentReasoningBlockId === null) {
1074
+ currentReasoningBlockId = String(blockCounter++);
1075
+ controller.enqueue({
1076
+ type: "reasoning-start",
1077
+ id: currentReasoningBlockId,
1078
+ providerMetadata: part.thoughtSignature ? {
1079
+ [providerOptionsName]: {
1080
+ thoughtSignature: part.thoughtSignature
1081
+ }
1082
+ } : void 0
1083
+ });
1084
+ }
1085
+ controller.enqueue({
1086
+ type: "reasoning-delta",
1087
+ id: currentReasoningBlockId,
1088
+ delta: part.text,
1089
+ providerMetadata: part.thoughtSignature ? {
1090
+ [providerOptionsName]: {
1091
+ thoughtSignature: part.thoughtSignature
1092
+ }
1093
+ } : void 0
1094
+ });
1095
+ } else {
1096
+ if (currentReasoningBlockId !== null) {
1097
+ controller.enqueue({
1098
+ type: "reasoning-end",
1099
+ id: currentReasoningBlockId
1100
+ });
1101
+ currentReasoningBlockId = null;
1102
+ }
1103
+ if (currentTextBlockId === null) {
1104
+ currentTextBlockId = String(blockCounter++);
1105
+ controller.enqueue({
1106
+ type: "text-start",
1107
+ id: currentTextBlockId,
1108
+ providerMetadata: part.thoughtSignature ? {
1109
+ [providerOptionsName]: {
1110
+ thoughtSignature: part.thoughtSignature
1111
+ }
1112
+ } : void 0
1113
+ });
1114
+ }
1115
+ controller.enqueue({
1116
+ type: "text-delta",
1117
+ id: currentTextBlockId,
1118
+ delta: part.text,
1119
+ providerMetadata: part.thoughtSignature ? {
1120
+ [providerOptionsName]: {
1121
+ thoughtSignature: part.thoughtSignature
1122
+ }
1123
+ } : void 0
1124
+ });
1125
+ }
1126
+ } else if ("inlineData" in part) {
1127
+ controller.enqueue({
1128
+ type: "file",
1129
+ mediaType: part.inlineData.mimeType,
1130
+ data: part.inlineData.data
1131
+ });
1132
+ }
1133
+ }
1134
+ const toolCallDeltas = getToolCallsFromParts({
1135
+ parts: content.parts,
1136
+ generateId: generateId2,
1137
+ providerOptionsName
1138
+ });
1139
+ if (toolCallDeltas != null) {
1140
+ for (const toolCall of toolCallDeltas) {
1141
+ controller.enqueue({
1142
+ type: "tool-input-start",
1143
+ id: toolCall.toolCallId,
1144
+ toolName: toolCall.toolName,
1145
+ providerMetadata: toolCall.providerMetadata
1146
+ });
1147
+ controller.enqueue({
1148
+ type: "tool-input-delta",
1149
+ id: toolCall.toolCallId,
1150
+ delta: toolCall.args,
1151
+ providerMetadata: toolCall.providerMetadata
1152
+ });
1153
+ controller.enqueue({
1154
+ type: "tool-input-end",
1155
+ id: toolCall.toolCallId,
1156
+ providerMetadata: toolCall.providerMetadata
1157
+ });
1158
+ controller.enqueue({
1159
+ type: "tool-call",
1160
+ toolCallId: toolCall.toolCallId,
1161
+ toolName: toolCall.toolName,
1162
+ input: toolCall.args,
1163
+ providerMetadata: toolCall.providerMetadata
1164
+ });
1165
+ hasToolCalls = true;
1166
+ }
1167
+ }
1168
+ }
1169
+ if (candidate.finishReason != null) {
1170
+ finishReason = {
1171
+ unified: mapGoogleGenerativeAIFinishReason({
1172
+ finishReason: candidate.finishReason,
1173
+ hasToolCalls
1174
+ }),
1175
+ raw: candidate.finishReason
1176
+ };
1177
+ providerMetadata = {
1178
+ [providerOptionsName]: {
1179
+ promptFeedback: (_d = value.promptFeedback) != null ? _d : null,
1180
+ groundingMetadata: (_e = candidate.groundingMetadata) != null ? _e : null,
1181
+ urlContextMetadata: (_f = candidate.urlContextMetadata) != null ? _f : null,
1182
+ safetyRatings: (_g = candidate.safetyRatings) != null ? _g : null
1183
+ }
1184
+ };
1185
+ if (usageMetadata != null) {
1186
+ providerMetadata[providerOptionsName].usageMetadata = usageMetadata;
1187
+ }
1188
+ }
1189
+ },
1190
+ flush(controller) {
1191
+ if (currentTextBlockId !== null) {
1192
+ controller.enqueue({
1193
+ type: "text-end",
1194
+ id: currentTextBlockId
1195
+ });
1196
+ }
1197
+ if (currentReasoningBlockId !== null) {
1198
+ controller.enqueue({
1199
+ type: "reasoning-end",
1200
+ id: currentReasoningBlockId
1201
+ });
1202
+ }
1203
+ controller.enqueue({
1204
+ type: "finish",
1205
+ finishReason,
1206
+ usage: convertGoogleGenerativeAIUsage(usage),
1207
+ providerMetadata
1208
+ });
1209
+ }
1210
+ })
1211
+ ),
1212
+ response: { headers: responseHeaders },
1213
+ request: { body: args }
1214
+ };
1215
+ }
1216
+ };
1217
+ function getToolCallsFromParts({
1218
+ parts,
1219
+ generateId: generateId2,
1220
+ providerOptionsName
1221
+ }) {
1222
+ const functionCallParts = parts == null ? void 0 : parts.filter(
1223
+ (part) => "functionCall" in part
1224
+ );
1225
+ return functionCallParts == null || functionCallParts.length === 0 ? void 0 : functionCallParts.map((part) => ({
1226
+ type: "tool-call",
1227
+ toolCallId: generateId2(),
1228
+ toolName: part.functionCall.name,
1229
+ args: JSON.stringify(part.functionCall.args),
1230
+ providerMetadata: part.thoughtSignature ? {
1231
+ [providerOptionsName]: {
1232
+ thoughtSignature: part.thoughtSignature
1233
+ }
1234
+ } : void 0
1235
+ }));
1236
+ }
1237
+ function extractSources({
1238
+ groundingMetadata,
1239
+ generateId: generateId2
1240
+ }) {
1241
+ var _a, _b, _c, _d, _e;
1242
+ if (!(groundingMetadata == null ? void 0 : groundingMetadata.groundingChunks)) {
1243
+ return void 0;
1244
+ }
1245
+ const sources = [];
1246
+ for (const chunk of groundingMetadata.groundingChunks) {
1247
+ if (chunk.web != null) {
1248
+ sources.push({
1249
+ type: "source",
1250
+ sourceType: "url",
1251
+ id: generateId2(),
1252
+ url: chunk.web.uri,
1253
+ title: (_a = chunk.web.title) != null ? _a : void 0
1254
+ });
1255
+ } else if (chunk.retrievedContext != null) {
1256
+ const uri = chunk.retrievedContext.uri;
1257
+ const fileSearchStore = chunk.retrievedContext.fileSearchStore;
1258
+ if (uri && (uri.startsWith("http://") || uri.startsWith("https://"))) {
1259
+ sources.push({
1260
+ type: "source",
1261
+ sourceType: "url",
1262
+ id: generateId2(),
1263
+ url: uri,
1264
+ title: (_b = chunk.retrievedContext.title) != null ? _b : void 0
1265
+ });
1266
+ } else if (uri) {
1267
+ const title = (_c = chunk.retrievedContext.title) != null ? _c : "Unknown Document";
1268
+ let mediaType = "application/octet-stream";
1269
+ let filename = void 0;
1270
+ if (uri.endsWith(".pdf")) {
1271
+ mediaType = "application/pdf";
1272
+ filename = uri.split("/").pop();
1273
+ } else if (uri.endsWith(".txt")) {
1274
+ mediaType = "text/plain";
1275
+ filename = uri.split("/").pop();
1276
+ } else if (uri.endsWith(".docx")) {
1277
+ mediaType = "application/vnd.openxmlformats-officedocument.wordprocessingml.document";
1278
+ filename = uri.split("/").pop();
1279
+ } else if (uri.endsWith(".doc")) {
1280
+ mediaType = "application/msword";
1281
+ filename = uri.split("/").pop();
1282
+ } else if (uri.match(/\.(md|markdown)$/)) {
1283
+ mediaType = "text/markdown";
1284
+ filename = uri.split("/").pop();
1285
+ } else {
1286
+ filename = uri.split("/").pop();
1287
+ }
1288
+ sources.push({
1289
+ type: "source",
1290
+ sourceType: "document",
1291
+ id: generateId2(),
1292
+ mediaType,
1293
+ title,
1294
+ filename
1295
+ });
1296
+ } else if (fileSearchStore) {
1297
+ const title = (_d = chunk.retrievedContext.title) != null ? _d : "Unknown Document";
1298
+ sources.push({
1299
+ type: "source",
1300
+ sourceType: "document",
1301
+ id: generateId2(),
1302
+ mediaType: "application/octet-stream",
1303
+ title,
1304
+ filename: fileSearchStore.split("/").pop()
1305
+ });
1306
+ }
1307
+ } else if (chunk.maps != null) {
1308
+ if (chunk.maps.uri) {
1309
+ sources.push({
1310
+ type: "source",
1311
+ sourceType: "url",
1312
+ id: generateId2(),
1313
+ url: chunk.maps.uri,
1314
+ title: (_e = chunk.maps.title) != null ? _e : void 0
1315
+ });
1316
+ }
1317
+ }
1318
+ }
1319
+ return sources.length > 0 ? sources : void 0;
1320
+ }
1321
+ var getGroundingMetadataSchema = () => import_v43.z.object({
1322
+ webSearchQueries: import_v43.z.array(import_v43.z.string()).nullish(),
1323
+ retrievalQueries: import_v43.z.array(import_v43.z.string()).nullish(),
1324
+ searchEntryPoint: import_v43.z.object({ renderedContent: import_v43.z.string() }).nullish(),
1325
+ groundingChunks: import_v43.z.array(
1326
+ import_v43.z.object({
1327
+ web: import_v43.z.object({ uri: import_v43.z.string(), title: import_v43.z.string().nullish() }).nullish(),
1328
+ retrievedContext: import_v43.z.object({
1329
+ uri: import_v43.z.string().nullish(),
1330
+ title: import_v43.z.string().nullish(),
1331
+ text: import_v43.z.string().nullish(),
1332
+ fileSearchStore: import_v43.z.string().nullish()
1333
+ }).nullish(),
1334
+ maps: import_v43.z.object({
1335
+ uri: import_v43.z.string().nullish(),
1336
+ title: import_v43.z.string().nullish(),
1337
+ text: import_v43.z.string().nullish(),
1338
+ placeId: import_v43.z.string().nullish()
1339
+ }).nullish()
1340
+ })
1341
+ ).nullish(),
1342
+ groundingSupports: import_v43.z.array(
1343
+ import_v43.z.object({
1344
+ segment: import_v43.z.object({
1345
+ startIndex: import_v43.z.number().nullish(),
1346
+ endIndex: import_v43.z.number().nullish(),
1347
+ text: import_v43.z.string().nullish()
1348
+ }),
1349
+ segment_text: import_v43.z.string().nullish(),
1350
+ groundingChunkIndices: import_v43.z.array(import_v43.z.number()).nullish(),
1351
+ supportChunkIndices: import_v43.z.array(import_v43.z.number()).nullish(),
1352
+ confidenceScores: import_v43.z.array(import_v43.z.number()).nullish(),
1353
+ confidenceScore: import_v43.z.array(import_v43.z.number()).nullish()
1354
+ })
1355
+ ).nullish(),
1356
+ retrievalMetadata: import_v43.z.union([
1357
+ import_v43.z.object({
1358
+ webDynamicRetrievalScore: import_v43.z.number()
1359
+ }),
1360
+ import_v43.z.object({})
1361
+ ]).nullish()
1362
+ });
1363
+ var getContentSchema = () => import_v43.z.object({
1364
+ parts: import_v43.z.array(
1365
+ import_v43.z.union([
1366
+ // note: order matters since text can be fully empty
1367
+ import_v43.z.object({
1368
+ functionCall: import_v43.z.object({
1369
+ name: import_v43.z.string(),
1370
+ args: import_v43.z.unknown()
1371
+ }),
1372
+ thoughtSignature: import_v43.z.string().nullish()
1373
+ }),
1374
+ import_v43.z.object({
1375
+ inlineData: import_v43.z.object({
1376
+ mimeType: import_v43.z.string(),
1377
+ data: import_v43.z.string()
1378
+ }),
1379
+ thoughtSignature: import_v43.z.string().nullish()
1380
+ }),
1381
+ import_v43.z.object({
1382
+ executableCode: import_v43.z.object({
1383
+ language: import_v43.z.string(),
1384
+ code: import_v43.z.string()
1385
+ }).nullish(),
1386
+ codeExecutionResult: import_v43.z.object({
1387
+ outcome: import_v43.z.string(),
1388
+ output: import_v43.z.string()
1389
+ }).nullish(),
1390
+ text: import_v43.z.string().nullish(),
1391
+ thought: import_v43.z.boolean().nullish(),
1392
+ thoughtSignature: import_v43.z.string().nullish()
1393
+ })
1394
+ ])
1395
+ ).nullish()
1396
+ });
1397
+ var getSafetyRatingSchema = () => import_v43.z.object({
1398
+ category: import_v43.z.string().nullish(),
1399
+ probability: import_v43.z.string().nullish(),
1400
+ probabilityScore: import_v43.z.number().nullish(),
1401
+ severity: import_v43.z.string().nullish(),
1402
+ severityScore: import_v43.z.number().nullish(),
1403
+ blocked: import_v43.z.boolean().nullish()
1404
+ });
1405
+ var usageSchema = import_v43.z.object({
1406
+ cachedContentTokenCount: import_v43.z.number().nullish(),
1407
+ thoughtsTokenCount: import_v43.z.number().nullish(),
1408
+ promptTokenCount: import_v43.z.number().nullish(),
1409
+ candidatesTokenCount: import_v43.z.number().nullish(),
1410
+ totalTokenCount: import_v43.z.number().nullish(),
1411
+ // https://cloud.google.com/vertex-ai/generative-ai/docs/reference/rest/v1/GenerateContentResponse#TrafficType
1412
+ trafficType: import_v43.z.string().nullish()
1413
+ });
1414
+ var getUrlContextMetadataSchema = () => import_v43.z.object({
1415
+ urlMetadata: import_v43.z.array(
1416
+ import_v43.z.object({
1417
+ retrievedUrl: import_v43.z.string(),
1418
+ urlRetrievalStatus: import_v43.z.string()
1419
+ })
1420
+ )
1421
+ });
1422
+ var responseSchema = (0, import_provider_utils4.lazySchema)(
1423
+ () => (0, import_provider_utils4.zodSchema)(
1424
+ import_v43.z.object({
1425
+ candidates: import_v43.z.array(
1426
+ import_v43.z.object({
1427
+ content: getContentSchema().nullish().or(import_v43.z.object({}).strict()),
1428
+ finishReason: import_v43.z.string().nullish(),
1429
+ safetyRatings: import_v43.z.array(getSafetyRatingSchema()).nullish(),
1430
+ groundingMetadata: getGroundingMetadataSchema().nullish(),
1431
+ urlContextMetadata: getUrlContextMetadataSchema().nullish()
1432
+ })
1433
+ ),
1434
+ usageMetadata: usageSchema.nullish(),
1435
+ promptFeedback: import_v43.z.object({
1436
+ blockReason: import_v43.z.string().nullish(),
1437
+ safetyRatings: import_v43.z.array(getSafetyRatingSchema()).nullish()
1438
+ }).nullish()
1439
+ })
1440
+ )
1441
+ );
1442
+ var chunkSchema = (0, import_provider_utils4.lazySchema)(
1443
+ () => (0, import_provider_utils4.zodSchema)(
1444
+ import_v43.z.object({
1445
+ candidates: import_v43.z.array(
1446
+ import_v43.z.object({
1447
+ content: getContentSchema().nullish(),
1448
+ finishReason: import_v43.z.string().nullish(),
1449
+ safetyRatings: import_v43.z.array(getSafetyRatingSchema()).nullish(),
1450
+ groundingMetadata: getGroundingMetadataSchema().nullish(),
1451
+ urlContextMetadata: getUrlContextMetadataSchema().nullish()
1452
+ })
1453
+ ).nullish(),
1454
+ usageMetadata: usageSchema.nullish(),
1455
+ promptFeedback: import_v43.z.object({
1456
+ blockReason: import_v43.z.string().nullish(),
1457
+ safetyRatings: import_v43.z.array(getSafetyRatingSchema()).nullish()
1458
+ }).nullish()
1459
+ })
1460
+ )
1461
+ );
1462
+
1463
+ // src/tool/code-execution.ts
1464
+ var import_provider_utils5 = require("@ai-sdk/provider-utils");
1465
+ var import_v44 = require("zod/v4");
1466
+ var codeExecution = (0, import_provider_utils5.createProviderToolFactoryWithOutputSchema)({
1467
+ id: "google.code_execution",
1468
+ inputSchema: import_v44.z.object({
1469
+ language: import_v44.z.string().describe("The programming language of the code."),
1470
+ code: import_v44.z.string().describe("The code to be executed.")
1471
+ }),
1472
+ outputSchema: import_v44.z.object({
1473
+ outcome: import_v44.z.string().describe('The outcome of the execution (e.g., "OUTCOME_OK").'),
1474
+ output: import_v44.z.string().describe("The output from the code execution.")
1475
+ })
1476
+ });
1477
+
1478
+ // src/tool/enterprise-web-search.ts
1479
+ var import_provider_utils6 = require("@ai-sdk/provider-utils");
1480
+ var import_v45 = require("zod/v4");
1481
+ var enterpriseWebSearch = (0, import_provider_utils6.createProviderToolFactory)({
1482
+ id: "google.enterprise_web_search",
1483
+ inputSchema: (0, import_provider_utils6.lazySchema)(() => (0, import_provider_utils6.zodSchema)(import_v45.z.object({})))
1484
+ });
1485
+
1486
+ // src/tool/file-search.ts
1487
+ var import_provider_utils7 = require("@ai-sdk/provider-utils");
1488
+ var import_v46 = require("zod/v4");
1489
+ var fileSearchArgsBaseSchema = import_v46.z.object({
1490
+ /** The names of the file_search_stores to retrieve from.
1491
+ * Example: `fileSearchStores/my-file-search-store-123`
1492
+ */
1493
+ fileSearchStoreNames: import_v46.z.array(import_v46.z.string()).describe(
1494
+ "The names of the file_search_stores to retrieve from. Example: `fileSearchStores/my-file-search-store-123`"
1495
+ ),
1496
+ /** The number of file search retrieval chunks to retrieve. */
1497
+ topK: import_v46.z.number().int().positive().describe("The number of file search retrieval chunks to retrieve.").optional(),
1498
+ /** Metadata filter to apply to the file search retrieval documents.
1499
+ * See https://google.aip.dev/160 for the syntax of the filter expression.
1500
+ */
1501
+ metadataFilter: import_v46.z.string().describe(
1502
+ "Metadata filter to apply to the file search retrieval documents. See https://google.aip.dev/160 for the syntax of the filter expression."
1503
+ ).optional()
1504
+ }).passthrough();
1505
+ var fileSearchArgsSchema = (0, import_provider_utils7.lazySchema)(
1506
+ () => (0, import_provider_utils7.zodSchema)(fileSearchArgsBaseSchema)
1507
+ );
1508
+ var fileSearch = (0, import_provider_utils7.createProviderToolFactory)({
1509
+ id: "google.file_search",
1510
+ inputSchema: fileSearchArgsSchema
1511
+ });
1512
+
1513
+ // src/tool/google-maps.ts
1514
+ var import_provider_utils8 = require("@ai-sdk/provider-utils");
1515
+ var import_v47 = require("zod/v4");
1516
+ var googleMaps = (0, import_provider_utils8.createProviderToolFactory)({
1517
+ id: "google.google_maps",
1518
+ inputSchema: (0, import_provider_utils8.lazySchema)(() => (0, import_provider_utils8.zodSchema)(import_v47.z.object({})))
1519
+ });
1520
+
1521
+ // src/tool/google-search.ts
1522
+ var import_provider_utils9 = require("@ai-sdk/provider-utils");
1523
+ var import_v48 = require("zod/v4");
1524
+ var googleSearch = (0, import_provider_utils9.createProviderToolFactory)({
1525
+ id: "google.google_search",
1526
+ inputSchema: (0, import_provider_utils9.lazySchema)(
1527
+ () => (0, import_provider_utils9.zodSchema)(
1528
+ import_v48.z.object({
1529
+ mode: import_v48.z.enum(["MODE_DYNAMIC", "MODE_UNSPECIFIED"]).default("MODE_UNSPECIFIED"),
1530
+ dynamicThreshold: import_v48.z.number().default(1)
1531
+ })
1532
+ )
1533
+ )
1534
+ });
1535
+
1536
+ // src/tool/url-context.ts
1537
+ var import_provider_utils10 = require("@ai-sdk/provider-utils");
1538
+ var import_v49 = require("zod/v4");
1539
+ var urlContext = (0, import_provider_utils10.createProviderToolFactory)({
1540
+ id: "google.url_context",
1541
+ inputSchema: (0, import_provider_utils10.lazySchema)(() => (0, import_provider_utils10.zodSchema)(import_v49.z.object({})))
1542
+ });
1543
+
1544
+ // src/tool/vertex-rag-store.ts
1545
+ var import_provider_utils11 = require("@ai-sdk/provider-utils");
1546
+ var import_v410 = require("zod/v4");
1547
+ var vertexRagStore = (0, import_provider_utils11.createProviderToolFactory)({
1548
+ id: "google.vertex_rag_store",
1549
+ inputSchema: import_v410.z.object({
1550
+ ragCorpus: import_v410.z.string(),
1551
+ topK: import_v410.z.number().optional()
1552
+ })
1553
+ });
1554
+
1555
+ // src/google-tools.ts
1556
+ var googleTools = {
1557
+ /**
1558
+ * Creates a Google search tool that gives Google direct access to real-time web content.
1559
+ * Must have name "google_search".
1560
+ */
1561
+ googleSearch,
1562
+ /**
1563
+ * Creates an Enterprise Web Search tool for grounding responses using a compliance-focused web index.
1564
+ * Designed for highly-regulated industries (finance, healthcare, public sector).
1565
+ * Does not log customer data and supports VPC service controls.
1566
+ * Must have name "enterprise_web_search".
1567
+ *
1568
+ * @note Only available on Vertex AI. Requires Gemini 2.0 or newer.
1569
+ *
1570
+ * @see https://cloud.google.com/vertex-ai/generative-ai/docs/grounding/web-grounding-enterprise
1571
+ */
1572
+ enterpriseWebSearch,
1573
+ /**
1574
+ * Creates a Google Maps grounding tool that gives the model access to Google Maps data.
1575
+ * Must have name "google_maps".
1576
+ *
1577
+ * @see https://ai.google.dev/gemini-api/docs/maps-grounding
1578
+ * @see https://cloud.google.com/vertex-ai/generative-ai/docs/grounding/grounding-with-google-maps
1579
+ */
1580
+ googleMaps,
1581
+ /**
1582
+ * Creates a URL context tool that gives Google direct access to real-time web content.
1583
+ * Must have name "url_context".
1584
+ */
1585
+ urlContext,
1586
+ /**
1587
+ * Enables Retrieval Augmented Generation (RAG) via the Gemini File Search tool.
1588
+ * Must have name "file_search".
1589
+ *
1590
+ * @param fileSearchStoreNames - Fully-qualified File Search store resource names.
1591
+ * @param metadataFilter - Optional filter expression to restrict the files that can be retrieved.
1592
+ * @param topK - Optional result limit for the number of chunks returned from File Search.
1593
+ *
1594
+ * @see https://ai.google.dev/gemini-api/docs/file-search
1595
+ */
1596
+ fileSearch,
1597
+ /**
1598
+ * A tool that enables the model to generate and run Python code.
1599
+ * Must have name "code_execution".
1600
+ *
1601
+ * @note Ensure the selected model supports Code Execution.
1602
+ * Multi-tool usage with the code execution tool is typically compatible with Gemini >=2 models.
1603
+ *
1604
+ * @see https://ai.google.dev/gemini-api/docs/code-execution (Google AI)
1605
+ * @see https://cloud.google.com/vertex-ai/generative-ai/docs/model-reference/code-execution-api (Vertex AI)
1606
+ */
1607
+ codeExecution,
1608
+ /**
1609
+ * Creates a Vertex RAG Store tool that enables the model to perform RAG searches against a Vertex RAG Store.
1610
+ * Must have name "vertex_rag_store".
1611
+ */
1612
+ vertexRagStore
1613
+ };
1614
+ // Annotate the CommonJS export names for ESM import in node:
1615
+ 0 && (module.exports = {
1616
+ GoogleGenerativeAILanguageModel,
1617
+ getGroundingMetadataSchema,
1618
+ getUrlContextMetadataSchema,
1619
+ googleTools
1620
+ });
1621
+ //# sourceMappingURL=index.js.map