@ai-sdk/google 4.0.0-beta.4 → 4.0.0-beta.41

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.
@@ -1,1706 +0,0 @@
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
- ...(providerOpts == null ? void 0 : providerOpts.thought) === true ? { thought: true } : {},
258
- thoughtSignature
259
- };
260
- }
261
- case "tool-call": {
262
- return {
263
- functionCall: {
264
- name: part.toolName,
265
- args: part.input
266
- },
267
- thoughtSignature
268
- };
269
- }
270
- }
271
- }).filter((part) => part !== void 0)
272
- });
273
- break;
274
- }
275
- case "tool": {
276
- systemMessagesAllowed = false;
277
- const parts = [];
278
- for (const part of content) {
279
- if (part.type === "tool-approval-response") {
280
- continue;
281
- }
282
- const output = part.output;
283
- if (output.type === "content") {
284
- for (const contentPart of output.value) {
285
- switch (contentPart.type) {
286
- case "text":
287
- parts.push({
288
- functionResponse: {
289
- name: part.toolName,
290
- response: {
291
- name: part.toolName,
292
- content: contentPart.text
293
- }
294
- }
295
- });
296
- break;
297
- case "image-data":
298
- parts.push(
299
- {
300
- inlineData: {
301
- mimeType: contentPart.mediaType,
302
- data: contentPart.data
303
- }
304
- },
305
- {
306
- text: "Tool executed successfully and returned this image as a response"
307
- }
308
- );
309
- break;
310
- default:
311
- parts.push({ text: JSON.stringify(contentPart) });
312
- break;
313
- }
314
- }
315
- } else {
316
- parts.push({
317
- functionResponse: {
318
- name: part.toolName,
319
- response: {
320
- name: part.toolName,
321
- content: output.type === "execution-denied" ? (_c = output.reason) != null ? _c : "Tool execution denied." : output.value
322
- }
323
- }
324
- });
325
- }
326
- }
327
- contents.push({
328
- role: "user",
329
- parts
330
- });
331
- break;
332
- }
333
- }
334
- }
335
- if (isGemmaModel && systemInstructionParts.length > 0 && contents.length > 0 && contents[0].role === "user") {
336
- const systemText = systemInstructionParts.map((part) => part.text).join("\n\n");
337
- contents[0].parts.unshift({ text: systemText + "\n\n" });
338
- }
339
- return {
340
- systemInstruction: systemInstructionParts.length > 0 && !isGemmaModel ? { parts: systemInstructionParts } : void 0,
341
- contents
342
- };
343
- }
344
-
345
- // src/get-model-path.ts
346
- function getModelPath(modelId) {
347
- return modelId.includes("/") ? modelId : `models/${modelId}`;
348
- }
349
-
350
- // src/google-error.ts
351
- import {
352
- createJsonErrorResponseHandler,
353
- lazySchema,
354
- zodSchema
355
- } from "@ai-sdk/provider-utils";
356
- import { z } from "zod/v4";
357
- var googleErrorDataSchema = lazySchema(
358
- () => zodSchema(
359
- z.object({
360
- error: z.object({
361
- code: z.number().nullable(),
362
- message: z.string(),
363
- status: z.string()
364
- })
365
- })
366
- )
367
- );
368
- var googleFailedResponseHandler = createJsonErrorResponseHandler({
369
- errorSchema: googleErrorDataSchema,
370
- errorToMessage: (data) => data.error.message
371
- });
372
-
373
- // src/google-generative-ai-options.ts
374
- import { lazySchema as lazySchema2, zodSchema as zodSchema2 } from "@ai-sdk/provider-utils";
375
- import { z as z2 } from "zod/v4";
376
- var googleLanguageModelOptions = lazySchema2(
377
- () => zodSchema2(
378
- z2.object({
379
- responseModalities: z2.array(z2.enum(["TEXT", "IMAGE"])).optional(),
380
- thinkingConfig: z2.object({
381
- thinkingBudget: z2.number().optional(),
382
- includeThoughts: z2.boolean().optional(),
383
- // https://ai.google.dev/gemini-api/docs/gemini-3?thinking=high#thinking_level
384
- thinkingLevel: z2.enum(["minimal", "low", "medium", "high"]).optional()
385
- }).optional(),
386
- /**
387
- * Optional.
388
- * The name of the cached content used as context to serve the prediction.
389
- * Format: cachedContents/{cachedContent}
390
- */
391
- cachedContent: z2.string().optional(),
392
- /**
393
- * Optional. Enable structured output. Default is true.
394
- *
395
- * This is useful when the JSON Schema contains elements that are
396
- * not supported by the OpenAPI schema version that
397
- * Google Generative AI uses. You can use this to disable
398
- * structured outputs if you need to.
399
- */
400
- structuredOutputs: z2.boolean().optional(),
401
- /**
402
- * Optional. A list of unique safety settings for blocking unsafe content.
403
- */
404
- safetySettings: z2.array(
405
- z2.object({
406
- category: z2.enum([
407
- "HARM_CATEGORY_UNSPECIFIED",
408
- "HARM_CATEGORY_HATE_SPEECH",
409
- "HARM_CATEGORY_DANGEROUS_CONTENT",
410
- "HARM_CATEGORY_HARASSMENT",
411
- "HARM_CATEGORY_SEXUALLY_EXPLICIT",
412
- "HARM_CATEGORY_CIVIC_INTEGRITY"
413
- ]),
414
- threshold: z2.enum([
415
- "HARM_BLOCK_THRESHOLD_UNSPECIFIED",
416
- "BLOCK_LOW_AND_ABOVE",
417
- "BLOCK_MEDIUM_AND_ABOVE",
418
- "BLOCK_ONLY_HIGH",
419
- "BLOCK_NONE",
420
- "OFF"
421
- ])
422
- })
423
- ).optional(),
424
- threshold: z2.enum([
425
- "HARM_BLOCK_THRESHOLD_UNSPECIFIED",
426
- "BLOCK_LOW_AND_ABOVE",
427
- "BLOCK_MEDIUM_AND_ABOVE",
428
- "BLOCK_ONLY_HIGH",
429
- "BLOCK_NONE",
430
- "OFF"
431
- ]).optional(),
432
- /**
433
- * Optional. Enables timestamp understanding for audio-only files.
434
- *
435
- * https://cloud.google.com/vertex-ai/generative-ai/docs/multimodal/audio-understanding
436
- */
437
- audioTimestamp: z2.boolean().optional(),
438
- /**
439
- * Optional. Defines labels used in billing reports. Available on Vertex AI only.
440
- *
441
- * https://cloud.google.com/vertex-ai/generative-ai/docs/multimodal/add-labels-to-api-calls
442
- */
443
- labels: z2.record(z2.string(), z2.string()).optional(),
444
- /**
445
- * Optional. If specified, the media resolution specified will be used.
446
- *
447
- * https://ai.google.dev/api/generate-content#MediaResolution
448
- */
449
- mediaResolution: z2.enum([
450
- "MEDIA_RESOLUTION_UNSPECIFIED",
451
- "MEDIA_RESOLUTION_LOW",
452
- "MEDIA_RESOLUTION_MEDIUM",
453
- "MEDIA_RESOLUTION_HIGH"
454
- ]).optional(),
455
- /**
456
- * Optional. Configures the image generation aspect ratio for Gemini models.
457
- *
458
- * https://ai.google.dev/gemini-api/docs/image-generation#aspect_ratios
459
- */
460
- imageConfig: z2.object({
461
- aspectRatio: z2.enum([
462
- "1:1",
463
- "2:3",
464
- "3:2",
465
- "3:4",
466
- "4:3",
467
- "4:5",
468
- "5:4",
469
- "9:16",
470
- "16:9",
471
- "21:9",
472
- "1:8",
473
- "8:1",
474
- "1:4",
475
- "4:1"
476
- ]).optional(),
477
- imageSize: z2.enum(["1K", "2K", "4K", "512"]).optional()
478
- }).optional(),
479
- /**
480
- * Optional. Configuration for grounding retrieval.
481
- * Used to provide location context for Google Maps and Google Search grounding.
482
- *
483
- * https://cloud.google.com/vertex-ai/generative-ai/docs/grounding/grounding-with-google-maps
484
- */
485
- retrievalConfig: z2.object({
486
- latLng: z2.object({
487
- latitude: z2.number(),
488
- longitude: z2.number()
489
- }).optional()
490
- }).optional()
491
- })
492
- )
493
- );
494
-
495
- // src/google-prepare-tools.ts
496
- import {
497
- UnsupportedFunctionalityError as UnsupportedFunctionalityError2
498
- } from "@ai-sdk/provider";
499
- function prepareTools({
500
- tools,
501
- toolChoice,
502
- modelId
503
- }) {
504
- var _a;
505
- tools = (tools == null ? void 0 : tools.length) ? tools : void 0;
506
- const toolWarnings = [];
507
- const isLatest = [
508
- "gemini-flash-latest",
509
- "gemini-flash-lite-latest",
510
- "gemini-pro-latest"
511
- ].some((id) => id === modelId);
512
- const isGemini2orNewer = modelId.includes("gemini-2") || modelId.includes("gemini-3") || modelId.includes("nano-banana") || isLatest;
513
- const supportsFileSearch = modelId.includes("gemini-2.5") || modelId.includes("gemini-3");
514
- if (tools == null) {
515
- return { tools: void 0, toolConfig: void 0, toolWarnings };
516
- }
517
- const hasFunctionTools = tools.some((tool) => tool.type === "function");
518
- const hasProviderTools = tools.some((tool) => tool.type === "provider");
519
- if (hasFunctionTools && hasProviderTools) {
520
- toolWarnings.push({
521
- type: "unsupported",
522
- feature: `combination of function and provider-defined tools`
523
- });
524
- }
525
- if (hasProviderTools) {
526
- const googleTools2 = [];
527
- const ProviderTools = tools.filter((tool) => tool.type === "provider");
528
- ProviderTools.forEach((tool) => {
529
- switch (tool.id) {
530
- case "google.google_search":
531
- if (isGemini2orNewer) {
532
- googleTools2.push({ googleSearch: { ...tool.args } });
533
- } else {
534
- toolWarnings.push({
535
- type: "unsupported",
536
- feature: `provider-defined tool ${tool.id}`,
537
- details: "Google Search requires Gemini 2.0 or newer."
538
- });
539
- }
540
- break;
541
- case "google.enterprise_web_search":
542
- if (isGemini2orNewer) {
543
- googleTools2.push({ enterpriseWebSearch: {} });
544
- } else {
545
- toolWarnings.push({
546
- type: "unsupported",
547
- feature: `provider-defined tool ${tool.id}`,
548
- details: "Enterprise Web Search requires Gemini 2.0 or newer."
549
- });
550
- }
551
- break;
552
- case "google.url_context":
553
- if (isGemini2orNewer) {
554
- googleTools2.push({ urlContext: {} });
555
- } else {
556
- toolWarnings.push({
557
- type: "unsupported",
558
- feature: `provider-defined tool ${tool.id}`,
559
- details: "The URL context tool is not supported with other Gemini models than Gemini 2."
560
- });
561
- }
562
- break;
563
- case "google.code_execution":
564
- if (isGemini2orNewer) {
565
- googleTools2.push({ codeExecution: {} });
566
- } else {
567
- toolWarnings.push({
568
- type: "unsupported",
569
- feature: `provider-defined tool ${tool.id}`,
570
- details: "The code execution tools is not supported with other Gemini models than Gemini 2."
571
- });
572
- }
573
- break;
574
- case "google.file_search":
575
- if (supportsFileSearch) {
576
- googleTools2.push({ fileSearch: { ...tool.args } });
577
- } else {
578
- toolWarnings.push({
579
- type: "unsupported",
580
- feature: `provider-defined tool ${tool.id}`,
581
- details: "The file search tool is only supported with Gemini 2.5 models and Gemini 3 models."
582
- });
583
- }
584
- break;
585
- case "google.vertex_rag_store":
586
- if (isGemini2orNewer) {
587
- googleTools2.push({
588
- retrieval: {
589
- vertex_rag_store: {
590
- rag_resources: {
591
- rag_corpus: tool.args.ragCorpus
592
- },
593
- similarity_top_k: tool.args.topK
594
- }
595
- }
596
- });
597
- } else {
598
- toolWarnings.push({
599
- type: "unsupported",
600
- feature: `provider-defined tool ${tool.id}`,
601
- details: "The RAG store tool is not supported with other Gemini models than Gemini 2."
602
- });
603
- }
604
- break;
605
- case "google.google_maps":
606
- if (isGemini2orNewer) {
607
- googleTools2.push({ googleMaps: {} });
608
- } else {
609
- toolWarnings.push({
610
- type: "unsupported",
611
- feature: `provider-defined tool ${tool.id}`,
612
- details: "The Google Maps grounding tool is not supported with Gemini models other than Gemini 2 or newer."
613
- });
614
- }
615
- break;
616
- default:
617
- toolWarnings.push({
618
- type: "unsupported",
619
- feature: `provider-defined tool ${tool.id}`
620
- });
621
- break;
622
- }
623
- });
624
- return {
625
- tools: googleTools2.length > 0 ? googleTools2 : void 0,
626
- toolConfig: void 0,
627
- toolWarnings
628
- };
629
- }
630
- const functionDeclarations = [];
631
- let hasStrictTools = false;
632
- for (const tool of tools) {
633
- switch (tool.type) {
634
- case "function":
635
- functionDeclarations.push({
636
- name: tool.name,
637
- description: (_a = tool.description) != null ? _a : "",
638
- parameters: convertJSONSchemaToOpenAPISchema(tool.inputSchema)
639
- });
640
- if (tool.strict === true) {
641
- hasStrictTools = true;
642
- }
643
- break;
644
- default:
645
- toolWarnings.push({
646
- type: "unsupported",
647
- feature: `function tool ${tool.name}`
648
- });
649
- break;
650
- }
651
- }
652
- if (toolChoice == null) {
653
- return {
654
- tools: [{ functionDeclarations }],
655
- toolConfig: hasStrictTools ? { functionCallingConfig: { mode: "VALIDATED" } } : void 0,
656
- toolWarnings
657
- };
658
- }
659
- const type = toolChoice.type;
660
- switch (type) {
661
- case "auto":
662
- return {
663
- tools: [{ functionDeclarations }],
664
- toolConfig: {
665
- functionCallingConfig: {
666
- mode: hasStrictTools ? "VALIDATED" : "AUTO"
667
- }
668
- },
669
- toolWarnings
670
- };
671
- case "none":
672
- return {
673
- tools: [{ functionDeclarations }],
674
- toolConfig: { functionCallingConfig: { mode: "NONE" } },
675
- toolWarnings
676
- };
677
- case "required":
678
- return {
679
- tools: [{ functionDeclarations }],
680
- toolConfig: {
681
- functionCallingConfig: {
682
- mode: hasStrictTools ? "VALIDATED" : "ANY"
683
- }
684
- },
685
- toolWarnings
686
- };
687
- case "tool":
688
- return {
689
- tools: [{ functionDeclarations }],
690
- toolConfig: {
691
- functionCallingConfig: {
692
- mode: hasStrictTools ? "VALIDATED" : "ANY",
693
- allowedFunctionNames: [toolChoice.toolName]
694
- }
695
- },
696
- toolWarnings
697
- };
698
- default: {
699
- const _exhaustiveCheck = type;
700
- throw new UnsupportedFunctionalityError2({
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 : 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 parseProviderOptions({
768
- provider: providerOptionsName,
769
- providerOptions,
770
- schema: googleLanguageModelOptions
771
- });
772
- if (googleOptions == null && providerOptionsName !== "google") {
773
- googleOptions = await parseProviderOptions({
774
- provider: "google",
775
- providerOptions,
776
- schema: googleLanguageModelOptions
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, _j;
849
- const { args, warnings, providerOptionsName } = await this.getArgs(options);
850
- const mergedHeaders = combineHeaders(
851
- await resolve(this.config.headers),
852
- options.headers
853
- );
854
- const {
855
- responseHeaders,
856
- value: response,
857
- rawValue: rawResponse
858
- } = await postJsonToApi({
859
- url: `${this.config.baseURL}/${getModelPath(
860
- this.modelId
861
- )}:generateContent`,
862
- headers: mergedHeaders,
863
- body: args,
864
- failedResponseHandler: googleFailedResponseHandler,
865
- successfulResponseHandler: 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: (_d = part.codeExecutionResult.output) != null ? _d : ""
894
- }
895
- });
896
- lastCodeExecutionToolCallId = void 0;
897
- } else if ("text" in part && part.text != null) {
898
- const thoughtSignatureMetadata = part.thoughtSignature ? {
899
- [providerOptionsName]: {
900
- thoughtSignature: part.thoughtSignature
901
- }
902
- } : void 0;
903
- if (part.text.length === 0) {
904
- if (thoughtSignatureMetadata != null && content.length > 0) {
905
- const lastContent = content[content.length - 1];
906
- lastContent.providerMetadata = thoughtSignatureMetadata;
907
- }
908
- } else {
909
- content.push({
910
- type: part.thought === true ? "reasoning" : "text",
911
- text: part.text,
912
- providerMetadata: thoughtSignatureMetadata
913
- });
914
- }
915
- } else if ("functionCall" in part) {
916
- content.push({
917
- type: "tool-call",
918
- toolCallId: this.config.generateId(),
919
- toolName: part.functionCall.name,
920
- input: JSON.stringify(part.functionCall.args),
921
- providerMetadata: part.thoughtSignature ? {
922
- [providerOptionsName]: {
923
- thoughtSignature: part.thoughtSignature
924
- }
925
- } : void 0
926
- });
927
- } else if ("inlineData" in part) {
928
- const hasThought = part.thought === true;
929
- const hasThoughtSignature = !!part.thoughtSignature;
930
- content.push({
931
- type: "file",
932
- data: part.inlineData.data,
933
- mediaType: part.inlineData.mimeType,
934
- providerMetadata: hasThought || hasThoughtSignature ? {
935
- [providerOptionsName]: {
936
- ...hasThought ? { thought: true } : {},
937
- ...hasThoughtSignature ? { thoughtSignature: part.thoughtSignature } : {}
938
- }
939
- } : void 0
940
- });
941
- }
942
- }
943
- const sources = (_e = extractSources({
944
- groundingMetadata: candidate.groundingMetadata,
945
- generateId: this.config.generateId
946
- })) != null ? _e : [];
947
- for (const source of sources) {
948
- content.push(source);
949
- }
950
- return {
951
- content,
952
- finishReason: {
953
- unified: mapGoogleGenerativeAIFinishReason({
954
- finishReason: candidate.finishReason,
955
- // Only count client-executed tool calls for finish reason determination.
956
- hasToolCalls: content.some(
957
- (part) => part.type === "tool-call" && !part.providerExecuted
958
- )
959
- }),
960
- raw: (_f = candidate.finishReason) != null ? _f : void 0
961
- },
962
- usage: convertGoogleGenerativeAIUsage(usageMetadata),
963
- warnings,
964
- providerMetadata: {
965
- [providerOptionsName]: {
966
- promptFeedback: (_g = response.promptFeedback) != null ? _g : null,
967
- groundingMetadata: (_h = candidate.groundingMetadata) != null ? _h : null,
968
- urlContextMetadata: (_i = candidate.urlContextMetadata) != null ? _i : null,
969
- safetyRatings: (_j = candidate.safetyRatings) != null ? _j : null,
970
- usageMetadata: usageMetadata != null ? usageMetadata : null
971
- }
972
- },
973
- request: { body: args },
974
- response: {
975
- // TODO timestamp, model id, id
976
- headers: responseHeaders,
977
- body: rawResponse
978
- }
979
- };
980
- }
981
- async doStream(options) {
982
- const { args, warnings, providerOptionsName } = await this.getArgs(options);
983
- const headers = combineHeaders(
984
- await resolve(this.config.headers),
985
- options.headers
986
- );
987
- const { responseHeaders, value: response } = await postJsonToApi({
988
- url: `${this.config.baseURL}/${getModelPath(
989
- this.modelId
990
- )}:streamGenerateContent?alt=sse`,
991
- headers,
992
- body: args,
993
- failedResponseHandler: googleFailedResponseHandler,
994
- successfulResponseHandler: createEventSourceResponseHandler(chunkSchema),
995
- abortSignal: options.abortSignal,
996
- fetch: this.config.fetch
997
- });
998
- let finishReason = {
999
- unified: "other",
1000
- raw: void 0
1001
- };
1002
- let usage = void 0;
1003
- let providerMetadata = void 0;
1004
- let lastGroundingMetadata = null;
1005
- let lastUrlContextMetadata = null;
1006
- const generateId2 = this.config.generateId;
1007
- let hasToolCalls = false;
1008
- let currentTextBlockId = null;
1009
- let currentReasoningBlockId = null;
1010
- let blockCounter = 0;
1011
- const emittedSourceUrls = /* @__PURE__ */ new Set();
1012
- let lastCodeExecutionToolCallId;
1013
- return {
1014
- stream: response.pipeThrough(
1015
- new TransformStream({
1016
- start(controller) {
1017
- controller.enqueue({ type: "stream-start", warnings });
1018
- },
1019
- transform(chunk, controller) {
1020
- var _a, _b, _c, _d, _e, _f;
1021
- if (options.includeRawChunks) {
1022
- controller.enqueue({ type: "raw", rawValue: chunk.rawValue });
1023
- }
1024
- if (!chunk.success) {
1025
- controller.enqueue({ type: "error", error: chunk.error });
1026
- return;
1027
- }
1028
- const value = chunk.value;
1029
- const usageMetadata = value.usageMetadata;
1030
- if (usageMetadata != null) {
1031
- usage = usageMetadata;
1032
- }
1033
- const candidate = (_a = value.candidates) == null ? void 0 : _a[0];
1034
- if (candidate == null) {
1035
- return;
1036
- }
1037
- const content = candidate.content;
1038
- if (candidate.groundingMetadata != null) {
1039
- lastGroundingMetadata = candidate.groundingMetadata;
1040
- }
1041
- if (candidate.urlContextMetadata != null) {
1042
- lastUrlContextMetadata = candidate.urlContextMetadata;
1043
- }
1044
- const sources = extractSources({
1045
- groundingMetadata: candidate.groundingMetadata,
1046
- generateId: generateId2
1047
- });
1048
- if (sources != null) {
1049
- for (const source of sources) {
1050
- if (source.sourceType === "url" && !emittedSourceUrls.has(source.url)) {
1051
- emittedSourceUrls.add(source.url);
1052
- controller.enqueue(source);
1053
- }
1054
- }
1055
- }
1056
- if (content != null) {
1057
- const parts = (_b = content.parts) != null ? _b : [];
1058
- for (const part of parts) {
1059
- if ("executableCode" in part && ((_c = part.executableCode) == null ? void 0 : _c.code)) {
1060
- const toolCallId = generateId2();
1061
- lastCodeExecutionToolCallId = toolCallId;
1062
- controller.enqueue({
1063
- type: "tool-call",
1064
- toolCallId,
1065
- toolName: "code_execution",
1066
- input: JSON.stringify(part.executableCode),
1067
- providerExecuted: true
1068
- });
1069
- } else if ("codeExecutionResult" in part && part.codeExecutionResult) {
1070
- const toolCallId = lastCodeExecutionToolCallId;
1071
- if (toolCallId) {
1072
- controller.enqueue({
1073
- type: "tool-result",
1074
- toolCallId,
1075
- toolName: "code_execution",
1076
- result: {
1077
- outcome: part.codeExecutionResult.outcome,
1078
- output: (_d = part.codeExecutionResult.output) != null ? _d : ""
1079
- }
1080
- });
1081
- lastCodeExecutionToolCallId = void 0;
1082
- }
1083
- } else if ("text" in part && part.text != null) {
1084
- const thoughtSignatureMetadata = part.thoughtSignature ? {
1085
- [providerOptionsName]: {
1086
- thoughtSignature: part.thoughtSignature
1087
- }
1088
- } : void 0;
1089
- if (part.text.length === 0) {
1090
- if (thoughtSignatureMetadata != null && currentTextBlockId !== null) {
1091
- controller.enqueue({
1092
- type: "text-delta",
1093
- id: currentTextBlockId,
1094
- delta: "",
1095
- providerMetadata: thoughtSignatureMetadata
1096
- });
1097
- }
1098
- } else if (part.thought === true) {
1099
- if (currentTextBlockId !== null) {
1100
- controller.enqueue({
1101
- type: "text-end",
1102
- id: currentTextBlockId
1103
- });
1104
- currentTextBlockId = null;
1105
- }
1106
- if (currentReasoningBlockId === null) {
1107
- currentReasoningBlockId = String(blockCounter++);
1108
- controller.enqueue({
1109
- type: "reasoning-start",
1110
- id: currentReasoningBlockId,
1111
- providerMetadata: thoughtSignatureMetadata
1112
- });
1113
- }
1114
- controller.enqueue({
1115
- type: "reasoning-delta",
1116
- id: currentReasoningBlockId,
1117
- delta: part.text,
1118
- providerMetadata: thoughtSignatureMetadata
1119
- });
1120
- } else {
1121
- if (currentReasoningBlockId !== null) {
1122
- controller.enqueue({
1123
- type: "reasoning-end",
1124
- id: currentReasoningBlockId
1125
- });
1126
- currentReasoningBlockId = null;
1127
- }
1128
- if (currentTextBlockId === null) {
1129
- currentTextBlockId = String(blockCounter++);
1130
- controller.enqueue({
1131
- type: "text-start",
1132
- id: currentTextBlockId,
1133
- providerMetadata: thoughtSignatureMetadata
1134
- });
1135
- }
1136
- controller.enqueue({
1137
- type: "text-delta",
1138
- id: currentTextBlockId,
1139
- delta: part.text,
1140
- providerMetadata: thoughtSignatureMetadata
1141
- });
1142
- }
1143
- } else if ("inlineData" in part) {
1144
- if (currentTextBlockId !== null) {
1145
- controller.enqueue({
1146
- type: "text-end",
1147
- id: currentTextBlockId
1148
- });
1149
- currentTextBlockId = null;
1150
- }
1151
- if (currentReasoningBlockId !== null) {
1152
- controller.enqueue({
1153
- type: "reasoning-end",
1154
- id: currentReasoningBlockId
1155
- });
1156
- currentReasoningBlockId = null;
1157
- }
1158
- const hasThought = part.thought === true;
1159
- const hasThoughtSignature = !!part.thoughtSignature;
1160
- const fileMeta = hasThought || hasThoughtSignature ? {
1161
- [providerOptionsName]: {
1162
- ...hasThought ? { thought: true } : {},
1163
- ...hasThoughtSignature ? { thoughtSignature: part.thoughtSignature } : {}
1164
- }
1165
- } : void 0;
1166
- controller.enqueue({
1167
- type: "file",
1168
- mediaType: part.inlineData.mimeType,
1169
- data: part.inlineData.data,
1170
- providerMetadata: fileMeta
1171
- });
1172
- }
1173
- }
1174
- const toolCallDeltas = getToolCallsFromParts({
1175
- parts: content.parts,
1176
- generateId: generateId2,
1177
- providerOptionsName
1178
- });
1179
- if (toolCallDeltas != null) {
1180
- for (const toolCall of toolCallDeltas) {
1181
- controller.enqueue({
1182
- type: "tool-input-start",
1183
- id: toolCall.toolCallId,
1184
- toolName: toolCall.toolName,
1185
- providerMetadata: toolCall.providerMetadata
1186
- });
1187
- controller.enqueue({
1188
- type: "tool-input-delta",
1189
- id: toolCall.toolCallId,
1190
- delta: toolCall.args,
1191
- providerMetadata: toolCall.providerMetadata
1192
- });
1193
- controller.enqueue({
1194
- type: "tool-input-end",
1195
- id: toolCall.toolCallId,
1196
- providerMetadata: toolCall.providerMetadata
1197
- });
1198
- controller.enqueue({
1199
- type: "tool-call",
1200
- toolCallId: toolCall.toolCallId,
1201
- toolName: toolCall.toolName,
1202
- input: toolCall.args,
1203
- providerMetadata: toolCall.providerMetadata
1204
- });
1205
- hasToolCalls = true;
1206
- }
1207
- }
1208
- }
1209
- if (candidate.finishReason != null) {
1210
- finishReason = {
1211
- unified: mapGoogleGenerativeAIFinishReason({
1212
- finishReason: candidate.finishReason,
1213
- hasToolCalls
1214
- }),
1215
- raw: candidate.finishReason
1216
- };
1217
- providerMetadata = {
1218
- [providerOptionsName]: {
1219
- promptFeedback: (_e = value.promptFeedback) != null ? _e : null,
1220
- groundingMetadata: lastGroundingMetadata,
1221
- urlContextMetadata: lastUrlContextMetadata,
1222
- safetyRatings: (_f = candidate.safetyRatings) != null ? _f : null
1223
- }
1224
- };
1225
- if (usageMetadata != null) {
1226
- providerMetadata[providerOptionsName].usageMetadata = usageMetadata;
1227
- }
1228
- }
1229
- },
1230
- flush(controller) {
1231
- if (currentTextBlockId !== null) {
1232
- controller.enqueue({
1233
- type: "text-end",
1234
- id: currentTextBlockId
1235
- });
1236
- }
1237
- if (currentReasoningBlockId !== null) {
1238
- controller.enqueue({
1239
- type: "reasoning-end",
1240
- id: currentReasoningBlockId
1241
- });
1242
- }
1243
- controller.enqueue({
1244
- type: "finish",
1245
- finishReason,
1246
- usage: convertGoogleGenerativeAIUsage(usage),
1247
- providerMetadata
1248
- });
1249
- }
1250
- })
1251
- ),
1252
- response: { headers: responseHeaders },
1253
- request: { body: args }
1254
- };
1255
- }
1256
- };
1257
- function getToolCallsFromParts({
1258
- parts,
1259
- generateId: generateId2,
1260
- providerOptionsName
1261
- }) {
1262
- const functionCallParts = parts == null ? void 0 : parts.filter(
1263
- (part) => "functionCall" in part
1264
- );
1265
- return functionCallParts == null || functionCallParts.length === 0 ? void 0 : functionCallParts.map((part) => ({
1266
- type: "tool-call",
1267
- toolCallId: generateId2(),
1268
- toolName: part.functionCall.name,
1269
- args: JSON.stringify(part.functionCall.args),
1270
- providerMetadata: part.thoughtSignature ? {
1271
- [providerOptionsName]: {
1272
- thoughtSignature: part.thoughtSignature
1273
- }
1274
- } : void 0
1275
- }));
1276
- }
1277
- function extractSources({
1278
- groundingMetadata,
1279
- generateId: generateId2
1280
- }) {
1281
- var _a, _b, _c, _d, _e, _f;
1282
- if (!(groundingMetadata == null ? void 0 : groundingMetadata.groundingChunks)) {
1283
- return void 0;
1284
- }
1285
- const sources = [];
1286
- for (const chunk of groundingMetadata.groundingChunks) {
1287
- if (chunk.web != null) {
1288
- sources.push({
1289
- type: "source",
1290
- sourceType: "url",
1291
- id: generateId2(),
1292
- url: chunk.web.uri,
1293
- title: (_a = chunk.web.title) != null ? _a : void 0
1294
- });
1295
- } else if (chunk.image != null) {
1296
- sources.push({
1297
- type: "source",
1298
- sourceType: "url",
1299
- id: generateId2(),
1300
- // Google requires attribution to the source URI, not the actual image URI.
1301
- // TODO: add another type in v7 to allow both the image and source URL to be included separately
1302
- url: chunk.image.sourceUri,
1303
- title: (_b = chunk.image.title) != null ? _b : void 0
1304
- });
1305
- } else if (chunk.retrievedContext != null) {
1306
- const uri = chunk.retrievedContext.uri;
1307
- const fileSearchStore = chunk.retrievedContext.fileSearchStore;
1308
- if (uri && (uri.startsWith("http://") || uri.startsWith("https://"))) {
1309
- sources.push({
1310
- type: "source",
1311
- sourceType: "url",
1312
- id: generateId2(),
1313
- url: uri,
1314
- title: (_c = chunk.retrievedContext.title) != null ? _c : void 0
1315
- });
1316
- } else if (uri) {
1317
- const title = (_d = chunk.retrievedContext.title) != null ? _d : "Unknown Document";
1318
- let mediaType = "application/octet-stream";
1319
- let filename = void 0;
1320
- if (uri.endsWith(".pdf")) {
1321
- mediaType = "application/pdf";
1322
- filename = uri.split("/").pop();
1323
- } else if (uri.endsWith(".txt")) {
1324
- mediaType = "text/plain";
1325
- filename = uri.split("/").pop();
1326
- } else if (uri.endsWith(".docx")) {
1327
- mediaType = "application/vnd.openxmlformats-officedocument.wordprocessingml.document";
1328
- filename = uri.split("/").pop();
1329
- } else if (uri.endsWith(".doc")) {
1330
- mediaType = "application/msword";
1331
- filename = uri.split("/").pop();
1332
- } else if (uri.match(/\.(md|markdown)$/)) {
1333
- mediaType = "text/markdown";
1334
- filename = uri.split("/").pop();
1335
- } else {
1336
- filename = uri.split("/").pop();
1337
- }
1338
- sources.push({
1339
- type: "source",
1340
- sourceType: "document",
1341
- id: generateId2(),
1342
- mediaType,
1343
- title,
1344
- filename
1345
- });
1346
- } else if (fileSearchStore) {
1347
- const title = (_e = chunk.retrievedContext.title) != null ? _e : "Unknown Document";
1348
- sources.push({
1349
- type: "source",
1350
- sourceType: "document",
1351
- id: generateId2(),
1352
- mediaType: "application/octet-stream",
1353
- title,
1354
- filename: fileSearchStore.split("/").pop()
1355
- });
1356
- }
1357
- } else if (chunk.maps != null) {
1358
- if (chunk.maps.uri) {
1359
- sources.push({
1360
- type: "source",
1361
- sourceType: "url",
1362
- id: generateId2(),
1363
- url: chunk.maps.uri,
1364
- title: (_f = chunk.maps.title) != null ? _f : void 0
1365
- });
1366
- }
1367
- }
1368
- }
1369
- return sources.length > 0 ? sources : void 0;
1370
- }
1371
- var getGroundingMetadataSchema = () => z3.object({
1372
- webSearchQueries: z3.array(z3.string()).nullish(),
1373
- imageSearchQueries: z3.array(z3.string()).nullish(),
1374
- retrievalQueries: z3.array(z3.string()).nullish(),
1375
- searchEntryPoint: z3.object({ renderedContent: z3.string() }).nullish(),
1376
- groundingChunks: z3.array(
1377
- z3.object({
1378
- web: z3.object({ uri: z3.string(), title: z3.string().nullish() }).nullish(),
1379
- image: z3.object({
1380
- sourceUri: z3.string(),
1381
- imageUri: z3.string(),
1382
- title: z3.string().nullish(),
1383
- domain: z3.string().nullish()
1384
- }).nullish(),
1385
- retrievedContext: z3.object({
1386
- uri: z3.string().nullish(),
1387
- title: z3.string().nullish(),
1388
- text: z3.string().nullish(),
1389
- fileSearchStore: z3.string().nullish()
1390
- }).nullish(),
1391
- maps: z3.object({
1392
- uri: z3.string().nullish(),
1393
- title: z3.string().nullish(),
1394
- text: z3.string().nullish(),
1395
- placeId: z3.string().nullish()
1396
- }).nullish()
1397
- })
1398
- ).nullish(),
1399
- groundingSupports: z3.array(
1400
- z3.object({
1401
- segment: z3.object({
1402
- startIndex: z3.number().nullish(),
1403
- endIndex: z3.number().nullish(),
1404
- text: z3.string().nullish()
1405
- }).nullish(),
1406
- segment_text: z3.string().nullish(),
1407
- groundingChunkIndices: z3.array(z3.number()).nullish(),
1408
- supportChunkIndices: z3.array(z3.number()).nullish(),
1409
- confidenceScores: z3.array(z3.number()).nullish(),
1410
- confidenceScore: z3.array(z3.number()).nullish()
1411
- })
1412
- ).nullish(),
1413
- retrievalMetadata: z3.union([
1414
- z3.object({
1415
- webDynamicRetrievalScore: z3.number()
1416
- }),
1417
- z3.object({})
1418
- ]).nullish()
1419
- });
1420
- var getContentSchema = () => z3.object({
1421
- parts: z3.array(
1422
- z3.union([
1423
- // note: order matters since text can be fully empty
1424
- z3.object({
1425
- functionCall: z3.object({
1426
- name: z3.string(),
1427
- args: z3.unknown()
1428
- }),
1429
- thoughtSignature: z3.string().nullish()
1430
- }),
1431
- z3.object({
1432
- inlineData: z3.object({
1433
- mimeType: z3.string(),
1434
- data: z3.string()
1435
- }),
1436
- thought: z3.boolean().nullish(),
1437
- thoughtSignature: z3.string().nullish()
1438
- }),
1439
- z3.object({
1440
- executableCode: z3.object({
1441
- language: z3.string(),
1442
- code: z3.string()
1443
- }).nullish(),
1444
- codeExecutionResult: z3.object({
1445
- outcome: z3.string(),
1446
- output: z3.string().nullish()
1447
- }).nullish(),
1448
- text: z3.string().nullish(),
1449
- thought: z3.boolean().nullish(),
1450
- thoughtSignature: z3.string().nullish()
1451
- })
1452
- ])
1453
- ).nullish()
1454
- });
1455
- var getSafetyRatingSchema = () => z3.object({
1456
- category: z3.string().nullish(),
1457
- probability: z3.string().nullish(),
1458
- probabilityScore: z3.number().nullish(),
1459
- severity: z3.string().nullish(),
1460
- severityScore: z3.number().nullish(),
1461
- blocked: z3.boolean().nullish()
1462
- });
1463
- var usageSchema = z3.object({
1464
- cachedContentTokenCount: z3.number().nullish(),
1465
- thoughtsTokenCount: z3.number().nullish(),
1466
- promptTokenCount: z3.number().nullish(),
1467
- candidatesTokenCount: z3.number().nullish(),
1468
- totalTokenCount: z3.number().nullish(),
1469
- // https://cloud.google.com/vertex-ai/generative-ai/docs/reference/rest/v1/GenerateContentResponse#TrafficType
1470
- trafficType: z3.string().nullish()
1471
- });
1472
- var getUrlContextMetadataSchema = () => z3.object({
1473
- urlMetadata: z3.array(
1474
- z3.object({
1475
- retrievedUrl: z3.string(),
1476
- urlRetrievalStatus: z3.string()
1477
- })
1478
- ).nullish()
1479
- });
1480
- var responseSchema = lazySchema3(
1481
- () => zodSchema3(
1482
- z3.object({
1483
- candidates: z3.array(
1484
- z3.object({
1485
- content: getContentSchema().nullish().or(z3.object({}).strict()),
1486
- finishReason: z3.string().nullish(),
1487
- safetyRatings: z3.array(getSafetyRatingSchema()).nullish(),
1488
- groundingMetadata: getGroundingMetadataSchema().nullish(),
1489
- urlContextMetadata: getUrlContextMetadataSchema().nullish()
1490
- })
1491
- ),
1492
- usageMetadata: usageSchema.nullish(),
1493
- promptFeedback: z3.object({
1494
- blockReason: z3.string().nullish(),
1495
- safetyRatings: z3.array(getSafetyRatingSchema()).nullish()
1496
- }).nullish()
1497
- })
1498
- )
1499
- );
1500
- var chunkSchema = lazySchema3(
1501
- () => zodSchema3(
1502
- z3.object({
1503
- candidates: z3.array(
1504
- z3.object({
1505
- content: getContentSchema().nullish(),
1506
- finishReason: z3.string().nullish(),
1507
- safetyRatings: z3.array(getSafetyRatingSchema()).nullish(),
1508
- groundingMetadata: getGroundingMetadataSchema().nullish(),
1509
- urlContextMetadata: getUrlContextMetadataSchema().nullish()
1510
- })
1511
- ).nullish(),
1512
- usageMetadata: usageSchema.nullish(),
1513
- promptFeedback: z3.object({
1514
- blockReason: z3.string().nullish(),
1515
- safetyRatings: z3.array(getSafetyRatingSchema()).nullish()
1516
- }).nullish()
1517
- })
1518
- )
1519
- );
1520
-
1521
- // src/tool/code-execution.ts
1522
- import { createProviderToolFactoryWithOutputSchema } from "@ai-sdk/provider-utils";
1523
- import { z as z4 } from "zod/v4";
1524
- var codeExecution = createProviderToolFactoryWithOutputSchema({
1525
- id: "google.code_execution",
1526
- inputSchema: z4.object({
1527
- language: z4.string().describe("The programming language of the code."),
1528
- code: z4.string().describe("The code to be executed.")
1529
- }),
1530
- outputSchema: z4.object({
1531
- outcome: z4.string().describe('The outcome of the execution (e.g., "OUTCOME_OK").'),
1532
- output: z4.string().describe("The output from the code execution.")
1533
- })
1534
- });
1535
-
1536
- // src/tool/enterprise-web-search.ts
1537
- import {
1538
- createProviderToolFactory,
1539
- lazySchema as lazySchema4,
1540
- zodSchema as zodSchema4
1541
- } from "@ai-sdk/provider-utils";
1542
- import { z as z5 } from "zod/v4";
1543
- var enterpriseWebSearch = createProviderToolFactory({
1544
- id: "google.enterprise_web_search",
1545
- inputSchema: lazySchema4(() => zodSchema4(z5.object({})))
1546
- });
1547
-
1548
- // src/tool/file-search.ts
1549
- import {
1550
- createProviderToolFactory as createProviderToolFactory2,
1551
- lazySchema as lazySchema5,
1552
- zodSchema as zodSchema5
1553
- } from "@ai-sdk/provider-utils";
1554
- import { z as z6 } from "zod/v4";
1555
- var fileSearchArgsBaseSchema = z6.object({
1556
- /** The names of the file_search_stores to retrieve from.
1557
- * Example: `fileSearchStores/my-file-search-store-123`
1558
- */
1559
- fileSearchStoreNames: z6.array(z6.string()).describe(
1560
- "The names of the file_search_stores to retrieve from. Example: `fileSearchStores/my-file-search-store-123`"
1561
- ),
1562
- /** The number of file search retrieval chunks to retrieve. */
1563
- topK: z6.number().int().positive().describe("The number of file search retrieval chunks to retrieve.").optional(),
1564
- /** Metadata filter to apply to the file search retrieval documents.
1565
- * See https://google.aip.dev/160 for the syntax of the filter expression.
1566
- */
1567
- metadataFilter: z6.string().describe(
1568
- "Metadata filter to apply to the file search retrieval documents. See https://google.aip.dev/160 for the syntax of the filter expression."
1569
- ).optional()
1570
- }).passthrough();
1571
- var fileSearchArgsSchema = lazySchema5(
1572
- () => zodSchema5(fileSearchArgsBaseSchema)
1573
- );
1574
- var fileSearch = createProviderToolFactory2({
1575
- id: "google.file_search",
1576
- inputSchema: fileSearchArgsSchema
1577
- });
1578
-
1579
- // src/tool/google-maps.ts
1580
- import {
1581
- createProviderToolFactory as createProviderToolFactory3,
1582
- lazySchema as lazySchema6,
1583
- zodSchema as zodSchema6
1584
- } from "@ai-sdk/provider-utils";
1585
- import { z as z7 } from "zod/v4";
1586
- var googleMaps = createProviderToolFactory3({
1587
- id: "google.google_maps",
1588
- inputSchema: lazySchema6(() => zodSchema6(z7.object({})))
1589
- });
1590
-
1591
- // src/tool/google-search.ts
1592
- import {
1593
- createProviderToolFactory as createProviderToolFactory4,
1594
- lazySchema as lazySchema7,
1595
- zodSchema as zodSchema7
1596
- } from "@ai-sdk/provider-utils";
1597
- import { z as z8 } from "zod/v4";
1598
- var googleSearchToolArgsBaseSchema = z8.object({
1599
- searchTypes: z8.object({
1600
- webSearch: z8.object({}).optional(),
1601
- imageSearch: z8.object({}).optional()
1602
- }).optional(),
1603
- timeRangeFilter: z8.object({
1604
- startTime: z8.string(),
1605
- endTime: z8.string()
1606
- }).optional()
1607
- }).passthrough();
1608
- var googleSearchToolArgsSchema = lazySchema7(
1609
- () => zodSchema7(googleSearchToolArgsBaseSchema)
1610
- );
1611
- var googleSearch = createProviderToolFactory4(
1612
- {
1613
- id: "google.google_search",
1614
- inputSchema: googleSearchToolArgsSchema
1615
- }
1616
- );
1617
-
1618
- // src/tool/url-context.ts
1619
- import {
1620
- createProviderToolFactory as createProviderToolFactory5,
1621
- lazySchema as lazySchema8,
1622
- zodSchema as zodSchema8
1623
- } from "@ai-sdk/provider-utils";
1624
- import { z as z9 } from "zod/v4";
1625
- var urlContext = createProviderToolFactory5({
1626
- id: "google.url_context",
1627
- inputSchema: lazySchema8(() => zodSchema8(z9.object({})))
1628
- });
1629
-
1630
- // src/tool/vertex-rag-store.ts
1631
- import { createProviderToolFactory as createProviderToolFactory6 } from "@ai-sdk/provider-utils";
1632
- import { z as z10 } from "zod/v4";
1633
- var vertexRagStore = createProviderToolFactory6({
1634
- id: "google.vertex_rag_store",
1635
- inputSchema: z10.object({
1636
- ragCorpus: z10.string(),
1637
- topK: z10.number().optional()
1638
- })
1639
- });
1640
-
1641
- // src/google-tools.ts
1642
- var googleTools = {
1643
- /**
1644
- * Creates a Google search tool that gives Google direct access to real-time web content.
1645
- * Must have name "google_search".
1646
- */
1647
- googleSearch,
1648
- /**
1649
- * Creates an Enterprise Web Search tool for grounding responses using a compliance-focused web index.
1650
- * Designed for highly-regulated industries (finance, healthcare, public sector).
1651
- * Does not log customer data and supports VPC service controls.
1652
- * Must have name "enterprise_web_search".
1653
- *
1654
- * @note Only available on Vertex AI. Requires Gemini 2.0 or newer.
1655
- *
1656
- * @see https://cloud.google.com/vertex-ai/generative-ai/docs/grounding/web-grounding-enterprise
1657
- */
1658
- enterpriseWebSearch,
1659
- /**
1660
- * Creates a Google Maps grounding tool that gives the model access to Google Maps data.
1661
- * Must have name "google_maps".
1662
- *
1663
- * @see https://ai.google.dev/gemini-api/docs/maps-grounding
1664
- * @see https://cloud.google.com/vertex-ai/generative-ai/docs/grounding/grounding-with-google-maps
1665
- */
1666
- googleMaps,
1667
- /**
1668
- * Creates a URL context tool that gives Google direct access to real-time web content.
1669
- * Must have name "url_context".
1670
- */
1671
- urlContext,
1672
- /**
1673
- * Enables Retrieval Augmented Generation (RAG) via the Gemini File Search tool.
1674
- * Must have name "file_search".
1675
- *
1676
- * @param fileSearchStoreNames - Fully-qualified File Search store resource names.
1677
- * @param metadataFilter - Optional filter expression to restrict the files that can be retrieved.
1678
- * @param topK - Optional result limit for the number of chunks returned from File Search.
1679
- *
1680
- * @see https://ai.google.dev/gemini-api/docs/file-search
1681
- */
1682
- fileSearch,
1683
- /**
1684
- * A tool that enables the model to generate and run Python code.
1685
- * Must have name "code_execution".
1686
- *
1687
- * @note Ensure the selected model supports Code Execution.
1688
- * Multi-tool usage with the code execution tool is typically compatible with Gemini >=2 models.
1689
- *
1690
- * @see https://ai.google.dev/gemini-api/docs/code-execution (Google AI)
1691
- * @see https://cloud.google.com/vertex-ai/generative-ai/docs/model-reference/code-execution-api (Vertex AI)
1692
- */
1693
- codeExecution,
1694
- /**
1695
- * Creates a Vertex RAG Store tool that enables the model to perform RAG searches against a Vertex RAG Store.
1696
- * Must have name "vertex_rag_store".
1697
- */
1698
- vertexRagStore
1699
- };
1700
- export {
1701
- GoogleGenerativeAILanguageModel,
1702
- getGroundingMetadataSchema,
1703
- getUrlContextMetadataSchema,
1704
- googleTools
1705
- };
1706
- //# sourceMappingURL=index.mjs.map