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