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