@ai-sdk/google 4.0.0-beta.4 → 4.0.0-beta.40

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