@ls-stack/server-i18n 0.0.0-stage → 0.6.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,1502 @@
1
+ import { _ as string, h as record, m as object, n as _enum, o as array, p as number, s as boolean, v as union, y as unknown } from "./schemas-BfUoDuyI.mjs";
2
+ import { $ as UnsupportedFunctionalityError, F as postJsonToApi, H as withoutTrailingSlash, I as resolve, N as parseProviderOptions, O as lazySchema, U as zodSchema, V as withUserAgentSuffix, W as AISDKError, Z as TooManyEmbeddingValuesForCallError, a as convertToBase64, d as createJsonErrorResponseHandler, f as createJsonResponseHandler, g as delay, k as loadApiKey, l as createEventSourceResponseHandler, m as createProviderToolFactoryWithOutputSchema, p as createProviderToolFactory, r as combineHeaders, s as convertUint8ArrayToBase64, x as getFromApi, y as generateId } from "./dist-BA5qgNhB.mjs";
3
+
4
+ //#region ../node_modules/.pnpm/@ai-sdk+google@3.0.20_zod@4.3.6/node_modules/@ai-sdk/google/dist/index.mjs
5
+ var VERSION = "3.0.20";
6
+ var googleFailedResponseHandler = createJsonErrorResponseHandler({
7
+ errorSchema: lazySchema(() => zodSchema(object({ error: object({
8
+ code: number().nullable(),
9
+ message: string(),
10
+ status: string()
11
+ }) }))),
12
+ errorToMessage: (data) => data.error.message
13
+ });
14
+ var googleGenerativeAIEmbeddingProviderOptions = lazySchema(() => zodSchema(object({
15
+ outputDimensionality: number().optional(),
16
+ taskType: _enum([
17
+ "SEMANTIC_SIMILARITY",
18
+ "CLASSIFICATION",
19
+ "CLUSTERING",
20
+ "RETRIEVAL_DOCUMENT",
21
+ "RETRIEVAL_QUERY",
22
+ "QUESTION_ANSWERING",
23
+ "FACT_VERIFICATION",
24
+ "CODE_RETRIEVAL_QUERY"
25
+ ]).optional()
26
+ })));
27
+ var GoogleGenerativeAIEmbeddingModel = class {
28
+ constructor(modelId, config) {
29
+ this.specificationVersion = "v3";
30
+ this.maxEmbeddingsPerCall = 2048;
31
+ this.supportsParallelCalls = true;
32
+ this.modelId = modelId;
33
+ this.config = config;
34
+ }
35
+ get provider() {
36
+ return this.config.provider;
37
+ }
38
+ async doEmbed({ values, headers, abortSignal, providerOptions }) {
39
+ const googleOptions = await parseProviderOptions({
40
+ provider: "google",
41
+ providerOptions,
42
+ schema: googleGenerativeAIEmbeddingProviderOptions
43
+ });
44
+ if (values.length > this.maxEmbeddingsPerCall) throw new TooManyEmbeddingValuesForCallError({
45
+ provider: this.provider,
46
+ modelId: this.modelId,
47
+ maxEmbeddingsPerCall: this.maxEmbeddingsPerCall,
48
+ values
49
+ });
50
+ const mergedHeaders = combineHeaders(await resolve(this.config.headers), headers);
51
+ if (values.length === 1) {
52
+ const { responseHeaders: responseHeaders2, value: response2, rawValue: rawValue2 } = await postJsonToApi({
53
+ url: `${this.config.baseURL}/models/${this.modelId}:embedContent`,
54
+ headers: mergedHeaders,
55
+ body: {
56
+ model: `models/${this.modelId}`,
57
+ content: { parts: [{ text: values[0] }] },
58
+ outputDimensionality: googleOptions == null ? void 0 : googleOptions.outputDimensionality,
59
+ taskType: googleOptions == null ? void 0 : googleOptions.taskType
60
+ },
61
+ failedResponseHandler: googleFailedResponseHandler,
62
+ successfulResponseHandler: createJsonResponseHandler(googleGenerativeAISingleEmbeddingResponseSchema),
63
+ abortSignal,
64
+ fetch: this.config.fetch
65
+ });
66
+ return {
67
+ warnings: [],
68
+ embeddings: [response2.embedding.values],
69
+ usage: void 0,
70
+ response: {
71
+ headers: responseHeaders2,
72
+ body: rawValue2
73
+ }
74
+ };
75
+ }
76
+ const { responseHeaders, value: response, rawValue } = await postJsonToApi({
77
+ url: `${this.config.baseURL}/models/${this.modelId}:batchEmbedContents`,
78
+ headers: mergedHeaders,
79
+ body: { requests: values.map((value) => ({
80
+ model: `models/${this.modelId}`,
81
+ content: {
82
+ role: "user",
83
+ parts: [{ text: value }]
84
+ },
85
+ outputDimensionality: googleOptions == null ? void 0 : googleOptions.outputDimensionality,
86
+ taskType: googleOptions == null ? void 0 : googleOptions.taskType
87
+ })) },
88
+ failedResponseHandler: googleFailedResponseHandler,
89
+ successfulResponseHandler: createJsonResponseHandler(googleGenerativeAITextEmbeddingResponseSchema),
90
+ abortSignal,
91
+ fetch: this.config.fetch
92
+ });
93
+ return {
94
+ warnings: [],
95
+ embeddings: response.embeddings.map((item) => item.values),
96
+ usage: void 0,
97
+ response: {
98
+ headers: responseHeaders,
99
+ body: rawValue
100
+ }
101
+ };
102
+ }
103
+ };
104
+ var googleGenerativeAITextEmbeddingResponseSchema = lazySchema(() => zodSchema(object({ embeddings: array(object({ values: array(number()) })) })));
105
+ var googleGenerativeAISingleEmbeddingResponseSchema = lazySchema(() => zodSchema(object({ embedding: object({ values: array(number()) }) })));
106
+ function convertGoogleGenerativeAIUsage(usage) {
107
+ var _a, _b, _c, _d;
108
+ if (usage == null) return {
109
+ inputTokens: {
110
+ total: void 0,
111
+ noCache: void 0,
112
+ cacheRead: void 0,
113
+ cacheWrite: void 0
114
+ },
115
+ outputTokens: {
116
+ total: void 0,
117
+ text: void 0,
118
+ reasoning: void 0
119
+ },
120
+ raw: void 0
121
+ };
122
+ const promptTokens = (_a = usage.promptTokenCount) != null ? _a : 0;
123
+ const candidatesTokens = (_b = usage.candidatesTokenCount) != null ? _b : 0;
124
+ const cachedContentTokens = (_c = usage.cachedContentTokenCount) != null ? _c : 0;
125
+ const thoughtsTokens = (_d = usage.thoughtsTokenCount) != null ? _d : 0;
126
+ return {
127
+ inputTokens: {
128
+ total: promptTokens,
129
+ noCache: promptTokens - cachedContentTokens,
130
+ cacheRead: cachedContentTokens,
131
+ cacheWrite: void 0
132
+ },
133
+ outputTokens: {
134
+ total: candidatesTokens + thoughtsTokens,
135
+ text: candidatesTokens,
136
+ reasoning: thoughtsTokens
137
+ },
138
+ raw: usage
139
+ };
140
+ }
141
+ function convertJSONSchemaToOpenAPISchema(jsonSchema, isRoot = true) {
142
+ if (jsonSchema == null) return;
143
+ if (isEmptyObjectSchema(jsonSchema)) {
144
+ if (isRoot) return;
145
+ if (typeof jsonSchema === "object" && jsonSchema.description) return {
146
+ type: "object",
147
+ description: jsonSchema.description
148
+ };
149
+ return { type: "object" };
150
+ }
151
+ if (typeof jsonSchema === "boolean") return {
152
+ type: "boolean",
153
+ properties: {}
154
+ };
155
+ const { type, description, required, properties, items, allOf, anyOf, oneOf, format, const: constValue, minLength, enum: enumValues } = jsonSchema;
156
+ const result = {};
157
+ if (description) result.description = description;
158
+ if (required) result.required = required;
159
+ if (format) result.format = format;
160
+ if (constValue !== void 0) result.enum = [constValue];
161
+ if (type) if (Array.isArray(type)) {
162
+ const hasNull = type.includes("null");
163
+ const nonNullTypes = type.filter((t) => t !== "null");
164
+ if (nonNullTypes.length === 0) result.type = "null";
165
+ else {
166
+ result.anyOf = nonNullTypes.map((t) => ({ type: t }));
167
+ if (hasNull) result.nullable = true;
168
+ }
169
+ } else result.type = type;
170
+ if (enumValues !== void 0) result.enum = enumValues;
171
+ if (properties != null) result.properties = Object.entries(properties).reduce((acc, [key, value]) => {
172
+ acc[key] = convertJSONSchemaToOpenAPISchema(value, false);
173
+ return acc;
174
+ }, {});
175
+ if (items) result.items = Array.isArray(items) ? items.map((item) => convertJSONSchemaToOpenAPISchema(item, false)) : convertJSONSchemaToOpenAPISchema(items, false);
176
+ if (allOf) result.allOf = allOf.map((item) => convertJSONSchemaToOpenAPISchema(item, false));
177
+ if (anyOf) if (anyOf.some((schema) => typeof schema === "object" && (schema == null ? void 0 : schema.type) === "null")) {
178
+ const nonNullSchemas = anyOf.filter((schema) => !(typeof schema === "object" && (schema == null ? void 0 : schema.type) === "null"));
179
+ if (nonNullSchemas.length === 1) {
180
+ const converted = convertJSONSchemaToOpenAPISchema(nonNullSchemas[0], false);
181
+ if (typeof converted === "object") {
182
+ result.nullable = true;
183
+ Object.assign(result, converted);
184
+ }
185
+ } else {
186
+ result.anyOf = nonNullSchemas.map((item) => convertJSONSchemaToOpenAPISchema(item, false));
187
+ result.nullable = true;
188
+ }
189
+ } else result.anyOf = anyOf.map((item) => convertJSONSchemaToOpenAPISchema(item, false));
190
+ if (oneOf) result.oneOf = oneOf.map((item) => convertJSONSchemaToOpenAPISchema(item, false));
191
+ if (minLength !== void 0) result.minLength = minLength;
192
+ return result;
193
+ }
194
+ function isEmptyObjectSchema(jsonSchema) {
195
+ return jsonSchema != null && typeof jsonSchema === "object" && jsonSchema.type === "object" && (jsonSchema.properties == null || Object.keys(jsonSchema.properties).length === 0) && !jsonSchema.additionalProperties;
196
+ }
197
+ function convertToGoogleGenerativeAIMessages(prompt, options) {
198
+ var _a, _b, _c;
199
+ const systemInstructionParts = [];
200
+ const contents = [];
201
+ let systemMessagesAllowed = true;
202
+ const isGemmaModel = (_a = options == null ? void 0 : options.isGemmaModel) != null ? _a : false;
203
+ const providerOptionsName = (_b = options == null ? void 0 : options.providerOptionsName) != null ? _b : "google";
204
+ for (const { role, content } of prompt) switch (role) {
205
+ case "system":
206
+ if (!systemMessagesAllowed) throw new UnsupportedFunctionalityError({ functionality: "system messages are only supported at the beginning of the conversation" });
207
+ systemInstructionParts.push({ text: content });
208
+ break;
209
+ case "user": {
210
+ systemMessagesAllowed = false;
211
+ const parts = [];
212
+ for (const part of content) switch (part.type) {
213
+ case "text":
214
+ parts.push({ text: part.text });
215
+ break;
216
+ case "file": {
217
+ const mediaType = part.mediaType === "image/*" ? "image/jpeg" : part.mediaType;
218
+ parts.push(part.data instanceof URL ? { fileData: {
219
+ mimeType: mediaType,
220
+ fileUri: part.data.toString()
221
+ } } : { inlineData: {
222
+ mimeType: mediaType,
223
+ data: convertToBase64(part.data)
224
+ } });
225
+ break;
226
+ }
227
+ }
228
+ contents.push({
229
+ role: "user",
230
+ parts
231
+ });
232
+ break;
233
+ }
234
+ case "assistant":
235
+ systemMessagesAllowed = false;
236
+ contents.push({
237
+ role: "model",
238
+ parts: content.map((part) => {
239
+ var _a2;
240
+ const providerOpts = (_a2 = part.providerOptions) == null ? void 0 : _a2[providerOptionsName];
241
+ const thoughtSignature = (providerOpts == null ? void 0 : providerOpts.thoughtSignature) != null ? String(providerOpts.thoughtSignature) : void 0;
242
+ switch (part.type) {
243
+ case "text": return part.text.length === 0 ? void 0 : {
244
+ text: part.text,
245
+ thoughtSignature
246
+ };
247
+ case "reasoning": return part.text.length === 0 ? void 0 : {
248
+ text: part.text,
249
+ thought: true,
250
+ thoughtSignature
251
+ };
252
+ case "file":
253
+ if (part.data instanceof URL) throw new UnsupportedFunctionalityError({ functionality: "File data URLs in assistant messages are not supported" });
254
+ return {
255
+ inlineData: {
256
+ mimeType: part.mediaType,
257
+ data: convertToBase64(part.data)
258
+ },
259
+ thoughtSignature
260
+ };
261
+ case "tool-call": return {
262
+ functionCall: {
263
+ name: part.toolName,
264
+ args: part.input
265
+ },
266
+ thoughtSignature
267
+ };
268
+ }
269
+ }).filter((part) => part !== void 0)
270
+ });
271
+ break;
272
+ case "tool": {
273
+ systemMessagesAllowed = false;
274
+ const parts = [];
275
+ for (const part of content) {
276
+ if (part.type === "tool-approval-response") continue;
277
+ const output = part.output;
278
+ if (output.type === "content") for (const contentPart of output.value) switch (contentPart.type) {
279
+ case "text":
280
+ parts.push({ functionResponse: {
281
+ name: part.toolName,
282
+ response: {
283
+ name: part.toolName,
284
+ content: contentPart.text
285
+ }
286
+ } });
287
+ break;
288
+ case "image-data":
289
+ parts.push({ inlineData: {
290
+ mimeType: contentPart.mediaType,
291
+ data: contentPart.data
292
+ } }, { text: "Tool executed successfully and returned this image as a response" });
293
+ break;
294
+ default:
295
+ parts.push({ text: JSON.stringify(contentPart) });
296
+ break;
297
+ }
298
+ else parts.push({ functionResponse: {
299
+ name: part.toolName,
300
+ response: {
301
+ name: part.toolName,
302
+ content: output.type === "execution-denied" ? (_c = output.reason) != null ? _c : "Tool execution denied." : output.value
303
+ }
304
+ } });
305
+ }
306
+ contents.push({
307
+ role: "user",
308
+ parts
309
+ });
310
+ break;
311
+ }
312
+ }
313
+ if (isGemmaModel && systemInstructionParts.length > 0 && contents.length > 0 && contents[0].role === "user") {
314
+ const systemText = systemInstructionParts.map((part) => part.text).join("\n\n");
315
+ contents[0].parts.unshift({ text: systemText + "\n\n" });
316
+ }
317
+ return {
318
+ systemInstruction: systemInstructionParts.length > 0 && !isGemmaModel ? { parts: systemInstructionParts } : void 0,
319
+ contents
320
+ };
321
+ }
322
+ function getModelPath(modelId) {
323
+ return modelId.includes("/") ? modelId : `models/${modelId}`;
324
+ }
325
+ var googleGenerativeAIProviderOptions = lazySchema(() => zodSchema(object({
326
+ responseModalities: array(_enum(["TEXT", "IMAGE"])).optional(),
327
+ thinkingConfig: object({
328
+ thinkingBudget: number().optional(),
329
+ includeThoughts: boolean().optional(),
330
+ thinkingLevel: _enum([
331
+ "minimal",
332
+ "low",
333
+ "medium",
334
+ "high"
335
+ ]).optional()
336
+ }).optional(),
337
+ cachedContent: string().optional(),
338
+ structuredOutputs: boolean().optional(),
339
+ safetySettings: array(object({
340
+ category: _enum([
341
+ "HARM_CATEGORY_UNSPECIFIED",
342
+ "HARM_CATEGORY_HATE_SPEECH",
343
+ "HARM_CATEGORY_DANGEROUS_CONTENT",
344
+ "HARM_CATEGORY_HARASSMENT",
345
+ "HARM_CATEGORY_SEXUALLY_EXPLICIT",
346
+ "HARM_CATEGORY_CIVIC_INTEGRITY"
347
+ ]),
348
+ threshold: _enum([
349
+ "HARM_BLOCK_THRESHOLD_UNSPECIFIED",
350
+ "BLOCK_LOW_AND_ABOVE",
351
+ "BLOCK_MEDIUM_AND_ABOVE",
352
+ "BLOCK_ONLY_HIGH",
353
+ "BLOCK_NONE",
354
+ "OFF"
355
+ ])
356
+ })).optional(),
357
+ threshold: _enum([
358
+ "HARM_BLOCK_THRESHOLD_UNSPECIFIED",
359
+ "BLOCK_LOW_AND_ABOVE",
360
+ "BLOCK_MEDIUM_AND_ABOVE",
361
+ "BLOCK_ONLY_HIGH",
362
+ "BLOCK_NONE",
363
+ "OFF"
364
+ ]).optional(),
365
+ audioTimestamp: boolean().optional(),
366
+ labels: record(string(), string()).optional(),
367
+ mediaResolution: _enum([
368
+ "MEDIA_RESOLUTION_UNSPECIFIED",
369
+ "MEDIA_RESOLUTION_LOW",
370
+ "MEDIA_RESOLUTION_MEDIUM",
371
+ "MEDIA_RESOLUTION_HIGH"
372
+ ]).optional(),
373
+ imageConfig: object({
374
+ aspectRatio: _enum([
375
+ "1:1",
376
+ "2:3",
377
+ "3:2",
378
+ "3:4",
379
+ "4:3",
380
+ "4:5",
381
+ "5:4",
382
+ "9:16",
383
+ "16:9",
384
+ "21:9"
385
+ ]).optional(),
386
+ imageSize: _enum([
387
+ "1K",
388
+ "2K",
389
+ "4K"
390
+ ]).optional()
391
+ }).optional(),
392
+ retrievalConfig: object({ latLng: object({
393
+ latitude: number(),
394
+ longitude: number()
395
+ }).optional() }).optional()
396
+ })));
397
+ function prepareTools({ tools, toolChoice, modelId }) {
398
+ var _a;
399
+ tools = (tools == null ? void 0 : tools.length) ? tools : void 0;
400
+ const toolWarnings = [];
401
+ const isLatest = [
402
+ "gemini-flash-latest",
403
+ "gemini-flash-lite-latest",
404
+ "gemini-pro-latest"
405
+ ].some((id) => id === modelId);
406
+ const isGemini2orNewer = modelId.includes("gemini-2") || modelId.includes("gemini-3") || isLatest;
407
+ const supportsDynamicRetrieval = modelId.includes("gemini-1.5-flash") && !modelId.includes("-8b");
408
+ const supportsFileSearch = modelId.includes("gemini-2.5") || modelId.includes("gemini-3");
409
+ if (tools == null) return {
410
+ tools: void 0,
411
+ toolConfig: void 0,
412
+ toolWarnings
413
+ };
414
+ const hasFunctionTools = tools.some((tool) => tool.type === "function");
415
+ const hasProviderTools = tools.some((tool) => tool.type === "provider");
416
+ if (hasFunctionTools && hasProviderTools) toolWarnings.push({
417
+ type: "unsupported",
418
+ feature: `combination of function and provider-defined tools`
419
+ });
420
+ if (hasProviderTools) {
421
+ const googleTools2 = [];
422
+ tools.filter((tool) => tool.type === "provider").forEach((tool) => {
423
+ switch (tool.id) {
424
+ case "google.google_search":
425
+ if (isGemini2orNewer) googleTools2.push({ googleSearch: {} });
426
+ else if (supportsDynamicRetrieval) googleTools2.push({ googleSearchRetrieval: { dynamicRetrievalConfig: {
427
+ mode: tool.args.mode,
428
+ dynamicThreshold: tool.args.dynamicThreshold
429
+ } } });
430
+ else googleTools2.push({ googleSearchRetrieval: {} });
431
+ break;
432
+ case "google.enterprise_web_search":
433
+ if (isGemini2orNewer) googleTools2.push({ enterpriseWebSearch: {} });
434
+ else toolWarnings.push({
435
+ type: "unsupported",
436
+ feature: `provider-defined tool ${tool.id}`,
437
+ details: "Enterprise Web Search requires Gemini 2.0 or newer."
438
+ });
439
+ break;
440
+ case "google.url_context":
441
+ if (isGemini2orNewer) googleTools2.push({ urlContext: {} });
442
+ else toolWarnings.push({
443
+ type: "unsupported",
444
+ feature: `provider-defined tool ${tool.id}`,
445
+ details: "The URL context tool is not supported with other Gemini models than Gemini 2."
446
+ });
447
+ break;
448
+ case "google.code_execution":
449
+ if (isGemini2orNewer) googleTools2.push({ codeExecution: {} });
450
+ else toolWarnings.push({
451
+ type: "unsupported",
452
+ feature: `provider-defined tool ${tool.id}`,
453
+ details: "The code execution tools is not supported with other Gemini models than Gemini 2."
454
+ });
455
+ break;
456
+ case "google.file_search":
457
+ if (supportsFileSearch) googleTools2.push({ fileSearch: { ...tool.args } });
458
+ else toolWarnings.push({
459
+ type: "unsupported",
460
+ feature: `provider-defined tool ${tool.id}`,
461
+ details: "The file search tool is only supported with Gemini 2.5 models and Gemini 3 models."
462
+ });
463
+ break;
464
+ case "google.vertex_rag_store":
465
+ if (isGemini2orNewer) googleTools2.push({ retrieval: { vertex_rag_store: {
466
+ rag_resources: { rag_corpus: tool.args.ragCorpus },
467
+ similarity_top_k: tool.args.topK
468
+ } } });
469
+ else toolWarnings.push({
470
+ type: "unsupported",
471
+ feature: `provider-defined tool ${tool.id}`,
472
+ details: "The RAG store tool is not supported with other Gemini models than Gemini 2."
473
+ });
474
+ break;
475
+ case "google.google_maps":
476
+ if (isGemini2orNewer) googleTools2.push({ googleMaps: {} });
477
+ else toolWarnings.push({
478
+ type: "unsupported",
479
+ feature: `provider-defined tool ${tool.id}`,
480
+ details: "The Google Maps grounding tool is not supported with Gemini models other than Gemini 2 or newer."
481
+ });
482
+ break;
483
+ default:
484
+ toolWarnings.push({
485
+ type: "unsupported",
486
+ feature: `provider-defined tool ${tool.id}`
487
+ });
488
+ break;
489
+ }
490
+ });
491
+ return {
492
+ tools: googleTools2.length > 0 ? googleTools2 : void 0,
493
+ toolConfig: void 0,
494
+ toolWarnings
495
+ };
496
+ }
497
+ const functionDeclarations = [];
498
+ for (const tool of tools) switch (tool.type) {
499
+ case "function":
500
+ functionDeclarations.push({
501
+ name: tool.name,
502
+ description: (_a = tool.description) != null ? _a : "",
503
+ parameters: convertJSONSchemaToOpenAPISchema(tool.inputSchema)
504
+ });
505
+ break;
506
+ default:
507
+ toolWarnings.push({
508
+ type: "unsupported",
509
+ feature: `function tool ${tool.name}`
510
+ });
511
+ break;
512
+ }
513
+ if (toolChoice == null) return {
514
+ tools: [{ functionDeclarations }],
515
+ toolConfig: void 0,
516
+ toolWarnings
517
+ };
518
+ const type = toolChoice.type;
519
+ switch (type) {
520
+ case "auto": return {
521
+ tools: [{ functionDeclarations }],
522
+ toolConfig: { functionCallingConfig: { mode: "AUTO" } },
523
+ toolWarnings
524
+ };
525
+ case "none": return {
526
+ tools: [{ functionDeclarations }],
527
+ toolConfig: { functionCallingConfig: { mode: "NONE" } },
528
+ toolWarnings
529
+ };
530
+ case "required": return {
531
+ tools: [{ functionDeclarations }],
532
+ toolConfig: { functionCallingConfig: { mode: "ANY" } },
533
+ toolWarnings
534
+ };
535
+ case "tool": return {
536
+ tools: [{ functionDeclarations }],
537
+ toolConfig: { functionCallingConfig: {
538
+ mode: "ANY",
539
+ allowedFunctionNames: [toolChoice.toolName]
540
+ } },
541
+ toolWarnings
542
+ };
543
+ default: throw new UnsupportedFunctionalityError({ functionality: `tool choice type: ${type}` });
544
+ }
545
+ }
546
+ function mapGoogleGenerativeAIFinishReason({ finishReason, hasToolCalls }) {
547
+ switch (finishReason) {
548
+ case "STOP": return hasToolCalls ? "tool-calls" : "stop";
549
+ case "MAX_TOKENS": return "length";
550
+ case "IMAGE_SAFETY":
551
+ case "RECITATION":
552
+ case "SAFETY":
553
+ case "BLOCKLIST":
554
+ case "PROHIBITED_CONTENT":
555
+ case "SPII": return "content-filter";
556
+ case "MALFORMED_FUNCTION_CALL": return "error";
557
+ default: return "other";
558
+ }
559
+ }
560
+ var GoogleGenerativeAILanguageModel = class {
561
+ constructor(modelId, config) {
562
+ this.specificationVersion = "v3";
563
+ var _a;
564
+ this.modelId = modelId;
565
+ this.config = config;
566
+ this.generateId = (_a = config.generateId) != null ? _a : generateId;
567
+ }
568
+ get provider() {
569
+ return this.config.provider;
570
+ }
571
+ get supportedUrls() {
572
+ var _a, _b, _c;
573
+ return (_c = (_b = (_a = this.config).supportedUrls) == null ? void 0 : _b.call(_a)) != null ? _c : {};
574
+ }
575
+ async getArgs({ prompt, maxOutputTokens, temperature, topP, topK, frequencyPenalty, presencePenalty, stopSequences, responseFormat, seed, tools, toolChoice, providerOptions }) {
576
+ var _a;
577
+ const warnings = [];
578
+ const providerOptionsName = this.config.provider.includes("vertex") ? "vertex" : "google";
579
+ let googleOptions = await parseProviderOptions({
580
+ provider: providerOptionsName,
581
+ providerOptions,
582
+ schema: googleGenerativeAIProviderOptions
583
+ });
584
+ if (googleOptions == null && providerOptionsName !== "google") googleOptions = await parseProviderOptions({
585
+ provider: "google",
586
+ providerOptions,
587
+ schema: googleGenerativeAIProviderOptions
588
+ });
589
+ if ((tools == null ? void 0 : tools.some((tool) => tool.type === "provider" && tool.id === "google.vertex_rag_store")) && !this.config.provider.startsWith("google.vertex.")) warnings.push({
590
+ type: "other",
591
+ 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}).`
592
+ });
593
+ const isGemmaModel = this.modelId.toLowerCase().startsWith("gemma-");
594
+ const { contents, systemInstruction } = convertToGoogleGenerativeAIMessages(prompt, {
595
+ isGemmaModel,
596
+ providerOptionsName
597
+ });
598
+ const { tools: googleTools2, toolConfig: googleToolConfig, toolWarnings } = prepareTools({
599
+ tools,
600
+ toolChoice,
601
+ modelId: this.modelId
602
+ });
603
+ return {
604
+ args: {
605
+ generationConfig: {
606
+ maxOutputTokens,
607
+ temperature,
608
+ topK,
609
+ topP,
610
+ frequencyPenalty,
611
+ presencePenalty,
612
+ stopSequences,
613
+ seed,
614
+ responseMimeType: (responseFormat == null ? void 0 : responseFormat.type) === "json" ? "application/json" : void 0,
615
+ responseSchema: (responseFormat == null ? void 0 : responseFormat.type) === "json" && responseFormat.schema != null && ((_a = googleOptions == null ? void 0 : googleOptions.structuredOutputs) != null ? _a : true) ? convertJSONSchemaToOpenAPISchema(responseFormat.schema) : void 0,
616
+ ...(googleOptions == null ? void 0 : googleOptions.audioTimestamp) && { audioTimestamp: googleOptions.audioTimestamp },
617
+ responseModalities: googleOptions == null ? void 0 : googleOptions.responseModalities,
618
+ thinkingConfig: googleOptions == null ? void 0 : googleOptions.thinkingConfig,
619
+ ...(googleOptions == null ? void 0 : googleOptions.mediaResolution) && { mediaResolution: googleOptions.mediaResolution },
620
+ ...(googleOptions == null ? void 0 : googleOptions.imageConfig) && { imageConfig: googleOptions.imageConfig }
621
+ },
622
+ contents,
623
+ systemInstruction: isGemmaModel ? void 0 : systemInstruction,
624
+ safetySettings: googleOptions == null ? void 0 : googleOptions.safetySettings,
625
+ tools: googleTools2,
626
+ toolConfig: (googleOptions == null ? void 0 : googleOptions.retrievalConfig) ? {
627
+ ...googleToolConfig,
628
+ retrievalConfig: googleOptions.retrievalConfig
629
+ } : googleToolConfig,
630
+ cachedContent: googleOptions == null ? void 0 : googleOptions.cachedContent,
631
+ labels: googleOptions == null ? void 0 : googleOptions.labels
632
+ },
633
+ warnings: [...warnings, ...toolWarnings],
634
+ providerOptionsName
635
+ };
636
+ }
637
+ async doGenerate(options) {
638
+ var _a, _b, _c, _d, _e, _f, _g, _h, _i;
639
+ const { args, warnings, providerOptionsName } = await this.getArgs(options);
640
+ const mergedHeaders = combineHeaders(await resolve(this.config.headers), options.headers);
641
+ const { responseHeaders, value: response, rawValue: rawResponse } = await postJsonToApi({
642
+ url: `${this.config.baseURL}/${getModelPath(this.modelId)}:generateContent`,
643
+ headers: mergedHeaders,
644
+ body: args,
645
+ failedResponseHandler: googleFailedResponseHandler,
646
+ successfulResponseHandler: createJsonResponseHandler(responseSchema),
647
+ abortSignal: options.abortSignal,
648
+ fetch: this.config.fetch
649
+ });
650
+ const candidate = response.candidates[0];
651
+ const content = [];
652
+ const parts = (_b = (_a = candidate.content) == null ? void 0 : _a.parts) != null ? _b : [];
653
+ const usageMetadata = response.usageMetadata;
654
+ let lastCodeExecutionToolCallId;
655
+ for (const part of parts) if ("executableCode" in part && ((_c = part.executableCode) == null ? void 0 : _c.code)) {
656
+ const toolCallId = this.config.generateId();
657
+ lastCodeExecutionToolCallId = toolCallId;
658
+ content.push({
659
+ type: "tool-call",
660
+ toolCallId,
661
+ toolName: "code_execution",
662
+ input: JSON.stringify(part.executableCode),
663
+ providerExecuted: true
664
+ });
665
+ } else if ("codeExecutionResult" in part && part.codeExecutionResult) {
666
+ content.push({
667
+ type: "tool-result",
668
+ toolCallId: lastCodeExecutionToolCallId,
669
+ toolName: "code_execution",
670
+ result: {
671
+ outcome: part.codeExecutionResult.outcome,
672
+ output: part.codeExecutionResult.output
673
+ }
674
+ });
675
+ lastCodeExecutionToolCallId = void 0;
676
+ } else if ("text" in part && part.text != null && part.text.length > 0) content.push({
677
+ type: part.thought === true ? "reasoning" : "text",
678
+ text: part.text,
679
+ providerMetadata: part.thoughtSignature ? { [providerOptionsName]: { thoughtSignature: part.thoughtSignature } } : void 0
680
+ });
681
+ else if ("functionCall" in part) content.push({
682
+ type: "tool-call",
683
+ toolCallId: this.config.generateId(),
684
+ toolName: part.functionCall.name,
685
+ input: JSON.stringify(part.functionCall.args),
686
+ providerMetadata: part.thoughtSignature ? { [providerOptionsName]: { thoughtSignature: part.thoughtSignature } } : void 0
687
+ });
688
+ else if ("inlineData" in part) content.push({
689
+ type: "file",
690
+ data: part.inlineData.data,
691
+ mediaType: part.inlineData.mimeType,
692
+ providerMetadata: part.thoughtSignature ? { [providerOptionsName]: { thoughtSignature: part.thoughtSignature } } : void 0
693
+ });
694
+ const sources = (_d = extractSources({
695
+ groundingMetadata: candidate.groundingMetadata,
696
+ generateId: this.config.generateId
697
+ })) != null ? _d : [];
698
+ for (const source of sources) content.push(source);
699
+ return {
700
+ content,
701
+ finishReason: {
702
+ unified: mapGoogleGenerativeAIFinishReason({
703
+ finishReason: candidate.finishReason,
704
+ hasToolCalls: content.some((part) => part.type === "tool-call" && !part.providerExecuted)
705
+ }),
706
+ raw: (_e = candidate.finishReason) != null ? _e : void 0
707
+ },
708
+ usage: convertGoogleGenerativeAIUsage(usageMetadata),
709
+ warnings,
710
+ providerMetadata: { [providerOptionsName]: {
711
+ promptFeedback: (_f = response.promptFeedback) != null ? _f : null,
712
+ groundingMetadata: (_g = candidate.groundingMetadata) != null ? _g : null,
713
+ urlContextMetadata: (_h = candidate.urlContextMetadata) != null ? _h : null,
714
+ safetyRatings: (_i = candidate.safetyRatings) != null ? _i : null,
715
+ usageMetadata: usageMetadata != null ? usageMetadata : null
716
+ } },
717
+ request: { body: args },
718
+ response: {
719
+ headers: responseHeaders,
720
+ body: rawResponse
721
+ }
722
+ };
723
+ }
724
+ async doStream(options) {
725
+ const { args, warnings, providerOptionsName } = await this.getArgs(options);
726
+ const headers = combineHeaders(await resolve(this.config.headers), options.headers);
727
+ const { responseHeaders, value: response } = await postJsonToApi({
728
+ url: `${this.config.baseURL}/${getModelPath(this.modelId)}:streamGenerateContent?alt=sse`,
729
+ headers,
730
+ body: args,
731
+ failedResponseHandler: googleFailedResponseHandler,
732
+ successfulResponseHandler: createEventSourceResponseHandler(chunkSchema),
733
+ abortSignal: options.abortSignal,
734
+ fetch: this.config.fetch
735
+ });
736
+ let finishReason = {
737
+ unified: "other",
738
+ raw: void 0
739
+ };
740
+ let usage = void 0;
741
+ let providerMetadata = void 0;
742
+ const generateId3 = this.config.generateId;
743
+ let hasToolCalls = false;
744
+ let currentTextBlockId = null;
745
+ let currentReasoningBlockId = null;
746
+ let blockCounter = 0;
747
+ const emittedSourceUrls = /* @__PURE__ */ new Set();
748
+ let lastCodeExecutionToolCallId;
749
+ return {
750
+ stream: response.pipeThrough(new TransformStream({
751
+ start(controller) {
752
+ controller.enqueue({
753
+ type: "stream-start",
754
+ warnings
755
+ });
756
+ },
757
+ transform(chunk, controller) {
758
+ var _a, _b, _c, _d, _e, _f, _g;
759
+ if (options.includeRawChunks) controller.enqueue({
760
+ type: "raw",
761
+ rawValue: chunk.rawValue
762
+ });
763
+ if (!chunk.success) {
764
+ controller.enqueue({
765
+ type: "error",
766
+ error: chunk.error
767
+ });
768
+ return;
769
+ }
770
+ const value = chunk.value;
771
+ const usageMetadata = value.usageMetadata;
772
+ if (usageMetadata != null) usage = usageMetadata;
773
+ const candidate = (_a = value.candidates) == null ? void 0 : _a[0];
774
+ if (candidate == null) return;
775
+ const content = candidate.content;
776
+ const sources = extractSources({
777
+ groundingMetadata: candidate.groundingMetadata,
778
+ generateId: generateId3
779
+ });
780
+ if (sources != null) {
781
+ for (const source of sources) if (source.sourceType === "url" && !emittedSourceUrls.has(source.url)) {
782
+ emittedSourceUrls.add(source.url);
783
+ controller.enqueue(source);
784
+ }
785
+ }
786
+ if (content != null) {
787
+ const parts = (_b = content.parts) != null ? _b : [];
788
+ for (const part of parts) if ("executableCode" in part && ((_c = part.executableCode) == null ? void 0 : _c.code)) {
789
+ const toolCallId = generateId3();
790
+ lastCodeExecutionToolCallId = toolCallId;
791
+ controller.enqueue({
792
+ type: "tool-call",
793
+ toolCallId,
794
+ toolName: "code_execution",
795
+ input: JSON.stringify(part.executableCode),
796
+ providerExecuted: true
797
+ });
798
+ } else if ("codeExecutionResult" in part && part.codeExecutionResult) {
799
+ const toolCallId = lastCodeExecutionToolCallId;
800
+ if (toolCallId) {
801
+ controller.enqueue({
802
+ type: "tool-result",
803
+ toolCallId,
804
+ toolName: "code_execution",
805
+ result: {
806
+ outcome: part.codeExecutionResult.outcome,
807
+ output: part.codeExecutionResult.output
808
+ }
809
+ });
810
+ lastCodeExecutionToolCallId = void 0;
811
+ }
812
+ } else if ("text" in part && part.text != null && part.text.length > 0) if (part.thought === true) {
813
+ if (currentTextBlockId !== null) {
814
+ controller.enqueue({
815
+ type: "text-end",
816
+ id: currentTextBlockId
817
+ });
818
+ currentTextBlockId = null;
819
+ }
820
+ if (currentReasoningBlockId === null) {
821
+ currentReasoningBlockId = String(blockCounter++);
822
+ controller.enqueue({
823
+ type: "reasoning-start",
824
+ id: currentReasoningBlockId,
825
+ providerMetadata: part.thoughtSignature ? { [providerOptionsName]: { thoughtSignature: part.thoughtSignature } } : void 0
826
+ });
827
+ }
828
+ controller.enqueue({
829
+ type: "reasoning-delta",
830
+ id: currentReasoningBlockId,
831
+ delta: part.text,
832
+ providerMetadata: part.thoughtSignature ? { [providerOptionsName]: { thoughtSignature: part.thoughtSignature } } : void 0
833
+ });
834
+ } else {
835
+ if (currentReasoningBlockId !== null) {
836
+ controller.enqueue({
837
+ type: "reasoning-end",
838
+ id: currentReasoningBlockId
839
+ });
840
+ currentReasoningBlockId = null;
841
+ }
842
+ if (currentTextBlockId === null) {
843
+ currentTextBlockId = String(blockCounter++);
844
+ controller.enqueue({
845
+ type: "text-start",
846
+ id: currentTextBlockId,
847
+ providerMetadata: part.thoughtSignature ? { [providerOptionsName]: { thoughtSignature: part.thoughtSignature } } : void 0
848
+ });
849
+ }
850
+ controller.enqueue({
851
+ type: "text-delta",
852
+ id: currentTextBlockId,
853
+ delta: part.text,
854
+ providerMetadata: part.thoughtSignature ? { [providerOptionsName]: { thoughtSignature: part.thoughtSignature } } : void 0
855
+ });
856
+ }
857
+ else if ("inlineData" in part) controller.enqueue({
858
+ type: "file",
859
+ mediaType: part.inlineData.mimeType,
860
+ data: part.inlineData.data
861
+ });
862
+ const toolCallDeltas = getToolCallsFromParts({
863
+ parts: content.parts,
864
+ generateId: generateId3,
865
+ providerOptionsName
866
+ });
867
+ if (toolCallDeltas != null) for (const toolCall of toolCallDeltas) {
868
+ controller.enqueue({
869
+ type: "tool-input-start",
870
+ id: toolCall.toolCallId,
871
+ toolName: toolCall.toolName,
872
+ providerMetadata: toolCall.providerMetadata
873
+ });
874
+ controller.enqueue({
875
+ type: "tool-input-delta",
876
+ id: toolCall.toolCallId,
877
+ delta: toolCall.args,
878
+ providerMetadata: toolCall.providerMetadata
879
+ });
880
+ controller.enqueue({
881
+ type: "tool-input-end",
882
+ id: toolCall.toolCallId,
883
+ providerMetadata: toolCall.providerMetadata
884
+ });
885
+ controller.enqueue({
886
+ type: "tool-call",
887
+ toolCallId: toolCall.toolCallId,
888
+ toolName: toolCall.toolName,
889
+ input: toolCall.args,
890
+ providerMetadata: toolCall.providerMetadata
891
+ });
892
+ hasToolCalls = true;
893
+ }
894
+ }
895
+ if (candidate.finishReason != null) {
896
+ finishReason = {
897
+ unified: mapGoogleGenerativeAIFinishReason({
898
+ finishReason: candidate.finishReason,
899
+ hasToolCalls
900
+ }),
901
+ raw: candidate.finishReason
902
+ };
903
+ providerMetadata = { [providerOptionsName]: {
904
+ promptFeedback: (_d = value.promptFeedback) != null ? _d : null,
905
+ groundingMetadata: (_e = candidate.groundingMetadata) != null ? _e : null,
906
+ urlContextMetadata: (_f = candidate.urlContextMetadata) != null ? _f : null,
907
+ safetyRatings: (_g = candidate.safetyRatings) != null ? _g : null
908
+ } };
909
+ if (usageMetadata != null) providerMetadata[providerOptionsName].usageMetadata = usageMetadata;
910
+ }
911
+ },
912
+ flush(controller) {
913
+ if (currentTextBlockId !== null) controller.enqueue({
914
+ type: "text-end",
915
+ id: currentTextBlockId
916
+ });
917
+ if (currentReasoningBlockId !== null) controller.enqueue({
918
+ type: "reasoning-end",
919
+ id: currentReasoningBlockId
920
+ });
921
+ controller.enqueue({
922
+ type: "finish",
923
+ finishReason,
924
+ usage: convertGoogleGenerativeAIUsage(usage),
925
+ providerMetadata
926
+ });
927
+ }
928
+ })),
929
+ response: { headers: responseHeaders },
930
+ request: { body: args }
931
+ };
932
+ }
933
+ };
934
+ function getToolCallsFromParts({ parts, generateId: generateId3, providerOptionsName }) {
935
+ const functionCallParts = parts == null ? void 0 : parts.filter((part) => "functionCall" in part);
936
+ return functionCallParts == null || functionCallParts.length === 0 ? void 0 : functionCallParts.map((part) => ({
937
+ type: "tool-call",
938
+ toolCallId: generateId3(),
939
+ toolName: part.functionCall.name,
940
+ args: JSON.stringify(part.functionCall.args),
941
+ providerMetadata: part.thoughtSignature ? { [providerOptionsName]: { thoughtSignature: part.thoughtSignature } } : void 0
942
+ }));
943
+ }
944
+ function extractSources({ groundingMetadata, generateId: generateId3 }) {
945
+ var _a, _b, _c, _d, _e;
946
+ if (!(groundingMetadata == null ? void 0 : groundingMetadata.groundingChunks)) return;
947
+ const sources = [];
948
+ for (const chunk of groundingMetadata.groundingChunks) if (chunk.web != null) sources.push({
949
+ type: "source",
950
+ sourceType: "url",
951
+ id: generateId3(),
952
+ url: chunk.web.uri,
953
+ title: (_a = chunk.web.title) != null ? _a : void 0
954
+ });
955
+ else if (chunk.retrievedContext != null) {
956
+ const uri = chunk.retrievedContext.uri;
957
+ const fileSearchStore = chunk.retrievedContext.fileSearchStore;
958
+ if (uri && (uri.startsWith("http://") || uri.startsWith("https://"))) sources.push({
959
+ type: "source",
960
+ sourceType: "url",
961
+ id: generateId3(),
962
+ url: uri,
963
+ title: (_b = chunk.retrievedContext.title) != null ? _b : void 0
964
+ });
965
+ else if (uri) {
966
+ const title = (_c = chunk.retrievedContext.title) != null ? _c : "Unknown Document";
967
+ let mediaType = "application/octet-stream";
968
+ let filename = void 0;
969
+ if (uri.endsWith(".pdf")) {
970
+ mediaType = "application/pdf";
971
+ filename = uri.split("/").pop();
972
+ } else if (uri.endsWith(".txt")) {
973
+ mediaType = "text/plain";
974
+ filename = uri.split("/").pop();
975
+ } else if (uri.endsWith(".docx")) {
976
+ mediaType = "application/vnd.openxmlformats-officedocument.wordprocessingml.document";
977
+ filename = uri.split("/").pop();
978
+ } else if (uri.endsWith(".doc")) {
979
+ mediaType = "application/msword";
980
+ filename = uri.split("/").pop();
981
+ } else if (uri.match(/\.(md|markdown)$/)) {
982
+ mediaType = "text/markdown";
983
+ filename = uri.split("/").pop();
984
+ } else filename = uri.split("/").pop();
985
+ sources.push({
986
+ type: "source",
987
+ sourceType: "document",
988
+ id: generateId3(),
989
+ mediaType,
990
+ title,
991
+ filename
992
+ });
993
+ } else if (fileSearchStore) {
994
+ const title = (_d = chunk.retrievedContext.title) != null ? _d : "Unknown Document";
995
+ sources.push({
996
+ type: "source",
997
+ sourceType: "document",
998
+ id: generateId3(),
999
+ mediaType: "application/octet-stream",
1000
+ title,
1001
+ filename: fileSearchStore.split("/").pop()
1002
+ });
1003
+ }
1004
+ } else if (chunk.maps != null) {
1005
+ if (chunk.maps.uri) sources.push({
1006
+ type: "source",
1007
+ sourceType: "url",
1008
+ id: generateId3(),
1009
+ url: chunk.maps.uri,
1010
+ title: (_e = chunk.maps.title) != null ? _e : void 0
1011
+ });
1012
+ }
1013
+ return sources.length > 0 ? sources : void 0;
1014
+ }
1015
+ var getGroundingMetadataSchema = () => object({
1016
+ webSearchQueries: array(string()).nullish(),
1017
+ retrievalQueries: array(string()).nullish(),
1018
+ searchEntryPoint: object({ renderedContent: string() }).nullish(),
1019
+ groundingChunks: array(object({
1020
+ web: object({
1021
+ uri: string(),
1022
+ title: string().nullish()
1023
+ }).nullish(),
1024
+ retrievedContext: object({
1025
+ uri: string().nullish(),
1026
+ title: string().nullish(),
1027
+ text: string().nullish(),
1028
+ fileSearchStore: string().nullish()
1029
+ }).nullish(),
1030
+ maps: object({
1031
+ uri: string().nullish(),
1032
+ title: string().nullish(),
1033
+ text: string().nullish(),
1034
+ placeId: string().nullish()
1035
+ }).nullish()
1036
+ })).nullish(),
1037
+ groundingSupports: array(object({
1038
+ segment: object({
1039
+ startIndex: number().nullish(),
1040
+ endIndex: number().nullish(),
1041
+ text: string().nullish()
1042
+ }).nullish(),
1043
+ segment_text: string().nullish(),
1044
+ groundingChunkIndices: array(number()).nullish(),
1045
+ supportChunkIndices: array(number()).nullish(),
1046
+ confidenceScores: array(number()).nullish(),
1047
+ confidenceScore: array(number()).nullish()
1048
+ })).nullish(),
1049
+ retrievalMetadata: union([object({ webDynamicRetrievalScore: number() }), object({})]).nullish()
1050
+ });
1051
+ var getContentSchema = () => object({ parts: array(union([
1052
+ object({
1053
+ functionCall: object({
1054
+ name: string(),
1055
+ args: unknown()
1056
+ }),
1057
+ thoughtSignature: string().nullish()
1058
+ }),
1059
+ object({
1060
+ inlineData: object({
1061
+ mimeType: string(),
1062
+ data: string()
1063
+ }),
1064
+ thoughtSignature: string().nullish()
1065
+ }),
1066
+ object({
1067
+ executableCode: object({
1068
+ language: string(),
1069
+ code: string()
1070
+ }).nullish(),
1071
+ codeExecutionResult: object({
1072
+ outcome: string(),
1073
+ output: string()
1074
+ }).nullish(),
1075
+ text: string().nullish(),
1076
+ thought: boolean().nullish(),
1077
+ thoughtSignature: string().nullish()
1078
+ })
1079
+ ])).nullish() });
1080
+ var getSafetyRatingSchema = () => object({
1081
+ category: string().nullish(),
1082
+ probability: string().nullish(),
1083
+ probabilityScore: number().nullish(),
1084
+ severity: string().nullish(),
1085
+ severityScore: number().nullish(),
1086
+ blocked: boolean().nullish()
1087
+ });
1088
+ var usageSchema = object({
1089
+ cachedContentTokenCount: number().nullish(),
1090
+ thoughtsTokenCount: number().nullish(),
1091
+ promptTokenCount: number().nullish(),
1092
+ candidatesTokenCount: number().nullish(),
1093
+ totalTokenCount: number().nullish(),
1094
+ trafficType: string().nullish()
1095
+ });
1096
+ var getUrlContextMetadataSchema = () => object({ urlMetadata: array(object({
1097
+ retrievedUrl: string(),
1098
+ urlRetrievalStatus: string()
1099
+ })) });
1100
+ var responseSchema = lazySchema(() => zodSchema(object({
1101
+ candidates: array(object({
1102
+ content: getContentSchema().nullish().or(object({}).strict()),
1103
+ finishReason: string().nullish(),
1104
+ safetyRatings: array(getSafetyRatingSchema()).nullish(),
1105
+ groundingMetadata: getGroundingMetadataSchema().nullish(),
1106
+ urlContextMetadata: getUrlContextMetadataSchema().nullish()
1107
+ })),
1108
+ usageMetadata: usageSchema.nullish(),
1109
+ promptFeedback: object({
1110
+ blockReason: string().nullish(),
1111
+ safetyRatings: array(getSafetyRatingSchema()).nullish()
1112
+ }).nullish()
1113
+ })));
1114
+ var chunkSchema = lazySchema(() => zodSchema(object({
1115
+ candidates: array(object({
1116
+ content: getContentSchema().nullish(),
1117
+ finishReason: string().nullish(),
1118
+ safetyRatings: array(getSafetyRatingSchema()).nullish(),
1119
+ groundingMetadata: getGroundingMetadataSchema().nullish(),
1120
+ urlContextMetadata: getUrlContextMetadataSchema().nullish()
1121
+ })).nullish(),
1122
+ usageMetadata: usageSchema.nullish(),
1123
+ promptFeedback: object({
1124
+ blockReason: string().nullish(),
1125
+ safetyRatings: array(getSafetyRatingSchema()).nullish()
1126
+ }).nullish()
1127
+ })));
1128
+ var codeExecution = createProviderToolFactoryWithOutputSchema({
1129
+ id: "google.code_execution",
1130
+ inputSchema: object({
1131
+ language: string().describe("The programming language of the code."),
1132
+ code: string().describe("The code to be executed.")
1133
+ }),
1134
+ outputSchema: object({
1135
+ outcome: string().describe("The outcome of the execution (e.g., \"OUTCOME_OK\")."),
1136
+ output: string().describe("The output from the code execution.")
1137
+ })
1138
+ });
1139
+ var enterpriseWebSearch = createProviderToolFactory({
1140
+ id: "google.enterprise_web_search",
1141
+ inputSchema: lazySchema(() => zodSchema(object({})))
1142
+ });
1143
+ var fileSearchArgsBaseSchema = object({
1144
+ fileSearchStoreNames: array(string()).describe("The names of the file_search_stores to retrieve from. Example: `fileSearchStores/my-file-search-store-123`"),
1145
+ topK: number().int().positive().describe("The number of file search retrieval chunks to retrieve.").optional(),
1146
+ metadataFilter: string().describe("Metadata filter to apply to the file search retrieval documents. See https://google.aip.dev/160 for the syntax of the filter expression.").optional()
1147
+ }).passthrough();
1148
+ var fileSearch = createProviderToolFactory({
1149
+ id: "google.file_search",
1150
+ inputSchema: lazySchema(() => zodSchema(fileSearchArgsBaseSchema))
1151
+ });
1152
+ var googleMaps = createProviderToolFactory({
1153
+ id: "google.google_maps",
1154
+ inputSchema: lazySchema(() => zodSchema(object({})))
1155
+ });
1156
+ var googleSearch = createProviderToolFactory({
1157
+ id: "google.google_search",
1158
+ inputSchema: lazySchema(() => zodSchema(object({
1159
+ mode: _enum(["MODE_DYNAMIC", "MODE_UNSPECIFIED"]).default("MODE_UNSPECIFIED"),
1160
+ dynamicThreshold: number().default(1)
1161
+ })))
1162
+ });
1163
+ var urlContext = createProviderToolFactory({
1164
+ id: "google.url_context",
1165
+ inputSchema: lazySchema(() => zodSchema(object({})))
1166
+ });
1167
+ var googleTools = {
1168
+ googleSearch,
1169
+ enterpriseWebSearch,
1170
+ googleMaps,
1171
+ urlContext,
1172
+ fileSearch,
1173
+ codeExecution,
1174
+ vertexRagStore: createProviderToolFactory({
1175
+ id: "google.vertex_rag_store",
1176
+ inputSchema: object({
1177
+ ragCorpus: string(),
1178
+ topK: number().optional()
1179
+ })
1180
+ })
1181
+ };
1182
+ var GoogleGenerativeAIImageModel = class {
1183
+ constructor(modelId, settings, config) {
1184
+ this.modelId = modelId;
1185
+ this.settings = settings;
1186
+ this.config = config;
1187
+ this.specificationVersion = "v3";
1188
+ }
1189
+ get maxImagesPerCall() {
1190
+ var _a;
1191
+ return (_a = this.settings.maxImagesPerCall) != null ? _a : 4;
1192
+ }
1193
+ get provider() {
1194
+ return this.config.provider;
1195
+ }
1196
+ async doGenerate(options) {
1197
+ var _a, _b, _c;
1198
+ const { prompt, n = 1, size, aspectRatio = "1:1", seed, providerOptions, headers, abortSignal, files, mask } = options;
1199
+ const warnings = [];
1200
+ if (files != null && files.length > 0) throw new Error("Google Generative AI does not support image editing. Use Google Vertex AI (@ai-sdk/google-vertex) for image editing capabilities.");
1201
+ if (mask != null) throw new Error("Google Generative AI does not support image editing with masks. Use Google Vertex AI (@ai-sdk/google-vertex) for image editing capabilities.");
1202
+ if (size != null) warnings.push({
1203
+ type: "unsupported",
1204
+ feature: "size",
1205
+ details: "This model does not support the `size` option. Use `aspectRatio` instead."
1206
+ });
1207
+ if (seed != null) warnings.push({
1208
+ type: "unsupported",
1209
+ feature: "seed",
1210
+ details: "This model does not support the `seed` option through this provider."
1211
+ });
1212
+ const googleOptions = await parseProviderOptions({
1213
+ provider: "google",
1214
+ providerOptions,
1215
+ schema: googleImageProviderOptionsSchema
1216
+ });
1217
+ const currentDate = (_c = (_b = (_a = this.config._internal) == null ? void 0 : _a.currentDate) == null ? void 0 : _b.call(_a)) != null ? _c : /* @__PURE__ */ new Date();
1218
+ const parameters = { sampleCount: n };
1219
+ if (aspectRatio != null) parameters.aspectRatio = aspectRatio;
1220
+ if (googleOptions) Object.assign(parameters, googleOptions);
1221
+ const body = {
1222
+ instances: [{ prompt }],
1223
+ parameters
1224
+ };
1225
+ const { responseHeaders, value: response } = await postJsonToApi({
1226
+ url: `${this.config.baseURL}/models/${this.modelId}:predict`,
1227
+ headers: combineHeaders(await resolve(this.config.headers), headers),
1228
+ body,
1229
+ failedResponseHandler: googleFailedResponseHandler,
1230
+ successfulResponseHandler: createJsonResponseHandler(googleImageResponseSchema),
1231
+ abortSignal,
1232
+ fetch: this.config.fetch
1233
+ });
1234
+ return {
1235
+ images: response.predictions.map((p) => p.bytesBase64Encoded),
1236
+ warnings: warnings != null ? warnings : [],
1237
+ providerMetadata: { google: { images: response.predictions.map((prediction) => ({})) } },
1238
+ response: {
1239
+ timestamp: currentDate,
1240
+ modelId: this.modelId,
1241
+ headers: responseHeaders
1242
+ }
1243
+ };
1244
+ }
1245
+ };
1246
+ var googleImageResponseSchema = lazySchema(() => zodSchema(object({ predictions: array(object({ bytesBase64Encoded: string() })).default([]) })));
1247
+ var googleImageProviderOptionsSchema = lazySchema(() => zodSchema(object({
1248
+ personGeneration: _enum([
1249
+ "dont_allow",
1250
+ "allow_adult",
1251
+ "allow_all"
1252
+ ]).nullish(),
1253
+ aspectRatio: _enum([
1254
+ "1:1",
1255
+ "3:4",
1256
+ "4:3",
1257
+ "9:16",
1258
+ "16:9"
1259
+ ]).nullish()
1260
+ })));
1261
+ var GoogleGenerativeAIVideoModel = class {
1262
+ constructor(modelId, config) {
1263
+ this.modelId = modelId;
1264
+ this.config = config;
1265
+ this.specificationVersion = "v3";
1266
+ }
1267
+ get provider() {
1268
+ return this.config.provider;
1269
+ }
1270
+ get maxVideosPerCall() {
1271
+ return 4;
1272
+ }
1273
+ async doGenerate(options) {
1274
+ var _a, _b, _c, _d, _e, _f, _g, _h;
1275
+ const currentDate = (_c = (_b = (_a = this.config._internal) == null ? void 0 : _a.currentDate) == null ? void 0 : _b.call(_a)) != null ? _c : /* @__PURE__ */ new Date();
1276
+ const warnings = [];
1277
+ const googleOptions = await parseProviderOptions({
1278
+ provider: "google",
1279
+ providerOptions: options.providerOptions,
1280
+ schema: googleVideoProviderOptionsSchema
1281
+ });
1282
+ const instances = [{}];
1283
+ const instance = instances[0];
1284
+ if (options.prompt != null) instance.prompt = options.prompt;
1285
+ if (options.image != null) if (options.image.type === "url") warnings.push({
1286
+ type: "unsupported",
1287
+ feature: "URL-based image input",
1288
+ details: "Google Generative AI video models require base64-encoded images. URL will be ignored."
1289
+ });
1290
+ else {
1291
+ const base64Data = typeof options.image.data === "string" ? options.image.data : convertUint8ArrayToBase64(options.image.data);
1292
+ instance.image = { inlineData: {
1293
+ mimeType: options.image.mediaType || "image/png",
1294
+ data: base64Data
1295
+ } };
1296
+ }
1297
+ if ((googleOptions == null ? void 0 : googleOptions.referenceImages) != null) instance.referenceImages = googleOptions.referenceImages.map((refImg) => {
1298
+ if (refImg.bytesBase64Encoded) return { inlineData: {
1299
+ mimeType: "image/png",
1300
+ data: refImg.bytesBase64Encoded
1301
+ } };
1302
+ else if (refImg.gcsUri) return { gcsUri: refImg.gcsUri };
1303
+ return refImg;
1304
+ });
1305
+ const parameters = { sampleCount: options.n };
1306
+ if (options.aspectRatio) parameters.aspectRatio = options.aspectRatio;
1307
+ if (options.resolution) parameters.resolution = {
1308
+ "1280x720": "720p",
1309
+ "1920x1080": "1080p",
1310
+ "3840x2160": "4k"
1311
+ }[options.resolution] || options.resolution;
1312
+ if (options.duration) parameters.durationSeconds = options.duration;
1313
+ if (options.seed) parameters.seed = options.seed;
1314
+ if (googleOptions != null) {
1315
+ const opts = googleOptions;
1316
+ if (opts.personGeneration !== void 0 && opts.personGeneration !== null) parameters.personGeneration = opts.personGeneration;
1317
+ if (opts.negativePrompt !== void 0 && opts.negativePrompt !== null) parameters.negativePrompt = opts.negativePrompt;
1318
+ for (const [key, value] of Object.entries(opts)) if (![
1319
+ "pollIntervalMs",
1320
+ "pollTimeoutMs",
1321
+ "personGeneration",
1322
+ "negativePrompt",
1323
+ "referenceImages"
1324
+ ].includes(key)) parameters[key] = value;
1325
+ }
1326
+ const { value: operation } = await postJsonToApi({
1327
+ url: `${this.config.baseURL}/models/${this.modelId}:predictLongRunning`,
1328
+ headers: combineHeaders(await resolve(this.config.headers), options.headers),
1329
+ body: {
1330
+ instances,
1331
+ parameters
1332
+ },
1333
+ successfulResponseHandler: createJsonResponseHandler(googleOperationSchema),
1334
+ failedResponseHandler: googleFailedResponseHandler,
1335
+ abortSignal: options.abortSignal,
1336
+ fetch: this.config.fetch
1337
+ });
1338
+ const operationName = operation.name;
1339
+ if (!operationName) throw new AISDKError({
1340
+ name: "GOOGLE_VIDEO_GENERATION_ERROR",
1341
+ message: "No operation name returned from API"
1342
+ });
1343
+ const pollIntervalMs = (_d = googleOptions == null ? void 0 : googleOptions.pollIntervalMs) != null ? _d : 1e4;
1344
+ const pollTimeoutMs = (_e = googleOptions == null ? void 0 : googleOptions.pollTimeoutMs) != null ? _e : 6e5;
1345
+ const startTime = Date.now();
1346
+ let finalOperation = operation;
1347
+ let responseHeaders;
1348
+ while (!finalOperation.done) {
1349
+ if (Date.now() - startTime > pollTimeoutMs) throw new AISDKError({
1350
+ name: "GOOGLE_VIDEO_GENERATION_TIMEOUT",
1351
+ message: `Video generation timed out after ${pollTimeoutMs}ms`
1352
+ });
1353
+ await delay(pollIntervalMs);
1354
+ if ((_f = options.abortSignal) == null ? void 0 : _f.aborted) throw new AISDKError({
1355
+ name: "GOOGLE_VIDEO_GENERATION_ABORTED",
1356
+ message: "Video generation request was aborted"
1357
+ });
1358
+ const { value: statusOperation, responseHeaders: pollHeaders } = await getFromApi({
1359
+ url: `${this.config.baseURL}/${operationName}`,
1360
+ headers: combineHeaders(await resolve(this.config.headers), options.headers),
1361
+ successfulResponseHandler: createJsonResponseHandler(googleOperationSchema),
1362
+ failedResponseHandler: googleFailedResponseHandler,
1363
+ abortSignal: options.abortSignal,
1364
+ fetch: this.config.fetch
1365
+ });
1366
+ finalOperation = statusOperation;
1367
+ responseHeaders = pollHeaders;
1368
+ }
1369
+ if (finalOperation.error) throw new AISDKError({
1370
+ name: "GOOGLE_VIDEO_GENERATION_FAILED",
1371
+ message: `Video generation failed: ${finalOperation.error.message}`
1372
+ });
1373
+ const response = finalOperation.response;
1374
+ if (!((_g = response == null ? void 0 : response.generateVideoResponse) == null ? void 0 : _g.generatedSamples) || response.generateVideoResponse.generatedSamples.length === 0) throw new AISDKError({
1375
+ name: "GOOGLE_VIDEO_GENERATION_ERROR",
1376
+ message: `No videos in response. Response: ${JSON.stringify(finalOperation)}`
1377
+ });
1378
+ const videos = [];
1379
+ const videoMetadata = [];
1380
+ const resolvedHeaders = await resolve(this.config.headers);
1381
+ const apiKey = resolvedHeaders == null ? void 0 : resolvedHeaders["x-goog-api-key"];
1382
+ for (const generatedSample of response.generateVideoResponse.generatedSamples) if ((_h = generatedSample.video) == null ? void 0 : _h.uri) {
1383
+ const urlWithAuth = apiKey ? `${generatedSample.video.uri}${generatedSample.video.uri.includes("?") ? "&" : "?"}key=${apiKey}` : generatedSample.video.uri;
1384
+ videos.push({
1385
+ type: "url",
1386
+ url: urlWithAuth,
1387
+ mediaType: "video/mp4"
1388
+ });
1389
+ videoMetadata.push({ uri: generatedSample.video.uri });
1390
+ }
1391
+ if (videos.length === 0) throw new AISDKError({
1392
+ name: "GOOGLE_VIDEO_GENERATION_ERROR",
1393
+ message: "No valid videos in response"
1394
+ });
1395
+ return {
1396
+ videos,
1397
+ warnings,
1398
+ response: {
1399
+ timestamp: currentDate,
1400
+ modelId: this.modelId,
1401
+ headers: responseHeaders
1402
+ },
1403
+ providerMetadata: { google: { videos: videoMetadata } }
1404
+ };
1405
+ }
1406
+ };
1407
+ var googleOperationSchema = object({
1408
+ name: string().nullish(),
1409
+ done: boolean().nullish(),
1410
+ error: object({
1411
+ code: number().nullish(),
1412
+ message: string(),
1413
+ status: string().nullish()
1414
+ }).nullish(),
1415
+ response: object({ generateVideoResponse: object({ generatedSamples: array(object({ video: object({ uri: string().nullish() }).nullish() })).nullish() }).nullish() }).nullish()
1416
+ });
1417
+ var googleVideoProviderOptionsSchema = lazySchema(() => zodSchema(object({
1418
+ pollIntervalMs: number().positive().nullish(),
1419
+ pollTimeoutMs: number().positive().nullish(),
1420
+ personGeneration: _enum([
1421
+ "dont_allow",
1422
+ "allow_adult",
1423
+ "allow_all"
1424
+ ]).nullish(),
1425
+ negativePrompt: string().nullish(),
1426
+ referenceImages: array(object({
1427
+ bytesBase64Encoded: string().nullish(),
1428
+ gcsUri: string().nullish()
1429
+ })).nullish()
1430
+ }).passthrough()));
1431
+ function createGoogleGenerativeAI(options = {}) {
1432
+ var _a, _b;
1433
+ const baseURL = (_a = withoutTrailingSlash(options.baseURL)) != null ? _a : "https://generativelanguage.googleapis.com/v1beta";
1434
+ const providerName = (_b = options.name) != null ? _b : "google.generative-ai";
1435
+ const getHeaders = () => withUserAgentSuffix({
1436
+ "x-goog-api-key": loadApiKey({
1437
+ apiKey: options.apiKey,
1438
+ environmentVariableName: "GOOGLE_GENERATIVE_AI_API_KEY",
1439
+ description: "Google Generative AI"
1440
+ }),
1441
+ ...options.headers
1442
+ }, `ai-sdk/google/${VERSION}`);
1443
+ const createChatModel = (modelId) => {
1444
+ var _a2;
1445
+ return new GoogleGenerativeAILanguageModel(modelId, {
1446
+ provider: providerName,
1447
+ baseURL,
1448
+ headers: getHeaders,
1449
+ generateId: (_a2 = options.generateId) != null ? _a2 : generateId,
1450
+ supportedUrls: () => ({ "*": [
1451
+ new RegExp(`^${baseURL}/files/.*$`),
1452
+ new RegExp(`^https://(?:www\\.)?youtube\\.com/watch\\?v=[\\w-]+(?:&[\\w=&.-]*)?$`),
1453
+ new RegExp(`^https://youtu\\.be/[\\w-]+(?:\\?[\\w=&.-]*)?$`)
1454
+ ] }),
1455
+ fetch: options.fetch
1456
+ });
1457
+ };
1458
+ const createEmbeddingModel = (modelId) => new GoogleGenerativeAIEmbeddingModel(modelId, {
1459
+ provider: providerName,
1460
+ baseURL,
1461
+ headers: getHeaders,
1462
+ fetch: options.fetch
1463
+ });
1464
+ const createImageModel = (modelId, settings = {}) => new GoogleGenerativeAIImageModel(modelId, settings, {
1465
+ provider: providerName,
1466
+ baseURL,
1467
+ headers: getHeaders,
1468
+ fetch: options.fetch
1469
+ });
1470
+ const createVideoModel = (modelId) => {
1471
+ var _a2;
1472
+ return new GoogleGenerativeAIVideoModel(modelId, {
1473
+ provider: providerName,
1474
+ baseURL,
1475
+ headers: getHeaders,
1476
+ fetch: options.fetch,
1477
+ generateId: (_a2 = options.generateId) != null ? _a2 : generateId
1478
+ });
1479
+ };
1480
+ const provider = function(modelId) {
1481
+ if (new.target) throw new Error("The Google Generative AI model function cannot be called with the new keyword.");
1482
+ return createChatModel(modelId);
1483
+ };
1484
+ provider.specificationVersion = "v3";
1485
+ provider.languageModel = createChatModel;
1486
+ provider.chat = createChatModel;
1487
+ provider.generativeAI = createChatModel;
1488
+ provider.embedding = createEmbeddingModel;
1489
+ provider.embeddingModel = createEmbeddingModel;
1490
+ provider.textEmbedding = createEmbeddingModel;
1491
+ provider.textEmbeddingModel = createEmbeddingModel;
1492
+ provider.image = createImageModel;
1493
+ provider.imageModel = createImageModel;
1494
+ provider.video = createVideoModel;
1495
+ provider.tools = googleTools;
1496
+ return provider;
1497
+ }
1498
+ var google = createGoogleGenerativeAI();
1499
+
1500
+ //#endregion
1501
+ export { google };
1502
+ //# sourceMappingURL=dist-CrzKI7n8.mjs.map