@depup/ai-sdk__google 3.0.43-depup.0

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