solid-translate 0.2.0 → 1.0.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,956 @@
1
+ #!/usr/bin/env node
2
+ import {
3
+ TooManyEmbeddingValuesForCallError,
4
+ UnsupportedFunctionalityError,
5
+ combineHeaders,
6
+ convertUint8ArrayToBase64,
7
+ createEventSourceResponseHandler,
8
+ createJsonErrorResponseHandler,
9
+ createJsonResponseHandler,
10
+ generateId,
11
+ loadApiKey,
12
+ parseProviderOptions,
13
+ postJsonToApi,
14
+ resolve,
15
+ withoutTrailingSlash
16
+ } from "./chunk-CIKZ6PF7.js";
17
+ import "./chunk-FYS2JH42.js";
18
+
19
+ // node_modules/@ai-sdk/google/dist/index.mjs
20
+ import { z as z2 } from "zod";
21
+ import { z } from "zod";
22
+ import { z as z3 } from "zod";
23
+ function convertJSONSchemaToOpenAPISchema(jsonSchema) {
24
+ if (isEmptyObjectSchema(jsonSchema)) {
25
+ return void 0;
26
+ }
27
+ if (typeof jsonSchema === "boolean") {
28
+ return { type: "boolean", properties: {} };
29
+ }
30
+ const {
31
+ type,
32
+ description,
33
+ required,
34
+ properties,
35
+ items,
36
+ allOf,
37
+ anyOf,
38
+ oneOf,
39
+ format,
40
+ const: constValue,
41
+ minLength,
42
+ enum: enumValues
43
+ } = jsonSchema;
44
+ const result = {};
45
+ if (description)
46
+ result.description = description;
47
+ if (required)
48
+ result.required = required;
49
+ if (format)
50
+ result.format = format;
51
+ if (constValue !== void 0) {
52
+ result.enum = [constValue];
53
+ }
54
+ if (type) {
55
+ if (Array.isArray(type)) {
56
+ if (type.includes("null")) {
57
+ result.type = type.filter((t) => t !== "null")[0];
58
+ result.nullable = true;
59
+ } else {
60
+ result.type = type;
61
+ }
62
+ } else if (type === "null") {
63
+ result.type = "null";
64
+ } else {
65
+ result.type = type;
66
+ }
67
+ }
68
+ if (enumValues !== void 0) {
69
+ result.enum = enumValues;
70
+ }
71
+ if (properties != null) {
72
+ result.properties = Object.entries(properties).reduce(
73
+ (acc, [key, value]) => {
74
+ acc[key] = convertJSONSchemaToOpenAPISchema(value);
75
+ return acc;
76
+ },
77
+ {}
78
+ );
79
+ }
80
+ if (items) {
81
+ result.items = Array.isArray(items) ? items.map(convertJSONSchemaToOpenAPISchema) : convertJSONSchemaToOpenAPISchema(items);
82
+ }
83
+ if (allOf) {
84
+ result.allOf = allOf.map(convertJSONSchemaToOpenAPISchema);
85
+ }
86
+ if (anyOf) {
87
+ if (anyOf.some(
88
+ (schema) => typeof schema === "object" && (schema == null ? void 0 : schema.type) === "null"
89
+ )) {
90
+ const nonNullSchemas = anyOf.filter(
91
+ (schema) => !(typeof schema === "object" && (schema == null ? void 0 : schema.type) === "null")
92
+ );
93
+ if (nonNullSchemas.length === 1) {
94
+ const converted = convertJSONSchemaToOpenAPISchema(nonNullSchemas[0]);
95
+ if (typeof converted === "object") {
96
+ result.nullable = true;
97
+ Object.assign(result, converted);
98
+ }
99
+ } else {
100
+ result.anyOf = nonNullSchemas.map(convertJSONSchemaToOpenAPISchema);
101
+ result.nullable = true;
102
+ }
103
+ } else {
104
+ result.anyOf = anyOf.map(convertJSONSchemaToOpenAPISchema);
105
+ }
106
+ }
107
+ if (oneOf) {
108
+ result.oneOf = oneOf.map(convertJSONSchemaToOpenAPISchema);
109
+ }
110
+ if (minLength !== void 0) {
111
+ result.minLength = minLength;
112
+ }
113
+ return result;
114
+ }
115
+ function isEmptyObjectSchema(jsonSchema) {
116
+ return jsonSchema != null && typeof jsonSchema === "object" && jsonSchema.type === "object" && (jsonSchema.properties == null || Object.keys(jsonSchema.properties).length === 0) && !jsonSchema.additionalProperties;
117
+ }
118
+ function convertToGoogleGenerativeAIMessages(prompt) {
119
+ var _a, _b;
120
+ const systemInstructionParts = [];
121
+ const contents = [];
122
+ let systemMessagesAllowed = true;
123
+ for (const { role, content } of prompt) {
124
+ switch (role) {
125
+ case "system": {
126
+ if (!systemMessagesAllowed) {
127
+ throw new UnsupportedFunctionalityError({
128
+ functionality: "system messages are only supported at the beginning of the conversation"
129
+ });
130
+ }
131
+ systemInstructionParts.push({ text: content });
132
+ break;
133
+ }
134
+ case "user": {
135
+ systemMessagesAllowed = false;
136
+ const parts = [];
137
+ for (const part of content) {
138
+ switch (part.type) {
139
+ case "text": {
140
+ parts.push({ text: part.text });
141
+ break;
142
+ }
143
+ case "image": {
144
+ parts.push(
145
+ part.image instanceof URL ? {
146
+ fileData: {
147
+ mimeType: (_a = part.mimeType) != null ? _a : "image/jpeg",
148
+ fileUri: part.image.toString()
149
+ }
150
+ } : {
151
+ inlineData: {
152
+ mimeType: (_b = part.mimeType) != null ? _b : "image/jpeg",
153
+ data: convertUint8ArrayToBase64(part.image)
154
+ }
155
+ }
156
+ );
157
+ break;
158
+ }
159
+ case "file": {
160
+ parts.push(
161
+ part.data instanceof URL ? {
162
+ fileData: {
163
+ mimeType: part.mimeType,
164
+ fileUri: part.data.toString()
165
+ }
166
+ } : {
167
+ inlineData: {
168
+ mimeType: part.mimeType,
169
+ data: part.data
170
+ }
171
+ }
172
+ );
173
+ break;
174
+ }
175
+ }
176
+ }
177
+ contents.push({ role: "user", parts });
178
+ break;
179
+ }
180
+ case "assistant": {
181
+ systemMessagesAllowed = false;
182
+ contents.push({
183
+ role: "model",
184
+ parts: content.map((part) => {
185
+ switch (part.type) {
186
+ case "text": {
187
+ return part.text.length === 0 ? void 0 : { text: part.text };
188
+ }
189
+ case "file": {
190
+ if (part.mimeType !== "image/png") {
191
+ throw new UnsupportedFunctionalityError({
192
+ functionality: "Only PNG images are supported in assistant messages"
193
+ });
194
+ }
195
+ if (part.data instanceof URL) {
196
+ throw new UnsupportedFunctionalityError({
197
+ functionality: "File data URLs in assistant messages are not supported"
198
+ });
199
+ }
200
+ return {
201
+ inlineData: {
202
+ mimeType: part.mimeType,
203
+ data: part.data
204
+ }
205
+ };
206
+ }
207
+ case "tool-call": {
208
+ return {
209
+ functionCall: {
210
+ name: part.toolName,
211
+ args: part.args
212
+ }
213
+ };
214
+ }
215
+ }
216
+ }).filter((part) => part !== void 0)
217
+ });
218
+ break;
219
+ }
220
+ case "tool": {
221
+ systemMessagesAllowed = false;
222
+ contents.push({
223
+ role: "user",
224
+ parts: content.map((part) => ({
225
+ functionResponse: {
226
+ name: part.toolName,
227
+ response: {
228
+ name: part.toolName,
229
+ content: part.result
230
+ }
231
+ }
232
+ }))
233
+ });
234
+ break;
235
+ }
236
+ }
237
+ }
238
+ return {
239
+ systemInstruction: systemInstructionParts.length > 0 ? { parts: systemInstructionParts } : void 0,
240
+ contents
241
+ };
242
+ }
243
+ function getModelPath(modelId) {
244
+ return modelId.includes("/") ? modelId : `models/${modelId}`;
245
+ }
246
+ var googleErrorDataSchema = z.object({
247
+ error: z.object({
248
+ code: z.number().nullable(),
249
+ message: z.string(),
250
+ status: z.string()
251
+ })
252
+ });
253
+ var googleFailedResponseHandler = createJsonErrorResponseHandler({
254
+ errorSchema: googleErrorDataSchema,
255
+ errorToMessage: (data) => data.error.message
256
+ });
257
+ function prepareTools(mode, useSearchGrounding, dynamicRetrievalConfig, modelId) {
258
+ var _a, _b;
259
+ const tools = ((_a = mode.tools) == null ? void 0 : _a.length) ? mode.tools : void 0;
260
+ const toolWarnings = [];
261
+ const isGemini2 = modelId.includes("gemini-2");
262
+ const supportsDynamicRetrieval = modelId.includes("gemini-1.5-flash") && !modelId.includes("-8b");
263
+ if (useSearchGrounding) {
264
+ return {
265
+ tools: isGemini2 ? { googleSearch: {} } : {
266
+ googleSearchRetrieval: !supportsDynamicRetrieval || !dynamicRetrievalConfig ? {} : { dynamicRetrievalConfig }
267
+ },
268
+ toolConfig: void 0,
269
+ toolWarnings
270
+ };
271
+ }
272
+ if (tools == null) {
273
+ return { tools: void 0, toolConfig: void 0, toolWarnings };
274
+ }
275
+ const functionDeclarations = [];
276
+ for (const tool of tools) {
277
+ if (tool.type === "provider-defined") {
278
+ toolWarnings.push({ type: "unsupported-tool", tool });
279
+ } else {
280
+ functionDeclarations.push({
281
+ name: tool.name,
282
+ description: (_b = tool.description) != null ? _b : "",
283
+ parameters: convertJSONSchemaToOpenAPISchema(tool.parameters)
284
+ });
285
+ }
286
+ }
287
+ const toolChoice = mode.toolChoice;
288
+ if (toolChoice == null) {
289
+ return {
290
+ tools: { functionDeclarations },
291
+ toolConfig: void 0,
292
+ toolWarnings
293
+ };
294
+ }
295
+ const type = toolChoice.type;
296
+ switch (type) {
297
+ case "auto":
298
+ return {
299
+ tools: { functionDeclarations },
300
+ toolConfig: { functionCallingConfig: { mode: "AUTO" } },
301
+ toolWarnings
302
+ };
303
+ case "none":
304
+ return {
305
+ tools: { functionDeclarations },
306
+ toolConfig: { functionCallingConfig: { mode: "NONE" } },
307
+ toolWarnings
308
+ };
309
+ case "required":
310
+ return {
311
+ tools: { functionDeclarations },
312
+ toolConfig: { functionCallingConfig: { mode: "ANY" } },
313
+ toolWarnings
314
+ };
315
+ case "tool":
316
+ return {
317
+ tools: { functionDeclarations },
318
+ toolConfig: {
319
+ functionCallingConfig: {
320
+ mode: "ANY",
321
+ allowedFunctionNames: [toolChoice.toolName]
322
+ }
323
+ },
324
+ toolWarnings
325
+ };
326
+ default: {
327
+ const _exhaustiveCheck = type;
328
+ throw new UnsupportedFunctionalityError({
329
+ functionality: `Unsupported tool choice type: ${_exhaustiveCheck}`
330
+ });
331
+ }
332
+ }
333
+ }
334
+ function mapGoogleGenerativeAIFinishReason({
335
+ finishReason,
336
+ hasToolCalls
337
+ }) {
338
+ switch (finishReason) {
339
+ case "STOP":
340
+ return hasToolCalls ? "tool-calls" : "stop";
341
+ case "MAX_TOKENS":
342
+ return "length";
343
+ case "IMAGE_SAFETY":
344
+ case "RECITATION":
345
+ case "SAFETY":
346
+ case "BLOCKLIST":
347
+ case "PROHIBITED_CONTENT":
348
+ case "SPII":
349
+ return "content-filter";
350
+ case "FINISH_REASON_UNSPECIFIED":
351
+ case "OTHER":
352
+ return "other";
353
+ case "MALFORMED_FUNCTION_CALL":
354
+ return "error";
355
+ default:
356
+ return "unknown";
357
+ }
358
+ }
359
+ var GoogleGenerativeAILanguageModel = class {
360
+ constructor(modelId, settings, config) {
361
+ this.specificationVersion = "v1";
362
+ this.defaultObjectGenerationMode = "json";
363
+ this.supportsImageUrls = false;
364
+ this.modelId = modelId;
365
+ this.settings = settings;
366
+ this.config = config;
367
+ }
368
+ get supportsStructuredOutputs() {
369
+ var _a;
370
+ return (_a = this.settings.structuredOutputs) != null ? _a : true;
371
+ }
372
+ get provider() {
373
+ return this.config.provider;
374
+ }
375
+ async getArgs({
376
+ mode,
377
+ prompt,
378
+ maxTokens,
379
+ temperature,
380
+ topP,
381
+ topK,
382
+ frequencyPenalty,
383
+ presencePenalty,
384
+ stopSequences,
385
+ responseFormat,
386
+ seed,
387
+ providerMetadata
388
+ }) {
389
+ var _a, _b, _c;
390
+ const type = mode.type;
391
+ const warnings = [];
392
+ const googleOptions = parseProviderOptions({
393
+ provider: "google",
394
+ providerOptions: providerMetadata,
395
+ schema: googleGenerativeAIProviderOptionsSchema
396
+ });
397
+ if (((_a = googleOptions == null ? void 0 : googleOptions.thinkingConfig) == null ? void 0 : _a.includeThoughts) === true && !this.config.provider.startsWith("google.vertex.")) {
398
+ warnings.push({
399
+ type: "other",
400
+ message: `The 'includeThoughts' option 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}).`
401
+ });
402
+ }
403
+ const generationConfig = {
404
+ // standardized settings:
405
+ maxOutputTokens: maxTokens,
406
+ temperature,
407
+ topK,
408
+ topP,
409
+ frequencyPenalty,
410
+ presencePenalty,
411
+ stopSequences,
412
+ seed,
413
+ // response format:
414
+ responseMimeType: (responseFormat == null ? void 0 : responseFormat.type) === "json" ? "application/json" : void 0,
415
+ responseSchema: (responseFormat == null ? void 0 : responseFormat.type) === "json" && responseFormat.schema != null && // Google GenAI does not support all OpenAPI Schema features,
416
+ // so this is needed as an escape hatch:
417
+ this.supportsStructuredOutputs ? convertJSONSchemaToOpenAPISchema(responseFormat.schema) : void 0,
418
+ ...this.settings.audioTimestamp && {
419
+ audioTimestamp: this.settings.audioTimestamp
420
+ },
421
+ // provider options:
422
+ responseModalities: googleOptions == null ? void 0 : googleOptions.responseModalities,
423
+ thinkingConfig: googleOptions == null ? void 0 : googleOptions.thinkingConfig
424
+ };
425
+ const { contents, systemInstruction } = convertToGoogleGenerativeAIMessages(prompt);
426
+ switch (type) {
427
+ case "regular": {
428
+ const { tools, toolConfig, toolWarnings } = prepareTools(
429
+ mode,
430
+ (_b = this.settings.useSearchGrounding) != null ? _b : false,
431
+ this.settings.dynamicRetrievalConfig,
432
+ this.modelId
433
+ );
434
+ return {
435
+ args: {
436
+ generationConfig,
437
+ contents,
438
+ systemInstruction,
439
+ safetySettings: this.settings.safetySettings,
440
+ tools,
441
+ toolConfig,
442
+ cachedContent: this.settings.cachedContent
443
+ },
444
+ warnings: [...warnings, ...toolWarnings]
445
+ };
446
+ }
447
+ case "object-json": {
448
+ return {
449
+ args: {
450
+ generationConfig: {
451
+ ...generationConfig,
452
+ responseMimeType: "application/json",
453
+ responseSchema: mode.schema != null && // Google GenAI does not support all OpenAPI Schema features,
454
+ // so this is needed as an escape hatch:
455
+ this.supportsStructuredOutputs ? convertJSONSchemaToOpenAPISchema(mode.schema) : void 0
456
+ },
457
+ contents,
458
+ systemInstruction,
459
+ safetySettings: this.settings.safetySettings,
460
+ cachedContent: this.settings.cachedContent
461
+ },
462
+ warnings
463
+ };
464
+ }
465
+ case "object-tool": {
466
+ return {
467
+ args: {
468
+ generationConfig,
469
+ contents,
470
+ systemInstruction,
471
+ tools: {
472
+ functionDeclarations: [
473
+ {
474
+ name: mode.tool.name,
475
+ description: (_c = mode.tool.description) != null ? _c : "",
476
+ parameters: convertJSONSchemaToOpenAPISchema(
477
+ mode.tool.parameters
478
+ )
479
+ }
480
+ ]
481
+ },
482
+ toolConfig: { functionCallingConfig: { mode: "ANY" } },
483
+ safetySettings: this.settings.safetySettings,
484
+ cachedContent: this.settings.cachedContent
485
+ },
486
+ warnings
487
+ };
488
+ }
489
+ default: {
490
+ const _exhaustiveCheck = type;
491
+ throw new Error(`Unsupported type: ${_exhaustiveCheck}`);
492
+ }
493
+ }
494
+ }
495
+ supportsUrl(url) {
496
+ return this.config.isSupportedUrl(url);
497
+ }
498
+ async doGenerate(options) {
499
+ var _a, _b, _c, _d, _e;
500
+ const { args, warnings } = await this.getArgs(options);
501
+ const body = JSON.stringify(args);
502
+ const mergedHeaders = combineHeaders(
503
+ await resolve(this.config.headers),
504
+ options.headers
505
+ );
506
+ const {
507
+ responseHeaders,
508
+ value: response,
509
+ rawValue: rawResponse
510
+ } = await postJsonToApi({
511
+ url: `${this.config.baseURL}/${getModelPath(
512
+ this.modelId
513
+ )}:generateContent`,
514
+ headers: mergedHeaders,
515
+ body: args,
516
+ failedResponseHandler: googleFailedResponseHandler,
517
+ successfulResponseHandler: createJsonResponseHandler(responseSchema),
518
+ abortSignal: options.abortSignal,
519
+ fetch: this.config.fetch
520
+ });
521
+ const { contents: rawPrompt, ...rawSettings } = args;
522
+ const candidate = response.candidates[0];
523
+ const parts = candidate.content == null || typeof candidate.content !== "object" || !("parts" in candidate.content) ? [] : candidate.content.parts;
524
+ const toolCalls = getToolCallsFromParts({
525
+ parts,
526
+ // Use candidateParts
527
+ generateId: this.config.generateId
528
+ });
529
+ const usageMetadata = response.usageMetadata;
530
+ return {
531
+ text: getTextFromParts(parts),
532
+ reasoning: getReasoningDetailsFromParts(parts),
533
+ files: (_a = getInlineDataParts(parts)) == null ? void 0 : _a.map((part) => ({
534
+ data: part.inlineData.data,
535
+ mimeType: part.inlineData.mimeType
536
+ })),
537
+ toolCalls,
538
+ finishReason: mapGoogleGenerativeAIFinishReason({
539
+ finishReason: candidate.finishReason,
540
+ hasToolCalls: toolCalls != null && toolCalls.length > 0
541
+ }),
542
+ usage: {
543
+ promptTokens: (_b = usageMetadata == null ? void 0 : usageMetadata.promptTokenCount) != null ? _b : NaN,
544
+ completionTokens: (_c = usageMetadata == null ? void 0 : usageMetadata.candidatesTokenCount) != null ? _c : NaN
545
+ },
546
+ rawCall: { rawPrompt, rawSettings },
547
+ rawResponse: { headers: responseHeaders, body: rawResponse },
548
+ warnings,
549
+ providerMetadata: {
550
+ google: {
551
+ groundingMetadata: (_d = candidate.groundingMetadata) != null ? _d : null,
552
+ safetyRatings: (_e = candidate.safetyRatings) != null ? _e : null
553
+ }
554
+ },
555
+ sources: extractSources({
556
+ groundingMetadata: candidate.groundingMetadata,
557
+ generateId: this.config.generateId
558
+ }),
559
+ request: { body }
560
+ };
561
+ }
562
+ async doStream(options) {
563
+ const { args, warnings } = await this.getArgs(options);
564
+ const body = JSON.stringify(args);
565
+ const headers = combineHeaders(
566
+ await resolve(this.config.headers),
567
+ options.headers
568
+ );
569
+ const { responseHeaders, value: response } = await postJsonToApi({
570
+ url: `${this.config.baseURL}/${getModelPath(
571
+ this.modelId
572
+ )}:streamGenerateContent?alt=sse`,
573
+ headers,
574
+ body: args,
575
+ failedResponseHandler: googleFailedResponseHandler,
576
+ successfulResponseHandler: createEventSourceResponseHandler(chunkSchema),
577
+ abortSignal: options.abortSignal,
578
+ fetch: this.config.fetch
579
+ });
580
+ const { contents: rawPrompt, ...rawSettings } = args;
581
+ let finishReason = "unknown";
582
+ let usage = {
583
+ promptTokens: Number.NaN,
584
+ completionTokens: Number.NaN
585
+ };
586
+ let providerMetadata = void 0;
587
+ const generateId2 = this.config.generateId;
588
+ let hasToolCalls = false;
589
+ return {
590
+ stream: response.pipeThrough(
591
+ new TransformStream({
592
+ transform(chunk, controller) {
593
+ var _a, _b, _c, _d, _e, _f;
594
+ if (!chunk.success) {
595
+ controller.enqueue({ type: "error", error: chunk.error });
596
+ return;
597
+ }
598
+ const value = chunk.value;
599
+ const usageMetadata = value.usageMetadata;
600
+ if (usageMetadata != null) {
601
+ usage = {
602
+ promptTokens: (_a = usageMetadata.promptTokenCount) != null ? _a : NaN,
603
+ completionTokens: (_b = usageMetadata.candidatesTokenCount) != null ? _b : NaN
604
+ };
605
+ }
606
+ const candidate = (_c = value.candidates) == null ? void 0 : _c[0];
607
+ if (candidate == null) {
608
+ return;
609
+ }
610
+ const content = candidate.content;
611
+ if (content != null) {
612
+ const deltaText = getTextFromParts(content.parts);
613
+ if (deltaText != null) {
614
+ controller.enqueue({
615
+ type: "text-delta",
616
+ textDelta: deltaText
617
+ });
618
+ }
619
+ const reasoningDeltaText = getReasoningDetailsFromParts(
620
+ content.parts
621
+ );
622
+ if (reasoningDeltaText != null) {
623
+ for (const part of reasoningDeltaText) {
624
+ controller.enqueue({
625
+ type: "reasoning",
626
+ textDelta: part.text
627
+ });
628
+ }
629
+ }
630
+ const inlineDataParts = getInlineDataParts(content.parts);
631
+ if (inlineDataParts != null) {
632
+ for (const part of inlineDataParts) {
633
+ controller.enqueue({
634
+ type: "file",
635
+ mimeType: part.inlineData.mimeType,
636
+ data: part.inlineData.data
637
+ });
638
+ }
639
+ }
640
+ const toolCallDeltas = getToolCallsFromParts({
641
+ parts: content.parts,
642
+ generateId: generateId2
643
+ });
644
+ if (toolCallDeltas != null) {
645
+ for (const toolCall of toolCallDeltas) {
646
+ controller.enqueue({
647
+ type: "tool-call-delta",
648
+ toolCallType: "function",
649
+ toolCallId: toolCall.toolCallId,
650
+ toolName: toolCall.toolName,
651
+ argsTextDelta: toolCall.args
652
+ });
653
+ controller.enqueue({
654
+ type: "tool-call",
655
+ toolCallType: "function",
656
+ toolCallId: toolCall.toolCallId,
657
+ toolName: toolCall.toolName,
658
+ args: toolCall.args
659
+ });
660
+ hasToolCalls = true;
661
+ }
662
+ }
663
+ }
664
+ if (candidate.finishReason != null) {
665
+ finishReason = mapGoogleGenerativeAIFinishReason({
666
+ finishReason: candidate.finishReason,
667
+ hasToolCalls
668
+ });
669
+ const sources = (_d = extractSources({
670
+ groundingMetadata: candidate.groundingMetadata,
671
+ generateId: generateId2
672
+ })) != null ? _d : [];
673
+ for (const source of sources) {
674
+ controller.enqueue({ type: "source", source });
675
+ }
676
+ providerMetadata = {
677
+ google: {
678
+ groundingMetadata: (_e = candidate.groundingMetadata) != null ? _e : null,
679
+ safetyRatings: (_f = candidate.safetyRatings) != null ? _f : null
680
+ }
681
+ };
682
+ }
683
+ },
684
+ flush(controller) {
685
+ controller.enqueue({
686
+ type: "finish",
687
+ finishReason,
688
+ usage,
689
+ providerMetadata
690
+ });
691
+ }
692
+ })
693
+ ),
694
+ rawCall: { rawPrompt, rawSettings },
695
+ rawResponse: { headers: responseHeaders },
696
+ warnings,
697
+ request: { body }
698
+ };
699
+ }
700
+ };
701
+ function getToolCallsFromParts({
702
+ parts,
703
+ generateId: generateId2
704
+ }) {
705
+ const functionCallParts = parts == null ? void 0 : parts.filter(
706
+ (part) => "functionCall" in part
707
+ );
708
+ return functionCallParts == null || functionCallParts.length === 0 ? void 0 : functionCallParts.map((part) => ({
709
+ toolCallType: "function",
710
+ toolCallId: generateId2(),
711
+ toolName: part.functionCall.name,
712
+ args: JSON.stringify(part.functionCall.args)
713
+ }));
714
+ }
715
+ function getTextFromParts(parts) {
716
+ const textParts = parts == null ? void 0 : parts.filter(
717
+ (part) => "text" in part && part.thought !== true
718
+ );
719
+ return textParts == null || textParts.length === 0 ? void 0 : textParts.map((part) => part.text).join("");
720
+ }
721
+ function getReasoningDetailsFromParts(parts) {
722
+ const reasoningParts = parts == null ? void 0 : parts.filter(
723
+ (part) => "text" in part && part.thought === true && part.text != null
724
+ );
725
+ return reasoningParts == null || reasoningParts.length === 0 ? void 0 : reasoningParts.map((part) => ({ type: "text", text: part.text }));
726
+ }
727
+ function getInlineDataParts(parts) {
728
+ return parts == null ? void 0 : parts.filter(
729
+ (part) => "inlineData" in part
730
+ );
731
+ }
732
+ function extractSources({
733
+ groundingMetadata,
734
+ generateId: generateId2
735
+ }) {
736
+ var _a;
737
+ return (_a = groundingMetadata == null ? void 0 : groundingMetadata.groundingChunks) == null ? void 0 : _a.filter(
738
+ (chunk) => chunk.web != null
739
+ ).map((chunk) => ({
740
+ sourceType: "url",
741
+ id: generateId2(),
742
+ url: chunk.web.uri,
743
+ title: chunk.web.title
744
+ }));
745
+ }
746
+ var contentSchema = z2.object({
747
+ parts: z2.array(
748
+ z2.union([
749
+ // note: order matters since text can be fully empty
750
+ z2.object({
751
+ functionCall: z2.object({
752
+ name: z2.string(),
753
+ args: z2.unknown()
754
+ })
755
+ }),
756
+ z2.object({
757
+ inlineData: z2.object({
758
+ mimeType: z2.string(),
759
+ data: z2.string()
760
+ })
761
+ }),
762
+ z2.object({
763
+ text: z2.string().nullish(),
764
+ thought: z2.boolean().nullish()
765
+ })
766
+ ])
767
+ ).nullish()
768
+ });
769
+ var groundingChunkSchema = z2.object({
770
+ web: z2.object({ uri: z2.string(), title: z2.string() }).nullish(),
771
+ retrievedContext: z2.object({ uri: z2.string(), title: z2.string() }).nullish()
772
+ });
773
+ var groundingMetadataSchema = z2.object({
774
+ webSearchQueries: z2.array(z2.string()).nullish(),
775
+ retrievalQueries: z2.array(z2.string()).nullish(),
776
+ searchEntryPoint: z2.object({ renderedContent: z2.string() }).nullish(),
777
+ groundingChunks: z2.array(groundingChunkSchema).nullish(),
778
+ groundingSupports: z2.array(
779
+ z2.object({
780
+ segment: z2.object({
781
+ startIndex: z2.number().nullish(),
782
+ endIndex: z2.number().nullish(),
783
+ text: z2.string().nullish()
784
+ }),
785
+ segment_text: z2.string().nullish(),
786
+ groundingChunkIndices: z2.array(z2.number()).nullish(),
787
+ supportChunkIndices: z2.array(z2.number()).nullish(),
788
+ confidenceScores: z2.array(z2.number()).nullish(),
789
+ confidenceScore: z2.array(z2.number()).nullish()
790
+ })
791
+ ).nullish(),
792
+ retrievalMetadata: z2.union([
793
+ z2.object({
794
+ webDynamicRetrievalScore: z2.number()
795
+ }),
796
+ z2.object({})
797
+ ]).nullish()
798
+ });
799
+ var safetyRatingSchema = z2.object({
800
+ category: z2.string().nullish(),
801
+ probability: z2.string().nullish(),
802
+ probabilityScore: z2.number().nullish(),
803
+ severity: z2.string().nullish(),
804
+ severityScore: z2.number().nullish(),
805
+ blocked: z2.boolean().nullish()
806
+ });
807
+ var responseSchema = z2.object({
808
+ candidates: z2.array(
809
+ z2.object({
810
+ content: contentSchema.nullish().or(z2.object({}).strict()),
811
+ finishReason: z2.string().nullish(),
812
+ safetyRatings: z2.array(safetyRatingSchema).nullish(),
813
+ groundingMetadata: groundingMetadataSchema.nullish()
814
+ })
815
+ ),
816
+ usageMetadata: z2.object({
817
+ promptTokenCount: z2.number().nullish(),
818
+ candidatesTokenCount: z2.number().nullish(),
819
+ totalTokenCount: z2.number().nullish()
820
+ }).nullish()
821
+ });
822
+ var chunkSchema = z2.object({
823
+ candidates: z2.array(
824
+ z2.object({
825
+ content: contentSchema.nullish(),
826
+ finishReason: z2.string().nullish(),
827
+ safetyRatings: z2.array(safetyRatingSchema).nullish(),
828
+ groundingMetadata: groundingMetadataSchema.nullish()
829
+ })
830
+ ).nullish(),
831
+ usageMetadata: z2.object({
832
+ promptTokenCount: z2.number().nullish(),
833
+ candidatesTokenCount: z2.number().nullish(),
834
+ totalTokenCount: z2.number().nullish()
835
+ }).nullish()
836
+ });
837
+ var googleGenerativeAIProviderOptionsSchema = z2.object({
838
+ responseModalities: z2.array(z2.enum(["TEXT", "IMAGE"])).nullish(),
839
+ thinkingConfig: z2.object({
840
+ thinkingBudget: z2.number().nullish(),
841
+ includeThoughts: z2.boolean().nullish()
842
+ }).nullish()
843
+ });
844
+ var GoogleGenerativeAIEmbeddingModel = class {
845
+ constructor(modelId, settings, config) {
846
+ this.specificationVersion = "v1";
847
+ this.modelId = modelId;
848
+ this.settings = settings;
849
+ this.config = config;
850
+ }
851
+ get provider() {
852
+ return this.config.provider;
853
+ }
854
+ get maxEmbeddingsPerCall() {
855
+ return 2048;
856
+ }
857
+ get supportsParallelCalls() {
858
+ return true;
859
+ }
860
+ async doEmbed({
861
+ values,
862
+ headers,
863
+ abortSignal
864
+ }) {
865
+ if (values.length > this.maxEmbeddingsPerCall) {
866
+ throw new TooManyEmbeddingValuesForCallError({
867
+ provider: this.provider,
868
+ modelId: this.modelId,
869
+ maxEmbeddingsPerCall: this.maxEmbeddingsPerCall,
870
+ values
871
+ });
872
+ }
873
+ const mergedHeaders = combineHeaders(
874
+ await resolve(this.config.headers),
875
+ headers
876
+ );
877
+ const { responseHeaders, value: response } = await postJsonToApi({
878
+ url: `${this.config.baseURL}/models/${this.modelId}:batchEmbedContents`,
879
+ headers: mergedHeaders,
880
+ body: {
881
+ requests: values.map((value) => ({
882
+ model: `models/${this.modelId}`,
883
+ content: { role: "user", parts: [{ text: value }] },
884
+ outputDimensionality: this.settings.outputDimensionality,
885
+ taskType: this.settings.taskType
886
+ }))
887
+ },
888
+ failedResponseHandler: googleFailedResponseHandler,
889
+ successfulResponseHandler: createJsonResponseHandler(
890
+ googleGenerativeAITextEmbeddingResponseSchema
891
+ ),
892
+ abortSignal,
893
+ fetch: this.config.fetch
894
+ });
895
+ return {
896
+ embeddings: response.embeddings.map((item) => item.values),
897
+ usage: void 0,
898
+ rawResponse: { headers: responseHeaders }
899
+ };
900
+ }
901
+ };
902
+ var googleGenerativeAITextEmbeddingResponseSchema = z3.object({
903
+ embeddings: z3.array(z3.object({ values: z3.array(z3.number()) }))
904
+ });
905
+ function isSupportedFileUrl(url) {
906
+ return url.toString().startsWith("https://generativelanguage.googleapis.com/v1beta/files/");
907
+ }
908
+ function createGoogleGenerativeAI(options = {}) {
909
+ var _a;
910
+ const baseURL = (_a = withoutTrailingSlash(options.baseURL)) != null ? _a : "https://generativelanguage.googleapis.com/v1beta";
911
+ const getHeaders = () => ({
912
+ "x-goog-api-key": loadApiKey({
913
+ apiKey: options.apiKey,
914
+ environmentVariableName: "GOOGLE_GENERATIVE_AI_API_KEY",
915
+ description: "Google Generative AI"
916
+ }),
917
+ ...options.headers
918
+ });
919
+ const createChatModel = (modelId, settings = {}) => {
920
+ var _a2;
921
+ return new GoogleGenerativeAILanguageModel(modelId, settings, {
922
+ provider: "google.generative-ai",
923
+ baseURL,
924
+ headers: getHeaders,
925
+ generateId: (_a2 = options.generateId) != null ? _a2 : generateId,
926
+ isSupportedUrl: isSupportedFileUrl,
927
+ fetch: options.fetch
928
+ });
929
+ };
930
+ const createEmbeddingModel = (modelId, settings = {}) => new GoogleGenerativeAIEmbeddingModel(modelId, settings, {
931
+ provider: "google.generative-ai",
932
+ baseURL,
933
+ headers: getHeaders,
934
+ fetch: options.fetch
935
+ });
936
+ const provider = function(modelId, settings) {
937
+ if (new.target) {
938
+ throw new Error(
939
+ "The Google Generative AI model function cannot be called with the new keyword."
940
+ );
941
+ }
942
+ return createChatModel(modelId, settings);
943
+ };
944
+ provider.languageModel = createChatModel;
945
+ provider.chat = createChatModel;
946
+ provider.generativeAI = createChatModel;
947
+ provider.embedding = createEmbeddingModel;
948
+ provider.textEmbedding = createEmbeddingModel;
949
+ provider.textEmbeddingModel = createEmbeddingModel;
950
+ return provider;
951
+ }
952
+ var google = createGoogleGenerativeAI();
953
+ export {
954
+ createGoogleGenerativeAI,
955
+ google
956
+ };