@snap-agent/core 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,1825 @@
1
+ import {
2
+ TooManyEmbeddingValuesForCallError,
3
+ UnsupportedFunctionalityError,
4
+ combineHeaders,
5
+ convertToBase64,
6
+ createEventSourceResponseHandler,
7
+ createJsonErrorResponseHandler,
8
+ createJsonResponseHandler,
9
+ createProviderDefinedToolFactory,
10
+ createProviderDefinedToolFactoryWithOutputSchema,
11
+ generateId,
12
+ lazySchema,
13
+ loadApiKey,
14
+ parseProviderOptions,
15
+ postJsonToApi,
16
+ resolve,
17
+ withUserAgentSuffix,
18
+ withoutTrailingSlash,
19
+ zodSchema
20
+ } from "./chunk-V4TPAVOY.mjs";
21
+
22
+ // node_modules/.pnpm/@ai-sdk+google@2.0.51_zod@3.25.76/node_modules/@ai-sdk/google/dist/index.mjs
23
+ import { z as z3 } from "zod/v4";
24
+ import { z } from "zod/v4";
25
+ import { z as z2 } from "zod/v4";
26
+ import { z as z5 } from "zod/v4";
27
+ import { z as z4 } from "zod/v4";
28
+ import { z as z6 } from "zod/v4";
29
+ import { z as z7 } from "zod/v4";
30
+ import { z as z8 } from "zod/v4";
31
+ import { z as z9 } from "zod/v4";
32
+ import { z as z10 } from "zod/v4";
33
+ import { z as z11 } from "zod/v4";
34
+ import { z as z12 } from "zod/v4";
35
+ import { z as z13 } from "zod/v4";
36
+ var VERSION = true ? "2.0.51" : "0.0.0-test";
37
+ var googleErrorDataSchema = lazySchema(
38
+ () => zodSchema(
39
+ z.object({
40
+ error: z.object({
41
+ code: z.number().nullable(),
42
+ message: z.string(),
43
+ status: z.string()
44
+ })
45
+ })
46
+ )
47
+ );
48
+ var googleFailedResponseHandler = createJsonErrorResponseHandler({
49
+ errorSchema: googleErrorDataSchema,
50
+ errorToMessage: (data) => data.error.message
51
+ });
52
+ var googleGenerativeAIEmbeddingProviderOptions = lazySchema(
53
+ () => zodSchema(
54
+ z2.object({
55
+ /**
56
+ * Optional. Optional reduced dimension for the output embedding.
57
+ * If set, excessive values in the output embedding are truncated from the end.
58
+ */
59
+ outputDimensionality: z2.number().optional(),
60
+ /**
61
+ * Optional. Specifies the task type for generating embeddings.
62
+ * Supported task types:
63
+ * - SEMANTIC_SIMILARITY: Optimized for text similarity.
64
+ * - CLASSIFICATION: Optimized for text classification.
65
+ * - CLUSTERING: Optimized for clustering texts based on similarity.
66
+ * - RETRIEVAL_DOCUMENT: Optimized for document retrieval.
67
+ * - RETRIEVAL_QUERY: Optimized for query-based retrieval.
68
+ * - QUESTION_ANSWERING: Optimized for answering questions.
69
+ * - FACT_VERIFICATION: Optimized for verifying factual information.
70
+ * - CODE_RETRIEVAL_QUERY: Optimized for retrieving code blocks based on natural language queries.
71
+ */
72
+ taskType: z2.enum([
73
+ "SEMANTIC_SIMILARITY",
74
+ "CLASSIFICATION",
75
+ "CLUSTERING",
76
+ "RETRIEVAL_DOCUMENT",
77
+ "RETRIEVAL_QUERY",
78
+ "QUESTION_ANSWERING",
79
+ "FACT_VERIFICATION",
80
+ "CODE_RETRIEVAL_QUERY"
81
+ ]).optional()
82
+ })
83
+ )
84
+ );
85
+ var GoogleGenerativeAIEmbeddingModel = class {
86
+ constructor(modelId, config) {
87
+ this.specificationVersion = "v2";
88
+ this.maxEmbeddingsPerCall = 2048;
89
+ this.supportsParallelCalls = true;
90
+ this.modelId = modelId;
91
+ this.config = config;
92
+ }
93
+ get provider() {
94
+ return this.config.provider;
95
+ }
96
+ async doEmbed({
97
+ values,
98
+ headers,
99
+ abortSignal,
100
+ providerOptions
101
+ }) {
102
+ const googleOptions = await parseProviderOptions({
103
+ provider: "google",
104
+ providerOptions,
105
+ schema: googleGenerativeAIEmbeddingProviderOptions
106
+ });
107
+ if (values.length > this.maxEmbeddingsPerCall) {
108
+ throw new TooManyEmbeddingValuesForCallError({
109
+ provider: this.provider,
110
+ modelId: this.modelId,
111
+ maxEmbeddingsPerCall: this.maxEmbeddingsPerCall,
112
+ values
113
+ });
114
+ }
115
+ const mergedHeaders = combineHeaders(
116
+ await resolve(this.config.headers),
117
+ headers
118
+ );
119
+ if (values.length === 1) {
120
+ const {
121
+ responseHeaders: responseHeaders2,
122
+ value: response2,
123
+ rawValue: rawValue2
124
+ } = await postJsonToApi({
125
+ url: `${this.config.baseURL}/models/${this.modelId}:embedContent`,
126
+ headers: mergedHeaders,
127
+ body: {
128
+ model: `models/${this.modelId}`,
129
+ content: {
130
+ parts: [{ text: values[0] }]
131
+ },
132
+ outputDimensionality: googleOptions == null ? void 0 : googleOptions.outputDimensionality,
133
+ taskType: googleOptions == null ? void 0 : googleOptions.taskType
134
+ },
135
+ failedResponseHandler: googleFailedResponseHandler,
136
+ successfulResponseHandler: createJsonResponseHandler(
137
+ googleGenerativeAISingleEmbeddingResponseSchema
138
+ ),
139
+ abortSignal,
140
+ fetch: this.config.fetch
141
+ });
142
+ return {
143
+ embeddings: [response2.embedding.values],
144
+ usage: void 0,
145
+ response: { headers: responseHeaders2, body: rawValue2 }
146
+ };
147
+ }
148
+ const {
149
+ responseHeaders,
150
+ value: response,
151
+ rawValue
152
+ } = await postJsonToApi({
153
+ url: `${this.config.baseURL}/models/${this.modelId}:batchEmbedContents`,
154
+ headers: mergedHeaders,
155
+ body: {
156
+ requests: values.map((value) => ({
157
+ model: `models/${this.modelId}`,
158
+ content: { role: "user", parts: [{ text: value }] },
159
+ outputDimensionality: googleOptions == null ? void 0 : googleOptions.outputDimensionality,
160
+ taskType: googleOptions == null ? void 0 : googleOptions.taskType
161
+ }))
162
+ },
163
+ failedResponseHandler: googleFailedResponseHandler,
164
+ successfulResponseHandler: createJsonResponseHandler(
165
+ googleGenerativeAITextEmbeddingResponseSchema
166
+ ),
167
+ abortSignal,
168
+ fetch: this.config.fetch
169
+ });
170
+ return {
171
+ embeddings: response.embeddings.map((item) => item.values),
172
+ usage: void 0,
173
+ response: { headers: responseHeaders, body: rawValue }
174
+ };
175
+ }
176
+ };
177
+ var googleGenerativeAITextEmbeddingResponseSchema = lazySchema(
178
+ () => zodSchema(
179
+ z3.object({
180
+ embeddings: z3.array(z3.object({ values: z3.array(z3.number()) }))
181
+ })
182
+ )
183
+ );
184
+ var googleGenerativeAISingleEmbeddingResponseSchema = lazySchema(
185
+ () => zodSchema(
186
+ z3.object({
187
+ embedding: z3.object({ values: z3.array(z3.number()) })
188
+ })
189
+ )
190
+ );
191
+ function convertJSONSchemaToOpenAPISchema(jsonSchema, isRoot = true) {
192
+ if (jsonSchema == null) {
193
+ return void 0;
194
+ }
195
+ if (isEmptyObjectSchema(jsonSchema)) {
196
+ if (isRoot) {
197
+ return void 0;
198
+ }
199
+ if (typeof jsonSchema === "object" && jsonSchema.description) {
200
+ return { type: "object", description: jsonSchema.description };
201
+ }
202
+ return { type: "object" };
203
+ }
204
+ if (typeof jsonSchema === "boolean") {
205
+ return { type: "boolean", properties: {} };
206
+ }
207
+ const {
208
+ type,
209
+ description,
210
+ required,
211
+ properties,
212
+ items,
213
+ allOf,
214
+ anyOf,
215
+ oneOf,
216
+ format,
217
+ const: constValue,
218
+ minLength,
219
+ enum: enumValues
220
+ } = jsonSchema;
221
+ const result = {};
222
+ if (description) result.description = description;
223
+ if (required) result.required = required;
224
+ if (format) result.format = format;
225
+ if (constValue !== void 0) {
226
+ result.enum = [constValue];
227
+ }
228
+ if (type) {
229
+ if (Array.isArray(type)) {
230
+ const hasNull = type.includes("null");
231
+ const nonNullTypes = type.filter((t) => t !== "null");
232
+ if (nonNullTypes.length === 0) {
233
+ result.type = "null";
234
+ } else {
235
+ result.anyOf = nonNullTypes.map((t) => ({ type: t }));
236
+ if (hasNull) {
237
+ result.nullable = true;
238
+ }
239
+ }
240
+ } else {
241
+ result.type = type;
242
+ }
243
+ }
244
+ if (enumValues !== void 0) {
245
+ result.enum = enumValues;
246
+ }
247
+ if (properties != null) {
248
+ result.properties = Object.entries(properties).reduce(
249
+ (acc, [key, value]) => {
250
+ acc[key] = convertJSONSchemaToOpenAPISchema(value, false);
251
+ return acc;
252
+ },
253
+ {}
254
+ );
255
+ }
256
+ if (items) {
257
+ result.items = Array.isArray(items) ? items.map((item) => convertJSONSchemaToOpenAPISchema(item, false)) : convertJSONSchemaToOpenAPISchema(items, false);
258
+ }
259
+ if (allOf) {
260
+ result.allOf = allOf.map(
261
+ (item) => convertJSONSchemaToOpenAPISchema(item, false)
262
+ );
263
+ }
264
+ if (anyOf) {
265
+ if (anyOf.some(
266
+ (schema) => typeof schema === "object" && (schema == null ? void 0 : schema.type) === "null"
267
+ )) {
268
+ const nonNullSchemas = anyOf.filter(
269
+ (schema) => !(typeof schema === "object" && (schema == null ? void 0 : schema.type) === "null")
270
+ );
271
+ if (nonNullSchemas.length === 1) {
272
+ const converted = convertJSONSchemaToOpenAPISchema(
273
+ nonNullSchemas[0],
274
+ false
275
+ );
276
+ if (typeof converted === "object") {
277
+ result.nullable = true;
278
+ Object.assign(result, converted);
279
+ }
280
+ } else {
281
+ result.anyOf = nonNullSchemas.map(
282
+ (item) => convertJSONSchemaToOpenAPISchema(item, false)
283
+ );
284
+ result.nullable = true;
285
+ }
286
+ } else {
287
+ result.anyOf = anyOf.map(
288
+ (item) => convertJSONSchemaToOpenAPISchema(item, false)
289
+ );
290
+ }
291
+ }
292
+ if (oneOf) {
293
+ result.oneOf = oneOf.map(
294
+ (item) => convertJSONSchemaToOpenAPISchema(item, false)
295
+ );
296
+ }
297
+ if (minLength !== void 0) {
298
+ result.minLength = minLength;
299
+ }
300
+ return result;
301
+ }
302
+ function isEmptyObjectSchema(jsonSchema) {
303
+ return jsonSchema != null && typeof jsonSchema === "object" && jsonSchema.type === "object" && (jsonSchema.properties == null || Object.keys(jsonSchema.properties).length === 0) && !jsonSchema.additionalProperties;
304
+ }
305
+ function convertToGoogleGenerativeAIMessages(prompt, options) {
306
+ var _a;
307
+ const systemInstructionParts = [];
308
+ const contents = [];
309
+ let systemMessagesAllowed = true;
310
+ const isGemmaModel = (_a = options == null ? void 0 : options.isGemmaModel) != null ? _a : false;
311
+ for (const { role, content } of prompt) {
312
+ switch (role) {
313
+ case "system": {
314
+ if (!systemMessagesAllowed) {
315
+ throw new UnsupportedFunctionalityError({
316
+ functionality: "system messages are only supported at the beginning of the conversation"
317
+ });
318
+ }
319
+ systemInstructionParts.push({ text: content });
320
+ break;
321
+ }
322
+ case "user": {
323
+ systemMessagesAllowed = false;
324
+ const parts = [];
325
+ for (const part of content) {
326
+ switch (part.type) {
327
+ case "text": {
328
+ parts.push({ text: part.text });
329
+ break;
330
+ }
331
+ case "file": {
332
+ const mediaType = part.mediaType === "image/*" ? "image/jpeg" : part.mediaType;
333
+ parts.push(
334
+ part.data instanceof URL ? {
335
+ fileData: {
336
+ mimeType: mediaType,
337
+ fileUri: part.data.toString()
338
+ }
339
+ } : {
340
+ inlineData: {
341
+ mimeType: mediaType,
342
+ data: convertToBase64(part.data)
343
+ }
344
+ }
345
+ );
346
+ break;
347
+ }
348
+ }
349
+ }
350
+ contents.push({ role: "user", parts });
351
+ break;
352
+ }
353
+ case "assistant": {
354
+ systemMessagesAllowed = false;
355
+ contents.push({
356
+ role: "model",
357
+ parts: content.map((part) => {
358
+ var _a2, _b, _c;
359
+ const thoughtSignature = ((_b = (_a2 = part.providerOptions) == null ? void 0 : _a2.google) == null ? void 0 : _b.thoughtSignature) != null ? String((_c = part.providerOptions.google) == null ? void 0 : _c.thoughtSignature) : void 0;
360
+ switch (part.type) {
361
+ case "text": {
362
+ return part.text.length === 0 ? void 0 : {
363
+ text: part.text,
364
+ thoughtSignature
365
+ };
366
+ }
367
+ case "reasoning": {
368
+ return part.text.length === 0 ? void 0 : {
369
+ text: part.text,
370
+ thought: true,
371
+ thoughtSignature
372
+ };
373
+ }
374
+ case "file": {
375
+ if (part.mediaType !== "image/png") {
376
+ throw new UnsupportedFunctionalityError({
377
+ functionality: "Only PNG images are supported in assistant messages"
378
+ });
379
+ }
380
+ if (part.data instanceof URL) {
381
+ throw new UnsupportedFunctionalityError({
382
+ functionality: "File data URLs in assistant messages are not supported"
383
+ });
384
+ }
385
+ return {
386
+ inlineData: {
387
+ mimeType: part.mediaType,
388
+ data: convertToBase64(part.data)
389
+ }
390
+ };
391
+ }
392
+ case "tool-call": {
393
+ return {
394
+ functionCall: {
395
+ name: part.toolName,
396
+ args: part.input
397
+ },
398
+ thoughtSignature
399
+ };
400
+ }
401
+ }
402
+ }).filter((part) => part !== void 0)
403
+ });
404
+ break;
405
+ }
406
+ case "tool": {
407
+ systemMessagesAllowed = false;
408
+ const parts = [];
409
+ for (const part of content) {
410
+ const output = part.output;
411
+ if (output.type === "content") {
412
+ for (const contentPart of output.value) {
413
+ switch (contentPart.type) {
414
+ case "text":
415
+ parts.push({
416
+ functionResponse: {
417
+ name: part.toolName,
418
+ response: {
419
+ name: part.toolName,
420
+ content: contentPart.text
421
+ }
422
+ }
423
+ });
424
+ break;
425
+ case "media":
426
+ parts.push(
427
+ {
428
+ inlineData: {
429
+ mimeType: contentPart.mediaType,
430
+ data: contentPart.data
431
+ }
432
+ },
433
+ {
434
+ text: "Tool executed successfully and returned this image as a response"
435
+ }
436
+ );
437
+ break;
438
+ default:
439
+ parts.push({ text: JSON.stringify(contentPart) });
440
+ break;
441
+ }
442
+ }
443
+ } else {
444
+ parts.push({
445
+ functionResponse: {
446
+ name: part.toolName,
447
+ response: {
448
+ name: part.toolName,
449
+ content: output.value
450
+ }
451
+ }
452
+ });
453
+ }
454
+ }
455
+ contents.push({
456
+ role: "user",
457
+ parts
458
+ });
459
+ break;
460
+ }
461
+ }
462
+ }
463
+ if (isGemmaModel && systemInstructionParts.length > 0 && contents.length > 0 && contents[0].role === "user") {
464
+ const systemText = systemInstructionParts.map((part) => part.text).join("\n\n");
465
+ contents[0].parts.unshift({ text: systemText + "\n\n" });
466
+ }
467
+ return {
468
+ systemInstruction: systemInstructionParts.length > 0 && !isGemmaModel ? { parts: systemInstructionParts } : void 0,
469
+ contents
470
+ };
471
+ }
472
+ function getModelPath(modelId) {
473
+ return modelId.includes("/") ? modelId : `models/${modelId}`;
474
+ }
475
+ var googleGenerativeAIProviderOptions = lazySchema(
476
+ () => zodSchema(
477
+ z4.object({
478
+ responseModalities: z4.array(z4.enum(["TEXT", "IMAGE"])).optional(),
479
+ thinkingConfig: z4.object({
480
+ thinkingBudget: z4.number().optional(),
481
+ includeThoughts: z4.boolean().optional(),
482
+ // https://ai.google.dev/gemini-api/docs/gemini-3?thinking=high#thinking_level
483
+ thinkingLevel: z4.enum(["minimal", "low", "medium", "high"]).optional()
484
+ }).optional(),
485
+ /**
486
+ * Optional.
487
+ * The name of the cached content used as context to serve the prediction.
488
+ * Format: cachedContents/{cachedContent}
489
+ */
490
+ cachedContent: z4.string().optional(),
491
+ /**
492
+ * Optional. Enable structured output. Default is true.
493
+ *
494
+ * This is useful when the JSON Schema contains elements that are
495
+ * not supported by the OpenAPI schema version that
496
+ * Google Generative AI uses. You can use this to disable
497
+ * structured outputs if you need to.
498
+ */
499
+ structuredOutputs: z4.boolean().optional(),
500
+ /**
501
+ * Optional. A list of unique safety settings for blocking unsafe content.
502
+ */
503
+ safetySettings: z4.array(
504
+ z4.object({
505
+ category: z4.enum([
506
+ "HARM_CATEGORY_UNSPECIFIED",
507
+ "HARM_CATEGORY_HATE_SPEECH",
508
+ "HARM_CATEGORY_DANGEROUS_CONTENT",
509
+ "HARM_CATEGORY_HARASSMENT",
510
+ "HARM_CATEGORY_SEXUALLY_EXPLICIT",
511
+ "HARM_CATEGORY_CIVIC_INTEGRITY"
512
+ ]),
513
+ threshold: z4.enum([
514
+ "HARM_BLOCK_THRESHOLD_UNSPECIFIED",
515
+ "BLOCK_LOW_AND_ABOVE",
516
+ "BLOCK_MEDIUM_AND_ABOVE",
517
+ "BLOCK_ONLY_HIGH",
518
+ "BLOCK_NONE",
519
+ "OFF"
520
+ ])
521
+ })
522
+ ).optional(),
523
+ threshold: z4.enum([
524
+ "HARM_BLOCK_THRESHOLD_UNSPECIFIED",
525
+ "BLOCK_LOW_AND_ABOVE",
526
+ "BLOCK_MEDIUM_AND_ABOVE",
527
+ "BLOCK_ONLY_HIGH",
528
+ "BLOCK_NONE",
529
+ "OFF"
530
+ ]).optional(),
531
+ /**
532
+ * Optional. Enables timestamp understanding for audio-only files.
533
+ *
534
+ * https://cloud.google.com/vertex-ai/generative-ai/docs/multimodal/audio-understanding
535
+ */
536
+ audioTimestamp: z4.boolean().optional(),
537
+ /**
538
+ * Optional. Defines labels used in billing reports. Available on Vertex AI only.
539
+ *
540
+ * https://cloud.google.com/vertex-ai/generative-ai/docs/multimodal/add-labels-to-api-calls
541
+ */
542
+ labels: z4.record(z4.string(), z4.string()).optional(),
543
+ /**
544
+ * Optional. If specified, the media resolution specified will be used.
545
+ *
546
+ * https://ai.google.dev/api/generate-content#MediaResolution
547
+ */
548
+ mediaResolution: z4.enum([
549
+ "MEDIA_RESOLUTION_UNSPECIFIED",
550
+ "MEDIA_RESOLUTION_LOW",
551
+ "MEDIA_RESOLUTION_MEDIUM",
552
+ "MEDIA_RESOLUTION_HIGH"
553
+ ]).optional(),
554
+ /**
555
+ * Optional. Configures the image generation aspect ratio for Gemini models.
556
+ *
557
+ * https://ai.google.dev/gemini-api/docs/image-generation#aspect_ratios
558
+ */
559
+ imageConfig: z4.object({
560
+ aspectRatio: z4.enum([
561
+ "1:1",
562
+ "2:3",
563
+ "3:2",
564
+ "3:4",
565
+ "4:3",
566
+ "4:5",
567
+ "5:4",
568
+ "9:16",
569
+ "16:9",
570
+ "21:9"
571
+ ]).optional(),
572
+ imageSize: z4.enum(["1K", "2K", "4K"]).optional()
573
+ }).optional(),
574
+ /**
575
+ * Optional. Configuration for grounding retrieval.
576
+ * Used to provide location context for Google Maps and Google Search grounding.
577
+ *
578
+ * https://cloud.google.com/vertex-ai/generative-ai/docs/grounding/grounding-with-google-maps
579
+ */
580
+ retrievalConfig: z4.object({
581
+ latLng: z4.object({
582
+ latitude: z4.number(),
583
+ longitude: z4.number()
584
+ }).optional()
585
+ }).optional()
586
+ })
587
+ )
588
+ );
589
+ function prepareTools({
590
+ tools,
591
+ toolChoice,
592
+ modelId
593
+ }) {
594
+ var _a;
595
+ tools = (tools == null ? void 0 : tools.length) ? tools : void 0;
596
+ const toolWarnings = [];
597
+ const isLatest = [
598
+ "gemini-flash-latest",
599
+ "gemini-flash-lite-latest",
600
+ "gemini-pro-latest"
601
+ ].some((id) => id === modelId);
602
+ const isGemini2orNewer = modelId.includes("gemini-2") || modelId.includes("gemini-3") || isLatest;
603
+ const supportsDynamicRetrieval = modelId.includes("gemini-1.5-flash") && !modelId.includes("-8b");
604
+ const supportsFileSearch = modelId.includes("gemini-2.5");
605
+ if (tools == null) {
606
+ return { tools: void 0, toolConfig: void 0, toolWarnings };
607
+ }
608
+ const hasFunctionTools = tools.some((tool) => tool.type === "function");
609
+ const hasProviderDefinedTools = tools.some(
610
+ (tool) => tool.type === "provider-defined"
611
+ );
612
+ if (hasFunctionTools && hasProviderDefinedTools) {
613
+ const functionTools = tools.filter((tool) => tool.type === "function");
614
+ toolWarnings.push({
615
+ type: "unsupported-tool",
616
+ tool: tools.find((tool) => tool.type === "function"),
617
+ details: `Cannot mix function tools with provider-defined tools in the same request. Falling back to provider-defined tools only. The following function tools will be ignored: ${functionTools.map((t) => t.name).join(", ")}. Please use either function tools or provider-defined tools, but not both.`
618
+ });
619
+ }
620
+ if (hasProviderDefinedTools) {
621
+ const googleTools2 = [];
622
+ const providerDefinedTools = tools.filter(
623
+ (tool) => tool.type === "provider-defined"
624
+ );
625
+ providerDefinedTools.forEach((tool) => {
626
+ switch (tool.id) {
627
+ case "google.google_search":
628
+ if (isGemini2orNewer) {
629
+ googleTools2.push({ googleSearch: {} });
630
+ } else if (supportsDynamicRetrieval) {
631
+ googleTools2.push({
632
+ googleSearchRetrieval: {
633
+ dynamicRetrievalConfig: {
634
+ mode: tool.args.mode,
635
+ dynamicThreshold: tool.args.dynamicThreshold
636
+ }
637
+ }
638
+ });
639
+ } else {
640
+ googleTools2.push({ googleSearchRetrieval: {} });
641
+ }
642
+ break;
643
+ case "google.enterprise_web_search":
644
+ if (isGemini2orNewer) {
645
+ googleTools2.push({ enterpriseWebSearch: {} });
646
+ } else {
647
+ toolWarnings.push({
648
+ type: "unsupported-tool",
649
+ tool,
650
+ details: "Enterprise Web Search requires Gemini 2.0 or newer."
651
+ });
652
+ }
653
+ break;
654
+ case "google.url_context":
655
+ if (isGemini2orNewer) {
656
+ googleTools2.push({ urlContext: {} });
657
+ } else {
658
+ toolWarnings.push({
659
+ type: "unsupported-tool",
660
+ tool,
661
+ details: "The URL context tool is not supported with other Gemini models than Gemini 2."
662
+ });
663
+ }
664
+ break;
665
+ case "google.code_execution":
666
+ if (isGemini2orNewer) {
667
+ googleTools2.push({ codeExecution: {} });
668
+ } else {
669
+ toolWarnings.push({
670
+ type: "unsupported-tool",
671
+ tool,
672
+ details: "The code execution tools is not supported with other Gemini models than Gemini 2."
673
+ });
674
+ }
675
+ break;
676
+ case "google.file_search":
677
+ if (supportsFileSearch) {
678
+ googleTools2.push({ fileSearch: { ...tool.args } });
679
+ } else {
680
+ toolWarnings.push({
681
+ type: "unsupported-tool",
682
+ tool,
683
+ details: "The file search tool is only supported with Gemini 2.5 models."
684
+ });
685
+ }
686
+ break;
687
+ case "google.vertex_rag_store":
688
+ if (isGemini2orNewer) {
689
+ googleTools2.push({
690
+ retrieval: {
691
+ vertex_rag_store: {
692
+ rag_resources: {
693
+ rag_corpus: tool.args.ragCorpus
694
+ },
695
+ similarity_top_k: tool.args.topK
696
+ }
697
+ }
698
+ });
699
+ } else {
700
+ toolWarnings.push({
701
+ type: "unsupported-tool",
702
+ tool,
703
+ details: "The RAG store tool is not supported with other Gemini models than Gemini 2."
704
+ });
705
+ }
706
+ break;
707
+ case "google.google_maps":
708
+ if (isGemini2orNewer) {
709
+ googleTools2.push({ googleMaps: {} });
710
+ } else {
711
+ toolWarnings.push({
712
+ type: "unsupported-tool",
713
+ tool,
714
+ details: "The Google Maps grounding tool is not supported with Gemini models other than Gemini 2 or newer."
715
+ });
716
+ }
717
+ break;
718
+ default:
719
+ toolWarnings.push({ type: "unsupported-tool", tool });
720
+ break;
721
+ }
722
+ });
723
+ return {
724
+ tools: googleTools2.length > 0 ? googleTools2 : void 0,
725
+ toolConfig: void 0,
726
+ toolWarnings
727
+ };
728
+ }
729
+ const functionDeclarations = [];
730
+ for (const tool of tools) {
731
+ switch (tool.type) {
732
+ case "function":
733
+ functionDeclarations.push({
734
+ name: tool.name,
735
+ description: (_a = tool.description) != null ? _a : "",
736
+ parameters: convertJSONSchemaToOpenAPISchema(tool.inputSchema)
737
+ });
738
+ break;
739
+ default:
740
+ toolWarnings.push({ type: "unsupported-tool", tool });
741
+ break;
742
+ }
743
+ }
744
+ if (toolChoice == null) {
745
+ return {
746
+ tools: [{ functionDeclarations }],
747
+ toolConfig: void 0,
748
+ toolWarnings
749
+ };
750
+ }
751
+ const type = toolChoice.type;
752
+ switch (type) {
753
+ case "auto":
754
+ return {
755
+ tools: [{ functionDeclarations }],
756
+ toolConfig: { functionCallingConfig: { mode: "AUTO" } },
757
+ toolWarnings
758
+ };
759
+ case "none":
760
+ return {
761
+ tools: [{ functionDeclarations }],
762
+ toolConfig: { functionCallingConfig: { mode: "NONE" } },
763
+ toolWarnings
764
+ };
765
+ case "required":
766
+ return {
767
+ tools: [{ functionDeclarations }],
768
+ toolConfig: { functionCallingConfig: { mode: "ANY" } },
769
+ toolWarnings
770
+ };
771
+ case "tool":
772
+ return {
773
+ tools: [{ functionDeclarations }],
774
+ toolConfig: {
775
+ functionCallingConfig: {
776
+ mode: "ANY",
777
+ allowedFunctionNames: [toolChoice.toolName]
778
+ }
779
+ },
780
+ toolWarnings
781
+ };
782
+ default: {
783
+ const _exhaustiveCheck = type;
784
+ throw new UnsupportedFunctionalityError({
785
+ functionality: `tool choice type: ${_exhaustiveCheck}`
786
+ });
787
+ }
788
+ }
789
+ }
790
+ function mapGoogleGenerativeAIFinishReason({
791
+ finishReason,
792
+ hasToolCalls
793
+ }) {
794
+ switch (finishReason) {
795
+ case "STOP":
796
+ return hasToolCalls ? "tool-calls" : "stop";
797
+ case "MAX_TOKENS":
798
+ return "length";
799
+ case "IMAGE_SAFETY":
800
+ case "RECITATION":
801
+ case "SAFETY":
802
+ case "BLOCKLIST":
803
+ case "PROHIBITED_CONTENT":
804
+ case "SPII":
805
+ return "content-filter";
806
+ case "FINISH_REASON_UNSPECIFIED":
807
+ case "OTHER":
808
+ return "other";
809
+ case "MALFORMED_FUNCTION_CALL":
810
+ return "error";
811
+ default:
812
+ return "unknown";
813
+ }
814
+ }
815
+ var GoogleGenerativeAILanguageModel = class {
816
+ constructor(modelId, config) {
817
+ this.specificationVersion = "v2";
818
+ var _a;
819
+ this.modelId = modelId;
820
+ this.config = config;
821
+ this.generateId = (_a = config.generateId) != null ? _a : generateId;
822
+ }
823
+ get provider() {
824
+ return this.config.provider;
825
+ }
826
+ get supportedUrls() {
827
+ var _a, _b, _c;
828
+ return (_c = (_b = (_a = this.config).supportedUrls) == null ? void 0 : _b.call(_a)) != null ? _c : {};
829
+ }
830
+ async getArgs({
831
+ prompt,
832
+ maxOutputTokens,
833
+ temperature,
834
+ topP,
835
+ topK,
836
+ frequencyPenalty,
837
+ presencePenalty,
838
+ stopSequences,
839
+ responseFormat,
840
+ seed,
841
+ tools,
842
+ toolChoice,
843
+ providerOptions
844
+ }) {
845
+ var _a;
846
+ const warnings = [];
847
+ const googleOptions = await parseProviderOptions({
848
+ provider: "google",
849
+ providerOptions,
850
+ schema: googleGenerativeAIProviderOptions
851
+ });
852
+ if ((tools == null ? void 0 : tools.some(
853
+ (tool) => tool.type === "provider-defined" && tool.id === "google.vertex_rag_store"
854
+ )) && !this.config.provider.startsWith("google.vertex.")) {
855
+ warnings.push({
856
+ type: "other",
857
+ 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}).`
858
+ });
859
+ }
860
+ const isGemmaModel = this.modelId.toLowerCase().startsWith("gemma-");
861
+ const { contents, systemInstruction } = convertToGoogleGenerativeAIMessages(
862
+ prompt,
863
+ { isGemmaModel }
864
+ );
865
+ const {
866
+ tools: googleTools2,
867
+ toolConfig: googleToolConfig,
868
+ toolWarnings
869
+ } = prepareTools({
870
+ tools,
871
+ toolChoice,
872
+ modelId: this.modelId
873
+ });
874
+ return {
875
+ args: {
876
+ generationConfig: {
877
+ // standardized settings:
878
+ maxOutputTokens,
879
+ temperature,
880
+ topK,
881
+ topP,
882
+ frequencyPenalty,
883
+ presencePenalty,
884
+ stopSequences,
885
+ seed,
886
+ // response format:
887
+ responseMimeType: (responseFormat == null ? void 0 : responseFormat.type) === "json" ? "application/json" : void 0,
888
+ responseSchema: (responseFormat == null ? void 0 : responseFormat.type) === "json" && responseFormat.schema != null && // Google GenAI does not support all OpenAPI Schema features,
889
+ // so this is needed as an escape hatch:
890
+ // TODO convert into provider option
891
+ ((_a = googleOptions == null ? void 0 : googleOptions.structuredOutputs) != null ? _a : true) ? convertJSONSchemaToOpenAPISchema(responseFormat.schema) : void 0,
892
+ ...(googleOptions == null ? void 0 : googleOptions.audioTimestamp) && {
893
+ audioTimestamp: googleOptions.audioTimestamp
894
+ },
895
+ // provider options:
896
+ responseModalities: googleOptions == null ? void 0 : googleOptions.responseModalities,
897
+ thinkingConfig: googleOptions == null ? void 0 : googleOptions.thinkingConfig,
898
+ ...(googleOptions == null ? void 0 : googleOptions.imageConfig) && {
899
+ imageConfig: googleOptions.imageConfig
900
+ },
901
+ ...(googleOptions == null ? void 0 : googleOptions.mediaResolution) && {
902
+ mediaResolution: googleOptions.mediaResolution
903
+ }
904
+ },
905
+ contents,
906
+ systemInstruction: isGemmaModel ? void 0 : systemInstruction,
907
+ safetySettings: googleOptions == null ? void 0 : googleOptions.safetySettings,
908
+ tools: googleTools2,
909
+ toolConfig: (googleOptions == null ? void 0 : googleOptions.retrievalConfig) ? {
910
+ ...googleToolConfig,
911
+ retrievalConfig: googleOptions.retrievalConfig
912
+ } : googleToolConfig,
913
+ cachedContent: googleOptions == null ? void 0 : googleOptions.cachedContent,
914
+ labels: googleOptions == null ? void 0 : googleOptions.labels
915
+ },
916
+ warnings: [...warnings, ...toolWarnings]
917
+ };
918
+ }
919
+ async doGenerate(options) {
920
+ var _a, _b, _c, _d, _e, _f, _g, _h, _i, _j, _k, _l, _m;
921
+ const { args, warnings } = await this.getArgs(options);
922
+ const body = JSON.stringify(args);
923
+ const mergedHeaders = combineHeaders(
924
+ await resolve(this.config.headers),
925
+ options.headers
926
+ );
927
+ const {
928
+ responseHeaders,
929
+ value: response,
930
+ rawValue: rawResponse
931
+ } = await postJsonToApi({
932
+ url: `${this.config.baseURL}/${getModelPath(
933
+ this.modelId
934
+ )}:generateContent`,
935
+ headers: mergedHeaders,
936
+ body: args,
937
+ failedResponseHandler: googleFailedResponseHandler,
938
+ successfulResponseHandler: createJsonResponseHandler(responseSchema),
939
+ abortSignal: options.abortSignal,
940
+ fetch: this.config.fetch
941
+ });
942
+ const candidate = response.candidates[0];
943
+ const content = [];
944
+ const parts = (_b = (_a = candidate.content) == null ? void 0 : _a.parts) != null ? _b : [];
945
+ const usageMetadata = response.usageMetadata;
946
+ let lastCodeExecutionToolCallId;
947
+ for (const part of parts) {
948
+ if ("executableCode" in part && ((_c = part.executableCode) == null ? void 0 : _c.code)) {
949
+ const toolCallId = this.config.generateId();
950
+ lastCodeExecutionToolCallId = toolCallId;
951
+ content.push({
952
+ type: "tool-call",
953
+ toolCallId,
954
+ toolName: "code_execution",
955
+ input: JSON.stringify(part.executableCode),
956
+ providerExecuted: true
957
+ });
958
+ } else if ("codeExecutionResult" in part && part.codeExecutionResult) {
959
+ content.push({
960
+ type: "tool-result",
961
+ // Assumes a result directly follows its corresponding call part.
962
+ toolCallId: lastCodeExecutionToolCallId,
963
+ toolName: "code_execution",
964
+ result: {
965
+ outcome: part.codeExecutionResult.outcome,
966
+ output: part.codeExecutionResult.output
967
+ },
968
+ providerExecuted: true
969
+ });
970
+ lastCodeExecutionToolCallId = void 0;
971
+ } else if ("text" in part && part.text != null && part.text.length > 0) {
972
+ content.push({
973
+ type: part.thought === true ? "reasoning" : "text",
974
+ text: part.text,
975
+ providerMetadata: part.thoughtSignature ? { google: { thoughtSignature: part.thoughtSignature } } : void 0
976
+ });
977
+ } else if ("functionCall" in part) {
978
+ content.push({
979
+ type: "tool-call",
980
+ toolCallId: this.config.generateId(),
981
+ toolName: part.functionCall.name,
982
+ input: JSON.stringify(part.functionCall.args),
983
+ providerMetadata: part.thoughtSignature ? { google: { thoughtSignature: part.thoughtSignature } } : void 0
984
+ });
985
+ } else if ("inlineData" in part) {
986
+ content.push({
987
+ type: "file",
988
+ data: part.inlineData.data,
989
+ mediaType: part.inlineData.mimeType
990
+ });
991
+ }
992
+ }
993
+ const sources = (_d = extractSources({
994
+ groundingMetadata: candidate.groundingMetadata,
995
+ generateId: this.config.generateId
996
+ })) != null ? _d : [];
997
+ for (const source of sources) {
998
+ content.push(source);
999
+ }
1000
+ return {
1001
+ content,
1002
+ finishReason: mapGoogleGenerativeAIFinishReason({
1003
+ finishReason: candidate.finishReason,
1004
+ hasToolCalls: content.some((part) => part.type === "tool-call")
1005
+ }),
1006
+ usage: {
1007
+ inputTokens: (_e = usageMetadata == null ? void 0 : usageMetadata.promptTokenCount) != null ? _e : void 0,
1008
+ outputTokens: (_f = usageMetadata == null ? void 0 : usageMetadata.candidatesTokenCount) != null ? _f : void 0,
1009
+ totalTokens: (_g = usageMetadata == null ? void 0 : usageMetadata.totalTokenCount) != null ? _g : void 0,
1010
+ reasoningTokens: (_h = usageMetadata == null ? void 0 : usageMetadata.thoughtsTokenCount) != null ? _h : void 0,
1011
+ cachedInputTokens: (_i = usageMetadata == null ? void 0 : usageMetadata.cachedContentTokenCount) != null ? _i : void 0
1012
+ },
1013
+ warnings,
1014
+ providerMetadata: {
1015
+ google: {
1016
+ promptFeedback: (_j = response.promptFeedback) != null ? _j : null,
1017
+ groundingMetadata: (_k = candidate.groundingMetadata) != null ? _k : null,
1018
+ urlContextMetadata: (_l = candidate.urlContextMetadata) != null ? _l : null,
1019
+ safetyRatings: (_m = candidate.safetyRatings) != null ? _m : null,
1020
+ usageMetadata: usageMetadata != null ? usageMetadata : null
1021
+ }
1022
+ },
1023
+ request: { body },
1024
+ response: {
1025
+ // TODO timestamp, model id, id
1026
+ headers: responseHeaders,
1027
+ body: rawResponse
1028
+ }
1029
+ };
1030
+ }
1031
+ async doStream(options) {
1032
+ const { args, warnings } = await this.getArgs(options);
1033
+ const body = JSON.stringify(args);
1034
+ const headers = combineHeaders(
1035
+ await resolve(this.config.headers),
1036
+ options.headers
1037
+ );
1038
+ const { responseHeaders, value: response } = await postJsonToApi({
1039
+ url: `${this.config.baseURL}/${getModelPath(
1040
+ this.modelId
1041
+ )}:streamGenerateContent?alt=sse`,
1042
+ headers,
1043
+ body: args,
1044
+ failedResponseHandler: googleFailedResponseHandler,
1045
+ successfulResponseHandler: createEventSourceResponseHandler(chunkSchema),
1046
+ abortSignal: options.abortSignal,
1047
+ fetch: this.config.fetch
1048
+ });
1049
+ let finishReason = "unknown";
1050
+ const usage = {
1051
+ inputTokens: void 0,
1052
+ outputTokens: void 0,
1053
+ totalTokens: void 0
1054
+ };
1055
+ let providerMetadata = void 0;
1056
+ const generateId3 = this.config.generateId;
1057
+ let hasToolCalls = false;
1058
+ let currentTextBlockId = null;
1059
+ let currentReasoningBlockId = null;
1060
+ let blockCounter = 0;
1061
+ const emittedSourceUrls = /* @__PURE__ */ new Set();
1062
+ let lastCodeExecutionToolCallId;
1063
+ return {
1064
+ stream: response.pipeThrough(
1065
+ new TransformStream({
1066
+ start(controller) {
1067
+ controller.enqueue({ type: "stream-start", warnings });
1068
+ },
1069
+ transform(chunk, controller) {
1070
+ var _a, _b, _c, _d, _e, _f, _g, _h, _i, _j, _k, _l;
1071
+ if (options.includeRawChunks) {
1072
+ controller.enqueue({ type: "raw", rawValue: chunk.rawValue });
1073
+ }
1074
+ if (!chunk.success) {
1075
+ controller.enqueue({ type: "error", error: chunk.error });
1076
+ return;
1077
+ }
1078
+ const value = chunk.value;
1079
+ const usageMetadata = value.usageMetadata;
1080
+ if (usageMetadata != null) {
1081
+ usage.inputTokens = (_a = usageMetadata.promptTokenCount) != null ? _a : void 0;
1082
+ usage.outputTokens = (_b = usageMetadata.candidatesTokenCount) != null ? _b : void 0;
1083
+ usage.totalTokens = (_c = usageMetadata.totalTokenCount) != null ? _c : void 0;
1084
+ usage.reasoningTokens = (_d = usageMetadata.thoughtsTokenCount) != null ? _d : void 0;
1085
+ usage.cachedInputTokens = (_e = usageMetadata.cachedContentTokenCount) != null ? _e : void 0;
1086
+ }
1087
+ const candidate = (_f = value.candidates) == null ? void 0 : _f[0];
1088
+ if (candidate == null) {
1089
+ return;
1090
+ }
1091
+ const content = candidate.content;
1092
+ const sources = extractSources({
1093
+ groundingMetadata: candidate.groundingMetadata,
1094
+ generateId: generateId3
1095
+ });
1096
+ if (sources != null) {
1097
+ for (const source of sources) {
1098
+ if (source.sourceType === "url" && !emittedSourceUrls.has(source.url)) {
1099
+ emittedSourceUrls.add(source.url);
1100
+ controller.enqueue(source);
1101
+ }
1102
+ }
1103
+ }
1104
+ if (content != null) {
1105
+ const parts = (_g = content.parts) != null ? _g : [];
1106
+ for (const part of parts) {
1107
+ if ("executableCode" in part && ((_h = part.executableCode) == null ? void 0 : _h.code)) {
1108
+ const toolCallId = generateId3();
1109
+ lastCodeExecutionToolCallId = toolCallId;
1110
+ controller.enqueue({
1111
+ type: "tool-call",
1112
+ toolCallId,
1113
+ toolName: "code_execution",
1114
+ input: JSON.stringify(part.executableCode),
1115
+ providerExecuted: true
1116
+ });
1117
+ hasToolCalls = true;
1118
+ } else if ("codeExecutionResult" in part && part.codeExecutionResult) {
1119
+ const toolCallId = lastCodeExecutionToolCallId;
1120
+ if (toolCallId) {
1121
+ controller.enqueue({
1122
+ type: "tool-result",
1123
+ toolCallId,
1124
+ toolName: "code_execution",
1125
+ result: {
1126
+ outcome: part.codeExecutionResult.outcome,
1127
+ output: part.codeExecutionResult.output
1128
+ },
1129
+ providerExecuted: true
1130
+ });
1131
+ lastCodeExecutionToolCallId = void 0;
1132
+ }
1133
+ } else if ("text" in part && part.text != null && part.text.length > 0) {
1134
+ if (part.thought === true) {
1135
+ if (currentTextBlockId !== null) {
1136
+ controller.enqueue({
1137
+ type: "text-end",
1138
+ id: currentTextBlockId
1139
+ });
1140
+ currentTextBlockId = null;
1141
+ }
1142
+ if (currentReasoningBlockId === null) {
1143
+ currentReasoningBlockId = String(blockCounter++);
1144
+ controller.enqueue({
1145
+ type: "reasoning-start",
1146
+ id: currentReasoningBlockId,
1147
+ providerMetadata: part.thoughtSignature ? {
1148
+ google: {
1149
+ thoughtSignature: part.thoughtSignature
1150
+ }
1151
+ } : void 0
1152
+ });
1153
+ }
1154
+ controller.enqueue({
1155
+ type: "reasoning-delta",
1156
+ id: currentReasoningBlockId,
1157
+ delta: part.text,
1158
+ providerMetadata: part.thoughtSignature ? {
1159
+ google: { thoughtSignature: part.thoughtSignature }
1160
+ } : void 0
1161
+ });
1162
+ } else {
1163
+ if (currentReasoningBlockId !== null) {
1164
+ controller.enqueue({
1165
+ type: "reasoning-end",
1166
+ id: currentReasoningBlockId
1167
+ });
1168
+ currentReasoningBlockId = null;
1169
+ }
1170
+ if (currentTextBlockId === null) {
1171
+ currentTextBlockId = String(blockCounter++);
1172
+ controller.enqueue({
1173
+ type: "text-start",
1174
+ id: currentTextBlockId,
1175
+ providerMetadata: part.thoughtSignature ? {
1176
+ google: {
1177
+ thoughtSignature: part.thoughtSignature
1178
+ }
1179
+ } : void 0
1180
+ });
1181
+ }
1182
+ controller.enqueue({
1183
+ type: "text-delta",
1184
+ id: currentTextBlockId,
1185
+ delta: part.text,
1186
+ providerMetadata: part.thoughtSignature ? {
1187
+ google: { thoughtSignature: part.thoughtSignature }
1188
+ } : void 0
1189
+ });
1190
+ }
1191
+ } else if ("inlineData" in part) {
1192
+ controller.enqueue({
1193
+ type: "file",
1194
+ mediaType: part.inlineData.mimeType,
1195
+ data: part.inlineData.data
1196
+ });
1197
+ }
1198
+ }
1199
+ const toolCallDeltas = getToolCallsFromParts({
1200
+ parts: content.parts,
1201
+ generateId: generateId3
1202
+ });
1203
+ if (toolCallDeltas != null) {
1204
+ for (const toolCall of toolCallDeltas) {
1205
+ controller.enqueue({
1206
+ type: "tool-input-start",
1207
+ id: toolCall.toolCallId,
1208
+ toolName: toolCall.toolName,
1209
+ providerMetadata: toolCall.providerMetadata
1210
+ });
1211
+ controller.enqueue({
1212
+ type: "tool-input-delta",
1213
+ id: toolCall.toolCallId,
1214
+ delta: toolCall.args,
1215
+ providerMetadata: toolCall.providerMetadata
1216
+ });
1217
+ controller.enqueue({
1218
+ type: "tool-input-end",
1219
+ id: toolCall.toolCallId,
1220
+ providerMetadata: toolCall.providerMetadata
1221
+ });
1222
+ controller.enqueue({
1223
+ type: "tool-call",
1224
+ toolCallId: toolCall.toolCallId,
1225
+ toolName: toolCall.toolName,
1226
+ input: toolCall.args,
1227
+ providerMetadata: toolCall.providerMetadata
1228
+ });
1229
+ hasToolCalls = true;
1230
+ }
1231
+ }
1232
+ }
1233
+ if (candidate.finishReason != null) {
1234
+ finishReason = mapGoogleGenerativeAIFinishReason({
1235
+ finishReason: candidate.finishReason,
1236
+ hasToolCalls
1237
+ });
1238
+ providerMetadata = {
1239
+ google: {
1240
+ promptFeedback: (_i = value.promptFeedback) != null ? _i : null,
1241
+ groundingMetadata: (_j = candidate.groundingMetadata) != null ? _j : null,
1242
+ urlContextMetadata: (_k = candidate.urlContextMetadata) != null ? _k : null,
1243
+ safetyRatings: (_l = candidate.safetyRatings) != null ? _l : null
1244
+ }
1245
+ };
1246
+ if (usageMetadata != null) {
1247
+ providerMetadata.google.usageMetadata = usageMetadata;
1248
+ }
1249
+ }
1250
+ },
1251
+ flush(controller) {
1252
+ if (currentTextBlockId !== null) {
1253
+ controller.enqueue({
1254
+ type: "text-end",
1255
+ id: currentTextBlockId
1256
+ });
1257
+ }
1258
+ if (currentReasoningBlockId !== null) {
1259
+ controller.enqueue({
1260
+ type: "reasoning-end",
1261
+ id: currentReasoningBlockId
1262
+ });
1263
+ }
1264
+ controller.enqueue({
1265
+ type: "finish",
1266
+ finishReason,
1267
+ usage,
1268
+ providerMetadata
1269
+ });
1270
+ }
1271
+ })
1272
+ ),
1273
+ response: { headers: responseHeaders },
1274
+ request: { body }
1275
+ };
1276
+ }
1277
+ };
1278
+ function getToolCallsFromParts({
1279
+ parts,
1280
+ generateId: generateId3
1281
+ }) {
1282
+ const functionCallParts = parts == null ? void 0 : parts.filter(
1283
+ (part) => "functionCall" in part
1284
+ );
1285
+ return functionCallParts == null || functionCallParts.length === 0 ? void 0 : functionCallParts.map((part) => ({
1286
+ type: "tool-call",
1287
+ toolCallId: generateId3(),
1288
+ toolName: part.functionCall.name,
1289
+ args: JSON.stringify(part.functionCall.args),
1290
+ providerMetadata: part.thoughtSignature ? { google: { thoughtSignature: part.thoughtSignature } } : void 0
1291
+ }));
1292
+ }
1293
+ function extractSources({
1294
+ groundingMetadata,
1295
+ generateId: generateId3
1296
+ }) {
1297
+ var _a, _b, _c, _d, _e;
1298
+ if (!(groundingMetadata == null ? void 0 : groundingMetadata.groundingChunks)) {
1299
+ return void 0;
1300
+ }
1301
+ const sources = [];
1302
+ for (const chunk of groundingMetadata.groundingChunks) {
1303
+ if (chunk.web != null) {
1304
+ sources.push({
1305
+ type: "source",
1306
+ sourceType: "url",
1307
+ id: generateId3(),
1308
+ url: chunk.web.uri,
1309
+ title: (_a = chunk.web.title) != null ? _a : void 0
1310
+ });
1311
+ } else if (chunk.retrievedContext != null) {
1312
+ const uri = chunk.retrievedContext.uri;
1313
+ const fileSearchStore = chunk.retrievedContext.fileSearchStore;
1314
+ if (uri && (uri.startsWith("http://") || uri.startsWith("https://"))) {
1315
+ sources.push({
1316
+ type: "source",
1317
+ sourceType: "url",
1318
+ id: generateId3(),
1319
+ url: uri,
1320
+ title: (_b = chunk.retrievedContext.title) != null ? _b : void 0
1321
+ });
1322
+ } else if (uri) {
1323
+ const title = (_c = chunk.retrievedContext.title) != null ? _c : "Unknown Document";
1324
+ let mediaType = "application/octet-stream";
1325
+ let filename = void 0;
1326
+ if (uri.endsWith(".pdf")) {
1327
+ mediaType = "application/pdf";
1328
+ filename = uri.split("/").pop();
1329
+ } else if (uri.endsWith(".txt")) {
1330
+ mediaType = "text/plain";
1331
+ filename = uri.split("/").pop();
1332
+ } else if (uri.endsWith(".docx")) {
1333
+ mediaType = "application/vnd.openxmlformats-officedocument.wordprocessingml.document";
1334
+ filename = uri.split("/").pop();
1335
+ } else if (uri.endsWith(".doc")) {
1336
+ mediaType = "application/msword";
1337
+ filename = uri.split("/").pop();
1338
+ } else if (uri.match(/\.(md|markdown)$/)) {
1339
+ mediaType = "text/markdown";
1340
+ filename = uri.split("/").pop();
1341
+ } else {
1342
+ filename = uri.split("/").pop();
1343
+ }
1344
+ sources.push({
1345
+ type: "source",
1346
+ sourceType: "document",
1347
+ id: generateId3(),
1348
+ mediaType,
1349
+ title,
1350
+ filename
1351
+ });
1352
+ } else if (fileSearchStore) {
1353
+ const title = (_d = chunk.retrievedContext.title) != null ? _d : "Unknown Document";
1354
+ sources.push({
1355
+ type: "source",
1356
+ sourceType: "document",
1357
+ id: generateId3(),
1358
+ mediaType: "application/octet-stream",
1359
+ title,
1360
+ filename: fileSearchStore.split("/").pop()
1361
+ });
1362
+ }
1363
+ } else if (chunk.maps != null) {
1364
+ if (chunk.maps.uri) {
1365
+ sources.push({
1366
+ type: "source",
1367
+ sourceType: "url",
1368
+ id: generateId3(),
1369
+ url: chunk.maps.uri,
1370
+ title: (_e = chunk.maps.title) != null ? _e : void 0
1371
+ });
1372
+ }
1373
+ }
1374
+ }
1375
+ return sources.length > 0 ? sources : void 0;
1376
+ }
1377
+ var getGroundingMetadataSchema = () => z5.object({
1378
+ webSearchQueries: z5.array(z5.string()).nullish(),
1379
+ retrievalQueries: z5.array(z5.string()).nullish(),
1380
+ searchEntryPoint: z5.object({ renderedContent: z5.string() }).nullish(),
1381
+ groundingChunks: z5.array(
1382
+ z5.object({
1383
+ web: z5.object({ uri: z5.string(), title: z5.string().nullish() }).nullish(),
1384
+ retrievedContext: z5.object({
1385
+ uri: z5.string().nullish(),
1386
+ title: z5.string().nullish(),
1387
+ text: z5.string().nullish(),
1388
+ fileSearchStore: z5.string().nullish()
1389
+ }).nullish(),
1390
+ maps: z5.object({
1391
+ uri: z5.string().nullish(),
1392
+ title: z5.string().nullish(),
1393
+ text: z5.string().nullish(),
1394
+ placeId: z5.string().nullish()
1395
+ }).nullish()
1396
+ })
1397
+ ).nullish(),
1398
+ groundingSupports: z5.array(
1399
+ z5.object({
1400
+ segment: z5.object({
1401
+ startIndex: z5.number().nullish(),
1402
+ endIndex: z5.number().nullish(),
1403
+ text: z5.string().nullish()
1404
+ }),
1405
+ segment_text: z5.string().nullish(),
1406
+ groundingChunkIndices: z5.array(z5.number()).nullish(),
1407
+ supportChunkIndices: z5.array(z5.number()).nullish(),
1408
+ confidenceScores: z5.array(z5.number()).nullish(),
1409
+ confidenceScore: z5.array(z5.number()).nullish()
1410
+ })
1411
+ ).nullish(),
1412
+ retrievalMetadata: z5.union([
1413
+ z5.object({
1414
+ webDynamicRetrievalScore: z5.number()
1415
+ }),
1416
+ z5.object({})
1417
+ ]).nullish()
1418
+ });
1419
+ var getContentSchema = () => z5.object({
1420
+ parts: z5.array(
1421
+ z5.union([
1422
+ // note: order matters since text can be fully empty
1423
+ z5.object({
1424
+ functionCall: z5.object({
1425
+ name: z5.string(),
1426
+ args: z5.unknown()
1427
+ }),
1428
+ thoughtSignature: z5.string().nullish()
1429
+ }),
1430
+ z5.object({
1431
+ inlineData: z5.object({
1432
+ mimeType: z5.string(),
1433
+ data: z5.string()
1434
+ })
1435
+ }),
1436
+ z5.object({
1437
+ executableCode: z5.object({
1438
+ language: z5.string(),
1439
+ code: z5.string()
1440
+ }).nullish(),
1441
+ codeExecutionResult: z5.object({
1442
+ outcome: z5.string(),
1443
+ output: z5.string()
1444
+ }).nullish(),
1445
+ text: z5.string().nullish(),
1446
+ thought: z5.boolean().nullish(),
1447
+ thoughtSignature: z5.string().nullish()
1448
+ })
1449
+ ])
1450
+ ).nullish()
1451
+ });
1452
+ var getSafetyRatingSchema = () => z5.object({
1453
+ category: z5.string().nullish(),
1454
+ probability: z5.string().nullish(),
1455
+ probabilityScore: z5.number().nullish(),
1456
+ severity: z5.string().nullish(),
1457
+ severityScore: z5.number().nullish(),
1458
+ blocked: z5.boolean().nullish()
1459
+ });
1460
+ var usageSchema = z5.object({
1461
+ cachedContentTokenCount: z5.number().nullish(),
1462
+ thoughtsTokenCount: z5.number().nullish(),
1463
+ promptTokenCount: z5.number().nullish(),
1464
+ candidatesTokenCount: z5.number().nullish(),
1465
+ totalTokenCount: z5.number().nullish(),
1466
+ // https://cloud.google.com/vertex-ai/generative-ai/docs/reference/rest/v1/GenerateContentResponse#TrafficType
1467
+ trafficType: z5.string().nullish()
1468
+ });
1469
+ var getUrlContextMetadataSchema = () => z5.object({
1470
+ urlMetadata: z5.array(
1471
+ z5.object({
1472
+ retrievedUrl: z5.string(),
1473
+ urlRetrievalStatus: z5.string()
1474
+ })
1475
+ )
1476
+ });
1477
+ var responseSchema = lazySchema(
1478
+ () => zodSchema(
1479
+ z5.object({
1480
+ candidates: z5.array(
1481
+ z5.object({
1482
+ content: getContentSchema().nullish().or(z5.object({}).strict()),
1483
+ finishReason: z5.string().nullish(),
1484
+ safetyRatings: z5.array(getSafetyRatingSchema()).nullish(),
1485
+ groundingMetadata: getGroundingMetadataSchema().nullish(),
1486
+ urlContextMetadata: getUrlContextMetadataSchema().nullish()
1487
+ })
1488
+ ),
1489
+ usageMetadata: usageSchema.nullish(),
1490
+ promptFeedback: z5.object({
1491
+ blockReason: z5.string().nullish(),
1492
+ safetyRatings: z5.array(getSafetyRatingSchema()).nullish()
1493
+ }).nullish()
1494
+ })
1495
+ )
1496
+ );
1497
+ var chunkSchema = lazySchema(
1498
+ () => zodSchema(
1499
+ z5.object({
1500
+ candidates: z5.array(
1501
+ z5.object({
1502
+ content: getContentSchema().nullish(),
1503
+ finishReason: z5.string().nullish(),
1504
+ safetyRatings: z5.array(getSafetyRatingSchema()).nullish(),
1505
+ groundingMetadata: getGroundingMetadataSchema().nullish(),
1506
+ urlContextMetadata: getUrlContextMetadataSchema().nullish()
1507
+ })
1508
+ ).nullish(),
1509
+ usageMetadata: usageSchema.nullish(),
1510
+ promptFeedback: z5.object({
1511
+ blockReason: z5.string().nullish(),
1512
+ safetyRatings: z5.array(getSafetyRatingSchema()).nullish()
1513
+ }).nullish()
1514
+ })
1515
+ )
1516
+ );
1517
+ var codeExecution = createProviderDefinedToolFactoryWithOutputSchema({
1518
+ id: "google.code_execution",
1519
+ name: "code_execution",
1520
+ inputSchema: z6.object({
1521
+ language: z6.string().describe("The programming language of the code."),
1522
+ code: z6.string().describe("The code to be executed.")
1523
+ }),
1524
+ outputSchema: z6.object({
1525
+ outcome: z6.string().describe('The outcome of the execution (e.g., "OUTCOME_OK").'),
1526
+ output: z6.string().describe("The output from the code execution.")
1527
+ })
1528
+ });
1529
+ var enterpriseWebSearch = createProviderDefinedToolFactory({
1530
+ id: "google.enterprise_web_search",
1531
+ name: "enterprise_web_search",
1532
+ inputSchema: lazySchema(() => zodSchema(z7.object({})))
1533
+ });
1534
+ var fileSearchArgsBaseSchema = z8.object({
1535
+ /** The names of the file_search_stores to retrieve from.
1536
+ * Example: `fileSearchStores/my-file-search-store-123`
1537
+ */
1538
+ fileSearchStoreNames: z8.array(z8.string()).describe(
1539
+ "The names of the file_search_stores to retrieve from. Example: `fileSearchStores/my-file-search-store-123`"
1540
+ ),
1541
+ /** The number of file search retrieval chunks to retrieve. */
1542
+ topK: z8.number().int().positive().describe("The number of file search retrieval chunks to retrieve.").optional(),
1543
+ /** Metadata filter to apply to the file search retrieval documents.
1544
+ * See https://google.aip.dev/160 for the syntax of the filter expression.
1545
+ */
1546
+ metadataFilter: z8.string().describe(
1547
+ "Metadata filter to apply to the file search retrieval documents. See https://google.aip.dev/160 for the syntax of the filter expression."
1548
+ ).optional()
1549
+ }).passthrough();
1550
+ var fileSearchArgsSchema = lazySchema(
1551
+ () => zodSchema(fileSearchArgsBaseSchema)
1552
+ );
1553
+ var fileSearch = createProviderDefinedToolFactory({
1554
+ id: "google.file_search",
1555
+ name: "file_search",
1556
+ inputSchema: fileSearchArgsSchema
1557
+ });
1558
+ var googleMaps = createProviderDefinedToolFactory({
1559
+ id: "google.google_maps",
1560
+ name: "google_maps",
1561
+ inputSchema: lazySchema(() => zodSchema(z9.object({})))
1562
+ });
1563
+ var googleSearch = createProviderDefinedToolFactory({
1564
+ id: "google.google_search",
1565
+ name: "google_search",
1566
+ inputSchema: lazySchema(
1567
+ () => zodSchema(
1568
+ z10.object({
1569
+ mode: z10.enum(["MODE_DYNAMIC", "MODE_UNSPECIFIED"]).default("MODE_UNSPECIFIED"),
1570
+ dynamicThreshold: z10.number().default(1)
1571
+ })
1572
+ )
1573
+ )
1574
+ });
1575
+ var urlContext = createProviderDefinedToolFactory({
1576
+ id: "google.url_context",
1577
+ name: "url_context",
1578
+ inputSchema: lazySchema(() => zodSchema(z11.object({})))
1579
+ });
1580
+ var vertexRagStore = createProviderDefinedToolFactory({
1581
+ id: "google.vertex_rag_store",
1582
+ name: "vertex_rag_store",
1583
+ inputSchema: z12.object({
1584
+ ragCorpus: z12.string(),
1585
+ topK: z12.number().optional()
1586
+ })
1587
+ });
1588
+ var googleTools = {
1589
+ /**
1590
+ * Creates a Google search tool that gives Google direct access to real-time web content.
1591
+ * Must have name "google_search".
1592
+ */
1593
+ googleSearch,
1594
+ /**
1595
+ * Creates an Enterprise Web Search tool for grounding responses using a compliance-focused web index.
1596
+ * Designed for highly-regulated industries (finance, healthcare, public sector).
1597
+ * Does not log customer data and supports VPC service controls.
1598
+ * Must have name "enterprise_web_search".
1599
+ *
1600
+ * @note Only available on Vertex AI. Requires Gemini 2.0 or newer.
1601
+ *
1602
+ * @see https://cloud.google.com/vertex-ai/generative-ai/docs/grounding/web-grounding-enterprise
1603
+ */
1604
+ enterpriseWebSearch,
1605
+ /**
1606
+ * Creates a Google Maps grounding tool that gives the model access to Google Maps data.
1607
+ * Must have name "google_maps".
1608
+ *
1609
+ * @see https://ai.google.dev/gemini-api/docs/maps-grounding
1610
+ * @see https://cloud.google.com/vertex-ai/generative-ai/docs/grounding/grounding-with-google-maps
1611
+ */
1612
+ googleMaps,
1613
+ /**
1614
+ * Creates a URL context tool that gives Google direct access to real-time web content.
1615
+ * Must have name "url_context".
1616
+ */
1617
+ urlContext,
1618
+ /**
1619
+ * Enables Retrieval Augmented Generation (RAG) via the Gemini File Search tool.
1620
+ * Must have name "file_search".
1621
+ *
1622
+ * @param fileSearchStoreNames - Fully-qualified File Search store resource names.
1623
+ * @param metadataFilter - Optional filter expression to restrict the files that can be retrieved.
1624
+ * @param topK - Optional result limit for the number of chunks returned from File Search.
1625
+ *
1626
+ * @see https://ai.google.dev/gemini-api/docs/file-search
1627
+ */
1628
+ fileSearch,
1629
+ /**
1630
+ * A tool that enables the model to generate and run Python code.
1631
+ * Must have name "code_execution".
1632
+ *
1633
+ * @note Ensure the selected model supports Code Execution.
1634
+ * Multi-tool usage with the code execution tool is typically compatible with Gemini >=2 models.
1635
+ *
1636
+ * @see https://ai.google.dev/gemini-api/docs/code-execution (Google AI)
1637
+ * @see https://cloud.google.com/vertex-ai/generative-ai/docs/model-reference/code-execution-api (Vertex AI)
1638
+ */
1639
+ codeExecution,
1640
+ /**
1641
+ * Creates a Vertex RAG Store tool that enables the model to perform RAG searches against a Vertex RAG Store.
1642
+ * Must have name "vertex_rag_store".
1643
+ */
1644
+ vertexRagStore
1645
+ };
1646
+ var GoogleGenerativeAIImageModel = class {
1647
+ constructor(modelId, settings, config) {
1648
+ this.modelId = modelId;
1649
+ this.settings = settings;
1650
+ this.config = config;
1651
+ this.specificationVersion = "v2";
1652
+ }
1653
+ get maxImagesPerCall() {
1654
+ var _a;
1655
+ return (_a = this.settings.maxImagesPerCall) != null ? _a : 4;
1656
+ }
1657
+ get provider() {
1658
+ return this.config.provider;
1659
+ }
1660
+ async doGenerate(options) {
1661
+ var _a, _b, _c;
1662
+ const {
1663
+ prompt,
1664
+ n = 1,
1665
+ size = "1024x1024",
1666
+ aspectRatio = "1:1",
1667
+ seed,
1668
+ providerOptions,
1669
+ headers,
1670
+ abortSignal
1671
+ } = options;
1672
+ const warnings = [];
1673
+ if (size != null) {
1674
+ warnings.push({
1675
+ type: "unsupported-setting",
1676
+ setting: "size",
1677
+ details: "This model does not support the `size` option. Use `aspectRatio` instead."
1678
+ });
1679
+ }
1680
+ if (seed != null) {
1681
+ warnings.push({
1682
+ type: "unsupported-setting",
1683
+ setting: "seed",
1684
+ details: "This model does not support the `seed` option through this provider."
1685
+ });
1686
+ }
1687
+ const googleOptions = await parseProviderOptions({
1688
+ provider: "google",
1689
+ providerOptions,
1690
+ schema: googleImageProviderOptionsSchema
1691
+ });
1692
+ const currentDate = (_c = (_b = (_a = this.config._internal) == null ? void 0 : _a.currentDate) == null ? void 0 : _b.call(_a)) != null ? _c : /* @__PURE__ */ new Date();
1693
+ const parameters = {
1694
+ sampleCount: n
1695
+ };
1696
+ if (aspectRatio != null) {
1697
+ parameters.aspectRatio = aspectRatio;
1698
+ }
1699
+ if (googleOptions) {
1700
+ Object.assign(parameters, googleOptions);
1701
+ }
1702
+ const body = {
1703
+ instances: [{ prompt }],
1704
+ parameters
1705
+ };
1706
+ const { responseHeaders, value: response } = await postJsonToApi({
1707
+ url: `${this.config.baseURL}/models/${this.modelId}:predict`,
1708
+ headers: combineHeaders(await resolve(this.config.headers), headers),
1709
+ body,
1710
+ failedResponseHandler: googleFailedResponseHandler,
1711
+ successfulResponseHandler: createJsonResponseHandler(
1712
+ googleImageResponseSchema
1713
+ ),
1714
+ abortSignal,
1715
+ fetch: this.config.fetch
1716
+ });
1717
+ return {
1718
+ images: response.predictions.map(
1719
+ (p) => p.bytesBase64Encoded
1720
+ ),
1721
+ warnings: warnings != null ? warnings : [],
1722
+ providerMetadata: {
1723
+ google: {
1724
+ images: response.predictions.map((prediction) => ({
1725
+ // Add any prediction-specific metadata here
1726
+ }))
1727
+ }
1728
+ },
1729
+ response: {
1730
+ timestamp: currentDate,
1731
+ modelId: this.modelId,
1732
+ headers: responseHeaders
1733
+ }
1734
+ };
1735
+ }
1736
+ };
1737
+ var googleImageResponseSchema = lazySchema(
1738
+ () => zodSchema(
1739
+ z13.object({
1740
+ predictions: z13.array(z13.object({ bytesBase64Encoded: z13.string() })).default([])
1741
+ })
1742
+ )
1743
+ );
1744
+ var googleImageProviderOptionsSchema = lazySchema(
1745
+ () => zodSchema(
1746
+ z13.object({
1747
+ personGeneration: z13.enum(["dont_allow", "allow_adult", "allow_all"]).nullish(),
1748
+ aspectRatio: z13.enum(["1:1", "3:4", "4:3", "9:16", "16:9"]).nullish()
1749
+ })
1750
+ )
1751
+ );
1752
+ function createGoogleGenerativeAI(options = {}) {
1753
+ var _a, _b;
1754
+ const baseURL = (_a = withoutTrailingSlash(options.baseURL)) != null ? _a : "https://generativelanguage.googleapis.com/v1beta";
1755
+ const providerName = (_b = options.name) != null ? _b : "google.generative-ai";
1756
+ const getHeaders = () => withUserAgentSuffix(
1757
+ {
1758
+ "x-goog-api-key": loadApiKey({
1759
+ apiKey: options.apiKey,
1760
+ environmentVariableName: "GOOGLE_GENERATIVE_AI_API_KEY",
1761
+ description: "Google Generative AI"
1762
+ }),
1763
+ ...options.headers
1764
+ },
1765
+ `ai-sdk/google/${VERSION}`
1766
+ );
1767
+ const createChatModel = (modelId) => {
1768
+ var _a2;
1769
+ return new GoogleGenerativeAILanguageModel(modelId, {
1770
+ provider: providerName,
1771
+ baseURL,
1772
+ headers: getHeaders,
1773
+ generateId: (_a2 = options.generateId) != null ? _a2 : generateId,
1774
+ supportedUrls: () => ({
1775
+ "*": [
1776
+ // Google Generative Language "files" endpoint
1777
+ // e.g. https://generativelanguage.googleapis.com/v1beta/files/...
1778
+ new RegExp(`^${baseURL}/files/.*$`),
1779
+ // YouTube URLs (public or unlisted videos)
1780
+ new RegExp(
1781
+ `^https://(?:www\\.)?youtube\\.com/watch\\?v=[\\w-]+(?:&[\\w=&.-]*)?$`
1782
+ ),
1783
+ new RegExp(`^https://youtu\\.be/[\\w-]+(?:\\?[\\w=&.-]*)?$`)
1784
+ ]
1785
+ }),
1786
+ fetch: options.fetch
1787
+ });
1788
+ };
1789
+ const createEmbeddingModel = (modelId) => new GoogleGenerativeAIEmbeddingModel(modelId, {
1790
+ provider: providerName,
1791
+ baseURL,
1792
+ headers: getHeaders,
1793
+ fetch: options.fetch
1794
+ });
1795
+ const createImageModel = (modelId, settings = {}) => new GoogleGenerativeAIImageModel(modelId, settings, {
1796
+ provider: providerName,
1797
+ baseURL,
1798
+ headers: getHeaders,
1799
+ fetch: options.fetch
1800
+ });
1801
+ const provider = function(modelId) {
1802
+ if (new.target) {
1803
+ throw new Error(
1804
+ "The Google Generative AI model function cannot be called with the new keyword."
1805
+ );
1806
+ }
1807
+ return createChatModel(modelId);
1808
+ };
1809
+ provider.languageModel = createChatModel;
1810
+ provider.chat = createChatModel;
1811
+ provider.generativeAI = createChatModel;
1812
+ provider.embedding = createEmbeddingModel;
1813
+ provider.textEmbedding = createEmbeddingModel;
1814
+ provider.textEmbeddingModel = createEmbeddingModel;
1815
+ provider.image = createImageModel;
1816
+ provider.imageModel = createImageModel;
1817
+ provider.tools = googleTools;
1818
+ return provider;
1819
+ }
1820
+ var google = createGoogleGenerativeAI();
1821
+ export {
1822
+ VERSION,
1823
+ createGoogleGenerativeAI,
1824
+ google
1825
+ };