@ai-sdk/google 4.0.0-beta.36 → 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.
package/dist/index.mjs DELETED
@@ -1,3439 +0,0 @@
1
- // src/google-provider.ts
2
- import {
3
- generateId as generateId2,
4
- loadApiKey,
5
- withoutTrailingSlash,
6
- withUserAgentSuffix
7
- } from "@ai-sdk/provider-utils";
8
-
9
- // src/version.ts
10
- var VERSION = true ? "4.0.0-beta.36" : "0.0.0-test";
11
-
12
- // src/google-generative-ai-embedding-model.ts
13
- import {
14
- TooManyEmbeddingValuesForCallError
15
- } from "@ai-sdk/provider";
16
- import {
17
- combineHeaders,
18
- createJsonResponseHandler,
19
- lazySchema as lazySchema3,
20
- parseProviderOptions,
21
- postJsonToApi,
22
- resolve,
23
- zodSchema as zodSchema3
24
- } from "@ai-sdk/provider-utils";
25
- import { z as z3 } from "zod/v4";
26
-
27
- // src/google-error.ts
28
- import {
29
- createJsonErrorResponseHandler,
30
- lazySchema,
31
- zodSchema
32
- } from "@ai-sdk/provider-utils";
33
- import { z } from "zod/v4";
34
- var googleErrorDataSchema = lazySchema(
35
- () => zodSchema(
36
- z.object({
37
- error: z.object({
38
- code: z.number().nullable(),
39
- message: z.string(),
40
- status: z.string()
41
- })
42
- })
43
- )
44
- );
45
- var googleFailedResponseHandler = createJsonErrorResponseHandler({
46
- errorSchema: googleErrorDataSchema,
47
- errorToMessage: (data) => data.error.message
48
- });
49
-
50
- // src/google-generative-ai-embedding-options.ts
51
- import {
52
- lazySchema as lazySchema2,
53
- zodSchema as zodSchema2
54
- } from "@ai-sdk/provider-utils";
55
- import { z as z2 } from "zod/v4";
56
- var googleEmbeddingContentPartSchema = z2.union([
57
- z2.object({ text: z2.string() }),
58
- z2.object({
59
- inlineData: z2.object({
60
- mimeType: z2.string(),
61
- data: z2.string()
62
- })
63
- })
64
- ]);
65
- var googleEmbeddingModelOptions = lazySchema2(
66
- () => zodSchema2(
67
- z2.object({
68
- /**
69
- * Optional. Optional reduced dimension for the output embedding.
70
- * If set, excessive values in the output embedding are truncated from the end.
71
- */
72
- outputDimensionality: z2.number().optional(),
73
- /**
74
- * Optional. Specifies the task type for generating embeddings.
75
- * Supported task types:
76
- * - SEMANTIC_SIMILARITY: Optimized for text similarity.
77
- * - CLASSIFICATION: Optimized for text classification.
78
- * - CLUSTERING: Optimized for clustering texts based on similarity.
79
- * - RETRIEVAL_DOCUMENT: Optimized for document retrieval.
80
- * - RETRIEVAL_QUERY: Optimized for query-based retrieval.
81
- * - QUESTION_ANSWERING: Optimized for answering questions.
82
- * - FACT_VERIFICATION: Optimized for verifying factual information.
83
- * - CODE_RETRIEVAL_QUERY: Optimized for retrieving code blocks based on natural language queries.
84
- */
85
- taskType: z2.enum([
86
- "SEMANTIC_SIMILARITY",
87
- "CLASSIFICATION",
88
- "CLUSTERING",
89
- "RETRIEVAL_DOCUMENT",
90
- "RETRIEVAL_QUERY",
91
- "QUESTION_ANSWERING",
92
- "FACT_VERIFICATION",
93
- "CODE_RETRIEVAL_QUERY"
94
- ]).optional(),
95
- /**
96
- * Optional. Per-value multimodal content parts for embedding non-text
97
- * content (images, video, PDF, audio). Each entry corresponds to the
98
- * embedding value at the same index and its parts are merged with the
99
- * text value in the request. Use `null` for entries that are text-only.
100
- *
101
- * The array length must match the number of values being embedded. In
102
- * the case of a single embedding, the array length must be 1.
103
- */
104
- content: z2.array(z2.array(googleEmbeddingContentPartSchema).min(1).nullable()).optional()
105
- })
106
- )
107
- );
108
-
109
- // src/google-generative-ai-embedding-model.ts
110
- var GoogleGenerativeAIEmbeddingModel = class {
111
- constructor(modelId, config) {
112
- this.specificationVersion = "v4";
113
- this.maxEmbeddingsPerCall = 2048;
114
- this.supportsParallelCalls = true;
115
- this.modelId = modelId;
116
- this.config = config;
117
- }
118
- get provider() {
119
- return this.config.provider;
120
- }
121
- async doEmbed({
122
- values,
123
- headers,
124
- abortSignal,
125
- providerOptions
126
- }) {
127
- const googleOptions = await parseProviderOptions({
128
- provider: "google",
129
- providerOptions,
130
- schema: googleEmbeddingModelOptions
131
- });
132
- if (values.length > this.maxEmbeddingsPerCall) {
133
- throw new TooManyEmbeddingValuesForCallError({
134
- provider: this.provider,
135
- modelId: this.modelId,
136
- maxEmbeddingsPerCall: this.maxEmbeddingsPerCall,
137
- values
138
- });
139
- }
140
- const mergedHeaders = combineHeaders(
141
- await resolve(this.config.headers),
142
- headers
143
- );
144
- const multimodalContent = googleOptions == null ? void 0 : googleOptions.content;
145
- if (multimodalContent != null && multimodalContent.length !== values.length) {
146
- throw new Error(
147
- `The number of multimodal content entries (${multimodalContent.length}) must match the number of values (${values.length}).`
148
- );
149
- }
150
- if (values.length === 1) {
151
- const valueParts = multimodalContent == null ? void 0 : multimodalContent[0];
152
- const textPart = values[0] ? [{ text: values[0] }] : [];
153
- const parts = valueParts != null ? [...textPart, ...valueParts] : [{ text: values[0] }];
154
- const {
155
- responseHeaders: responseHeaders2,
156
- value: response2,
157
- rawValue: rawValue2
158
- } = await postJsonToApi({
159
- url: `${this.config.baseURL}/models/${this.modelId}:embedContent`,
160
- headers: mergedHeaders,
161
- body: {
162
- model: `models/${this.modelId}`,
163
- content: {
164
- parts
165
- },
166
- outputDimensionality: googleOptions == null ? void 0 : googleOptions.outputDimensionality,
167
- taskType: googleOptions == null ? void 0 : googleOptions.taskType
168
- },
169
- failedResponseHandler: googleFailedResponseHandler,
170
- successfulResponseHandler: createJsonResponseHandler(
171
- googleGenerativeAISingleEmbeddingResponseSchema
172
- ),
173
- abortSignal,
174
- fetch: this.config.fetch
175
- });
176
- return {
177
- warnings: [],
178
- embeddings: [response2.embedding.values],
179
- usage: void 0,
180
- response: { headers: responseHeaders2, body: rawValue2 }
181
- };
182
- }
183
- const {
184
- responseHeaders,
185
- value: response,
186
- rawValue
187
- } = await postJsonToApi({
188
- url: `${this.config.baseURL}/models/${this.modelId}:batchEmbedContents`,
189
- headers: mergedHeaders,
190
- body: {
191
- requests: values.map((value, index) => {
192
- const valueParts = multimodalContent == null ? void 0 : multimodalContent[index];
193
- const textPart = value ? [{ text: value }] : [];
194
- return {
195
- model: `models/${this.modelId}`,
196
- content: {
197
- role: "user",
198
- parts: valueParts != null ? [...textPart, ...valueParts] : [{ text: value }]
199
- },
200
- outputDimensionality: googleOptions == null ? void 0 : googleOptions.outputDimensionality,
201
- taskType: googleOptions == null ? void 0 : googleOptions.taskType
202
- };
203
- })
204
- },
205
- failedResponseHandler: googleFailedResponseHandler,
206
- successfulResponseHandler: createJsonResponseHandler(
207
- googleGenerativeAITextEmbeddingResponseSchema
208
- ),
209
- abortSignal,
210
- fetch: this.config.fetch
211
- });
212
- return {
213
- warnings: [],
214
- embeddings: response.embeddings.map((item) => item.values),
215
- usage: void 0,
216
- response: { headers: responseHeaders, body: rawValue }
217
- };
218
- }
219
- };
220
- var googleGenerativeAITextEmbeddingResponseSchema = lazySchema3(
221
- () => zodSchema3(
222
- z3.object({
223
- embeddings: z3.array(z3.object({ values: z3.array(z3.number()) }))
224
- })
225
- )
226
- );
227
- var googleGenerativeAISingleEmbeddingResponseSchema = lazySchema3(
228
- () => zodSchema3(
229
- z3.object({
230
- embedding: z3.object({ values: z3.array(z3.number()) })
231
- })
232
- )
233
- );
234
-
235
- // src/google-generative-ai-language-model.ts
236
- import {
237
- combineHeaders as combineHeaders2,
238
- createEventSourceResponseHandler,
239
- createJsonResponseHandler as createJsonResponseHandler2,
240
- generateId,
241
- isCustomReasoning,
242
- lazySchema as lazySchema5,
243
- mapReasoningToProviderBudget,
244
- mapReasoningToProviderEffort,
245
- parseProviderOptions as parseProviderOptions2,
246
- postJsonToApi as postJsonToApi2,
247
- resolve as resolve2,
248
- zodSchema as zodSchema5
249
- } from "@ai-sdk/provider-utils";
250
- import { z as z5 } from "zod/v4";
251
-
252
- // src/convert-google-generative-ai-usage.ts
253
- function convertGoogleGenerativeAIUsage(usage) {
254
- var _a, _b, _c, _d;
255
- if (usage == null) {
256
- return {
257
- inputTokens: {
258
- total: void 0,
259
- noCache: void 0,
260
- cacheRead: void 0,
261
- cacheWrite: void 0
262
- },
263
- outputTokens: {
264
- total: void 0,
265
- text: void 0,
266
- reasoning: void 0
267
- },
268
- raw: void 0
269
- };
270
- }
271
- const promptTokens = (_a = usage.promptTokenCount) != null ? _a : 0;
272
- const candidatesTokens = (_b = usage.candidatesTokenCount) != null ? _b : 0;
273
- const cachedContentTokens = (_c = usage.cachedContentTokenCount) != null ? _c : 0;
274
- const thoughtsTokens = (_d = usage.thoughtsTokenCount) != null ? _d : 0;
275
- return {
276
- inputTokens: {
277
- total: promptTokens,
278
- noCache: promptTokens - cachedContentTokens,
279
- cacheRead: cachedContentTokens,
280
- cacheWrite: void 0
281
- },
282
- outputTokens: {
283
- total: candidatesTokens + thoughtsTokens,
284
- text: candidatesTokens,
285
- reasoning: thoughtsTokens
286
- },
287
- raw: usage
288
- };
289
- }
290
-
291
- // src/convert-json-schema-to-openapi-schema.ts
292
- function convertJSONSchemaToOpenAPISchema(jsonSchema, isRoot = true) {
293
- if (jsonSchema == null) {
294
- return void 0;
295
- }
296
- if (isEmptyObjectSchema(jsonSchema)) {
297
- if (isRoot) {
298
- return void 0;
299
- }
300
- if (typeof jsonSchema === "object" && jsonSchema.description) {
301
- return { type: "object", description: jsonSchema.description };
302
- }
303
- return { type: "object" };
304
- }
305
- if (typeof jsonSchema === "boolean") {
306
- return { type: "boolean", properties: {} };
307
- }
308
- const {
309
- type,
310
- description,
311
- required,
312
- properties,
313
- items,
314
- allOf,
315
- anyOf,
316
- oneOf,
317
- format,
318
- const: constValue,
319
- minLength,
320
- enum: enumValues
321
- } = jsonSchema;
322
- const result = {};
323
- if (description) result.description = description;
324
- if (required) result.required = required;
325
- if (format) result.format = format;
326
- if (constValue !== void 0) {
327
- result.enum = [constValue];
328
- }
329
- if (type) {
330
- if (Array.isArray(type)) {
331
- const hasNull = type.includes("null");
332
- const nonNullTypes = type.filter((t) => t !== "null");
333
- if (nonNullTypes.length === 0) {
334
- result.type = "null";
335
- } else {
336
- result.anyOf = nonNullTypes.map((t) => ({ type: t }));
337
- if (hasNull) {
338
- result.nullable = true;
339
- }
340
- }
341
- } else {
342
- result.type = type;
343
- }
344
- }
345
- if (enumValues !== void 0) {
346
- result.enum = enumValues;
347
- }
348
- if (properties != null) {
349
- result.properties = Object.entries(properties).reduce(
350
- (acc, [key, value]) => {
351
- acc[key] = convertJSONSchemaToOpenAPISchema(value, false);
352
- return acc;
353
- },
354
- {}
355
- );
356
- }
357
- if (items) {
358
- result.items = Array.isArray(items) ? items.map((item) => convertJSONSchemaToOpenAPISchema(item, false)) : convertJSONSchemaToOpenAPISchema(items, false);
359
- }
360
- if (allOf) {
361
- result.allOf = allOf.map(
362
- (item) => convertJSONSchemaToOpenAPISchema(item, false)
363
- );
364
- }
365
- if (anyOf) {
366
- if (anyOf.some(
367
- (schema) => typeof schema === "object" && (schema == null ? void 0 : schema.type) === "null"
368
- )) {
369
- const nonNullSchemas = anyOf.filter(
370
- (schema) => !(typeof schema === "object" && (schema == null ? void 0 : schema.type) === "null")
371
- );
372
- if (nonNullSchemas.length === 1) {
373
- const converted = convertJSONSchemaToOpenAPISchema(
374
- nonNullSchemas[0],
375
- false
376
- );
377
- if (typeof converted === "object") {
378
- result.nullable = true;
379
- Object.assign(result, converted);
380
- }
381
- } else {
382
- result.anyOf = nonNullSchemas.map(
383
- (item) => convertJSONSchemaToOpenAPISchema(item, false)
384
- );
385
- result.nullable = true;
386
- }
387
- } else {
388
- result.anyOf = anyOf.map(
389
- (item) => convertJSONSchemaToOpenAPISchema(item, false)
390
- );
391
- }
392
- }
393
- if (oneOf) {
394
- result.oneOf = oneOf.map(
395
- (item) => convertJSONSchemaToOpenAPISchema(item, false)
396
- );
397
- }
398
- if (minLength !== void 0) {
399
- result.minLength = minLength;
400
- }
401
- return result;
402
- }
403
- function isEmptyObjectSchema(jsonSchema) {
404
- return jsonSchema != null && typeof jsonSchema === "object" && jsonSchema.type === "object" && (jsonSchema.properties == null || Object.keys(jsonSchema.properties).length === 0) && !jsonSchema.additionalProperties;
405
- }
406
-
407
- // src/convert-to-google-generative-ai-messages.ts
408
- import {
409
- UnsupportedFunctionalityError
410
- } from "@ai-sdk/provider";
411
- import {
412
- convertToBase64,
413
- isProviderReference,
414
- resolveProviderReference
415
- } from "@ai-sdk/provider-utils";
416
- var dataUrlRegex = /^data:([^;,]+);base64,(.+)$/s;
417
- function parseBase64DataUrl(value) {
418
- const match = dataUrlRegex.exec(value);
419
- if (match == null) {
420
- return void 0;
421
- }
422
- return {
423
- mediaType: match[1],
424
- data: match[2]
425
- };
426
- }
427
- function convertUrlToolResultPart(url) {
428
- const parsedDataUrl = parseBase64DataUrl(url);
429
- if (parsedDataUrl == null) {
430
- return void 0;
431
- }
432
- return {
433
- inlineData: {
434
- mimeType: parsedDataUrl.mediaType,
435
- data: parsedDataUrl.data
436
- }
437
- };
438
- }
439
- function appendToolResultParts(parts, toolName, outputValue) {
440
- const functionResponseParts = [];
441
- const responseTextParts = [];
442
- for (const contentPart of outputValue) {
443
- switch (contentPart.type) {
444
- case "text": {
445
- responseTextParts.push(contentPart.text);
446
- break;
447
- }
448
- case "image-data":
449
- case "file-data": {
450
- functionResponseParts.push({
451
- inlineData: {
452
- mimeType: contentPart.mediaType,
453
- data: contentPart.data
454
- }
455
- });
456
- break;
457
- }
458
- case "image-url":
459
- case "file-url": {
460
- const functionResponsePart = convertUrlToolResultPart(
461
- contentPart.url
462
- );
463
- if (functionResponsePart != null) {
464
- functionResponseParts.push(functionResponsePart);
465
- } else {
466
- responseTextParts.push(JSON.stringify(contentPart));
467
- }
468
- break;
469
- }
470
- default: {
471
- responseTextParts.push(JSON.stringify(contentPart));
472
- break;
473
- }
474
- }
475
- }
476
- parts.push({
477
- functionResponse: {
478
- name: toolName,
479
- response: {
480
- name: toolName,
481
- content: responseTextParts.length > 0 ? responseTextParts.join("\n") : "Tool executed successfully."
482
- },
483
- ...functionResponseParts.length > 0 ? { parts: functionResponseParts } : {}
484
- }
485
- });
486
- }
487
- function appendLegacyToolResultParts(parts, toolName, outputValue) {
488
- for (const contentPart of outputValue) {
489
- switch (contentPart.type) {
490
- case "text":
491
- parts.push({
492
- functionResponse: {
493
- name: toolName,
494
- response: {
495
- name: toolName,
496
- content: contentPart.text
497
- }
498
- }
499
- });
500
- break;
501
- case "image-data":
502
- parts.push(
503
- {
504
- inlineData: {
505
- mimeType: String(contentPart.mediaType),
506
- data: String(contentPart.data)
507
- }
508
- },
509
- {
510
- text: "Tool executed successfully and returned this image as a response"
511
- }
512
- );
513
- break;
514
- default:
515
- parts.push({ text: JSON.stringify(contentPart) });
516
- break;
517
- }
518
- }
519
- }
520
- function convertToGoogleGenerativeAIMessages(prompt, options) {
521
- var _a, _b, _c, _d, _e, _f, _g, _h;
522
- const systemInstructionParts = [];
523
- const contents = [];
524
- let systemMessagesAllowed = true;
525
- const isGemmaModel = (_a = options == null ? void 0 : options.isGemmaModel) != null ? _a : false;
526
- const providerOptionsName = (_b = options == null ? void 0 : options.providerOptionsName) != null ? _b : "google";
527
- const supportsFunctionResponseParts = (_c = options == null ? void 0 : options.supportsFunctionResponseParts) != null ? _c : true;
528
- for (const { role, content } of prompt) {
529
- switch (role) {
530
- case "system": {
531
- if (!systemMessagesAllowed) {
532
- throw new UnsupportedFunctionalityError({
533
- functionality: "system messages are only supported at the beginning of the conversation"
534
- });
535
- }
536
- systemInstructionParts.push({ text: content });
537
- break;
538
- }
539
- case "user": {
540
- systemMessagesAllowed = false;
541
- const parts = [];
542
- for (const part of content) {
543
- switch (part.type) {
544
- case "text": {
545
- parts.push({ text: part.text });
546
- break;
547
- }
548
- case "file": {
549
- const mediaType = part.mediaType === "image/*" ? "image/jpeg" : part.mediaType;
550
- if (part.data instanceof URL) {
551
- parts.push({
552
- fileData: {
553
- mimeType: mediaType,
554
- fileUri: part.data.toString()
555
- }
556
- });
557
- } else if (isProviderReference(part.data)) {
558
- if (providerOptionsName === "vertex") {
559
- throw new UnsupportedFunctionalityError({
560
- functionality: "file parts with provider references"
561
- });
562
- }
563
- parts.push({
564
- fileData: {
565
- mimeType: mediaType,
566
- fileUri: resolveProviderReference({
567
- reference: part.data,
568
- provider: "google"
569
- })
570
- }
571
- });
572
- } else {
573
- parts.push({
574
- inlineData: {
575
- mimeType: mediaType,
576
- data: convertToBase64(part.data)
577
- }
578
- });
579
- }
580
- break;
581
- }
582
- }
583
- }
584
- contents.push({ role: "user", parts });
585
- break;
586
- }
587
- case "assistant": {
588
- systemMessagesAllowed = false;
589
- contents.push({
590
- role: "model",
591
- parts: content.map((part) => {
592
- var _a2, _b2, _c2, _d2;
593
- 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;
594
- const thoughtSignature = (providerOpts == null ? void 0 : providerOpts.thoughtSignature) != null ? String(providerOpts.thoughtSignature) : void 0;
595
- switch (part.type) {
596
- case "text": {
597
- return part.text.length === 0 ? void 0 : {
598
- text: part.text,
599
- thoughtSignature
600
- };
601
- }
602
- case "reasoning": {
603
- return part.text.length === 0 ? void 0 : {
604
- text: part.text,
605
- thought: true,
606
- thoughtSignature
607
- };
608
- }
609
- case "reasoning-file": {
610
- if (part.data instanceof URL) {
611
- throw new UnsupportedFunctionalityError({
612
- functionality: "File data URLs in assistant messages are not supported"
613
- });
614
- }
615
- return {
616
- inlineData: {
617
- mimeType: part.mediaType,
618
- data: convertToBase64(part.data)
619
- },
620
- thought: true,
621
- thoughtSignature
622
- };
623
- }
624
- case "file": {
625
- if (part.data instanceof URL) {
626
- throw new UnsupportedFunctionalityError({
627
- functionality: "File data URLs in assistant messages are not supported"
628
- });
629
- }
630
- if (isProviderReference(part.data)) {
631
- if (providerOptionsName === "vertex") {
632
- throw new UnsupportedFunctionalityError({
633
- functionality: "file parts with provider references"
634
- });
635
- }
636
- return {
637
- fileData: {
638
- mimeType: part.mediaType,
639
- fileUri: resolveProviderReference({
640
- reference: part.data,
641
- provider: "google"
642
- })
643
- },
644
- ...(providerOpts == null ? void 0 : providerOpts.thought) === true ? { thought: true } : {},
645
- thoughtSignature
646
- };
647
- }
648
- return {
649
- inlineData: {
650
- mimeType: part.mediaType,
651
- data: convertToBase64(part.data)
652
- },
653
- ...(providerOpts == null ? void 0 : providerOpts.thought) === true ? { thought: true } : {},
654
- thoughtSignature
655
- };
656
- }
657
- case "tool-call": {
658
- const serverToolCallId = (providerOpts == null ? void 0 : providerOpts.serverToolCallId) != null ? String(providerOpts.serverToolCallId) : void 0;
659
- const serverToolType = (providerOpts == null ? void 0 : providerOpts.serverToolType) != null ? String(providerOpts.serverToolType) : void 0;
660
- if (serverToolCallId && serverToolType) {
661
- return {
662
- toolCall: {
663
- toolType: serverToolType,
664
- args: typeof part.input === "string" ? JSON.parse(part.input) : part.input,
665
- id: serverToolCallId
666
- },
667
- thoughtSignature
668
- };
669
- }
670
- return {
671
- functionCall: {
672
- name: part.toolName,
673
- args: part.input
674
- },
675
- thoughtSignature
676
- };
677
- }
678
- case "tool-result": {
679
- const serverToolCallId = (providerOpts == null ? void 0 : providerOpts.serverToolCallId) != null ? String(providerOpts.serverToolCallId) : void 0;
680
- const serverToolType = (providerOpts == null ? void 0 : providerOpts.serverToolType) != null ? String(providerOpts.serverToolType) : void 0;
681
- if (serverToolCallId && serverToolType) {
682
- return {
683
- toolResponse: {
684
- toolType: serverToolType,
685
- response: part.output.type === "json" ? part.output.value : {},
686
- id: serverToolCallId
687
- },
688
- thoughtSignature
689
- };
690
- }
691
- return void 0;
692
- }
693
- }
694
- }).filter((part) => part !== void 0)
695
- });
696
- break;
697
- }
698
- case "tool": {
699
- systemMessagesAllowed = false;
700
- const parts = [];
701
- for (const part of content) {
702
- if (part.type === "tool-approval-response") {
703
- continue;
704
- }
705
- 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;
706
- const serverToolCallId = (partProviderOpts == null ? void 0 : partProviderOpts.serverToolCallId) != null ? String(partProviderOpts.serverToolCallId) : void 0;
707
- const serverToolType = (partProviderOpts == null ? void 0 : partProviderOpts.serverToolType) != null ? String(partProviderOpts.serverToolType) : void 0;
708
- if (serverToolCallId && serverToolType) {
709
- const serverThoughtSignature = (partProviderOpts == null ? void 0 : partProviderOpts.thoughtSignature) != null ? String(partProviderOpts.thoughtSignature) : void 0;
710
- if (contents.length > 0) {
711
- const lastContent = contents[contents.length - 1];
712
- if (lastContent.role === "model") {
713
- lastContent.parts.push({
714
- toolResponse: {
715
- toolType: serverToolType,
716
- response: part.output.type === "json" ? part.output.value : {},
717
- id: serverToolCallId
718
- },
719
- thoughtSignature: serverThoughtSignature
720
- });
721
- continue;
722
- }
723
- }
724
- }
725
- const output = part.output;
726
- if (output.type === "content") {
727
- if (supportsFunctionResponseParts) {
728
- appendToolResultParts(parts, part.toolName, output.value);
729
- } else {
730
- appendLegacyToolResultParts(parts, part.toolName, output.value);
731
- }
732
- } else {
733
- parts.push({
734
- functionResponse: {
735
- name: part.toolName,
736
- response: {
737
- name: part.toolName,
738
- content: output.type === "execution-denied" ? (_h = output.reason) != null ? _h : "Tool execution denied." : output.value
739
- }
740
- }
741
- });
742
- }
743
- }
744
- contents.push({
745
- role: "user",
746
- parts
747
- });
748
- break;
749
- }
750
- }
751
- }
752
- if (isGemmaModel && systemInstructionParts.length > 0 && contents.length > 0 && contents[0].role === "user") {
753
- const systemText = systemInstructionParts.map((part) => part.text).join("\n\n");
754
- contents[0].parts.unshift({ text: systemText + "\n\n" });
755
- }
756
- return {
757
- systemInstruction: systemInstructionParts.length > 0 && !isGemmaModel ? { parts: systemInstructionParts } : void 0,
758
- contents
759
- };
760
- }
761
-
762
- // src/get-model-path.ts
763
- function getModelPath(modelId) {
764
- return modelId.includes("/") ? modelId : `models/${modelId}`;
765
- }
766
-
767
- // src/google-generative-ai-options.ts
768
- import { lazySchema as lazySchema4, zodSchema as zodSchema4 } from "@ai-sdk/provider-utils";
769
- import { z as z4 } from "zod/v4";
770
- var googleLanguageModelOptions = lazySchema4(
771
- () => zodSchema4(
772
- z4.object({
773
- responseModalities: z4.array(z4.enum(["TEXT", "IMAGE"])).optional(),
774
- thinkingConfig: z4.object({
775
- thinkingBudget: z4.number().optional(),
776
- includeThoughts: z4.boolean().optional(),
777
- // https://ai.google.dev/gemini-api/docs/gemini-3?thinking=high#thinking_level
778
- thinkingLevel: z4.enum(["minimal", "low", "medium", "high"]).optional()
779
- }).optional(),
780
- /**
781
- * Optional.
782
- * The name of the cached content used as context to serve the prediction.
783
- * Format: cachedContents/{cachedContent}
784
- */
785
- cachedContent: z4.string().optional(),
786
- /**
787
- * Optional. Enable structured output. Default is true.
788
- *
789
- * This is useful when the JSON Schema contains elements that are
790
- * not supported by the OpenAPI schema version that
791
- * Google Generative AI uses. You can use this to disable
792
- * structured outputs if you need to.
793
- */
794
- structuredOutputs: z4.boolean().optional(),
795
- /**
796
- * Optional. A list of unique safety settings for blocking unsafe content.
797
- */
798
- safetySettings: z4.array(
799
- z4.object({
800
- category: z4.enum([
801
- "HARM_CATEGORY_UNSPECIFIED",
802
- "HARM_CATEGORY_HATE_SPEECH",
803
- "HARM_CATEGORY_DANGEROUS_CONTENT",
804
- "HARM_CATEGORY_HARASSMENT",
805
- "HARM_CATEGORY_SEXUALLY_EXPLICIT",
806
- "HARM_CATEGORY_CIVIC_INTEGRITY"
807
- ]),
808
- threshold: z4.enum([
809
- "HARM_BLOCK_THRESHOLD_UNSPECIFIED",
810
- "BLOCK_LOW_AND_ABOVE",
811
- "BLOCK_MEDIUM_AND_ABOVE",
812
- "BLOCK_ONLY_HIGH",
813
- "BLOCK_NONE",
814
- "OFF"
815
- ])
816
- })
817
- ).optional(),
818
- threshold: z4.enum([
819
- "HARM_BLOCK_THRESHOLD_UNSPECIFIED",
820
- "BLOCK_LOW_AND_ABOVE",
821
- "BLOCK_MEDIUM_AND_ABOVE",
822
- "BLOCK_ONLY_HIGH",
823
- "BLOCK_NONE",
824
- "OFF"
825
- ]).optional(),
826
- /**
827
- * Optional. Enables timestamp understanding for audio-only files.
828
- *
829
- * https://cloud.google.com/vertex-ai/generative-ai/docs/multimodal/audio-understanding
830
- */
831
- audioTimestamp: z4.boolean().optional(),
832
- /**
833
- * Optional. Defines labels used in billing reports. Available on Vertex AI only.
834
- *
835
- * https://cloud.google.com/vertex-ai/generative-ai/docs/multimodal/add-labels-to-api-calls
836
- */
837
- labels: z4.record(z4.string(), z4.string()).optional(),
838
- /**
839
- * Optional. If specified, the media resolution specified will be used.
840
- *
841
- * https://ai.google.dev/api/generate-content#MediaResolution
842
- */
843
- mediaResolution: z4.enum([
844
- "MEDIA_RESOLUTION_UNSPECIFIED",
845
- "MEDIA_RESOLUTION_LOW",
846
- "MEDIA_RESOLUTION_MEDIUM",
847
- "MEDIA_RESOLUTION_HIGH"
848
- ]).optional(),
849
- /**
850
- * Optional. Configures the image generation aspect ratio for Gemini models.
851
- *
852
- * https://ai.google.dev/gemini-api/docs/image-generation#aspect_ratios
853
- */
854
- imageConfig: z4.object({
855
- aspectRatio: z4.enum([
856
- "1:1",
857
- "2:3",
858
- "3:2",
859
- "3:4",
860
- "4:3",
861
- "4:5",
862
- "5:4",
863
- "9:16",
864
- "16:9",
865
- "21:9",
866
- "1:8",
867
- "8:1",
868
- "1:4",
869
- "4:1"
870
- ]).optional(),
871
- imageSize: z4.enum(["1K", "2K", "4K", "512"]).optional()
872
- }).optional(),
873
- /**
874
- * Optional. Configuration for grounding retrieval.
875
- * Used to provide location context for Google Maps and Google Search grounding.
876
- *
877
- * https://cloud.google.com/vertex-ai/generative-ai/docs/grounding/grounding-with-google-maps
878
- */
879
- retrievalConfig: z4.object({
880
- latLng: z4.object({
881
- latitude: z4.number(),
882
- longitude: z4.number()
883
- }).optional()
884
- }).optional(),
885
- /**
886
- * Optional. When set to true, function call arguments will be streamed
887
- * incrementally via partialArgs in streaming responses. Only supported
888
- * on the Vertex AI API (not the Gemini API) and only for Gemini 3+
889
- * models.
890
- *
891
- * @default false
892
- *
893
- * https://docs.cloud.google.com/vertex-ai/generative-ai/docs/multimodal/function-calling#streaming-fc
894
- */
895
- streamFunctionCallArguments: z4.boolean().optional(),
896
- /**
897
- * Optional. The service tier to use for the request.
898
- */
899
- serviceTier: z4.enum(["standard", "flex", "priority"]).optional()
900
- })
901
- )
902
- );
903
- var VertexServiceTierMap = {
904
- standard: "SERVICE_TIER_STANDARD",
905
- flex: "SERVICE_TIER_FLEX",
906
- priority: "SERVICE_TIER_PRIORITY"
907
- };
908
-
909
- // src/google-prepare-tools.ts
910
- import {
911
- UnsupportedFunctionalityError as UnsupportedFunctionalityError2
912
- } from "@ai-sdk/provider";
913
- function prepareTools({
914
- tools,
915
- toolChoice,
916
- modelId
917
- }) {
918
- var _a, _b;
919
- tools = (tools == null ? void 0 : tools.length) ? tools : void 0;
920
- const toolWarnings = [];
921
- const isLatest = [
922
- "gemini-flash-latest",
923
- "gemini-flash-lite-latest",
924
- "gemini-pro-latest"
925
- ].some((id) => id === modelId);
926
- const isGemini2orNewer = modelId.includes("gemini-2") || modelId.includes("gemini-3") || modelId.includes("nano-banana") || isLatest;
927
- const isGemini3orNewer = modelId.includes("gemini-3");
928
- const supportsFileSearch = modelId.includes("gemini-2.5") || modelId.includes("gemini-3");
929
- if (tools == null) {
930
- return { tools: void 0, toolConfig: void 0, toolWarnings };
931
- }
932
- const hasFunctionTools = tools.some((tool) => tool.type === "function");
933
- const hasProviderTools = tools.some((tool) => tool.type === "provider");
934
- if (hasFunctionTools && hasProviderTools && !isGemini3orNewer) {
935
- toolWarnings.push({
936
- type: "unsupported",
937
- feature: `combination of function and provider-defined tools`
938
- });
939
- }
940
- if (hasProviderTools) {
941
- const googleTools2 = [];
942
- const ProviderTools = tools.filter((tool) => tool.type === "provider");
943
- ProviderTools.forEach((tool) => {
944
- switch (tool.id) {
945
- case "google.google_search":
946
- if (isGemini2orNewer) {
947
- googleTools2.push({ googleSearch: { ...tool.args } });
948
- } else {
949
- toolWarnings.push({
950
- type: "unsupported",
951
- feature: `provider-defined tool ${tool.id}`,
952
- details: "Google Search requires Gemini 2.0 or newer."
953
- });
954
- }
955
- break;
956
- case "google.enterprise_web_search":
957
- if (isGemini2orNewer) {
958
- googleTools2.push({ enterpriseWebSearch: {} });
959
- } else {
960
- toolWarnings.push({
961
- type: "unsupported",
962
- feature: `provider-defined tool ${tool.id}`,
963
- details: "Enterprise Web Search requires Gemini 2.0 or newer."
964
- });
965
- }
966
- break;
967
- case "google.url_context":
968
- if (isGemini2orNewer) {
969
- googleTools2.push({ urlContext: {} });
970
- } else {
971
- toolWarnings.push({
972
- type: "unsupported",
973
- feature: `provider-defined tool ${tool.id}`,
974
- details: "The URL context tool is not supported with other Gemini models than Gemini 2."
975
- });
976
- }
977
- break;
978
- case "google.code_execution":
979
- if (isGemini2orNewer) {
980
- googleTools2.push({ codeExecution: {} });
981
- } else {
982
- toolWarnings.push({
983
- type: "unsupported",
984
- feature: `provider-defined tool ${tool.id}`,
985
- details: "The code execution tool is not supported with other Gemini models than Gemini 2."
986
- });
987
- }
988
- break;
989
- case "google.file_search":
990
- if (supportsFileSearch) {
991
- googleTools2.push({ fileSearch: { ...tool.args } });
992
- } else {
993
- toolWarnings.push({
994
- type: "unsupported",
995
- feature: `provider-defined tool ${tool.id}`,
996
- details: "The file search tool is only supported with Gemini 2.5 models and Gemini 3 models."
997
- });
998
- }
999
- break;
1000
- case "google.vertex_rag_store":
1001
- if (isGemini2orNewer) {
1002
- googleTools2.push({
1003
- retrieval: {
1004
- vertex_rag_store: {
1005
- rag_resources: {
1006
- rag_corpus: tool.args.ragCorpus
1007
- },
1008
- similarity_top_k: tool.args.topK
1009
- }
1010
- }
1011
- });
1012
- } else {
1013
- toolWarnings.push({
1014
- type: "unsupported",
1015
- feature: `provider-defined tool ${tool.id}`,
1016
- details: "The RAG store tool is not supported with other Gemini models than Gemini 2."
1017
- });
1018
- }
1019
- break;
1020
- case "google.google_maps":
1021
- if (isGemini2orNewer) {
1022
- googleTools2.push({ googleMaps: {} });
1023
- } else {
1024
- toolWarnings.push({
1025
- type: "unsupported",
1026
- feature: `provider-defined tool ${tool.id}`,
1027
- details: "The Google Maps grounding tool is not supported with Gemini models other than Gemini 2 or newer."
1028
- });
1029
- }
1030
- break;
1031
- default:
1032
- toolWarnings.push({
1033
- type: "unsupported",
1034
- feature: `provider-defined tool ${tool.id}`
1035
- });
1036
- break;
1037
- }
1038
- });
1039
- if (hasFunctionTools && isGemini3orNewer && googleTools2.length > 0) {
1040
- const functionDeclarations2 = [];
1041
- for (const tool of tools) {
1042
- if (tool.type === "function") {
1043
- functionDeclarations2.push({
1044
- name: tool.name,
1045
- description: (_a = tool.description) != null ? _a : "",
1046
- parameters: convertJSONSchemaToOpenAPISchema(tool.inputSchema)
1047
- });
1048
- }
1049
- }
1050
- const combinedToolConfig = {
1051
- functionCallingConfig: { mode: "VALIDATED" },
1052
- includeServerSideToolInvocations: true
1053
- };
1054
- if (toolChoice != null) {
1055
- switch (toolChoice.type) {
1056
- case "auto":
1057
- break;
1058
- case "none":
1059
- combinedToolConfig.functionCallingConfig = { mode: "NONE" };
1060
- break;
1061
- case "required":
1062
- combinedToolConfig.functionCallingConfig = { mode: "ANY" };
1063
- break;
1064
- case "tool":
1065
- combinedToolConfig.functionCallingConfig = {
1066
- mode: "ANY",
1067
- allowedFunctionNames: [toolChoice.toolName]
1068
- };
1069
- break;
1070
- }
1071
- }
1072
- return {
1073
- tools: [...googleTools2, { functionDeclarations: functionDeclarations2 }],
1074
- toolConfig: combinedToolConfig,
1075
- toolWarnings
1076
- };
1077
- }
1078
- return {
1079
- tools: googleTools2.length > 0 ? googleTools2 : void 0,
1080
- toolConfig: void 0,
1081
- toolWarnings
1082
- };
1083
- }
1084
- const functionDeclarations = [];
1085
- let hasStrictTools = false;
1086
- for (const tool of tools) {
1087
- switch (tool.type) {
1088
- case "function":
1089
- functionDeclarations.push({
1090
- name: tool.name,
1091
- description: (_b = tool.description) != null ? _b : "",
1092
- parameters: convertJSONSchemaToOpenAPISchema(tool.inputSchema)
1093
- });
1094
- if (tool.strict === true) {
1095
- hasStrictTools = true;
1096
- }
1097
- break;
1098
- default:
1099
- toolWarnings.push({
1100
- type: "unsupported",
1101
- feature: `function tool ${tool.name}`
1102
- });
1103
- break;
1104
- }
1105
- }
1106
- if (toolChoice == null) {
1107
- return {
1108
- tools: [{ functionDeclarations }],
1109
- toolConfig: hasStrictTools ? { functionCallingConfig: { mode: "VALIDATED" } } : void 0,
1110
- toolWarnings
1111
- };
1112
- }
1113
- const type = toolChoice.type;
1114
- switch (type) {
1115
- case "auto":
1116
- return {
1117
- tools: [{ functionDeclarations }],
1118
- toolConfig: {
1119
- functionCallingConfig: {
1120
- mode: hasStrictTools ? "VALIDATED" : "AUTO"
1121
- }
1122
- },
1123
- toolWarnings
1124
- };
1125
- case "none":
1126
- return {
1127
- tools: [{ functionDeclarations }],
1128
- toolConfig: { functionCallingConfig: { mode: "NONE" } },
1129
- toolWarnings
1130
- };
1131
- case "required":
1132
- return {
1133
- tools: [{ functionDeclarations }],
1134
- toolConfig: {
1135
- functionCallingConfig: {
1136
- mode: hasStrictTools ? "VALIDATED" : "ANY"
1137
- }
1138
- },
1139
- toolWarnings
1140
- };
1141
- case "tool":
1142
- return {
1143
- tools: [{ functionDeclarations }],
1144
- toolConfig: {
1145
- functionCallingConfig: {
1146
- mode: hasStrictTools ? "VALIDATED" : "ANY",
1147
- allowedFunctionNames: [toolChoice.toolName]
1148
- }
1149
- },
1150
- toolWarnings
1151
- };
1152
- default: {
1153
- const _exhaustiveCheck = type;
1154
- throw new UnsupportedFunctionalityError2({
1155
- functionality: `tool choice type: ${_exhaustiveCheck}`
1156
- });
1157
- }
1158
- }
1159
- }
1160
-
1161
- // src/google-json-accumulator.ts
1162
- var GoogleJSONAccumulator = class {
1163
- constructor() {
1164
- this.accumulatedArgs = {};
1165
- this.jsonText = "";
1166
- /**
1167
- * Stack representing the currently "open" containers in the JSON output.
1168
- * Entry 0 is always the root `{` object once the first value is written.
1169
- */
1170
- this.pathStack = [];
1171
- /**
1172
- * Whether a string value is currently "open" (willContinue was true),
1173
- * meaning the closing quote has not yet been emitted.
1174
- */
1175
- this.stringOpen = false;
1176
- }
1177
- /**
1178
- * Input: [{jsonPath:"$.brightness",numberValue:50}]
1179
- * Output: { currentJSON:{brightness:50}, textDelta:'{"brightness":50' }
1180
- */
1181
- processPartialArgs(partialArgs) {
1182
- let delta = "";
1183
- for (const arg of partialArgs) {
1184
- const rawPath = arg.jsonPath.replace(/^\$\./, "");
1185
- if (!rawPath) continue;
1186
- const segments = parsePath(rawPath);
1187
- const existingValue = getNestedValue(this.accumulatedArgs, segments);
1188
- const isStringContinuation = arg.stringValue != null && existingValue !== void 0;
1189
- if (isStringContinuation) {
1190
- const escaped = JSON.stringify(arg.stringValue).slice(1, -1);
1191
- setNestedValue(
1192
- this.accumulatedArgs,
1193
- segments,
1194
- existingValue + arg.stringValue
1195
- );
1196
- delta += escaped;
1197
- continue;
1198
- }
1199
- const resolved = resolvePartialArgValue(arg);
1200
- if (resolved == null) continue;
1201
- setNestedValue(this.accumulatedArgs, segments, resolved.value);
1202
- delta += this.emitNavigationTo(segments, arg, resolved.json);
1203
- }
1204
- this.jsonText += delta;
1205
- return {
1206
- currentJSON: this.accumulatedArgs,
1207
- textDelta: delta
1208
- };
1209
- }
1210
- /**
1211
- * Input: jsonText='{"brightness":50', accumulatedArgs={brightness:50}
1212
- * Output: { finalJSON:'{"brightness":50}', closingDelta:'}' }
1213
- */
1214
- finalize() {
1215
- const finalArgs = JSON.stringify(this.accumulatedArgs);
1216
- const closingDelta = finalArgs.slice(this.jsonText.length);
1217
- return { finalJSON: finalArgs, closingDelta };
1218
- }
1219
- /**
1220
- * Input: pathStack=[] (first call) or pathStack=[root,...] (subsequent calls)
1221
- * Output: '{' (first call) or '' (subsequent calls)
1222
- */
1223
- ensureRoot() {
1224
- if (this.pathStack.length === 0) {
1225
- this.pathStack.push({ segment: "", isArray: false, childCount: 0 });
1226
- return "{";
1227
- }
1228
- return "";
1229
- }
1230
- /**
1231
- * Emits the JSON text fragment needed to navigate from the current open
1232
- * path to the new leaf at `targetSegments`, then writes the value.
1233
- *
1234
- * Input: targetSegments=["recipe","name"], arg={jsonPath:"$.recipe.name",stringValue:"Lasagna"}, valueJson='"Lasagna"'
1235
- * Output: '{"recipe":{"name":"Lasagna"'
1236
- */
1237
- emitNavigationTo(targetSegments, arg, valueJson) {
1238
- let fragment = "";
1239
- if (this.stringOpen) {
1240
- fragment += '"';
1241
- this.stringOpen = false;
1242
- }
1243
- fragment += this.ensureRoot();
1244
- const targetContainerSegments = targetSegments.slice(0, -1);
1245
- const leafSegment = targetSegments[targetSegments.length - 1];
1246
- const commonDepth = this.findCommonStackDepth(targetContainerSegments);
1247
- fragment += this.closeDownTo(commonDepth);
1248
- fragment += this.openDownTo(targetContainerSegments, leafSegment);
1249
- fragment += this.emitLeaf(leafSegment, arg, valueJson);
1250
- return fragment;
1251
- }
1252
- /**
1253
- * Returns the stack depth to preserve when navigating to a new target
1254
- * container path. Always >= 1 (the root is never popped).
1255
- *
1256
- * Input: stack=[root,"recipe","ingredients",0], target=["recipe","ingredients",1]
1257
- * Output: 3 (keep root+"recipe"+"ingredients")
1258
- */
1259
- findCommonStackDepth(targetContainer) {
1260
- const maxDepth = Math.min(
1261
- this.pathStack.length - 1,
1262
- targetContainer.length
1263
- );
1264
- let common = 0;
1265
- for (let i = 0; i < maxDepth; i++) {
1266
- if (this.pathStack[i + 1].segment === targetContainer[i]) {
1267
- common++;
1268
- } else {
1269
- break;
1270
- }
1271
- }
1272
- return common + 1;
1273
- }
1274
- /**
1275
- * Closes containers from the current stack depth back down to `targetDepth`.
1276
- *
1277
- * Input: this.pathStack=[root,"recipe","ingredients",0], targetDepth=3
1278
- * Output: '}'
1279
- */
1280
- closeDownTo(targetDepth) {
1281
- let fragment = "";
1282
- while (this.pathStack.length > targetDepth) {
1283
- const entry = this.pathStack.pop();
1284
- fragment += entry.isArray ? "]" : "}";
1285
- }
1286
- return fragment;
1287
- }
1288
- /**
1289
- * Opens containers from the current stack depth down to the full target
1290
- * container path, emitting opening `{`, `[`, keys, and commas as needed.
1291
- * `leafSegment` is used to determine if the innermost container is an array.
1292
- *
1293
- * Input: this.pathStack=[root], targetContainer=["recipe","ingredients"], leafSegment=0
1294
- * Output: '"recipe":{"ingredients":['
1295
- */
1296
- openDownTo(targetContainer, leafSegment) {
1297
- let fragment = "";
1298
- const startIdx = this.pathStack.length - 1;
1299
- for (let i = startIdx; i < targetContainer.length; i++) {
1300
- const seg = targetContainer[i];
1301
- const parentEntry = this.pathStack[this.pathStack.length - 1];
1302
- if (parentEntry.childCount > 0) {
1303
- fragment += ",";
1304
- }
1305
- parentEntry.childCount++;
1306
- if (typeof seg === "string") {
1307
- fragment += `${JSON.stringify(seg)}:`;
1308
- }
1309
- const childSeg = i + 1 < targetContainer.length ? targetContainer[i + 1] : leafSegment;
1310
- const isArray = typeof childSeg === "number";
1311
- fragment += isArray ? "[" : "{";
1312
- this.pathStack.push({ segment: seg, isArray, childCount: 0 });
1313
- }
1314
- return fragment;
1315
- }
1316
- /**
1317
- * Emits the comma, key, and value for a leaf entry in the current container.
1318
- *
1319
- * Input: leafSegment="name", arg={stringValue:"Lasagna"}, valueJson='"Lasagna"'
1320
- * Output: '"name":"Lasagna"' (or ',"name":"Lasagna"' if container.childCount > 0)
1321
- */
1322
- emitLeaf(leafSegment, arg, valueJson) {
1323
- let fragment = "";
1324
- const container = this.pathStack[this.pathStack.length - 1];
1325
- if (container.childCount > 0) {
1326
- fragment += ",";
1327
- }
1328
- container.childCount++;
1329
- if (typeof leafSegment === "string") {
1330
- fragment += `${JSON.stringify(leafSegment)}:`;
1331
- }
1332
- if (arg.stringValue != null && arg.willContinue) {
1333
- fragment += valueJson.slice(0, -1);
1334
- this.stringOpen = true;
1335
- } else {
1336
- fragment += valueJson;
1337
- }
1338
- return fragment;
1339
- }
1340
- };
1341
- function parsePath(rawPath) {
1342
- const segments = [];
1343
- for (const part of rawPath.split(".")) {
1344
- const bracketIdx = part.indexOf("[");
1345
- if (bracketIdx === -1) {
1346
- segments.push(part);
1347
- } else {
1348
- if (bracketIdx > 0) segments.push(part.slice(0, bracketIdx));
1349
- for (const m of part.matchAll(/\[(\d+)\]/g)) {
1350
- segments.push(parseInt(m[1], 10));
1351
- }
1352
- }
1353
- }
1354
- return segments;
1355
- }
1356
- function getNestedValue(obj, segments) {
1357
- let current = obj;
1358
- for (const seg of segments) {
1359
- if (current == null || typeof current !== "object") return void 0;
1360
- current = current[seg];
1361
- }
1362
- return current;
1363
- }
1364
- function setNestedValue(obj, segments, value) {
1365
- let current = obj;
1366
- for (let i = 0; i < segments.length - 1; i++) {
1367
- const seg = segments[i];
1368
- const nextSeg = segments[i + 1];
1369
- if (current[seg] == null) {
1370
- current[seg] = typeof nextSeg === "number" ? [] : {};
1371
- }
1372
- current = current[seg];
1373
- }
1374
- current[segments[segments.length - 1]] = value;
1375
- }
1376
- function resolvePartialArgValue(arg) {
1377
- var _a, _b;
1378
- const value = (_b = (_a = arg.stringValue) != null ? _a : arg.numberValue) != null ? _b : arg.boolValue;
1379
- if (value != null) return { value, json: JSON.stringify(value) };
1380
- if ("nullValue" in arg) return { value: null, json: "null" };
1381
- return void 0;
1382
- }
1383
-
1384
- // src/map-google-generative-ai-finish-reason.ts
1385
- function mapGoogleGenerativeAIFinishReason({
1386
- finishReason,
1387
- hasToolCalls
1388
- }) {
1389
- switch (finishReason) {
1390
- case "STOP":
1391
- return hasToolCalls ? "tool-calls" : "stop";
1392
- case "MAX_TOKENS":
1393
- return "length";
1394
- case "IMAGE_SAFETY":
1395
- case "RECITATION":
1396
- case "SAFETY":
1397
- case "BLOCKLIST":
1398
- case "PROHIBITED_CONTENT":
1399
- case "SPII":
1400
- return "content-filter";
1401
- case "MALFORMED_FUNCTION_CALL":
1402
- return "error";
1403
- case "FINISH_REASON_UNSPECIFIED":
1404
- case "OTHER":
1405
- default:
1406
- return "other";
1407
- }
1408
- }
1409
-
1410
- // src/google-generative-ai-language-model.ts
1411
- var GoogleGenerativeAILanguageModel = class {
1412
- constructor(modelId, config) {
1413
- this.specificationVersion = "v4";
1414
- var _a;
1415
- this.modelId = modelId;
1416
- this.config = config;
1417
- this.generateId = (_a = config.generateId) != null ? _a : generateId;
1418
- }
1419
- get provider() {
1420
- return this.config.provider;
1421
- }
1422
- get supportedUrls() {
1423
- var _a, _b, _c;
1424
- return (_c = (_b = (_a = this.config).supportedUrls) == null ? void 0 : _b.call(_a)) != null ? _c : {};
1425
- }
1426
- async getArgs({
1427
- prompt,
1428
- maxOutputTokens,
1429
- temperature,
1430
- topP,
1431
- topK,
1432
- frequencyPenalty,
1433
- presencePenalty,
1434
- stopSequences,
1435
- responseFormat,
1436
- seed,
1437
- tools,
1438
- toolChoice,
1439
- reasoning,
1440
- providerOptions
1441
- }, { isStreaming = false } = {}) {
1442
- var _a, _b;
1443
- const warnings = [];
1444
- const providerOptionsName = this.config.provider.includes("vertex") ? "vertex" : "google";
1445
- let googleOptions = await parseProviderOptions2({
1446
- provider: providerOptionsName,
1447
- providerOptions,
1448
- schema: googleLanguageModelOptions
1449
- });
1450
- if (googleOptions == null && providerOptionsName !== "google") {
1451
- googleOptions = await parseProviderOptions2({
1452
- provider: "google",
1453
- providerOptions,
1454
- schema: googleLanguageModelOptions
1455
- });
1456
- }
1457
- const isVertexProvider = this.config.provider.startsWith("google.vertex.");
1458
- if ((tools == null ? void 0 : tools.some(
1459
- (tool) => tool.type === "provider" && tool.id === "google.vertex_rag_store"
1460
- )) && !isVertexProvider) {
1461
- warnings.push({
1462
- type: "other",
1463
- 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}).`
1464
- });
1465
- }
1466
- if ((googleOptions == null ? void 0 : googleOptions.streamFunctionCallArguments) && !isVertexProvider) {
1467
- warnings.push({
1468
- type: "other",
1469
- 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`
1470
- });
1471
- }
1472
- let sanitizedServiceTier = googleOptions == null ? void 0 : googleOptions.serviceTier;
1473
- if ((googleOptions == null ? void 0 : googleOptions.serviceTier) && isVertexProvider) {
1474
- sanitizedServiceTier = VertexServiceTierMap[googleOptions.serviceTier];
1475
- }
1476
- const isGemmaModel = this.modelId.toLowerCase().startsWith("gemma-");
1477
- const supportsFunctionResponseParts = this.modelId.startsWith("gemini-3");
1478
- const { contents, systemInstruction } = convertToGoogleGenerativeAIMessages(
1479
- prompt,
1480
- {
1481
- isGemmaModel,
1482
- providerOptionsName,
1483
- supportsFunctionResponseParts
1484
- }
1485
- );
1486
- const {
1487
- tools: googleTools2,
1488
- toolConfig: googleToolConfig,
1489
- toolWarnings
1490
- } = prepareTools({
1491
- tools,
1492
- toolChoice,
1493
- modelId: this.modelId
1494
- });
1495
- const resolvedThinking = resolveThinkingConfig({
1496
- reasoning,
1497
- modelId: this.modelId,
1498
- warnings
1499
- });
1500
- const thinkingConfig = (googleOptions == null ? void 0 : googleOptions.thinkingConfig) || resolvedThinking ? { ...resolvedThinking, ...googleOptions == null ? void 0 : googleOptions.thinkingConfig } : void 0;
1501
- const streamFunctionCallArguments = isStreaming && isVertexProvider ? (_a = googleOptions == null ? void 0 : googleOptions.streamFunctionCallArguments) != null ? _a : false : void 0;
1502
- const toolConfig = googleToolConfig || streamFunctionCallArguments || (googleOptions == null ? void 0 : googleOptions.retrievalConfig) ? {
1503
- ...googleToolConfig,
1504
- ...streamFunctionCallArguments && {
1505
- functionCallingConfig: {
1506
- ...googleToolConfig == null ? void 0 : googleToolConfig.functionCallingConfig,
1507
- streamFunctionCallArguments: true
1508
- }
1509
- },
1510
- ...(googleOptions == null ? void 0 : googleOptions.retrievalConfig) && {
1511
- retrievalConfig: googleOptions.retrievalConfig
1512
- }
1513
- } : void 0;
1514
- return {
1515
- args: {
1516
- generationConfig: {
1517
- // standardized settings:
1518
- maxOutputTokens,
1519
- temperature,
1520
- topK,
1521
- topP,
1522
- frequencyPenalty,
1523
- presencePenalty,
1524
- stopSequences,
1525
- seed,
1526
- // response format:
1527
- responseMimeType: (responseFormat == null ? void 0 : responseFormat.type) === "json" ? "application/json" : void 0,
1528
- responseSchema: (responseFormat == null ? void 0 : responseFormat.type) === "json" && responseFormat.schema != null && // Google GenAI does not support all OpenAPI Schema features,
1529
- // so this is needed as an escape hatch:
1530
- // TODO convert into provider option
1531
- ((_b = googleOptions == null ? void 0 : googleOptions.structuredOutputs) != null ? _b : true) ? convertJSONSchemaToOpenAPISchema(responseFormat.schema) : void 0,
1532
- ...(googleOptions == null ? void 0 : googleOptions.audioTimestamp) && {
1533
- audioTimestamp: googleOptions.audioTimestamp
1534
- },
1535
- // provider options:
1536
- responseModalities: googleOptions == null ? void 0 : googleOptions.responseModalities,
1537
- thinkingConfig,
1538
- ...(googleOptions == null ? void 0 : googleOptions.mediaResolution) && {
1539
- mediaResolution: googleOptions.mediaResolution
1540
- },
1541
- ...(googleOptions == null ? void 0 : googleOptions.imageConfig) && {
1542
- imageConfig: googleOptions.imageConfig
1543
- }
1544
- },
1545
- contents,
1546
- systemInstruction: isGemmaModel ? void 0 : systemInstruction,
1547
- safetySettings: googleOptions == null ? void 0 : googleOptions.safetySettings,
1548
- tools: googleTools2,
1549
- toolConfig,
1550
- cachedContent: googleOptions == null ? void 0 : googleOptions.cachedContent,
1551
- labels: googleOptions == null ? void 0 : googleOptions.labels,
1552
- serviceTier: sanitizedServiceTier
1553
- },
1554
- warnings: [...warnings, ...toolWarnings],
1555
- providerOptionsName
1556
- };
1557
- }
1558
- async doGenerate(options) {
1559
- var _a, _b, _c, _d, _e, _f, _g, _h, _i, _j, _k, _l, _m, _n, _o, _p;
1560
- const { args, warnings, providerOptionsName } = await this.getArgs(options);
1561
- const mergedHeaders = combineHeaders2(
1562
- await resolve2(this.config.headers),
1563
- options.headers
1564
- );
1565
- const {
1566
- responseHeaders,
1567
- value: response,
1568
- rawValue: rawResponse
1569
- } = await postJsonToApi2({
1570
- url: `${this.config.baseURL}/${getModelPath(
1571
- this.modelId
1572
- )}:generateContent`,
1573
- headers: mergedHeaders,
1574
- body: args,
1575
- failedResponseHandler: googleFailedResponseHandler,
1576
- successfulResponseHandler: createJsonResponseHandler2(responseSchema),
1577
- abortSignal: options.abortSignal,
1578
- fetch: this.config.fetch
1579
- });
1580
- const candidate = response.candidates[0];
1581
- const content = [];
1582
- const parts = (_b = (_a = candidate.content) == null ? void 0 : _a.parts) != null ? _b : [];
1583
- const usageMetadata = response.usageMetadata;
1584
- let lastCodeExecutionToolCallId;
1585
- let lastServerToolCallId;
1586
- for (const part of parts) {
1587
- if ("executableCode" in part && ((_c = part.executableCode) == null ? void 0 : _c.code)) {
1588
- const toolCallId = this.config.generateId();
1589
- lastCodeExecutionToolCallId = toolCallId;
1590
- content.push({
1591
- type: "tool-call",
1592
- toolCallId,
1593
- toolName: "code_execution",
1594
- input: JSON.stringify(part.executableCode),
1595
- providerExecuted: true
1596
- });
1597
- } else if ("codeExecutionResult" in part && part.codeExecutionResult) {
1598
- content.push({
1599
- type: "tool-result",
1600
- // Assumes a result directly follows its corresponding call part.
1601
- toolCallId: lastCodeExecutionToolCallId,
1602
- toolName: "code_execution",
1603
- result: {
1604
- outcome: part.codeExecutionResult.outcome,
1605
- output: (_d = part.codeExecutionResult.output) != null ? _d : ""
1606
- }
1607
- });
1608
- lastCodeExecutionToolCallId = void 0;
1609
- } else if ("text" in part && part.text != null) {
1610
- const thoughtSignatureMetadata = part.thoughtSignature ? {
1611
- [providerOptionsName]: {
1612
- thoughtSignature: part.thoughtSignature
1613
- }
1614
- } : void 0;
1615
- if (part.text.length === 0) {
1616
- if (thoughtSignatureMetadata != null && content.length > 0) {
1617
- const lastContent = content[content.length - 1];
1618
- lastContent.providerMetadata = thoughtSignatureMetadata;
1619
- }
1620
- } else {
1621
- content.push({
1622
- type: part.thought === true ? "reasoning" : "text",
1623
- text: part.text,
1624
- providerMetadata: thoughtSignatureMetadata
1625
- });
1626
- }
1627
- } else if ("functionCall" in part && part.functionCall.name != null && part.functionCall.args != null) {
1628
- content.push({
1629
- type: "tool-call",
1630
- toolCallId: this.config.generateId(),
1631
- toolName: part.functionCall.name,
1632
- input: JSON.stringify(part.functionCall.args),
1633
- providerMetadata: part.thoughtSignature ? {
1634
- [providerOptionsName]: {
1635
- thoughtSignature: part.thoughtSignature
1636
- }
1637
- } : void 0
1638
- });
1639
- } else if ("inlineData" in part) {
1640
- const hasThought = part.thought === true;
1641
- const hasThoughtSignature = !!part.thoughtSignature;
1642
- content.push({
1643
- type: hasThought ? "reasoning-file" : "file",
1644
- data: part.inlineData.data,
1645
- mediaType: part.inlineData.mimeType,
1646
- providerMetadata: hasThoughtSignature ? {
1647
- [providerOptionsName]: {
1648
- thoughtSignature: part.thoughtSignature
1649
- }
1650
- } : void 0
1651
- });
1652
- } else if ("toolCall" in part && part.toolCall) {
1653
- const toolCallId = (_e = part.toolCall.id) != null ? _e : this.config.generateId();
1654
- lastServerToolCallId = toolCallId;
1655
- content.push({
1656
- type: "tool-call",
1657
- toolCallId,
1658
- toolName: `server:${part.toolCall.toolType}`,
1659
- input: JSON.stringify((_f = part.toolCall.args) != null ? _f : {}),
1660
- providerExecuted: true,
1661
- dynamic: true,
1662
- providerMetadata: part.thoughtSignature ? {
1663
- [providerOptionsName]: {
1664
- thoughtSignature: part.thoughtSignature,
1665
- serverToolCallId: toolCallId,
1666
- serverToolType: part.toolCall.toolType
1667
- }
1668
- } : {
1669
- [providerOptionsName]: {
1670
- serverToolCallId: toolCallId,
1671
- serverToolType: part.toolCall.toolType
1672
- }
1673
- }
1674
- });
1675
- } else if ("toolResponse" in part && part.toolResponse) {
1676
- const responseToolCallId = (_g = lastServerToolCallId != null ? lastServerToolCallId : part.toolResponse.id) != null ? _g : this.config.generateId();
1677
- content.push({
1678
- type: "tool-result",
1679
- toolCallId: responseToolCallId,
1680
- toolName: `server:${part.toolResponse.toolType}`,
1681
- result: (_h = part.toolResponse.response) != null ? _h : {},
1682
- providerMetadata: part.thoughtSignature ? {
1683
- [providerOptionsName]: {
1684
- thoughtSignature: part.thoughtSignature,
1685
- serverToolCallId: responseToolCallId,
1686
- serverToolType: part.toolResponse.toolType
1687
- }
1688
- } : {
1689
- [providerOptionsName]: {
1690
- serverToolCallId: responseToolCallId,
1691
- serverToolType: part.toolResponse.toolType
1692
- }
1693
- }
1694
- });
1695
- lastServerToolCallId = void 0;
1696
- }
1697
- }
1698
- const sources = (_i = extractSources({
1699
- groundingMetadata: candidate.groundingMetadata,
1700
- generateId: this.config.generateId
1701
- })) != null ? _i : [];
1702
- for (const source of sources) {
1703
- content.push(source);
1704
- }
1705
- return {
1706
- content,
1707
- finishReason: {
1708
- unified: mapGoogleGenerativeAIFinishReason({
1709
- finishReason: candidate.finishReason,
1710
- // Only count client-executed tool calls for finish reason determination.
1711
- hasToolCalls: content.some(
1712
- (part) => part.type === "tool-call" && !part.providerExecuted
1713
- )
1714
- }),
1715
- raw: (_j = candidate.finishReason) != null ? _j : void 0
1716
- },
1717
- usage: convertGoogleGenerativeAIUsage(usageMetadata),
1718
- warnings,
1719
- providerMetadata: {
1720
- [providerOptionsName]: {
1721
- promptFeedback: (_k = response.promptFeedback) != null ? _k : null,
1722
- groundingMetadata: (_l = candidate.groundingMetadata) != null ? _l : null,
1723
- urlContextMetadata: (_m = candidate.urlContextMetadata) != null ? _m : null,
1724
- safetyRatings: (_n = candidate.safetyRatings) != null ? _n : null,
1725
- usageMetadata: usageMetadata != null ? usageMetadata : null,
1726
- finishMessage: (_o = candidate.finishMessage) != null ? _o : null,
1727
- serviceTier: (_p = response.serviceTier) != null ? _p : null
1728
- }
1729
- },
1730
- request: { body: args },
1731
- response: {
1732
- // TODO timestamp, model id, id
1733
- headers: responseHeaders,
1734
- body: rawResponse
1735
- }
1736
- };
1737
- }
1738
- async doStream(options) {
1739
- const { args, warnings, providerOptionsName } = await this.getArgs(
1740
- options,
1741
- { isStreaming: true }
1742
- );
1743
- const headers = combineHeaders2(
1744
- await resolve2(this.config.headers),
1745
- options.headers
1746
- );
1747
- const { responseHeaders, value: response } = await postJsonToApi2({
1748
- url: `${this.config.baseURL}/${getModelPath(
1749
- this.modelId
1750
- )}:streamGenerateContent?alt=sse`,
1751
- headers,
1752
- body: args,
1753
- failedResponseHandler: googleFailedResponseHandler,
1754
- successfulResponseHandler: createEventSourceResponseHandler(chunkSchema),
1755
- abortSignal: options.abortSignal,
1756
- fetch: this.config.fetch
1757
- });
1758
- let finishReason = {
1759
- unified: "other",
1760
- raw: void 0
1761
- };
1762
- let usage = void 0;
1763
- let providerMetadata = void 0;
1764
- let lastGroundingMetadata = null;
1765
- let lastUrlContextMetadata = null;
1766
- let serviceTier = null;
1767
- const generateId3 = this.config.generateId;
1768
- let hasToolCalls = false;
1769
- let currentTextBlockId = null;
1770
- let currentReasoningBlockId = null;
1771
- let blockCounter = 0;
1772
- const emittedSourceUrls = /* @__PURE__ */ new Set();
1773
- let lastCodeExecutionToolCallId;
1774
- let lastServerToolCallId;
1775
- const activeStreamingToolCalls = [];
1776
- return {
1777
- stream: response.pipeThrough(
1778
- new TransformStream({
1779
- start(controller) {
1780
- controller.enqueue({ type: "stream-start", warnings });
1781
- },
1782
- transform(chunk, controller) {
1783
- var _a, _b, _c, _d, _e, _f, _g, _h, _i, _j, _k, _l;
1784
- if (options.includeRawChunks) {
1785
- controller.enqueue({ type: "raw", rawValue: chunk.rawValue });
1786
- }
1787
- if (!chunk.success) {
1788
- controller.enqueue({ type: "error", error: chunk.error });
1789
- return;
1790
- }
1791
- const value = chunk.value;
1792
- const usageMetadata = value.usageMetadata;
1793
- if (usageMetadata != null) {
1794
- usage = usageMetadata;
1795
- }
1796
- if (value.serviceTier != null) {
1797
- serviceTier = value.serviceTier;
1798
- }
1799
- const candidate = (_a = value.candidates) == null ? void 0 : _a[0];
1800
- if (candidate == null) {
1801
- return;
1802
- }
1803
- const content = candidate.content;
1804
- if (candidate.groundingMetadata != null) {
1805
- lastGroundingMetadata = candidate.groundingMetadata;
1806
- }
1807
- if (candidate.urlContextMetadata != null) {
1808
- lastUrlContextMetadata = candidate.urlContextMetadata;
1809
- }
1810
- const sources = extractSources({
1811
- groundingMetadata: candidate.groundingMetadata,
1812
- generateId: generateId3
1813
- });
1814
- if (sources != null) {
1815
- for (const source of sources) {
1816
- if (source.sourceType === "url" && !emittedSourceUrls.has(source.url)) {
1817
- emittedSourceUrls.add(source.url);
1818
- controller.enqueue(source);
1819
- }
1820
- }
1821
- }
1822
- if (content != null) {
1823
- const parts = (_b = content.parts) != null ? _b : [];
1824
- for (const part of parts) {
1825
- if ("executableCode" in part && ((_c = part.executableCode) == null ? void 0 : _c.code)) {
1826
- const toolCallId = generateId3();
1827
- lastCodeExecutionToolCallId = toolCallId;
1828
- controller.enqueue({
1829
- type: "tool-call",
1830
- toolCallId,
1831
- toolName: "code_execution",
1832
- input: JSON.stringify(part.executableCode),
1833
- providerExecuted: true
1834
- });
1835
- } else if ("codeExecutionResult" in part && part.codeExecutionResult) {
1836
- const toolCallId = lastCodeExecutionToolCallId;
1837
- if (toolCallId) {
1838
- controller.enqueue({
1839
- type: "tool-result",
1840
- toolCallId,
1841
- toolName: "code_execution",
1842
- result: {
1843
- outcome: part.codeExecutionResult.outcome,
1844
- output: (_d = part.codeExecutionResult.output) != null ? _d : ""
1845
- }
1846
- });
1847
- lastCodeExecutionToolCallId = void 0;
1848
- }
1849
- } else if ("text" in part && part.text != null) {
1850
- const thoughtSignatureMetadata = part.thoughtSignature ? {
1851
- [providerOptionsName]: {
1852
- thoughtSignature: part.thoughtSignature
1853
- }
1854
- } : void 0;
1855
- if (part.text.length === 0) {
1856
- if (thoughtSignatureMetadata != null && currentTextBlockId !== null) {
1857
- controller.enqueue({
1858
- type: "text-delta",
1859
- id: currentTextBlockId,
1860
- delta: "",
1861
- providerMetadata: thoughtSignatureMetadata
1862
- });
1863
- }
1864
- } else if (part.thought === true) {
1865
- if (currentTextBlockId !== null) {
1866
- controller.enqueue({
1867
- type: "text-end",
1868
- id: currentTextBlockId
1869
- });
1870
- currentTextBlockId = null;
1871
- }
1872
- if (currentReasoningBlockId === null) {
1873
- currentReasoningBlockId = String(blockCounter++);
1874
- controller.enqueue({
1875
- type: "reasoning-start",
1876
- id: currentReasoningBlockId,
1877
- providerMetadata: thoughtSignatureMetadata
1878
- });
1879
- }
1880
- controller.enqueue({
1881
- type: "reasoning-delta",
1882
- id: currentReasoningBlockId,
1883
- delta: part.text,
1884
- providerMetadata: thoughtSignatureMetadata
1885
- });
1886
- } else {
1887
- if (currentReasoningBlockId !== null) {
1888
- controller.enqueue({
1889
- type: "reasoning-end",
1890
- id: currentReasoningBlockId
1891
- });
1892
- currentReasoningBlockId = null;
1893
- }
1894
- if (currentTextBlockId === null) {
1895
- currentTextBlockId = String(blockCounter++);
1896
- controller.enqueue({
1897
- type: "text-start",
1898
- id: currentTextBlockId,
1899
- providerMetadata: thoughtSignatureMetadata
1900
- });
1901
- }
1902
- controller.enqueue({
1903
- type: "text-delta",
1904
- id: currentTextBlockId,
1905
- delta: part.text,
1906
- providerMetadata: thoughtSignatureMetadata
1907
- });
1908
- }
1909
- } else if ("inlineData" in part) {
1910
- if (currentTextBlockId !== null) {
1911
- controller.enqueue({
1912
- type: "text-end",
1913
- id: currentTextBlockId
1914
- });
1915
- currentTextBlockId = null;
1916
- }
1917
- if (currentReasoningBlockId !== null) {
1918
- controller.enqueue({
1919
- type: "reasoning-end",
1920
- id: currentReasoningBlockId
1921
- });
1922
- currentReasoningBlockId = null;
1923
- }
1924
- const hasThought = part.thought === true;
1925
- const hasThoughtSignature = !!part.thoughtSignature;
1926
- const fileMeta = hasThoughtSignature ? {
1927
- [providerOptionsName]: {
1928
- thoughtSignature: part.thoughtSignature
1929
- }
1930
- } : void 0;
1931
- controller.enqueue({
1932
- type: hasThought ? "reasoning-file" : "file",
1933
- mediaType: part.inlineData.mimeType,
1934
- data: part.inlineData.data,
1935
- providerMetadata: fileMeta
1936
- });
1937
- } else if ("toolCall" in part && part.toolCall) {
1938
- const toolCallId = (_e = part.toolCall.id) != null ? _e : generateId3();
1939
- lastServerToolCallId = toolCallId;
1940
- const serverMeta = {
1941
- [providerOptionsName]: {
1942
- ...part.thoughtSignature ? { thoughtSignature: part.thoughtSignature } : {},
1943
- serverToolCallId: toolCallId,
1944
- serverToolType: part.toolCall.toolType
1945
- }
1946
- };
1947
- controller.enqueue({
1948
- type: "tool-call",
1949
- toolCallId,
1950
- toolName: `server:${part.toolCall.toolType}`,
1951
- input: JSON.stringify((_f = part.toolCall.args) != null ? _f : {}),
1952
- providerExecuted: true,
1953
- dynamic: true,
1954
- providerMetadata: serverMeta
1955
- });
1956
- } else if ("toolResponse" in part && part.toolResponse) {
1957
- const responseToolCallId = (_g = lastServerToolCallId != null ? lastServerToolCallId : part.toolResponse.id) != null ? _g : generateId3();
1958
- const serverMeta = {
1959
- [providerOptionsName]: {
1960
- ...part.thoughtSignature ? { thoughtSignature: part.thoughtSignature } : {},
1961
- serverToolCallId: responseToolCallId,
1962
- serverToolType: part.toolResponse.toolType
1963
- }
1964
- };
1965
- controller.enqueue({
1966
- type: "tool-result",
1967
- toolCallId: responseToolCallId,
1968
- toolName: `server:${part.toolResponse.toolType}`,
1969
- result: (_h = part.toolResponse.response) != null ? _h : {},
1970
- providerMetadata: serverMeta
1971
- });
1972
- lastServerToolCallId = void 0;
1973
- }
1974
- }
1975
- for (const part of parts) {
1976
- if (!("functionCall" in part)) continue;
1977
- const providerMeta = part.thoughtSignature ? {
1978
- [providerOptionsName]: {
1979
- thoughtSignature: part.thoughtSignature
1980
- }
1981
- } : void 0;
1982
- const isStreamingChunk = part.functionCall.partialArgs != null || part.functionCall.name != null && part.functionCall.willContinue === true;
1983
- const isTerminalChunk = part.functionCall.name == null && part.functionCall.args == null && part.functionCall.partialArgs == null && part.functionCall.willContinue == null;
1984
- const isCompleteCall = part.functionCall.name != null && part.functionCall.args != null && part.functionCall.partialArgs == null;
1985
- if (isStreamingChunk) {
1986
- if (part.functionCall.name != null && part.functionCall.willContinue === true) {
1987
- const toolCallId = generateId3();
1988
- const accumulator = new GoogleJSONAccumulator();
1989
- activeStreamingToolCalls.push({
1990
- toolCallId,
1991
- toolName: part.functionCall.name,
1992
- accumulator,
1993
- providerMetadata: providerMeta
1994
- });
1995
- controller.enqueue({
1996
- type: "tool-input-start",
1997
- id: toolCallId,
1998
- toolName: part.functionCall.name,
1999
- providerMetadata: providerMeta
2000
- });
2001
- if (part.functionCall.partialArgs != null) {
2002
- const { textDelta } = accumulator.processPartialArgs(
2003
- part.functionCall.partialArgs
2004
- );
2005
- if (textDelta.length > 0) {
2006
- controller.enqueue({
2007
- type: "tool-input-delta",
2008
- id: toolCallId,
2009
- delta: textDelta,
2010
- providerMetadata: providerMeta
2011
- });
2012
- }
2013
- }
2014
- } else if (part.functionCall.partialArgs != null && activeStreamingToolCalls.length > 0) {
2015
- const active = activeStreamingToolCalls[activeStreamingToolCalls.length - 1];
2016
- const { textDelta } = active.accumulator.processPartialArgs(
2017
- part.functionCall.partialArgs
2018
- );
2019
- if (textDelta.length > 0) {
2020
- controller.enqueue({
2021
- type: "tool-input-delta",
2022
- id: active.toolCallId,
2023
- delta: textDelta,
2024
- providerMetadata: providerMeta
2025
- });
2026
- }
2027
- }
2028
- } else if (isTerminalChunk && activeStreamingToolCalls.length > 0) {
2029
- const active = activeStreamingToolCalls.pop();
2030
- const { finalJSON, closingDelta } = active.accumulator.finalize();
2031
- if (closingDelta.length > 0) {
2032
- controller.enqueue({
2033
- type: "tool-input-delta",
2034
- id: active.toolCallId,
2035
- delta: closingDelta,
2036
- providerMetadata: active.providerMetadata
2037
- });
2038
- }
2039
- controller.enqueue({
2040
- type: "tool-input-end",
2041
- id: active.toolCallId,
2042
- providerMetadata: active.providerMetadata
2043
- });
2044
- controller.enqueue({
2045
- type: "tool-call",
2046
- toolCallId: active.toolCallId,
2047
- toolName: active.toolName,
2048
- input: finalJSON,
2049
- providerMetadata: active.providerMetadata
2050
- });
2051
- hasToolCalls = true;
2052
- } else if (isCompleteCall) {
2053
- const toolCallId = generateId3();
2054
- const toolName = part.functionCall.name;
2055
- const args2 = typeof part.functionCall.args === "string" ? part.functionCall.args : JSON.stringify((_i = part.functionCall.args) != null ? _i : {});
2056
- controller.enqueue({
2057
- type: "tool-input-start",
2058
- id: toolCallId,
2059
- toolName,
2060
- providerMetadata: providerMeta
2061
- });
2062
- controller.enqueue({
2063
- type: "tool-input-delta",
2064
- id: toolCallId,
2065
- delta: args2,
2066
- providerMetadata: providerMeta
2067
- });
2068
- controller.enqueue({
2069
- type: "tool-input-end",
2070
- id: toolCallId,
2071
- providerMetadata: providerMeta
2072
- });
2073
- controller.enqueue({
2074
- type: "tool-call",
2075
- toolCallId,
2076
- toolName,
2077
- input: args2,
2078
- providerMetadata: providerMeta
2079
- });
2080
- hasToolCalls = true;
2081
- }
2082
- }
2083
- }
2084
- if (candidate.finishReason != null) {
2085
- finishReason = {
2086
- unified: mapGoogleGenerativeAIFinishReason({
2087
- finishReason: candidate.finishReason,
2088
- hasToolCalls
2089
- }),
2090
- raw: candidate.finishReason
2091
- };
2092
- providerMetadata = {
2093
- [providerOptionsName]: {
2094
- promptFeedback: (_j = value.promptFeedback) != null ? _j : null,
2095
- groundingMetadata: lastGroundingMetadata,
2096
- urlContextMetadata: lastUrlContextMetadata,
2097
- safetyRatings: (_k = candidate.safetyRatings) != null ? _k : null,
2098
- usageMetadata: usageMetadata != null ? usageMetadata : null,
2099
- finishMessage: (_l = candidate.finishMessage) != null ? _l : null,
2100
- serviceTier
2101
- }
2102
- };
2103
- }
2104
- },
2105
- flush(controller) {
2106
- if (currentTextBlockId !== null) {
2107
- controller.enqueue({
2108
- type: "text-end",
2109
- id: currentTextBlockId
2110
- });
2111
- }
2112
- if (currentReasoningBlockId !== null) {
2113
- controller.enqueue({
2114
- type: "reasoning-end",
2115
- id: currentReasoningBlockId
2116
- });
2117
- }
2118
- controller.enqueue({
2119
- type: "finish",
2120
- finishReason,
2121
- usage: convertGoogleGenerativeAIUsage(usage),
2122
- providerMetadata
2123
- });
2124
- }
2125
- })
2126
- ),
2127
- response: { headers: responseHeaders },
2128
- request: { body: args }
2129
- };
2130
- }
2131
- };
2132
- function isGemini3Model(modelId) {
2133
- return /gemini-3[\.\-]/i.test(modelId) || /gemini-3$/i.test(modelId);
2134
- }
2135
- function getMaxOutputTokensForGemini25Model() {
2136
- return 65536;
2137
- }
2138
- function getMaxThinkingTokensForGemini25Model(modelId) {
2139
- const id = modelId.toLowerCase();
2140
- if (id.includes("2.5-pro") || id.includes("gemini-3-pro-image")) {
2141
- return 32768;
2142
- }
2143
- return 24576;
2144
- }
2145
- function resolveThinkingConfig({
2146
- reasoning,
2147
- modelId,
2148
- warnings
2149
- }) {
2150
- if (!isCustomReasoning(reasoning)) {
2151
- return void 0;
2152
- }
2153
- if (isGemini3Model(modelId) && !modelId.includes("gemini-3-pro-image")) {
2154
- return resolveGemini3ThinkingConfig({ reasoning, warnings });
2155
- }
2156
- return resolveGemini25ThinkingConfig({ reasoning, modelId, warnings });
2157
- }
2158
- function resolveGemini3ThinkingConfig({
2159
- reasoning,
2160
- warnings
2161
- }) {
2162
- if (reasoning === "none") {
2163
- return { thinkingLevel: "minimal" };
2164
- }
2165
- const thinkingLevel = mapReasoningToProviderEffort({
2166
- reasoning,
2167
- effortMap: {
2168
- minimal: "minimal",
2169
- low: "low",
2170
- medium: "medium",
2171
- high: "high",
2172
- xhigh: "high"
2173
- },
2174
- warnings
2175
- });
2176
- if (thinkingLevel == null) {
2177
- return void 0;
2178
- }
2179
- return { thinkingLevel };
2180
- }
2181
- function resolveGemini25ThinkingConfig({
2182
- reasoning,
2183
- modelId,
2184
- warnings
2185
- }) {
2186
- if (reasoning === "none") {
2187
- return { thinkingBudget: 0 };
2188
- }
2189
- const thinkingBudget = mapReasoningToProviderBudget({
2190
- reasoning,
2191
- maxOutputTokens: getMaxOutputTokensForGemini25Model(),
2192
- maxReasoningBudget: getMaxThinkingTokensForGemini25Model(modelId),
2193
- minReasoningBudget: 0,
2194
- warnings
2195
- });
2196
- if (thinkingBudget == null) {
2197
- return void 0;
2198
- }
2199
- return { thinkingBudget };
2200
- }
2201
- function extractSources({
2202
- groundingMetadata,
2203
- generateId: generateId3
2204
- }) {
2205
- var _a, _b, _c, _d, _e, _f;
2206
- if (!(groundingMetadata == null ? void 0 : groundingMetadata.groundingChunks)) {
2207
- return void 0;
2208
- }
2209
- const sources = [];
2210
- for (const chunk of groundingMetadata.groundingChunks) {
2211
- if (chunk.web != null) {
2212
- sources.push({
2213
- type: "source",
2214
- sourceType: "url",
2215
- id: generateId3(),
2216
- url: chunk.web.uri,
2217
- title: (_a = chunk.web.title) != null ? _a : void 0
2218
- });
2219
- } else if (chunk.image != null) {
2220
- sources.push({
2221
- type: "source",
2222
- sourceType: "url",
2223
- id: generateId3(),
2224
- // Google requires attribution to the source URI, not the actual image URI.
2225
- // TODO: add another type in v7 to allow both the image and source URL to be included separately
2226
- url: chunk.image.sourceUri,
2227
- title: (_b = chunk.image.title) != null ? _b : void 0
2228
- });
2229
- } else if (chunk.retrievedContext != null) {
2230
- const uri = chunk.retrievedContext.uri;
2231
- const fileSearchStore = chunk.retrievedContext.fileSearchStore;
2232
- if (uri && (uri.startsWith("http://") || uri.startsWith("https://"))) {
2233
- sources.push({
2234
- type: "source",
2235
- sourceType: "url",
2236
- id: generateId3(),
2237
- url: uri,
2238
- title: (_c = chunk.retrievedContext.title) != null ? _c : void 0
2239
- });
2240
- } else if (uri) {
2241
- const title = (_d = chunk.retrievedContext.title) != null ? _d : "Unknown Document";
2242
- let mediaType = "application/octet-stream";
2243
- let filename = void 0;
2244
- if (uri.endsWith(".pdf")) {
2245
- mediaType = "application/pdf";
2246
- filename = uri.split("/").pop();
2247
- } else if (uri.endsWith(".txt")) {
2248
- mediaType = "text/plain";
2249
- filename = uri.split("/").pop();
2250
- } else if (uri.endsWith(".docx")) {
2251
- mediaType = "application/vnd.openxmlformats-officedocument.wordprocessingml.document";
2252
- filename = uri.split("/").pop();
2253
- } else if (uri.endsWith(".doc")) {
2254
- mediaType = "application/msword";
2255
- filename = uri.split("/").pop();
2256
- } else if (uri.match(/\.(md|markdown)$/)) {
2257
- mediaType = "text/markdown";
2258
- filename = uri.split("/").pop();
2259
- } else {
2260
- filename = uri.split("/").pop();
2261
- }
2262
- sources.push({
2263
- type: "source",
2264
- sourceType: "document",
2265
- id: generateId3(),
2266
- mediaType,
2267
- title,
2268
- filename
2269
- });
2270
- } else if (fileSearchStore) {
2271
- const title = (_e = chunk.retrievedContext.title) != null ? _e : "Unknown Document";
2272
- sources.push({
2273
- type: "source",
2274
- sourceType: "document",
2275
- id: generateId3(),
2276
- mediaType: "application/octet-stream",
2277
- title,
2278
- filename: fileSearchStore.split("/").pop()
2279
- });
2280
- }
2281
- } else if (chunk.maps != null) {
2282
- if (chunk.maps.uri) {
2283
- sources.push({
2284
- type: "source",
2285
- sourceType: "url",
2286
- id: generateId3(),
2287
- url: chunk.maps.uri,
2288
- title: (_f = chunk.maps.title) != null ? _f : void 0
2289
- });
2290
- }
2291
- }
2292
- }
2293
- return sources.length > 0 ? sources : void 0;
2294
- }
2295
- var getGroundingMetadataSchema = () => z5.object({
2296
- webSearchQueries: z5.array(z5.string()).nullish(),
2297
- imageSearchQueries: z5.array(z5.string()).nullish(),
2298
- retrievalQueries: z5.array(z5.string()).nullish(),
2299
- searchEntryPoint: z5.object({ renderedContent: z5.string() }).nullish(),
2300
- groundingChunks: z5.array(
2301
- z5.object({
2302
- web: z5.object({ uri: z5.string(), title: z5.string().nullish() }).nullish(),
2303
- image: z5.object({
2304
- sourceUri: z5.string(),
2305
- imageUri: z5.string(),
2306
- title: z5.string().nullish(),
2307
- domain: z5.string().nullish()
2308
- }).nullish(),
2309
- retrievedContext: z5.object({
2310
- uri: z5.string().nullish(),
2311
- title: z5.string().nullish(),
2312
- text: z5.string().nullish(),
2313
- fileSearchStore: z5.string().nullish()
2314
- }).nullish(),
2315
- maps: z5.object({
2316
- uri: z5.string().nullish(),
2317
- title: z5.string().nullish(),
2318
- text: z5.string().nullish(),
2319
- placeId: z5.string().nullish()
2320
- }).nullish()
2321
- })
2322
- ).nullish(),
2323
- groundingSupports: z5.array(
2324
- z5.object({
2325
- segment: z5.object({
2326
- startIndex: z5.number().nullish(),
2327
- endIndex: z5.number().nullish(),
2328
- text: z5.string().nullish()
2329
- }).nullish(),
2330
- segment_text: z5.string().nullish(),
2331
- groundingChunkIndices: z5.array(z5.number()).nullish(),
2332
- supportChunkIndices: z5.array(z5.number()).nullish(),
2333
- confidenceScores: z5.array(z5.number()).nullish(),
2334
- confidenceScore: z5.array(z5.number()).nullish()
2335
- })
2336
- ).nullish(),
2337
- retrievalMetadata: z5.union([
2338
- z5.object({
2339
- webDynamicRetrievalScore: z5.number()
2340
- }),
2341
- z5.object({})
2342
- ]).nullish()
2343
- });
2344
- var partialArgSchema = z5.object({
2345
- jsonPath: z5.string(),
2346
- stringValue: z5.string().nullish(),
2347
- numberValue: z5.number().nullish(),
2348
- boolValue: z5.boolean().nullish(),
2349
- nullValue: z5.unknown().nullish(),
2350
- willContinue: z5.boolean().nullish()
2351
- });
2352
- var getContentSchema = () => z5.object({
2353
- parts: z5.array(
2354
- z5.union([
2355
- // note: order matters since text can be fully empty
2356
- z5.object({
2357
- functionCall: z5.object({
2358
- name: z5.string().nullish(),
2359
- args: z5.unknown().nullish(),
2360
- partialArgs: z5.array(partialArgSchema).nullish(),
2361
- willContinue: z5.boolean().nullish()
2362
- }),
2363
- thoughtSignature: z5.string().nullish()
2364
- }),
2365
- z5.object({
2366
- inlineData: z5.object({
2367
- mimeType: z5.string(),
2368
- data: z5.string()
2369
- }),
2370
- thought: z5.boolean().nullish(),
2371
- thoughtSignature: z5.string().nullish()
2372
- }),
2373
- z5.object({
2374
- toolCall: z5.object({
2375
- toolType: z5.string(),
2376
- args: z5.unknown().nullish(),
2377
- id: z5.string()
2378
- }),
2379
- thoughtSignature: z5.string().nullish()
2380
- }),
2381
- z5.object({
2382
- toolResponse: z5.object({
2383
- toolType: z5.string(),
2384
- response: z5.unknown().nullish(),
2385
- id: z5.string()
2386
- }),
2387
- thoughtSignature: z5.string().nullish()
2388
- }),
2389
- z5.object({
2390
- executableCode: z5.object({
2391
- language: z5.string(),
2392
- code: z5.string()
2393
- }).nullish(),
2394
- codeExecutionResult: z5.object({
2395
- outcome: z5.string(),
2396
- output: z5.string().nullish()
2397
- }).nullish(),
2398
- text: z5.string().nullish(),
2399
- thought: z5.boolean().nullish(),
2400
- thoughtSignature: z5.string().nullish()
2401
- })
2402
- ])
2403
- ).nullish()
2404
- });
2405
- var getSafetyRatingSchema = () => z5.object({
2406
- category: z5.string().nullish(),
2407
- probability: z5.string().nullish(),
2408
- probabilityScore: z5.number().nullish(),
2409
- severity: z5.string().nullish(),
2410
- severityScore: z5.number().nullish(),
2411
- blocked: z5.boolean().nullish()
2412
- });
2413
- var tokenDetailsSchema = z5.array(
2414
- z5.object({
2415
- modality: z5.string(),
2416
- tokenCount: z5.number()
2417
- })
2418
- ).nullish();
2419
- var usageSchema = z5.object({
2420
- cachedContentTokenCount: z5.number().nullish(),
2421
- thoughtsTokenCount: z5.number().nullish(),
2422
- promptTokenCount: z5.number().nullish(),
2423
- candidatesTokenCount: z5.number().nullish(),
2424
- totalTokenCount: z5.number().nullish(),
2425
- // https://cloud.google.com/vertex-ai/generative-ai/docs/reference/rest/v1/GenerateContentResponse#TrafficType
2426
- trafficType: z5.string().nullish(),
2427
- // https://ai.google.dev/api/generate-content#Modality
2428
- promptTokensDetails: tokenDetailsSchema,
2429
- candidatesTokensDetails: tokenDetailsSchema
2430
- });
2431
- var getUrlContextMetadataSchema = () => z5.object({
2432
- urlMetadata: z5.array(
2433
- z5.object({
2434
- retrievedUrl: z5.string(),
2435
- urlRetrievalStatus: z5.string()
2436
- })
2437
- ).nullish()
2438
- });
2439
- var responseSchema = lazySchema5(
2440
- () => zodSchema5(
2441
- z5.object({
2442
- candidates: z5.array(
2443
- z5.object({
2444
- content: getContentSchema().nullish().or(z5.object({}).strict()),
2445
- finishReason: z5.string().nullish(),
2446
- finishMessage: z5.string().nullish(),
2447
- safetyRatings: z5.array(getSafetyRatingSchema()).nullish(),
2448
- groundingMetadata: getGroundingMetadataSchema().nullish(),
2449
- urlContextMetadata: getUrlContextMetadataSchema().nullish()
2450
- })
2451
- ),
2452
- usageMetadata: usageSchema.nullish(),
2453
- promptFeedback: z5.object({
2454
- blockReason: z5.string().nullish(),
2455
- safetyRatings: z5.array(getSafetyRatingSchema()).nullish()
2456
- }).nullish(),
2457
- serviceTier: z5.string().nullish()
2458
- })
2459
- )
2460
- );
2461
- var chunkSchema = lazySchema5(
2462
- () => zodSchema5(
2463
- z5.object({
2464
- candidates: z5.array(
2465
- z5.object({
2466
- content: getContentSchema().nullish(),
2467
- finishReason: z5.string().nullish(),
2468
- finishMessage: z5.string().nullish(),
2469
- safetyRatings: z5.array(getSafetyRatingSchema()).nullish(),
2470
- groundingMetadata: getGroundingMetadataSchema().nullish(),
2471
- urlContextMetadata: getUrlContextMetadataSchema().nullish()
2472
- })
2473
- ).nullish(),
2474
- usageMetadata: usageSchema.nullish(),
2475
- promptFeedback: z5.object({
2476
- blockReason: z5.string().nullish(),
2477
- safetyRatings: z5.array(getSafetyRatingSchema()).nullish()
2478
- }).nullish(),
2479
- serviceTier: z5.string().nullish()
2480
- })
2481
- )
2482
- );
2483
-
2484
- // src/tool/code-execution.ts
2485
- import { createProviderToolFactoryWithOutputSchema } from "@ai-sdk/provider-utils";
2486
- import { z as z6 } from "zod/v4";
2487
- var codeExecution = createProviderToolFactoryWithOutputSchema({
2488
- id: "google.code_execution",
2489
- inputSchema: z6.object({
2490
- language: z6.string().describe("The programming language of the code."),
2491
- code: z6.string().describe("The code to be executed.")
2492
- }),
2493
- outputSchema: z6.object({
2494
- outcome: z6.string().describe('The outcome of the execution (e.g., "OUTCOME_OK").'),
2495
- output: z6.string().describe("The output from the code execution.")
2496
- })
2497
- });
2498
-
2499
- // src/tool/enterprise-web-search.ts
2500
- import {
2501
- createProviderToolFactory,
2502
- lazySchema as lazySchema6,
2503
- zodSchema as zodSchema6
2504
- } from "@ai-sdk/provider-utils";
2505
- import { z as z7 } from "zod/v4";
2506
- var enterpriseWebSearch = createProviderToolFactory({
2507
- id: "google.enterprise_web_search",
2508
- inputSchema: lazySchema6(() => zodSchema6(z7.object({})))
2509
- });
2510
-
2511
- // src/tool/file-search.ts
2512
- import {
2513
- createProviderToolFactory as createProviderToolFactory2,
2514
- lazySchema as lazySchema7,
2515
- zodSchema as zodSchema7
2516
- } from "@ai-sdk/provider-utils";
2517
- import { z as z8 } from "zod/v4";
2518
- var fileSearchArgsBaseSchema = z8.object({
2519
- /** The names of the file_search_stores to retrieve from.
2520
- * Example: `fileSearchStores/my-file-search-store-123`
2521
- */
2522
- fileSearchStoreNames: z8.array(z8.string()).describe(
2523
- "The names of the file_search_stores to retrieve from. Example: `fileSearchStores/my-file-search-store-123`"
2524
- ),
2525
- /** The number of file search retrieval chunks to retrieve. */
2526
- topK: z8.number().int().positive().describe("The number of file search retrieval chunks to retrieve.").optional(),
2527
- /** Metadata filter to apply to the file search retrieval documents.
2528
- * See https://google.aip.dev/160 for the syntax of the filter expression.
2529
- */
2530
- metadataFilter: z8.string().describe(
2531
- "Metadata filter to apply to the file search retrieval documents. See https://google.aip.dev/160 for the syntax of the filter expression."
2532
- ).optional()
2533
- }).passthrough();
2534
- var fileSearchArgsSchema = lazySchema7(
2535
- () => zodSchema7(fileSearchArgsBaseSchema)
2536
- );
2537
- var fileSearch = createProviderToolFactory2({
2538
- id: "google.file_search",
2539
- inputSchema: fileSearchArgsSchema
2540
- });
2541
-
2542
- // src/tool/google-maps.ts
2543
- import {
2544
- createProviderToolFactory as createProviderToolFactory3,
2545
- lazySchema as lazySchema8,
2546
- zodSchema as zodSchema8
2547
- } from "@ai-sdk/provider-utils";
2548
- import { z as z9 } from "zod/v4";
2549
- var googleMaps = createProviderToolFactory3({
2550
- id: "google.google_maps",
2551
- inputSchema: lazySchema8(() => zodSchema8(z9.object({})))
2552
- });
2553
-
2554
- // src/tool/google-search.ts
2555
- import {
2556
- createProviderToolFactory as createProviderToolFactory4,
2557
- lazySchema as lazySchema9,
2558
- zodSchema as zodSchema9
2559
- } from "@ai-sdk/provider-utils";
2560
- import { z as z10 } from "zod/v4";
2561
- var googleSearchToolArgsBaseSchema = z10.object({
2562
- searchTypes: z10.object({
2563
- webSearch: z10.object({}).optional(),
2564
- imageSearch: z10.object({}).optional()
2565
- }).optional(),
2566
- timeRangeFilter: z10.object({
2567
- startTime: z10.string(),
2568
- endTime: z10.string()
2569
- }).optional()
2570
- }).passthrough();
2571
- var googleSearchToolArgsSchema = lazySchema9(
2572
- () => zodSchema9(googleSearchToolArgsBaseSchema)
2573
- );
2574
- var googleSearch = createProviderToolFactory4(
2575
- {
2576
- id: "google.google_search",
2577
- inputSchema: googleSearchToolArgsSchema
2578
- }
2579
- );
2580
-
2581
- // src/tool/url-context.ts
2582
- import {
2583
- createProviderToolFactory as createProviderToolFactory5,
2584
- lazySchema as lazySchema10,
2585
- zodSchema as zodSchema10
2586
- } from "@ai-sdk/provider-utils";
2587
- import { z as z11 } from "zod/v4";
2588
- var urlContext = createProviderToolFactory5({
2589
- id: "google.url_context",
2590
- inputSchema: lazySchema10(() => zodSchema10(z11.object({})))
2591
- });
2592
-
2593
- // src/tool/vertex-rag-store.ts
2594
- import { createProviderToolFactory as createProviderToolFactory6 } from "@ai-sdk/provider-utils";
2595
- import { z as z12 } from "zod/v4";
2596
- var vertexRagStore = createProviderToolFactory6({
2597
- id: "google.vertex_rag_store",
2598
- inputSchema: z12.object({
2599
- ragCorpus: z12.string(),
2600
- topK: z12.number().optional()
2601
- })
2602
- });
2603
-
2604
- // src/google-tools.ts
2605
- var googleTools = {
2606
- /**
2607
- * Creates a Google search tool that gives Google direct access to real-time web content.
2608
- * Must have name "google_search".
2609
- */
2610
- googleSearch,
2611
- /**
2612
- * Creates an Enterprise Web Search tool for grounding responses using a compliance-focused web index.
2613
- * Designed for highly-regulated industries (finance, healthcare, public sector).
2614
- * Does not log customer data and supports VPC service controls.
2615
- * Must have name "enterprise_web_search".
2616
- *
2617
- * @note Only available on Vertex AI. Requires Gemini 2.0 or newer.
2618
- *
2619
- * @see https://cloud.google.com/vertex-ai/generative-ai/docs/grounding/web-grounding-enterprise
2620
- */
2621
- enterpriseWebSearch,
2622
- /**
2623
- * Creates a Google Maps grounding tool that gives the model access to Google Maps data.
2624
- * Must have name "google_maps".
2625
- *
2626
- * @see https://ai.google.dev/gemini-api/docs/maps-grounding
2627
- * @see https://cloud.google.com/vertex-ai/generative-ai/docs/grounding/grounding-with-google-maps
2628
- */
2629
- googleMaps,
2630
- /**
2631
- * Creates a URL context tool that gives Google direct access to real-time web content.
2632
- * Must have name "url_context".
2633
- */
2634
- urlContext,
2635
- /**
2636
- * Enables Retrieval Augmented Generation (RAG) via the Gemini File Search tool.
2637
- * Must have name "file_search".
2638
- *
2639
- * @param fileSearchStoreNames - Fully-qualified File Search store resource names.
2640
- * @param metadataFilter - Optional filter expression to restrict the files that can be retrieved.
2641
- * @param topK - Optional result limit for the number of chunks returned from File Search.
2642
- *
2643
- * @see https://ai.google.dev/gemini-api/docs/file-search
2644
- */
2645
- fileSearch,
2646
- /**
2647
- * A tool that enables the model to generate and run Python code.
2648
- * Must have name "code_execution".
2649
- *
2650
- * @note Ensure the selected model supports Code Execution.
2651
- * Multi-tool usage with the code execution tool is typically compatible with Gemini >=2 models.
2652
- *
2653
- * @see https://ai.google.dev/gemini-api/docs/code-execution (Google AI)
2654
- * @see https://cloud.google.com/vertex-ai/generative-ai/docs/model-reference/code-execution-api (Vertex AI)
2655
- */
2656
- codeExecution,
2657
- /**
2658
- * Creates a Vertex RAG Store tool that enables the model to perform RAG searches against a Vertex RAG Store.
2659
- * Must have name "vertex_rag_store".
2660
- */
2661
- vertexRagStore
2662
- };
2663
-
2664
- // src/google-generative-ai-image-model.ts
2665
- import {
2666
- combineHeaders as combineHeaders3,
2667
- convertToBase64 as convertToBase642,
2668
- createJsonResponseHandler as createJsonResponseHandler3,
2669
- generateId as defaultGenerateId,
2670
- lazySchema as lazySchema11,
2671
- parseProviderOptions as parseProviderOptions3,
2672
- postJsonToApi as postJsonToApi3,
2673
- resolve as resolve3,
2674
- zodSchema as zodSchema11
2675
- } from "@ai-sdk/provider-utils";
2676
- import { z as z13 } from "zod/v4";
2677
- var GoogleGenerativeAIImageModel = class {
2678
- constructor(modelId, settings, config) {
2679
- this.modelId = modelId;
2680
- this.settings = settings;
2681
- this.config = config;
2682
- this.specificationVersion = "v4";
2683
- }
2684
- get maxImagesPerCall() {
2685
- if (this.settings.maxImagesPerCall != null) {
2686
- return this.settings.maxImagesPerCall;
2687
- }
2688
- if (isGeminiModel(this.modelId)) {
2689
- return 10;
2690
- }
2691
- return 4;
2692
- }
2693
- get provider() {
2694
- return this.config.provider;
2695
- }
2696
- async doGenerate(options) {
2697
- if (isGeminiModel(this.modelId)) {
2698
- return this.doGenerateGemini(options);
2699
- }
2700
- return this.doGenerateImagen(options);
2701
- }
2702
- async doGenerateImagen(options) {
2703
- var _a, _b, _c;
2704
- const {
2705
- prompt,
2706
- n = 1,
2707
- size,
2708
- aspectRatio = "1:1",
2709
- seed,
2710
- providerOptions,
2711
- headers,
2712
- abortSignal,
2713
- files,
2714
- mask
2715
- } = options;
2716
- const warnings = [];
2717
- if (files != null && files.length > 0) {
2718
- throw new Error(
2719
- "Google Generative AI does not support image editing with Imagen models. Use Google Vertex AI (@ai-sdk/google-vertex) for image editing capabilities."
2720
- );
2721
- }
2722
- if (mask != null) {
2723
- throw new Error(
2724
- "Google Generative AI does not support image editing with masks. Use Google Vertex AI (@ai-sdk/google-vertex) for image editing capabilities."
2725
- );
2726
- }
2727
- if (size != null) {
2728
- warnings.push({
2729
- type: "unsupported",
2730
- feature: "size",
2731
- details: "This model does not support the `size` option. Use `aspectRatio` instead."
2732
- });
2733
- }
2734
- if (seed != null) {
2735
- warnings.push({
2736
- type: "unsupported",
2737
- feature: "seed",
2738
- details: "This model does not support the `seed` option through this provider."
2739
- });
2740
- }
2741
- const googleOptions = await parseProviderOptions3({
2742
- provider: "google",
2743
- providerOptions,
2744
- schema: googleImageModelOptionsSchema
2745
- });
2746
- const currentDate = (_c = (_b = (_a = this.config._internal) == null ? void 0 : _a.currentDate) == null ? void 0 : _b.call(_a)) != null ? _c : /* @__PURE__ */ new Date();
2747
- const parameters = {
2748
- sampleCount: n
2749
- };
2750
- if (aspectRatio != null) {
2751
- parameters.aspectRatio = aspectRatio;
2752
- }
2753
- if (googleOptions) {
2754
- Object.assign(parameters, googleOptions);
2755
- }
2756
- const body = {
2757
- instances: [{ prompt }],
2758
- parameters
2759
- };
2760
- const { responseHeaders, value: response } = await postJsonToApi3({
2761
- url: `${this.config.baseURL}/models/${this.modelId}:predict`,
2762
- headers: combineHeaders3(await resolve3(this.config.headers), headers),
2763
- body,
2764
- failedResponseHandler: googleFailedResponseHandler,
2765
- successfulResponseHandler: createJsonResponseHandler3(
2766
- googleImageResponseSchema
2767
- ),
2768
- abortSignal,
2769
- fetch: this.config.fetch
2770
- });
2771
- return {
2772
- images: response.predictions.map(
2773
- (p) => p.bytesBase64Encoded
2774
- ),
2775
- warnings,
2776
- providerMetadata: {
2777
- google: {
2778
- images: response.predictions.map(() => ({
2779
- // Add any prediction-specific metadata here
2780
- }))
2781
- }
2782
- },
2783
- response: {
2784
- timestamp: currentDate,
2785
- modelId: this.modelId,
2786
- headers: responseHeaders
2787
- }
2788
- };
2789
- }
2790
- async doGenerateGemini(options) {
2791
- var _a, _b, _c, _d, _e, _f, _g, _h, _i;
2792
- const {
2793
- prompt,
2794
- n,
2795
- size,
2796
- aspectRatio,
2797
- seed,
2798
- providerOptions,
2799
- headers,
2800
- abortSignal,
2801
- files,
2802
- mask
2803
- } = options;
2804
- const warnings = [];
2805
- if (mask != null) {
2806
- throw new Error(
2807
- "Gemini image models do not support mask-based image editing."
2808
- );
2809
- }
2810
- if (n != null && n > 1) {
2811
- throw new Error(
2812
- "Gemini image models do not support generating a set number of images per call. Use n=1 or omit the n parameter."
2813
- );
2814
- }
2815
- if (size != null) {
2816
- warnings.push({
2817
- type: "unsupported",
2818
- feature: "size",
2819
- details: "This model does not support the `size` option. Use `aspectRatio` instead."
2820
- });
2821
- }
2822
- const userContent = [];
2823
- if (prompt != null) {
2824
- userContent.push({ type: "text", text: prompt });
2825
- }
2826
- if (files != null && files.length > 0) {
2827
- for (const file of files) {
2828
- if (file.type === "url") {
2829
- userContent.push({
2830
- type: "file",
2831
- data: new URL(file.url),
2832
- mediaType: "image/*"
2833
- });
2834
- } else {
2835
- userContent.push({
2836
- type: "file",
2837
- data: typeof file.data === "string" ? file.data : new Uint8Array(file.data),
2838
- mediaType: file.mediaType
2839
- });
2840
- }
2841
- }
2842
- }
2843
- const languageModelPrompt = [
2844
- { role: "user", content: userContent }
2845
- ];
2846
- const languageModel = new GoogleGenerativeAILanguageModel(this.modelId, {
2847
- provider: this.config.provider,
2848
- baseURL: this.config.baseURL,
2849
- headers: (_a = this.config.headers) != null ? _a : {},
2850
- fetch: this.config.fetch,
2851
- generateId: (_b = this.config.generateId) != null ? _b : defaultGenerateId
2852
- });
2853
- const result = await languageModel.doGenerate({
2854
- prompt: languageModelPrompt,
2855
- seed,
2856
- providerOptions: {
2857
- google: {
2858
- responseModalities: ["IMAGE"],
2859
- imageConfig: aspectRatio ? {
2860
- aspectRatio
2861
- } : void 0,
2862
- ...(_c = providerOptions == null ? void 0 : providerOptions.google) != null ? _c : {}
2863
- }
2864
- },
2865
- headers,
2866
- abortSignal
2867
- });
2868
- const currentDate = (_f = (_e = (_d = this.config._internal) == null ? void 0 : _d.currentDate) == null ? void 0 : _e.call(_d)) != null ? _f : /* @__PURE__ */ new Date();
2869
- const images = [];
2870
- for (const part of result.content) {
2871
- if (part.type === "file" && part.mediaType.startsWith("image/")) {
2872
- images.push(convertToBase642(part.data));
2873
- }
2874
- }
2875
- return {
2876
- images,
2877
- warnings,
2878
- providerMetadata: {
2879
- google: {
2880
- images: images.map(() => ({}))
2881
- }
2882
- },
2883
- response: {
2884
- timestamp: currentDate,
2885
- modelId: this.modelId,
2886
- headers: (_g = result.response) == null ? void 0 : _g.headers
2887
- },
2888
- usage: result.usage ? {
2889
- inputTokens: result.usage.inputTokens.total,
2890
- outputTokens: result.usage.outputTokens.total,
2891
- totalTokens: ((_h = result.usage.inputTokens.total) != null ? _h : 0) + ((_i = result.usage.outputTokens.total) != null ? _i : 0)
2892
- } : void 0
2893
- };
2894
- }
2895
- };
2896
- function isGeminiModel(modelId) {
2897
- return modelId.startsWith("gemini-");
2898
- }
2899
- var googleImageResponseSchema = lazySchema11(
2900
- () => zodSchema11(
2901
- z13.object({
2902
- predictions: z13.array(z13.object({ bytesBase64Encoded: z13.string() })).default([])
2903
- })
2904
- )
2905
- );
2906
- var googleImageModelOptionsSchema = lazySchema11(
2907
- () => zodSchema11(
2908
- z13.object({
2909
- personGeneration: z13.enum(["dont_allow", "allow_adult", "allow_all"]).nullish(),
2910
- aspectRatio: z13.enum(["1:1", "3:4", "4:3", "9:16", "16:9"]).nullish()
2911
- })
2912
- )
2913
- );
2914
-
2915
- // src/google-generative-ai-files.ts
2916
- import {
2917
- AISDKError
2918
- } from "@ai-sdk/provider";
2919
- import {
2920
- combineHeaders as combineHeaders4,
2921
- createJsonResponseHandler as createJsonResponseHandler4,
2922
- delay,
2923
- lazySchema as lazySchema12,
2924
- parseProviderOptions as parseProviderOptions4,
2925
- zodSchema as zodSchema12,
2926
- getFromApi
2927
- } from "@ai-sdk/provider-utils";
2928
- import { z as z14 } from "zod/v4";
2929
- var GoogleGenerativeAIFiles = class {
2930
- constructor(config) {
2931
- this.config = config;
2932
- this.specificationVersion = "v4";
2933
- }
2934
- get provider() {
2935
- return this.config.provider;
2936
- }
2937
- async uploadFile(options) {
2938
- var _a, _b, _c, _d;
2939
- const googleOptions = await parseProviderOptions4({
2940
- provider: "google",
2941
- providerOptions: options.providerOptions,
2942
- schema: googleFilesUploadOptionsSchema
2943
- });
2944
- const resolvedHeaders = this.config.headers();
2945
- const fetchFn = (_a = this.config.fetch) != null ? _a : globalThis.fetch;
2946
- const warnings = [];
2947
- if (options.filename != null) {
2948
- warnings.push({ type: "unsupported", feature: "filename" });
2949
- }
2950
- const data = options.data;
2951
- const fileBytes = data instanceof Uint8Array ? data : Uint8Array.from(atob(data), (c) => c.charCodeAt(0));
2952
- const mediaType = options.mediaType;
2953
- const displayName = googleOptions == null ? void 0 : googleOptions.displayName;
2954
- const baseOrigin = this.config.baseURL.replace(/\/v1beta$/, "");
2955
- const initResponse = await fetchFn(`${baseOrigin}/upload/v1beta/files`, {
2956
- method: "POST",
2957
- headers: {
2958
- ...resolvedHeaders,
2959
- "X-Goog-Upload-Protocol": "resumable",
2960
- "X-Goog-Upload-Command": "start",
2961
- "X-Goog-Upload-Header-Content-Length": String(fileBytes.length),
2962
- "X-Goog-Upload-Header-Content-Type": mediaType,
2963
- "Content-Type": "application/json"
2964
- },
2965
- body: JSON.stringify({
2966
- file: {
2967
- ...displayName != null ? { display_name: displayName } : {}
2968
- }
2969
- })
2970
- });
2971
- if (!initResponse.ok) {
2972
- const errorBody = await initResponse.text();
2973
- throw new AISDKError({
2974
- name: "GOOGLE_FILES_UPLOAD_ERROR",
2975
- message: `Failed to initiate resumable upload: ${initResponse.status} ${errorBody}`
2976
- });
2977
- }
2978
- const uploadUrl = initResponse.headers.get("x-goog-upload-url");
2979
- if (!uploadUrl) {
2980
- throw new AISDKError({
2981
- name: "GOOGLE_FILES_UPLOAD_ERROR",
2982
- message: "No upload URL returned from initiation request"
2983
- });
2984
- }
2985
- const uploadResponse = await fetchFn(uploadUrl, {
2986
- method: "POST",
2987
- headers: {
2988
- "Content-Length": String(fileBytes.length),
2989
- "X-Goog-Upload-Offset": "0",
2990
- "X-Goog-Upload-Command": "upload, finalize"
2991
- },
2992
- body: fileBytes
2993
- });
2994
- if (!uploadResponse.ok) {
2995
- const errorBody = await uploadResponse.text();
2996
- throw new AISDKError({
2997
- name: "GOOGLE_FILES_UPLOAD_ERROR",
2998
- message: `Failed to upload file data: ${uploadResponse.status} ${errorBody}`
2999
- });
3000
- }
3001
- const uploadResult = await uploadResponse.json();
3002
- let file = uploadResult.file;
3003
- const pollIntervalMs = (_b = googleOptions == null ? void 0 : googleOptions.pollIntervalMs) != null ? _b : 2e3;
3004
- const pollTimeoutMs = (_c = googleOptions == null ? void 0 : googleOptions.pollTimeoutMs) != null ? _c : 3e5;
3005
- const startTime = Date.now();
3006
- while (file.state === "PROCESSING") {
3007
- if (Date.now() - startTime > pollTimeoutMs) {
3008
- throw new AISDKError({
3009
- name: "GOOGLE_FILES_UPLOAD_TIMEOUT",
3010
- message: `File processing timed out after ${pollTimeoutMs}ms`
3011
- });
3012
- }
3013
- await delay(pollIntervalMs);
3014
- const { value: fileStatus } = await getFromApi({
3015
- url: `${this.config.baseURL}/${file.name}`,
3016
- headers: combineHeaders4(resolvedHeaders),
3017
- successfulResponseHandler: createJsonResponseHandler4(
3018
- googleFileResponseSchema
3019
- ),
3020
- failedResponseHandler: googleFailedResponseHandler,
3021
- fetch: this.config.fetch
3022
- });
3023
- file = fileStatus;
3024
- }
3025
- if (file.state === "FAILED") {
3026
- throw new AISDKError({
3027
- name: "GOOGLE_FILES_UPLOAD_FAILED",
3028
- message: `File processing failed for ${file.name}`
3029
- });
3030
- }
3031
- return {
3032
- warnings,
3033
- providerReference: { google: file.uri },
3034
- mediaType: (_d = file.mimeType) != null ? _d : options.mediaType,
3035
- providerMetadata: {
3036
- google: {
3037
- name: file.name,
3038
- displayName: file.displayName,
3039
- mimeType: file.mimeType,
3040
- sizeBytes: file.sizeBytes,
3041
- state: file.state,
3042
- uri: file.uri,
3043
- ...file.createTime != null ? { createTime: file.createTime } : {},
3044
- ...file.updateTime != null ? { updateTime: file.updateTime } : {},
3045
- ...file.expirationTime != null ? { expirationTime: file.expirationTime } : {},
3046
- ...file.sha256Hash != null ? { sha256Hash: file.sha256Hash } : {}
3047
- }
3048
- }
3049
- };
3050
- }
3051
- };
3052
- var googleFileResponseSchema = lazySchema12(
3053
- () => zodSchema12(
3054
- z14.object({
3055
- name: z14.string(),
3056
- displayName: z14.string().nullish(),
3057
- mimeType: z14.string(),
3058
- sizeBytes: z14.string().nullish(),
3059
- createTime: z14.string().nullish(),
3060
- updateTime: z14.string().nullish(),
3061
- expirationTime: z14.string().nullish(),
3062
- sha256Hash: z14.string().nullish(),
3063
- uri: z14.string(),
3064
- state: z14.string()
3065
- })
3066
- )
3067
- );
3068
- var googleFilesUploadOptionsSchema = lazySchema12(
3069
- () => zodSchema12(
3070
- z14.object({
3071
- displayName: z14.string().nullish(),
3072
- pollIntervalMs: z14.number().positive().nullish(),
3073
- pollTimeoutMs: z14.number().positive().nullish()
3074
- }).passthrough()
3075
- )
3076
- );
3077
-
3078
- // src/google-generative-ai-video-model.ts
3079
- import {
3080
- AISDKError as AISDKError2
3081
- } from "@ai-sdk/provider";
3082
- import {
3083
- combineHeaders as combineHeaders5,
3084
- convertUint8ArrayToBase64,
3085
- createJsonResponseHandler as createJsonResponseHandler5,
3086
- delay as delay2,
3087
- getFromApi as getFromApi2,
3088
- lazySchema as lazySchema13,
3089
- parseProviderOptions as parseProviderOptions5,
3090
- postJsonToApi as postJsonToApi4,
3091
- resolve as resolve4,
3092
- zodSchema as zodSchema13
3093
- } from "@ai-sdk/provider-utils";
3094
- import { z as z15 } from "zod/v4";
3095
- var GoogleGenerativeAIVideoModel = class {
3096
- constructor(modelId, config) {
3097
- this.modelId = modelId;
3098
- this.config = config;
3099
- this.specificationVersion = "v4";
3100
- }
3101
- get provider() {
3102
- return this.config.provider;
3103
- }
3104
- get maxVideosPerCall() {
3105
- return 4;
3106
- }
3107
- async doGenerate(options) {
3108
- var _a, _b, _c, _d, _e, _f, _g, _h;
3109
- const currentDate = (_c = (_b = (_a = this.config._internal) == null ? void 0 : _a.currentDate) == null ? void 0 : _b.call(_a)) != null ? _c : /* @__PURE__ */ new Date();
3110
- const warnings = [];
3111
- const googleOptions = await parseProviderOptions5({
3112
- provider: "google",
3113
- providerOptions: options.providerOptions,
3114
- schema: googleVideoModelOptionsSchema
3115
- });
3116
- const instances = [{}];
3117
- const instance = instances[0];
3118
- if (options.prompt != null) {
3119
- instance.prompt = options.prompt;
3120
- }
3121
- if (options.image != null) {
3122
- if (options.image.type === "url") {
3123
- warnings.push({
3124
- type: "unsupported",
3125
- feature: "URL-based image input",
3126
- details: "Google Generative AI video models require base64-encoded images. URL will be ignored."
3127
- });
3128
- } else {
3129
- const base64Data = typeof options.image.data === "string" ? options.image.data : convertUint8ArrayToBase64(options.image.data);
3130
- instance.image = {
3131
- inlineData: {
3132
- mimeType: options.image.mediaType || "image/png",
3133
- data: base64Data
3134
- }
3135
- };
3136
- }
3137
- }
3138
- if ((googleOptions == null ? void 0 : googleOptions.referenceImages) != null) {
3139
- instance.referenceImages = googleOptions.referenceImages.map((refImg) => {
3140
- if (refImg.bytesBase64Encoded) {
3141
- return {
3142
- inlineData: {
3143
- mimeType: "image/png",
3144
- data: refImg.bytesBase64Encoded
3145
- }
3146
- };
3147
- } else if (refImg.gcsUri) {
3148
- return {
3149
- gcsUri: refImg.gcsUri
3150
- };
3151
- }
3152
- return refImg;
3153
- });
3154
- }
3155
- const parameters = {
3156
- sampleCount: options.n
3157
- };
3158
- if (options.aspectRatio) {
3159
- parameters.aspectRatio = options.aspectRatio;
3160
- }
3161
- if (options.resolution) {
3162
- const resolutionMap = {
3163
- "1280x720": "720p",
3164
- "1920x1080": "1080p",
3165
- "3840x2160": "4k"
3166
- };
3167
- parameters.resolution = resolutionMap[options.resolution] || options.resolution;
3168
- }
3169
- if (options.duration) {
3170
- parameters.durationSeconds = options.duration;
3171
- }
3172
- if (options.seed) {
3173
- parameters.seed = options.seed;
3174
- }
3175
- if (googleOptions != null) {
3176
- const opts = googleOptions;
3177
- if (opts.personGeneration !== void 0 && opts.personGeneration !== null) {
3178
- parameters.personGeneration = opts.personGeneration;
3179
- }
3180
- if (opts.negativePrompt !== void 0 && opts.negativePrompt !== null) {
3181
- parameters.negativePrompt = opts.negativePrompt;
3182
- }
3183
- for (const [key, value] of Object.entries(opts)) {
3184
- if (![
3185
- "pollIntervalMs",
3186
- "pollTimeoutMs",
3187
- "personGeneration",
3188
- "negativePrompt",
3189
- "referenceImages"
3190
- ].includes(key)) {
3191
- parameters[key] = value;
3192
- }
3193
- }
3194
- }
3195
- const { value: operation } = await postJsonToApi4({
3196
- url: `${this.config.baseURL}/models/${this.modelId}:predictLongRunning`,
3197
- headers: combineHeaders5(
3198
- await resolve4(this.config.headers),
3199
- options.headers
3200
- ),
3201
- body: {
3202
- instances,
3203
- parameters
3204
- },
3205
- successfulResponseHandler: createJsonResponseHandler5(
3206
- googleOperationSchema
3207
- ),
3208
- failedResponseHandler: googleFailedResponseHandler,
3209
- abortSignal: options.abortSignal,
3210
- fetch: this.config.fetch
3211
- });
3212
- const operationName = operation.name;
3213
- if (!operationName) {
3214
- throw new AISDKError2({
3215
- name: "GOOGLE_VIDEO_GENERATION_ERROR",
3216
- message: "No operation name returned from API"
3217
- });
3218
- }
3219
- const pollIntervalMs = (_d = googleOptions == null ? void 0 : googleOptions.pollIntervalMs) != null ? _d : 1e4;
3220
- const pollTimeoutMs = (_e = googleOptions == null ? void 0 : googleOptions.pollTimeoutMs) != null ? _e : 6e5;
3221
- const startTime = Date.now();
3222
- let finalOperation = operation;
3223
- let responseHeaders;
3224
- while (!finalOperation.done) {
3225
- if (Date.now() - startTime > pollTimeoutMs) {
3226
- throw new AISDKError2({
3227
- name: "GOOGLE_VIDEO_GENERATION_TIMEOUT",
3228
- message: `Video generation timed out after ${pollTimeoutMs}ms`
3229
- });
3230
- }
3231
- await delay2(pollIntervalMs);
3232
- if ((_f = options.abortSignal) == null ? void 0 : _f.aborted) {
3233
- throw new AISDKError2({
3234
- name: "GOOGLE_VIDEO_GENERATION_ABORTED",
3235
- message: "Video generation request was aborted"
3236
- });
3237
- }
3238
- const { value: statusOperation, responseHeaders: pollHeaders } = await getFromApi2({
3239
- url: `${this.config.baseURL}/${operationName}`,
3240
- headers: combineHeaders5(
3241
- await resolve4(this.config.headers),
3242
- options.headers
3243
- ),
3244
- successfulResponseHandler: createJsonResponseHandler5(
3245
- googleOperationSchema
3246
- ),
3247
- failedResponseHandler: googleFailedResponseHandler,
3248
- abortSignal: options.abortSignal,
3249
- fetch: this.config.fetch
3250
- });
3251
- finalOperation = statusOperation;
3252
- responseHeaders = pollHeaders;
3253
- }
3254
- if (finalOperation.error) {
3255
- throw new AISDKError2({
3256
- name: "GOOGLE_VIDEO_GENERATION_FAILED",
3257
- message: `Video generation failed: ${finalOperation.error.message}`
3258
- });
3259
- }
3260
- const response = finalOperation.response;
3261
- if (!((_g = response == null ? void 0 : response.generateVideoResponse) == null ? void 0 : _g.generatedSamples) || response.generateVideoResponse.generatedSamples.length === 0) {
3262
- throw new AISDKError2({
3263
- name: "GOOGLE_VIDEO_GENERATION_ERROR",
3264
- message: `No videos in response. Response: ${JSON.stringify(finalOperation)}`
3265
- });
3266
- }
3267
- const videos = [];
3268
- const videoMetadata = [];
3269
- const resolvedHeaders = await resolve4(this.config.headers);
3270
- const apiKey = resolvedHeaders == null ? void 0 : resolvedHeaders["x-goog-api-key"];
3271
- for (const generatedSample of response.generateVideoResponse.generatedSamples) {
3272
- if ((_h = generatedSample.video) == null ? void 0 : _h.uri) {
3273
- const urlWithAuth = apiKey ? `${generatedSample.video.uri}${generatedSample.video.uri.includes("?") ? "&" : "?"}key=${apiKey}` : generatedSample.video.uri;
3274
- videos.push({
3275
- type: "url",
3276
- url: urlWithAuth,
3277
- mediaType: "video/mp4"
3278
- });
3279
- videoMetadata.push({
3280
- uri: generatedSample.video.uri
3281
- });
3282
- }
3283
- }
3284
- if (videos.length === 0) {
3285
- throw new AISDKError2({
3286
- name: "GOOGLE_VIDEO_GENERATION_ERROR",
3287
- message: "No valid videos in response"
3288
- });
3289
- }
3290
- return {
3291
- videos,
3292
- warnings,
3293
- response: {
3294
- timestamp: currentDate,
3295
- modelId: this.modelId,
3296
- headers: responseHeaders
3297
- },
3298
- providerMetadata: {
3299
- google: {
3300
- videos: videoMetadata
3301
- }
3302
- }
3303
- };
3304
- }
3305
- };
3306
- var googleOperationSchema = z15.object({
3307
- name: z15.string().nullish(),
3308
- done: z15.boolean().nullish(),
3309
- error: z15.object({
3310
- code: z15.number().nullish(),
3311
- message: z15.string(),
3312
- status: z15.string().nullish()
3313
- }).nullish(),
3314
- response: z15.object({
3315
- generateVideoResponse: z15.object({
3316
- generatedSamples: z15.array(
3317
- z15.object({
3318
- video: z15.object({
3319
- uri: z15.string().nullish()
3320
- }).nullish()
3321
- })
3322
- ).nullish()
3323
- }).nullish()
3324
- }).nullish()
3325
- });
3326
- var googleVideoModelOptionsSchema = lazySchema13(
3327
- () => zodSchema13(
3328
- z15.object({
3329
- pollIntervalMs: z15.number().positive().nullish(),
3330
- pollTimeoutMs: z15.number().positive().nullish(),
3331
- personGeneration: z15.enum(["dont_allow", "allow_adult", "allow_all"]).nullish(),
3332
- negativePrompt: z15.string().nullish(),
3333
- referenceImages: z15.array(
3334
- z15.object({
3335
- bytesBase64Encoded: z15.string().nullish(),
3336
- gcsUri: z15.string().nullish()
3337
- })
3338
- ).nullish()
3339
- }).passthrough()
3340
- )
3341
- );
3342
-
3343
- // src/google-provider.ts
3344
- function createGoogleGenerativeAI(options = {}) {
3345
- var _a, _b;
3346
- const baseURL = (_a = withoutTrailingSlash(options.baseURL)) != null ? _a : "https://generativelanguage.googleapis.com/v1beta";
3347
- const providerName = (_b = options.name) != null ? _b : "google.generative-ai";
3348
- const getHeaders = () => withUserAgentSuffix(
3349
- {
3350
- "x-goog-api-key": loadApiKey({
3351
- apiKey: options.apiKey,
3352
- environmentVariableName: "GOOGLE_GENERATIVE_AI_API_KEY",
3353
- description: "Google Generative AI"
3354
- }),
3355
- ...options.headers
3356
- },
3357
- `ai-sdk/google/${VERSION}`
3358
- );
3359
- const createChatModel = (modelId) => {
3360
- var _a2;
3361
- return new GoogleGenerativeAILanguageModel(modelId, {
3362
- provider: providerName,
3363
- baseURL,
3364
- headers: getHeaders,
3365
- generateId: (_a2 = options.generateId) != null ? _a2 : generateId2,
3366
- supportedUrls: () => ({
3367
- "*": [
3368
- // Google Generative Language "files" endpoint
3369
- // e.g. https://generativelanguage.googleapis.com/v1beta/files/...
3370
- new RegExp(`^${baseURL}/files/.*$`),
3371
- // YouTube URLs (public or unlisted videos)
3372
- new RegExp(
3373
- `^https://(?:www\\.)?youtube\\.com/watch\\?v=[\\w-]+(?:&[\\w=&.-]*)?$`
3374
- ),
3375
- new RegExp(`^https://youtu\\.be/[\\w-]+(?:\\?[\\w=&.-]*)?$`)
3376
- ]
3377
- }),
3378
- fetch: options.fetch
3379
- });
3380
- };
3381
- const createEmbeddingModel = (modelId) => new GoogleGenerativeAIEmbeddingModel(modelId, {
3382
- provider: providerName,
3383
- baseURL,
3384
- headers: getHeaders,
3385
- fetch: options.fetch
3386
- });
3387
- const createImageModel = (modelId, settings = {}) => new GoogleGenerativeAIImageModel(modelId, settings, {
3388
- provider: providerName,
3389
- baseURL,
3390
- headers: getHeaders,
3391
- fetch: options.fetch
3392
- });
3393
- const createFiles = () => new GoogleGenerativeAIFiles({
3394
- provider: providerName,
3395
- baseURL,
3396
- headers: getHeaders,
3397
- fetch: options.fetch
3398
- });
3399
- const createVideoModel = (modelId) => {
3400
- var _a2;
3401
- return new GoogleGenerativeAIVideoModel(modelId, {
3402
- provider: providerName,
3403
- baseURL,
3404
- headers: getHeaders,
3405
- fetch: options.fetch,
3406
- generateId: (_a2 = options.generateId) != null ? _a2 : generateId2
3407
- });
3408
- };
3409
- const provider = function(modelId) {
3410
- if (new.target) {
3411
- throw new Error(
3412
- "The Google Generative AI model function cannot be called with the new keyword."
3413
- );
3414
- }
3415
- return createChatModel(modelId);
3416
- };
3417
- provider.specificationVersion = "v4";
3418
- provider.languageModel = createChatModel;
3419
- provider.chat = createChatModel;
3420
- provider.generativeAI = createChatModel;
3421
- provider.embedding = createEmbeddingModel;
3422
- provider.embeddingModel = createEmbeddingModel;
3423
- provider.textEmbedding = createEmbeddingModel;
3424
- provider.textEmbeddingModel = createEmbeddingModel;
3425
- provider.image = createImageModel;
3426
- provider.imageModel = createImageModel;
3427
- provider.video = createVideoModel;
3428
- provider.videoModel = createVideoModel;
3429
- provider.files = createFiles;
3430
- provider.tools = googleTools;
3431
- return provider;
3432
- }
3433
- var google = createGoogleGenerativeAI();
3434
- export {
3435
- VERSION,
3436
- createGoogleGenerativeAI,
3437
- google
3438
- };
3439
- //# sourceMappingURL=index.mjs.map