Open History to see the last commit
1import { isFileSource, unsupportedFileSourceError } from '@tanstack/ai'
2import { BaseTextAdapter } from '@tanstack/ai/adapters'
3import { undoNullWidening } from '@tanstack/ai-utils'
4import { convertToolsToProviderFormat } from '../tools/tool-converter'
5import {
6 createMistralClient,
7 generateId,
8 getMistralApiKeyFromEnv,
9} from '../utils/client'
10import { makeMistralStructuredOutputCompatibleWithMap } from '../utils/schema-converter'
11import { createToolInputNormalizer } from '../utils/tool-input-normalizer'
12import type {
13 ContentPart,
14 Modality,
15 ModelMessage,
16 AdapterYieldChunk,
17 TextOptions,
18} from '@tanstack/ai'
19import type {
20 MISTRAL_CHAT_MODELS,
21 MistralChatModelProviderOptionsByName,
22 MistralModelInputModalitiesByName,
23 MistralTextAdapterModel,
24} from '../model-meta'
25import type {
26 StructuredOutputOptions,
27 StructuredOutputResult,
28} from '@tanstack/ai/adapters'
29import type { Mistral } from '@mistralai/mistralai'
30import type { ChatCompletionStreamRequest } from '@mistralai/mistralai/models/components'
31import type {
32 ExternalTextProviderOptions,
33 InternalTextProviderOptions,
34} from '../text/text-provider-options'
35import type {
36 ChatCompletionContentPart,
37 ChatCompletionMessageParam,
38 MistralImageMetadata,
39 MistralMessageMetadataByModality,
40} from '../message-types'
41import type { MistralClientConfig } from '../utils/client'
42import type { ToolInputNormalizer } from '../utils/tool-input-normalizer'
43
44/** Cast an event object to StreamChunk. Adapters construct events with string
45 * literal types which are structurally compatible with the EventType enum. */
46const asChunk = (chunk: Record<string, unknown>) =>
47 // oxlint-disable-next-line eslint-js/no-restricted-syntax -- Record<string, unknown> doesn't structurally overlap the StreamChunk discriminated union; events are built with literal `type` fields the union accepts at runtime
48 chunk as unknown as AdapterYieldChunk
49
50/**
51 * Parse the accumulated streaming arguments for a tool call. Throws a clear
52 * error if the JSON is malformed — silently substituting `{}` would let a
53 * tool fire with empty inputs, masking truncated streams or mis-shaped output.
54 */
55function parseToolCallInput(
56 toolCall: {
57 id: string
58 name: string
59 arguments: string
60 },
61 normalizeToolInput: ToolInputNormalizer,
62): unknown {
63 if (!toolCall.arguments) return {}
64 try {
65 return normalizeToolInput(toolCall.name, JSON.parse(toolCall.arguments))
66 } catch (cause) {
67 const preview = toolCall.arguments.slice(0, 200)
68 const ellipsis = toolCall.arguments.length > 200 ? '...' : ''
69 throw new Error(
70 `Failed to parse tool call arguments for tool '${toolCall.name}' (id: ${toolCall.id}). Arguments: ${preview}${ellipsis}`,
71 { cause },
72 )
73 }
74}
75
76/**
77 * Configuration for Mistral text adapter.
78 */
79export type MistralTextConfig = MistralClientConfig
80
81/**
82 * Alias for TextProviderOptions for external use.
83 */
84export type MistralTextProviderOptions = ExternalTextProviderOptions
85
86// ===========================
87// Type Resolution Helpers
88// ===========================
89
90type ResolveProviderOptions<TModel extends string> =
91 TModel extends keyof MistralChatModelProviderOptionsByName
92 ? MistralChatModelProviderOptionsByName[TModel]
93 : MistralTextProviderOptions
94
95type ResolveInputModalities<TModel extends string> =
96 TModel extends keyof MistralModelInputModalitiesByName
97 ? MistralModelInputModalitiesByName[TModel]
98 : readonly ['text']
99
100// ===========================
101// Wire-format chunk types
102// ===========================
103
104/**
105 * Snake-case shape of a Mistral chat completion stream chunk as returned on the
106 * wire. We bypass the SDK's `chat.stream` because its Zod validation rejects
107 * tool-call argument deltas that omit `function.name` (only the first chunk in
108 * a tool call carries the name).
109 */
110interface MistralRawToolCall {
111 id?: string
112 type?: string
113 index?: number
114 function?: {
115 name?: string
116 arguments?: string | Record<string, unknown>
117 }
118}
119
120interface MistralRawChoice {
121 index?: number
122 delta?: {
123 role?: string | null
124 content?:
125 | string
126 | Array<{
127 type: string
128 text?: string
129 // Mistral magistral models stream reasoning as content parts of
130 // type 'thinking' whose `thinking` field is itself an array of
131 // text/reference chunks. See Mistral SDK ThinkChunk type.
132 thinking?: Array<{ type: string; text?: string }>
133 }>
134 | null
135 // Some OpenAI-compatible deployments (DeepSeek, Groq for reasoning
136 // models, and aimock-based test environments) emit reasoning via a
137 // separate `reasoning_content` delta field rather than as a content
138 // part. Accept both shapes — they cannot collide because real Mistral
139 // never sets the OpenAI-compat field, and aimock never sets the
140 // thinking content part.
141 reasoning_content?: string | null
142 tool_calls?: Array<MistralRawToolCall>
143 }
144 finish_reason?: string | null
145}
146
147interface MistralRawChunk {
148 id?: string
149 model?: string
150 choices?: Array<MistralRawChoice>
151 usage?: {
152 prompt_tokens?: number
153 completion_tokens?: number
154 total_tokens?: number
155 }
156}
157
158// ===========================
159// Adapter Implementation
160// ===========================
161
162/**
163 * Mistral Text (Chat) Adapter.
164 *
165 * Tree-shakeable adapter for Mistral chat/text completion functionality.
166 */
167export class MistralTextAdapter<
168 TModel extends MistralTextAdapterModel,
169 TProviderOptions extends Record<string, any> = ResolveProviderOptions<TModel>,
170 TInputModalities extends ReadonlyArray<Modality> =
171 ResolveInputModalities<TModel>,
172> extends BaseTextAdapter<
173 TModel,
174 TProviderOptions,
175 TInputModalities,
176 MistralMessageMetadataByModality
177> {
178 readonly name = 'mistral' as const
179
180 private readonly client: Mistral
181 private readonly rawConfig: MistralClientConfig
182
183 constructor(config: MistralTextConfig, model: TModel) {
184 super(config, model)
185 // The SDK client is retained for `structuredOutput` (non-streaming). The
186 // streaming path bypasses the SDK and uses `fetchRawMistralStream` because
187 // the SDK's Zod schemas reject partial tool-call argument deltas.
188 this.client = createMistralClient(config)
189 this.rawConfig = config
190 }
191
192 async *chatStream(
193 options: TextOptions<TProviderOptions>,
194 ): AsyncIterable<AdapterYieldChunk> {
195 const requestParams = this.mapTextOptionsToMistral(options)
196 const timestamp = Date.now()
197
198 const aguiState = {
199 runId: options.runId ?? generateId(this.name),
200 threadId: options.threadId ?? generateId(this.name),
201 messageId: generateId(this.name),
202 timestamp,
203 hasEmittedRunStarted: false,
204 }
205
206 try {
207 const stream = this.fetchRawMistralStream(requestParams, this.rawConfig)
208 yield* this.processMistralStreamChunks(stream, options, aguiState)
209 } catch (error: unknown) {
210 const err = error as Error & { code?: string }
211
212 if (!aguiState.hasEmittedRunStarted) {
213 aguiState.hasEmittedRunStarted = true
214 yield asChunk({
215 type: 'RUN_STARTED',
216 runId: aguiState.runId,
217 threadId: aguiState.threadId,
218 model: options.model,
219 timestamp,
220 })
221 }
222
223 yield asChunk({
224 type: 'RUN_ERROR',
225 runId: aguiState.runId,
226 model: options.model,
227 timestamp,
228 message: err.message || 'Unknown error',
229 code: err.code,
230 error: {
231 message: err.message || 'Unknown error',
232 code: err.code,
233 },
234 })
235
236 throw err
237 }
238 }
239
240 /**
241 * Generate structured output using Mistral's JSON Schema response format.
242 */
243 async structuredOutput(
244 options: StructuredOutputOptions<TProviderOptions>,
245 ): Promise<StructuredOutputResult<unknown>> {
246 const { chatOptions, outputSchema } = options
247 const { stream: _stream, ...nonStreamParams } =
248 this.mapTextOptionsToMistral(chatOptions)
249
250 const {
251 schema: jsonSchema,
252 nullWideningMap,
253 strict,
254 } = makeMistralStructuredOutputCompatibleWithMap(
255 outputSchema,
256 outputSchema.required || [],
257 )
258
259 const response = await this.client.chat.complete({
260 ...nonStreamParams,
261 responseFormat: {
262 type: 'json_schema',
263 jsonSchema: {
264 name: 'structured_output',
265 schemaDefinition: jsonSchema,
266 strict,
267 },
268 },
269 })
270
271 const rawText = response.choices[0]?.message?.content
272 const textContent = typeof rawText === 'string' ? rawText : ''
273
274 let parsed: unknown
275 try {
276 parsed = JSON.parse(textContent)
277 } catch {
278 throw new Error(
279 `Failed to parse structured output as JSON. Content: ${textContent.slice(0, 200)}${textContent.length > 200 ? '...' : ''}`,
280 )
281 }
282
283 const usage = response.usage
284 return {
285 data: undoNullWidening(parsed, nullWideningMap),
286 rawText: textContent,
287 ...(usage && {
288 usage: {
289 promptTokens: usage.promptTokens ?? 0,
290 completionTokens: usage.completionTokens ?? 0,
291 totalTokens: usage.totalTokens ?? 0,
292 },
293 }),
294 }
295 }
296
297 /**
298 * Processes streaming chunks from the Mistral API and yields AG-UI stream events.
299 */
300 private async *processMistralStreamChunks(
301 stream: AsyncIterable<MistralRawChunk>,
302 options: TextOptions,
303 aguiState: {
304 runId: string
305 threadId: string
306 messageId: string
307 timestamp: number
308 hasEmittedRunStarted: boolean
309 },
310 ): AsyncIterable<AdapterYieldChunk> {
311 let accumulatedContent = ''
312 const timestamp = aguiState.timestamp
313 let hasEmittedTextMessageStart = false
314 let hasEmittedTextMessageEnd = false
315 let hasEmittedToolCall = false
316 let hasEmittedRunFinished = false
317 let lastChunkModel = options.model
318 const normalizeToolInput = createToolInputNormalizer(options.tools)
319
320 // Reasoning lifecycle (magistral-* models stream `thinking` content
321 // parts before any text). Mirrors the anthropic adapter's pattern:
322 // open REASONING_* events on the first thinking delta, close them when
323 // text/tool content begins or the run finishes.
324 let reasoningMessageId: string | null = null
325 let hasClosedReasoning = false
326
327 const toolCallsInProgress = new Map<
328 number,
329 {
330 id: string
331 name: string
332 arguments: string
333 started: boolean
334 ended: boolean
335 }
336 >()
337
338 try {
339 for await (const chunk of stream) {
340 lastChunkModel = chunk.model || options.model
341 const choice = chunk.choices?.[0]
342 if (!choice) continue
343
344 const chunkModel = chunk.model || options.model
345
346 if (!aguiState.hasEmittedRunStarted) {
347 aguiState.hasEmittedRunStarted = true
348 yield asChunk({
349 type: 'RUN_STARTED',
350 runId: aguiState.runId,
351 threadId: aguiState.threadId,
352 model: chunkModel,
353 timestamp,
354 })
355 }
356
357 const delta = choice.delta
358 const { text: deltaContent, thinking: deltaThinkingFromContent } =
359 this.extractDeltaParts(delta?.content)
360 // Reasoning may also arrive as a separate top-level field
361 // (`delta.reasoning_content`) on OpenAI-compatible deployments.
362 const deltaThinking =
363 deltaThinkingFromContent +
364 (typeof delta?.reasoning_content === 'string'
365 ? delta.reasoning_content
366 : '')
367 const deltaToolCalls = delta?.tool_calls
368
369 // Emit reasoning events FIRST so they always precede the matching
370 // text or tool deltas in the same chunk.
371 if (deltaThinking) {
372 if (reasoningMessageId === null) {
373 reasoningMessageId = generateId(this.name)
374 yield asChunk({
375 type: 'REASONING_START',
376 messageId: reasoningMessageId,
377 model: chunkModel,
378 timestamp,
379 })
380 yield asChunk({
381 type: 'REASONING_MESSAGE_START',
382 messageId: reasoningMessageId,
383 role: 'reasoning',
384 model: chunkModel,
385 timestamp,
386 })
387 }
388 yield asChunk({
389 type: 'REASONING_MESSAGE_CONTENT',
390 messageId: reasoningMessageId,
391 model: chunkModel,
392 timestamp,
393 delta: deltaThinking,
394 })
395 }
396
397 // Close reasoning before any text/tool output starts in this chunk.
398 const aboutToEmitOutput =
399 !!deltaContent || (!!deltaToolCalls && deltaToolCalls.length > 0)
400 if (
401 reasoningMessageId !== null &&
402 !hasClosedReasoning &&
403 aboutToEmitOutput
404 ) {
405 hasClosedReasoning = true
406 yield asChunk({
407 type: 'REASONING_MESSAGE_END',
408 messageId: reasoningMessageId,
409 model: chunkModel,
410 timestamp,
411 })
412 yield asChunk({
413 type: 'REASONING_END',
414 messageId: reasoningMessageId,
415 model: chunkModel,
416 timestamp,
417 })
418 }
419
420 if (deltaContent) {
421 if (!hasEmittedTextMessageStart) {
422 hasEmittedTextMessageStart = true
423 yield asChunk({
424 type: 'TEXT_MESSAGE_START',
425 messageId: aguiState.messageId,
426 model: chunkModel,
427 timestamp,
428 role: 'assistant',
429 })
430 }
431
432 accumulatedContent += deltaContent
433
434 yield asChunk({
435 type: 'TEXT_MESSAGE_CONTENT',
436 messageId: aguiState.messageId,
437 model: chunkModel,
438 timestamp,
439 delta: deltaContent,
440 content: accumulatedContent,
441 })
442 }
443
444 if (deltaToolCalls) {
445 for (const [i, toolCallDelta] of deltaToolCalls.entries()) {
446 const index = toolCallDelta.index ?? i
447
448 let toolCall = toolCallsInProgress.get(index)
449 if (!toolCall) {
450 toolCall = {
451 id: toolCallDelta.id || '',
452 name: toolCallDelta.function?.name || '',
453 arguments: '',
454 started: false,
455 ended: false,
456 }
457 toolCallsInProgress.set(index, toolCall)
458 }
459
460 if (toolCallDelta.id) toolCall.id = toolCallDelta.id
461 if (toolCallDelta.function?.name) {
462 toolCall.name = toolCallDelta.function.name
463 }
464
465 const rawArgs = toolCallDelta.function?.arguments
466 const argsDelta =
467 rawArgs === undefined
468 ? undefined
469 : typeof rawArgs === 'string'
470 ? rawArgs
471 : JSON.stringify(rawArgs)
472
473 if (argsDelta !== undefined) {
474 toolCall.arguments += argsDelta
475 }
476
477 const justStarted =
478 !!toolCall.id && !!toolCall.name && !toolCall.started
479 if (justStarted) {
480 toolCall.started = true
481 yield asChunk({
482 type: 'TOOL_CALL_START',
483 toolCallId: toolCall.id,
484 toolCallName: toolCall.name,
485 toolName: toolCall.name,
486 model: chunkModel,
487 timestamp,
488 index,
489 })
490 // Replay any args buffered before id+name arrived (including
491 // this chunk's argsDelta, if any).
492 if (toolCall.arguments.length > 0) {
493 yield asChunk({
494 type: 'TOOL_CALL_ARGS',
495 toolCallId: toolCall.id,
496 model: chunkModel,
497 timestamp,
498 delta: toolCall.arguments,
499 })
500 }
501 } else if (argsDelta !== undefined && toolCall.started) {
502 yield asChunk({
503 type: 'TOOL_CALL_ARGS',
504 toolCallId: toolCall.id,
505 model: chunkModel,
506 timestamp,
507 delta: argsDelta,
508 })
509 }
510 }
511 }
512
513 const finishReason = choice.finish_reason
514 if (finishReason) {
515 if (finishReason === 'tool_calls' || toolCallsInProgress.size > 0) {
516 for (const [, toolCall] of toolCallsInProgress) {
517 if (
518 !toolCall.started ||
519 !toolCall.id ||
520 !toolCall.name ||
521 toolCall.ended
522 ) {
523 continue
524 }
525
526 const parsedInput = parseToolCallInput(
527 toolCall,
528 normalizeToolInput,
529 )
530
531 toolCall.ended = true
532 hasEmittedToolCall = true
533 yield asChunk({
534 type: 'TOOL_CALL_END',
535 toolCallId: toolCall.id,
536 toolCallName: toolCall.name,
537 toolName: toolCall.name,
538 model: chunkModel,
539 timestamp,
540 input: parsedInput,
541 })
542 }
543 }
544
545 const computedFinishReason =
546 finishReason === 'tool_calls' || hasEmittedToolCall
547 ? 'tool_calls'
548 : finishReason === 'length'
549 ? 'length'
550 : 'stop'
551
552 // If the run finished while reasoning was still open (no text or
553 // tool output ever followed), close reasoning before TEXT/RUN
554 // finalization events.
555 if (reasoningMessageId !== null && !hasClosedReasoning) {
556 hasClosedReasoning = true
557 yield asChunk({
558 type: 'REASONING_MESSAGE_END',
559 messageId: reasoningMessageId,
560 model: chunkModel,
561 timestamp,
562 })
563 yield asChunk({
564 type: 'REASONING_END',
565 messageId: reasoningMessageId,
566 model: chunkModel,
567 timestamp,
568 })
569 }
570
571 if (hasEmittedTextMessageStart && !hasEmittedTextMessageEnd) {
572 hasEmittedTextMessageEnd = true
573 yield asChunk({
574 type: 'TEXT_MESSAGE_END',
575 messageId: aguiState.messageId,
576 model: chunkModel,
577 timestamp,
578 })
579 }
580
581 const usage = chunk.usage
582 hasEmittedRunFinished = true
583 yield asChunk({
584 type: 'RUN_FINISHED',
585 runId: aguiState.runId,
586 threadId: aguiState.threadId,
587 model: chunkModel,
588 timestamp,
589 usage: usage
590 ? {
591 promptTokens: usage.prompt_tokens || 0,
592 completionTokens: usage.completion_tokens || 0,
593 totalTokens: usage.total_tokens || 0,
594 }
595 : undefined,
596 finishReason: computedFinishReason,
597 })
598 }
599 }
600
601 // Stream ended cleanly without finish_reason — flush any open
602 // lifecycle events so consumers don't see orphaned starts. This
603 // happens for abrupt `[DONE]` or upstream cuts.
604 if (!hasEmittedRunFinished) {
605 if (reasoningMessageId !== null && !hasClosedReasoning) {
606 hasClosedReasoning = true
607 yield asChunk({
608 type: 'REASONING_MESSAGE_END',
609 messageId: reasoningMessageId,
610 model: lastChunkModel,
611 timestamp,
612 })
613 yield asChunk({
614 type: 'REASONING_END',
615 messageId: reasoningMessageId,
616 model: lastChunkModel,
617 timestamp,
618 })
619 }
620 for (const [, toolCall] of toolCallsInProgress) {
621 if (toolCall.started && !toolCall.ended) {
622 toolCall.ended = true
623 hasEmittedToolCall = true
624 yield asChunk({
625 type: 'TOOL_CALL_END',
626 toolCallId: toolCall.id,
627 toolCallName: toolCall.name,
628 toolName: toolCall.name,
629 model: lastChunkModel,
630 timestamp,
631 input: parseToolCallInput(toolCall, normalizeToolInput),
632 })
633 }
634 }
635 if (hasEmittedTextMessageStart && !hasEmittedTextMessageEnd) {
636 hasEmittedTextMessageEnd = true
637 yield asChunk({
638 type: 'TEXT_MESSAGE_END',
639 messageId: aguiState.messageId,
640 model: lastChunkModel,
641 timestamp,
642 })
643 }
644 hasEmittedRunFinished = true
645 yield asChunk({
646 type: 'RUN_FINISHED',
647 runId: aguiState.runId,
648 threadId: aguiState.threadId,
649 model: lastChunkModel,
650 timestamp,
651 usage: undefined,
652 finishReason: hasEmittedToolCall ? 'tool_calls' : 'stop',
653 })
654 }
655 } catch (error: unknown) {
656 // Lifecycle cleanup (TEXT_MESSAGE_END / TOOL_CALL_END / REASONING_END)
657 // on error path so consumers don't see orphaned starts. RUN_ERROR is
658 // emitted by the outer chatStream catch — emitting it here would
659 // duplicate the event.
660 if (reasoningMessageId !== null && !hasClosedReasoning) {
661 hasClosedReasoning = true
662 yield asChunk({
663 type: 'REASONING_MESSAGE_END',
664 messageId: reasoningMessageId,
665 model: lastChunkModel,
666 timestamp,
667 })
668 yield asChunk({
669 type: 'REASONING_END',
670 messageId: reasoningMessageId,
671 model: lastChunkModel,
672 timestamp,
673 })
674 }
675 if (hasEmittedTextMessageStart && !hasEmittedTextMessageEnd) {
676 hasEmittedTextMessageEnd = true
677 yield asChunk({
678 type: 'TEXT_MESSAGE_END',
679 messageId: aguiState.messageId,
680 model: lastChunkModel,
681 timestamp,
682 })
683 }
684 for (const [, toolCall] of toolCallsInProgress) {
685 if (toolCall.started && !toolCall.ended) {
686 toolCall.ended = true
687 // Best-effort parse for the partial args; if invalid, surface
688 // empty input rather than throwing inside the cleanup path.
689 let partialInput: unknown = {}
690 try {
691 partialInput = toolCall.arguments
692 ? normalizeToolInput(
693 toolCall.name,
694 JSON.parse(toolCall.arguments),
695 )
696 : {}
697 } catch {
698 partialInput = {}
699 }
700 yield asChunk({
701 type: 'TOOL_CALL_END',
702 toolCallId: toolCall.id,
703 toolCallName: toolCall.name,
704 toolName: toolCall.name,
705 model: lastChunkModel,
706 timestamp,
707 input: partialInput,
708 })
709 }
710 }
711 throw error
712 }
713 }
714
715 /**
716 * Makes a raw fetch request to the Mistral chat completions endpoint and
717 * parses the SSE stream manually, bypassing the SDK's Zod validation which
718 * rejects streaming tool call chunks that omit `name` in argument deltas.
719 */
720 private async *fetchRawMistralStream(
721 params: ChatCompletionStreamRequest,
722 config: MistralClientConfig,
723 ): AsyncGenerator<MistralRawChunk> {
724 const serverURL = (
725 config.baseURL ??
726 config.serverURL ??
727 'https://api.mistral.ai'
728 )
729 .replace(/\/+$/, '')
730 .replace(/\/v1$/, '')
731 const url =
732 config.resolveRequestUrl?.(true) ?? `${serverURL}/v1/chat/completions`
733
734 const body = this.toWireBody(params)
735 const accessToken =
736 config.getAccessToken === undefined
737 ? config.apiKey
738 : await config.getAccessToken()
739
740 const headers: Record<string, string> = {
741 'Content-Type': 'application/json',
742 Authorization: `Bearer ${accessToken}`,
743 ...config.defaultHeaders,
744 }
745
746 const response = await fetch(url, {
747 method: 'POST',
748 headers,
749 body: JSON.stringify(body),
750 })
751
752 if (!response.ok) {
753 const errorText = await response.text()
754 throw new Error(`Mistral API error ${response.status}: ${errorText}`)
755 }
756
757 if (!response.body) {
758 throw new Error(
759 'Mistral API returned a response with no body. This may indicate a proxy or runtime that does not support streaming.',
760 )
761 }
762
763 const reader = response.body.getReader()
764 const decoder = new TextDecoder()
765 let buffer = ''
766
767 try {
768 for (;;) {
769 const { done, value } = await reader.read()
770 if (done) break
771
772 buffer += decoder.decode(value, { stream: true })
773 const lines = buffer.split('\n')
774 // split('\n') always yields at least one element, so pop() is a
775 // string here; `?? ''` only satisfies the type narrowing.
776 buffer = lines.pop() ?? ''
777
778 for (const line of lines) {
779 const trimmed = line.trim()
780 if (!trimmed.startsWith('data:')) continue
781 const data = trimmed.slice(5).trimStart()
782 if (data === '[DONE]') return
783
784 let parsed: unknown
785 try {
786 parsed = JSON.parse(data)
787 } catch (e) {
788 if (e instanceof SyntaxError) {
789 console.warn(
790 `[mistral] skipped unparseable SSE chunk: ${data.slice(0, 200)}`,
791 )
792 continue
793 }
794 throw e
795 }
796
797 // Mistral signals mid-stream errors via an `error` field. Surface
798 // them as RUN_ERROR rather than swallowing them as empty chunks.
799 if (
800 parsed &&
801 typeof parsed === 'object' &&
802 'error' in parsed &&
803 !('choices' in parsed)
804 ) {
805 const errPayload = parsed.error
806 const message =
807 typeof errPayload === 'string'
808 ? errPayload
809 : errPayload &&
810 typeof errPayload === 'object' &&
811 'message' in errPayload
812 ? String(errPayload.message)
813 : JSON.stringify(errPayload)
814 throw new Error(`Mistral stream error: ${message}`)
815 }
816
817 yield parsed as MistralRawChunk
818 }
819 }
820 } finally {
821 await reader.cancel().catch(() => {})
822 reader.releaseLock()
823 }
824 }
825
826 /**
827 * Converts the SDK's camelCase `ChatCompletionStreamRequest` into the
828 * snake_case wire body, including converting messages.
829 */
830 private toWireBody(
831 params: ChatCompletionStreamRequest,
832 ): Record<string, unknown> {
833 const {
834 messages,
835 maxTokens,
836 topP,
837 randomSeed,
838 responseFormat,
839 toolChoice,
840 parallelToolCalls,
841 frequencyPenalty,
842 presencePenalty,
843 safePrompt,
844 stream: _stream,
845 ...rest
846 } = params
847
848 return {
849 ...rest,
850 messages: messages.map(messageToWire),
851 stream: true,
852 // Opt in to usage on the final streaming chunk.
853 stream_options: { include_usage: true },
854 ...(maxTokens != null && { max_tokens: maxTokens }),
855 ...(topP != null && { top_p: topP }),
856 ...(randomSeed != null && { random_seed: randomSeed }),
857 ...(responseFormat != null && { response_format: responseFormat }),
858 ...(toolChoice != null && { tool_choice: toolChoice }),
859 ...(parallelToolCalls != null && {
860 parallel_tool_calls: parallelToolCalls,
861 }),
862 ...(frequencyPenalty != null && { frequency_penalty: frequencyPenalty }),
863 ...(presencePenalty != null && { presence_penalty: presencePenalty }),
864 ...(safePrompt != null && { safe_prompt: safePrompt }),
865 }
866 }
867
868 /**
869 * Splits a Mistral delta content payload into text and reasoning deltas.
870 * Mistral reasoning models (magistral-*) stream reasoning content as
871 * `{ type: 'thinking', thinking: [{ type: 'text', text }, ...] }` content
872 * parts. A single delta may contain text only, thinking only, or — rarely —
873 * both (when a step transitions); both fields are returned so the caller
874 * can sequence REASONING and TEXT lifecycle events in order.
875 */
876 private extractDeltaParts(
877 content:
878 | string
879 | Array<{
880 type: string
881 text?: string
882 thinking?: Array<{ type: string; text?: string }>
883 }>
884 | null
885 | undefined,
886 ): { text: string; thinking: string } {
887 if (!content) return { text: '', thinking: '' }
888 if (typeof content === 'string') return { text: content, thinking: '' }
889
890 let text = ''
891 let thinking = ''
892 for (const part of content) {
893 if (part.type === 'text' && typeof part.text === 'string') {
894 text += part.text
895 } else if (part.type === 'thinking' && Array.isArray(part.thinking)) {
896 for (const inner of part.thinking) {
897 if (inner.type === 'text' && typeof inner.text === 'string') {
898 thinking += inner.text
899 }
900 }
901 }
902 }
903 return { text, thinking }
904 }
905
906 /**
907 * Maps common TextOptions to Mistral Chat Completions request parameters.
908 */
909 private mapTextOptionsToMistral(
910 options: TextOptions<TProviderOptions>,
911 ): ChatCompletionStreamRequest {
912 const modelOptions = options.modelOptions as
913 | Omit<InternalTextProviderOptions, 'tools'>
914 | undefined
915
916 const tools = options.tools
917 ? convertToolsToProviderFormat(options.tools)
918 : undefined
919
920 const messages: Array<ChatCompletionMessageParam> = []
921
922 if (options.systemPrompts && options.systemPrompts.length > 0) {
923 messages.push({
924 role: 'system',
925 content: options.systemPrompts.join('\n'),
926 })
927 }
928
929 for (const message of options.messages) {
930 messages.push(this.convertMessageToMistral(message))
931 }
932
933 return {
934 model: this.rawConfig.requestModel ?? options.model,
935 messages: messages,
936 temperature: modelOptions?.temperature ?? undefined,
937 maxTokens: modelOptions?.max_tokens ?? undefined,
938 topP: modelOptions?.top_p ?? undefined,
939 tools: tools as ChatCompletionStreamRequest['tools'],
940 stream: true,
941 ...(modelOptions && {
942 ...(modelOptions.stop != null && { stop: modelOptions.stop }),
943 ...(modelOptions.random_seed != null && {
944 randomSeed: modelOptions.random_seed,
945 }),
946 ...(modelOptions.response_format != null && {
947 responseFormat: modelOptions.response_format,
948 }),
949 ...(modelOptions.tool_choice != null && {
950 toolChoice: modelOptions.tool_choice,
951 }),
952 ...(modelOptions.parallel_tool_calls != null && {
953 parallelToolCalls: modelOptions.parallel_tool_calls,
954 }),
955 ...(modelOptions.frequency_penalty != null && {
956 frequencyPenalty: modelOptions.frequency_penalty,
957 }),
958 ...(modelOptions.presence_penalty != null && {
959 presencePenalty: modelOptions.presence_penalty,
960 }),
961 ...(modelOptions.n != null && { n: modelOptions.n }),
962 ...(modelOptions.prediction != null && {
963 prediction: modelOptions.prediction,
964 }),
965 ...(modelOptions.safe_prompt != null && {
966 safePrompt: modelOptions.safe_prompt,
967 }),
968 }),
969 }
970 }
971
972 /**
973 * Converts a TanStack AI ModelMessage to a Mistral ChatCompletionMessageParam.
974 */
975 private convertMessageToMistral(
976 message: ModelMessage,
977 ): ChatCompletionMessageParam {
978 if (message.role === 'tool') {
979 if (!message.toolCallId) {
980 throw new Error('Missing toolCallId for tool message')
981 }
982 return {
983 role: 'tool',
984 toolCallId: message.toolCallId,
985 content:
986 typeof message.content === 'string'
987 ? message.content
988 : JSON.stringify(message.content),
989 }
990 }
991
992 if (message.role === 'assistant') {
993 const toolCalls = message.toolCalls?.map((tc) => ({
994 id: tc.id,
995 type: 'function' as const,
996 function: {
997 name: tc.function.name,
998 arguments:
999 typeof tc.function.arguments === 'string'
1000 ? tc.function.arguments
1001 : JSON.stringify(tc.function.arguments),
1002 },
1003 }))
1004
1005 return {
1006 role: 'assistant',
1007 content: this.extractTextContent(message.content),
1008 ...(toolCalls && toolCalls.length > 0 ? { toolCalls } : {}),
1009 }
1010 }
1011
1012 const contentParts = this.normalizeContent(message.content)
1013
1014 if (contentParts.length === 1 && contentParts[0]?.type === 'text') {
1015 return {
1016 role: 'user',
1017 content: contentParts[0].content,
1018 }
1019 }
1020
1021 const parts = contentParts.map((part) =>
1022 this.convertContentPartToMistral(part),
1023 )
1024
1025 return {
1026 role: 'user',
1027 content: parts.length > 0 ? parts : '',
1028 }
1029 }
1030
1031 /**
1032 * Converts a ContentPart to a Mistral content part. Returns undefined for
1033 * unsupported part types.
1034 */
1035 private convertContentPartToMistral(
1036 part: ContentPart,
1037 ): ChatCompletionContentPart {
1038 if (part.type === 'text') {
1039 return { type: 'text', text: part.content }
1040 }
1041
1042 if (part.type === 'image') {
1043 if (isFileSource(part.source)) {
1044 throw unsupportedFileSourceError('mistral')
1045 }
1046 const imageMetadata = part.metadata as MistralImageMetadata | undefined
1047 const imageValue = part.source.value
1048 const imageUrl =
1049 part.source.type === 'data' && !imageValue.startsWith('data:')
1050 ? `data:${part.source.mimeType};base64,${imageValue}`
1051 : imageValue
1052 return {
1053 type: 'image_url',
1054 imageUrl: imageMetadata?.detail
1055 ? { url: imageUrl, detail: imageMetadata.detail }
1056 : imageUrl,
1057 }
1058 }
1059
1060 if (part.type === 'document') {
1061 if (isFileSource(part.source)) {
1062 throw unsupportedFileSourceError('mistral')
1063 }
1064 const documentValue = part.source.value
1065 const documentUrl =
1066 part.source.type === 'data' && !documentValue.startsWith('data:')
1067 ? `data:${part.source.mimeType};base64,${documentValue}`
1068 : documentValue
1069 return { type: 'document_url', documentUrl }
1070 }
1071
1072 throw new Error(
1073 `Mistral text adapter does not support content part of type '${(part as ContentPart).type}'. Supported types: text, image, document. Use a vision-capable model (mistral-medium-latest or mistral-small-latest) for images and documents.`,
1074 )
1075 }
1076
1077 /**
1078 * Normalizes message content to an array of ContentPart.
1079 */
1080 private normalizeContent(
1081 content: string | null | undefined | Array<ContentPart>,
1082 ): Array<ContentPart> {
1083 if (content === null || content === undefined) return []
1084 if (typeof content === 'string') return [{ type: 'text', content }]
1085 return content
1086 }
1087
1088 /**
1089 * Extracts text content from a content value that may be string, null, or ContentPart array.
1090 */
1091 private extractTextContent(
1092 content: string | null | undefined | Array<ContentPart>,
1093 ): string {
1094 if (content === null || content === undefined) return ''
1095 if (typeof content === 'string') return content
1096 return content
1097 .filter((p) => p.type === 'text')
1098 .map((p) => p.content)
1099 .join('')
1100 }
1101}
1102
1103/**
1104 * Snake-cases a Mistral SDK message into the wire format expected by the API.
1105 */
1106function messageToWire(msg: ChatCompletionStreamRequest['messages'][number]) {
1107 if (msg.role === 'tool') {
1108 return {
1109 role: 'tool',
1110 tool_call_id: msg.toolCallId,
1111 content: msg.content,
1112 ...(msg.name !== undefined ? { name: msg.name } : {}),
1113 }
1114 }
1115 if (msg.role === 'assistant') {
1116 const base: Record<string, unknown> = {
1117 role: 'assistant',
1118 content: msg.content ?? null,
1119 }
1120 if (msg.toolCalls && msg.toolCalls.length > 0) {
1121 base.tool_calls = msg.toolCalls.map((tc) => ({
1122 id: tc.id,
1123 type: tc.type ?? 'function',
1124 function: tc.function,
1125 }))
1126 }
1127 if (msg.prefix !== undefined) base.prefix = msg.prefix
1128 return base
1129 }
1130 if (msg.role === 'user' && Array.isArray(msg.content)) {
1131 return {
1132 role: 'user',
1133 content: msg.content.map((part) => {
1134 if (part.type === 'image_url') {
1135 return { type: 'image_url', image_url: part.imageUrl }
1136 }
1137 if (part.type === 'document_url') {
1138 return { type: 'document_url', document_url: part.documentUrl }
1139 }
1140 return part
1141 }),
1142 }
1143 }
1144 return msg
1145}
1146
1147/**
1148 * Creates a Mistral text adapter with explicit API key.
1149 *
1150 * @param model - The model name (e.g., 'mistral-large-latest')
1151 * @param apiKey - Your Mistral API key
1152 * @param config - Optional additional configuration
1153 * @returns Configured Mistral text adapter instance
1154 *
1155 * @example
1156 * ```typescript
1157 * const adapter = createMistralText('mistral-large-latest', 'api_key');
1158 * ```
1159 */
1160export function createMistralText<
1161 TModel extends (typeof MISTRAL_CHAT_MODELS)[number],
1162>(
1163 model: TModel,
1164 apiKey: string,
1165 config?: Omit<MistralTextConfig, 'apiKey'>,
1166): MistralTextAdapter<TModel> {
1167 return new MistralTextAdapter({ apiKey, ...config }, model)
1168}
1169
1170/**
1171 * Creates a Mistral text adapter using the `MISTRAL_API_KEY` environment variable.
1172 *
1173 * @param model - The model name (e.g., 'mistral-large-latest')
1174 * @param config - Optional configuration (excluding apiKey)
1175 * @returns Configured Mistral text adapter instance
1176 * @throws Error if MISTRAL_API_KEY is not found in environment
1177 *
1178 * @example
1179 * ```typescript
1180 * const adapter = mistralText('mistral-large-latest');
1181 * ```
1182 */
1183export function mistralText<
1184 TModel extends (typeof MISTRAL_CHAT_MODELS)[number],
1185>(
1186 model: TModel,
1187 config?: Omit<MistralTextConfig, 'apiKey'>,
1188): MistralTextAdapter<TModel> {
1189 const apiKey = getMistralApiKeyFromEnv()
1190 return createMistralText(model, apiKey, config)
1191}