@ai-sdk/mistral 4.0.0-beta.21 → 4.0.0-beta.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.
package/dist/index.mjs DELETED
@@ -1,920 +0,0 @@
1
- // src/mistral-provider.ts
2
- import {
3
- NoSuchModelError
4
- } from "@ai-sdk/provider";
5
- import {
6
- loadApiKey,
7
- withoutTrailingSlash,
8
- withUserAgentSuffix
9
- } from "@ai-sdk/provider-utils";
10
-
11
- // src/mistral-chat-language-model.ts
12
- import {
13
- combineHeaders,
14
- createEventSourceResponseHandler,
15
- createJsonResponseHandler,
16
- generateId,
17
- injectJsonInstructionIntoMessages,
18
- isCustomReasoning,
19
- mapReasoningToProviderEffort,
20
- parseProviderOptions,
21
- postJsonToApi
22
- } from "@ai-sdk/provider-utils";
23
- import { z as z3 } from "zod/v4";
24
-
25
- // src/convert-mistral-usage.ts
26
- function convertMistralUsage(usage) {
27
- if (usage == null) {
28
- return {
29
- inputTokens: {
30
- total: void 0,
31
- noCache: void 0,
32
- cacheRead: void 0,
33
- cacheWrite: void 0
34
- },
35
- outputTokens: {
36
- total: void 0,
37
- text: void 0,
38
- reasoning: void 0
39
- },
40
- raw: void 0
41
- };
42
- }
43
- const promptTokens = usage.prompt_tokens;
44
- const completionTokens = usage.completion_tokens;
45
- return {
46
- inputTokens: {
47
- total: promptTokens,
48
- noCache: promptTokens,
49
- cacheRead: void 0,
50
- cacheWrite: void 0
51
- },
52
- outputTokens: {
53
- total: completionTokens,
54
- text: completionTokens,
55
- reasoning: void 0
56
- },
57
- raw: usage
58
- };
59
- }
60
-
61
- // src/convert-to-mistral-chat-messages.ts
62
- import {
63
- UnsupportedFunctionalityError
64
- } from "@ai-sdk/provider";
65
- import { convertToBase64, isProviderReference } from "@ai-sdk/provider-utils";
66
- function formatFileUrl({
67
- data,
68
- mediaType
69
- }) {
70
- return data instanceof URL ? data.toString() : `data:${mediaType};base64,${convertToBase64(data)}`;
71
- }
72
- function convertToMistralChatMessages(prompt) {
73
- var _a;
74
- const messages = [];
75
- for (let i = 0; i < prompt.length; i++) {
76
- const { role, content } = prompt[i];
77
- const isLastMessage = i === prompt.length - 1;
78
- switch (role) {
79
- case "system": {
80
- messages.push({ role: "system", content });
81
- break;
82
- }
83
- case "user": {
84
- messages.push({
85
- role: "user",
86
- content: content.map((part) => {
87
- switch (part.type) {
88
- case "text": {
89
- return { type: "text", text: part.text };
90
- }
91
- case "file": {
92
- if (isProviderReference(part.data)) {
93
- throw new UnsupportedFunctionalityError({
94
- functionality: "file parts with provider references"
95
- });
96
- }
97
- if (part.mediaType.startsWith("image/")) {
98
- const mediaType = part.mediaType === "image/*" ? "image/jpeg" : part.mediaType;
99
- return {
100
- type: "image_url",
101
- image_url: formatFileUrl({ data: part.data, mediaType })
102
- };
103
- } else if (part.mediaType === "application/pdf") {
104
- return {
105
- type: "document_url",
106
- document_url: formatFileUrl({
107
- data: part.data,
108
- mediaType: "application/pdf"
109
- })
110
- };
111
- } else {
112
- throw new UnsupportedFunctionalityError({
113
- functionality: "Only images and PDF file parts are supported"
114
- });
115
- }
116
- }
117
- }
118
- })
119
- });
120
- break;
121
- }
122
- case "assistant": {
123
- let text = "";
124
- const toolCalls = [];
125
- for (const part of content) {
126
- switch (part.type) {
127
- case "text": {
128
- text += part.text;
129
- break;
130
- }
131
- case "tool-call": {
132
- toolCalls.push({
133
- id: part.toolCallId,
134
- type: "function",
135
- function: {
136
- name: part.toolName,
137
- arguments: JSON.stringify(part.input)
138
- }
139
- });
140
- break;
141
- }
142
- case "reasoning": {
143
- text += part.text;
144
- break;
145
- }
146
- default: {
147
- throw new Error(
148
- `Unsupported content type in assistant message: ${part.type}`
149
- );
150
- }
151
- }
152
- }
153
- messages.push({
154
- role: "assistant",
155
- content: text,
156
- prefix: isLastMessage ? true : void 0,
157
- tool_calls: toolCalls.length > 0 ? toolCalls : void 0
158
- });
159
- break;
160
- }
161
- case "tool": {
162
- for (const toolResponse of content) {
163
- if (toolResponse.type === "tool-approval-response") {
164
- continue;
165
- }
166
- const output = toolResponse.output;
167
- let contentValue;
168
- switch (output.type) {
169
- case "text":
170
- case "error-text":
171
- contentValue = output.value;
172
- break;
173
- case "execution-denied":
174
- contentValue = (_a = output.reason) != null ? _a : "Tool execution denied.";
175
- break;
176
- case "content":
177
- case "json":
178
- case "error-json":
179
- contentValue = JSON.stringify(output.value);
180
- break;
181
- }
182
- messages.push({
183
- role: "tool",
184
- name: toolResponse.toolName,
185
- tool_call_id: toolResponse.toolCallId,
186
- content: contentValue
187
- });
188
- }
189
- break;
190
- }
191
- default: {
192
- const _exhaustiveCheck = role;
193
- throw new Error(`Unsupported role: ${_exhaustiveCheck}`);
194
- }
195
- }
196
- }
197
- return messages;
198
- }
199
-
200
- // src/get-response-metadata.ts
201
- function getResponseMetadata({
202
- id,
203
- model,
204
- created
205
- }) {
206
- return {
207
- id: id != null ? id : void 0,
208
- modelId: model != null ? model : void 0,
209
- timestamp: created != null ? new Date(created * 1e3) : void 0
210
- };
211
- }
212
-
213
- // src/map-mistral-finish-reason.ts
214
- function mapMistralFinishReason(finishReason) {
215
- switch (finishReason) {
216
- case "stop":
217
- return "stop";
218
- case "length":
219
- case "model_length":
220
- return "length";
221
- case "tool_calls":
222
- return "tool-calls";
223
- default:
224
- return "other";
225
- }
226
- }
227
-
228
- // src/mistral-chat-options.ts
229
- import { z } from "zod/v4";
230
- var mistralLanguageModelOptions = z.object({
231
- /**
232
- * Whether to inject a safety prompt before all conversations.
233
- *
234
- * Defaults to `false`.
235
- */
236
- safePrompt: z.boolean().optional(),
237
- documentImageLimit: z.number().optional(),
238
- documentPageLimit: z.number().optional(),
239
- /**
240
- * Whether to use structured outputs.
241
- *
242
- * @default true
243
- */
244
- structuredOutputs: z.boolean().optional(),
245
- /**
246
- * Whether to use strict JSON schema validation.
247
- *
248
- * @default false
249
- */
250
- strictJsonSchema: z.boolean().optional(),
251
- /**
252
- * Whether to enable parallel function calling during tool use.
253
- * When set to false, the model will use at most one tool per response.
254
- *
255
- * @default true
256
- */
257
- parallelToolCalls: z.boolean().optional(),
258
- /**
259
- * Controls the reasoning effort for models that support adjustable reasoning.
260
- *
261
- * - `'high'`: Enable reasoning
262
- * - `'none'`: Disable reasoning
263
- */
264
- reasoningEffort: z.enum(["high", "none"]).optional()
265
- });
266
-
267
- // src/mistral-error.ts
268
- import { createJsonErrorResponseHandler } from "@ai-sdk/provider-utils";
269
- import { z as z2 } from "zod/v4";
270
- var mistralErrorDataSchema = z2.object({
271
- object: z2.literal("error"),
272
- message: z2.string(),
273
- type: z2.string(),
274
- param: z2.string().nullable(),
275
- code: z2.string().nullable()
276
- });
277
- var mistralFailedResponseHandler = createJsonErrorResponseHandler({
278
- errorSchema: mistralErrorDataSchema,
279
- errorToMessage: (data) => data.message
280
- });
281
-
282
- // src/mistral-prepare-tools.ts
283
- import {
284
- UnsupportedFunctionalityError as UnsupportedFunctionalityError2
285
- } from "@ai-sdk/provider";
286
- function prepareTools({
287
- tools,
288
- toolChoice
289
- }) {
290
- tools = (tools == null ? void 0 : tools.length) ? tools : void 0;
291
- const toolWarnings = [];
292
- if (tools == null) {
293
- return { tools: void 0, toolChoice: void 0, toolWarnings };
294
- }
295
- const mistralTools = [];
296
- for (const tool of tools) {
297
- if (tool.type === "provider") {
298
- toolWarnings.push({
299
- type: "unsupported",
300
- feature: `provider-defined tool ${tool.id}`
301
- });
302
- } else {
303
- mistralTools.push({
304
- type: "function",
305
- function: {
306
- name: tool.name,
307
- description: tool.description,
308
- parameters: tool.inputSchema,
309
- ...tool.strict != null ? { strict: tool.strict } : {}
310
- }
311
- });
312
- }
313
- }
314
- if (toolChoice == null) {
315
- return { tools: mistralTools, toolChoice: void 0, toolWarnings };
316
- }
317
- const type = toolChoice.type;
318
- switch (type) {
319
- case "auto":
320
- case "none":
321
- return { tools: mistralTools, toolChoice: type, toolWarnings };
322
- case "required":
323
- return { tools: mistralTools, toolChoice: "any", toolWarnings };
324
- // mistral does not support tool mode directly,
325
- // so we filter the tools and force the tool choice through 'any'
326
- case "tool":
327
- return {
328
- tools: mistralTools.filter(
329
- (tool) => tool.function.name === toolChoice.toolName
330
- ),
331
- toolChoice: "any",
332
- toolWarnings
333
- };
334
- default: {
335
- const _exhaustiveCheck = type;
336
- throw new UnsupportedFunctionalityError2({
337
- functionality: `tool choice type: ${_exhaustiveCheck}`
338
- });
339
- }
340
- }
341
- }
342
-
343
- // src/mistral-chat-language-model.ts
344
- var MistralChatLanguageModel = class {
345
- constructor(modelId, config) {
346
- this.specificationVersion = "v4";
347
- this.supportedUrls = {
348
- "application/pdf": [/^https:\/\/.*$/]
349
- };
350
- var _a;
351
- this.modelId = modelId;
352
- this.config = config;
353
- this.generateId = (_a = config.generateId) != null ? _a : generateId;
354
- }
355
- get provider() {
356
- return this.config.provider;
357
- }
358
- async getArgs({
359
- prompt,
360
- maxOutputTokens,
361
- temperature,
362
- topP,
363
- topK,
364
- frequencyPenalty,
365
- presencePenalty,
366
- reasoning,
367
- stopSequences,
368
- responseFormat,
369
- seed,
370
- providerOptions,
371
- tools,
372
- toolChoice
373
- }) {
374
- var _a, _b, _c, _d, _e;
375
- const warnings = [];
376
- const options = (_a = await parseProviderOptions({
377
- provider: "mistral",
378
- providerOptions,
379
- schema: mistralLanguageModelOptions
380
- })) != null ? _a : {};
381
- if (topK != null) {
382
- warnings.push({ type: "unsupported", feature: "topK" });
383
- }
384
- if (frequencyPenalty != null) {
385
- warnings.push({ type: "unsupported", feature: "frequencyPenalty" });
386
- }
387
- if (presencePenalty != null) {
388
- warnings.push({ type: "unsupported", feature: "presencePenalty" });
389
- }
390
- if (stopSequences != null) {
391
- warnings.push({ type: "unsupported", feature: "stopSequences" });
392
- }
393
- const supportsReasoningEffort = this.modelId === "mistral-small-latest" || this.modelId === "mistral-small-2603";
394
- let resolvedReasoningEffort;
395
- if (supportsReasoningEffort) {
396
- resolvedReasoningEffort = (_b = options.reasoningEffort) != null ? _b : isCustomReasoning(reasoning) ? reasoning === "none" ? "none" : mapReasoningToProviderEffort({
397
- reasoning,
398
- effortMap: {
399
- minimal: "high",
400
- low: "high",
401
- medium: "high",
402
- high: "high",
403
- xhigh: "high"
404
- },
405
- warnings
406
- }) : void 0;
407
- } else if (isCustomReasoning(reasoning)) {
408
- warnings.push({
409
- type: "unsupported",
410
- feature: "reasoning",
411
- details: "This model does not support reasoning configuration."
412
- });
413
- }
414
- const structuredOutputs = (_c = options.structuredOutputs) != null ? _c : true;
415
- const strictJsonSchema = (_d = options.strictJsonSchema) != null ? _d : false;
416
- if ((responseFormat == null ? void 0 : responseFormat.type) === "json" && !(responseFormat == null ? void 0 : responseFormat.schema)) {
417
- prompt = injectJsonInstructionIntoMessages({
418
- messages: prompt,
419
- schema: responseFormat.schema
420
- });
421
- }
422
- const baseArgs = {
423
- // model id:
424
- model: this.modelId,
425
- // model specific settings:
426
- safe_prompt: options.safePrompt,
427
- // standardized settings:
428
- max_tokens: maxOutputTokens,
429
- temperature,
430
- top_p: topP,
431
- random_seed: seed,
432
- reasoning_effort: resolvedReasoningEffort,
433
- // response format:
434
- response_format: (responseFormat == null ? void 0 : responseFormat.type) === "json" ? structuredOutputs && (responseFormat == null ? void 0 : responseFormat.schema) != null ? {
435
- type: "json_schema",
436
- json_schema: {
437
- schema: responseFormat.schema,
438
- strict: strictJsonSchema,
439
- name: (_e = responseFormat.name) != null ? _e : "response",
440
- description: responseFormat.description
441
- }
442
- } : { type: "json_object" } : void 0,
443
- // mistral-specific provider options:
444
- document_image_limit: options.documentImageLimit,
445
- document_page_limit: options.documentPageLimit,
446
- // messages:
447
- messages: convertToMistralChatMessages(prompt)
448
- };
449
- const {
450
- tools: mistralTools,
451
- toolChoice: mistralToolChoice,
452
- toolWarnings
453
- } = prepareTools({
454
- tools,
455
- toolChoice
456
- });
457
- return {
458
- args: {
459
- ...baseArgs,
460
- tools: mistralTools,
461
- tool_choice: mistralToolChoice,
462
- ...mistralTools != null && options.parallelToolCalls !== void 0 ? { parallel_tool_calls: options.parallelToolCalls } : {}
463
- },
464
- warnings: [...warnings, ...toolWarnings]
465
- };
466
- }
467
- async doGenerate(options) {
468
- var _a;
469
- const { args: body, warnings } = await this.getArgs(options);
470
- const {
471
- responseHeaders,
472
- value: response,
473
- rawValue: rawResponse
474
- } = await postJsonToApi({
475
- url: `${this.config.baseURL}/chat/completions`,
476
- headers: combineHeaders(this.config.headers(), options.headers),
477
- body,
478
- failedResponseHandler: mistralFailedResponseHandler,
479
- successfulResponseHandler: createJsonResponseHandler(
480
- mistralChatResponseSchema
481
- ),
482
- abortSignal: options.abortSignal,
483
- fetch: this.config.fetch
484
- });
485
- const choice = response.choices[0];
486
- const content = [];
487
- if (choice.message.content != null && Array.isArray(choice.message.content)) {
488
- for (const part of choice.message.content) {
489
- if (part.type === "thinking") {
490
- const reasoningText = extractReasoningContent(part.thinking);
491
- if (reasoningText.length > 0) {
492
- content.push({ type: "reasoning", text: reasoningText });
493
- }
494
- } else if (part.type === "text") {
495
- if (part.text.length > 0) {
496
- content.push({ type: "text", text: part.text });
497
- }
498
- }
499
- }
500
- } else {
501
- const text = extractTextContent(choice.message.content);
502
- if (text != null && text.length > 0) {
503
- content.push({ type: "text", text });
504
- }
505
- }
506
- if (choice.message.tool_calls != null) {
507
- for (const toolCall of choice.message.tool_calls) {
508
- content.push({
509
- type: "tool-call",
510
- toolCallId: toolCall.id,
511
- toolName: toolCall.function.name,
512
- input: toolCall.function.arguments
513
- });
514
- }
515
- }
516
- return {
517
- content,
518
- finishReason: {
519
- unified: mapMistralFinishReason(choice.finish_reason),
520
- raw: (_a = choice.finish_reason) != null ? _a : void 0
521
- },
522
- usage: convertMistralUsage(response.usage),
523
- request: { body },
524
- response: {
525
- ...getResponseMetadata(response),
526
- headers: responseHeaders,
527
- body: rawResponse
528
- },
529
- warnings
530
- };
531
- }
532
- async doStream(options) {
533
- const { args, warnings } = await this.getArgs(options);
534
- const body = { ...args, stream: true };
535
- const { responseHeaders, value: response } = await postJsonToApi({
536
- url: `${this.config.baseURL}/chat/completions`,
537
- headers: combineHeaders(this.config.headers(), options.headers),
538
- body,
539
- failedResponseHandler: mistralFailedResponseHandler,
540
- successfulResponseHandler: createEventSourceResponseHandler(
541
- mistralChatChunkSchema
542
- ),
543
- abortSignal: options.abortSignal,
544
- fetch: this.config.fetch
545
- });
546
- let finishReason = {
547
- unified: "other",
548
- raw: void 0
549
- };
550
- let usage = void 0;
551
- let isFirstChunk = true;
552
- let activeText = false;
553
- let activeReasoningId = null;
554
- const generateId2 = this.generateId;
555
- return {
556
- stream: response.pipeThrough(
557
- new TransformStream({
558
- start(controller) {
559
- controller.enqueue({ type: "stream-start", warnings });
560
- },
561
- transform(chunk, controller) {
562
- if (options.includeRawChunks) {
563
- controller.enqueue({ type: "raw", rawValue: chunk.rawValue });
564
- }
565
- if (!chunk.success) {
566
- controller.enqueue({ type: "error", error: chunk.error });
567
- return;
568
- }
569
- const value = chunk.value;
570
- if (isFirstChunk) {
571
- isFirstChunk = false;
572
- controller.enqueue({
573
- type: "response-metadata",
574
- ...getResponseMetadata(value)
575
- });
576
- }
577
- if (value.usage != null) {
578
- usage = value.usage;
579
- }
580
- const choice = value.choices[0];
581
- const delta = choice.delta;
582
- const textContent = extractTextContent(delta.content);
583
- if (delta.content != null && Array.isArray(delta.content)) {
584
- for (const part of delta.content) {
585
- if (part.type === "thinking") {
586
- const reasoningDelta = extractReasoningContent(part.thinking);
587
- if (reasoningDelta.length > 0) {
588
- if (activeReasoningId == null) {
589
- if (activeText) {
590
- controller.enqueue({ type: "text-end", id: "0" });
591
- activeText = false;
592
- }
593
- activeReasoningId = generateId2();
594
- controller.enqueue({
595
- type: "reasoning-start",
596
- id: activeReasoningId
597
- });
598
- }
599
- controller.enqueue({
600
- type: "reasoning-delta",
601
- id: activeReasoningId,
602
- delta: reasoningDelta
603
- });
604
- }
605
- }
606
- }
607
- }
608
- if (textContent != null && textContent.length > 0) {
609
- if (!activeText) {
610
- if (activeReasoningId != null) {
611
- controller.enqueue({
612
- type: "reasoning-end",
613
- id: activeReasoningId
614
- });
615
- activeReasoningId = null;
616
- }
617
- controller.enqueue({ type: "text-start", id: "0" });
618
- activeText = true;
619
- }
620
- controller.enqueue({
621
- type: "text-delta",
622
- id: "0",
623
- delta: textContent
624
- });
625
- }
626
- if ((delta == null ? void 0 : delta.tool_calls) != null) {
627
- for (const toolCall of delta.tool_calls) {
628
- const toolCallId = toolCall.id;
629
- const toolName = toolCall.function.name;
630
- const input = toolCall.function.arguments;
631
- controller.enqueue({
632
- type: "tool-input-start",
633
- id: toolCallId,
634
- toolName
635
- });
636
- controller.enqueue({
637
- type: "tool-input-delta",
638
- id: toolCallId,
639
- delta: input
640
- });
641
- controller.enqueue({
642
- type: "tool-input-end",
643
- id: toolCallId
644
- });
645
- controller.enqueue({
646
- type: "tool-call",
647
- toolCallId,
648
- toolName,
649
- input
650
- });
651
- }
652
- }
653
- if (choice.finish_reason != null) {
654
- finishReason = {
655
- unified: mapMistralFinishReason(choice.finish_reason),
656
- raw: choice.finish_reason
657
- };
658
- }
659
- },
660
- flush(controller) {
661
- if (activeReasoningId != null) {
662
- controller.enqueue({
663
- type: "reasoning-end",
664
- id: activeReasoningId
665
- });
666
- }
667
- if (activeText) {
668
- controller.enqueue({ type: "text-end", id: "0" });
669
- }
670
- controller.enqueue({
671
- type: "finish",
672
- finishReason,
673
- usage: convertMistralUsage(usage)
674
- });
675
- }
676
- })
677
- ),
678
- request: { body },
679
- response: { headers: responseHeaders }
680
- };
681
- }
682
- };
683
- function extractReasoningContent(thinking) {
684
- return thinking.filter((chunk) => chunk.type === "text").map((chunk) => chunk.text).join("");
685
- }
686
- function extractTextContent(content) {
687
- if (typeof content === "string") {
688
- return content;
689
- }
690
- if (content == null) {
691
- return void 0;
692
- }
693
- const textContent = [];
694
- for (const chunk of content) {
695
- const { type } = chunk;
696
- switch (type) {
697
- case "text":
698
- textContent.push(chunk.text);
699
- break;
700
- case "thinking":
701
- case "image_url":
702
- case "reference":
703
- break;
704
- default: {
705
- const _exhaustiveCheck = type;
706
- throw new Error(`Unsupported type: ${_exhaustiveCheck}`);
707
- }
708
- }
709
- }
710
- return textContent.length ? textContent.join("") : void 0;
711
- }
712
- var mistralContentSchema = z3.union([
713
- z3.string(),
714
- z3.array(
715
- z3.discriminatedUnion("type", [
716
- z3.object({
717
- type: z3.literal("text"),
718
- text: z3.string()
719
- }),
720
- z3.object({
721
- type: z3.literal("image_url"),
722
- image_url: z3.union([
723
- z3.string(),
724
- z3.object({
725
- url: z3.string(),
726
- detail: z3.string().nullable()
727
- })
728
- ])
729
- }),
730
- z3.object({
731
- type: z3.literal("reference"),
732
- reference_ids: z3.array(z3.union([z3.string(), z3.number()]))
733
- }),
734
- z3.object({
735
- type: z3.literal("thinking"),
736
- thinking: z3.array(
737
- z3.object({
738
- type: z3.literal("text"),
739
- text: z3.string()
740
- })
741
- )
742
- })
743
- ])
744
- )
745
- ]).nullish();
746
- var mistralUsageSchema = z3.object({
747
- prompt_tokens: z3.number(),
748
- completion_tokens: z3.number(),
749
- total_tokens: z3.number()
750
- });
751
- var mistralChatResponseSchema = z3.object({
752
- id: z3.string().nullish(),
753
- created: z3.number().nullish(),
754
- model: z3.string().nullish(),
755
- choices: z3.array(
756
- z3.object({
757
- message: z3.object({
758
- role: z3.literal("assistant"),
759
- content: mistralContentSchema,
760
- tool_calls: z3.array(
761
- z3.object({
762
- id: z3.string(),
763
- function: z3.object({ name: z3.string(), arguments: z3.string() })
764
- })
765
- ).nullish()
766
- }),
767
- index: z3.number(),
768
- finish_reason: z3.string().nullish()
769
- })
770
- ),
771
- object: z3.literal("chat.completion"),
772
- usage: mistralUsageSchema
773
- });
774
- var mistralChatChunkSchema = z3.object({
775
- id: z3.string().nullish(),
776
- created: z3.number().nullish(),
777
- model: z3.string().nullish(),
778
- choices: z3.array(
779
- z3.object({
780
- delta: z3.object({
781
- role: z3.enum(["assistant"]).optional(),
782
- content: mistralContentSchema,
783
- tool_calls: z3.array(
784
- z3.object({
785
- id: z3.string(),
786
- function: z3.object({ name: z3.string(), arguments: z3.string() })
787
- })
788
- ).nullish()
789
- }),
790
- finish_reason: z3.string().nullish(),
791
- index: z3.number()
792
- })
793
- ),
794
- usage: mistralUsageSchema.nullish()
795
- });
796
-
797
- // src/mistral-embedding-model.ts
798
- import {
799
- TooManyEmbeddingValuesForCallError
800
- } from "@ai-sdk/provider";
801
- import {
802
- combineHeaders as combineHeaders2,
803
- createJsonResponseHandler as createJsonResponseHandler2,
804
- postJsonToApi as postJsonToApi2
805
- } from "@ai-sdk/provider-utils";
806
- import { z as z4 } from "zod/v4";
807
- var MistralEmbeddingModel = class {
808
- constructor(modelId, config) {
809
- this.specificationVersion = "v4";
810
- this.maxEmbeddingsPerCall = 32;
811
- this.supportsParallelCalls = false;
812
- this.modelId = modelId;
813
- this.config = config;
814
- }
815
- get provider() {
816
- return this.config.provider;
817
- }
818
- async doEmbed({
819
- values,
820
- abortSignal,
821
- headers
822
- }) {
823
- if (values.length > this.maxEmbeddingsPerCall) {
824
- throw new TooManyEmbeddingValuesForCallError({
825
- provider: this.provider,
826
- modelId: this.modelId,
827
- maxEmbeddingsPerCall: this.maxEmbeddingsPerCall,
828
- values
829
- });
830
- }
831
- const {
832
- responseHeaders,
833
- value: response,
834
- rawValue
835
- } = await postJsonToApi2({
836
- url: `${this.config.baseURL}/embeddings`,
837
- headers: combineHeaders2(this.config.headers(), headers),
838
- body: {
839
- model: this.modelId,
840
- input: values,
841
- encoding_format: "float"
842
- },
843
- failedResponseHandler: mistralFailedResponseHandler,
844
- successfulResponseHandler: createJsonResponseHandler2(
845
- MistralTextEmbeddingResponseSchema
846
- ),
847
- abortSignal,
848
- fetch: this.config.fetch
849
- });
850
- return {
851
- warnings: [],
852
- embeddings: response.data.map((item) => item.embedding),
853
- usage: response.usage ? { tokens: response.usage.prompt_tokens } : void 0,
854
- response: { headers: responseHeaders, body: rawValue }
855
- };
856
- }
857
- };
858
- var MistralTextEmbeddingResponseSchema = z4.object({
859
- data: z4.array(z4.object({ embedding: z4.array(z4.number()) })),
860
- usage: z4.object({ prompt_tokens: z4.number() }).nullish()
861
- });
862
-
863
- // src/version.ts
864
- var VERSION = true ? "4.0.0-beta.21" : "0.0.0-test";
865
-
866
- // src/mistral-provider.ts
867
- function createMistral(options = {}) {
868
- var _a;
869
- const baseURL = (_a = withoutTrailingSlash(options.baseURL)) != null ? _a : "https://api.mistral.ai/v1";
870
- const getHeaders = () => withUserAgentSuffix(
871
- {
872
- Authorization: `Bearer ${loadApiKey({
873
- apiKey: options.apiKey,
874
- environmentVariableName: "MISTRAL_API_KEY",
875
- description: "Mistral"
876
- })}`,
877
- ...options.headers
878
- },
879
- `ai-sdk/mistral/${VERSION}`
880
- );
881
- const createChatModel = (modelId) => new MistralChatLanguageModel(modelId, {
882
- provider: "mistral.chat",
883
- baseURL,
884
- headers: getHeaders,
885
- fetch: options.fetch,
886
- generateId: options.generateId
887
- });
888
- const createEmbeddingModel = (modelId) => new MistralEmbeddingModel(modelId, {
889
- provider: "mistral.embedding",
890
- baseURL,
891
- headers: getHeaders,
892
- fetch: options.fetch
893
- });
894
- const provider = function(modelId) {
895
- if (new.target) {
896
- throw new Error(
897
- "The Mistral model function cannot be called with the new keyword."
898
- );
899
- }
900
- return createChatModel(modelId);
901
- };
902
- provider.specificationVersion = "v4";
903
- provider.languageModel = createChatModel;
904
- provider.chat = createChatModel;
905
- provider.embedding = createEmbeddingModel;
906
- provider.embeddingModel = createEmbeddingModel;
907
- provider.textEmbedding = createEmbeddingModel;
908
- provider.textEmbeddingModel = createEmbeddingModel;
909
- provider.imageModel = (modelId) => {
910
- throw new NoSuchModelError({ modelId, modelType: "imageModel" });
911
- };
912
- return provider;
913
- }
914
- var mistral = createMistral();
915
- export {
916
- VERSION,
917
- createMistral,
918
- mistral
919
- };
920
- //# sourceMappingURL=index.mjs.map