Skip to content
Source
Sign inSign up
TanStack/ai
Open History to see the last commit

text.ts

1,485 lines46.7 KB

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 }
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 }
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 } }
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
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 }
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 }
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 : {}
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 }
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
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 }
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 ?? generateId(this.name),
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 toolName: toolCall.name,
699 model: chunkModel,
700 timestamp,
701 index,
702 })
703 // Replay any args buffered before id+name arrived (including
704 // this chunk's argsDelta, if any).
705 if (toolCall.arguments.length > 0) {
706 yield asChunk({
707 type: 'TOOL_CALL_ARGS',
708 toolCallId: toolCall.id,
709 model: chunkModel,
710 timestamp,
711 delta: toolCall.arguments,
712 })
713 }
714 } else if (argsDelta !== undefined && toolCall.started) {
715 yield asChunk({
716 type: 'TOOL_CALL_ARGS',
717 toolCallId: toolCall.id,
718 model: chunkModel,
719 timestamp,
720 delta: argsDelta,
721 })
722 }
723 }
724 }
725​
726 const finishReason = choice.finish_reason
727 if (finishReason) {
728 if (finishReason === 'tool_calls' || toolCallsInProgress.size > 0) {
729 for (const [, toolCall] of toolCallsInProgress) {
730 if (
731 !toolCall.started ||
732 !toolCall.id ||
733 !toolCall.name ||
734 toolCall.ended
735 ) {
736 continue
737 }
738​
739 const parsedInput = parseToolCallInput(
740 toolCall,
741 normalizeToolInput,
742 )
743​
744 toolCall.ended = true
745 hasEmittedToolCall = true
746 yield asChunk({
747 type: 'TOOL_CALL_END',
748 toolCallId: toolCall.id,
749 toolCallName: toolCall.name,
750 toolName: toolCall.name,
751 model: chunkModel,
752 timestamp,
753 args: toolCall.arguments,
754 input: parsedInput,
755 })
756 }
757 }
758​
759 const computedFinishReason =
760 finishReason === 'tool_calls' || hasEmittedToolCall
761 ? 'tool_calls'
762 : finishReason === 'length'
763 ? 'length'
764 : 'stop'
765​
766 // If the run finished while reasoning was still open (no text or
767 // tool output ever followed), close reasoning before TEXT/RUN
768 // finalization events.
769 if (reasoningMessageId !== null && !hasClosedReasoning) {
770 hasClosedReasoning = true
771 yield asChunk({
772 type: 'REASONING_MESSAGE_END',
773 messageId: reasoningMessageId,
774 model: chunkModel,
775 timestamp,
776 })
777 yield asChunk({
778 type: 'REASONING_END',
779 messageId: reasoningMessageId,
780 model: chunkModel,
781 timestamp,
782 })
783 }
784​
785 if (hasEmittedTextMessageStart && !hasEmittedTextMessageEnd) {
786 hasEmittedTextMessageEnd = true
787 yield asChunk({
788 type: 'TEXT_MESSAGE_END',
789 messageId: aguiState.messageId,
790 model: chunkModel,
791 timestamp,
792 })
793 }
794​
795 const usage = chunk.usage
796 hasEmittedRunFinished = true
797 yield asChunk({
798 type: 'RUN_FINISHED',
799 ...(responseId && { responseId }),
800 runId: aguiState.runId,
801 threadId: aguiState.threadId,
802 model: chunkModel,
803 timestamp,
804 usage: usage
805 ? {
806 promptTokens: usage.prompt_tokens || 0,
807 completionTokens: usage.completion_tokens || 0,
808 totalTokens: usage.total_tokens || 0,
809 ...mistralCachedTokens(usage),
810 }
811 : undefined,
812 finishReason: computedFinishReason,
813 })
814 }
815 }
816​
817 // Stream ended cleanly without finish_reason — flush any open
818 // lifecycle events so consumers don't see orphaned starts. This
819 // happens for abrupt `[DONE]` or upstream cuts.
820 if (!hasEmittedRunFinished) {
821 if (reasoningMessageId !== null && !hasClosedReasoning) {
822 hasClosedReasoning = true
823 yield asChunk({
824 type: 'REASONING_MESSAGE_END',
825 messageId: reasoningMessageId,
826 model: lastChunkModel,
827 timestamp,
828 })
829 yield asChunk({
830 type: 'REASONING_END',
831 messageId: reasoningMessageId,
832 model: lastChunkModel,
833 timestamp,
834 })
835 }
836 for (const [, toolCall] of toolCallsInProgress) {
837 if (toolCall.started && !toolCall.ended) {
838 // Parse before marking ended, so a parse error still lets the
839 // catch below send TOOL_CALL_END with the raw args.
840 const parsedInput = parseToolCallInput(toolCall, normalizeToolInput)
841 toolCall.ended = true
842 hasEmittedToolCall = true
843 yield asChunk({
844 type: 'TOOL_CALL_END',
845 toolCallId: toolCall.id,
846 toolCallName: toolCall.name,
847 toolName: toolCall.name,
848 model: lastChunkModel,
849 timestamp,
850 args: toolCall.arguments,
851 input: parsedInput,
852 })
853 }
854 }
855 if (hasEmittedTextMessageStart && !hasEmittedTextMessageEnd) {
856 hasEmittedTextMessageEnd = true
857 yield asChunk({
858 type: 'TEXT_MESSAGE_END',
859 messageId: aguiState.messageId,
860 model: lastChunkModel,
861 timestamp,
862 })
863 }
864 hasEmittedRunFinished = true
865 yield asChunk({
866 type: 'RUN_FINISHED',
867 ...(responseId && { responseId }),
868 runId: aguiState.runId,
869 threadId: aguiState.threadId,
870 model: lastChunkModel,
871 timestamp,
872 usage: undefined,
873 finishReason: hasEmittedToolCall ? 'tool_calls' : 'stop',
874 })
875 }
876 } catch (error: unknown) {
877 // Lifecycle cleanup (TEXT_MESSAGE_END / TOOL_CALL_END / REASONING_END)
878 // on error path so consumers don't see orphaned starts. RUN_ERROR is
879 // emitted by the outer chatStream catch — emitting it here would
880 // duplicate the event.
881 if (reasoningMessageId !== null && !hasClosedReasoning) {
882 hasClosedReasoning = true
883 yield asChunk({
884 type: 'REASONING_MESSAGE_END',
885 messageId: reasoningMessageId,
886 model: lastChunkModel,
887 timestamp,
888 })
889 yield asChunk({
890 type: 'REASONING_END',
891 messageId: reasoningMessageId,
892 model: lastChunkModel,
893 timestamp,
894 })
895 }
896 if (hasEmittedTextMessageStart && !hasEmittedTextMessageEnd) {
897 hasEmittedTextMessageEnd = true
898 yield asChunk({
899 type: 'TEXT_MESSAGE_END',
900 messageId: aguiState.messageId,
901 model: lastChunkModel,
902 timestamp,
903 })
904 }
905 for (const [, toolCall] of toolCallsInProgress) {
906 if (toolCall.started && !toolCall.ended) {
907 toolCall.ended = true
908 // Best-effort parse for the partial args. If invalid, leave input
909 // out and send the raw args, so core reports the parse error.
910 let partialInput: unknown
911 try {
912 partialInput = toolCall.arguments
913 ? normalizeToolInput(
914 toolCall.name,
915 JSON.parse(toolCall.arguments),
916 )
917 : {}
918 } catch {
919 partialInput = undefined
920 }
921 yield asChunk({
922 type: 'TOOL_CALL_END',
923 toolCallId: toolCall.id,
924 toolCallName: toolCall.name,
925 toolName: toolCall.name,
926 model: lastChunkModel,
927 timestamp,
928 args: toolCall.arguments,
929 ...(partialInput !== undefined && { input: partialInput }),
930 })
931 }
932 }
933 throw error
934 }
935 }
936​
937 /**
938 * Makes a raw fetch request to the Mistral chat completions endpoint and
939 * parses the SSE stream manually, bypassing the SDK's Zod validation which
940 * rejects streaming tool call chunks that omit `name` in argument deltas.
941 */
942 private async *fetchRawMistralStream(
943 body: Record<string, unknown>,
944 config: MistralClientConfig,
945 wrapFetch: FetchWrapper | undefined,
946 ): AsyncGenerator<MistralRawChunk> {
947 const serverURL = (
948 config.baseURL ??
949 config.serverURL ??
950 'https://api.mistral.ai'
951 )
952 .replace(/\/+$/, '')
953 .replace(/\/v1$/, '')
954 const url =
955 config.resolveRequestUrl?.(true) ?? `${serverURL}/v1/chat/completions`
956​
957 const accessToken =
958 config.getAccessToken === undefined
959 ? config.apiKey
960 : await config.getAccessToken()
961​
962 const headers: Record<string, string> = {
963 'Content-Type': 'application/json',
964 Authorization: `Bearer ${accessToken}`,
965 ...config.defaultHeaders,
966 }
967​
968 const send = wrapFetch ? wrapFetch(fetch) : fetch
969 const response = await send(url, {
970 method: 'POST',
971 headers,
972 body: JSON.stringify(body),
973 })
974​
975 if (!response.ok) {
976 const errorText = await response.text()
977 throw new Error(`Mistral API error ${response.status}: ${errorText}`)
978 }
979​
980 if (!response.body) {
981 throw new Error(
982 'Mistral API returned a response with no body. This may indicate a proxy or runtime that does not support streaming.',
983 )
984 }
985​
986 const reader = response.body.getReader()
987 const decoder = new TextDecoder()
988 let buffer = ''
989​
990 try {
991 for (;;) {
992 const { done, value } = await reader.read()
993 if (done) break
994​
995 buffer += decoder.decode(value, { stream: true })
996 const lines = buffer.split('\n')
997 // split('\n') always yields at least one element, so pop() is a
998 // string here; `?? ''` only satisfies the type narrowing.
999 buffer = lines.pop() ?? ''
1000​
1001 for (const line of lines) {
1002 const trimmed = line.trim()
1003 if (!trimmed.startsWith('data:')) continue
1004 const data = trimmed.slice(5).trimStart()
1005 if (data === '[DONE]') return
1006​
1007 let parsed: unknown
1008 try {
1009 parsed = JSON.parse(data)
1010 } catch (e) {
1011 if (e instanceof SyntaxError) {
1012 console.warn(
1013 `[mistral] skipped unparseable SSE chunk: ${data.slice(0, 200)}`,
1015 continue
1017 throw e
1019​
1020 // Mistral signals mid-stream errors via an `error` field. Surface
1021 // them as RUN_ERROR rather than swallowing them as empty chunks.
1022 if (
1023 parsed &&
1024 typeof parsed === 'object' &&
1025 'error' in parsed &&
1026 !('choices' in parsed)
1027 ) {
1028 const errPayload = parsed.error
1029 const message =
1030 typeof errPayload === 'string'
1031 ? errPayload
1032 : errPayload &&
1033 typeof errPayload === 'object' &&
1034 'message' in errPayload
1035 ? String(errPayload.message)
1036 : JSON.stringify(errPayload)
1037 throw new Error(`Mistral stream error: ${message}`)
1039​
1040 yield parsed as MistralRawChunk
1043 } finally {
1044 await reader.cancel().catch(() => {})
1045 reader.releaseLock()
1048​
1049 /**
1050 * Converts the SDK's camelCase `ChatCompletionStreamRequest` into the
1051 * snake_case wire body, including converting messages.
1052 */
1053 private toWireBody(
1054 params: ChatCompletionStreamRequest,
1055 ): Record<string, unknown> {
1056 const {
1057 messages,
1058 maxTokens,
1059 topP,
1060 randomSeed,
1061 responseFormat,
1062 toolChoice,
1063 parallelToolCalls,
1064 frequencyPenalty,
1065 presencePenalty,
1066 safePrompt,
1067 reasoningEffort,
1068 promptMode,
1069 stream: _stream,
1070 ...rest
1071 } = params
1072​
1073 return {
1074 ...rest,
1075 messages: messages.map(messageToWire),
1076 stream: true,
1077 // Opt in to usage on the final streaming chunk.
1078 stream_options: { include_usage: true },
1079 ...(maxTokens != null && { max_tokens: maxTokens }),
1080 ...(topP != null && { top_p: topP }),
1081 ...(randomSeed != null && { random_seed: randomSeed }),
1082 ...(responseFormat != null && { response_format: responseFormat }),
1083 ...(toolChoice != null && { tool_choice: toolChoice }),
1084 ...(parallelToolCalls != null && {
1085 parallel_tool_calls: parallelToolCalls,
1086 }),
1087 ...(frequencyPenalty != null && { frequency_penalty: frequencyPenalty }),
1088 ...(presencePenalty != null && { presence_penalty: presencePenalty }),
1089 ...(safePrompt != null && { safe_prompt: safePrompt }),
1090 ...(reasoningEffort != null && { reasoning_effort: reasoningEffort }),
1091 ...(promptMode != null && { prompt_mode: promptMode }),
1094​
1095 /**
1096 * Splits a Mistral delta content payload into text and reasoning deltas.
1097 * Mistral reasoning models (magistral-*) stream reasoning content as
1098 * `{ type: 'thinking', thinking: [{ type: 'text', text }, ...] }` content
1099 * parts. A single delta may contain text only, thinking only, or — rarely —
1100 * both (when a step transitions); both fields are returned so the caller
1101 * can sequence REASONING and TEXT lifecycle events in order.
1102 */
1103 private extractDeltaParts(
1104 content:
1105 | string
1106 | Array<{
1107 type: string
1108 text?: string
1109 thinking?: Array<{ type: string; text?: string }>
1110 }>
1111 | null
1112 | undefined,
1113 ): { text: string; thinking: string } {
1114 if (!content) return { text: '', thinking: '' }
1115 if (typeof content === 'string') return { text: content, thinking: '' }
1116​
1117 let text = ''
1118 let thinking = ''
1119 for (const part of content) {
1120 if (part.type === 'text' && typeof part.text === 'string') {
1121 text += part.text
1122 } else if (part.type === 'thinking' && Array.isArray(part.thinking)) {
1123 for (const inner of part.thinking) {
1124 if (inner.type === 'text' && typeof inner.text === 'string') {
1125 thinking += inner.text
1130 return { text, thinking }
1132​
1133 /**
1134 * Maps common TextOptions to Mistral Chat Completions request parameters.
1135 */
1136 private mapTextOptionsToMistral(
1137 options: TextOptions<TProviderOptions>,
1138 ): ChatCompletionStreamRequest {
1139 const modelOptions = options.modelOptions as
1140 | Omit<InternalTextProviderOptions, 'tools'>
1141 | undefined
1142​
1143 const tools = options.tools
1144 ? convertToolsToProviderFormat(options.tools)
1145 : undefined
1146​
1147 // History from another model loses its signatures, and its tool IDs are
1148 // rewritten to the 9-character IDs Mistral accepts.
1149 const replay = transformMessagesForReplay(
1150 options.messages,
1151 { provider: this.provider, api: this.api, model: options.model },
1152 (id, { attempt }) => {
1153 const normalized = id.replace(/[^a-zA-Z0-9]/g, '')
1154 if (attempt === 0 && normalized.length === 9) return normalized
1155 const seed = normalized || id
1156 return hashToolCallId(attempt === 0 ? seed : `${seed}:${attempt}`)
1157 .replace(/[^a-zA-Z0-9]/g, '')
1158 .slice(0, 9)
1159 },
1161 const messages: ChatCompletionStreamRequest['messages'] = []
1162​
1163 if (options.systemPrompts && options.systemPrompts.length > 0) {
1164 messages.push({
1165 role: 'system',
1166 content: options.systemPrompts.join('\n'),
1167 })
1169​
1170 for (const message of replay.messages) {
1171 messages.push(this.convertMessageToMistral(message))
1173​
1174 // `chat({ toolChoice })` is sent only when the request has tools. It goes
1175 // before the `modelOptions` spread, so a `tool_choice` there wins.
1176 const toolChoiceField =
1177 tools?.length && options.toolChoice !== undefined
1178 ? { toolChoice: toMistralToolChoice(options.toolChoice) }
1179 : undefined
1180​
1181 return {
1182 ...toolChoiceField,
1183 model: this.rawConfig.requestModel ?? options.model,
1184 messages: messages,
1185 temperature: modelOptions?.temperature ?? undefined,
1186 maxTokens: modelOptions?.max_tokens ?? undefined,
1187 topP: modelOptions?.top_p ?? undefined,
1188 tools: tools as ChatCompletionStreamRequest['tools'],
1189 stream: true,
1190 ...mistralReasoning(
1191 options.model,
1192 options.reasoning,
1193 MISTRAL_MODEL_REASONING[options.model],
1194 ),
1195 ...(modelOptions && {
1196 ...(modelOptions.stop != null && { stop: modelOptions.stop }),
1197 ...(modelOptions.random_seed != null && {
1198 randomSeed: modelOptions.random_seed,
1199 }),
1200 ...(modelOptions.response_format != null && {
1201 responseFormat: modelOptions.response_format,
1202 }),
1203 ...(modelOptions.tool_choice != null && {
1204 toolChoice: modelOptions.tool_choice,
1205 }),
1206 ...(modelOptions.parallel_tool_calls != null && {
1207 parallelToolCalls: modelOptions.parallel_tool_calls,
1208 }),
1209 ...(modelOptions.frequency_penalty != null && {
1210 frequencyPenalty: modelOptions.frequency_penalty,
1211 }),
1212 ...(modelOptions.presence_penalty != null && {
1213 presencePenalty: modelOptions.presence_penalty,
1214 }),
1215 ...(modelOptions.n != null && { n: modelOptions.n }),
1216 ...(modelOptions.prediction != null && {
1217 prediction: modelOptions.prediction,
1218 }),
1219 ...(modelOptions.safe_prompt != null && {
1220 safePrompt: modelOptions.safe_prompt,
1221 }),
1222 }),
1225​
1226 /**
1227 * Converts a TanStack AI ModelMessage to a Mistral ChatCompletionMessageParam.
1228 */
1229 private convertMessageToMistral(
1230 message: ModelMessage,
1231 ): ChatCompletionStreamRequest['messages'][number] {
1232 if (message.role === 'tool') {
1233 if (!message.toolCallId) {
1234 throw new Error('Missing toolCallId for tool message')
1236 return {
1237 role: 'tool',
1238 toolCallId: message.toolCallId,
1239 // Mistral accepts image chunks in a tool message, so send the parts.
1240 content: Array.isArray(message.content)
1241 ? message.content.map((part) =>
1242 this.convertContentPartToMistral(part),
1244 : typeof message.content === 'string'
1245 ? message.content
1246 : JSON.stringify(message.content),
1249​
1250 if (message.role === 'assistant') {
1251 const toolCalls = message.toolCalls?.map((tc) => ({
1252 id: tc.id,
1253 type: 'function' as const,
1254 function: {
1255 name: tc.function.name,
1256 arguments:
1257 typeof tc.function.arguments === 'string'
1258 ? tc.function.arguments
1259 : JSON.stringify(tc.function.arguments),
1260 },
1261 }))
1262​
1263 return {
1264 role: 'assistant',
1265 content: this.assistantContent(message),
1266 ...(toolCalls && toolCalls.length > 0 ? { toolCalls } : {}),
1269​
1270 const contentParts = this.normalizeContent(message.content)
1271​
1272 if (contentParts.length === 1 && contentParts[0]?.type === 'text') {
1273 return {
1274 role: 'user',
1275 content: contentParts[0].content,
1278​
1279 const parts = contentParts.map((part) =>
1280 this.convertContentPartToMistral(part),
1282​
1283 return {
1284 role: 'user',
1285 content: parts.length > 0 ? parts : '',
1288​
1289 /** Readable thinking and text, in the stored block order. */
1290 private assistantContent(message: ModelMessage): AssistantMessage['content'] {
1291 if (!message.thinking?.length)
1292 return this.extractTextContent(message.content)
1293 const blocks = orderedAssistantBlocks(message) ?? [
1294 ...message.thinking.map((thinking) => ({
1295 type: 'thinking' as const,
1296 thinking,
1297 })),
1298 { type: 'text' as const, text: this.extractTextContent(message.content) },
1300 const content: Array<ContentChunk> = []
1301 for (const block of blocks) {
1302 if (block.type === 'text')
1303 content.push({ type: 'text', text: block.text })
1304 else if (
1305 block.type === 'thinking' &&
1306 !block.thinking.redacted &&
1307 block.thinking.content.trim()
1308 ) {
1309 content.push({
1310 type: 'thinking',
1311 thinking: [{ type: 'text', text: block.thinking.content }],
1312 })
1315 return content
1317​
1318 /**
1319 * Converts a ContentPart to a Mistral content part. Returns undefined for
1320 * unsupported part types.
1321 */
1322 private convertContentPartToMistral(
1323 part: ContentPart,
1324 ): ChatCompletionContentPart {
1325 if (part.type === 'text') {
1326 return { type: 'text', text: part.content }
1328​
1329 if (part.type === 'image') {
1330 if (isFileSource(part.source)) {
1331 throw unsupportedFileSourceError('mistral')
1333 const imageMetadata = part.metadata as MistralImageMetadata | undefined
1334 const imageValue = part.source.value
1335 const imageUrl =
1336 part.source.type === 'data' && !imageValue.startsWith('data:')
1337 ? `data:${part.source.mimeType};base64,${imageValue}`
1338 : imageValue
1339 return {
1340 type: 'image_url',
1341 imageUrl: imageMetadata?.detail
1342 ? { url: imageUrl, detail: imageMetadata.detail }
1343 : imageUrl,
1346​
1347 if (part.type === 'document') {
1348 if (isFileSource(part.source)) {
1349 throw unsupportedFileSourceError('mistral')
1351 const documentValue = part.source.value
1352 const documentUrl =
1353 part.source.type === 'data' && !documentValue.startsWith('data:')
1354 ? `data:${part.source.mimeType};base64,${documentValue}`
1355 : documentValue
1356 return { type: 'document_url', documentUrl }
1358​
1359 throw new Error(
1360 `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.`,
1363​
1364 /**
1365 * Normalizes message content to an array of ContentPart.
1366 */
1367 private normalizeContent(
1368 content: string | null | undefined | Array<ContentPart>,
1369 ): Array<ContentPart> {
1370 if (content === null || content === undefined) return []
1371 if (typeof content === 'string') return [{ type: 'text', content }]
1372 return content
1374​
1375 /**
1376 * Extracts text content from a content value that may be string, null, or ContentPart array.
1377 */
1378 private extractTextContent(
1379 content: string | null | undefined | Array<ContentPart>,
1380 ): string {
1381 if (content === null || content === undefined) return ''
1382 if (typeof content === 'string') return content
1383 return content
1384 .filter((p) => p.type === 'text')
1385 .map((p) => p.content)
1386 .join('')
1389​
1390/**
1391 * Snake-cases a Mistral SDK message into the wire format expected by the API.
1392 */
1393function messageToWire(msg: ChatCompletionStreamRequest['messages'][number]) {
1394 if (msg.role === 'tool') {
1395 return {
1396 role: 'tool',
1397 tool_call_id: msg.toolCallId,
1398 content: Array.isArray(msg.content)
1399 ? msg.content.map(contentPartToWire)
1400 : msg.content,
1401 ...(msg.name !== undefined ? { name: msg.name } : {}),
1404 if (msg.role === 'assistant') {
1405 const base: Record<string, unknown> = {
1406 role: 'assistant',
1407 content: msg.content ?? null,
1409 if (msg.toolCalls && msg.toolCalls.length > 0) {
1410 base.tool_calls = msg.toolCalls.map((tc) => ({
1411 id: tc.id,
1412 type: tc.type ?? 'function',
1413 function: tc.function,
1414 }))
1416 if (msg.prefix !== undefined) base.prefix = msg.prefix
1417 return base
1419 if (msg.role === 'user' && Array.isArray(msg.content)) {
1420 return {
1421 role: 'user',
1422 content: msg.content.map(contentPartToWire),
1425 return msg
1427​
1428/**
1429 * Snake-cases one content chunk of a user or tool message.
1430 */
1431function contentPartToWire(part: ContentChunk) {
1432 if (part.type === 'image_url') {
1433 return { type: 'image_url', image_url: part.imageUrl }
1435 if (part.type === 'document_url') {
1436 return { type: 'document_url', document_url: part.documentUrl }
1438 return part
1440​
1441/**
1442 * Creates a Mistral text adapter with explicit API key.
1444 * @param model - The model name (e.g., 'mistral-large-latest')
1445 * @param apiKey - Your Mistral API key
1446 * @param config - Optional additional configuration
1447 * @returns Configured Mistral text adapter instance
1449 * @example
1450 * ```typescript
1451 * const adapter = createMistralText('mistral-large-latest', 'api_key');
1452 * ```
1453 */
1454export function createMistralText<
1455 TModel extends (typeof MISTRAL_CHAT_MODELS)[number],
1457 model: TModel,
1458 apiKey: string,
1459 config?: Omit<MistralTextConfig, 'apiKey'>,
1460): MistralTextAdapter<TModel> {
1461 return new MistralTextAdapter({ apiKey, ...config }, model)
1463​
1464/**
1465 * Creates a Mistral text adapter using the `MISTRAL_API_KEY` environment variable.
1467 * @param model - The model name (e.g., 'mistral-large-latest')
1468 * @param config - Optional configuration (excluding apiKey)
1469 * @returns Configured Mistral text adapter instance
1470 * @throws Error if MISTRAL_API_KEY is not found in environment
1472 * @example
1473 * ```typescript
1474 * const adapter = mistralText('mistral-large-latest');
1475 * ```
1476 */
1477export function mistralText<
1478 TModel extends (typeof MISTRAL_CHAT_MODELS)[number],
1480 model: TModel,
1481 config?: Omit<MistralTextConfig, 'apiKey'>,
1482): MistralTextAdapter<TModel> {
1483 const apiKey = getMistralApiKeyFromEnv()
1484 return createMistralText(model, apiKey, config)