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