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