@ai-sdk/google 4.0.0-beta.35 → 4.0.0-beta.37

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,2449 +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
-
693
- // src/google-prepare-tools.ts
694
- import {
695
- UnsupportedFunctionalityError as UnsupportedFunctionalityError2
696
- } from "@ai-sdk/provider";
697
- function prepareTools({
698
- tools,
699
- toolChoice,
700
- modelId
701
- }) {
702
- var _a, _b;
703
- tools = (tools == null ? void 0 : tools.length) ? tools : void 0;
704
- const toolWarnings = [];
705
- const isLatest = [
706
- "gemini-flash-latest",
707
- "gemini-flash-lite-latest",
708
- "gemini-pro-latest"
709
- ].some((id) => id === modelId);
710
- const isGemini2orNewer = modelId.includes("gemini-2") || modelId.includes("gemini-3") || modelId.includes("nano-banana") || isLatest;
711
- const isGemini3orNewer = modelId.includes("gemini-3");
712
- const supportsFileSearch = modelId.includes("gemini-2.5") || modelId.includes("gemini-3");
713
- if (tools == null) {
714
- return { tools: void 0, toolConfig: void 0, toolWarnings };
715
- }
716
- const hasFunctionTools = tools.some((tool) => tool.type === "function");
717
- const hasProviderTools = tools.some((tool) => tool.type === "provider");
718
- if (hasFunctionTools && hasProviderTools && !isGemini3orNewer) {
719
- toolWarnings.push({
720
- type: "unsupported",
721
- feature: `combination of function and provider-defined tools`
722
- });
723
- }
724
- if (hasProviderTools) {
725
- const googleTools2 = [];
726
- const ProviderTools = tools.filter((tool) => tool.type === "provider");
727
- ProviderTools.forEach((tool) => {
728
- switch (tool.id) {
729
- case "google.google_search":
730
- if (isGemini2orNewer) {
731
- googleTools2.push({ googleSearch: { ...tool.args } });
732
- } else {
733
- toolWarnings.push({
734
- type: "unsupported",
735
- feature: `provider-defined tool ${tool.id}`,
736
- details: "Google Search requires Gemini 2.0 or newer."
737
- });
738
- }
739
- break;
740
- case "google.enterprise_web_search":
741
- if (isGemini2orNewer) {
742
- googleTools2.push({ enterpriseWebSearch: {} });
743
- } else {
744
- toolWarnings.push({
745
- type: "unsupported",
746
- feature: `provider-defined tool ${tool.id}`,
747
- details: "Enterprise Web Search requires Gemini 2.0 or newer."
748
- });
749
- }
750
- break;
751
- case "google.url_context":
752
- if (isGemini2orNewer) {
753
- googleTools2.push({ urlContext: {} });
754
- } else {
755
- toolWarnings.push({
756
- type: "unsupported",
757
- feature: `provider-defined tool ${tool.id}`,
758
- details: "The URL context tool is not supported with other Gemini models than Gemini 2."
759
- });
760
- }
761
- break;
762
- case "google.code_execution":
763
- if (isGemini2orNewer) {
764
- googleTools2.push({ codeExecution: {} });
765
- } else {
766
- toolWarnings.push({
767
- type: "unsupported",
768
- feature: `provider-defined tool ${tool.id}`,
769
- details: "The code execution tool is not supported with other Gemini models than Gemini 2."
770
- });
771
- }
772
- break;
773
- case "google.file_search":
774
- if (supportsFileSearch) {
775
- googleTools2.push({ fileSearch: { ...tool.args } });
776
- } else {
777
- toolWarnings.push({
778
- type: "unsupported",
779
- feature: `provider-defined tool ${tool.id}`,
780
- details: "The file search tool is only supported with Gemini 2.5 models and Gemini 3 models."
781
- });
782
- }
783
- break;
784
- case "google.vertex_rag_store":
785
- if (isGemini2orNewer) {
786
- googleTools2.push({
787
- retrieval: {
788
- vertex_rag_store: {
789
- rag_resources: {
790
- rag_corpus: tool.args.ragCorpus
791
- },
792
- similarity_top_k: tool.args.topK
793
- }
794
- }
795
- });
796
- } else {
797
- toolWarnings.push({
798
- type: "unsupported",
799
- feature: `provider-defined tool ${tool.id}`,
800
- details: "The RAG store tool is not supported with other Gemini models than Gemini 2."
801
- });
802
- }
803
- break;
804
- case "google.google_maps":
805
- if (isGemini2orNewer) {
806
- googleTools2.push({ googleMaps: {} });
807
- } else {
808
- toolWarnings.push({
809
- type: "unsupported",
810
- feature: `provider-defined tool ${tool.id}`,
811
- details: "The Google Maps grounding tool is not supported with Gemini models other than Gemini 2 or newer."
812
- });
813
- }
814
- break;
815
- default:
816
- toolWarnings.push({
817
- type: "unsupported",
818
- feature: `provider-defined tool ${tool.id}`
819
- });
820
- break;
821
- }
822
- });
823
- if (hasFunctionTools && isGemini3orNewer && googleTools2.length > 0) {
824
- const functionDeclarations2 = [];
825
- for (const tool of tools) {
826
- if (tool.type === "function") {
827
- functionDeclarations2.push({
828
- name: tool.name,
829
- description: (_a = tool.description) != null ? _a : "",
830
- parameters: convertJSONSchemaToOpenAPISchema(tool.inputSchema)
831
- });
832
- }
833
- }
834
- const combinedToolConfig = {
835
- functionCallingConfig: { mode: "VALIDATED" },
836
- includeServerSideToolInvocations: true
837
- };
838
- if (toolChoice != null) {
839
- switch (toolChoice.type) {
840
- case "auto":
841
- break;
842
- case "none":
843
- combinedToolConfig.functionCallingConfig = { mode: "NONE" };
844
- break;
845
- case "required":
846
- combinedToolConfig.functionCallingConfig = { mode: "ANY" };
847
- break;
848
- case "tool":
849
- combinedToolConfig.functionCallingConfig = {
850
- mode: "ANY",
851
- allowedFunctionNames: [toolChoice.toolName]
852
- };
853
- break;
854
- }
855
- }
856
- return {
857
- tools: [...googleTools2, { functionDeclarations: functionDeclarations2 }],
858
- toolConfig: combinedToolConfig,
859
- toolWarnings
860
- };
861
- }
862
- return {
863
- tools: googleTools2.length > 0 ? googleTools2 : void 0,
864
- toolConfig: void 0,
865
- toolWarnings
866
- };
867
- }
868
- const functionDeclarations = [];
869
- let hasStrictTools = false;
870
- for (const tool of tools) {
871
- switch (tool.type) {
872
- case "function":
873
- functionDeclarations.push({
874
- name: tool.name,
875
- description: (_b = tool.description) != null ? _b : "",
876
- parameters: convertJSONSchemaToOpenAPISchema(tool.inputSchema)
877
- });
878
- if (tool.strict === true) {
879
- hasStrictTools = true;
880
- }
881
- break;
882
- default:
883
- toolWarnings.push({
884
- type: "unsupported",
885
- feature: `function tool ${tool.name}`
886
- });
887
- break;
888
- }
889
- }
890
- if (toolChoice == null) {
891
- return {
892
- tools: [{ functionDeclarations }],
893
- toolConfig: hasStrictTools ? { functionCallingConfig: { mode: "VALIDATED" } } : void 0,
894
- toolWarnings
895
- };
896
- }
897
- const type = toolChoice.type;
898
- switch (type) {
899
- case "auto":
900
- return {
901
- tools: [{ functionDeclarations }],
902
- toolConfig: {
903
- functionCallingConfig: {
904
- mode: hasStrictTools ? "VALIDATED" : "AUTO"
905
- }
906
- },
907
- toolWarnings
908
- };
909
- case "none":
910
- return {
911
- tools: [{ functionDeclarations }],
912
- toolConfig: { functionCallingConfig: { mode: "NONE" } },
913
- toolWarnings
914
- };
915
- case "required":
916
- return {
917
- tools: [{ functionDeclarations }],
918
- toolConfig: {
919
- functionCallingConfig: {
920
- mode: hasStrictTools ? "VALIDATED" : "ANY"
921
- }
922
- },
923
- toolWarnings
924
- };
925
- case "tool":
926
- return {
927
- tools: [{ functionDeclarations }],
928
- toolConfig: {
929
- functionCallingConfig: {
930
- mode: hasStrictTools ? "VALIDATED" : "ANY",
931
- allowedFunctionNames: [toolChoice.toolName]
932
- }
933
- },
934
- toolWarnings
935
- };
936
- default: {
937
- const _exhaustiveCheck = type;
938
- throw new UnsupportedFunctionalityError2({
939
- functionality: `tool choice type: ${_exhaustiveCheck}`
940
- });
941
- }
942
- }
943
- }
944
-
945
- // src/google-json-accumulator.ts
946
- var GoogleJSONAccumulator = class {
947
- constructor() {
948
- this.accumulatedArgs = {};
949
- this.jsonText = "";
950
- /**
951
- * Stack representing the currently "open" containers in the JSON output.
952
- * Entry 0 is always the root `{` object once the first value is written.
953
- */
954
- this.pathStack = [];
955
- /**
956
- * Whether a string value is currently "open" (willContinue was true),
957
- * meaning the closing quote has not yet been emitted.
958
- */
959
- this.stringOpen = false;
960
- }
961
- /**
962
- * Input: [{jsonPath:"$.brightness",numberValue:50}]
963
- * Output: { currentJSON:{brightness:50}, textDelta:'{"brightness":50' }
964
- */
965
- processPartialArgs(partialArgs) {
966
- let delta = "";
967
- for (const arg of partialArgs) {
968
- const rawPath = arg.jsonPath.replace(/^\$\./, "");
969
- if (!rawPath) continue;
970
- const segments = parsePath(rawPath);
971
- const existingValue = getNestedValue(this.accumulatedArgs, segments);
972
- const isStringContinuation = arg.stringValue != null && existingValue !== void 0;
973
- if (isStringContinuation) {
974
- const escaped = JSON.stringify(arg.stringValue).slice(1, -1);
975
- setNestedValue(
976
- this.accumulatedArgs,
977
- segments,
978
- existingValue + arg.stringValue
979
- );
980
- delta += escaped;
981
- continue;
982
- }
983
- const resolved = resolvePartialArgValue(arg);
984
- if (resolved == null) continue;
985
- setNestedValue(this.accumulatedArgs, segments, resolved.value);
986
- delta += this.emitNavigationTo(segments, arg, resolved.json);
987
- }
988
- this.jsonText += delta;
989
- return {
990
- currentJSON: this.accumulatedArgs,
991
- textDelta: delta
992
- };
993
- }
994
- /**
995
- * Input: jsonText='{"brightness":50', accumulatedArgs={brightness:50}
996
- * Output: { finalJSON:'{"brightness":50}', closingDelta:'}' }
997
- */
998
- finalize() {
999
- const finalArgs = JSON.stringify(this.accumulatedArgs);
1000
- const closingDelta = finalArgs.slice(this.jsonText.length);
1001
- return { finalJSON: finalArgs, closingDelta };
1002
- }
1003
- /**
1004
- * Input: pathStack=[] (first call) or pathStack=[root,...] (subsequent calls)
1005
- * Output: '{' (first call) or '' (subsequent calls)
1006
- */
1007
- ensureRoot() {
1008
- if (this.pathStack.length === 0) {
1009
- this.pathStack.push({ segment: "", isArray: false, childCount: 0 });
1010
- return "{";
1011
- }
1012
- return "";
1013
- }
1014
- /**
1015
- * Emits the JSON text fragment needed to navigate from the current open
1016
- * path to the new leaf at `targetSegments`, then writes the value.
1017
- *
1018
- * Input: targetSegments=["recipe","name"], arg={jsonPath:"$.recipe.name",stringValue:"Lasagna"}, valueJson='"Lasagna"'
1019
- * Output: '{"recipe":{"name":"Lasagna"'
1020
- */
1021
- emitNavigationTo(targetSegments, arg, valueJson) {
1022
- let fragment = "";
1023
- if (this.stringOpen) {
1024
- fragment += '"';
1025
- this.stringOpen = false;
1026
- }
1027
- fragment += this.ensureRoot();
1028
- const targetContainerSegments = targetSegments.slice(0, -1);
1029
- const leafSegment = targetSegments[targetSegments.length - 1];
1030
- const commonDepth = this.findCommonStackDepth(targetContainerSegments);
1031
- fragment += this.closeDownTo(commonDepth);
1032
- fragment += this.openDownTo(targetContainerSegments, leafSegment);
1033
- fragment += this.emitLeaf(leafSegment, arg, valueJson);
1034
- return fragment;
1035
- }
1036
- /**
1037
- * Returns the stack depth to preserve when navigating to a new target
1038
- * container path. Always >= 1 (the root is never popped).
1039
- *
1040
- * Input: stack=[root,"recipe","ingredients",0], target=["recipe","ingredients",1]
1041
- * Output: 3 (keep root+"recipe"+"ingredients")
1042
- */
1043
- findCommonStackDepth(targetContainer) {
1044
- const maxDepth = Math.min(
1045
- this.pathStack.length - 1,
1046
- targetContainer.length
1047
- );
1048
- let common = 0;
1049
- for (let i = 0; i < maxDepth; i++) {
1050
- if (this.pathStack[i + 1].segment === targetContainer[i]) {
1051
- common++;
1052
- } else {
1053
- break;
1054
- }
1055
- }
1056
- return common + 1;
1057
- }
1058
- /**
1059
- * Closes containers from the current stack depth back down to `targetDepth`.
1060
- *
1061
- * Input: this.pathStack=[root,"recipe","ingredients",0], targetDepth=3
1062
- * Output: '}'
1063
- */
1064
- closeDownTo(targetDepth) {
1065
- let fragment = "";
1066
- while (this.pathStack.length > targetDepth) {
1067
- const entry = this.pathStack.pop();
1068
- fragment += entry.isArray ? "]" : "}";
1069
- }
1070
- return fragment;
1071
- }
1072
- /**
1073
- * Opens containers from the current stack depth down to the full target
1074
- * container path, emitting opening `{`, `[`, keys, and commas as needed.
1075
- * `leafSegment` is used to determine if the innermost container is an array.
1076
- *
1077
- * Input: this.pathStack=[root], targetContainer=["recipe","ingredients"], leafSegment=0
1078
- * Output: '"recipe":{"ingredients":['
1079
- */
1080
- openDownTo(targetContainer, leafSegment) {
1081
- let fragment = "";
1082
- const startIdx = this.pathStack.length - 1;
1083
- for (let i = startIdx; i < targetContainer.length; i++) {
1084
- const seg = targetContainer[i];
1085
- const parentEntry = this.pathStack[this.pathStack.length - 1];
1086
- if (parentEntry.childCount > 0) {
1087
- fragment += ",";
1088
- }
1089
- parentEntry.childCount++;
1090
- if (typeof seg === "string") {
1091
- fragment += `${JSON.stringify(seg)}:`;
1092
- }
1093
- const childSeg = i + 1 < targetContainer.length ? targetContainer[i + 1] : leafSegment;
1094
- const isArray = typeof childSeg === "number";
1095
- fragment += isArray ? "[" : "{";
1096
- this.pathStack.push({ segment: seg, isArray, childCount: 0 });
1097
- }
1098
- return fragment;
1099
- }
1100
- /**
1101
- * Emits the comma, key, and value for a leaf entry in the current container.
1102
- *
1103
- * Input: leafSegment="name", arg={stringValue:"Lasagna"}, valueJson='"Lasagna"'
1104
- * Output: '"name":"Lasagna"' (or ',"name":"Lasagna"' if container.childCount > 0)
1105
- */
1106
- emitLeaf(leafSegment, arg, valueJson) {
1107
- let fragment = "";
1108
- const container = this.pathStack[this.pathStack.length - 1];
1109
- if (container.childCount > 0) {
1110
- fragment += ",";
1111
- }
1112
- container.childCount++;
1113
- if (typeof leafSegment === "string") {
1114
- fragment += `${JSON.stringify(leafSegment)}:`;
1115
- }
1116
- if (arg.stringValue != null && arg.willContinue) {
1117
- fragment += valueJson.slice(0, -1);
1118
- this.stringOpen = true;
1119
- } else {
1120
- fragment += valueJson;
1121
- }
1122
- return fragment;
1123
- }
1124
- };
1125
- function parsePath(rawPath) {
1126
- const segments = [];
1127
- for (const part of rawPath.split(".")) {
1128
- const bracketIdx = part.indexOf("[");
1129
- if (bracketIdx === -1) {
1130
- segments.push(part);
1131
- } else {
1132
- if (bracketIdx > 0) segments.push(part.slice(0, bracketIdx));
1133
- for (const m of part.matchAll(/\[(\d+)\]/g)) {
1134
- segments.push(parseInt(m[1], 10));
1135
- }
1136
- }
1137
- }
1138
- return segments;
1139
- }
1140
- function getNestedValue(obj, segments) {
1141
- let current = obj;
1142
- for (const seg of segments) {
1143
- if (current == null || typeof current !== "object") return void 0;
1144
- current = current[seg];
1145
- }
1146
- return current;
1147
- }
1148
- function setNestedValue(obj, segments, value) {
1149
- let current = obj;
1150
- for (let i = 0; i < segments.length - 1; i++) {
1151
- const seg = segments[i];
1152
- const nextSeg = segments[i + 1];
1153
- if (current[seg] == null) {
1154
- current[seg] = typeof nextSeg === "number" ? [] : {};
1155
- }
1156
- current = current[seg];
1157
- }
1158
- current[segments[segments.length - 1]] = value;
1159
- }
1160
- function resolvePartialArgValue(arg) {
1161
- var _a, _b;
1162
- const value = (_b = (_a = arg.stringValue) != null ? _a : arg.numberValue) != null ? _b : arg.boolValue;
1163
- if (value != null) return { value, json: JSON.stringify(value) };
1164
- if ("nullValue" in arg) return { value: null, json: "null" };
1165
- return void 0;
1166
- }
1167
-
1168
- // src/map-google-generative-ai-finish-reason.ts
1169
- function mapGoogleGenerativeAIFinishReason({
1170
- finishReason,
1171
- hasToolCalls
1172
- }) {
1173
- switch (finishReason) {
1174
- case "STOP":
1175
- return hasToolCalls ? "tool-calls" : "stop";
1176
- case "MAX_TOKENS":
1177
- return "length";
1178
- case "IMAGE_SAFETY":
1179
- case "RECITATION":
1180
- case "SAFETY":
1181
- case "BLOCKLIST":
1182
- case "PROHIBITED_CONTENT":
1183
- case "SPII":
1184
- return "content-filter";
1185
- case "MALFORMED_FUNCTION_CALL":
1186
- return "error";
1187
- case "FINISH_REASON_UNSPECIFIED":
1188
- case "OTHER":
1189
- default:
1190
- return "other";
1191
- }
1192
- }
1193
-
1194
- // src/google-generative-ai-language-model.ts
1195
- var GoogleGenerativeAILanguageModel = class {
1196
- constructor(modelId, config) {
1197
- this.specificationVersion = "v4";
1198
- var _a;
1199
- this.modelId = modelId;
1200
- this.config = config;
1201
- this.generateId = (_a = config.generateId) != null ? _a : generateId;
1202
- }
1203
- get provider() {
1204
- return this.config.provider;
1205
- }
1206
- get supportedUrls() {
1207
- var _a, _b, _c;
1208
- return (_c = (_b = (_a = this.config).supportedUrls) == null ? void 0 : _b.call(_a)) != null ? _c : {};
1209
- }
1210
- async getArgs({
1211
- prompt,
1212
- maxOutputTokens,
1213
- temperature,
1214
- topP,
1215
- topK,
1216
- frequencyPenalty,
1217
- presencePenalty,
1218
- stopSequences,
1219
- responseFormat,
1220
- seed,
1221
- tools,
1222
- toolChoice,
1223
- reasoning,
1224
- providerOptions
1225
- }, { isStreaming = false } = {}) {
1226
- var _a, _b;
1227
- const warnings = [];
1228
- const providerOptionsName = this.config.provider.includes("vertex") ? "vertex" : "google";
1229
- let googleOptions = await parseProviderOptions({
1230
- provider: providerOptionsName,
1231
- providerOptions,
1232
- schema: googleLanguageModelOptions
1233
- });
1234
- if (googleOptions == null && providerOptionsName !== "google") {
1235
- googleOptions = await parseProviderOptions({
1236
- provider: "google",
1237
- providerOptions,
1238
- schema: googleLanguageModelOptions
1239
- });
1240
- }
1241
- const isVertexProvider = this.config.provider.startsWith("google.vertex.");
1242
- if ((tools == null ? void 0 : tools.some(
1243
- (tool) => tool.type === "provider" && tool.id === "google.vertex_rag_store"
1244
- )) && !isVertexProvider) {
1245
- warnings.push({
1246
- type: "other",
1247
- 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}).`
1248
- });
1249
- }
1250
- if ((googleOptions == null ? void 0 : googleOptions.streamFunctionCallArguments) && !isVertexProvider) {
1251
- warnings.push({
1252
- type: "other",
1253
- 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`
1254
- });
1255
- }
1256
- const isGemmaModel = this.modelId.toLowerCase().startsWith("gemma-");
1257
- const supportsFunctionResponseParts = this.modelId.startsWith("gemini-3");
1258
- const { contents, systemInstruction } = convertToGoogleGenerativeAIMessages(
1259
- prompt,
1260
- {
1261
- isGemmaModel,
1262
- providerOptionsName,
1263
- supportsFunctionResponseParts
1264
- }
1265
- );
1266
- const {
1267
- tools: googleTools2,
1268
- toolConfig: googleToolConfig,
1269
- toolWarnings
1270
- } = prepareTools({
1271
- tools,
1272
- toolChoice,
1273
- modelId: this.modelId
1274
- });
1275
- const resolvedThinking = resolveThinkingConfig({
1276
- reasoning,
1277
- modelId: this.modelId,
1278
- warnings
1279
- });
1280
- const thinkingConfig = (googleOptions == null ? void 0 : googleOptions.thinkingConfig) || resolvedThinking ? { ...resolvedThinking, ...googleOptions == null ? void 0 : googleOptions.thinkingConfig } : void 0;
1281
- const streamFunctionCallArguments = isStreaming && isVertexProvider ? (_a = googleOptions == null ? void 0 : googleOptions.streamFunctionCallArguments) != null ? _a : false : void 0;
1282
- const toolConfig = googleToolConfig || streamFunctionCallArguments || (googleOptions == null ? void 0 : googleOptions.retrievalConfig) ? {
1283
- ...googleToolConfig,
1284
- ...streamFunctionCallArguments && {
1285
- functionCallingConfig: {
1286
- ...googleToolConfig == null ? void 0 : googleToolConfig.functionCallingConfig,
1287
- streamFunctionCallArguments: true
1288
- }
1289
- },
1290
- ...(googleOptions == null ? void 0 : googleOptions.retrievalConfig) && {
1291
- retrievalConfig: googleOptions.retrievalConfig
1292
- }
1293
- } : void 0;
1294
- return {
1295
- args: {
1296
- generationConfig: {
1297
- // standardized settings:
1298
- maxOutputTokens,
1299
- temperature,
1300
- topK,
1301
- topP,
1302
- frequencyPenalty,
1303
- presencePenalty,
1304
- stopSequences,
1305
- seed,
1306
- // response format:
1307
- responseMimeType: (responseFormat == null ? void 0 : responseFormat.type) === "json" ? "application/json" : void 0,
1308
- responseSchema: (responseFormat == null ? void 0 : responseFormat.type) === "json" && responseFormat.schema != null && // Google GenAI does not support all OpenAPI Schema features,
1309
- // so this is needed as an escape hatch:
1310
- // TODO convert into provider option
1311
- ((_b = googleOptions == null ? void 0 : googleOptions.structuredOutputs) != null ? _b : true) ? convertJSONSchemaToOpenAPISchema(responseFormat.schema) : void 0,
1312
- ...(googleOptions == null ? void 0 : googleOptions.audioTimestamp) && {
1313
- audioTimestamp: googleOptions.audioTimestamp
1314
- },
1315
- // provider options:
1316
- responseModalities: googleOptions == null ? void 0 : googleOptions.responseModalities,
1317
- thinkingConfig,
1318
- ...(googleOptions == null ? void 0 : googleOptions.mediaResolution) && {
1319
- mediaResolution: googleOptions.mediaResolution
1320
- },
1321
- ...(googleOptions == null ? void 0 : googleOptions.imageConfig) && {
1322
- imageConfig: googleOptions.imageConfig
1323
- }
1324
- },
1325
- contents,
1326
- systemInstruction: isGemmaModel ? void 0 : systemInstruction,
1327
- safetySettings: googleOptions == null ? void 0 : googleOptions.safetySettings,
1328
- tools: googleTools2,
1329
- toolConfig,
1330
- cachedContent: googleOptions == null ? void 0 : googleOptions.cachedContent,
1331
- labels: googleOptions == null ? void 0 : googleOptions.labels,
1332
- serviceTier: googleOptions == null ? void 0 : googleOptions.serviceTier
1333
- },
1334
- warnings: [...warnings, ...toolWarnings],
1335
- providerOptionsName
1336
- };
1337
- }
1338
- async doGenerate(options) {
1339
- var _a, _b, _c, _d, _e, _f, _g, _h, _i, _j, _k, _l, _m, _n, _o, _p;
1340
- const { args, warnings, providerOptionsName } = await this.getArgs(options);
1341
- const mergedHeaders = combineHeaders(
1342
- await resolve(this.config.headers),
1343
- options.headers
1344
- );
1345
- const {
1346
- responseHeaders,
1347
- value: response,
1348
- rawValue: rawResponse
1349
- } = await postJsonToApi({
1350
- url: `${this.config.baseURL}/${getModelPath(
1351
- this.modelId
1352
- )}:generateContent`,
1353
- headers: mergedHeaders,
1354
- body: args,
1355
- failedResponseHandler: googleFailedResponseHandler,
1356
- successfulResponseHandler: createJsonResponseHandler(responseSchema),
1357
- abortSignal: options.abortSignal,
1358
- fetch: this.config.fetch
1359
- });
1360
- const candidate = response.candidates[0];
1361
- const content = [];
1362
- const parts = (_b = (_a = candidate.content) == null ? void 0 : _a.parts) != null ? _b : [];
1363
- const usageMetadata = response.usageMetadata;
1364
- let lastCodeExecutionToolCallId;
1365
- let lastServerToolCallId;
1366
- for (const part of parts) {
1367
- if ("executableCode" in part && ((_c = part.executableCode) == null ? void 0 : _c.code)) {
1368
- const toolCallId = this.config.generateId();
1369
- lastCodeExecutionToolCallId = toolCallId;
1370
- content.push({
1371
- type: "tool-call",
1372
- toolCallId,
1373
- toolName: "code_execution",
1374
- input: JSON.stringify(part.executableCode),
1375
- providerExecuted: true
1376
- });
1377
- } else if ("codeExecutionResult" in part && part.codeExecutionResult) {
1378
- content.push({
1379
- type: "tool-result",
1380
- // Assumes a result directly follows its corresponding call part.
1381
- toolCallId: lastCodeExecutionToolCallId,
1382
- toolName: "code_execution",
1383
- result: {
1384
- outcome: part.codeExecutionResult.outcome,
1385
- output: (_d = part.codeExecutionResult.output) != null ? _d : ""
1386
- }
1387
- });
1388
- lastCodeExecutionToolCallId = void 0;
1389
- } else if ("text" in part && part.text != null) {
1390
- const thoughtSignatureMetadata = part.thoughtSignature ? {
1391
- [providerOptionsName]: {
1392
- thoughtSignature: part.thoughtSignature
1393
- }
1394
- } : void 0;
1395
- if (part.text.length === 0) {
1396
- if (thoughtSignatureMetadata != null && content.length > 0) {
1397
- const lastContent = content[content.length - 1];
1398
- lastContent.providerMetadata = thoughtSignatureMetadata;
1399
- }
1400
- } else {
1401
- content.push({
1402
- type: part.thought === true ? "reasoning" : "text",
1403
- text: part.text,
1404
- providerMetadata: thoughtSignatureMetadata
1405
- });
1406
- }
1407
- } else if ("functionCall" in part && part.functionCall.name != null && part.functionCall.args != null) {
1408
- content.push({
1409
- type: "tool-call",
1410
- toolCallId: this.config.generateId(),
1411
- toolName: part.functionCall.name,
1412
- input: JSON.stringify(part.functionCall.args),
1413
- providerMetadata: part.thoughtSignature ? {
1414
- [providerOptionsName]: {
1415
- thoughtSignature: part.thoughtSignature
1416
- }
1417
- } : void 0
1418
- });
1419
- } else if ("inlineData" in part) {
1420
- const hasThought = part.thought === true;
1421
- const hasThoughtSignature = !!part.thoughtSignature;
1422
- content.push({
1423
- type: hasThought ? "reasoning-file" : "file",
1424
- data: part.inlineData.data,
1425
- mediaType: part.inlineData.mimeType,
1426
- providerMetadata: hasThoughtSignature ? {
1427
- [providerOptionsName]: {
1428
- thoughtSignature: part.thoughtSignature
1429
- }
1430
- } : void 0
1431
- });
1432
- } else if ("toolCall" in part && part.toolCall) {
1433
- const toolCallId = (_e = part.toolCall.id) != null ? _e : this.config.generateId();
1434
- lastServerToolCallId = toolCallId;
1435
- content.push({
1436
- type: "tool-call",
1437
- toolCallId,
1438
- toolName: `server:${part.toolCall.toolType}`,
1439
- input: JSON.stringify((_f = part.toolCall.args) != null ? _f : {}),
1440
- providerExecuted: true,
1441
- dynamic: true,
1442
- providerMetadata: part.thoughtSignature ? {
1443
- [providerOptionsName]: {
1444
- thoughtSignature: part.thoughtSignature,
1445
- serverToolCallId: toolCallId,
1446
- serverToolType: part.toolCall.toolType
1447
- }
1448
- } : {
1449
- [providerOptionsName]: {
1450
- serverToolCallId: toolCallId,
1451
- serverToolType: part.toolCall.toolType
1452
- }
1453
- }
1454
- });
1455
- } else if ("toolResponse" in part && part.toolResponse) {
1456
- const responseToolCallId = (_g = lastServerToolCallId != null ? lastServerToolCallId : part.toolResponse.id) != null ? _g : this.config.generateId();
1457
- content.push({
1458
- type: "tool-result",
1459
- toolCallId: responseToolCallId,
1460
- toolName: `server:${part.toolResponse.toolType}`,
1461
- result: (_h = part.toolResponse.response) != null ? _h : {},
1462
- providerMetadata: part.thoughtSignature ? {
1463
- [providerOptionsName]: {
1464
- thoughtSignature: part.thoughtSignature,
1465
- serverToolCallId: responseToolCallId,
1466
- serverToolType: part.toolResponse.toolType
1467
- }
1468
- } : {
1469
- [providerOptionsName]: {
1470
- serverToolCallId: responseToolCallId,
1471
- serverToolType: part.toolResponse.toolType
1472
- }
1473
- }
1474
- });
1475
- lastServerToolCallId = void 0;
1476
- }
1477
- }
1478
- const sources = (_i = extractSources({
1479
- groundingMetadata: candidate.groundingMetadata,
1480
- generateId: this.config.generateId
1481
- })) != null ? _i : [];
1482
- for (const source of sources) {
1483
- content.push(source);
1484
- }
1485
- return {
1486
- content,
1487
- finishReason: {
1488
- unified: mapGoogleGenerativeAIFinishReason({
1489
- finishReason: candidate.finishReason,
1490
- // Only count client-executed tool calls for finish reason determination.
1491
- hasToolCalls: content.some(
1492
- (part) => part.type === "tool-call" && !part.providerExecuted
1493
- )
1494
- }),
1495
- raw: (_j = candidate.finishReason) != null ? _j : void 0
1496
- },
1497
- usage: convertGoogleGenerativeAIUsage(usageMetadata),
1498
- warnings,
1499
- providerMetadata: {
1500
- [providerOptionsName]: {
1501
- promptFeedback: (_k = response.promptFeedback) != null ? _k : null,
1502
- groundingMetadata: (_l = candidate.groundingMetadata) != null ? _l : null,
1503
- urlContextMetadata: (_m = candidate.urlContextMetadata) != null ? _m : null,
1504
- safetyRatings: (_n = candidate.safetyRatings) != null ? _n : null,
1505
- usageMetadata: usageMetadata != null ? usageMetadata : null,
1506
- finishMessage: (_o = candidate.finishMessage) != null ? _o : null,
1507
- serviceTier: (_p = response.serviceTier) != null ? _p : null
1508
- }
1509
- },
1510
- request: { body: args },
1511
- response: {
1512
- // TODO timestamp, model id, id
1513
- headers: responseHeaders,
1514
- body: rawResponse
1515
- }
1516
- };
1517
- }
1518
- async doStream(options) {
1519
- const { args, warnings, providerOptionsName } = await this.getArgs(
1520
- options,
1521
- { isStreaming: true }
1522
- );
1523
- const headers = combineHeaders(
1524
- await resolve(this.config.headers),
1525
- options.headers
1526
- );
1527
- const { responseHeaders, value: response } = await postJsonToApi({
1528
- url: `${this.config.baseURL}/${getModelPath(
1529
- this.modelId
1530
- )}:streamGenerateContent?alt=sse`,
1531
- headers,
1532
- body: args,
1533
- failedResponseHandler: googleFailedResponseHandler,
1534
- successfulResponseHandler: createEventSourceResponseHandler(chunkSchema),
1535
- abortSignal: options.abortSignal,
1536
- fetch: this.config.fetch
1537
- });
1538
- let finishReason = {
1539
- unified: "other",
1540
- raw: void 0
1541
- };
1542
- let usage = void 0;
1543
- let providerMetadata = void 0;
1544
- let lastGroundingMetadata = null;
1545
- let lastUrlContextMetadata = null;
1546
- let serviceTier = null;
1547
- const generateId2 = this.config.generateId;
1548
- let hasToolCalls = false;
1549
- let currentTextBlockId = null;
1550
- let currentReasoningBlockId = null;
1551
- let blockCounter = 0;
1552
- const emittedSourceUrls = /* @__PURE__ */ new Set();
1553
- let lastCodeExecutionToolCallId;
1554
- let lastServerToolCallId;
1555
- const activeStreamingToolCalls = [];
1556
- return {
1557
- stream: response.pipeThrough(
1558
- new TransformStream({
1559
- start(controller) {
1560
- controller.enqueue({ type: "stream-start", warnings });
1561
- },
1562
- transform(chunk, controller) {
1563
- var _a, _b, _c, _d, _e, _f, _g, _h, _i, _j, _k, _l;
1564
- if (options.includeRawChunks) {
1565
- controller.enqueue({ type: "raw", rawValue: chunk.rawValue });
1566
- }
1567
- if (!chunk.success) {
1568
- controller.enqueue({ type: "error", error: chunk.error });
1569
- return;
1570
- }
1571
- const value = chunk.value;
1572
- const usageMetadata = value.usageMetadata;
1573
- if (usageMetadata != null) {
1574
- usage = usageMetadata;
1575
- }
1576
- if (value.serviceTier != null) {
1577
- serviceTier = value.serviceTier;
1578
- }
1579
- const candidate = (_a = value.candidates) == null ? void 0 : _a[0];
1580
- if (candidate == null) {
1581
- return;
1582
- }
1583
- const content = candidate.content;
1584
- if (candidate.groundingMetadata != null) {
1585
- lastGroundingMetadata = candidate.groundingMetadata;
1586
- }
1587
- if (candidate.urlContextMetadata != null) {
1588
- lastUrlContextMetadata = candidate.urlContextMetadata;
1589
- }
1590
- const sources = extractSources({
1591
- groundingMetadata: candidate.groundingMetadata,
1592
- generateId: generateId2
1593
- });
1594
- if (sources != null) {
1595
- for (const source of sources) {
1596
- if (source.sourceType === "url" && !emittedSourceUrls.has(source.url)) {
1597
- emittedSourceUrls.add(source.url);
1598
- controller.enqueue(source);
1599
- }
1600
- }
1601
- }
1602
- if (content != null) {
1603
- const parts = (_b = content.parts) != null ? _b : [];
1604
- for (const part of parts) {
1605
- if ("executableCode" in part && ((_c = part.executableCode) == null ? void 0 : _c.code)) {
1606
- const toolCallId = generateId2();
1607
- lastCodeExecutionToolCallId = toolCallId;
1608
- controller.enqueue({
1609
- type: "tool-call",
1610
- toolCallId,
1611
- toolName: "code_execution",
1612
- input: JSON.stringify(part.executableCode),
1613
- providerExecuted: true
1614
- });
1615
- } else if ("codeExecutionResult" in part && part.codeExecutionResult) {
1616
- const toolCallId = lastCodeExecutionToolCallId;
1617
- if (toolCallId) {
1618
- controller.enqueue({
1619
- type: "tool-result",
1620
- toolCallId,
1621
- toolName: "code_execution",
1622
- result: {
1623
- outcome: part.codeExecutionResult.outcome,
1624
- output: (_d = part.codeExecutionResult.output) != null ? _d : ""
1625
- }
1626
- });
1627
- lastCodeExecutionToolCallId = void 0;
1628
- }
1629
- } else if ("text" in part && part.text != null) {
1630
- const thoughtSignatureMetadata = part.thoughtSignature ? {
1631
- [providerOptionsName]: {
1632
- thoughtSignature: part.thoughtSignature
1633
- }
1634
- } : void 0;
1635
- if (part.text.length === 0) {
1636
- if (thoughtSignatureMetadata != null && currentTextBlockId !== null) {
1637
- controller.enqueue({
1638
- type: "text-delta",
1639
- id: currentTextBlockId,
1640
- delta: "",
1641
- providerMetadata: thoughtSignatureMetadata
1642
- });
1643
- }
1644
- } else if (part.thought === true) {
1645
- if (currentTextBlockId !== null) {
1646
- controller.enqueue({
1647
- type: "text-end",
1648
- id: currentTextBlockId
1649
- });
1650
- currentTextBlockId = null;
1651
- }
1652
- if (currentReasoningBlockId === null) {
1653
- currentReasoningBlockId = String(blockCounter++);
1654
- controller.enqueue({
1655
- type: "reasoning-start",
1656
- id: currentReasoningBlockId,
1657
- providerMetadata: thoughtSignatureMetadata
1658
- });
1659
- }
1660
- controller.enqueue({
1661
- type: "reasoning-delta",
1662
- id: currentReasoningBlockId,
1663
- delta: part.text,
1664
- providerMetadata: thoughtSignatureMetadata
1665
- });
1666
- } else {
1667
- if (currentReasoningBlockId !== null) {
1668
- controller.enqueue({
1669
- type: "reasoning-end",
1670
- id: currentReasoningBlockId
1671
- });
1672
- currentReasoningBlockId = null;
1673
- }
1674
- if (currentTextBlockId === null) {
1675
- currentTextBlockId = String(blockCounter++);
1676
- controller.enqueue({
1677
- type: "text-start",
1678
- id: currentTextBlockId,
1679
- providerMetadata: thoughtSignatureMetadata
1680
- });
1681
- }
1682
- controller.enqueue({
1683
- type: "text-delta",
1684
- id: currentTextBlockId,
1685
- delta: part.text,
1686
- providerMetadata: thoughtSignatureMetadata
1687
- });
1688
- }
1689
- } else if ("inlineData" in part) {
1690
- if (currentTextBlockId !== null) {
1691
- controller.enqueue({
1692
- type: "text-end",
1693
- id: currentTextBlockId
1694
- });
1695
- currentTextBlockId = null;
1696
- }
1697
- if (currentReasoningBlockId !== null) {
1698
- controller.enqueue({
1699
- type: "reasoning-end",
1700
- id: currentReasoningBlockId
1701
- });
1702
- currentReasoningBlockId = null;
1703
- }
1704
- const hasThought = part.thought === true;
1705
- const hasThoughtSignature = !!part.thoughtSignature;
1706
- const fileMeta = hasThoughtSignature ? {
1707
- [providerOptionsName]: {
1708
- thoughtSignature: part.thoughtSignature
1709
- }
1710
- } : void 0;
1711
- controller.enqueue({
1712
- type: hasThought ? "reasoning-file" : "file",
1713
- mediaType: part.inlineData.mimeType,
1714
- data: part.inlineData.data,
1715
- providerMetadata: fileMeta
1716
- });
1717
- } else if ("toolCall" in part && part.toolCall) {
1718
- const toolCallId = (_e = part.toolCall.id) != null ? _e : generateId2();
1719
- lastServerToolCallId = toolCallId;
1720
- const serverMeta = {
1721
- [providerOptionsName]: {
1722
- ...part.thoughtSignature ? { thoughtSignature: part.thoughtSignature } : {},
1723
- serverToolCallId: toolCallId,
1724
- serverToolType: part.toolCall.toolType
1725
- }
1726
- };
1727
- controller.enqueue({
1728
- type: "tool-call",
1729
- toolCallId,
1730
- toolName: `server:${part.toolCall.toolType}`,
1731
- input: JSON.stringify((_f = part.toolCall.args) != null ? _f : {}),
1732
- providerExecuted: true,
1733
- dynamic: true,
1734
- providerMetadata: serverMeta
1735
- });
1736
- } else if ("toolResponse" in part && part.toolResponse) {
1737
- const responseToolCallId = (_g = lastServerToolCallId != null ? lastServerToolCallId : part.toolResponse.id) != null ? _g : generateId2();
1738
- const serverMeta = {
1739
- [providerOptionsName]: {
1740
- ...part.thoughtSignature ? { thoughtSignature: part.thoughtSignature } : {},
1741
- serverToolCallId: responseToolCallId,
1742
- serverToolType: part.toolResponse.toolType
1743
- }
1744
- };
1745
- controller.enqueue({
1746
- type: "tool-result",
1747
- toolCallId: responseToolCallId,
1748
- toolName: `server:${part.toolResponse.toolType}`,
1749
- result: (_h = part.toolResponse.response) != null ? _h : {},
1750
- providerMetadata: serverMeta
1751
- });
1752
- lastServerToolCallId = void 0;
1753
- }
1754
- }
1755
- for (const part of parts) {
1756
- if (!("functionCall" in part)) continue;
1757
- const providerMeta = part.thoughtSignature ? {
1758
- [providerOptionsName]: {
1759
- thoughtSignature: part.thoughtSignature
1760
- }
1761
- } : void 0;
1762
- const isStreamingChunk = part.functionCall.partialArgs != null || part.functionCall.name != null && part.functionCall.willContinue === true;
1763
- const isTerminalChunk = part.functionCall.name == null && part.functionCall.args == null && part.functionCall.partialArgs == null && part.functionCall.willContinue == null;
1764
- const isCompleteCall = part.functionCall.name != null && part.functionCall.args != null && part.functionCall.partialArgs == null;
1765
- if (isStreamingChunk) {
1766
- if (part.functionCall.name != null && part.functionCall.willContinue === true) {
1767
- const toolCallId = generateId2();
1768
- const accumulator = new GoogleJSONAccumulator();
1769
- activeStreamingToolCalls.push({
1770
- toolCallId,
1771
- toolName: part.functionCall.name,
1772
- accumulator,
1773
- providerMetadata: providerMeta
1774
- });
1775
- controller.enqueue({
1776
- type: "tool-input-start",
1777
- id: toolCallId,
1778
- toolName: part.functionCall.name,
1779
- providerMetadata: providerMeta
1780
- });
1781
- if (part.functionCall.partialArgs != null) {
1782
- const { textDelta } = accumulator.processPartialArgs(
1783
- part.functionCall.partialArgs
1784
- );
1785
- if (textDelta.length > 0) {
1786
- controller.enqueue({
1787
- type: "tool-input-delta",
1788
- id: toolCallId,
1789
- delta: textDelta,
1790
- providerMetadata: providerMeta
1791
- });
1792
- }
1793
- }
1794
- } else if (part.functionCall.partialArgs != null && activeStreamingToolCalls.length > 0) {
1795
- const active = activeStreamingToolCalls[activeStreamingToolCalls.length - 1];
1796
- const { textDelta } = active.accumulator.processPartialArgs(
1797
- part.functionCall.partialArgs
1798
- );
1799
- if (textDelta.length > 0) {
1800
- controller.enqueue({
1801
- type: "tool-input-delta",
1802
- id: active.toolCallId,
1803
- delta: textDelta,
1804
- providerMetadata: providerMeta
1805
- });
1806
- }
1807
- }
1808
- } else if (isTerminalChunk && activeStreamingToolCalls.length > 0) {
1809
- const active = activeStreamingToolCalls.pop();
1810
- const { finalJSON, closingDelta } = active.accumulator.finalize();
1811
- if (closingDelta.length > 0) {
1812
- controller.enqueue({
1813
- type: "tool-input-delta",
1814
- id: active.toolCallId,
1815
- delta: closingDelta,
1816
- providerMetadata: active.providerMetadata
1817
- });
1818
- }
1819
- controller.enqueue({
1820
- type: "tool-input-end",
1821
- id: active.toolCallId,
1822
- providerMetadata: active.providerMetadata
1823
- });
1824
- controller.enqueue({
1825
- type: "tool-call",
1826
- toolCallId: active.toolCallId,
1827
- toolName: active.toolName,
1828
- input: finalJSON,
1829
- providerMetadata: active.providerMetadata
1830
- });
1831
- hasToolCalls = true;
1832
- } else if (isCompleteCall) {
1833
- const toolCallId = generateId2();
1834
- const toolName = part.functionCall.name;
1835
- const args2 = typeof part.functionCall.args === "string" ? part.functionCall.args : JSON.stringify((_i = part.functionCall.args) != null ? _i : {});
1836
- controller.enqueue({
1837
- type: "tool-input-start",
1838
- id: toolCallId,
1839
- toolName,
1840
- providerMetadata: providerMeta
1841
- });
1842
- controller.enqueue({
1843
- type: "tool-input-delta",
1844
- id: toolCallId,
1845
- delta: args2,
1846
- providerMetadata: providerMeta
1847
- });
1848
- controller.enqueue({
1849
- type: "tool-input-end",
1850
- id: toolCallId,
1851
- providerMetadata: providerMeta
1852
- });
1853
- controller.enqueue({
1854
- type: "tool-call",
1855
- toolCallId,
1856
- toolName,
1857
- input: args2,
1858
- providerMetadata: providerMeta
1859
- });
1860
- hasToolCalls = true;
1861
- }
1862
- }
1863
- }
1864
- if (candidate.finishReason != null) {
1865
- finishReason = {
1866
- unified: mapGoogleGenerativeAIFinishReason({
1867
- finishReason: candidate.finishReason,
1868
- hasToolCalls
1869
- }),
1870
- raw: candidate.finishReason
1871
- };
1872
- providerMetadata = {
1873
- [providerOptionsName]: {
1874
- promptFeedback: (_j = value.promptFeedback) != null ? _j : null,
1875
- groundingMetadata: lastGroundingMetadata,
1876
- urlContextMetadata: lastUrlContextMetadata,
1877
- safetyRatings: (_k = candidate.safetyRatings) != null ? _k : null,
1878
- usageMetadata: usageMetadata != null ? usageMetadata : null,
1879
- finishMessage: (_l = candidate.finishMessage) != null ? _l : null,
1880
- serviceTier
1881
- }
1882
- };
1883
- }
1884
- },
1885
- flush(controller) {
1886
- if (currentTextBlockId !== null) {
1887
- controller.enqueue({
1888
- type: "text-end",
1889
- id: currentTextBlockId
1890
- });
1891
- }
1892
- if (currentReasoningBlockId !== null) {
1893
- controller.enqueue({
1894
- type: "reasoning-end",
1895
- id: currentReasoningBlockId
1896
- });
1897
- }
1898
- controller.enqueue({
1899
- type: "finish",
1900
- finishReason,
1901
- usage: convertGoogleGenerativeAIUsage(usage),
1902
- providerMetadata
1903
- });
1904
- }
1905
- })
1906
- ),
1907
- response: { headers: responseHeaders },
1908
- request: { body: args }
1909
- };
1910
- }
1911
- };
1912
- function isGemini3Model(modelId) {
1913
- return /gemini-3[\.\-]/i.test(modelId) || /gemini-3$/i.test(modelId);
1914
- }
1915
- function getMaxOutputTokensForGemini25Model() {
1916
- return 65536;
1917
- }
1918
- function getMaxThinkingTokensForGemini25Model(modelId) {
1919
- const id = modelId.toLowerCase();
1920
- if (id.includes("2.5-pro") || id.includes("gemini-3-pro-image")) {
1921
- return 32768;
1922
- }
1923
- return 24576;
1924
- }
1925
- function resolveThinkingConfig({
1926
- reasoning,
1927
- modelId,
1928
- warnings
1929
- }) {
1930
- if (!isCustomReasoning(reasoning)) {
1931
- return void 0;
1932
- }
1933
- if (isGemini3Model(modelId) && !modelId.includes("gemini-3-pro-image")) {
1934
- return resolveGemini3ThinkingConfig({ reasoning, warnings });
1935
- }
1936
- return resolveGemini25ThinkingConfig({ reasoning, modelId, warnings });
1937
- }
1938
- function resolveGemini3ThinkingConfig({
1939
- reasoning,
1940
- warnings
1941
- }) {
1942
- if (reasoning === "none") {
1943
- return { thinkingLevel: "minimal" };
1944
- }
1945
- const thinkingLevel = mapReasoningToProviderEffort({
1946
- reasoning,
1947
- effortMap: {
1948
- minimal: "minimal",
1949
- low: "low",
1950
- medium: "medium",
1951
- high: "high",
1952
- xhigh: "high"
1953
- },
1954
- warnings
1955
- });
1956
- if (thinkingLevel == null) {
1957
- return void 0;
1958
- }
1959
- return { thinkingLevel };
1960
- }
1961
- function resolveGemini25ThinkingConfig({
1962
- reasoning,
1963
- modelId,
1964
- warnings
1965
- }) {
1966
- if (reasoning === "none") {
1967
- return { thinkingBudget: 0 };
1968
- }
1969
- const thinkingBudget = mapReasoningToProviderBudget({
1970
- reasoning,
1971
- maxOutputTokens: getMaxOutputTokensForGemini25Model(),
1972
- maxReasoningBudget: getMaxThinkingTokensForGemini25Model(modelId),
1973
- minReasoningBudget: 0,
1974
- warnings
1975
- });
1976
- if (thinkingBudget == null) {
1977
- return void 0;
1978
- }
1979
- return { thinkingBudget };
1980
- }
1981
- function extractSources({
1982
- groundingMetadata,
1983
- generateId: generateId2
1984
- }) {
1985
- var _a, _b, _c, _d, _e, _f;
1986
- if (!(groundingMetadata == null ? void 0 : groundingMetadata.groundingChunks)) {
1987
- return void 0;
1988
- }
1989
- const sources = [];
1990
- for (const chunk of groundingMetadata.groundingChunks) {
1991
- if (chunk.web != null) {
1992
- sources.push({
1993
- type: "source",
1994
- sourceType: "url",
1995
- id: generateId2(),
1996
- url: chunk.web.uri,
1997
- title: (_a = chunk.web.title) != null ? _a : void 0
1998
- });
1999
- } else if (chunk.image != null) {
2000
- sources.push({
2001
- type: "source",
2002
- sourceType: "url",
2003
- id: generateId2(),
2004
- // Google requires attribution to the source URI, not the actual image URI.
2005
- // TODO: add another type in v7 to allow both the image and source URL to be included separately
2006
- url: chunk.image.sourceUri,
2007
- title: (_b = chunk.image.title) != null ? _b : void 0
2008
- });
2009
- } else if (chunk.retrievedContext != null) {
2010
- const uri = chunk.retrievedContext.uri;
2011
- const fileSearchStore = chunk.retrievedContext.fileSearchStore;
2012
- if (uri && (uri.startsWith("http://") || uri.startsWith("https://"))) {
2013
- sources.push({
2014
- type: "source",
2015
- sourceType: "url",
2016
- id: generateId2(),
2017
- url: uri,
2018
- title: (_c = chunk.retrievedContext.title) != null ? _c : void 0
2019
- });
2020
- } else if (uri) {
2021
- const title = (_d = chunk.retrievedContext.title) != null ? _d : "Unknown Document";
2022
- let mediaType = "application/octet-stream";
2023
- let filename = void 0;
2024
- if (uri.endsWith(".pdf")) {
2025
- mediaType = "application/pdf";
2026
- filename = uri.split("/").pop();
2027
- } else if (uri.endsWith(".txt")) {
2028
- mediaType = "text/plain";
2029
- filename = uri.split("/").pop();
2030
- } else if (uri.endsWith(".docx")) {
2031
- mediaType = "application/vnd.openxmlformats-officedocument.wordprocessingml.document";
2032
- filename = uri.split("/").pop();
2033
- } else if (uri.endsWith(".doc")) {
2034
- mediaType = "application/msword";
2035
- filename = uri.split("/").pop();
2036
- } else if (uri.match(/\.(md|markdown)$/)) {
2037
- mediaType = "text/markdown";
2038
- filename = uri.split("/").pop();
2039
- } else {
2040
- filename = uri.split("/").pop();
2041
- }
2042
- sources.push({
2043
- type: "source",
2044
- sourceType: "document",
2045
- id: generateId2(),
2046
- mediaType,
2047
- title,
2048
- filename
2049
- });
2050
- } else if (fileSearchStore) {
2051
- const title = (_e = chunk.retrievedContext.title) != null ? _e : "Unknown Document";
2052
- sources.push({
2053
- type: "source",
2054
- sourceType: "document",
2055
- id: generateId2(),
2056
- mediaType: "application/octet-stream",
2057
- title,
2058
- filename: fileSearchStore.split("/").pop()
2059
- });
2060
- }
2061
- } else if (chunk.maps != null) {
2062
- if (chunk.maps.uri) {
2063
- sources.push({
2064
- type: "source",
2065
- sourceType: "url",
2066
- id: generateId2(),
2067
- url: chunk.maps.uri,
2068
- title: (_f = chunk.maps.title) != null ? _f : void 0
2069
- });
2070
- }
2071
- }
2072
- }
2073
- return sources.length > 0 ? sources : void 0;
2074
- }
2075
- var getGroundingMetadataSchema = () => z3.object({
2076
- webSearchQueries: z3.array(z3.string()).nullish(),
2077
- imageSearchQueries: z3.array(z3.string()).nullish(),
2078
- retrievalQueries: z3.array(z3.string()).nullish(),
2079
- searchEntryPoint: z3.object({ renderedContent: z3.string() }).nullish(),
2080
- groundingChunks: z3.array(
2081
- z3.object({
2082
- web: z3.object({ uri: z3.string(), title: z3.string().nullish() }).nullish(),
2083
- image: z3.object({
2084
- sourceUri: z3.string(),
2085
- imageUri: z3.string(),
2086
- title: z3.string().nullish(),
2087
- domain: z3.string().nullish()
2088
- }).nullish(),
2089
- retrievedContext: z3.object({
2090
- uri: z3.string().nullish(),
2091
- title: z3.string().nullish(),
2092
- text: z3.string().nullish(),
2093
- fileSearchStore: z3.string().nullish()
2094
- }).nullish(),
2095
- maps: z3.object({
2096
- uri: z3.string().nullish(),
2097
- title: z3.string().nullish(),
2098
- text: z3.string().nullish(),
2099
- placeId: z3.string().nullish()
2100
- }).nullish()
2101
- })
2102
- ).nullish(),
2103
- groundingSupports: z3.array(
2104
- z3.object({
2105
- segment: z3.object({
2106
- startIndex: z3.number().nullish(),
2107
- endIndex: z3.number().nullish(),
2108
- text: z3.string().nullish()
2109
- }).nullish(),
2110
- segment_text: z3.string().nullish(),
2111
- groundingChunkIndices: z3.array(z3.number()).nullish(),
2112
- supportChunkIndices: z3.array(z3.number()).nullish(),
2113
- confidenceScores: z3.array(z3.number()).nullish(),
2114
- confidenceScore: z3.array(z3.number()).nullish()
2115
- })
2116
- ).nullish(),
2117
- retrievalMetadata: z3.union([
2118
- z3.object({
2119
- webDynamicRetrievalScore: z3.number()
2120
- }),
2121
- z3.object({})
2122
- ]).nullish()
2123
- });
2124
- var partialArgSchema = z3.object({
2125
- jsonPath: z3.string(),
2126
- stringValue: z3.string().nullish(),
2127
- numberValue: z3.number().nullish(),
2128
- boolValue: z3.boolean().nullish(),
2129
- nullValue: z3.unknown().nullish(),
2130
- willContinue: z3.boolean().nullish()
2131
- });
2132
- var getContentSchema = () => z3.object({
2133
- parts: z3.array(
2134
- z3.union([
2135
- // note: order matters since text can be fully empty
2136
- z3.object({
2137
- functionCall: z3.object({
2138
- name: z3.string().nullish(),
2139
- args: z3.unknown().nullish(),
2140
- partialArgs: z3.array(partialArgSchema).nullish(),
2141
- willContinue: z3.boolean().nullish()
2142
- }),
2143
- thoughtSignature: z3.string().nullish()
2144
- }),
2145
- z3.object({
2146
- inlineData: z3.object({
2147
- mimeType: z3.string(),
2148
- data: z3.string()
2149
- }),
2150
- thought: z3.boolean().nullish(),
2151
- thoughtSignature: z3.string().nullish()
2152
- }),
2153
- z3.object({
2154
- toolCall: z3.object({
2155
- toolType: z3.string(),
2156
- args: z3.unknown().nullish(),
2157
- id: z3.string()
2158
- }),
2159
- thoughtSignature: z3.string().nullish()
2160
- }),
2161
- z3.object({
2162
- toolResponse: z3.object({
2163
- toolType: z3.string(),
2164
- response: z3.unknown().nullish(),
2165
- id: z3.string()
2166
- }),
2167
- thoughtSignature: z3.string().nullish()
2168
- }),
2169
- z3.object({
2170
- executableCode: z3.object({
2171
- language: z3.string(),
2172
- code: z3.string()
2173
- }).nullish(),
2174
- codeExecutionResult: z3.object({
2175
- outcome: z3.string(),
2176
- output: z3.string().nullish()
2177
- }).nullish(),
2178
- text: z3.string().nullish(),
2179
- thought: z3.boolean().nullish(),
2180
- thoughtSignature: z3.string().nullish()
2181
- })
2182
- ])
2183
- ).nullish()
2184
- });
2185
- var getSafetyRatingSchema = () => z3.object({
2186
- category: z3.string().nullish(),
2187
- probability: z3.string().nullish(),
2188
- probabilityScore: z3.number().nullish(),
2189
- severity: z3.string().nullish(),
2190
- severityScore: z3.number().nullish(),
2191
- blocked: z3.boolean().nullish()
2192
- });
2193
- var tokenDetailsSchema = z3.array(
2194
- z3.object({
2195
- modality: z3.string(),
2196
- tokenCount: z3.number()
2197
- })
2198
- ).nullish();
2199
- var usageSchema = z3.object({
2200
- cachedContentTokenCount: z3.number().nullish(),
2201
- thoughtsTokenCount: z3.number().nullish(),
2202
- promptTokenCount: z3.number().nullish(),
2203
- candidatesTokenCount: z3.number().nullish(),
2204
- totalTokenCount: z3.number().nullish(),
2205
- // https://cloud.google.com/vertex-ai/generative-ai/docs/reference/rest/v1/GenerateContentResponse#TrafficType
2206
- trafficType: z3.string().nullish(),
2207
- // https://ai.google.dev/api/generate-content#Modality
2208
- promptTokensDetails: tokenDetailsSchema,
2209
- candidatesTokensDetails: tokenDetailsSchema
2210
- });
2211
- var getUrlContextMetadataSchema = () => z3.object({
2212
- urlMetadata: z3.array(
2213
- z3.object({
2214
- retrievedUrl: z3.string(),
2215
- urlRetrievalStatus: z3.string()
2216
- })
2217
- ).nullish()
2218
- });
2219
- var responseSchema = lazySchema3(
2220
- () => zodSchema3(
2221
- z3.object({
2222
- candidates: z3.array(
2223
- z3.object({
2224
- content: getContentSchema().nullish().or(z3.object({}).strict()),
2225
- finishReason: z3.string().nullish(),
2226
- finishMessage: z3.string().nullish(),
2227
- safetyRatings: z3.array(getSafetyRatingSchema()).nullish(),
2228
- groundingMetadata: getGroundingMetadataSchema().nullish(),
2229
- urlContextMetadata: getUrlContextMetadataSchema().nullish()
2230
- })
2231
- ),
2232
- usageMetadata: usageSchema.nullish(),
2233
- promptFeedback: z3.object({
2234
- blockReason: z3.string().nullish(),
2235
- safetyRatings: z3.array(getSafetyRatingSchema()).nullish()
2236
- }).nullish(),
2237
- serviceTier: z3.string().nullish()
2238
- })
2239
- )
2240
- );
2241
- var chunkSchema = lazySchema3(
2242
- () => zodSchema3(
2243
- z3.object({
2244
- candidates: z3.array(
2245
- z3.object({
2246
- content: getContentSchema().nullish(),
2247
- finishReason: z3.string().nullish(),
2248
- finishMessage: z3.string().nullish(),
2249
- safetyRatings: z3.array(getSafetyRatingSchema()).nullish(),
2250
- groundingMetadata: getGroundingMetadataSchema().nullish(),
2251
- urlContextMetadata: getUrlContextMetadataSchema().nullish()
2252
- })
2253
- ).nullish(),
2254
- usageMetadata: usageSchema.nullish(),
2255
- promptFeedback: z3.object({
2256
- blockReason: z3.string().nullish(),
2257
- safetyRatings: z3.array(getSafetyRatingSchema()).nullish()
2258
- }).nullish(),
2259
- serviceTier: z3.string().nullish()
2260
- })
2261
- )
2262
- );
2263
-
2264
- // src/tool/code-execution.ts
2265
- import { createProviderToolFactoryWithOutputSchema } from "@ai-sdk/provider-utils";
2266
- import { z as z4 } from "zod/v4";
2267
- var codeExecution = createProviderToolFactoryWithOutputSchema({
2268
- id: "google.code_execution",
2269
- inputSchema: z4.object({
2270
- language: z4.string().describe("The programming language of the code."),
2271
- code: z4.string().describe("The code to be executed.")
2272
- }),
2273
- outputSchema: z4.object({
2274
- outcome: z4.string().describe('The outcome of the execution (e.g., "OUTCOME_OK").'),
2275
- output: z4.string().describe("The output from the code execution.")
2276
- })
2277
- });
2278
-
2279
- // src/tool/enterprise-web-search.ts
2280
- import {
2281
- createProviderToolFactory,
2282
- lazySchema as lazySchema4,
2283
- zodSchema as zodSchema4
2284
- } from "@ai-sdk/provider-utils";
2285
- import { z as z5 } from "zod/v4";
2286
- var enterpriseWebSearch = createProviderToolFactory({
2287
- id: "google.enterprise_web_search",
2288
- inputSchema: lazySchema4(() => zodSchema4(z5.object({})))
2289
- });
2290
-
2291
- // src/tool/file-search.ts
2292
- import {
2293
- createProviderToolFactory as createProviderToolFactory2,
2294
- lazySchema as lazySchema5,
2295
- zodSchema as zodSchema5
2296
- } from "@ai-sdk/provider-utils";
2297
- import { z as z6 } from "zod/v4";
2298
- var fileSearchArgsBaseSchema = z6.object({
2299
- /** The names of the file_search_stores to retrieve from.
2300
- * Example: `fileSearchStores/my-file-search-store-123`
2301
- */
2302
- fileSearchStoreNames: z6.array(z6.string()).describe(
2303
- "The names of the file_search_stores to retrieve from. Example: `fileSearchStores/my-file-search-store-123`"
2304
- ),
2305
- /** The number of file search retrieval chunks to retrieve. */
2306
- topK: z6.number().int().positive().describe("The number of file search retrieval chunks to retrieve.").optional(),
2307
- /** Metadata filter to apply to the file search retrieval documents.
2308
- * See https://google.aip.dev/160 for the syntax of the filter expression.
2309
- */
2310
- metadataFilter: z6.string().describe(
2311
- "Metadata filter to apply to the file search retrieval documents. See https://google.aip.dev/160 for the syntax of the filter expression."
2312
- ).optional()
2313
- }).passthrough();
2314
- var fileSearchArgsSchema = lazySchema5(
2315
- () => zodSchema5(fileSearchArgsBaseSchema)
2316
- );
2317
- var fileSearch = createProviderToolFactory2({
2318
- id: "google.file_search",
2319
- inputSchema: fileSearchArgsSchema
2320
- });
2321
-
2322
- // src/tool/google-maps.ts
2323
- import {
2324
- createProviderToolFactory as createProviderToolFactory3,
2325
- lazySchema as lazySchema6,
2326
- zodSchema as zodSchema6
2327
- } from "@ai-sdk/provider-utils";
2328
- import { z as z7 } from "zod/v4";
2329
- var googleMaps = createProviderToolFactory3({
2330
- id: "google.google_maps",
2331
- inputSchema: lazySchema6(() => zodSchema6(z7.object({})))
2332
- });
2333
-
2334
- // src/tool/google-search.ts
2335
- import {
2336
- createProviderToolFactory as createProviderToolFactory4,
2337
- lazySchema as lazySchema7,
2338
- zodSchema as zodSchema7
2339
- } from "@ai-sdk/provider-utils";
2340
- import { z as z8 } from "zod/v4";
2341
- var googleSearchToolArgsBaseSchema = z8.object({
2342
- searchTypes: z8.object({
2343
- webSearch: z8.object({}).optional(),
2344
- imageSearch: z8.object({}).optional()
2345
- }).optional(),
2346
- timeRangeFilter: z8.object({
2347
- startTime: z8.string(),
2348
- endTime: z8.string()
2349
- }).optional()
2350
- }).passthrough();
2351
- var googleSearchToolArgsSchema = lazySchema7(
2352
- () => zodSchema7(googleSearchToolArgsBaseSchema)
2353
- );
2354
- var googleSearch = createProviderToolFactory4(
2355
- {
2356
- id: "google.google_search",
2357
- inputSchema: googleSearchToolArgsSchema
2358
- }
2359
- );
2360
-
2361
- // src/tool/url-context.ts
2362
- import {
2363
- createProviderToolFactory as createProviderToolFactory5,
2364
- lazySchema as lazySchema8,
2365
- zodSchema as zodSchema8
2366
- } from "@ai-sdk/provider-utils";
2367
- import { z as z9 } from "zod/v4";
2368
- var urlContext = createProviderToolFactory5({
2369
- id: "google.url_context",
2370
- inputSchema: lazySchema8(() => zodSchema8(z9.object({})))
2371
- });
2372
-
2373
- // src/tool/vertex-rag-store.ts
2374
- import { createProviderToolFactory as createProviderToolFactory6 } from "@ai-sdk/provider-utils";
2375
- import { z as z10 } from "zod/v4";
2376
- var vertexRagStore = createProviderToolFactory6({
2377
- id: "google.vertex_rag_store",
2378
- inputSchema: z10.object({
2379
- ragCorpus: z10.string(),
2380
- topK: z10.number().optional()
2381
- })
2382
- });
2383
-
2384
- // src/google-tools.ts
2385
- var googleTools = {
2386
- /**
2387
- * Creates a Google search tool that gives Google direct access to real-time web content.
2388
- * Must have name "google_search".
2389
- */
2390
- googleSearch,
2391
- /**
2392
- * Creates an Enterprise Web Search tool for grounding responses using a compliance-focused web index.
2393
- * Designed for highly-regulated industries (finance, healthcare, public sector).
2394
- * Does not log customer data and supports VPC service controls.
2395
- * Must have name "enterprise_web_search".
2396
- *
2397
- * @note Only available on Vertex AI. Requires Gemini 2.0 or newer.
2398
- *
2399
- * @see https://cloud.google.com/vertex-ai/generative-ai/docs/grounding/web-grounding-enterprise
2400
- */
2401
- enterpriseWebSearch,
2402
- /**
2403
- * Creates a Google Maps grounding tool that gives the model access to Google Maps data.
2404
- * Must have name "google_maps".
2405
- *
2406
- * @see https://ai.google.dev/gemini-api/docs/maps-grounding
2407
- * @see https://cloud.google.com/vertex-ai/generative-ai/docs/grounding/grounding-with-google-maps
2408
- */
2409
- googleMaps,
2410
- /**
2411
- * Creates a URL context tool that gives Google direct access to real-time web content.
2412
- * Must have name "url_context".
2413
- */
2414
- urlContext,
2415
- /**
2416
- * Enables Retrieval Augmented Generation (RAG) via the Gemini File Search tool.
2417
- * Must have name "file_search".
2418
- *
2419
- * @param fileSearchStoreNames - Fully-qualified File Search store resource names.
2420
- * @param metadataFilter - Optional filter expression to restrict the files that can be retrieved.
2421
- * @param topK - Optional result limit for the number of chunks returned from File Search.
2422
- *
2423
- * @see https://ai.google.dev/gemini-api/docs/file-search
2424
- */
2425
- fileSearch,
2426
- /**
2427
- * A tool that enables the model to generate and run Python code.
2428
- * Must have name "code_execution".
2429
- *
2430
- * @note Ensure the selected model supports Code Execution.
2431
- * Multi-tool usage with the code execution tool is typically compatible with Gemini >=2 models.
2432
- *
2433
- * @see https://ai.google.dev/gemini-api/docs/code-execution (Google AI)
2434
- * @see https://cloud.google.com/vertex-ai/generative-ai/docs/model-reference/code-execution-api (Vertex AI)
2435
- */
2436
- codeExecution,
2437
- /**
2438
- * Creates a Vertex RAG Store tool that enables the model to perform RAG searches against a Vertex RAG Store.
2439
- * Must have name "vertex_rag_store".
2440
- */
2441
- vertexRagStore
2442
- };
2443
- export {
2444
- GoogleGenerativeAILanguageModel,
2445
- getGroundingMetadataSchema,
2446
- getUrlContextMetadataSchema,
2447
- googleTools
2448
- };
2449
- //# sourceMappingURL=index.mjs.map