@ai-sdk/google 4.0.0-beta.36 → 4.0.0-beta.38

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,2458 +0,0 @@
1
- // src/google-generative-ai-language-model.ts
2
- import {
3
- combineHeaders,
4
- createEventSourceResponseHandler,
5
- createJsonResponseHandler,
6
- generateId,
7
- isCustomReasoning,
8
- lazySchema as lazySchema3,
9
- mapReasoningToProviderBudget,
10
- mapReasoningToProviderEffort,
11
- parseProviderOptions,
12
- postJsonToApi,
13
- resolve,
14
- zodSchema as zodSchema3
15
- } from "@ai-sdk/provider-utils";
16
- import { z as z3 } from "zod/v4";
17
-
18
- // src/convert-google-generative-ai-usage.ts
19
- function convertGoogleGenerativeAIUsage(usage) {
20
- var _a, _b, _c, _d;
21
- if (usage == null) {
22
- return {
23
- inputTokens: {
24
- total: void 0,
25
- noCache: void 0,
26
- cacheRead: void 0,
27
- cacheWrite: void 0
28
- },
29
- outputTokens: {
30
- total: void 0,
31
- text: void 0,
32
- reasoning: void 0
33
- },
34
- raw: void 0
35
- };
36
- }
37
- const promptTokens = (_a = usage.promptTokenCount) != null ? _a : 0;
38
- const candidatesTokens = (_b = usage.candidatesTokenCount) != null ? _b : 0;
39
- const cachedContentTokens = (_c = usage.cachedContentTokenCount) != null ? _c : 0;
40
- const thoughtsTokens = (_d = usage.thoughtsTokenCount) != null ? _d : 0;
41
- return {
42
- inputTokens: {
43
- total: promptTokens,
44
- noCache: promptTokens - cachedContentTokens,
45
- cacheRead: cachedContentTokens,
46
- cacheWrite: void 0
47
- },
48
- outputTokens: {
49
- total: candidatesTokens + thoughtsTokens,
50
- text: candidatesTokens,
51
- reasoning: thoughtsTokens
52
- },
53
- raw: usage
54
- };
55
- }
56
-
57
- // src/convert-json-schema-to-openapi-schema.ts
58
- function convertJSONSchemaToOpenAPISchema(jsonSchema, isRoot = true) {
59
- if (jsonSchema == null) {
60
- return void 0;
61
- }
62
- if (isEmptyObjectSchema(jsonSchema)) {
63
- if (isRoot) {
64
- return void 0;
65
- }
66
- if (typeof jsonSchema === "object" && jsonSchema.description) {
67
- return { type: "object", description: jsonSchema.description };
68
- }
69
- return { type: "object" };
70
- }
71
- if (typeof jsonSchema === "boolean") {
72
- return { type: "boolean", properties: {} };
73
- }
74
- const {
75
- type,
76
- description,
77
- required,
78
- properties,
79
- items,
80
- allOf,
81
- anyOf,
82
- oneOf,
83
- format,
84
- const: constValue,
85
- minLength,
86
- enum: enumValues
87
- } = jsonSchema;
88
- const result = {};
89
- if (description) result.description = description;
90
- if (required) result.required = required;
91
- if (format) result.format = format;
92
- if (constValue !== void 0) {
93
- result.enum = [constValue];
94
- }
95
- if (type) {
96
- if (Array.isArray(type)) {
97
- const hasNull = type.includes("null");
98
- const nonNullTypes = type.filter((t) => t !== "null");
99
- if (nonNullTypes.length === 0) {
100
- result.type = "null";
101
- } else {
102
- result.anyOf = nonNullTypes.map((t) => ({ type: t }));
103
- if (hasNull) {
104
- result.nullable = true;
105
- }
106
- }
107
- } else {
108
- result.type = type;
109
- }
110
- }
111
- if (enumValues !== void 0) {
112
- result.enum = enumValues;
113
- }
114
- if (properties != null) {
115
- result.properties = Object.entries(properties).reduce(
116
- (acc, [key, value]) => {
117
- acc[key] = convertJSONSchemaToOpenAPISchema(value, false);
118
- return acc;
119
- },
120
- {}
121
- );
122
- }
123
- if (items) {
124
- result.items = Array.isArray(items) ? items.map((item) => convertJSONSchemaToOpenAPISchema(item, false)) : convertJSONSchemaToOpenAPISchema(items, false);
125
- }
126
- if (allOf) {
127
- result.allOf = allOf.map(
128
- (item) => convertJSONSchemaToOpenAPISchema(item, false)
129
- );
130
- }
131
- if (anyOf) {
132
- if (anyOf.some(
133
- (schema) => typeof schema === "object" && (schema == null ? void 0 : schema.type) === "null"
134
- )) {
135
- const nonNullSchemas = anyOf.filter(
136
- (schema) => !(typeof schema === "object" && (schema == null ? void 0 : schema.type) === "null")
137
- );
138
- if (nonNullSchemas.length === 1) {
139
- const converted = convertJSONSchemaToOpenAPISchema(
140
- nonNullSchemas[0],
141
- false
142
- );
143
- if (typeof converted === "object") {
144
- result.nullable = true;
145
- Object.assign(result, converted);
146
- }
147
- } else {
148
- result.anyOf = nonNullSchemas.map(
149
- (item) => convertJSONSchemaToOpenAPISchema(item, false)
150
- );
151
- result.nullable = true;
152
- }
153
- } else {
154
- result.anyOf = anyOf.map(
155
- (item) => convertJSONSchemaToOpenAPISchema(item, false)
156
- );
157
- }
158
- }
159
- if (oneOf) {
160
- result.oneOf = oneOf.map(
161
- (item) => convertJSONSchemaToOpenAPISchema(item, false)
162
- );
163
- }
164
- if (minLength !== void 0) {
165
- result.minLength = minLength;
166
- }
167
- return result;
168
- }
169
- function isEmptyObjectSchema(jsonSchema) {
170
- return jsonSchema != null && typeof jsonSchema === "object" && jsonSchema.type === "object" && (jsonSchema.properties == null || Object.keys(jsonSchema.properties).length === 0) && !jsonSchema.additionalProperties;
171
- }
172
-
173
- // src/convert-to-google-generative-ai-messages.ts
174
- import {
175
- UnsupportedFunctionalityError
176
- } from "@ai-sdk/provider";
177
- import {
178
- convertToBase64,
179
- isProviderReference,
180
- resolveProviderReference
181
- } from "@ai-sdk/provider-utils";
182
- var dataUrlRegex = /^data:([^;,]+);base64,(.+)$/s;
183
- function parseBase64DataUrl(value) {
184
- const match = dataUrlRegex.exec(value);
185
- if (match == null) {
186
- return void 0;
187
- }
188
- return {
189
- mediaType: match[1],
190
- data: match[2]
191
- };
192
- }
193
- function convertUrlToolResultPart(url) {
194
- const parsedDataUrl = parseBase64DataUrl(url);
195
- if (parsedDataUrl == null) {
196
- return void 0;
197
- }
198
- return {
199
- inlineData: {
200
- mimeType: parsedDataUrl.mediaType,
201
- data: parsedDataUrl.data
202
- }
203
- };
204
- }
205
- function appendToolResultParts(parts, toolName, outputValue) {
206
- const functionResponseParts = [];
207
- const responseTextParts = [];
208
- for (const contentPart of outputValue) {
209
- switch (contentPart.type) {
210
- case "text": {
211
- responseTextParts.push(contentPart.text);
212
- break;
213
- }
214
- case "image-data":
215
- case "file-data": {
216
- functionResponseParts.push({
217
- inlineData: {
218
- mimeType: contentPart.mediaType,
219
- data: contentPart.data
220
- }
221
- });
222
- break;
223
- }
224
- case "image-url":
225
- case "file-url": {
226
- const functionResponsePart = convertUrlToolResultPart(
227
- contentPart.url
228
- );
229
- if (functionResponsePart != null) {
230
- functionResponseParts.push(functionResponsePart);
231
- } else {
232
- responseTextParts.push(JSON.stringify(contentPart));
233
- }
234
- break;
235
- }
236
- default: {
237
- responseTextParts.push(JSON.stringify(contentPart));
238
- break;
239
- }
240
- }
241
- }
242
- parts.push({
243
- functionResponse: {
244
- name: toolName,
245
- response: {
246
- name: toolName,
247
- content: responseTextParts.length > 0 ? responseTextParts.join("\n") : "Tool executed successfully."
248
- },
249
- ...functionResponseParts.length > 0 ? { parts: functionResponseParts } : {}
250
- }
251
- });
252
- }
253
- function appendLegacyToolResultParts(parts, toolName, outputValue) {
254
- for (const contentPart of outputValue) {
255
- switch (contentPart.type) {
256
- case "text":
257
- parts.push({
258
- functionResponse: {
259
- name: toolName,
260
- response: {
261
- name: toolName,
262
- content: contentPart.text
263
- }
264
- }
265
- });
266
- break;
267
- case "image-data":
268
- parts.push(
269
- {
270
- inlineData: {
271
- mimeType: String(contentPart.mediaType),
272
- data: String(contentPart.data)
273
- }
274
- },
275
- {
276
- text: "Tool executed successfully and returned this image as a response"
277
- }
278
- );
279
- break;
280
- default:
281
- parts.push({ text: JSON.stringify(contentPart) });
282
- break;
283
- }
284
- }
285
- }
286
- function convertToGoogleGenerativeAIMessages(prompt, options) {
287
- var _a, _b, _c, _d, _e, _f, _g, _h;
288
- const systemInstructionParts = [];
289
- const contents = [];
290
- let systemMessagesAllowed = true;
291
- const isGemmaModel = (_a = options == null ? void 0 : options.isGemmaModel) != null ? _a : false;
292
- const providerOptionsName = (_b = options == null ? void 0 : options.providerOptionsName) != null ? _b : "google";
293
- const supportsFunctionResponseParts = (_c = options == null ? void 0 : options.supportsFunctionResponseParts) != null ? _c : true;
294
- for (const { role, content } of prompt) {
295
- switch (role) {
296
- case "system": {
297
- if (!systemMessagesAllowed) {
298
- throw new UnsupportedFunctionalityError({
299
- functionality: "system messages are only supported at the beginning of the conversation"
300
- });
301
- }
302
- systemInstructionParts.push({ text: content });
303
- break;
304
- }
305
- case "user": {
306
- systemMessagesAllowed = false;
307
- const parts = [];
308
- for (const part of content) {
309
- switch (part.type) {
310
- case "text": {
311
- parts.push({ text: part.text });
312
- break;
313
- }
314
- case "file": {
315
- const mediaType = part.mediaType === "image/*" ? "image/jpeg" : part.mediaType;
316
- if (part.data instanceof URL) {
317
- parts.push({
318
- fileData: {
319
- mimeType: mediaType,
320
- fileUri: part.data.toString()
321
- }
322
- });
323
- } else if (isProviderReference(part.data)) {
324
- if (providerOptionsName === "vertex") {
325
- throw new UnsupportedFunctionalityError({
326
- functionality: "file parts with provider references"
327
- });
328
- }
329
- parts.push({
330
- fileData: {
331
- mimeType: mediaType,
332
- fileUri: resolveProviderReference({
333
- reference: part.data,
334
- provider: "google"
335
- })
336
- }
337
- });
338
- } else {
339
- parts.push({
340
- inlineData: {
341
- mimeType: mediaType,
342
- data: convertToBase64(part.data)
343
- }
344
- });
345
- }
346
- break;
347
- }
348
- }
349
- }
350
- contents.push({ role: "user", parts });
351
- break;
352
- }
353
- case "assistant": {
354
- systemMessagesAllowed = false;
355
- contents.push({
356
- role: "model",
357
- parts: content.map((part) => {
358
- var _a2, _b2, _c2, _d2;
359
- const providerOpts = (_d2 = (_a2 = part.providerOptions) == null ? void 0 : _a2[providerOptionsName]) != null ? _d2 : providerOptionsName !== "google" ? (_b2 = part.providerOptions) == null ? void 0 : _b2.google : (_c2 = part.providerOptions) == null ? void 0 : _c2.vertex;
360
- const thoughtSignature = (providerOpts == null ? void 0 : providerOpts.thoughtSignature) != null ? String(providerOpts.thoughtSignature) : void 0;
361
- switch (part.type) {
362
- case "text": {
363
- return part.text.length === 0 ? void 0 : {
364
- text: part.text,
365
- thoughtSignature
366
- };
367
- }
368
- case "reasoning": {
369
- return part.text.length === 0 ? void 0 : {
370
- text: part.text,
371
- thought: true,
372
- thoughtSignature
373
- };
374
- }
375
- case "reasoning-file": {
376
- if (part.data instanceof URL) {
377
- throw new UnsupportedFunctionalityError({
378
- functionality: "File data URLs in assistant messages are not supported"
379
- });
380
- }
381
- return {
382
- inlineData: {
383
- mimeType: part.mediaType,
384
- data: convertToBase64(part.data)
385
- },
386
- thought: true,
387
- thoughtSignature
388
- };
389
- }
390
- case "file": {
391
- if (part.data instanceof URL) {
392
- throw new UnsupportedFunctionalityError({
393
- functionality: "File data URLs in assistant messages are not supported"
394
- });
395
- }
396
- if (isProviderReference(part.data)) {
397
- if (providerOptionsName === "vertex") {
398
- throw new UnsupportedFunctionalityError({
399
- functionality: "file parts with provider references"
400
- });
401
- }
402
- return {
403
- fileData: {
404
- mimeType: part.mediaType,
405
- fileUri: resolveProviderReference({
406
- reference: part.data,
407
- provider: "google"
408
- })
409
- },
410
- ...(providerOpts == null ? void 0 : providerOpts.thought) === true ? { thought: true } : {},
411
- thoughtSignature
412
- };
413
- }
414
- return {
415
- inlineData: {
416
- mimeType: part.mediaType,
417
- data: convertToBase64(part.data)
418
- },
419
- ...(providerOpts == null ? void 0 : providerOpts.thought) === true ? { thought: true } : {},
420
- thoughtSignature
421
- };
422
- }
423
- case "tool-call": {
424
- const serverToolCallId = (providerOpts == null ? void 0 : providerOpts.serverToolCallId) != null ? String(providerOpts.serverToolCallId) : void 0;
425
- const serverToolType = (providerOpts == null ? void 0 : providerOpts.serverToolType) != null ? String(providerOpts.serverToolType) : void 0;
426
- if (serverToolCallId && serverToolType) {
427
- return {
428
- toolCall: {
429
- toolType: serverToolType,
430
- args: typeof part.input === "string" ? JSON.parse(part.input) : part.input,
431
- id: serverToolCallId
432
- },
433
- thoughtSignature
434
- };
435
- }
436
- return {
437
- functionCall: {
438
- name: part.toolName,
439
- args: part.input
440
- },
441
- thoughtSignature
442
- };
443
- }
444
- case "tool-result": {
445
- const serverToolCallId = (providerOpts == null ? void 0 : providerOpts.serverToolCallId) != null ? String(providerOpts.serverToolCallId) : void 0;
446
- const serverToolType = (providerOpts == null ? void 0 : providerOpts.serverToolType) != null ? String(providerOpts.serverToolType) : void 0;
447
- if (serverToolCallId && serverToolType) {
448
- return {
449
- toolResponse: {
450
- toolType: serverToolType,
451
- response: part.output.type === "json" ? part.output.value : {},
452
- id: serverToolCallId
453
- },
454
- thoughtSignature
455
- };
456
- }
457
- return void 0;
458
- }
459
- }
460
- }).filter((part) => part !== void 0)
461
- });
462
- break;
463
- }
464
- case "tool": {
465
- systemMessagesAllowed = false;
466
- const parts = [];
467
- for (const part of content) {
468
- if (part.type === "tool-approval-response") {
469
- continue;
470
- }
471
- const partProviderOpts = (_g = (_d = part.providerOptions) == null ? void 0 : _d[providerOptionsName]) != null ? _g : providerOptionsName !== "google" ? (_e = part.providerOptions) == null ? void 0 : _e.google : (_f = part.providerOptions) == null ? void 0 : _f.vertex;
472
- const serverToolCallId = (partProviderOpts == null ? void 0 : partProviderOpts.serverToolCallId) != null ? String(partProviderOpts.serverToolCallId) : void 0;
473
- const serverToolType = (partProviderOpts == null ? void 0 : partProviderOpts.serverToolType) != null ? String(partProviderOpts.serverToolType) : void 0;
474
- if (serverToolCallId && serverToolType) {
475
- const serverThoughtSignature = (partProviderOpts == null ? void 0 : partProviderOpts.thoughtSignature) != null ? String(partProviderOpts.thoughtSignature) : void 0;
476
- if (contents.length > 0) {
477
- const lastContent = contents[contents.length - 1];
478
- if (lastContent.role === "model") {
479
- lastContent.parts.push({
480
- toolResponse: {
481
- toolType: serverToolType,
482
- response: part.output.type === "json" ? part.output.value : {},
483
- id: serverToolCallId
484
- },
485
- thoughtSignature: serverThoughtSignature
486
- });
487
- continue;
488
- }
489
- }
490
- }
491
- const output = part.output;
492
- if (output.type === "content") {
493
- if (supportsFunctionResponseParts) {
494
- appendToolResultParts(parts, part.toolName, output.value);
495
- } else {
496
- appendLegacyToolResultParts(parts, part.toolName, output.value);
497
- }
498
- } else {
499
- parts.push({
500
- functionResponse: {
501
- name: part.toolName,
502
- response: {
503
- name: part.toolName,
504
- content: output.type === "execution-denied" ? (_h = output.reason) != null ? _h : "Tool execution denied." : output.value
505
- }
506
- }
507
- });
508
- }
509
- }
510
- contents.push({
511
- role: "user",
512
- parts
513
- });
514
- break;
515
- }
516
- }
517
- }
518
- if (isGemmaModel && systemInstructionParts.length > 0 && contents.length > 0 && contents[0].role === "user") {
519
- const systemText = systemInstructionParts.map((part) => part.text).join("\n\n");
520
- contents[0].parts.unshift({ text: systemText + "\n\n" });
521
- }
522
- return {
523
- systemInstruction: systemInstructionParts.length > 0 && !isGemmaModel ? { parts: systemInstructionParts } : void 0,
524
- contents
525
- };
526
- }
527
-
528
- // src/get-model-path.ts
529
- function getModelPath(modelId) {
530
- return modelId.includes("/") ? modelId : `models/${modelId}`;
531
- }
532
-
533
- // src/google-error.ts
534
- import {
535
- createJsonErrorResponseHandler,
536
- lazySchema,
537
- zodSchema
538
- } from "@ai-sdk/provider-utils";
539
- import { z } from "zod/v4";
540
- var googleErrorDataSchema = lazySchema(
541
- () => zodSchema(
542
- z.object({
543
- error: z.object({
544
- code: z.number().nullable(),
545
- message: z.string(),
546
- status: z.string()
547
- })
548
- })
549
- )
550
- );
551
- var googleFailedResponseHandler = createJsonErrorResponseHandler({
552
- errorSchema: googleErrorDataSchema,
553
- errorToMessage: (data) => data.error.message
554
- });
555
-
556
- // src/google-generative-ai-options.ts
557
- import { lazySchema as lazySchema2, zodSchema as zodSchema2 } from "@ai-sdk/provider-utils";
558
- import { z as z2 } from "zod/v4";
559
- var googleLanguageModelOptions = lazySchema2(
560
- () => zodSchema2(
561
- z2.object({
562
- responseModalities: z2.array(z2.enum(["TEXT", "IMAGE"])).optional(),
563
- thinkingConfig: z2.object({
564
- thinkingBudget: z2.number().optional(),
565
- includeThoughts: z2.boolean().optional(),
566
- // https://ai.google.dev/gemini-api/docs/gemini-3?thinking=high#thinking_level
567
- thinkingLevel: z2.enum(["minimal", "low", "medium", "high"]).optional()
568
- }).optional(),
569
- /**
570
- * Optional.
571
- * The name of the cached content used as context to serve the prediction.
572
- * Format: cachedContents/{cachedContent}
573
- */
574
- cachedContent: z2.string().optional(),
575
- /**
576
- * Optional. Enable structured output. Default is true.
577
- *
578
- * This is useful when the JSON Schema contains elements that are
579
- * not supported by the OpenAPI schema version that
580
- * Google Generative AI uses. You can use this to disable
581
- * structured outputs if you need to.
582
- */
583
- structuredOutputs: z2.boolean().optional(),
584
- /**
585
- * Optional. A list of unique safety settings for blocking unsafe content.
586
- */
587
- safetySettings: z2.array(
588
- z2.object({
589
- category: z2.enum([
590
- "HARM_CATEGORY_UNSPECIFIED",
591
- "HARM_CATEGORY_HATE_SPEECH",
592
- "HARM_CATEGORY_DANGEROUS_CONTENT",
593
- "HARM_CATEGORY_HARASSMENT",
594
- "HARM_CATEGORY_SEXUALLY_EXPLICIT",
595
- "HARM_CATEGORY_CIVIC_INTEGRITY"
596
- ]),
597
- threshold: z2.enum([
598
- "HARM_BLOCK_THRESHOLD_UNSPECIFIED",
599
- "BLOCK_LOW_AND_ABOVE",
600
- "BLOCK_MEDIUM_AND_ABOVE",
601
- "BLOCK_ONLY_HIGH",
602
- "BLOCK_NONE",
603
- "OFF"
604
- ])
605
- })
606
- ).optional(),
607
- threshold: z2.enum([
608
- "HARM_BLOCK_THRESHOLD_UNSPECIFIED",
609
- "BLOCK_LOW_AND_ABOVE",
610
- "BLOCK_MEDIUM_AND_ABOVE",
611
- "BLOCK_ONLY_HIGH",
612
- "BLOCK_NONE",
613
- "OFF"
614
- ]).optional(),
615
- /**
616
- * Optional. Enables timestamp understanding for audio-only files.
617
- *
618
- * https://cloud.google.com/vertex-ai/generative-ai/docs/multimodal/audio-understanding
619
- */
620
- audioTimestamp: z2.boolean().optional(),
621
- /**
622
- * Optional. Defines labels used in billing reports. Available on Vertex AI only.
623
- *
624
- * https://cloud.google.com/vertex-ai/generative-ai/docs/multimodal/add-labels-to-api-calls
625
- */
626
- labels: z2.record(z2.string(), z2.string()).optional(),
627
- /**
628
- * Optional. If specified, the media resolution specified will be used.
629
- *
630
- * https://ai.google.dev/api/generate-content#MediaResolution
631
- */
632
- mediaResolution: z2.enum([
633
- "MEDIA_RESOLUTION_UNSPECIFIED",
634
- "MEDIA_RESOLUTION_LOW",
635
- "MEDIA_RESOLUTION_MEDIUM",
636
- "MEDIA_RESOLUTION_HIGH"
637
- ]).optional(),
638
- /**
639
- * Optional. Configures the image generation aspect ratio for Gemini models.
640
- *
641
- * https://ai.google.dev/gemini-api/docs/image-generation#aspect_ratios
642
- */
643
- imageConfig: z2.object({
644
- aspectRatio: z2.enum([
645
- "1:1",
646
- "2:3",
647
- "3:2",
648
- "3:4",
649
- "4:3",
650
- "4:5",
651
- "5:4",
652
- "9:16",
653
- "16:9",
654
- "21:9",
655
- "1:8",
656
- "8:1",
657
- "1:4",
658
- "4:1"
659
- ]).optional(),
660
- imageSize: z2.enum(["1K", "2K", "4K", "512"]).optional()
661
- }).optional(),
662
- /**
663
- * Optional. Configuration for grounding retrieval.
664
- * Used to provide location context for Google Maps and Google Search grounding.
665
- *
666
- * https://cloud.google.com/vertex-ai/generative-ai/docs/grounding/grounding-with-google-maps
667
- */
668
- retrievalConfig: z2.object({
669
- latLng: z2.object({
670
- latitude: z2.number(),
671
- longitude: z2.number()
672
- }).optional()
673
- }).optional(),
674
- /**
675
- * Optional. When set to true, function call arguments will be streamed
676
- * incrementally via partialArgs in streaming responses. Only supported
677
- * on the Vertex AI API (not the Gemini API) and only for Gemini 3+
678
- * models.
679
- *
680
- * @default false
681
- *
682
- * https://docs.cloud.google.com/vertex-ai/generative-ai/docs/multimodal/function-calling#streaming-fc
683
- */
684
- streamFunctionCallArguments: z2.boolean().optional(),
685
- /**
686
- * Optional. The service tier to use for the request.
687
- */
688
- serviceTier: z2.enum(["standard", "flex", "priority"]).optional()
689
- })
690
- )
691
- );
692
- var VertexServiceTierMap = {
693
- standard: "SERVICE_TIER_STANDARD",
694
- flex: "SERVICE_TIER_FLEX",
695
- priority: "SERVICE_TIER_PRIORITY"
696
- };
697
-
698
- // src/google-prepare-tools.ts
699
- import {
700
- UnsupportedFunctionalityError as UnsupportedFunctionalityError2
701
- } from "@ai-sdk/provider";
702
- function prepareTools({
703
- tools,
704
- toolChoice,
705
- modelId
706
- }) {
707
- var _a, _b;
708
- tools = (tools == null ? void 0 : tools.length) ? tools : void 0;
709
- const toolWarnings = [];
710
- const isLatest = [
711
- "gemini-flash-latest",
712
- "gemini-flash-lite-latest",
713
- "gemini-pro-latest"
714
- ].some((id) => id === modelId);
715
- const isGemini2orNewer = modelId.includes("gemini-2") || modelId.includes("gemini-3") || modelId.includes("nano-banana") || isLatest;
716
- const isGemini3orNewer = modelId.includes("gemini-3");
717
- const supportsFileSearch = modelId.includes("gemini-2.5") || modelId.includes("gemini-3");
718
- if (tools == null) {
719
- return { tools: void 0, toolConfig: void 0, toolWarnings };
720
- }
721
- const hasFunctionTools = tools.some((tool) => tool.type === "function");
722
- const hasProviderTools = tools.some((tool) => tool.type === "provider");
723
- if (hasFunctionTools && hasProviderTools && !isGemini3orNewer) {
724
- toolWarnings.push({
725
- type: "unsupported",
726
- feature: `combination of function and provider-defined tools`
727
- });
728
- }
729
- if (hasProviderTools) {
730
- const googleTools2 = [];
731
- const ProviderTools = tools.filter((tool) => tool.type === "provider");
732
- ProviderTools.forEach((tool) => {
733
- switch (tool.id) {
734
- case "google.google_search":
735
- if (isGemini2orNewer) {
736
- googleTools2.push({ googleSearch: { ...tool.args } });
737
- } else {
738
- toolWarnings.push({
739
- type: "unsupported",
740
- feature: `provider-defined tool ${tool.id}`,
741
- details: "Google Search requires Gemini 2.0 or newer."
742
- });
743
- }
744
- break;
745
- case "google.enterprise_web_search":
746
- if (isGemini2orNewer) {
747
- googleTools2.push({ enterpriseWebSearch: {} });
748
- } else {
749
- toolWarnings.push({
750
- type: "unsupported",
751
- feature: `provider-defined tool ${tool.id}`,
752
- details: "Enterprise Web Search requires Gemini 2.0 or newer."
753
- });
754
- }
755
- break;
756
- case "google.url_context":
757
- if (isGemini2orNewer) {
758
- googleTools2.push({ urlContext: {} });
759
- } else {
760
- toolWarnings.push({
761
- type: "unsupported",
762
- feature: `provider-defined tool ${tool.id}`,
763
- details: "The URL context tool is not supported with other Gemini models than Gemini 2."
764
- });
765
- }
766
- break;
767
- case "google.code_execution":
768
- if (isGemini2orNewer) {
769
- googleTools2.push({ codeExecution: {} });
770
- } else {
771
- toolWarnings.push({
772
- type: "unsupported",
773
- feature: `provider-defined tool ${tool.id}`,
774
- details: "The code execution tool is not supported with other Gemini models than Gemini 2."
775
- });
776
- }
777
- break;
778
- case "google.file_search":
779
- if (supportsFileSearch) {
780
- googleTools2.push({ fileSearch: { ...tool.args } });
781
- } else {
782
- toolWarnings.push({
783
- type: "unsupported",
784
- feature: `provider-defined tool ${tool.id}`,
785
- details: "The file search tool is only supported with Gemini 2.5 models and Gemini 3 models."
786
- });
787
- }
788
- break;
789
- case "google.vertex_rag_store":
790
- if (isGemini2orNewer) {
791
- googleTools2.push({
792
- retrieval: {
793
- vertex_rag_store: {
794
- rag_resources: {
795
- rag_corpus: tool.args.ragCorpus
796
- },
797
- similarity_top_k: tool.args.topK
798
- }
799
- }
800
- });
801
- } else {
802
- toolWarnings.push({
803
- type: "unsupported",
804
- feature: `provider-defined tool ${tool.id}`,
805
- details: "The RAG store tool is not supported with other Gemini models than Gemini 2."
806
- });
807
- }
808
- break;
809
- case "google.google_maps":
810
- if (isGemini2orNewer) {
811
- googleTools2.push({ googleMaps: {} });
812
- } else {
813
- toolWarnings.push({
814
- type: "unsupported",
815
- feature: `provider-defined tool ${tool.id}`,
816
- details: "The Google Maps grounding tool is not supported with Gemini models other than Gemini 2 or newer."
817
- });
818
- }
819
- break;
820
- default:
821
- toolWarnings.push({
822
- type: "unsupported",
823
- feature: `provider-defined tool ${tool.id}`
824
- });
825
- break;
826
- }
827
- });
828
- if (hasFunctionTools && isGemini3orNewer && googleTools2.length > 0) {
829
- const functionDeclarations2 = [];
830
- for (const tool of tools) {
831
- if (tool.type === "function") {
832
- functionDeclarations2.push({
833
- name: tool.name,
834
- description: (_a = tool.description) != null ? _a : "",
835
- parameters: convertJSONSchemaToOpenAPISchema(tool.inputSchema)
836
- });
837
- }
838
- }
839
- const combinedToolConfig = {
840
- functionCallingConfig: { mode: "VALIDATED" },
841
- includeServerSideToolInvocations: true
842
- };
843
- if (toolChoice != null) {
844
- switch (toolChoice.type) {
845
- case "auto":
846
- break;
847
- case "none":
848
- combinedToolConfig.functionCallingConfig = { mode: "NONE" };
849
- break;
850
- case "required":
851
- combinedToolConfig.functionCallingConfig = { mode: "ANY" };
852
- break;
853
- case "tool":
854
- combinedToolConfig.functionCallingConfig = {
855
- mode: "ANY",
856
- allowedFunctionNames: [toolChoice.toolName]
857
- };
858
- break;
859
- }
860
- }
861
- return {
862
- tools: [...googleTools2, { functionDeclarations: functionDeclarations2 }],
863
- toolConfig: combinedToolConfig,
864
- toolWarnings
865
- };
866
- }
867
- return {
868
- tools: googleTools2.length > 0 ? googleTools2 : void 0,
869
- toolConfig: void 0,
870
- toolWarnings
871
- };
872
- }
873
- const functionDeclarations = [];
874
- let hasStrictTools = false;
875
- for (const tool of tools) {
876
- switch (tool.type) {
877
- case "function":
878
- functionDeclarations.push({
879
- name: tool.name,
880
- description: (_b = tool.description) != null ? _b : "",
881
- parameters: convertJSONSchemaToOpenAPISchema(tool.inputSchema)
882
- });
883
- if (tool.strict === true) {
884
- hasStrictTools = true;
885
- }
886
- break;
887
- default:
888
- toolWarnings.push({
889
- type: "unsupported",
890
- feature: `function tool ${tool.name}`
891
- });
892
- break;
893
- }
894
- }
895
- if (toolChoice == null) {
896
- return {
897
- tools: [{ functionDeclarations }],
898
- toolConfig: hasStrictTools ? { functionCallingConfig: { mode: "VALIDATED" } } : void 0,
899
- toolWarnings
900
- };
901
- }
902
- const type = toolChoice.type;
903
- switch (type) {
904
- case "auto":
905
- return {
906
- tools: [{ functionDeclarations }],
907
- toolConfig: {
908
- functionCallingConfig: {
909
- mode: hasStrictTools ? "VALIDATED" : "AUTO"
910
- }
911
- },
912
- toolWarnings
913
- };
914
- case "none":
915
- return {
916
- tools: [{ functionDeclarations }],
917
- toolConfig: { functionCallingConfig: { mode: "NONE" } },
918
- toolWarnings
919
- };
920
- case "required":
921
- return {
922
- tools: [{ functionDeclarations }],
923
- toolConfig: {
924
- functionCallingConfig: {
925
- mode: hasStrictTools ? "VALIDATED" : "ANY"
926
- }
927
- },
928
- toolWarnings
929
- };
930
- case "tool":
931
- return {
932
- tools: [{ functionDeclarations }],
933
- toolConfig: {
934
- functionCallingConfig: {
935
- mode: hasStrictTools ? "VALIDATED" : "ANY",
936
- allowedFunctionNames: [toolChoice.toolName]
937
- }
938
- },
939
- toolWarnings
940
- };
941
- default: {
942
- const _exhaustiveCheck = type;
943
- throw new UnsupportedFunctionalityError2({
944
- functionality: `tool choice type: ${_exhaustiveCheck}`
945
- });
946
- }
947
- }
948
- }
949
-
950
- // src/google-json-accumulator.ts
951
- var GoogleJSONAccumulator = class {
952
- constructor() {
953
- this.accumulatedArgs = {};
954
- this.jsonText = "";
955
- /**
956
- * Stack representing the currently "open" containers in the JSON output.
957
- * Entry 0 is always the root `{` object once the first value is written.
958
- */
959
- this.pathStack = [];
960
- /**
961
- * Whether a string value is currently "open" (willContinue was true),
962
- * meaning the closing quote has not yet been emitted.
963
- */
964
- this.stringOpen = false;
965
- }
966
- /**
967
- * Input: [{jsonPath:"$.brightness",numberValue:50}]
968
- * Output: { currentJSON:{brightness:50}, textDelta:'{"brightness":50' }
969
- */
970
- processPartialArgs(partialArgs) {
971
- let delta = "";
972
- for (const arg of partialArgs) {
973
- const rawPath = arg.jsonPath.replace(/^\$\./, "");
974
- if (!rawPath) continue;
975
- const segments = parsePath(rawPath);
976
- const existingValue = getNestedValue(this.accumulatedArgs, segments);
977
- const isStringContinuation = arg.stringValue != null && existingValue !== void 0;
978
- if (isStringContinuation) {
979
- const escaped = JSON.stringify(arg.stringValue).slice(1, -1);
980
- setNestedValue(
981
- this.accumulatedArgs,
982
- segments,
983
- existingValue + arg.stringValue
984
- );
985
- delta += escaped;
986
- continue;
987
- }
988
- const resolved = resolvePartialArgValue(arg);
989
- if (resolved == null) continue;
990
- setNestedValue(this.accumulatedArgs, segments, resolved.value);
991
- delta += this.emitNavigationTo(segments, arg, resolved.json);
992
- }
993
- this.jsonText += delta;
994
- return {
995
- currentJSON: this.accumulatedArgs,
996
- textDelta: delta
997
- };
998
- }
999
- /**
1000
- * Input: jsonText='{"brightness":50', accumulatedArgs={brightness:50}
1001
- * Output: { finalJSON:'{"brightness":50}', closingDelta:'}' }
1002
- */
1003
- finalize() {
1004
- const finalArgs = JSON.stringify(this.accumulatedArgs);
1005
- const closingDelta = finalArgs.slice(this.jsonText.length);
1006
- return { finalJSON: finalArgs, closingDelta };
1007
- }
1008
- /**
1009
- * Input: pathStack=[] (first call) or pathStack=[root,...] (subsequent calls)
1010
- * Output: '{' (first call) or '' (subsequent calls)
1011
- */
1012
- ensureRoot() {
1013
- if (this.pathStack.length === 0) {
1014
- this.pathStack.push({ segment: "", isArray: false, childCount: 0 });
1015
- return "{";
1016
- }
1017
- return "";
1018
- }
1019
- /**
1020
- * Emits the JSON text fragment needed to navigate from the current open
1021
- * path to the new leaf at `targetSegments`, then writes the value.
1022
- *
1023
- * Input: targetSegments=["recipe","name"], arg={jsonPath:"$.recipe.name",stringValue:"Lasagna"}, valueJson='"Lasagna"'
1024
- * Output: '{"recipe":{"name":"Lasagna"'
1025
- */
1026
- emitNavigationTo(targetSegments, arg, valueJson) {
1027
- let fragment = "";
1028
- if (this.stringOpen) {
1029
- fragment += '"';
1030
- this.stringOpen = false;
1031
- }
1032
- fragment += this.ensureRoot();
1033
- const targetContainerSegments = targetSegments.slice(0, -1);
1034
- const leafSegment = targetSegments[targetSegments.length - 1];
1035
- const commonDepth = this.findCommonStackDepth(targetContainerSegments);
1036
- fragment += this.closeDownTo(commonDepth);
1037
- fragment += this.openDownTo(targetContainerSegments, leafSegment);
1038
- fragment += this.emitLeaf(leafSegment, arg, valueJson);
1039
- return fragment;
1040
- }
1041
- /**
1042
- * Returns the stack depth to preserve when navigating to a new target
1043
- * container path. Always >= 1 (the root is never popped).
1044
- *
1045
- * Input: stack=[root,"recipe","ingredients",0], target=["recipe","ingredients",1]
1046
- * Output: 3 (keep root+"recipe"+"ingredients")
1047
- */
1048
- findCommonStackDepth(targetContainer) {
1049
- const maxDepth = Math.min(
1050
- this.pathStack.length - 1,
1051
- targetContainer.length
1052
- );
1053
- let common = 0;
1054
- for (let i = 0; i < maxDepth; i++) {
1055
- if (this.pathStack[i + 1].segment === targetContainer[i]) {
1056
- common++;
1057
- } else {
1058
- break;
1059
- }
1060
- }
1061
- return common + 1;
1062
- }
1063
- /**
1064
- * Closes containers from the current stack depth back down to `targetDepth`.
1065
- *
1066
- * Input: this.pathStack=[root,"recipe","ingredients",0], targetDepth=3
1067
- * Output: '}'
1068
- */
1069
- closeDownTo(targetDepth) {
1070
- let fragment = "";
1071
- while (this.pathStack.length > targetDepth) {
1072
- const entry = this.pathStack.pop();
1073
- fragment += entry.isArray ? "]" : "}";
1074
- }
1075
- return fragment;
1076
- }
1077
- /**
1078
- * Opens containers from the current stack depth down to the full target
1079
- * container path, emitting opening `{`, `[`, keys, and commas as needed.
1080
- * `leafSegment` is used to determine if the innermost container is an array.
1081
- *
1082
- * Input: this.pathStack=[root], targetContainer=["recipe","ingredients"], leafSegment=0
1083
- * Output: '"recipe":{"ingredients":['
1084
- */
1085
- openDownTo(targetContainer, leafSegment) {
1086
- let fragment = "";
1087
- const startIdx = this.pathStack.length - 1;
1088
- for (let i = startIdx; i < targetContainer.length; i++) {
1089
- const seg = targetContainer[i];
1090
- const parentEntry = this.pathStack[this.pathStack.length - 1];
1091
- if (parentEntry.childCount > 0) {
1092
- fragment += ",";
1093
- }
1094
- parentEntry.childCount++;
1095
- if (typeof seg === "string") {
1096
- fragment += `${JSON.stringify(seg)}:`;
1097
- }
1098
- const childSeg = i + 1 < targetContainer.length ? targetContainer[i + 1] : leafSegment;
1099
- const isArray = typeof childSeg === "number";
1100
- fragment += isArray ? "[" : "{";
1101
- this.pathStack.push({ segment: seg, isArray, childCount: 0 });
1102
- }
1103
- return fragment;
1104
- }
1105
- /**
1106
- * Emits the comma, key, and value for a leaf entry in the current container.
1107
- *
1108
- * Input: leafSegment="name", arg={stringValue:"Lasagna"}, valueJson='"Lasagna"'
1109
- * Output: '"name":"Lasagna"' (or ',"name":"Lasagna"' if container.childCount > 0)
1110
- */
1111
- emitLeaf(leafSegment, arg, valueJson) {
1112
- let fragment = "";
1113
- const container = this.pathStack[this.pathStack.length - 1];
1114
- if (container.childCount > 0) {
1115
- fragment += ",";
1116
- }
1117
- container.childCount++;
1118
- if (typeof leafSegment === "string") {
1119
- fragment += `${JSON.stringify(leafSegment)}:`;
1120
- }
1121
- if (arg.stringValue != null && arg.willContinue) {
1122
- fragment += valueJson.slice(0, -1);
1123
- this.stringOpen = true;
1124
- } else {
1125
- fragment += valueJson;
1126
- }
1127
- return fragment;
1128
- }
1129
- };
1130
- function parsePath(rawPath) {
1131
- const segments = [];
1132
- for (const part of rawPath.split(".")) {
1133
- const bracketIdx = part.indexOf("[");
1134
- if (bracketIdx === -1) {
1135
- segments.push(part);
1136
- } else {
1137
- if (bracketIdx > 0) segments.push(part.slice(0, bracketIdx));
1138
- for (const m of part.matchAll(/\[(\d+)\]/g)) {
1139
- segments.push(parseInt(m[1], 10));
1140
- }
1141
- }
1142
- }
1143
- return segments;
1144
- }
1145
- function getNestedValue(obj, segments) {
1146
- let current = obj;
1147
- for (const seg of segments) {
1148
- if (current == null || typeof current !== "object") return void 0;
1149
- current = current[seg];
1150
- }
1151
- return current;
1152
- }
1153
- function setNestedValue(obj, segments, value) {
1154
- let current = obj;
1155
- for (let i = 0; i < segments.length - 1; i++) {
1156
- const seg = segments[i];
1157
- const nextSeg = segments[i + 1];
1158
- if (current[seg] == null) {
1159
- current[seg] = typeof nextSeg === "number" ? [] : {};
1160
- }
1161
- current = current[seg];
1162
- }
1163
- current[segments[segments.length - 1]] = value;
1164
- }
1165
- function resolvePartialArgValue(arg) {
1166
- var _a, _b;
1167
- const value = (_b = (_a = arg.stringValue) != null ? _a : arg.numberValue) != null ? _b : arg.boolValue;
1168
- if (value != null) return { value, json: JSON.stringify(value) };
1169
- if ("nullValue" in arg) return { value: null, json: "null" };
1170
- return void 0;
1171
- }
1172
-
1173
- // src/map-google-generative-ai-finish-reason.ts
1174
- function mapGoogleGenerativeAIFinishReason({
1175
- finishReason,
1176
- hasToolCalls
1177
- }) {
1178
- switch (finishReason) {
1179
- case "STOP":
1180
- return hasToolCalls ? "tool-calls" : "stop";
1181
- case "MAX_TOKENS":
1182
- return "length";
1183
- case "IMAGE_SAFETY":
1184
- case "RECITATION":
1185
- case "SAFETY":
1186
- case "BLOCKLIST":
1187
- case "PROHIBITED_CONTENT":
1188
- case "SPII":
1189
- return "content-filter";
1190
- case "MALFORMED_FUNCTION_CALL":
1191
- return "error";
1192
- case "FINISH_REASON_UNSPECIFIED":
1193
- case "OTHER":
1194
- default:
1195
- return "other";
1196
- }
1197
- }
1198
-
1199
- // src/google-generative-ai-language-model.ts
1200
- var GoogleGenerativeAILanguageModel = class {
1201
- constructor(modelId, config) {
1202
- this.specificationVersion = "v4";
1203
- var _a;
1204
- this.modelId = modelId;
1205
- this.config = config;
1206
- this.generateId = (_a = config.generateId) != null ? _a : generateId;
1207
- }
1208
- get provider() {
1209
- return this.config.provider;
1210
- }
1211
- get supportedUrls() {
1212
- var _a, _b, _c;
1213
- return (_c = (_b = (_a = this.config).supportedUrls) == null ? void 0 : _b.call(_a)) != null ? _c : {};
1214
- }
1215
- async getArgs({
1216
- prompt,
1217
- maxOutputTokens,
1218
- temperature,
1219
- topP,
1220
- topK,
1221
- frequencyPenalty,
1222
- presencePenalty,
1223
- stopSequences,
1224
- responseFormat,
1225
- seed,
1226
- tools,
1227
- toolChoice,
1228
- reasoning,
1229
- providerOptions
1230
- }, { isStreaming = false } = {}) {
1231
- var _a, _b;
1232
- const warnings = [];
1233
- const providerOptionsName = this.config.provider.includes("vertex") ? "vertex" : "google";
1234
- let googleOptions = await parseProviderOptions({
1235
- provider: providerOptionsName,
1236
- providerOptions,
1237
- schema: googleLanguageModelOptions
1238
- });
1239
- if (googleOptions == null && providerOptionsName !== "google") {
1240
- googleOptions = await parseProviderOptions({
1241
- provider: "google",
1242
- providerOptions,
1243
- schema: googleLanguageModelOptions
1244
- });
1245
- }
1246
- const isVertexProvider = this.config.provider.startsWith("google.vertex.");
1247
- if ((tools == null ? void 0 : tools.some(
1248
- (tool) => tool.type === "provider" && tool.id === "google.vertex_rag_store"
1249
- )) && !isVertexProvider) {
1250
- warnings.push({
1251
- type: "other",
1252
- 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}).`
1253
- });
1254
- }
1255
- if ((googleOptions == null ? void 0 : googleOptions.streamFunctionCallArguments) && !isVertexProvider) {
1256
- warnings.push({
1257
- type: "other",
1258
- message: `'streamFunctionCallArguments' is only supported on the Vertex AI API and will be ignored with the current Google provider (${this.config.provider}). See https://docs.cloud.google.com/vertex-ai/generative-ai/docs/multimodal/function-calling#streaming-fc`
1259
- });
1260
- }
1261
- let sanitizedServiceTier = googleOptions == null ? void 0 : googleOptions.serviceTier;
1262
- if ((googleOptions == null ? void 0 : googleOptions.serviceTier) && isVertexProvider) {
1263
- sanitizedServiceTier = VertexServiceTierMap[googleOptions.serviceTier];
1264
- }
1265
- const isGemmaModel = this.modelId.toLowerCase().startsWith("gemma-");
1266
- const supportsFunctionResponseParts = this.modelId.startsWith("gemini-3");
1267
- const { contents, systemInstruction } = convertToGoogleGenerativeAIMessages(
1268
- prompt,
1269
- {
1270
- isGemmaModel,
1271
- providerOptionsName,
1272
- supportsFunctionResponseParts
1273
- }
1274
- );
1275
- const {
1276
- tools: googleTools2,
1277
- toolConfig: googleToolConfig,
1278
- toolWarnings
1279
- } = prepareTools({
1280
- tools,
1281
- toolChoice,
1282
- modelId: this.modelId
1283
- });
1284
- const resolvedThinking = resolveThinkingConfig({
1285
- reasoning,
1286
- modelId: this.modelId,
1287
- warnings
1288
- });
1289
- const thinkingConfig = (googleOptions == null ? void 0 : googleOptions.thinkingConfig) || resolvedThinking ? { ...resolvedThinking, ...googleOptions == null ? void 0 : googleOptions.thinkingConfig } : void 0;
1290
- const streamFunctionCallArguments = isStreaming && isVertexProvider ? (_a = googleOptions == null ? void 0 : googleOptions.streamFunctionCallArguments) != null ? _a : false : void 0;
1291
- const toolConfig = googleToolConfig || streamFunctionCallArguments || (googleOptions == null ? void 0 : googleOptions.retrievalConfig) ? {
1292
- ...googleToolConfig,
1293
- ...streamFunctionCallArguments && {
1294
- functionCallingConfig: {
1295
- ...googleToolConfig == null ? void 0 : googleToolConfig.functionCallingConfig,
1296
- streamFunctionCallArguments: true
1297
- }
1298
- },
1299
- ...(googleOptions == null ? void 0 : googleOptions.retrievalConfig) && {
1300
- retrievalConfig: googleOptions.retrievalConfig
1301
- }
1302
- } : void 0;
1303
- return {
1304
- args: {
1305
- generationConfig: {
1306
- // standardized settings:
1307
- maxOutputTokens,
1308
- temperature,
1309
- topK,
1310
- topP,
1311
- frequencyPenalty,
1312
- presencePenalty,
1313
- stopSequences,
1314
- seed,
1315
- // response format:
1316
- responseMimeType: (responseFormat == null ? void 0 : responseFormat.type) === "json" ? "application/json" : void 0,
1317
- responseSchema: (responseFormat == null ? void 0 : responseFormat.type) === "json" && responseFormat.schema != null && // Google GenAI does not support all OpenAPI Schema features,
1318
- // so this is needed as an escape hatch:
1319
- // TODO convert into provider option
1320
- ((_b = googleOptions == null ? void 0 : googleOptions.structuredOutputs) != null ? _b : true) ? convertJSONSchemaToOpenAPISchema(responseFormat.schema) : void 0,
1321
- ...(googleOptions == null ? void 0 : googleOptions.audioTimestamp) && {
1322
- audioTimestamp: googleOptions.audioTimestamp
1323
- },
1324
- // provider options:
1325
- responseModalities: googleOptions == null ? void 0 : googleOptions.responseModalities,
1326
- thinkingConfig,
1327
- ...(googleOptions == null ? void 0 : googleOptions.mediaResolution) && {
1328
- mediaResolution: googleOptions.mediaResolution
1329
- },
1330
- ...(googleOptions == null ? void 0 : googleOptions.imageConfig) && {
1331
- imageConfig: googleOptions.imageConfig
1332
- }
1333
- },
1334
- contents,
1335
- systemInstruction: isGemmaModel ? void 0 : systemInstruction,
1336
- safetySettings: googleOptions == null ? void 0 : googleOptions.safetySettings,
1337
- tools: googleTools2,
1338
- toolConfig,
1339
- cachedContent: googleOptions == null ? void 0 : googleOptions.cachedContent,
1340
- labels: googleOptions == null ? void 0 : googleOptions.labels,
1341
- serviceTier: sanitizedServiceTier
1342
- },
1343
- warnings: [...warnings, ...toolWarnings],
1344
- providerOptionsName
1345
- };
1346
- }
1347
- async doGenerate(options) {
1348
- var _a, _b, _c, _d, _e, _f, _g, _h, _i, _j, _k, _l, _m, _n, _o, _p;
1349
- const { args, warnings, providerOptionsName } = await this.getArgs(options);
1350
- const mergedHeaders = combineHeaders(
1351
- await resolve(this.config.headers),
1352
- options.headers
1353
- );
1354
- const {
1355
- responseHeaders,
1356
- value: response,
1357
- rawValue: rawResponse
1358
- } = await postJsonToApi({
1359
- url: `${this.config.baseURL}/${getModelPath(
1360
- this.modelId
1361
- )}:generateContent`,
1362
- headers: mergedHeaders,
1363
- body: args,
1364
- failedResponseHandler: googleFailedResponseHandler,
1365
- successfulResponseHandler: createJsonResponseHandler(responseSchema),
1366
- abortSignal: options.abortSignal,
1367
- fetch: this.config.fetch
1368
- });
1369
- const candidate = response.candidates[0];
1370
- const content = [];
1371
- const parts = (_b = (_a = candidate.content) == null ? void 0 : _a.parts) != null ? _b : [];
1372
- const usageMetadata = response.usageMetadata;
1373
- let lastCodeExecutionToolCallId;
1374
- let lastServerToolCallId;
1375
- for (const part of parts) {
1376
- if ("executableCode" in part && ((_c = part.executableCode) == null ? void 0 : _c.code)) {
1377
- const toolCallId = this.config.generateId();
1378
- lastCodeExecutionToolCallId = toolCallId;
1379
- content.push({
1380
- type: "tool-call",
1381
- toolCallId,
1382
- toolName: "code_execution",
1383
- input: JSON.stringify(part.executableCode),
1384
- providerExecuted: true
1385
- });
1386
- } else if ("codeExecutionResult" in part && part.codeExecutionResult) {
1387
- content.push({
1388
- type: "tool-result",
1389
- // Assumes a result directly follows its corresponding call part.
1390
- toolCallId: lastCodeExecutionToolCallId,
1391
- toolName: "code_execution",
1392
- result: {
1393
- outcome: part.codeExecutionResult.outcome,
1394
- output: (_d = part.codeExecutionResult.output) != null ? _d : ""
1395
- }
1396
- });
1397
- lastCodeExecutionToolCallId = void 0;
1398
- } else if ("text" in part && part.text != null) {
1399
- const thoughtSignatureMetadata = part.thoughtSignature ? {
1400
- [providerOptionsName]: {
1401
- thoughtSignature: part.thoughtSignature
1402
- }
1403
- } : void 0;
1404
- if (part.text.length === 0) {
1405
- if (thoughtSignatureMetadata != null && content.length > 0) {
1406
- const lastContent = content[content.length - 1];
1407
- lastContent.providerMetadata = thoughtSignatureMetadata;
1408
- }
1409
- } else {
1410
- content.push({
1411
- type: part.thought === true ? "reasoning" : "text",
1412
- text: part.text,
1413
- providerMetadata: thoughtSignatureMetadata
1414
- });
1415
- }
1416
- } else if ("functionCall" in part && part.functionCall.name != null && part.functionCall.args != null) {
1417
- content.push({
1418
- type: "tool-call",
1419
- toolCallId: this.config.generateId(),
1420
- toolName: part.functionCall.name,
1421
- input: JSON.stringify(part.functionCall.args),
1422
- providerMetadata: part.thoughtSignature ? {
1423
- [providerOptionsName]: {
1424
- thoughtSignature: part.thoughtSignature
1425
- }
1426
- } : void 0
1427
- });
1428
- } else if ("inlineData" in part) {
1429
- const hasThought = part.thought === true;
1430
- const hasThoughtSignature = !!part.thoughtSignature;
1431
- content.push({
1432
- type: hasThought ? "reasoning-file" : "file",
1433
- data: part.inlineData.data,
1434
- mediaType: part.inlineData.mimeType,
1435
- providerMetadata: hasThoughtSignature ? {
1436
- [providerOptionsName]: {
1437
- thoughtSignature: part.thoughtSignature
1438
- }
1439
- } : void 0
1440
- });
1441
- } else if ("toolCall" in part && part.toolCall) {
1442
- const toolCallId = (_e = part.toolCall.id) != null ? _e : this.config.generateId();
1443
- lastServerToolCallId = toolCallId;
1444
- content.push({
1445
- type: "tool-call",
1446
- toolCallId,
1447
- toolName: `server:${part.toolCall.toolType}`,
1448
- input: JSON.stringify((_f = part.toolCall.args) != null ? _f : {}),
1449
- providerExecuted: true,
1450
- dynamic: true,
1451
- providerMetadata: part.thoughtSignature ? {
1452
- [providerOptionsName]: {
1453
- thoughtSignature: part.thoughtSignature,
1454
- serverToolCallId: toolCallId,
1455
- serverToolType: part.toolCall.toolType
1456
- }
1457
- } : {
1458
- [providerOptionsName]: {
1459
- serverToolCallId: toolCallId,
1460
- serverToolType: part.toolCall.toolType
1461
- }
1462
- }
1463
- });
1464
- } else if ("toolResponse" in part && part.toolResponse) {
1465
- const responseToolCallId = (_g = lastServerToolCallId != null ? lastServerToolCallId : part.toolResponse.id) != null ? _g : this.config.generateId();
1466
- content.push({
1467
- type: "tool-result",
1468
- toolCallId: responseToolCallId,
1469
- toolName: `server:${part.toolResponse.toolType}`,
1470
- result: (_h = part.toolResponse.response) != null ? _h : {},
1471
- providerMetadata: part.thoughtSignature ? {
1472
- [providerOptionsName]: {
1473
- thoughtSignature: part.thoughtSignature,
1474
- serverToolCallId: responseToolCallId,
1475
- serverToolType: part.toolResponse.toolType
1476
- }
1477
- } : {
1478
- [providerOptionsName]: {
1479
- serverToolCallId: responseToolCallId,
1480
- serverToolType: part.toolResponse.toolType
1481
- }
1482
- }
1483
- });
1484
- lastServerToolCallId = void 0;
1485
- }
1486
- }
1487
- const sources = (_i = extractSources({
1488
- groundingMetadata: candidate.groundingMetadata,
1489
- generateId: this.config.generateId
1490
- })) != null ? _i : [];
1491
- for (const source of sources) {
1492
- content.push(source);
1493
- }
1494
- return {
1495
- content,
1496
- finishReason: {
1497
- unified: mapGoogleGenerativeAIFinishReason({
1498
- finishReason: candidate.finishReason,
1499
- // Only count client-executed tool calls for finish reason determination.
1500
- hasToolCalls: content.some(
1501
- (part) => part.type === "tool-call" && !part.providerExecuted
1502
- )
1503
- }),
1504
- raw: (_j = candidate.finishReason) != null ? _j : void 0
1505
- },
1506
- usage: convertGoogleGenerativeAIUsage(usageMetadata),
1507
- warnings,
1508
- providerMetadata: {
1509
- [providerOptionsName]: {
1510
- promptFeedback: (_k = response.promptFeedback) != null ? _k : null,
1511
- groundingMetadata: (_l = candidate.groundingMetadata) != null ? _l : null,
1512
- urlContextMetadata: (_m = candidate.urlContextMetadata) != null ? _m : null,
1513
- safetyRatings: (_n = candidate.safetyRatings) != null ? _n : null,
1514
- usageMetadata: usageMetadata != null ? usageMetadata : null,
1515
- finishMessage: (_o = candidate.finishMessage) != null ? _o : null,
1516
- serviceTier: (_p = response.serviceTier) != null ? _p : null
1517
- }
1518
- },
1519
- request: { body: args },
1520
- response: {
1521
- // TODO timestamp, model id, id
1522
- headers: responseHeaders,
1523
- body: rawResponse
1524
- }
1525
- };
1526
- }
1527
- async doStream(options) {
1528
- const { args, warnings, providerOptionsName } = await this.getArgs(
1529
- options,
1530
- { isStreaming: true }
1531
- );
1532
- const headers = combineHeaders(
1533
- await resolve(this.config.headers),
1534
- options.headers
1535
- );
1536
- const { responseHeaders, value: response } = await postJsonToApi({
1537
- url: `${this.config.baseURL}/${getModelPath(
1538
- this.modelId
1539
- )}:streamGenerateContent?alt=sse`,
1540
- headers,
1541
- body: args,
1542
- failedResponseHandler: googleFailedResponseHandler,
1543
- successfulResponseHandler: createEventSourceResponseHandler(chunkSchema),
1544
- abortSignal: options.abortSignal,
1545
- fetch: this.config.fetch
1546
- });
1547
- let finishReason = {
1548
- unified: "other",
1549
- raw: void 0
1550
- };
1551
- let usage = void 0;
1552
- let providerMetadata = void 0;
1553
- let lastGroundingMetadata = null;
1554
- let lastUrlContextMetadata = null;
1555
- let serviceTier = null;
1556
- const generateId2 = this.config.generateId;
1557
- let hasToolCalls = false;
1558
- let currentTextBlockId = null;
1559
- let currentReasoningBlockId = null;
1560
- let blockCounter = 0;
1561
- const emittedSourceUrls = /* @__PURE__ */ new Set();
1562
- let lastCodeExecutionToolCallId;
1563
- let lastServerToolCallId;
1564
- const activeStreamingToolCalls = [];
1565
- return {
1566
- stream: response.pipeThrough(
1567
- new TransformStream({
1568
- start(controller) {
1569
- controller.enqueue({ type: "stream-start", warnings });
1570
- },
1571
- transform(chunk, controller) {
1572
- var _a, _b, _c, _d, _e, _f, _g, _h, _i, _j, _k, _l;
1573
- if (options.includeRawChunks) {
1574
- controller.enqueue({ type: "raw", rawValue: chunk.rawValue });
1575
- }
1576
- if (!chunk.success) {
1577
- controller.enqueue({ type: "error", error: chunk.error });
1578
- return;
1579
- }
1580
- const value = chunk.value;
1581
- const usageMetadata = value.usageMetadata;
1582
- if (usageMetadata != null) {
1583
- usage = usageMetadata;
1584
- }
1585
- if (value.serviceTier != null) {
1586
- serviceTier = value.serviceTier;
1587
- }
1588
- const candidate = (_a = value.candidates) == null ? void 0 : _a[0];
1589
- if (candidate == null) {
1590
- return;
1591
- }
1592
- const content = candidate.content;
1593
- if (candidate.groundingMetadata != null) {
1594
- lastGroundingMetadata = candidate.groundingMetadata;
1595
- }
1596
- if (candidate.urlContextMetadata != null) {
1597
- lastUrlContextMetadata = candidate.urlContextMetadata;
1598
- }
1599
- const sources = extractSources({
1600
- groundingMetadata: candidate.groundingMetadata,
1601
- generateId: generateId2
1602
- });
1603
- if (sources != null) {
1604
- for (const source of sources) {
1605
- if (source.sourceType === "url" && !emittedSourceUrls.has(source.url)) {
1606
- emittedSourceUrls.add(source.url);
1607
- controller.enqueue(source);
1608
- }
1609
- }
1610
- }
1611
- if (content != null) {
1612
- const parts = (_b = content.parts) != null ? _b : [];
1613
- for (const part of parts) {
1614
- if ("executableCode" in part && ((_c = part.executableCode) == null ? void 0 : _c.code)) {
1615
- const toolCallId = generateId2();
1616
- lastCodeExecutionToolCallId = toolCallId;
1617
- controller.enqueue({
1618
- type: "tool-call",
1619
- toolCallId,
1620
- toolName: "code_execution",
1621
- input: JSON.stringify(part.executableCode),
1622
- providerExecuted: true
1623
- });
1624
- } else if ("codeExecutionResult" in part && part.codeExecutionResult) {
1625
- const toolCallId = lastCodeExecutionToolCallId;
1626
- if (toolCallId) {
1627
- controller.enqueue({
1628
- type: "tool-result",
1629
- toolCallId,
1630
- toolName: "code_execution",
1631
- result: {
1632
- outcome: part.codeExecutionResult.outcome,
1633
- output: (_d = part.codeExecutionResult.output) != null ? _d : ""
1634
- }
1635
- });
1636
- lastCodeExecutionToolCallId = void 0;
1637
- }
1638
- } else if ("text" in part && part.text != null) {
1639
- const thoughtSignatureMetadata = part.thoughtSignature ? {
1640
- [providerOptionsName]: {
1641
- thoughtSignature: part.thoughtSignature
1642
- }
1643
- } : void 0;
1644
- if (part.text.length === 0) {
1645
- if (thoughtSignatureMetadata != null && currentTextBlockId !== null) {
1646
- controller.enqueue({
1647
- type: "text-delta",
1648
- id: currentTextBlockId,
1649
- delta: "",
1650
- providerMetadata: thoughtSignatureMetadata
1651
- });
1652
- }
1653
- } else if (part.thought === true) {
1654
- if (currentTextBlockId !== null) {
1655
- controller.enqueue({
1656
- type: "text-end",
1657
- id: currentTextBlockId
1658
- });
1659
- currentTextBlockId = null;
1660
- }
1661
- if (currentReasoningBlockId === null) {
1662
- currentReasoningBlockId = String(blockCounter++);
1663
- controller.enqueue({
1664
- type: "reasoning-start",
1665
- id: currentReasoningBlockId,
1666
- providerMetadata: thoughtSignatureMetadata
1667
- });
1668
- }
1669
- controller.enqueue({
1670
- type: "reasoning-delta",
1671
- id: currentReasoningBlockId,
1672
- delta: part.text,
1673
- providerMetadata: thoughtSignatureMetadata
1674
- });
1675
- } else {
1676
- if (currentReasoningBlockId !== null) {
1677
- controller.enqueue({
1678
- type: "reasoning-end",
1679
- id: currentReasoningBlockId
1680
- });
1681
- currentReasoningBlockId = null;
1682
- }
1683
- if (currentTextBlockId === null) {
1684
- currentTextBlockId = String(blockCounter++);
1685
- controller.enqueue({
1686
- type: "text-start",
1687
- id: currentTextBlockId,
1688
- providerMetadata: thoughtSignatureMetadata
1689
- });
1690
- }
1691
- controller.enqueue({
1692
- type: "text-delta",
1693
- id: currentTextBlockId,
1694
- delta: part.text,
1695
- providerMetadata: thoughtSignatureMetadata
1696
- });
1697
- }
1698
- } else if ("inlineData" in part) {
1699
- if (currentTextBlockId !== null) {
1700
- controller.enqueue({
1701
- type: "text-end",
1702
- id: currentTextBlockId
1703
- });
1704
- currentTextBlockId = null;
1705
- }
1706
- if (currentReasoningBlockId !== null) {
1707
- controller.enqueue({
1708
- type: "reasoning-end",
1709
- id: currentReasoningBlockId
1710
- });
1711
- currentReasoningBlockId = null;
1712
- }
1713
- const hasThought = part.thought === true;
1714
- const hasThoughtSignature = !!part.thoughtSignature;
1715
- const fileMeta = hasThoughtSignature ? {
1716
- [providerOptionsName]: {
1717
- thoughtSignature: part.thoughtSignature
1718
- }
1719
- } : void 0;
1720
- controller.enqueue({
1721
- type: hasThought ? "reasoning-file" : "file",
1722
- mediaType: part.inlineData.mimeType,
1723
- data: part.inlineData.data,
1724
- providerMetadata: fileMeta
1725
- });
1726
- } else if ("toolCall" in part && part.toolCall) {
1727
- const toolCallId = (_e = part.toolCall.id) != null ? _e : generateId2();
1728
- lastServerToolCallId = toolCallId;
1729
- const serverMeta = {
1730
- [providerOptionsName]: {
1731
- ...part.thoughtSignature ? { thoughtSignature: part.thoughtSignature } : {},
1732
- serverToolCallId: toolCallId,
1733
- serverToolType: part.toolCall.toolType
1734
- }
1735
- };
1736
- controller.enqueue({
1737
- type: "tool-call",
1738
- toolCallId,
1739
- toolName: `server:${part.toolCall.toolType}`,
1740
- input: JSON.stringify((_f = part.toolCall.args) != null ? _f : {}),
1741
- providerExecuted: true,
1742
- dynamic: true,
1743
- providerMetadata: serverMeta
1744
- });
1745
- } else if ("toolResponse" in part && part.toolResponse) {
1746
- const responseToolCallId = (_g = lastServerToolCallId != null ? lastServerToolCallId : part.toolResponse.id) != null ? _g : generateId2();
1747
- const serverMeta = {
1748
- [providerOptionsName]: {
1749
- ...part.thoughtSignature ? { thoughtSignature: part.thoughtSignature } : {},
1750
- serverToolCallId: responseToolCallId,
1751
- serverToolType: part.toolResponse.toolType
1752
- }
1753
- };
1754
- controller.enqueue({
1755
- type: "tool-result",
1756
- toolCallId: responseToolCallId,
1757
- toolName: `server:${part.toolResponse.toolType}`,
1758
- result: (_h = part.toolResponse.response) != null ? _h : {},
1759
- providerMetadata: serverMeta
1760
- });
1761
- lastServerToolCallId = void 0;
1762
- }
1763
- }
1764
- for (const part of parts) {
1765
- if (!("functionCall" in part)) continue;
1766
- const providerMeta = part.thoughtSignature ? {
1767
- [providerOptionsName]: {
1768
- thoughtSignature: part.thoughtSignature
1769
- }
1770
- } : void 0;
1771
- const isStreamingChunk = part.functionCall.partialArgs != null || part.functionCall.name != null && part.functionCall.willContinue === true;
1772
- const isTerminalChunk = part.functionCall.name == null && part.functionCall.args == null && part.functionCall.partialArgs == null && part.functionCall.willContinue == null;
1773
- const isCompleteCall = part.functionCall.name != null && part.functionCall.args != null && part.functionCall.partialArgs == null;
1774
- if (isStreamingChunk) {
1775
- if (part.functionCall.name != null && part.functionCall.willContinue === true) {
1776
- const toolCallId = generateId2();
1777
- const accumulator = new GoogleJSONAccumulator();
1778
- activeStreamingToolCalls.push({
1779
- toolCallId,
1780
- toolName: part.functionCall.name,
1781
- accumulator,
1782
- providerMetadata: providerMeta
1783
- });
1784
- controller.enqueue({
1785
- type: "tool-input-start",
1786
- id: toolCallId,
1787
- toolName: part.functionCall.name,
1788
- providerMetadata: providerMeta
1789
- });
1790
- if (part.functionCall.partialArgs != null) {
1791
- const { textDelta } = accumulator.processPartialArgs(
1792
- part.functionCall.partialArgs
1793
- );
1794
- if (textDelta.length > 0) {
1795
- controller.enqueue({
1796
- type: "tool-input-delta",
1797
- id: toolCallId,
1798
- delta: textDelta,
1799
- providerMetadata: providerMeta
1800
- });
1801
- }
1802
- }
1803
- } else if (part.functionCall.partialArgs != null && activeStreamingToolCalls.length > 0) {
1804
- const active = activeStreamingToolCalls[activeStreamingToolCalls.length - 1];
1805
- const { textDelta } = active.accumulator.processPartialArgs(
1806
- part.functionCall.partialArgs
1807
- );
1808
- if (textDelta.length > 0) {
1809
- controller.enqueue({
1810
- type: "tool-input-delta",
1811
- id: active.toolCallId,
1812
- delta: textDelta,
1813
- providerMetadata: providerMeta
1814
- });
1815
- }
1816
- }
1817
- } else if (isTerminalChunk && activeStreamingToolCalls.length > 0) {
1818
- const active = activeStreamingToolCalls.pop();
1819
- const { finalJSON, closingDelta } = active.accumulator.finalize();
1820
- if (closingDelta.length > 0) {
1821
- controller.enqueue({
1822
- type: "tool-input-delta",
1823
- id: active.toolCallId,
1824
- delta: closingDelta,
1825
- providerMetadata: active.providerMetadata
1826
- });
1827
- }
1828
- controller.enqueue({
1829
- type: "tool-input-end",
1830
- id: active.toolCallId,
1831
- providerMetadata: active.providerMetadata
1832
- });
1833
- controller.enqueue({
1834
- type: "tool-call",
1835
- toolCallId: active.toolCallId,
1836
- toolName: active.toolName,
1837
- input: finalJSON,
1838
- providerMetadata: active.providerMetadata
1839
- });
1840
- hasToolCalls = true;
1841
- } else if (isCompleteCall) {
1842
- const toolCallId = generateId2();
1843
- const toolName = part.functionCall.name;
1844
- const args2 = typeof part.functionCall.args === "string" ? part.functionCall.args : JSON.stringify((_i = part.functionCall.args) != null ? _i : {});
1845
- controller.enqueue({
1846
- type: "tool-input-start",
1847
- id: toolCallId,
1848
- toolName,
1849
- providerMetadata: providerMeta
1850
- });
1851
- controller.enqueue({
1852
- type: "tool-input-delta",
1853
- id: toolCallId,
1854
- delta: args2,
1855
- providerMetadata: providerMeta
1856
- });
1857
- controller.enqueue({
1858
- type: "tool-input-end",
1859
- id: toolCallId,
1860
- providerMetadata: providerMeta
1861
- });
1862
- controller.enqueue({
1863
- type: "tool-call",
1864
- toolCallId,
1865
- toolName,
1866
- input: args2,
1867
- providerMetadata: providerMeta
1868
- });
1869
- hasToolCalls = true;
1870
- }
1871
- }
1872
- }
1873
- if (candidate.finishReason != null) {
1874
- finishReason = {
1875
- unified: mapGoogleGenerativeAIFinishReason({
1876
- finishReason: candidate.finishReason,
1877
- hasToolCalls
1878
- }),
1879
- raw: candidate.finishReason
1880
- };
1881
- providerMetadata = {
1882
- [providerOptionsName]: {
1883
- promptFeedback: (_j = value.promptFeedback) != null ? _j : null,
1884
- groundingMetadata: lastGroundingMetadata,
1885
- urlContextMetadata: lastUrlContextMetadata,
1886
- safetyRatings: (_k = candidate.safetyRatings) != null ? _k : null,
1887
- usageMetadata: usageMetadata != null ? usageMetadata : null,
1888
- finishMessage: (_l = candidate.finishMessage) != null ? _l : null,
1889
- serviceTier
1890
- }
1891
- };
1892
- }
1893
- },
1894
- flush(controller) {
1895
- if (currentTextBlockId !== null) {
1896
- controller.enqueue({
1897
- type: "text-end",
1898
- id: currentTextBlockId
1899
- });
1900
- }
1901
- if (currentReasoningBlockId !== null) {
1902
- controller.enqueue({
1903
- type: "reasoning-end",
1904
- id: currentReasoningBlockId
1905
- });
1906
- }
1907
- controller.enqueue({
1908
- type: "finish",
1909
- finishReason,
1910
- usage: convertGoogleGenerativeAIUsage(usage),
1911
- providerMetadata
1912
- });
1913
- }
1914
- })
1915
- ),
1916
- response: { headers: responseHeaders },
1917
- request: { body: args }
1918
- };
1919
- }
1920
- };
1921
- function isGemini3Model(modelId) {
1922
- return /gemini-3[\.\-]/i.test(modelId) || /gemini-3$/i.test(modelId);
1923
- }
1924
- function getMaxOutputTokensForGemini25Model() {
1925
- return 65536;
1926
- }
1927
- function getMaxThinkingTokensForGemini25Model(modelId) {
1928
- const id = modelId.toLowerCase();
1929
- if (id.includes("2.5-pro") || id.includes("gemini-3-pro-image")) {
1930
- return 32768;
1931
- }
1932
- return 24576;
1933
- }
1934
- function resolveThinkingConfig({
1935
- reasoning,
1936
- modelId,
1937
- warnings
1938
- }) {
1939
- if (!isCustomReasoning(reasoning)) {
1940
- return void 0;
1941
- }
1942
- if (isGemini3Model(modelId) && !modelId.includes("gemini-3-pro-image")) {
1943
- return resolveGemini3ThinkingConfig({ reasoning, warnings });
1944
- }
1945
- return resolveGemini25ThinkingConfig({ reasoning, modelId, warnings });
1946
- }
1947
- function resolveGemini3ThinkingConfig({
1948
- reasoning,
1949
- warnings
1950
- }) {
1951
- if (reasoning === "none") {
1952
- return { thinkingLevel: "minimal" };
1953
- }
1954
- const thinkingLevel = mapReasoningToProviderEffort({
1955
- reasoning,
1956
- effortMap: {
1957
- minimal: "minimal",
1958
- low: "low",
1959
- medium: "medium",
1960
- high: "high",
1961
- xhigh: "high"
1962
- },
1963
- warnings
1964
- });
1965
- if (thinkingLevel == null) {
1966
- return void 0;
1967
- }
1968
- return { thinkingLevel };
1969
- }
1970
- function resolveGemini25ThinkingConfig({
1971
- reasoning,
1972
- modelId,
1973
- warnings
1974
- }) {
1975
- if (reasoning === "none") {
1976
- return { thinkingBudget: 0 };
1977
- }
1978
- const thinkingBudget = mapReasoningToProviderBudget({
1979
- reasoning,
1980
- maxOutputTokens: getMaxOutputTokensForGemini25Model(),
1981
- maxReasoningBudget: getMaxThinkingTokensForGemini25Model(modelId),
1982
- minReasoningBudget: 0,
1983
- warnings
1984
- });
1985
- if (thinkingBudget == null) {
1986
- return void 0;
1987
- }
1988
- return { thinkingBudget };
1989
- }
1990
- function extractSources({
1991
- groundingMetadata,
1992
- generateId: generateId2
1993
- }) {
1994
- var _a, _b, _c, _d, _e, _f;
1995
- if (!(groundingMetadata == null ? void 0 : groundingMetadata.groundingChunks)) {
1996
- return void 0;
1997
- }
1998
- const sources = [];
1999
- for (const chunk of groundingMetadata.groundingChunks) {
2000
- if (chunk.web != null) {
2001
- sources.push({
2002
- type: "source",
2003
- sourceType: "url",
2004
- id: generateId2(),
2005
- url: chunk.web.uri,
2006
- title: (_a = chunk.web.title) != null ? _a : void 0
2007
- });
2008
- } else if (chunk.image != null) {
2009
- sources.push({
2010
- type: "source",
2011
- sourceType: "url",
2012
- id: generateId2(),
2013
- // Google requires attribution to the source URI, not the actual image URI.
2014
- // TODO: add another type in v7 to allow both the image and source URL to be included separately
2015
- url: chunk.image.sourceUri,
2016
- title: (_b = chunk.image.title) != null ? _b : void 0
2017
- });
2018
- } else if (chunk.retrievedContext != null) {
2019
- const uri = chunk.retrievedContext.uri;
2020
- const fileSearchStore = chunk.retrievedContext.fileSearchStore;
2021
- if (uri && (uri.startsWith("http://") || uri.startsWith("https://"))) {
2022
- sources.push({
2023
- type: "source",
2024
- sourceType: "url",
2025
- id: generateId2(),
2026
- url: uri,
2027
- title: (_c = chunk.retrievedContext.title) != null ? _c : void 0
2028
- });
2029
- } else if (uri) {
2030
- const title = (_d = chunk.retrievedContext.title) != null ? _d : "Unknown Document";
2031
- let mediaType = "application/octet-stream";
2032
- let filename = void 0;
2033
- if (uri.endsWith(".pdf")) {
2034
- mediaType = "application/pdf";
2035
- filename = uri.split("/").pop();
2036
- } else if (uri.endsWith(".txt")) {
2037
- mediaType = "text/plain";
2038
- filename = uri.split("/").pop();
2039
- } else if (uri.endsWith(".docx")) {
2040
- mediaType = "application/vnd.openxmlformats-officedocument.wordprocessingml.document";
2041
- filename = uri.split("/").pop();
2042
- } else if (uri.endsWith(".doc")) {
2043
- mediaType = "application/msword";
2044
- filename = uri.split("/").pop();
2045
- } else if (uri.match(/\.(md|markdown)$/)) {
2046
- mediaType = "text/markdown";
2047
- filename = uri.split("/").pop();
2048
- } else {
2049
- filename = uri.split("/").pop();
2050
- }
2051
- sources.push({
2052
- type: "source",
2053
- sourceType: "document",
2054
- id: generateId2(),
2055
- mediaType,
2056
- title,
2057
- filename
2058
- });
2059
- } else if (fileSearchStore) {
2060
- const title = (_e = chunk.retrievedContext.title) != null ? _e : "Unknown Document";
2061
- sources.push({
2062
- type: "source",
2063
- sourceType: "document",
2064
- id: generateId2(),
2065
- mediaType: "application/octet-stream",
2066
- title,
2067
- filename: fileSearchStore.split("/").pop()
2068
- });
2069
- }
2070
- } else if (chunk.maps != null) {
2071
- if (chunk.maps.uri) {
2072
- sources.push({
2073
- type: "source",
2074
- sourceType: "url",
2075
- id: generateId2(),
2076
- url: chunk.maps.uri,
2077
- title: (_f = chunk.maps.title) != null ? _f : void 0
2078
- });
2079
- }
2080
- }
2081
- }
2082
- return sources.length > 0 ? sources : void 0;
2083
- }
2084
- var getGroundingMetadataSchema = () => z3.object({
2085
- webSearchQueries: z3.array(z3.string()).nullish(),
2086
- imageSearchQueries: z3.array(z3.string()).nullish(),
2087
- retrievalQueries: z3.array(z3.string()).nullish(),
2088
- searchEntryPoint: z3.object({ renderedContent: z3.string() }).nullish(),
2089
- groundingChunks: z3.array(
2090
- z3.object({
2091
- web: z3.object({ uri: z3.string(), title: z3.string().nullish() }).nullish(),
2092
- image: z3.object({
2093
- sourceUri: z3.string(),
2094
- imageUri: z3.string(),
2095
- title: z3.string().nullish(),
2096
- domain: z3.string().nullish()
2097
- }).nullish(),
2098
- retrievedContext: z3.object({
2099
- uri: z3.string().nullish(),
2100
- title: z3.string().nullish(),
2101
- text: z3.string().nullish(),
2102
- fileSearchStore: z3.string().nullish()
2103
- }).nullish(),
2104
- maps: z3.object({
2105
- uri: z3.string().nullish(),
2106
- title: z3.string().nullish(),
2107
- text: z3.string().nullish(),
2108
- placeId: z3.string().nullish()
2109
- }).nullish()
2110
- })
2111
- ).nullish(),
2112
- groundingSupports: z3.array(
2113
- z3.object({
2114
- segment: z3.object({
2115
- startIndex: z3.number().nullish(),
2116
- endIndex: z3.number().nullish(),
2117
- text: z3.string().nullish()
2118
- }).nullish(),
2119
- segment_text: z3.string().nullish(),
2120
- groundingChunkIndices: z3.array(z3.number()).nullish(),
2121
- supportChunkIndices: z3.array(z3.number()).nullish(),
2122
- confidenceScores: z3.array(z3.number()).nullish(),
2123
- confidenceScore: z3.array(z3.number()).nullish()
2124
- })
2125
- ).nullish(),
2126
- retrievalMetadata: z3.union([
2127
- z3.object({
2128
- webDynamicRetrievalScore: z3.number()
2129
- }),
2130
- z3.object({})
2131
- ]).nullish()
2132
- });
2133
- var partialArgSchema = z3.object({
2134
- jsonPath: z3.string(),
2135
- stringValue: z3.string().nullish(),
2136
- numberValue: z3.number().nullish(),
2137
- boolValue: z3.boolean().nullish(),
2138
- nullValue: z3.unknown().nullish(),
2139
- willContinue: z3.boolean().nullish()
2140
- });
2141
- var getContentSchema = () => z3.object({
2142
- parts: z3.array(
2143
- z3.union([
2144
- // note: order matters since text can be fully empty
2145
- z3.object({
2146
- functionCall: z3.object({
2147
- name: z3.string().nullish(),
2148
- args: z3.unknown().nullish(),
2149
- partialArgs: z3.array(partialArgSchema).nullish(),
2150
- willContinue: z3.boolean().nullish()
2151
- }),
2152
- thoughtSignature: z3.string().nullish()
2153
- }),
2154
- z3.object({
2155
- inlineData: z3.object({
2156
- mimeType: z3.string(),
2157
- data: z3.string()
2158
- }),
2159
- thought: z3.boolean().nullish(),
2160
- thoughtSignature: z3.string().nullish()
2161
- }),
2162
- z3.object({
2163
- toolCall: z3.object({
2164
- toolType: z3.string(),
2165
- args: z3.unknown().nullish(),
2166
- id: z3.string()
2167
- }),
2168
- thoughtSignature: z3.string().nullish()
2169
- }),
2170
- z3.object({
2171
- toolResponse: z3.object({
2172
- toolType: z3.string(),
2173
- response: z3.unknown().nullish(),
2174
- id: z3.string()
2175
- }),
2176
- thoughtSignature: z3.string().nullish()
2177
- }),
2178
- z3.object({
2179
- executableCode: z3.object({
2180
- language: z3.string(),
2181
- code: z3.string()
2182
- }).nullish(),
2183
- codeExecutionResult: z3.object({
2184
- outcome: z3.string(),
2185
- output: z3.string().nullish()
2186
- }).nullish(),
2187
- text: z3.string().nullish(),
2188
- thought: z3.boolean().nullish(),
2189
- thoughtSignature: z3.string().nullish()
2190
- })
2191
- ])
2192
- ).nullish()
2193
- });
2194
- var getSafetyRatingSchema = () => z3.object({
2195
- category: z3.string().nullish(),
2196
- probability: z3.string().nullish(),
2197
- probabilityScore: z3.number().nullish(),
2198
- severity: z3.string().nullish(),
2199
- severityScore: z3.number().nullish(),
2200
- blocked: z3.boolean().nullish()
2201
- });
2202
- var tokenDetailsSchema = z3.array(
2203
- z3.object({
2204
- modality: z3.string(),
2205
- tokenCount: z3.number()
2206
- })
2207
- ).nullish();
2208
- var usageSchema = z3.object({
2209
- cachedContentTokenCount: z3.number().nullish(),
2210
- thoughtsTokenCount: z3.number().nullish(),
2211
- promptTokenCount: z3.number().nullish(),
2212
- candidatesTokenCount: z3.number().nullish(),
2213
- totalTokenCount: z3.number().nullish(),
2214
- // https://cloud.google.com/vertex-ai/generative-ai/docs/reference/rest/v1/GenerateContentResponse#TrafficType
2215
- trafficType: z3.string().nullish(),
2216
- // https://ai.google.dev/api/generate-content#Modality
2217
- promptTokensDetails: tokenDetailsSchema,
2218
- candidatesTokensDetails: tokenDetailsSchema
2219
- });
2220
- var getUrlContextMetadataSchema = () => z3.object({
2221
- urlMetadata: z3.array(
2222
- z3.object({
2223
- retrievedUrl: z3.string(),
2224
- urlRetrievalStatus: z3.string()
2225
- })
2226
- ).nullish()
2227
- });
2228
- var responseSchema = lazySchema3(
2229
- () => zodSchema3(
2230
- z3.object({
2231
- candidates: z3.array(
2232
- z3.object({
2233
- content: getContentSchema().nullish().or(z3.object({}).strict()),
2234
- finishReason: z3.string().nullish(),
2235
- finishMessage: z3.string().nullish(),
2236
- safetyRatings: z3.array(getSafetyRatingSchema()).nullish(),
2237
- groundingMetadata: getGroundingMetadataSchema().nullish(),
2238
- urlContextMetadata: getUrlContextMetadataSchema().nullish()
2239
- })
2240
- ),
2241
- usageMetadata: usageSchema.nullish(),
2242
- promptFeedback: z3.object({
2243
- blockReason: z3.string().nullish(),
2244
- safetyRatings: z3.array(getSafetyRatingSchema()).nullish()
2245
- }).nullish(),
2246
- serviceTier: z3.string().nullish()
2247
- })
2248
- )
2249
- );
2250
- var chunkSchema = lazySchema3(
2251
- () => zodSchema3(
2252
- z3.object({
2253
- candidates: z3.array(
2254
- z3.object({
2255
- content: getContentSchema().nullish(),
2256
- finishReason: z3.string().nullish(),
2257
- finishMessage: z3.string().nullish(),
2258
- safetyRatings: z3.array(getSafetyRatingSchema()).nullish(),
2259
- groundingMetadata: getGroundingMetadataSchema().nullish(),
2260
- urlContextMetadata: getUrlContextMetadataSchema().nullish()
2261
- })
2262
- ).nullish(),
2263
- usageMetadata: usageSchema.nullish(),
2264
- promptFeedback: z3.object({
2265
- blockReason: z3.string().nullish(),
2266
- safetyRatings: z3.array(getSafetyRatingSchema()).nullish()
2267
- }).nullish(),
2268
- serviceTier: z3.string().nullish()
2269
- })
2270
- )
2271
- );
2272
-
2273
- // src/tool/code-execution.ts
2274
- import { createProviderToolFactoryWithOutputSchema } from "@ai-sdk/provider-utils";
2275
- import { z as z4 } from "zod/v4";
2276
- var codeExecution = createProviderToolFactoryWithOutputSchema({
2277
- id: "google.code_execution",
2278
- inputSchema: z4.object({
2279
- language: z4.string().describe("The programming language of the code."),
2280
- code: z4.string().describe("The code to be executed.")
2281
- }),
2282
- outputSchema: z4.object({
2283
- outcome: z4.string().describe('The outcome of the execution (e.g., "OUTCOME_OK").'),
2284
- output: z4.string().describe("The output from the code execution.")
2285
- })
2286
- });
2287
-
2288
- // src/tool/enterprise-web-search.ts
2289
- import {
2290
- createProviderToolFactory,
2291
- lazySchema as lazySchema4,
2292
- zodSchema as zodSchema4
2293
- } from "@ai-sdk/provider-utils";
2294
- import { z as z5 } from "zod/v4";
2295
- var enterpriseWebSearch = createProviderToolFactory({
2296
- id: "google.enterprise_web_search",
2297
- inputSchema: lazySchema4(() => zodSchema4(z5.object({})))
2298
- });
2299
-
2300
- // src/tool/file-search.ts
2301
- import {
2302
- createProviderToolFactory as createProviderToolFactory2,
2303
- lazySchema as lazySchema5,
2304
- zodSchema as zodSchema5
2305
- } from "@ai-sdk/provider-utils";
2306
- import { z as z6 } from "zod/v4";
2307
- var fileSearchArgsBaseSchema = z6.object({
2308
- /** The names of the file_search_stores to retrieve from.
2309
- * Example: `fileSearchStores/my-file-search-store-123`
2310
- */
2311
- fileSearchStoreNames: z6.array(z6.string()).describe(
2312
- "The names of the file_search_stores to retrieve from. Example: `fileSearchStores/my-file-search-store-123`"
2313
- ),
2314
- /** The number of file search retrieval chunks to retrieve. */
2315
- topK: z6.number().int().positive().describe("The number of file search retrieval chunks to retrieve.").optional(),
2316
- /** Metadata filter to apply to the file search retrieval documents.
2317
- * See https://google.aip.dev/160 for the syntax of the filter expression.
2318
- */
2319
- metadataFilter: z6.string().describe(
2320
- "Metadata filter to apply to the file search retrieval documents. See https://google.aip.dev/160 for the syntax of the filter expression."
2321
- ).optional()
2322
- }).passthrough();
2323
- var fileSearchArgsSchema = lazySchema5(
2324
- () => zodSchema5(fileSearchArgsBaseSchema)
2325
- );
2326
- var fileSearch = createProviderToolFactory2({
2327
- id: "google.file_search",
2328
- inputSchema: fileSearchArgsSchema
2329
- });
2330
-
2331
- // src/tool/google-maps.ts
2332
- import {
2333
- createProviderToolFactory as createProviderToolFactory3,
2334
- lazySchema as lazySchema6,
2335
- zodSchema as zodSchema6
2336
- } from "@ai-sdk/provider-utils";
2337
- import { z as z7 } from "zod/v4";
2338
- var googleMaps = createProviderToolFactory3({
2339
- id: "google.google_maps",
2340
- inputSchema: lazySchema6(() => zodSchema6(z7.object({})))
2341
- });
2342
-
2343
- // src/tool/google-search.ts
2344
- import {
2345
- createProviderToolFactory as createProviderToolFactory4,
2346
- lazySchema as lazySchema7,
2347
- zodSchema as zodSchema7
2348
- } from "@ai-sdk/provider-utils";
2349
- import { z as z8 } from "zod/v4";
2350
- var googleSearchToolArgsBaseSchema = z8.object({
2351
- searchTypes: z8.object({
2352
- webSearch: z8.object({}).optional(),
2353
- imageSearch: z8.object({}).optional()
2354
- }).optional(),
2355
- timeRangeFilter: z8.object({
2356
- startTime: z8.string(),
2357
- endTime: z8.string()
2358
- }).optional()
2359
- }).passthrough();
2360
- var googleSearchToolArgsSchema = lazySchema7(
2361
- () => zodSchema7(googleSearchToolArgsBaseSchema)
2362
- );
2363
- var googleSearch = createProviderToolFactory4(
2364
- {
2365
- id: "google.google_search",
2366
- inputSchema: googleSearchToolArgsSchema
2367
- }
2368
- );
2369
-
2370
- // src/tool/url-context.ts
2371
- import {
2372
- createProviderToolFactory as createProviderToolFactory5,
2373
- lazySchema as lazySchema8,
2374
- zodSchema as zodSchema8
2375
- } from "@ai-sdk/provider-utils";
2376
- import { z as z9 } from "zod/v4";
2377
- var urlContext = createProviderToolFactory5({
2378
- id: "google.url_context",
2379
- inputSchema: lazySchema8(() => zodSchema8(z9.object({})))
2380
- });
2381
-
2382
- // src/tool/vertex-rag-store.ts
2383
- import { createProviderToolFactory as createProviderToolFactory6 } from "@ai-sdk/provider-utils";
2384
- import { z as z10 } from "zod/v4";
2385
- var vertexRagStore = createProviderToolFactory6({
2386
- id: "google.vertex_rag_store",
2387
- inputSchema: z10.object({
2388
- ragCorpus: z10.string(),
2389
- topK: z10.number().optional()
2390
- })
2391
- });
2392
-
2393
- // src/google-tools.ts
2394
- var googleTools = {
2395
- /**
2396
- * Creates a Google search tool that gives Google direct access to real-time web content.
2397
- * Must have name "google_search".
2398
- */
2399
- googleSearch,
2400
- /**
2401
- * Creates an Enterprise Web Search tool for grounding responses using a compliance-focused web index.
2402
- * Designed for highly-regulated industries (finance, healthcare, public sector).
2403
- * Does not log customer data and supports VPC service controls.
2404
- * Must have name "enterprise_web_search".
2405
- *
2406
- * @note Only available on Vertex AI. Requires Gemini 2.0 or newer.
2407
- *
2408
- * @see https://cloud.google.com/vertex-ai/generative-ai/docs/grounding/web-grounding-enterprise
2409
- */
2410
- enterpriseWebSearch,
2411
- /**
2412
- * Creates a Google Maps grounding tool that gives the model access to Google Maps data.
2413
- * Must have name "google_maps".
2414
- *
2415
- * @see https://ai.google.dev/gemini-api/docs/maps-grounding
2416
- * @see https://cloud.google.com/vertex-ai/generative-ai/docs/grounding/grounding-with-google-maps
2417
- */
2418
- googleMaps,
2419
- /**
2420
- * Creates a URL context tool that gives Google direct access to real-time web content.
2421
- * Must have name "url_context".
2422
- */
2423
- urlContext,
2424
- /**
2425
- * Enables Retrieval Augmented Generation (RAG) via the Gemini File Search tool.
2426
- * Must have name "file_search".
2427
- *
2428
- * @param fileSearchStoreNames - Fully-qualified File Search store resource names.
2429
- * @param metadataFilter - Optional filter expression to restrict the files that can be retrieved.
2430
- * @param topK - Optional result limit for the number of chunks returned from File Search.
2431
- *
2432
- * @see https://ai.google.dev/gemini-api/docs/file-search
2433
- */
2434
- fileSearch,
2435
- /**
2436
- * A tool that enables the model to generate and run Python code.
2437
- * Must have name "code_execution".
2438
- *
2439
- * @note Ensure the selected model supports Code Execution.
2440
- * Multi-tool usage with the code execution tool is typically compatible with Gemini >=2 models.
2441
- *
2442
- * @see https://ai.google.dev/gemini-api/docs/code-execution (Google AI)
2443
- * @see https://cloud.google.com/vertex-ai/generative-ai/docs/model-reference/code-execution-api (Vertex AI)
2444
- */
2445
- codeExecution,
2446
- /**
2447
- * Creates a Vertex RAG Store tool that enables the model to perform RAG searches against a Vertex RAG Store.
2448
- * Must have name "vertex_rag_store".
2449
- */
2450
- vertexRagStore
2451
- };
2452
- export {
2453
- GoogleGenerativeAILanguageModel,
2454
- getGroundingMetadataSchema,
2455
- getUrlContextMetadataSchema,
2456
- googleTools
2457
- };
2458
- //# sourceMappingURL=index.mjs.map