@ai-sdk/google 4.0.0-beta.7 → 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 +614 -5
  2. package/README.md +6 -4
  3. package/dist/index.d.ts +301 -50
  4. package/dist/index.js +5410 -639
  5. package/dist/index.js.map +1 -1
  6. package/dist/internal/index.d.ts +100 -26
  7. package/dist/internal/index.js +1653 -451
  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} +701 -219
  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 -376
  65. package/dist/index.mjs +0 -2517
  66. package/dist/index.mjs.map +0 -1
  67. package/dist/internal/index.d.mts +0 -284
  68. package/dist/internal/index.mjs +0 -1706
  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 -38
package/dist/index.mjs DELETED
@@ -1,2517 +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.7" : "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;
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
- }
1183
- },
1184
- request: { body: args },
1185
- response: {
1186
- // TODO timestamp, model id, id
1187
- headers: responseHeaders,
1188
- body: rawResponse
1189
- }
1190
- };
1191
- }
1192
- async doStream(options) {
1193
- const { args, warnings, providerOptionsName } = await this.getArgs(options);
1194
- const headers = combineHeaders2(
1195
- await resolve2(this.config.headers),
1196
- options.headers
1197
- );
1198
- const { responseHeaders, value: response } = await postJsonToApi2({
1199
- url: `${this.config.baseURL}/${getModelPath(
1200
- this.modelId
1201
- )}:streamGenerateContent?alt=sse`,
1202
- headers,
1203
- body: args,
1204
- failedResponseHandler: googleFailedResponseHandler,
1205
- successfulResponseHandler: createEventSourceResponseHandler(chunkSchema),
1206
- abortSignal: options.abortSignal,
1207
- fetch: this.config.fetch
1208
- });
1209
- let finishReason = {
1210
- unified: "other",
1211
- raw: void 0
1212
- };
1213
- let usage = void 0;
1214
- let providerMetadata = void 0;
1215
- let lastGroundingMetadata = null;
1216
- let lastUrlContextMetadata = null;
1217
- const generateId3 = this.config.generateId;
1218
- let hasToolCalls = false;
1219
- let currentTextBlockId = null;
1220
- let currentReasoningBlockId = null;
1221
- let blockCounter = 0;
1222
- const emittedSourceUrls = /* @__PURE__ */ new Set();
1223
- let lastCodeExecutionToolCallId;
1224
- return {
1225
- stream: response.pipeThrough(
1226
- new TransformStream({
1227
- start(controller) {
1228
- controller.enqueue({ type: "stream-start", warnings });
1229
- },
1230
- transform(chunk, controller) {
1231
- var _a, _b, _c, _d, _e, _f;
1232
- if (options.includeRawChunks) {
1233
- controller.enqueue({ type: "raw", rawValue: chunk.rawValue });
1234
- }
1235
- if (!chunk.success) {
1236
- controller.enqueue({ type: "error", error: chunk.error });
1237
- return;
1238
- }
1239
- const value = chunk.value;
1240
- const usageMetadata = value.usageMetadata;
1241
- if (usageMetadata != null) {
1242
- usage = usageMetadata;
1243
- }
1244
- const candidate = (_a = value.candidates) == null ? void 0 : _a[0];
1245
- if (candidate == null) {
1246
- return;
1247
- }
1248
- const content = candidate.content;
1249
- if (candidate.groundingMetadata != null) {
1250
- lastGroundingMetadata = candidate.groundingMetadata;
1251
- }
1252
- if (candidate.urlContextMetadata != null) {
1253
- lastUrlContextMetadata = candidate.urlContextMetadata;
1254
- }
1255
- const sources = extractSources({
1256
- groundingMetadata: candidate.groundingMetadata,
1257
- generateId: generateId3
1258
- });
1259
- if (sources != null) {
1260
- for (const source of sources) {
1261
- if (source.sourceType === "url" && !emittedSourceUrls.has(source.url)) {
1262
- emittedSourceUrls.add(source.url);
1263
- controller.enqueue(source);
1264
- }
1265
- }
1266
- }
1267
- if (content != null) {
1268
- const parts = (_b = content.parts) != null ? _b : [];
1269
- for (const part of parts) {
1270
- if ("executableCode" in part && ((_c = part.executableCode) == null ? void 0 : _c.code)) {
1271
- const toolCallId = generateId3();
1272
- lastCodeExecutionToolCallId = toolCallId;
1273
- controller.enqueue({
1274
- type: "tool-call",
1275
- toolCallId,
1276
- toolName: "code_execution",
1277
- input: JSON.stringify(part.executableCode),
1278
- providerExecuted: true
1279
- });
1280
- } else if ("codeExecutionResult" in part && part.codeExecutionResult) {
1281
- const toolCallId = lastCodeExecutionToolCallId;
1282
- if (toolCallId) {
1283
- controller.enqueue({
1284
- type: "tool-result",
1285
- toolCallId,
1286
- toolName: "code_execution",
1287
- result: {
1288
- outcome: part.codeExecutionResult.outcome,
1289
- output: (_d = part.codeExecutionResult.output) != null ? _d : ""
1290
- }
1291
- });
1292
- lastCodeExecutionToolCallId = void 0;
1293
- }
1294
- } else if ("text" in part && part.text != null) {
1295
- const thoughtSignatureMetadata = part.thoughtSignature ? {
1296
- [providerOptionsName]: {
1297
- thoughtSignature: part.thoughtSignature
1298
- }
1299
- } : void 0;
1300
- if (part.text.length === 0) {
1301
- if (thoughtSignatureMetadata != null && currentTextBlockId !== null) {
1302
- controller.enqueue({
1303
- type: "text-delta",
1304
- id: currentTextBlockId,
1305
- delta: "",
1306
- providerMetadata: thoughtSignatureMetadata
1307
- });
1308
- }
1309
- } else if (part.thought === true) {
1310
- if (currentTextBlockId !== null) {
1311
- controller.enqueue({
1312
- type: "text-end",
1313
- id: currentTextBlockId
1314
- });
1315
- currentTextBlockId = null;
1316
- }
1317
- if (currentReasoningBlockId === null) {
1318
- currentReasoningBlockId = String(blockCounter++);
1319
- controller.enqueue({
1320
- type: "reasoning-start",
1321
- id: currentReasoningBlockId,
1322
- providerMetadata: thoughtSignatureMetadata
1323
- });
1324
- }
1325
- controller.enqueue({
1326
- type: "reasoning-delta",
1327
- id: currentReasoningBlockId,
1328
- delta: part.text,
1329
- providerMetadata: thoughtSignatureMetadata
1330
- });
1331
- } else {
1332
- if (currentReasoningBlockId !== null) {
1333
- controller.enqueue({
1334
- type: "reasoning-end",
1335
- id: currentReasoningBlockId
1336
- });
1337
- currentReasoningBlockId = null;
1338
- }
1339
- if (currentTextBlockId === null) {
1340
- currentTextBlockId = String(blockCounter++);
1341
- controller.enqueue({
1342
- type: "text-start",
1343
- id: currentTextBlockId,
1344
- providerMetadata: thoughtSignatureMetadata
1345
- });
1346
- }
1347
- controller.enqueue({
1348
- type: "text-delta",
1349
- id: currentTextBlockId,
1350
- delta: part.text,
1351
- providerMetadata: thoughtSignatureMetadata
1352
- });
1353
- }
1354
- } else if ("inlineData" in part) {
1355
- if (currentTextBlockId !== null) {
1356
- controller.enqueue({
1357
- type: "text-end",
1358
- id: currentTextBlockId
1359
- });
1360
- currentTextBlockId = null;
1361
- }
1362
- if (currentReasoningBlockId !== null) {
1363
- controller.enqueue({
1364
- type: "reasoning-end",
1365
- id: currentReasoningBlockId
1366
- });
1367
- currentReasoningBlockId = null;
1368
- }
1369
- const hasThought = part.thought === true;
1370
- const hasThoughtSignature = !!part.thoughtSignature;
1371
- const fileMeta = hasThought || hasThoughtSignature ? {
1372
- [providerOptionsName]: {
1373
- ...hasThought ? { thought: true } : {},
1374
- ...hasThoughtSignature ? { thoughtSignature: part.thoughtSignature } : {}
1375
- }
1376
- } : void 0;
1377
- controller.enqueue({
1378
- type: "file",
1379
- mediaType: part.inlineData.mimeType,
1380
- data: part.inlineData.data,
1381
- providerMetadata: fileMeta
1382
- });
1383
- }
1384
- }
1385
- const toolCallDeltas = getToolCallsFromParts({
1386
- parts: content.parts,
1387
- generateId: generateId3,
1388
- providerOptionsName
1389
- });
1390
- if (toolCallDeltas != null) {
1391
- for (const toolCall of toolCallDeltas) {
1392
- controller.enqueue({
1393
- type: "tool-input-start",
1394
- id: toolCall.toolCallId,
1395
- toolName: toolCall.toolName,
1396
- providerMetadata: toolCall.providerMetadata
1397
- });
1398
- controller.enqueue({
1399
- type: "tool-input-delta",
1400
- id: toolCall.toolCallId,
1401
- delta: toolCall.args,
1402
- providerMetadata: toolCall.providerMetadata
1403
- });
1404
- controller.enqueue({
1405
- type: "tool-input-end",
1406
- id: toolCall.toolCallId,
1407
- providerMetadata: toolCall.providerMetadata
1408
- });
1409
- controller.enqueue({
1410
- type: "tool-call",
1411
- toolCallId: toolCall.toolCallId,
1412
- toolName: toolCall.toolName,
1413
- input: toolCall.args,
1414
- providerMetadata: toolCall.providerMetadata
1415
- });
1416
- hasToolCalls = true;
1417
- }
1418
- }
1419
- }
1420
- if (candidate.finishReason != null) {
1421
- finishReason = {
1422
- unified: mapGoogleGenerativeAIFinishReason({
1423
- finishReason: candidate.finishReason,
1424
- hasToolCalls
1425
- }),
1426
- raw: candidate.finishReason
1427
- };
1428
- providerMetadata = {
1429
- [providerOptionsName]: {
1430
- promptFeedback: (_e = value.promptFeedback) != null ? _e : null,
1431
- groundingMetadata: lastGroundingMetadata,
1432
- urlContextMetadata: lastUrlContextMetadata,
1433
- safetyRatings: (_f = candidate.safetyRatings) != null ? _f : null
1434
- }
1435
- };
1436
- if (usageMetadata != null) {
1437
- providerMetadata[providerOptionsName].usageMetadata = usageMetadata;
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
- safetyRatings: z5.array(getSafetyRatingSchema()).nullish(),
1699
- groundingMetadata: getGroundingMetadataSchema().nullish(),
1700
- urlContextMetadata: getUrlContextMetadataSchema().nullish()
1701
- })
1702
- ),
1703
- usageMetadata: usageSchema.nullish(),
1704
- promptFeedback: z5.object({
1705
- blockReason: z5.string().nullish(),
1706
- safetyRatings: z5.array(getSafetyRatingSchema()).nullish()
1707
- }).nullish()
1708
- })
1709
- )
1710
- );
1711
- var chunkSchema = lazySchema5(
1712
- () => zodSchema5(
1713
- z5.object({
1714
- candidates: z5.array(
1715
- z5.object({
1716
- content: getContentSchema().nullish(),
1717
- finishReason: z5.string().nullish(),
1718
- safetyRatings: z5.array(getSafetyRatingSchema()).nullish(),
1719
- groundingMetadata: getGroundingMetadataSchema().nullish(),
1720
- urlContextMetadata: getUrlContextMetadataSchema().nullish()
1721
- })
1722
- ).nullish(),
1723
- usageMetadata: usageSchema.nullish(),
1724
- promptFeedback: z5.object({
1725
- blockReason: z5.string().nullish(),
1726
- safetyRatings: z5.array(getSafetyRatingSchema()).nullish()
1727
- }).nullish()
1728
- })
1729
- )
1730
- );
1731
-
1732
- // src/tool/code-execution.ts
1733
- import { createProviderToolFactoryWithOutputSchema } from "@ai-sdk/provider-utils";
1734
- import { z as z6 } from "zod/v4";
1735
- var codeExecution = createProviderToolFactoryWithOutputSchema({
1736
- id: "google.code_execution",
1737
- inputSchema: z6.object({
1738
- language: z6.string().describe("The programming language of the code."),
1739
- code: z6.string().describe("The code to be executed.")
1740
- }),
1741
- outputSchema: z6.object({
1742
- outcome: z6.string().describe('The outcome of the execution (e.g., "OUTCOME_OK").'),
1743
- output: z6.string().describe("The output from the code execution.")
1744
- })
1745
- });
1746
-
1747
- // src/tool/enterprise-web-search.ts
1748
- import {
1749
- createProviderToolFactory,
1750
- lazySchema as lazySchema6,
1751
- zodSchema as zodSchema6
1752
- } from "@ai-sdk/provider-utils";
1753
- import { z as z7 } from "zod/v4";
1754
- var enterpriseWebSearch = createProviderToolFactory({
1755
- id: "google.enterprise_web_search",
1756
- inputSchema: lazySchema6(() => zodSchema6(z7.object({})))
1757
- });
1758
-
1759
- // src/tool/file-search.ts
1760
- import {
1761
- createProviderToolFactory as createProviderToolFactory2,
1762
- lazySchema as lazySchema7,
1763
- zodSchema as zodSchema7
1764
- } from "@ai-sdk/provider-utils";
1765
- import { z as z8 } from "zod/v4";
1766
- var fileSearchArgsBaseSchema = z8.object({
1767
- /** The names of the file_search_stores to retrieve from.
1768
- * Example: `fileSearchStores/my-file-search-store-123`
1769
- */
1770
- fileSearchStoreNames: z8.array(z8.string()).describe(
1771
- "The names of the file_search_stores to retrieve from. Example: `fileSearchStores/my-file-search-store-123`"
1772
- ),
1773
- /** The number of file search retrieval chunks to retrieve. */
1774
- topK: z8.number().int().positive().describe("The number of file search retrieval chunks to retrieve.").optional(),
1775
- /** Metadata filter to apply to the file search retrieval documents.
1776
- * See https://google.aip.dev/160 for the syntax of the filter expression.
1777
- */
1778
- metadataFilter: z8.string().describe(
1779
- "Metadata filter to apply to the file search retrieval documents. See https://google.aip.dev/160 for the syntax of the filter expression."
1780
- ).optional()
1781
- }).passthrough();
1782
- var fileSearchArgsSchema = lazySchema7(
1783
- () => zodSchema7(fileSearchArgsBaseSchema)
1784
- );
1785
- var fileSearch = createProviderToolFactory2({
1786
- id: "google.file_search",
1787
- inputSchema: fileSearchArgsSchema
1788
- });
1789
-
1790
- // src/tool/google-maps.ts
1791
- import {
1792
- createProviderToolFactory as createProviderToolFactory3,
1793
- lazySchema as lazySchema8,
1794
- zodSchema as zodSchema8
1795
- } from "@ai-sdk/provider-utils";
1796
- import { z as z9 } from "zod/v4";
1797
- var googleMaps = createProviderToolFactory3({
1798
- id: "google.google_maps",
1799
- inputSchema: lazySchema8(() => zodSchema8(z9.object({})))
1800
- });
1801
-
1802
- // src/tool/google-search.ts
1803
- import {
1804
- createProviderToolFactory as createProviderToolFactory4,
1805
- lazySchema as lazySchema9,
1806
- zodSchema as zodSchema9
1807
- } from "@ai-sdk/provider-utils";
1808
- import { z as z10 } from "zod/v4";
1809
- var googleSearchToolArgsBaseSchema = z10.object({
1810
- searchTypes: z10.object({
1811
- webSearch: z10.object({}).optional(),
1812
- imageSearch: z10.object({}).optional()
1813
- }).optional(),
1814
- timeRangeFilter: z10.object({
1815
- startTime: z10.string(),
1816
- endTime: z10.string()
1817
- }).optional()
1818
- }).passthrough();
1819
- var googleSearchToolArgsSchema = lazySchema9(
1820
- () => zodSchema9(googleSearchToolArgsBaseSchema)
1821
- );
1822
- var googleSearch = createProviderToolFactory4(
1823
- {
1824
- id: "google.google_search",
1825
- inputSchema: googleSearchToolArgsSchema
1826
- }
1827
- );
1828
-
1829
- // src/tool/url-context.ts
1830
- import {
1831
- createProviderToolFactory as createProviderToolFactory5,
1832
- lazySchema as lazySchema10,
1833
- zodSchema as zodSchema10
1834
- } from "@ai-sdk/provider-utils";
1835
- import { z as z11 } from "zod/v4";
1836
- var urlContext = createProviderToolFactory5({
1837
- id: "google.url_context",
1838
- inputSchema: lazySchema10(() => zodSchema10(z11.object({})))
1839
- });
1840
-
1841
- // src/tool/vertex-rag-store.ts
1842
- import { createProviderToolFactory as createProviderToolFactory6 } from "@ai-sdk/provider-utils";
1843
- import { z as z12 } from "zod/v4";
1844
- var vertexRagStore = createProviderToolFactory6({
1845
- id: "google.vertex_rag_store",
1846
- inputSchema: z12.object({
1847
- ragCorpus: z12.string(),
1848
- topK: z12.number().optional()
1849
- })
1850
- });
1851
-
1852
- // src/google-tools.ts
1853
- var googleTools = {
1854
- /**
1855
- * Creates a Google search tool that gives Google direct access to real-time web content.
1856
- * Must have name "google_search".
1857
- */
1858
- googleSearch,
1859
- /**
1860
- * Creates an Enterprise Web Search tool for grounding responses using a compliance-focused web index.
1861
- * Designed for highly-regulated industries (finance, healthcare, public sector).
1862
- * Does not log customer data and supports VPC service controls.
1863
- * Must have name "enterprise_web_search".
1864
- *
1865
- * @note Only available on Vertex AI. Requires Gemini 2.0 or newer.
1866
- *
1867
- * @see https://cloud.google.com/vertex-ai/generative-ai/docs/grounding/web-grounding-enterprise
1868
- */
1869
- enterpriseWebSearch,
1870
- /**
1871
- * Creates a Google Maps grounding tool that gives the model access to Google Maps data.
1872
- * Must have name "google_maps".
1873
- *
1874
- * @see https://ai.google.dev/gemini-api/docs/maps-grounding
1875
- * @see https://cloud.google.com/vertex-ai/generative-ai/docs/grounding/grounding-with-google-maps
1876
- */
1877
- googleMaps,
1878
- /**
1879
- * Creates a URL context tool that gives Google direct access to real-time web content.
1880
- * Must have name "url_context".
1881
- */
1882
- urlContext,
1883
- /**
1884
- * Enables Retrieval Augmented Generation (RAG) via the Gemini File Search tool.
1885
- * Must have name "file_search".
1886
- *
1887
- * @param fileSearchStoreNames - Fully-qualified File Search store resource names.
1888
- * @param metadataFilter - Optional filter expression to restrict the files that can be retrieved.
1889
- * @param topK - Optional result limit for the number of chunks returned from File Search.
1890
- *
1891
- * @see https://ai.google.dev/gemini-api/docs/file-search
1892
- */
1893
- fileSearch,
1894
- /**
1895
- * A tool that enables the model to generate and run Python code.
1896
- * Must have name "code_execution".
1897
- *
1898
- * @note Ensure the selected model supports Code Execution.
1899
- * Multi-tool usage with the code execution tool is typically compatible with Gemini >=2 models.
1900
- *
1901
- * @see https://ai.google.dev/gemini-api/docs/code-execution (Google AI)
1902
- * @see https://cloud.google.com/vertex-ai/generative-ai/docs/model-reference/code-execution-api (Vertex AI)
1903
- */
1904
- codeExecution,
1905
- /**
1906
- * Creates a Vertex RAG Store tool that enables the model to perform RAG searches against a Vertex RAG Store.
1907
- * Must have name "vertex_rag_store".
1908
- */
1909
- vertexRagStore
1910
- };
1911
-
1912
- // src/google-generative-ai-image-model.ts
1913
- import {
1914
- combineHeaders as combineHeaders3,
1915
- convertToBase64 as convertToBase642,
1916
- createJsonResponseHandler as createJsonResponseHandler3,
1917
- generateId as defaultGenerateId,
1918
- lazySchema as lazySchema11,
1919
- parseProviderOptions as parseProviderOptions3,
1920
- postJsonToApi as postJsonToApi3,
1921
- resolve as resolve3,
1922
- zodSchema as zodSchema11
1923
- } from "@ai-sdk/provider-utils";
1924
- import { z as z13 } from "zod/v4";
1925
- var GoogleGenerativeAIImageModel = class {
1926
- constructor(modelId, settings, config) {
1927
- this.modelId = modelId;
1928
- this.settings = settings;
1929
- this.config = config;
1930
- this.specificationVersion = "v3";
1931
- }
1932
- get maxImagesPerCall() {
1933
- if (this.settings.maxImagesPerCall != null) {
1934
- return this.settings.maxImagesPerCall;
1935
- }
1936
- if (isGeminiModel(this.modelId)) {
1937
- return 10;
1938
- }
1939
- return 4;
1940
- }
1941
- get provider() {
1942
- return this.config.provider;
1943
- }
1944
- async doGenerate(options) {
1945
- if (isGeminiModel(this.modelId)) {
1946
- return this.doGenerateGemini(options);
1947
- }
1948
- return this.doGenerateImagen(options);
1949
- }
1950
- async doGenerateImagen(options) {
1951
- var _a, _b, _c;
1952
- const {
1953
- prompt,
1954
- n = 1,
1955
- size,
1956
- aspectRatio = "1:1",
1957
- seed,
1958
- providerOptions,
1959
- headers,
1960
- abortSignal,
1961
- files,
1962
- mask
1963
- } = options;
1964
- const warnings = [];
1965
- if (files != null && files.length > 0) {
1966
- throw new Error(
1967
- "Google Generative AI does not support image editing with Imagen models. Use Google Vertex AI (@ai-sdk/google-vertex) for image editing capabilities."
1968
- );
1969
- }
1970
- if (mask != null) {
1971
- throw new Error(
1972
- "Google Generative AI does not support image editing with masks. Use Google Vertex AI (@ai-sdk/google-vertex) for image editing capabilities."
1973
- );
1974
- }
1975
- if (size != null) {
1976
- warnings.push({
1977
- type: "unsupported",
1978
- feature: "size",
1979
- details: "This model does not support the `size` option. Use `aspectRatio` instead."
1980
- });
1981
- }
1982
- if (seed != null) {
1983
- warnings.push({
1984
- type: "unsupported",
1985
- feature: "seed",
1986
- details: "This model does not support the `seed` option through this provider."
1987
- });
1988
- }
1989
- const googleOptions = await parseProviderOptions3({
1990
- provider: "google",
1991
- providerOptions,
1992
- schema: googleImageModelOptionsSchema
1993
- });
1994
- const currentDate = (_c = (_b = (_a = this.config._internal) == null ? void 0 : _a.currentDate) == null ? void 0 : _b.call(_a)) != null ? _c : /* @__PURE__ */ new Date();
1995
- const parameters = {
1996
- sampleCount: n
1997
- };
1998
- if (aspectRatio != null) {
1999
- parameters.aspectRatio = aspectRatio;
2000
- }
2001
- if (googleOptions) {
2002
- Object.assign(parameters, googleOptions);
2003
- }
2004
- const body = {
2005
- instances: [{ prompt }],
2006
- parameters
2007
- };
2008
- const { responseHeaders, value: response } = await postJsonToApi3({
2009
- url: `${this.config.baseURL}/models/${this.modelId}:predict`,
2010
- headers: combineHeaders3(await resolve3(this.config.headers), headers),
2011
- body,
2012
- failedResponseHandler: googleFailedResponseHandler,
2013
- successfulResponseHandler: createJsonResponseHandler3(
2014
- googleImageResponseSchema
2015
- ),
2016
- abortSignal,
2017
- fetch: this.config.fetch
2018
- });
2019
- return {
2020
- images: response.predictions.map(
2021
- (p) => p.bytesBase64Encoded
2022
- ),
2023
- warnings,
2024
- providerMetadata: {
2025
- google: {
2026
- images: response.predictions.map(() => ({
2027
- // Add any prediction-specific metadata here
2028
- }))
2029
- }
2030
- },
2031
- response: {
2032
- timestamp: currentDate,
2033
- modelId: this.modelId,
2034
- headers: responseHeaders
2035
- }
2036
- };
2037
- }
2038
- async doGenerateGemini(options) {
2039
- var _a, _b, _c, _d, _e, _f, _g, _h, _i;
2040
- const {
2041
- prompt,
2042
- n,
2043
- size,
2044
- aspectRatio,
2045
- seed,
2046
- providerOptions,
2047
- headers,
2048
- abortSignal,
2049
- files,
2050
- mask
2051
- } = options;
2052
- const warnings = [];
2053
- if (mask != null) {
2054
- throw new Error(
2055
- "Gemini image models do not support mask-based image editing."
2056
- );
2057
- }
2058
- if (n != null && n > 1) {
2059
- throw new Error(
2060
- "Gemini image models do not support generating a set number of images per call. Use n=1 or omit the n parameter."
2061
- );
2062
- }
2063
- if (size != null) {
2064
- warnings.push({
2065
- type: "unsupported",
2066
- feature: "size",
2067
- details: "This model does not support the `size` option. Use `aspectRatio` instead."
2068
- });
2069
- }
2070
- const userContent = [];
2071
- if (prompt != null) {
2072
- userContent.push({ type: "text", text: prompt });
2073
- }
2074
- if (files != null && files.length > 0) {
2075
- for (const file of files) {
2076
- if (file.type === "url") {
2077
- userContent.push({
2078
- type: "file",
2079
- data: new URL(file.url),
2080
- mediaType: "image/*"
2081
- });
2082
- } else {
2083
- userContent.push({
2084
- type: "file",
2085
- data: typeof file.data === "string" ? file.data : new Uint8Array(file.data),
2086
- mediaType: file.mediaType
2087
- });
2088
- }
2089
- }
2090
- }
2091
- const languageModelPrompt = [
2092
- { role: "user", content: userContent }
2093
- ];
2094
- const languageModel = new GoogleGenerativeAILanguageModel(this.modelId, {
2095
- provider: this.config.provider,
2096
- baseURL: this.config.baseURL,
2097
- headers: (_a = this.config.headers) != null ? _a : {},
2098
- fetch: this.config.fetch,
2099
- generateId: (_b = this.config.generateId) != null ? _b : defaultGenerateId
2100
- });
2101
- const result = await languageModel.doGenerate({
2102
- prompt: languageModelPrompt,
2103
- seed,
2104
- providerOptions: {
2105
- google: {
2106
- responseModalities: ["IMAGE"],
2107
- imageConfig: aspectRatio ? {
2108
- aspectRatio
2109
- } : void 0,
2110
- ...(_c = providerOptions == null ? void 0 : providerOptions.google) != null ? _c : {}
2111
- }
2112
- },
2113
- headers,
2114
- abortSignal
2115
- });
2116
- const currentDate = (_f = (_e = (_d = this.config._internal) == null ? void 0 : _d.currentDate) == null ? void 0 : _e.call(_d)) != null ? _f : /* @__PURE__ */ new Date();
2117
- const images = [];
2118
- for (const part of result.content) {
2119
- if (part.type === "file" && part.mediaType.startsWith("image/")) {
2120
- images.push(convertToBase642(part.data));
2121
- }
2122
- }
2123
- return {
2124
- images,
2125
- warnings,
2126
- providerMetadata: {
2127
- google: {
2128
- images: images.map(() => ({}))
2129
- }
2130
- },
2131
- response: {
2132
- timestamp: currentDate,
2133
- modelId: this.modelId,
2134
- headers: (_g = result.response) == null ? void 0 : _g.headers
2135
- },
2136
- usage: result.usage ? {
2137
- inputTokens: result.usage.inputTokens.total,
2138
- outputTokens: result.usage.outputTokens.total,
2139
- totalTokens: ((_h = result.usage.inputTokens.total) != null ? _h : 0) + ((_i = result.usage.outputTokens.total) != null ? _i : 0)
2140
- } : void 0
2141
- };
2142
- }
2143
- };
2144
- function isGeminiModel(modelId) {
2145
- return modelId.startsWith("gemini-");
2146
- }
2147
- var googleImageResponseSchema = lazySchema11(
2148
- () => zodSchema11(
2149
- z13.object({
2150
- predictions: z13.array(z13.object({ bytesBase64Encoded: z13.string() })).default([])
2151
- })
2152
- )
2153
- );
2154
- var googleImageModelOptionsSchema = lazySchema11(
2155
- () => zodSchema11(
2156
- z13.object({
2157
- personGeneration: z13.enum(["dont_allow", "allow_adult", "allow_all"]).nullish(),
2158
- aspectRatio: z13.enum(["1:1", "3:4", "4:3", "9:16", "16:9"]).nullish()
2159
- })
2160
- )
2161
- );
2162
-
2163
- // src/google-generative-ai-video-model.ts
2164
- import {
2165
- AISDKError
2166
- } from "@ai-sdk/provider";
2167
- import {
2168
- combineHeaders as combineHeaders4,
2169
- convertUint8ArrayToBase64,
2170
- createJsonResponseHandler as createJsonResponseHandler4,
2171
- delay,
2172
- getFromApi,
2173
- lazySchema as lazySchema12,
2174
- parseProviderOptions as parseProviderOptions4,
2175
- postJsonToApi as postJsonToApi4,
2176
- resolve as resolve4,
2177
- zodSchema as zodSchema12
2178
- } from "@ai-sdk/provider-utils";
2179
- import { z as z14 } from "zod/v4";
2180
- var GoogleGenerativeAIVideoModel = class {
2181
- constructor(modelId, config) {
2182
- this.modelId = modelId;
2183
- this.config = config;
2184
- this.specificationVersion = "v3";
2185
- }
2186
- get provider() {
2187
- return this.config.provider;
2188
- }
2189
- get maxVideosPerCall() {
2190
- return 4;
2191
- }
2192
- async doGenerate(options) {
2193
- var _a, _b, _c, _d, _e, _f, _g, _h;
2194
- const currentDate = (_c = (_b = (_a = this.config._internal) == null ? void 0 : _a.currentDate) == null ? void 0 : _b.call(_a)) != null ? _c : /* @__PURE__ */ new Date();
2195
- const warnings = [];
2196
- const googleOptions = await parseProviderOptions4({
2197
- provider: "google",
2198
- providerOptions: options.providerOptions,
2199
- schema: googleVideoModelOptionsSchema
2200
- });
2201
- const instances = [{}];
2202
- const instance = instances[0];
2203
- if (options.prompt != null) {
2204
- instance.prompt = options.prompt;
2205
- }
2206
- if (options.image != null) {
2207
- if (options.image.type === "url") {
2208
- warnings.push({
2209
- type: "unsupported",
2210
- feature: "URL-based image input",
2211
- details: "Google Generative AI video models require base64-encoded images. URL will be ignored."
2212
- });
2213
- } else {
2214
- const base64Data = typeof options.image.data === "string" ? options.image.data : convertUint8ArrayToBase64(options.image.data);
2215
- instance.image = {
2216
- inlineData: {
2217
- mimeType: options.image.mediaType || "image/png",
2218
- data: base64Data
2219
- }
2220
- };
2221
- }
2222
- }
2223
- if ((googleOptions == null ? void 0 : googleOptions.referenceImages) != null) {
2224
- instance.referenceImages = googleOptions.referenceImages.map((refImg) => {
2225
- if (refImg.bytesBase64Encoded) {
2226
- return {
2227
- inlineData: {
2228
- mimeType: "image/png",
2229
- data: refImg.bytesBase64Encoded
2230
- }
2231
- };
2232
- } else if (refImg.gcsUri) {
2233
- return {
2234
- gcsUri: refImg.gcsUri
2235
- };
2236
- }
2237
- return refImg;
2238
- });
2239
- }
2240
- const parameters = {
2241
- sampleCount: options.n
2242
- };
2243
- if (options.aspectRatio) {
2244
- parameters.aspectRatio = options.aspectRatio;
2245
- }
2246
- if (options.resolution) {
2247
- const resolutionMap = {
2248
- "1280x720": "720p",
2249
- "1920x1080": "1080p",
2250
- "3840x2160": "4k"
2251
- };
2252
- parameters.resolution = resolutionMap[options.resolution] || options.resolution;
2253
- }
2254
- if (options.duration) {
2255
- parameters.durationSeconds = options.duration;
2256
- }
2257
- if (options.seed) {
2258
- parameters.seed = options.seed;
2259
- }
2260
- if (googleOptions != null) {
2261
- const opts = googleOptions;
2262
- if (opts.personGeneration !== void 0 && opts.personGeneration !== null) {
2263
- parameters.personGeneration = opts.personGeneration;
2264
- }
2265
- if (opts.negativePrompt !== void 0 && opts.negativePrompt !== null) {
2266
- parameters.negativePrompt = opts.negativePrompt;
2267
- }
2268
- for (const [key, value] of Object.entries(opts)) {
2269
- if (![
2270
- "pollIntervalMs",
2271
- "pollTimeoutMs",
2272
- "personGeneration",
2273
- "negativePrompt",
2274
- "referenceImages"
2275
- ].includes(key)) {
2276
- parameters[key] = value;
2277
- }
2278
- }
2279
- }
2280
- const { value: operation } = await postJsonToApi4({
2281
- url: `${this.config.baseURL}/models/${this.modelId}:predictLongRunning`,
2282
- headers: combineHeaders4(
2283
- await resolve4(this.config.headers),
2284
- options.headers
2285
- ),
2286
- body: {
2287
- instances,
2288
- parameters
2289
- },
2290
- successfulResponseHandler: createJsonResponseHandler4(
2291
- googleOperationSchema
2292
- ),
2293
- failedResponseHandler: googleFailedResponseHandler,
2294
- abortSignal: options.abortSignal,
2295
- fetch: this.config.fetch
2296
- });
2297
- const operationName = operation.name;
2298
- if (!operationName) {
2299
- throw new AISDKError({
2300
- name: "GOOGLE_VIDEO_GENERATION_ERROR",
2301
- message: "No operation name returned from API"
2302
- });
2303
- }
2304
- const pollIntervalMs = (_d = googleOptions == null ? void 0 : googleOptions.pollIntervalMs) != null ? _d : 1e4;
2305
- const pollTimeoutMs = (_e = googleOptions == null ? void 0 : googleOptions.pollTimeoutMs) != null ? _e : 6e5;
2306
- const startTime = Date.now();
2307
- let finalOperation = operation;
2308
- let responseHeaders;
2309
- while (!finalOperation.done) {
2310
- if (Date.now() - startTime > pollTimeoutMs) {
2311
- throw new AISDKError({
2312
- name: "GOOGLE_VIDEO_GENERATION_TIMEOUT",
2313
- message: `Video generation timed out after ${pollTimeoutMs}ms`
2314
- });
2315
- }
2316
- await delay(pollIntervalMs);
2317
- if ((_f = options.abortSignal) == null ? void 0 : _f.aborted) {
2318
- throw new AISDKError({
2319
- name: "GOOGLE_VIDEO_GENERATION_ABORTED",
2320
- message: "Video generation request was aborted"
2321
- });
2322
- }
2323
- const { value: statusOperation, responseHeaders: pollHeaders } = await getFromApi({
2324
- url: `${this.config.baseURL}/${operationName}`,
2325
- headers: combineHeaders4(
2326
- await resolve4(this.config.headers),
2327
- options.headers
2328
- ),
2329
- successfulResponseHandler: createJsonResponseHandler4(
2330
- googleOperationSchema
2331
- ),
2332
- failedResponseHandler: googleFailedResponseHandler,
2333
- abortSignal: options.abortSignal,
2334
- fetch: this.config.fetch
2335
- });
2336
- finalOperation = statusOperation;
2337
- responseHeaders = pollHeaders;
2338
- }
2339
- if (finalOperation.error) {
2340
- throw new AISDKError({
2341
- name: "GOOGLE_VIDEO_GENERATION_FAILED",
2342
- message: `Video generation failed: ${finalOperation.error.message}`
2343
- });
2344
- }
2345
- const response = finalOperation.response;
2346
- if (!((_g = response == null ? void 0 : response.generateVideoResponse) == null ? void 0 : _g.generatedSamples) || response.generateVideoResponse.generatedSamples.length === 0) {
2347
- throw new AISDKError({
2348
- name: "GOOGLE_VIDEO_GENERATION_ERROR",
2349
- message: `No videos in response. Response: ${JSON.stringify(finalOperation)}`
2350
- });
2351
- }
2352
- const videos = [];
2353
- const videoMetadata = [];
2354
- const resolvedHeaders = await resolve4(this.config.headers);
2355
- const apiKey = resolvedHeaders == null ? void 0 : resolvedHeaders["x-goog-api-key"];
2356
- for (const generatedSample of response.generateVideoResponse.generatedSamples) {
2357
- if ((_h = generatedSample.video) == null ? void 0 : _h.uri) {
2358
- const urlWithAuth = apiKey ? `${generatedSample.video.uri}${generatedSample.video.uri.includes("?") ? "&" : "?"}key=${apiKey}` : generatedSample.video.uri;
2359
- videos.push({
2360
- type: "url",
2361
- url: urlWithAuth,
2362
- mediaType: "video/mp4"
2363
- });
2364
- videoMetadata.push({
2365
- uri: generatedSample.video.uri
2366
- });
2367
- }
2368
- }
2369
- if (videos.length === 0) {
2370
- throw new AISDKError({
2371
- name: "GOOGLE_VIDEO_GENERATION_ERROR",
2372
- message: "No valid videos in response"
2373
- });
2374
- }
2375
- return {
2376
- videos,
2377
- warnings,
2378
- response: {
2379
- timestamp: currentDate,
2380
- modelId: this.modelId,
2381
- headers: responseHeaders
2382
- },
2383
- providerMetadata: {
2384
- google: {
2385
- videos: videoMetadata
2386
- }
2387
- }
2388
- };
2389
- }
2390
- };
2391
- var googleOperationSchema = z14.object({
2392
- name: z14.string().nullish(),
2393
- done: z14.boolean().nullish(),
2394
- error: z14.object({
2395
- code: z14.number().nullish(),
2396
- message: z14.string(),
2397
- status: z14.string().nullish()
2398
- }).nullish(),
2399
- response: z14.object({
2400
- generateVideoResponse: z14.object({
2401
- generatedSamples: z14.array(
2402
- z14.object({
2403
- video: z14.object({
2404
- uri: z14.string().nullish()
2405
- }).nullish()
2406
- })
2407
- ).nullish()
2408
- }).nullish()
2409
- }).nullish()
2410
- });
2411
- var googleVideoModelOptionsSchema = lazySchema12(
2412
- () => zodSchema12(
2413
- z14.object({
2414
- pollIntervalMs: z14.number().positive().nullish(),
2415
- pollTimeoutMs: z14.number().positive().nullish(),
2416
- personGeneration: z14.enum(["dont_allow", "allow_adult", "allow_all"]).nullish(),
2417
- negativePrompt: z14.string().nullish(),
2418
- referenceImages: z14.array(
2419
- z14.object({
2420
- bytesBase64Encoded: z14.string().nullish(),
2421
- gcsUri: z14.string().nullish()
2422
- })
2423
- ).nullish()
2424
- }).passthrough()
2425
- )
2426
- );
2427
-
2428
- // src/google-provider.ts
2429
- function createGoogleGenerativeAI(options = {}) {
2430
- var _a, _b;
2431
- const baseURL = (_a = withoutTrailingSlash(options.baseURL)) != null ? _a : "https://generativelanguage.googleapis.com/v1beta";
2432
- const providerName = (_b = options.name) != null ? _b : "google.generative-ai";
2433
- const getHeaders = () => withUserAgentSuffix(
2434
- {
2435
- "x-goog-api-key": loadApiKey({
2436
- apiKey: options.apiKey,
2437
- environmentVariableName: "GOOGLE_GENERATIVE_AI_API_KEY",
2438
- description: "Google Generative AI"
2439
- }),
2440
- ...options.headers
2441
- },
2442
- `ai-sdk/google/${VERSION}`
2443
- );
2444
- const createChatModel = (modelId) => {
2445
- var _a2;
2446
- return new GoogleGenerativeAILanguageModel(modelId, {
2447
- provider: providerName,
2448
- baseURL,
2449
- headers: getHeaders,
2450
- generateId: (_a2 = options.generateId) != null ? _a2 : generateId2,
2451
- supportedUrls: () => ({
2452
- "*": [
2453
- // Google Generative Language "files" endpoint
2454
- // e.g. https://generativelanguage.googleapis.com/v1beta/files/...
2455
- new RegExp(`^${baseURL}/files/.*$`),
2456
- // YouTube URLs (public or unlisted videos)
2457
- new RegExp(
2458
- `^https://(?:www\\.)?youtube\\.com/watch\\?v=[\\w-]+(?:&[\\w=&.-]*)?$`
2459
- ),
2460
- new RegExp(`^https://youtu\\.be/[\\w-]+(?:\\?[\\w=&.-]*)?$`)
2461
- ]
2462
- }),
2463
- fetch: options.fetch
2464
- });
2465
- };
2466
- const createEmbeddingModel = (modelId) => new GoogleGenerativeAIEmbeddingModel(modelId, {
2467
- provider: providerName,
2468
- baseURL,
2469
- headers: getHeaders,
2470
- fetch: options.fetch
2471
- });
2472
- const createImageModel = (modelId, settings = {}) => new GoogleGenerativeAIImageModel(modelId, settings, {
2473
- provider: providerName,
2474
- baseURL,
2475
- headers: getHeaders,
2476
- fetch: options.fetch
2477
- });
2478
- const createVideoModel = (modelId) => {
2479
- var _a2;
2480
- return new GoogleGenerativeAIVideoModel(modelId, {
2481
- provider: providerName,
2482
- baseURL,
2483
- headers: getHeaders,
2484
- fetch: options.fetch,
2485
- generateId: (_a2 = options.generateId) != null ? _a2 : generateId2
2486
- });
2487
- };
2488
- const provider = function(modelId) {
2489
- if (new.target) {
2490
- throw new Error(
2491
- "The Google Generative AI model function cannot be called with the new keyword."
2492
- );
2493
- }
2494
- return createChatModel(modelId);
2495
- };
2496
- provider.specificationVersion = "v3";
2497
- provider.languageModel = createChatModel;
2498
- provider.chat = createChatModel;
2499
- provider.generativeAI = createChatModel;
2500
- provider.embedding = createEmbeddingModel;
2501
- provider.embeddingModel = createEmbeddingModel;
2502
- provider.textEmbedding = createEmbeddingModel;
2503
- provider.textEmbeddingModel = createEmbeddingModel;
2504
- provider.image = createImageModel;
2505
- provider.imageModel = createImageModel;
2506
- provider.video = createVideoModel;
2507
- provider.videoModel = createVideoModel;
2508
- provider.tools = googleTools;
2509
- return provider;
2510
- }
2511
- var google = createGoogleGenerativeAI();
2512
- export {
2513
- VERSION,
2514
- createGoogleGenerativeAI,
2515
- google
2516
- };
2517
- //# sourceMappingURL=index.mjs.map