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