@ai-sdk/google 4.0.0-beta.8 → 4.0.0-beta.82

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