ai 3.0.20 → 3.0.22

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 (63) hide show
  1. package/dist/index.d.mts +45 -354
  2. package/dist/index.d.ts +45 -354
  3. package/dist/index.js +161 -460
  4. package/dist/index.js.map +1 -1
  5. package/dist/index.mjs +136 -430
  6. package/dist/index.mjs.map +1 -1
  7. package/package.json +6 -41
  8. package/react/dist/index.d.mts +1 -1
  9. package/react/dist/index.d.ts +1 -1
  10. package/react/dist/index.js +3 -3
  11. package/react/dist/index.js.map +1 -1
  12. package/react/dist/index.mjs +3 -3
  13. package/react/dist/index.mjs.map +1 -1
  14. package/rsc/dist/rsc-server.mjs +3 -3
  15. package/rsc/dist/rsc-server.mjs.map +1 -1
  16. package/solid/dist/index.d.mts +1 -1
  17. package/solid/dist/index.d.ts +1 -1
  18. package/solid/dist/index.js +3 -3
  19. package/solid/dist/index.js.map +1 -1
  20. package/solid/dist/index.mjs +3 -3
  21. package/solid/dist/index.mjs.map +1 -1
  22. package/svelte/dist/index.d.mts +1 -1
  23. package/svelte/dist/index.d.ts +1 -1
  24. package/svelte/dist/index.js +3 -3
  25. package/svelte/dist/index.js.map +1 -1
  26. package/svelte/dist/index.mjs +3 -3
  27. package/svelte/dist/index.mjs.map +1 -1
  28. package/vue/dist/index.d.mts +1 -1
  29. package/vue/dist/index.d.ts +1 -1
  30. package/vue/dist/index.js +3 -3
  31. package/vue/dist/index.js.map +1 -1
  32. package/vue/dist/index.mjs +3 -3
  33. package/vue/dist/index.mjs.map +1 -1
  34. package/anthropic/dist/index.d.mts +0 -403
  35. package/anthropic/dist/index.d.ts +0 -403
  36. package/anthropic/dist/index.js +0 -950
  37. package/anthropic/dist/index.js.map +0 -1
  38. package/anthropic/dist/index.mjs +0 -914
  39. package/anthropic/dist/index.mjs.map +0 -1
  40. package/google/dist/index.d.mts +0 -399
  41. package/google/dist/index.d.ts +0 -399
  42. package/google/dist/index.js +0 -954
  43. package/google/dist/index.js.map +0 -1
  44. package/google/dist/index.mjs +0 -918
  45. package/google/dist/index.mjs.map +0 -1
  46. package/mistral/dist/index.d.mts +0 -404
  47. package/mistral/dist/index.d.ts +0 -404
  48. package/mistral/dist/index.js +0 -921
  49. package/mistral/dist/index.js.map +0 -1
  50. package/mistral/dist/index.mjs +0 -885
  51. package/mistral/dist/index.mjs.map +0 -1
  52. package/openai/dist/index.d.mts +0 -468
  53. package/openai/dist/index.d.ts +0 -468
  54. package/openai/dist/index.js +0 -1334
  55. package/openai/dist/index.js.map +0 -1
  56. package/openai/dist/index.mjs +0 -1298
  57. package/openai/dist/index.mjs.map +0 -1
  58. package/spec/dist/index.d.mts +0 -780
  59. package/spec/dist/index.d.ts +0 -780
  60. package/spec/dist/index.js +0 -863
  61. package/spec/dist/index.js.map +0 -1
  62. package/spec/dist/index.mjs +0 -797
  63. package/spec/dist/index.mjs.map +0 -1
@@ -1,921 +0,0 @@
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
- // spec/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
- // spec/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
- // spec/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
- // spec/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
- // spec/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
- // spec/util/parse-json.ts
155
- var import_secure_json_parse = __toESM(require("secure-json-parse"));
156
-
157
- // spec/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
- // spec/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
- // spec/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
- // spec/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
- // spec/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
- // spec/util/response-handler.ts
390
- var import_stream = require("eventsource-parser/stream");
391
-
392
- // spec/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
- // spec/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
- // spec/errors/unsupported-functionality-error.ts
492
- var UnsupportedFunctionalityError = class extends Error {
493
- constructor({ functionality }) {
494
- super(`'${functionality}' functionality not supported.`);
495
- this.name = "AI_UnsupportedFunctionalityError";
496
- this.functionality = functionality;
497
- }
498
- static isUnsupportedFunctionalityError(error) {
499
- return error instanceof Error && error.name === "AI_UnsupportedFunctionalityError" && typeof error.functionality === "string";
500
- }
501
- toJSON() {
502
- return {
503
- name: this.name,
504
- message: this.message,
505
- stack: this.stack,
506
- functionality: this.functionality
507
- };
508
- }
509
- };
510
-
511
- // mistral/mistral-chat-language-model.ts
512
- var import_zod2 = require("zod");
513
-
514
- // mistral/convert-to-mistral-chat-messages.ts
515
- function convertToMistralChatMessages(prompt) {
516
- const messages = [];
517
- for (const { role, content } of prompt) {
518
- switch (role) {
519
- case "system": {
520
- messages.push({ role: "system", content });
521
- break;
522
- }
523
- case "user": {
524
- messages.push({
525
- role: "user",
526
- content: content.map((part) => {
527
- switch (part.type) {
528
- case "text": {
529
- return part.text;
530
- }
531
- case "image": {
532
- throw new UnsupportedFunctionalityError({
533
- functionality: "image-part"
534
- });
535
- }
536
- }
537
- }).join("")
538
- });
539
- break;
540
- }
541
- case "assistant": {
542
- let text = "";
543
- const toolCalls = [];
544
- for (const part of content) {
545
- switch (part.type) {
546
- case "text": {
547
- text += part.text;
548
- break;
549
- }
550
- case "tool-call": {
551
- toolCalls.push({
552
- id: part.toolCallId,
553
- type: "function",
554
- function: {
555
- name: part.toolName,
556
- arguments: JSON.stringify(part.args)
557
- }
558
- });
559
- break;
560
- }
561
- default: {
562
- const _exhaustiveCheck = part;
563
- throw new Error(`Unsupported part: ${_exhaustiveCheck}`);
564
- }
565
- }
566
- }
567
- messages.push({
568
- role: "assistant",
569
- content: text,
570
- tool_calls: toolCalls.length > 0 ? toolCalls.map(({ function: { name, arguments: args } }) => ({
571
- id: "null",
572
- type: "function",
573
- function: { name, arguments: args }
574
- })) : void 0
575
- });
576
- break;
577
- }
578
- case "tool": {
579
- for (const toolResponse of content) {
580
- messages.push({
581
- role: "tool",
582
- name: toolResponse.toolName,
583
- content: JSON.stringify(toolResponse.result)
584
- });
585
- }
586
- break;
587
- }
588
- default: {
589
- const _exhaustiveCheck = role;
590
- throw new Error(`Unsupported role: ${_exhaustiveCheck}`);
591
- }
592
- }
593
- }
594
- return messages;
595
- }
596
-
597
- // mistral/map-mistral-finish-reason.ts
598
- function mapMistralFinishReason(finishReason) {
599
- switch (finishReason) {
600
- case "stop":
601
- return "stop";
602
- case "length":
603
- case "model_length":
604
- return "length";
605
- case "tool_calls":
606
- return "tool-calls";
607
- default:
608
- return "other";
609
- }
610
- }
611
-
612
- // mistral/mistral-error.ts
613
- var import_zod = require("zod");
614
- var mistralErrorDataSchema = import_zod.z.object({
615
- object: import_zod.z.literal("error"),
616
- message: import_zod.z.string(),
617
- type: import_zod.z.string(),
618
- param: import_zod.z.string().nullable(),
619
- code: import_zod.z.string().nullable()
620
- });
621
- var mistralFailedResponseHandler = createJsonErrorResponseHandler({
622
- errorSchema: mistralErrorDataSchema,
623
- errorToMessage: (data) => data.message
624
- });
625
-
626
- // mistral/mistral-chat-language-model.ts
627
- var MistralChatLanguageModel = class {
628
- constructor(modelId, settings, config) {
629
- this.specificationVersion = "v1";
630
- this.defaultObjectGenerationMode = "json";
631
- this.modelId = modelId;
632
- this.settings = settings;
633
- this.config = config;
634
- }
635
- get provider() {
636
- return this.config.provider;
637
- }
638
- getArgs({
639
- mode,
640
- prompt,
641
- maxTokens,
642
- temperature,
643
- topP,
644
- frequencyPenalty,
645
- presencePenalty,
646
- seed
647
- }) {
648
- var _a;
649
- const type = mode.type;
650
- const warnings = [];
651
- if (frequencyPenalty != null) {
652
- warnings.push({
653
- type: "unsupported-setting",
654
- setting: "frequencyPenalty"
655
- });
656
- }
657
- if (presencePenalty != null) {
658
- warnings.push({
659
- type: "unsupported-setting",
660
- setting: "presencePenalty"
661
- });
662
- }
663
- const baseArgs = {
664
- // model id:
665
- model: this.modelId,
666
- // model specific settings:
667
- safe_prompt: this.settings.safePrompt,
668
- // standardized settings:
669
- max_tokens: maxTokens,
670
- temperature,
671
- // uses 0..1 scale
672
- top_p: topP,
673
- random_seed: seed,
674
- // messages:
675
- messages: convertToMistralChatMessages(prompt)
676
- };
677
- switch (type) {
678
- case "regular": {
679
- const tools = ((_a = mode.tools) == null ? void 0 : _a.length) ? mode.tools : void 0;
680
- return {
681
- args: {
682
- ...baseArgs,
683
- tools: tools == null ? void 0 : tools.map((tool) => ({
684
- type: "function",
685
- function: {
686
- name: tool.name,
687
- description: tool.description,
688
- parameters: tool.parameters
689
- }
690
- }))
691
- },
692
- warnings
693
- };
694
- }
695
- case "object-json": {
696
- return {
697
- args: {
698
- ...baseArgs,
699
- response_format: { type: "json_object" }
700
- },
701
- warnings
702
- };
703
- }
704
- case "object-tool": {
705
- return {
706
- args: {
707
- ...baseArgs,
708
- tool_choice: "any",
709
- tools: [{ type: "function", function: mode.tool }]
710
- },
711
- warnings
712
- };
713
- }
714
- case "object-grammar": {
715
- throw new UnsupportedFunctionalityError({
716
- functionality: "object-grammar mode"
717
- });
718
- }
719
- default: {
720
- const _exhaustiveCheck = type;
721
- throw new Error(`Unsupported type: ${_exhaustiveCheck}`);
722
- }
723
- }
724
- }
725
- async doGenerate(options) {
726
- var _a, _b;
727
- const { args, warnings } = this.getArgs(options);
728
- const response = await postJsonToApi({
729
- url: `${this.config.baseUrl}/chat/completions`,
730
- headers: this.config.headers(),
731
- body: args,
732
- failedResponseHandler: mistralFailedResponseHandler,
733
- successfulResponseHandler: createJsonResponseHandler(
734
- mistralChatResponseSchema
735
- ),
736
- abortSignal: options.abortSignal
737
- });
738
- const { messages: rawPrompt, ...rawSettings } = args;
739
- const choice = response.choices[0];
740
- return {
741
- text: (_a = choice.message.content) != null ? _a : void 0,
742
- toolCalls: (_b = choice.message.tool_calls) == null ? void 0 : _b.map((toolCall) => ({
743
- toolCallType: "function",
744
- toolCallId: this.config.generateId(),
745
- toolName: toolCall.function.name,
746
- args: toolCall.function.arguments
747
- })),
748
- finishReason: mapMistralFinishReason(choice.finish_reason),
749
- usage: {
750
- promptTokens: response.usage.prompt_tokens,
751
- completionTokens: response.usage.completion_tokens
752
- },
753
- rawCall: { rawPrompt, rawSettings },
754
- warnings
755
- };
756
- }
757
- async doStream(options) {
758
- const { args, warnings } = this.getArgs(options);
759
- const response = await postJsonToApi({
760
- url: `${this.config.baseUrl}/chat/completions`,
761
- headers: this.config.headers(),
762
- body: {
763
- ...args,
764
- stream: true
765
- },
766
- failedResponseHandler: mistralFailedResponseHandler,
767
- successfulResponseHandler: createEventSourceResponseHandler(
768
- mistralChatChunkSchema
769
- ),
770
- abortSignal: options.abortSignal
771
- });
772
- const { messages: rawPrompt, ...rawSettings } = args;
773
- let finishReason = "other";
774
- let usage = {
775
- promptTokens: Number.NaN,
776
- completionTokens: Number.NaN
777
- };
778
- const generateId2 = this.config.generateId;
779
- return {
780
- stream: response.pipeThrough(
781
- new TransformStream({
782
- transform(chunk, controller) {
783
- if (!chunk.success) {
784
- controller.enqueue({ type: "error", error: chunk.error });
785
- return;
786
- }
787
- const value = chunk.value;
788
- if (value.usage != null) {
789
- usage = {
790
- promptTokens: value.usage.prompt_tokens,
791
- completionTokens: value.usage.completion_tokens
792
- };
793
- }
794
- const choice = value.choices[0];
795
- if ((choice == null ? void 0 : choice.finish_reason) != null) {
796
- finishReason = mapMistralFinishReason(choice.finish_reason);
797
- }
798
- if ((choice == null ? void 0 : choice.delta) == null) {
799
- return;
800
- }
801
- const delta = choice.delta;
802
- if (delta.content != null) {
803
- controller.enqueue({
804
- type: "text-delta",
805
- textDelta: delta.content
806
- });
807
- }
808
- if (delta.tool_calls != null) {
809
- for (const toolCall of delta.tool_calls) {
810
- const toolCallId = generateId2();
811
- controller.enqueue({
812
- type: "tool-call-delta",
813
- toolCallType: "function",
814
- toolCallId,
815
- toolName: toolCall.function.name,
816
- argsTextDelta: toolCall.function.arguments
817
- });
818
- controller.enqueue({
819
- type: "tool-call",
820
- toolCallType: "function",
821
- toolCallId,
822
- toolName: toolCall.function.name,
823
- args: toolCall.function.arguments
824
- });
825
- }
826
- }
827
- },
828
- flush(controller) {
829
- controller.enqueue({ type: "finish", finishReason, usage });
830
- }
831
- })
832
- ),
833
- rawCall: { rawPrompt, rawSettings },
834
- warnings
835
- };
836
- }
837
- };
838
- var mistralChatResponseSchema = import_zod2.z.object({
839
- choices: import_zod2.z.array(
840
- import_zod2.z.object({
841
- message: import_zod2.z.object({
842
- role: import_zod2.z.literal("assistant"),
843
- content: import_zod2.z.string().nullable(),
844
- tool_calls: import_zod2.z.array(
845
- import_zod2.z.object({
846
- function: import_zod2.z.object({
847
- name: import_zod2.z.string(),
848
- arguments: import_zod2.z.string()
849
- })
850
- })
851
- ).optional().nullable()
852
- }),
853
- index: import_zod2.z.number(),
854
- finish_reason: import_zod2.z.string().optional().nullable()
855
- })
856
- ),
857
- object: import_zod2.z.literal("chat.completion"),
858
- usage: import_zod2.z.object({
859
- prompt_tokens: import_zod2.z.number(),
860
- completion_tokens: import_zod2.z.number()
861
- })
862
- });
863
- var mistralChatChunkSchema = import_zod2.z.object({
864
- object: import_zod2.z.literal("chat.completion.chunk"),
865
- choices: import_zod2.z.array(
866
- import_zod2.z.object({
867
- delta: import_zod2.z.object({
868
- role: import_zod2.z.enum(["assistant"]).optional(),
869
- content: import_zod2.z.string().nullable().optional(),
870
- tool_calls: import_zod2.z.array(
871
- import_zod2.z.object({
872
- function: import_zod2.z.object({ name: import_zod2.z.string(), arguments: import_zod2.z.string() })
873
- })
874
- ).optional().nullable()
875
- }),
876
- finish_reason: import_zod2.z.string().nullable().optional(),
877
- index: import_zod2.z.number()
878
- })
879
- ),
880
- usage: import_zod2.z.object({
881
- prompt_tokens: import_zod2.z.number(),
882
- completion_tokens: import_zod2.z.number()
883
- }).optional().nullable()
884
- });
885
-
886
- // mistral/mistral-facade.ts
887
- var Mistral = class {
888
- constructor(options = {}) {
889
- var _a;
890
- this.baseUrl = options.baseUrl;
891
- this.apiKey = options.apiKey;
892
- this.generateId = (_a = options.generateId) != null ? _a : generateId;
893
- }
894
- get baseConfig() {
895
- var _a;
896
- return {
897
- baseUrl: (_a = this.baseUrl) != null ? _a : "https://api.mistral.ai/v1",
898
- headers: () => ({
899
- Authorization: `Bearer ${loadApiKey({
900
- apiKey: this.apiKey,
901
- environmentVariableName: "MISTRAL_API_KEY",
902
- description: "Mistral"
903
- })}`
904
- })
905
- };
906
- }
907
- chat(modelId, settings = {}) {
908
- return new MistralChatLanguageModel(modelId, settings, {
909
- provider: "mistral.chat",
910
- ...this.baseConfig,
911
- generateId: this.generateId
912
- });
913
- }
914
- };
915
- var mistral = new Mistral();
916
- // Annotate the CommonJS export names for ESM import in node:
917
- 0 && (module.exports = {
918
- Mistral,
919
- mistral
920
- });
921
- //# sourceMappingURL=index.js.map