ai 3.0.12 → 3.0.14

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (57) hide show
  1. package/README.md +1 -1
  2. package/ai-model-specification/dist/index.d.mts +704 -0
  3. package/ai-model-specification/dist/index.d.ts +704 -0
  4. package/ai-model-specification/dist/index.js +806 -0
  5. package/ai-model-specification/dist/index.js.map +1 -0
  6. package/ai-model-specification/dist/index.mjs +742 -0
  7. package/ai-model-specification/dist/index.mjs.map +1 -0
  8. package/dist/index.d.mts +686 -4
  9. package/dist/index.d.ts +686 -4
  10. package/dist/index.js +1723 -15
  11. package/dist/index.js.map +1 -1
  12. package/dist/index.mjs +1700 -15
  13. package/dist/index.mjs.map +1 -1
  14. package/mistral/dist/index.d.mts +367 -0
  15. package/mistral/dist/index.d.ts +367 -0
  16. package/mistral/dist/index.js +936 -0
  17. package/mistral/dist/index.js.map +1 -0
  18. package/mistral/dist/index.mjs +900 -0
  19. package/mistral/dist/index.mjs.map +1 -0
  20. package/openai/dist/index.d.mts +430 -0
  21. package/openai/dist/index.d.ts +430 -0
  22. package/openai/dist/index.js +1355 -0
  23. package/openai/dist/index.js.map +1 -0
  24. package/openai/dist/index.mjs +1319 -0
  25. package/openai/dist/index.mjs.map +1 -0
  26. package/package.json +33 -7
  27. package/prompts/dist/index.d.mts +13 -1
  28. package/prompts/dist/index.d.ts +13 -1
  29. package/prompts/dist/index.js +13 -0
  30. package/prompts/dist/index.js.map +1 -1
  31. package/prompts/dist/index.mjs +12 -0
  32. package/prompts/dist/index.mjs.map +1 -1
  33. package/react/dist/index.d.mts +8 -4
  34. package/react/dist/index.d.ts +8 -4
  35. package/react/dist/index.js +36 -34
  36. package/react/dist/index.js.map +1 -1
  37. package/react/dist/index.mjs +36 -34
  38. package/react/dist/index.mjs.map +1 -1
  39. package/rsc/dist/index.d.ts +45 -8
  40. package/rsc/dist/rsc-server.d.mts +45 -8
  41. package/rsc/dist/rsc-server.mjs +67 -13
  42. package/rsc/dist/rsc-server.mjs.map +1 -1
  43. package/rsc/dist/rsc-shared.d.mts +5 -8
  44. package/rsc/dist/rsc-shared.mjs +23 -2
  45. package/rsc/dist/rsc-shared.mjs.map +1 -1
  46. package/solid/dist/index.js +29 -27
  47. package/solid/dist/index.js.map +1 -1
  48. package/solid/dist/index.mjs +29 -27
  49. package/solid/dist/index.mjs.map +1 -1
  50. package/svelte/dist/index.js +31 -29
  51. package/svelte/dist/index.js.map +1 -1
  52. package/svelte/dist/index.mjs +31 -29
  53. package/svelte/dist/index.mjs.map +1 -1
  54. package/vue/dist/index.js +29 -27
  55. package/vue/dist/index.js.map +1 -1
  56. package/vue/dist/index.mjs +29 -27
  57. package/vue/dist/index.mjs.map +1 -1
@@ -0,0 +1,936 @@
1
+ "use strict";
2
+ var __create = Object.create;
3
+ var __defProp = Object.defineProperty;
4
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
5
+ var __getOwnPropNames = Object.getOwnPropertyNames;
6
+ var __getProtoOf = Object.getPrototypeOf;
7
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
8
+ var __export = (target, all) => {
9
+ for (var name in all)
10
+ __defProp(target, name, { get: all[name], enumerable: true });
11
+ };
12
+ var __copyProps = (to, from, except, desc) => {
13
+ if (from && typeof from === "object" || typeof from === "function") {
14
+ for (let key of __getOwnPropNames(from))
15
+ if (!__hasOwnProp.call(to, key) && key !== except)
16
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
17
+ }
18
+ return to;
19
+ };
20
+ var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
21
+ // If the importer is in node compatibility mode or this is not an ESM
22
+ // file that has been converted to a CommonJS file using a Babel-
23
+ // compatible transform (i.e. "__esModule" has not been set), then set
24
+ // "default" to the CommonJS "module.exports" for node compatibility.
25
+ isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
26
+ mod
27
+ ));
28
+ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
29
+
30
+ // mistral/index.ts
31
+ var mistral_exports = {};
32
+ __export(mistral_exports, {
33
+ Mistral: () => Mistral,
34
+ mistral: () => mistral
35
+ });
36
+ module.exports = __toCommonJS(mistral_exports);
37
+
38
+ // ai-model-specification/errors/api-call-error.ts
39
+ var APICallError = class extends Error {
40
+ constructor({
41
+ message,
42
+ url,
43
+ requestBodyValues,
44
+ statusCode,
45
+ responseBody,
46
+ cause,
47
+ isRetryable = statusCode != null && (statusCode === 408 || // request timeout
48
+ statusCode === 409 || // conflict
49
+ statusCode === 429 || // too many requests
50
+ statusCode >= 500),
51
+ // server error
52
+ data
53
+ }) {
54
+ super(message);
55
+ this.name = "AI_APICallError";
56
+ this.url = url;
57
+ this.requestBodyValues = requestBodyValues;
58
+ this.statusCode = statusCode;
59
+ this.responseBody = responseBody;
60
+ this.cause = cause;
61
+ this.isRetryable = isRetryable;
62
+ this.data = data;
63
+ }
64
+ static isAPICallError(error) {
65
+ return error instanceof Error && error.name === "AI_APICallError" && typeof error.url === "string" && typeof error.requestBodyValues === "object" && (error.statusCode == null || typeof error.statusCode === "number") && (error.responseBody == null || typeof error.responseBody === "string") && (error.cause == null || typeof error.cause === "object") && typeof error.isRetryable === "boolean" && (error.data == null || typeof error.data === "object");
66
+ }
67
+ toJSON() {
68
+ return {
69
+ name: this.name,
70
+ message: this.message,
71
+ url: this.url,
72
+ requestBodyValues: this.requestBodyValues,
73
+ statusCode: this.statusCode,
74
+ responseBody: this.responseBody,
75
+ cause: this.cause,
76
+ isRetryable: this.isRetryable,
77
+ data: this.data
78
+ };
79
+ }
80
+ };
81
+
82
+ // ai-model-specification/util/generate-id.ts
83
+ var import_non_secure = require("nanoid/non-secure");
84
+ var generateId = (0, import_non_secure.customAlphabet)(
85
+ "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz",
86
+ 7
87
+ );
88
+
89
+ // ai-model-specification/util/get-error-message.ts
90
+ function getErrorMessage(error) {
91
+ if (error == null) {
92
+ return "unknown error";
93
+ }
94
+ if (typeof error === "string") {
95
+ return error;
96
+ }
97
+ if (error instanceof Error) {
98
+ return error.message;
99
+ }
100
+ return JSON.stringify(error);
101
+ }
102
+
103
+ // ai-model-specification/errors/load-api-key-error.ts
104
+ var LoadAPIKeyError = class extends Error {
105
+ constructor({ message }) {
106
+ super(message);
107
+ this.name = "AI_LoadAPIKeyError";
108
+ }
109
+ static isLoadAPIKeyError(error) {
110
+ return error instanceof Error && error.name === "AI_LoadAPIKeyError";
111
+ }
112
+ toJSON() {
113
+ return {
114
+ name: this.name,
115
+ message: this.message
116
+ };
117
+ }
118
+ };
119
+
120
+ // ai-model-specification/util/load-api-key.ts
121
+ function loadApiKey({
122
+ apiKey,
123
+ environmentVariableName,
124
+ apiKeyParameterName = "apiKey",
125
+ description
126
+ }) {
127
+ if (typeof apiKey === "string") {
128
+ return apiKey;
129
+ }
130
+ if (apiKey != null) {
131
+ throw new LoadAPIKeyError({
132
+ message: `${description} API key must be a string.`
133
+ });
134
+ }
135
+ if (typeof process === "undefined") {
136
+ throw new LoadAPIKeyError({
137
+ message: `${description} API key is missing. Pass it using the '${apiKeyParameterName}' parameter. Environment variables is not supported in this environment.`
138
+ });
139
+ }
140
+ apiKey = process.env[environmentVariableName];
141
+ if (apiKey == null) {
142
+ throw new LoadAPIKeyError({
143
+ message: `${description} API key is missing. Pass it using the '${apiKeyParameterName}' parameter or the ${environmentVariableName} environment variable.`
144
+ });
145
+ }
146
+ if (typeof apiKey !== "string") {
147
+ throw new LoadAPIKeyError({
148
+ message: `${description} API key must be a string. The value of the ${environmentVariableName} environment variable is not a string.`
149
+ });
150
+ }
151
+ return apiKey;
152
+ }
153
+
154
+ // ai-model-specification/util/parse-json.ts
155
+ var import_secure_json_parse = __toESM(require("secure-json-parse"));
156
+
157
+ // ai-model-specification/errors/json-parse-error.ts
158
+ var JSONParseError = class extends Error {
159
+ constructor({ text, cause }) {
160
+ super(
161
+ `JSON parsing failed: Text: ${text}.
162
+ Error message: ${getErrorMessage(cause)}`
163
+ );
164
+ this.name = "AI_JSONParseError";
165
+ this.cause = cause;
166
+ this.text = text;
167
+ }
168
+ static isJSONParseError(error) {
169
+ return error instanceof Error && error.name === "AI_JSONParseError" && typeof error.text === "string" && typeof error.cause === "string";
170
+ }
171
+ toJSON() {
172
+ return {
173
+ name: this.name,
174
+ message: this.message,
175
+ cause: this.cause,
176
+ stack: this.stack,
177
+ valueText: this.text
178
+ };
179
+ }
180
+ };
181
+
182
+ // ai-model-specification/errors/type-validation-error.ts
183
+ var TypeValidationError = class extends Error {
184
+ constructor({ value, cause }) {
185
+ super(
186
+ `Type validation failed: Value: ${JSON.stringify(value)}.
187
+ Error message: ${getErrorMessage(cause)}`
188
+ );
189
+ this.name = "AI_TypeValidationError";
190
+ this.cause = cause;
191
+ this.value = value;
192
+ }
193
+ static isTypeValidationError(error) {
194
+ return error instanceof Error && error.name === "AI_TypeValidationError" && typeof error.value === "string" && typeof error.cause === "string";
195
+ }
196
+ toJSON() {
197
+ return {
198
+ name: this.name,
199
+ message: this.message,
200
+ cause: this.cause,
201
+ stack: this.stack,
202
+ value: this.value
203
+ };
204
+ }
205
+ };
206
+
207
+ // ai-model-specification/util/validate-types.ts
208
+ function validateTypes({
209
+ value,
210
+ schema
211
+ }) {
212
+ try {
213
+ return schema.parse(value);
214
+ } catch (error) {
215
+ throw new TypeValidationError({ value, cause: error });
216
+ }
217
+ }
218
+ function safeValidateTypes({
219
+ value,
220
+ schema
221
+ }) {
222
+ try {
223
+ const validationResult = schema.safeParse(value);
224
+ if (validationResult.success) {
225
+ return {
226
+ success: true,
227
+ value: validationResult.data
228
+ };
229
+ }
230
+ return {
231
+ success: false,
232
+ error: new TypeValidationError({
233
+ value,
234
+ cause: validationResult.error
235
+ })
236
+ };
237
+ } catch (error) {
238
+ return {
239
+ success: false,
240
+ error: TypeValidationError.isTypeValidationError(error) ? error : new TypeValidationError({ value, cause: error })
241
+ };
242
+ }
243
+ }
244
+
245
+ // ai-model-specification/util/parse-json.ts
246
+ function parseJSON({
247
+ text,
248
+ schema
249
+ }) {
250
+ try {
251
+ const value = import_secure_json_parse.default.parse(text);
252
+ if (schema == null) {
253
+ return value;
254
+ }
255
+ return validateTypes({ value, schema });
256
+ } catch (error) {
257
+ if (JSONParseError.isJSONParseError(error) || TypeValidationError.isTypeValidationError(error)) {
258
+ throw error;
259
+ }
260
+ throw new JSONParseError({ text, cause: error });
261
+ }
262
+ }
263
+ function safeParseJSON({
264
+ text,
265
+ schema
266
+ }) {
267
+ try {
268
+ const value = import_secure_json_parse.default.parse(text);
269
+ if (schema == null) {
270
+ return {
271
+ success: true,
272
+ value
273
+ };
274
+ }
275
+ return safeValidateTypes({ value, schema });
276
+ } catch (error) {
277
+ return {
278
+ success: false,
279
+ error: JSONParseError.isJSONParseError(error) ? error : new JSONParseError({ text, cause: error })
280
+ };
281
+ }
282
+ }
283
+
284
+ // ai-model-specification/util/post-to-api.ts
285
+ var postJsonToApi = async ({
286
+ url,
287
+ headers,
288
+ body,
289
+ failedResponseHandler,
290
+ successfulResponseHandler,
291
+ abortSignal
292
+ }) => postToApi({
293
+ url,
294
+ headers: {
295
+ ...headers,
296
+ "Content-Type": "application/json"
297
+ },
298
+ body: {
299
+ content: JSON.stringify(body),
300
+ values: body
301
+ },
302
+ failedResponseHandler,
303
+ successfulResponseHandler,
304
+ abortSignal
305
+ });
306
+ var postToApi = async ({
307
+ url,
308
+ headers = {},
309
+ body,
310
+ successfulResponseHandler,
311
+ failedResponseHandler,
312
+ abortSignal
313
+ }) => {
314
+ try {
315
+ const definedHeaders = Object.fromEntries(
316
+ Object.entries(headers).filter(([_key, value]) => value != null)
317
+ );
318
+ const response = await fetch(url, {
319
+ method: "POST",
320
+ headers: definedHeaders,
321
+ body: body.content,
322
+ signal: abortSignal
323
+ });
324
+ if (!response.ok) {
325
+ try {
326
+ throw await failedResponseHandler({
327
+ response,
328
+ url,
329
+ requestBodyValues: body.values
330
+ });
331
+ } catch (error) {
332
+ if (error instanceof Error) {
333
+ if (error.name === "AbortError" || APICallError.isAPICallError(error)) {
334
+ throw error;
335
+ }
336
+ }
337
+ throw new APICallError({
338
+ message: "Failed to process error response",
339
+ cause: error,
340
+ statusCode: response.status,
341
+ url,
342
+ requestBodyValues: body.values
343
+ });
344
+ }
345
+ }
346
+ try {
347
+ return await successfulResponseHandler({
348
+ response,
349
+ url,
350
+ requestBodyValues: body.values
351
+ });
352
+ } catch (error) {
353
+ if (error instanceof Error) {
354
+ if (error.name === "AbortError" || APICallError.isAPICallError(error)) {
355
+ throw error;
356
+ }
357
+ }
358
+ throw new APICallError({
359
+ message: "Failed to process successful response",
360
+ cause: error,
361
+ statusCode: response.status,
362
+ url,
363
+ requestBodyValues: body.values
364
+ });
365
+ }
366
+ } catch (error) {
367
+ if (error instanceof Error) {
368
+ if (error.name === "AbortError") {
369
+ throw error;
370
+ }
371
+ }
372
+ if (error instanceof TypeError && error.message === "fetch failed") {
373
+ const cause = error.cause;
374
+ if (cause != null) {
375
+ throw new APICallError({
376
+ message: `Cannot connect to API: ${cause.message}`,
377
+ cause,
378
+ url,
379
+ requestBodyValues: body.values,
380
+ isRetryable: true
381
+ // retry when network error
382
+ });
383
+ }
384
+ }
385
+ throw error;
386
+ }
387
+ };
388
+
389
+ // ai-model-specification/util/response-handler.ts
390
+ var import_stream = require("eventsource-parser/stream");
391
+
392
+ // ai-model-specification/errors/no-response-body-error.ts
393
+ var NoResponseBodyError = class extends Error {
394
+ constructor({ message = "No response body" } = {}) {
395
+ super(message);
396
+ this.name = "AI_NoResponseBodyError";
397
+ }
398
+ static isNoResponseBodyError(error) {
399
+ return error instanceof Error && error.name === "AI_NoResponseBodyError";
400
+ }
401
+ toJSON() {
402
+ return {
403
+ name: this.name,
404
+ message: this.message,
405
+ stack: this.stack
406
+ };
407
+ }
408
+ };
409
+
410
+ // ai-model-specification/util/response-handler.ts
411
+ var createJsonErrorResponseHandler = ({
412
+ errorSchema,
413
+ errorToMessage,
414
+ isRetryable
415
+ }) => async ({ response, url, requestBodyValues }) => {
416
+ const responseBody = await response.text();
417
+ if (responseBody.trim() === "") {
418
+ return new APICallError({
419
+ message: response.statusText,
420
+ url,
421
+ requestBodyValues,
422
+ statusCode: response.status,
423
+ responseBody,
424
+ isRetryable: isRetryable == null ? void 0 : isRetryable(response)
425
+ });
426
+ }
427
+ try {
428
+ const parsedError = parseJSON({
429
+ text: responseBody,
430
+ schema: errorSchema
431
+ });
432
+ return new APICallError({
433
+ message: errorToMessage(parsedError),
434
+ url,
435
+ requestBodyValues,
436
+ statusCode: response.status,
437
+ responseBody,
438
+ data: parsedError,
439
+ isRetryable: isRetryable == null ? void 0 : isRetryable(response, parsedError)
440
+ });
441
+ } catch (parseError) {
442
+ return new APICallError({
443
+ message: response.statusText,
444
+ url,
445
+ requestBodyValues,
446
+ statusCode: response.status,
447
+ responseBody,
448
+ isRetryable: isRetryable == null ? void 0 : isRetryable(response)
449
+ });
450
+ }
451
+ };
452
+ var createEventSourceResponseHandler = (chunkSchema) => async ({ response }) => {
453
+ if (response.body == null) {
454
+ throw new NoResponseBodyError();
455
+ }
456
+ return response.body.pipeThrough(new TextDecoderStream()).pipeThrough(new import_stream.EventSourceParserStream()).pipeThrough(
457
+ new TransformStream({
458
+ transform({ data }, controller) {
459
+ if (data === "[DONE]") {
460
+ return;
461
+ }
462
+ controller.enqueue(
463
+ safeParseJSON({
464
+ text: data,
465
+ schema: chunkSchema
466
+ })
467
+ );
468
+ }
469
+ })
470
+ );
471
+ };
472
+ var createJsonResponseHandler = (responseSchema) => async ({ response, url, requestBodyValues }) => {
473
+ const responseBody = await response.text();
474
+ const parsedResult = safeParseJSON({
475
+ text: responseBody,
476
+ schema: responseSchema
477
+ });
478
+ if (!parsedResult.success) {
479
+ throw new APICallError({
480
+ message: "Invalid JSON response",
481
+ cause: parsedResult.error,
482
+ statusCode: response.status,
483
+ responseBody,
484
+ url,
485
+ requestBodyValues
486
+ });
487
+ }
488
+ return parsedResult.value;
489
+ };
490
+
491
+ // ai-model-specification/errors/unsupported-functionality-error.ts
492
+ var UnsupportedFunctionalityError = class extends Error {
493
+ constructor({
494
+ provider,
495
+ functionality
496
+ }) {
497
+ super(
498
+ `Functionality not supported by the provider. Provider: ${provider}.
499
+ Functionality: ${functionality}`
500
+ );
501
+ this.name = "AI_UnsupportedFunctionalityError";
502
+ this.provider = provider;
503
+ this.functionality = functionality;
504
+ }
505
+ static isUnsupportedFunctionalityError(error) {
506
+ return error instanceof Error && error.name === "AI_UnsupportedFunctionalityError" && typeof error.provider === "string" && typeof error.functionality === "string";
507
+ }
508
+ toJSON() {
509
+ return {
510
+ name: this.name,
511
+ message: this.message,
512
+ stack: this.stack,
513
+ provider: this.provider,
514
+ functionality: this.functionality
515
+ };
516
+ }
517
+ };
518
+
519
+ // mistral/mistral-chat-language-model.ts
520
+ var import_zod2 = require("zod");
521
+
522
+ // mistral/convert-to-mistral-chat-messages.ts
523
+ function convertToMistralChatMessages({
524
+ prompt,
525
+ provider
526
+ }) {
527
+ const messages = [];
528
+ for (const { role, content } of prompt) {
529
+ switch (role) {
530
+ case "system": {
531
+ messages.push({ role: "system", content });
532
+ break;
533
+ }
534
+ case "user": {
535
+ messages.push({
536
+ role: "user",
537
+ content: content.map((part) => {
538
+ switch (part.type) {
539
+ case "text": {
540
+ return part.text;
541
+ }
542
+ case "image": {
543
+ throw new UnsupportedFunctionalityError({
544
+ provider,
545
+ functionality: "image-part"
546
+ });
547
+ }
548
+ }
549
+ }).join("")
550
+ });
551
+ break;
552
+ }
553
+ case "assistant": {
554
+ let text = "";
555
+ const toolCalls = [];
556
+ for (const part of content) {
557
+ switch (part.type) {
558
+ case "text": {
559
+ text += part.text;
560
+ break;
561
+ }
562
+ case "tool-call": {
563
+ toolCalls.push({
564
+ id: part.toolCallId,
565
+ type: "function",
566
+ function: {
567
+ name: part.toolName,
568
+ arguments: JSON.stringify(part.args)
569
+ }
570
+ });
571
+ break;
572
+ }
573
+ default: {
574
+ const _exhaustiveCheck = part;
575
+ throw new Error(`Unsupported part: ${_exhaustiveCheck}`);
576
+ }
577
+ }
578
+ }
579
+ messages.push({
580
+ role: "assistant",
581
+ content: text,
582
+ tool_calls: toolCalls.length > 0 ? toolCalls.map(({ function: { name, arguments: args } }) => ({
583
+ id: "null",
584
+ type: "function",
585
+ function: { name, arguments: args }
586
+ })) : void 0
587
+ });
588
+ break;
589
+ }
590
+ case "tool": {
591
+ for (const toolResponse of content) {
592
+ messages.push({
593
+ role: "tool",
594
+ name: toolResponse.toolName,
595
+ content: JSON.stringify(toolResponse.result)
596
+ });
597
+ }
598
+ break;
599
+ }
600
+ default: {
601
+ const _exhaustiveCheck = role;
602
+ throw new Error(`Unsupported role: ${_exhaustiveCheck}`);
603
+ }
604
+ }
605
+ }
606
+ return messages;
607
+ }
608
+
609
+ // mistral/map-mistral-finish-reason.ts
610
+ function mapMistralFinishReason(finishReason) {
611
+ switch (finishReason) {
612
+ case "stop":
613
+ return "stop";
614
+ case "length":
615
+ case "model_length":
616
+ return "length";
617
+ case "tool_calls":
618
+ return "tool-calls";
619
+ default:
620
+ return "other";
621
+ }
622
+ }
623
+
624
+ // mistral/mistral-error.ts
625
+ var import_zod = require("zod");
626
+ var mistralErrorDataSchema = import_zod.z.object({
627
+ object: import_zod.z.literal("error"),
628
+ message: import_zod.z.string(),
629
+ type: import_zod.z.string(),
630
+ param: import_zod.z.string().nullable(),
631
+ code: import_zod.z.string().nullable()
632
+ });
633
+ var mistralFailedResponseHandler = createJsonErrorResponseHandler({
634
+ errorSchema: mistralErrorDataSchema,
635
+ errorToMessage: (data) => data.message
636
+ });
637
+
638
+ // mistral/mistral-chat-language-model.ts
639
+ var MistralChatLanguageModel = class {
640
+ constructor(modelId, settings, config) {
641
+ this.specificationVersion = "v1";
642
+ this.defaultObjectGenerationMode = "json";
643
+ this.modelId = modelId;
644
+ this.settings = settings;
645
+ this.config = config;
646
+ }
647
+ get provider() {
648
+ return this.config.provider;
649
+ }
650
+ getArgs({
651
+ mode,
652
+ prompt,
653
+ maxTokens,
654
+ temperature,
655
+ topP,
656
+ frequencyPenalty,
657
+ presencePenalty,
658
+ seed
659
+ }) {
660
+ var _a;
661
+ const type = mode.type;
662
+ const warnings = [];
663
+ if (frequencyPenalty != null) {
664
+ warnings.push({
665
+ type: "unsupported-setting",
666
+ setting: "frequencyPenalty"
667
+ });
668
+ }
669
+ if (presencePenalty != null) {
670
+ warnings.push({
671
+ type: "unsupported-setting",
672
+ setting: "presencePenalty"
673
+ });
674
+ }
675
+ const baseArgs = {
676
+ // model id:
677
+ model: this.modelId,
678
+ // model specific settings:
679
+ safe_prompt: this.settings.safePrompt,
680
+ // standardized settings:
681
+ max_tokens: maxTokens,
682
+ temperature,
683
+ // uses 0..1 scale
684
+ top_p: topP,
685
+ random_seed: seed,
686
+ // messages:
687
+ messages: convertToMistralChatMessages({
688
+ provider: this.provider,
689
+ prompt
690
+ })
691
+ };
692
+ switch (type) {
693
+ case "regular": {
694
+ const tools = ((_a = mode.tools) == null ? void 0 : _a.length) ? mode.tools : void 0;
695
+ return {
696
+ args: {
697
+ ...baseArgs,
698
+ tools: tools == null ? void 0 : tools.map((tool) => ({
699
+ type: "function",
700
+ function: {
701
+ name: tool.name,
702
+ description: tool.description,
703
+ parameters: tool.parameters
704
+ }
705
+ }))
706
+ },
707
+ warnings
708
+ };
709
+ }
710
+ case "object-json": {
711
+ return {
712
+ args: {
713
+ ...baseArgs,
714
+ response_format: { type: "json_object" }
715
+ },
716
+ warnings
717
+ };
718
+ }
719
+ case "object-tool": {
720
+ return {
721
+ args: {
722
+ ...baseArgs,
723
+ tool_choice: "any",
724
+ tools: [{ type: "function", function: mode.tool }]
725
+ },
726
+ warnings
727
+ };
728
+ }
729
+ case "object-grammar": {
730
+ throw new UnsupportedFunctionalityError({
731
+ functionality: "object-grammar mode",
732
+ provider: this.provider
733
+ });
734
+ }
735
+ default: {
736
+ const _exhaustiveCheck = type;
737
+ throw new Error(`Unsupported type: ${_exhaustiveCheck}`);
738
+ }
739
+ }
740
+ }
741
+ async doGenerate(options) {
742
+ var _a, _b;
743
+ const { args, warnings } = this.getArgs(options);
744
+ const response = await postJsonToApi({
745
+ url: `${this.config.baseUrl}/chat/completions`,
746
+ headers: this.config.headers(),
747
+ body: args,
748
+ failedResponseHandler: mistralFailedResponseHandler,
749
+ successfulResponseHandler: createJsonResponseHandler(
750
+ openAIChatResponseSchema
751
+ ),
752
+ abortSignal: options.abortSignal
753
+ });
754
+ const { messages: rawPrompt, ...rawSettings } = args;
755
+ const choice = response.choices[0];
756
+ return {
757
+ text: (_a = choice.message.content) != null ? _a : void 0,
758
+ toolCalls: (_b = choice.message.tool_calls) == null ? void 0 : _b.map((toolCall) => ({
759
+ toolCallType: "function",
760
+ toolCallId: this.config.generateId(),
761
+ toolName: toolCall.function.name,
762
+ args: toolCall.function.arguments
763
+ })),
764
+ finishReason: mapMistralFinishReason(choice.finish_reason),
765
+ usage: {
766
+ promptTokens: response.usage.prompt_tokens,
767
+ completionTokens: response.usage.completion_tokens
768
+ },
769
+ rawCall: { rawPrompt, rawSettings },
770
+ warnings
771
+ };
772
+ }
773
+ async doStream(options) {
774
+ const { args, warnings } = this.getArgs(options);
775
+ const response = await postJsonToApi({
776
+ url: `${this.config.baseUrl}/chat/completions`,
777
+ headers: this.config.headers(),
778
+ body: {
779
+ ...args,
780
+ stream: true
781
+ },
782
+ failedResponseHandler: mistralFailedResponseHandler,
783
+ successfulResponseHandler: createEventSourceResponseHandler(
784
+ mistralChatChunkSchema
785
+ ),
786
+ abortSignal: options.abortSignal
787
+ });
788
+ const { messages: rawPrompt, ...rawSettings } = args;
789
+ let finishReason = "other";
790
+ let usage = {
791
+ promptTokens: Number.NaN,
792
+ completionTokens: Number.NaN
793
+ };
794
+ const generateId2 = this.config.generateId;
795
+ return {
796
+ stream: response.pipeThrough(
797
+ new TransformStream({
798
+ transform(chunk, controller) {
799
+ if (!chunk.success) {
800
+ controller.enqueue({ type: "error", error: chunk.error });
801
+ return;
802
+ }
803
+ const value = chunk.value;
804
+ if (value.usage != null) {
805
+ usage = {
806
+ promptTokens: value.usage.prompt_tokens,
807
+ completionTokens: value.usage.completion_tokens
808
+ };
809
+ }
810
+ const choice = value.choices[0];
811
+ if ((choice == null ? void 0 : choice.finish_reason) != null) {
812
+ finishReason = mapMistralFinishReason(choice.finish_reason);
813
+ }
814
+ if ((choice == null ? void 0 : choice.delta) == null) {
815
+ return;
816
+ }
817
+ const delta = choice.delta;
818
+ if (delta.content != null) {
819
+ controller.enqueue({
820
+ type: "text-delta",
821
+ textDelta: delta.content
822
+ });
823
+ }
824
+ if (delta.tool_calls != null) {
825
+ for (const toolCall of delta.tool_calls) {
826
+ controller.enqueue({
827
+ type: "tool-call-delta",
828
+ toolCallType: "function",
829
+ toolCallId: generateId2(),
830
+ toolName: toolCall.function.name,
831
+ argsTextDelta: toolCall.function.arguments
832
+ });
833
+ controller.enqueue({
834
+ type: "tool-call",
835
+ toolCallType: "function",
836
+ toolCallId: generateId2(),
837
+ toolName: toolCall.function.name,
838
+ args: toolCall.function.arguments
839
+ });
840
+ }
841
+ }
842
+ },
843
+ flush(controller) {
844
+ controller.enqueue({ type: "finish", finishReason, usage });
845
+ }
846
+ })
847
+ ),
848
+ rawCall: { rawPrompt, rawSettings },
849
+ warnings
850
+ };
851
+ }
852
+ };
853
+ var openAIChatResponseSchema = import_zod2.z.object({
854
+ choices: import_zod2.z.array(
855
+ import_zod2.z.object({
856
+ message: import_zod2.z.object({
857
+ role: import_zod2.z.literal("assistant"),
858
+ content: import_zod2.z.string().nullable(),
859
+ tool_calls: import_zod2.z.array(
860
+ import_zod2.z.object({
861
+ function: import_zod2.z.object({
862
+ name: import_zod2.z.string(),
863
+ arguments: import_zod2.z.string()
864
+ })
865
+ })
866
+ ).optional().nullable()
867
+ }),
868
+ index: import_zod2.z.number(),
869
+ finish_reason: import_zod2.z.string().optional().nullable()
870
+ })
871
+ ),
872
+ object: import_zod2.z.literal("chat.completion"),
873
+ usage: import_zod2.z.object({
874
+ prompt_tokens: import_zod2.z.number(),
875
+ completion_tokens: import_zod2.z.number()
876
+ })
877
+ });
878
+ var mistralChatChunkSchema = import_zod2.z.object({
879
+ object: import_zod2.z.literal("chat.completion.chunk"),
880
+ choices: import_zod2.z.array(
881
+ import_zod2.z.object({
882
+ delta: import_zod2.z.object({
883
+ role: import_zod2.z.enum(["assistant"]).optional(),
884
+ content: import_zod2.z.string().nullable().optional(),
885
+ tool_calls: import_zod2.z.array(
886
+ import_zod2.z.object({
887
+ function: import_zod2.z.object({ name: import_zod2.z.string(), arguments: import_zod2.z.string() })
888
+ })
889
+ ).optional().nullable()
890
+ }),
891
+ finish_reason: import_zod2.z.string().nullable().optional(),
892
+ index: import_zod2.z.number()
893
+ })
894
+ ),
895
+ usage: import_zod2.z.object({
896
+ prompt_tokens: import_zod2.z.number(),
897
+ completion_tokens: import_zod2.z.number()
898
+ }).optional().nullable()
899
+ });
900
+
901
+ // mistral/mistral-facade.ts
902
+ var Mistral = class {
903
+ constructor(options = {}) {
904
+ var _a;
905
+ this.baseUrl = options.baseUrl;
906
+ this.apiKey = options.apiKey;
907
+ this.generateId = (_a = options.generateId) != null ? _a : generateId;
908
+ }
909
+ get baseConfig() {
910
+ var _a;
911
+ return {
912
+ baseUrl: (_a = this.baseUrl) != null ? _a : "https://api.mistral.ai/v1",
913
+ headers: () => ({
914
+ Authorization: `Bearer ${loadApiKey({
915
+ apiKey: this.apiKey,
916
+ environmentVariableName: "MISTRAL_API_KEY",
917
+ description: "Mistral"
918
+ })}`
919
+ })
920
+ };
921
+ }
922
+ chat(modelId, settings = {}) {
923
+ return new MistralChatLanguageModel(modelId, settings, {
924
+ provider: "mistral.chat",
925
+ ...this.baseConfig,
926
+ generateId: this.generateId
927
+ });
928
+ }
929
+ };
930
+ var mistral = new Mistral();
931
+ // Annotate the CommonJS export names for ESM import in node:
932
+ 0 && (module.exports = {
933
+ Mistral,
934
+ mistral
935
+ });
936
+ //# sourceMappingURL=index.js.map