@tanstack/ai-mistral 0.7.1 → 1.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -82,11 +82,8 @@ const adapter = createMistralText(
82
82
  - `ministral-8b-latest` - 8B edge model
83
83
  - `ministral-3b-latest` - 3B edge model
84
84
  - `codestral-latest` - Code-specialized model (256k context)
85
- - `pixtral-large-latest` - Large vision model
86
- - `pixtral-12b-2409` - 12B vision model
87
85
  - `magistral-medium-latest` - Reasoning model
88
86
  - `magistral-small-latest` - Small reasoning model
89
- - `open-mistral-nemo` - Open 12B model
90
87
 
91
88
  See [Mistral model comparison](https://docs.mistral.ai/getting-started/models/compare) for full details.
92
89
 
@@ -96,7 +93,7 @@ See [Mistral model comparison](https://docs.mistral.ai/getting-started/models/co
96
93
  - ✅ Structured output (JSON Schema)
97
94
  - ✅ Function/tool calling
98
95
  - ✅ Reasoning (magistral-\_ models — streamed as `REASONING\__` events)
99
- - ✅ Multimodal input (text + images) — requires a vision-capable model (`pixtral-large-latest`, `pixtral-12b-2409`, `mistral-medium-latest`, or `mistral-small-latest`)
96
+ - ✅ Multimodal input (text + images) — requires a vision-capable model (`mistral-medium-latest` or `mistral-small-latest`)
100
97
  - ❌ Embeddings (use [@mistralai/mistralai](https://github.com/mistralai/client-ts) directly)
101
98
  - ❌ Image generation
102
99
 
@@ -121,7 +121,7 @@ var MistralTextAdapter = class extends BaseTextAdapter {
121
121
  const timestamp = Date.now();
122
122
  const aguiState = {
123
123
  runId: options.runId ?? generateId(this.name),
124
- threadId: options.threadId ?? generateId(this.name),
124
+ threadId: options.threadId,
125
125
  messageId: generateId(this.name),
126
126
  timestamp,
127
127
  hasEmittedRunStarted: false
@@ -350,7 +350,6 @@ var MistralTextAdapter = class extends BaseTextAdapter {
350
350
  type: "TOOL_CALL_START",
351
351
  toolCallId: toolCall.id,
352
352
  toolCallName: toolCall.name,
353
- toolName: toolCall.name,
354
353
  model: chunkModel,
355
354
  timestamp,
356
355
  index
@@ -381,7 +380,6 @@ var MistralTextAdapter = class extends BaseTextAdapter {
381
380
  type: "TOOL_CALL_END",
382
381
  toolCallId: toolCall.id,
383
382
  toolCallName: toolCall.name,
384
- toolName: toolCall.name,
385
383
  model: chunkModel,
386
384
  timestamp,
387
385
  args: toolCall.arguments,
@@ -456,7 +454,6 @@ var MistralTextAdapter = class extends BaseTextAdapter {
456
454
  type: "TOOL_CALL_END",
457
455
  toolCallId: toolCall.id,
458
456
  toolCallName: toolCall.name,
459
- toolName: toolCall.name,
460
457
  model: lastChunkModel,
461
458
  timestamp,
462
459
  args: toolCall.arguments,
@@ -521,7 +518,6 @@ var MistralTextAdapter = class extends BaseTextAdapter {
521
518
  type: "TOOL_CALL_END",
522
519
  toolCallId: toolCall.id,
523
520
  toolCallName: toolCall.name,
524
- toolName: toolCall.name,
525
521
  model: lastChunkModel,
526
522
  timestamp,
527
523
  args: toolCall.arguments,
@@ -1 +1 @@
1
- {"version":3,"file":"text.js","names":[],"sources":["../../../src/adapters/text.ts"],"sourcesContent":["import { isFileSource, unsupportedFileSourceError } from '@tanstack/ai'\nimport { BaseTextAdapter } from '@tanstack/ai/adapters'\nimport { undoNullWidening } from '@tanstack/ai-utils'\nimport { convertToolsToProviderFormat } from '../tools/tool-converter'\nimport {\n createMistralClient,\n generateId,\n getMistralApiKeyFromEnv,\n} from '../utils/client'\nimport { makeMistralStructuredOutputCompatibleWithMap } from '../utils/schema-converter'\nimport { createToolInputNormalizer } from '../utils/tool-input-normalizer'\nimport {\n MISTRAL_MODEL_INPUT_MODALITIES,\n MISTRAL_MODEL_REASONING,\n} from '../model-meta'\nimport {\n hashToolCallId,\n orderedAssistantBlocks,\n resolveReasoning,\n transformMessagesForReplay,\n} from '@tanstack/ai/adapter-internals'\nimport type {\n ContentPart,\n FetchWrapper,\n Modality,\n ModelMessage,\n AdapterYieldChunk,\n ModelReasoning,\n ReasoningRequest,\n ResolvedPromptCache,\n TextOptions,\n ToolChoice,\n} from '@tanstack/ai'\nimport type {\n MISTRAL_CHAT_MODELS,\n MistralChatModelProviderOptionsByName,\n MistralModelInputModalitiesByName,\n MistralModelReasoningByName,\n MistralTextAdapterModel,\n} from '../model-meta'\nimport type {\n StructuredOutputOptions,\n StructuredOutputResult,\n} from '@tanstack/ai/adapters'\nimport type { Mistral } from '@mistralai/mistralai'\nimport type {\n AssistantMessage,\n ChatCompletionStreamRequest,\n ContentChunk,\n ReasoningEffort,\n} from '@mistralai/mistralai/models/components'\nimport type {\n ExternalTextProviderOptions,\n InternalTextProviderOptions,\n} from '../text/text-provider-options'\nimport type {\n ChatCompletionContentPart,\n MistralImageMetadata,\n MistralMessageMetadataByModality,\n} from '../message-types'\nimport type { MistralClientConfig } from '../utils/client'\nimport type { ToolInputNormalizer } from '../utils/tool-input-normalizer'\n\n/** Cast an event object to StreamChunk. Adapters construct events with string\n * literal types which are structurally compatible with the EventType enum. */\nconst asChunk = (chunk: Record<string, unknown>) =>\n // 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\n chunk as unknown as AdapterYieldChunk\n\n/**\n * Parse the accumulated streaming arguments for a tool call. Throws a clear\n * error if the JSON is malformed — silently substituting `{}` would let a\n * tool fire with empty inputs, masking truncated streams or mis-shaped output.\n */\nfunction parseToolCallInput(\n toolCall: {\n id: string\n name: string\n arguments: string\n },\n normalizeToolInput: ToolInputNormalizer,\n): unknown {\n if (!toolCall.arguments) return {}\n try {\n return normalizeToolInput(toolCall.name, JSON.parse(toolCall.arguments))\n } catch (cause) {\n const preview = toolCall.arguments.slice(0, 200)\n const ellipsis = toolCall.arguments.length > 200 ? '...' : ''\n throw new Error(\n `Failed to parse tool call arguments for tool '${toolCall.name}' (id: ${toolCall.id}). Arguments: ${preview}${ellipsis}`,\n { cause },\n )\n }\n}\n\n/**\n * Configuration for Mistral text adapter.\n */\nexport type MistralTextConfig = MistralClientConfig\n\n/**\n * Alias for TextProviderOptions for external use.\n */\nexport type MistralTextProviderOptions = ExternalTextProviderOptions\n\n// ===========================\n// Type Resolution Helpers\n// ===========================\n\ntype ResolveProviderOptions<TModel extends string> =\n TModel extends keyof MistralChatModelProviderOptionsByName\n ? MistralChatModelProviderOptionsByName[TModel]\n : MistralTextProviderOptions\n\n/** The reasoning levels of a model, for `chat({ reasoning })`. `never`: none. */\ntype ResolveReasoning<TModel extends string> =\n TModel extends keyof MistralModelReasoningByName\n ? MistralModelReasoningByName[TModel]\n : never\n\n/**\n * The Mistral reasoning fields for `chat({ reasoning })`, by pi's rule:\n * - a model with effort levels (Mistral Small, Mistral Medium):\n * `reasoningEffort` with the level's value, `none` for `off`.\n * - Magistral: `promptMode: 'reasoning'`, and nothing for `off`.\n */\nfunction mistralReasoning(\n model: string,\n request: ReasoningRequest | undefined,\n reasoning: ModelReasoning | undefined,\n): Pick<ChatCompletionStreamRequest, 'promptMode' | 'reasoningEffort'> {\n const resolved = resolveReasoning(request, reasoning)\n if (!resolved) return {}\n if (model.startsWith('magistral')) {\n return resolved.level === 'off' ? {} : { promptMode: 'reasoning' }\n }\n // `ReasoningEffort` is an open enum, so a newer value still goes out.\n return { reasoningEffort: resolved.value as ReasoningEffort }\n}\n\n/** Maps `chat({ toolChoice })` to the Mistral `toolChoice`. */\nfunction toMistralToolChoice(\n choice: ToolChoice,\n): NonNullable<ChatCompletionStreamRequest['toolChoice']> {\n if (typeof choice === 'string') return choice\n return { type: 'function', function: { name: choice.name } }\n}\n\n/**\n * The Mistral wire field for `chat({ promptCache })`. Mistral caches without\n * a flag, so only the key goes out. There is no key for `'none'`. Send the\n * key only to `api.mistral.ai`. The SDK request schema drops unknown fields,\n * so structured output adds the key after that schema runs.\n */\nfunction mistralPromptCacheKey(promptCache: ResolvedPromptCache | undefined) {\n if (!promptCache?.key || promptCache.retention === 'none') return undefined\n return promptCache.key\n}\n\nfunction mistralOwnApi(config: MistralClientConfig, provider: string) {\n if (provider === 'google-vertex') return false\n const serverURL =\n config.baseURL ?? config.serverURL ?? 'https://api.mistral.ai'\n try {\n return new URL(serverURL).hostname === 'api.mistral.ai'\n } catch {\n return false\n }\n}\n\n/** Add `prompt_cache_key` to a JSON body the SDK has already serialized. */\nfunction withPromptCacheKey(next: typeof fetch, key: string): typeof fetch {\n return async (input, init) => {\n const body = init?.body\n const text =\n typeof body === 'string'\n ? body\n : body instanceof ArrayBuffer\n ? new TextDecoder().decode(body)\n : undefined\n if (text === undefined) return next(input, init)\n let parsed: unknown\n try {\n parsed = JSON.parse(text)\n } catch {\n return next(input, init)\n }\n if (\n typeof parsed !== 'object' ||\n parsed === null ||\n Array.isArray(parsed)\n ) {\n return next(input, init)\n }\n return next(input, {\n ...init,\n body: JSON.stringify({ ...parsed, prompt_cache_key: key }),\n })\n }\n}\n\n/**\n * `promptTokensDetails.cachedTokens` when Mistral read prompt tokens from the\n * cache. Mistral sends the count in `prompt_tokens_details.cached_tokens` or\n * in `num_cached_tokens`. The SDK keeps these raw keys on `usage` with no\n * types, so the values are checked here.\n */\nfunction mistralCachedTokens(usage: Record<string, unknown>) {\n const details = usage.prompt_tokens_details\n const hasDetailsCount =\n typeof details === 'object' &&\n details !== null &&\n 'cached_tokens' in details\n const cachedTokens = hasDetailsCount\n ? details.cached_tokens\n : usage.num_cached_tokens\n return typeof cachedTokens === 'number' && cachedTokens > 0\n ? { promptTokensDetails: { cachedTokens } }\n : {}\n}\n\ntype ResolveInputModalities<TModel extends string> =\n TModel extends keyof MistralModelInputModalitiesByName\n ? MistralModelInputModalitiesByName[TModel]\n : readonly ['text']\n\n// ===========================\n// Wire-format chunk types\n// ===========================\n\n/**\n * Snake-case shape of a Mistral chat completion stream chunk as returned on the\n * wire. We bypass the SDK's `chat.stream` because its Zod validation rejects\n * tool-call argument deltas that omit `function.name` (only the first chunk in\n * a tool call carries the name).\n */\ninterface MistralRawToolCall {\n id?: string\n type?: string\n index?: number\n function?: {\n name?: string\n arguments?: string | Record<string, unknown>\n }\n}\n\ninterface MistralRawChoice {\n index?: number\n delta?: {\n role?: string | null\n content?:\n | string\n | Array<{\n type: string\n text?: string\n // Mistral magistral models stream reasoning as content parts of\n // type 'thinking' whose `thinking` field is itself an array of\n // text/reference chunks. See Mistral SDK ThinkChunk type.\n thinking?: Array<{ type: string; text?: string }>\n }>\n | null\n // Some OpenAI-compatible deployments (DeepSeek, Groq for reasoning\n // models, and aimock-based test environments) emit reasoning via a\n // separate `reasoning_content` delta field rather than as a content\n // part. Accept both shapes — they cannot collide because real Mistral\n // never sets the OpenAI-compat field, and aimock never sets the\n // thinking content part.\n reasoning_content?: string | null\n tool_calls?: Array<MistralRawToolCall>\n }\n finish_reason?: string | null\n}\n\ninterface MistralRawChunk {\n id?: string\n model?: string\n choices?: Array<MistralRawChoice>\n usage?: {\n prompt_tokens?: number\n completion_tokens?: number\n total_tokens?: number\n // Cache reads. Mistral sends one of these two.\n prompt_tokens_details?: { cached_tokens?: number } | null\n num_cached_tokens?: number | null\n }\n}\n\n// ===========================\n// Adapter Implementation\n// ===========================\n\n/**\n * Mistral Text (Chat) Adapter.\n *\n * Tree-shakeable adapter for Mistral chat/text completion functionality.\n */\nexport class MistralTextAdapter<\n TModel extends MistralTextAdapterModel,\n TProviderOptions extends Record<string, any> = ResolveProviderOptions<TModel>,\n TInputModalities extends ReadonlyArray<Modality> =\n ResolveInputModalities<TModel>,\n> extends BaseTextAdapter<\n TModel,\n TProviderOptions,\n TInputModalities,\n MistralMessageMetadataByModality,\n ReadonlyArray<string>,\n unknown,\n never,\n ResolveReasoning<TModel>\n> {\n readonly name = 'mistral' as const\n override readonly api = 'mistral-conversations' as const\n override readonly provider: string\n override readonly inputModalities = MISTRAL_MODEL_INPUT_MODALITIES[this.model]\n\n private readonly client: Mistral\n private readonly rawConfig: MistralClientConfig\n\n constructor(config: MistralTextConfig, model: TModel) {\n super(config, model)\n // The SDK client is retained for `structuredOutput` (non-streaming). The\n // streaming path bypasses the SDK and uses `fetchRawMistralStream` because\n // the SDK's Zod schemas reject partial tool-call argument deltas.\n this.client = createMistralClient(config)\n this.rawConfig = config\n this.provider =\n config.getAccessToken && config.resolveRequestUrl\n ? 'google-vertex'\n : this.name\n }\n\n async *chatStream(\n options: TextOptions<TProviderOptions>,\n ): AsyncIterable<AdapterYieldChunk> {\n const requestParams = this.mapTextOptionsToMistral(options)\n const timestamp = Date.now()\n\n const aguiState = {\n runId: options.runId ?? generateId(this.name),\n threadId: options.threadId ?? generateId(this.name),\n messageId: generateId(this.name),\n timestamp,\n hasEmittedRunStarted: false,\n }\n\n try {\n const cacheKey = mistralOwnApi(this.rawConfig, this.provider)\n ? mistralPromptCacheKey(options.promptCache)\n : undefined\n const body = {\n ...this.toWireBody(requestParams),\n ...(cacheKey !== undefined && { prompt_cache_key: cacheKey }),\n }\n const stream = this.fetchRawMistralStream(\n body,\n this.rawConfig,\n options.wrapFetch,\n )\n for await (const chunk of this.processMistralStreamChunks(\n stream,\n options,\n aguiState,\n )) {\n yield chunk.type === 'RUN_STARTED' || chunk.type === 'RUN_ERROR'\n ? {\n ...chunk,\n metadata: {\n ...chunk.metadata,\n tanstack: {\n ...chunk.metadata?.tanstack,\n source: {\n provider: this.provider,\n api: this.api,\n model: options.model,\n },\n },\n },\n }\n : chunk\n }\n } catch (error: unknown) {\n const err = error as Error & { code?: string }\n\n if (!aguiState.hasEmittedRunStarted) {\n aguiState.hasEmittedRunStarted = true\n yield asChunk({\n type: 'RUN_STARTED',\n runId: aguiState.runId,\n threadId: aguiState.threadId,\n metadata: {\n tanstack: {\n source: {\n provider: this.provider,\n api: this.api,\n model: options.model,\n },\n },\n },\n model: options.model,\n timestamp,\n })\n }\n\n yield asChunk({\n type: 'RUN_ERROR',\n metadata: {\n tanstack: {\n source: {\n provider: this.provider,\n api: this.api,\n model: options.model,\n },\n },\n },\n runId: aguiState.runId,\n model: options.model,\n timestamp,\n message: err.message || 'Unknown error',\n code: err.code,\n error: {\n message: err.message || 'Unknown error',\n code: err.code,\n },\n })\n\n throw err\n }\n }\n\n /**\n * Generate structured output using Mistral's JSON Schema response format.\n */\n async structuredOutput(\n options: StructuredOutputOptions<TProviderOptions>,\n ): Promise<StructuredOutputResult<unknown>> {\n const { chatOptions, outputSchema } = options\n const { stream: _stream, ...nonStreamParams } =\n this.mapTextOptionsToMistral(chatOptions)\n\n const {\n schema: jsonSchema,\n nullWideningMap,\n strict,\n } = makeMistralStructuredOutputCompatibleWithMap(\n outputSchema,\n outputSchema.required || [],\n )\n\n const cacheKey = mistralOwnApi(this.rawConfig, this.provider)\n ? mistralPromptCacheKey(chatOptions.promptCache)\n : undefined\n const next = chatOptions.wrapFetch ? chatOptions.wrapFetch(fetch) : fetch\n const client = cacheKey\n ? createMistralClient(this.rawConfig, withPromptCacheKey(next, cacheKey))\n : chatOptions.wrapFetch\n ? createMistralClient(this.rawConfig, next)\n : this.client\n const response = await client.chat.complete({\n ...nonStreamParams,\n responseFormat: {\n type: 'json_schema',\n jsonSchema: {\n name: 'structured_output',\n schemaDefinition: jsonSchema,\n strict,\n },\n },\n })\n\n // A response cut off at the output cap is a truncated JSON document;\n // report it before the parse error (issue #1426).\n if (response.choices[0]?.finishReason === 'length') {\n throw new Error(\n 'mistral.structuredOutput: the response was cut off because the maximum token limit was reached (finish_reason=length); raise modelOptions.max_tokens',\n )\n }\n\n const rawText = response.choices[0]?.message?.content\n const textContent = typeof rawText === 'string' ? rawText : ''\n\n let parsed: unknown\n try {\n parsed = JSON.parse(textContent)\n } catch {\n throw new Error(\n `Failed to parse structured output as JSON. Content: ${textContent.slice(0, 200)}${textContent.length > 200 ? '...' : ''}`,\n )\n }\n\n const usage = response.usage\n return {\n data: undoNullWidening(parsed, nullWideningMap),\n ...(response.id && { responseId: response.id }),\n ...(response.model && { model: response.model }),\n rawText: textContent,\n ...(usage && {\n usage: {\n promptTokens: usage.promptTokens ?? 0,\n completionTokens: usage.completionTokens ?? 0,\n totalTokens: usage.totalTokens ?? 0,\n ...mistralCachedTokens(usage),\n },\n }),\n }\n }\n\n /**\n * Processes streaming chunks from the Mistral API and yields AG-UI stream events.\n */\n private async *processMistralStreamChunks(\n stream: AsyncIterable<MistralRawChunk>,\n options: TextOptions,\n aguiState: {\n runId: string\n threadId: string\n messageId: string\n timestamp: number\n hasEmittedRunStarted: boolean\n },\n ): AsyncIterable<AdapterYieldChunk> {\n let accumulatedContent = ''\n const timestamp = aguiState.timestamp\n let hasEmittedTextMessageStart = false\n let hasEmittedTextMessageEnd = false\n let hasEmittedToolCall = false\n let hasEmittedRunFinished = false\n let lastChunkModel = options.model\n let responseId: string | undefined\n const normalizeToolInput = createToolInputNormalizer(options.tools)\n\n // Reasoning lifecycle (magistral-* models stream `thinking` content\n // parts before any text). Mirrors the anthropic adapter's pattern:\n // open REASONING_* events on the first thinking delta, close them when\n // text/tool content begins or the run finishes.\n let reasoningMessageId: string | null = null\n let hasClosedReasoning = false\n\n const toolCallsInProgress = new Map<\n number,\n {\n id: string\n name: string\n arguments: string\n started: boolean\n ended: boolean\n }\n >()\n\n try {\n for await (const chunk of stream) {\n lastChunkModel = chunk.model || lastChunkModel\n if (chunk.id) responseId = chunk.id\n const choice = chunk.choices?.[0]\n if (!choice) continue\n\n const chunkModel = chunk.model || options.model\n\n if (!aguiState.hasEmittedRunStarted) {\n aguiState.hasEmittedRunStarted = true\n yield asChunk({\n type: 'RUN_STARTED',\n runId: aguiState.runId,\n threadId: aguiState.threadId,\n model: chunkModel,\n timestamp,\n })\n }\n\n const delta = choice.delta\n const { text: deltaContent, thinking: deltaThinkingFromContent } =\n this.extractDeltaParts(delta?.content)\n // Reasoning may also arrive as a separate top-level field\n // (`delta.reasoning_content`) on OpenAI-compatible deployments.\n const deltaThinking =\n deltaThinkingFromContent +\n (typeof delta?.reasoning_content === 'string'\n ? delta.reasoning_content\n : '')\n const deltaToolCalls = delta?.tool_calls\n\n // Emit reasoning events FIRST so they always precede the matching\n // text or tool deltas in the same chunk.\n if (deltaThinking) {\n if (reasoningMessageId === null) {\n reasoningMessageId = generateId(this.name)\n yield asChunk({\n type: 'REASONING_START',\n messageId: reasoningMessageId,\n model: chunkModel,\n timestamp,\n })\n yield asChunk({\n type: 'REASONING_MESSAGE_START',\n messageId: reasoningMessageId,\n role: 'reasoning',\n model: chunkModel,\n timestamp,\n })\n }\n yield asChunk({\n type: 'REASONING_MESSAGE_CONTENT',\n messageId: reasoningMessageId,\n model: chunkModel,\n timestamp,\n delta: deltaThinking,\n })\n }\n\n // Close reasoning before any text/tool output starts in this chunk.\n const aboutToEmitOutput =\n !!deltaContent || (!!deltaToolCalls && deltaToolCalls.length > 0)\n if (\n reasoningMessageId !== null &&\n !hasClosedReasoning &&\n aboutToEmitOutput\n ) {\n hasClosedReasoning = true\n yield asChunk({\n type: 'REASONING_MESSAGE_END',\n messageId: reasoningMessageId,\n model: chunkModel,\n timestamp,\n })\n yield asChunk({\n type: 'REASONING_END',\n messageId: reasoningMessageId,\n model: chunkModel,\n timestamp,\n })\n }\n\n if (deltaContent) {\n if (!hasEmittedTextMessageStart) {\n hasEmittedTextMessageStart = true\n yield asChunk({\n type: 'TEXT_MESSAGE_START',\n messageId: aguiState.messageId,\n model: chunkModel,\n timestamp,\n role: 'assistant',\n })\n }\n\n accumulatedContent += deltaContent\n\n yield asChunk({\n type: 'TEXT_MESSAGE_CONTENT',\n messageId: aguiState.messageId,\n model: chunkModel,\n timestamp,\n delta: deltaContent,\n content: accumulatedContent,\n })\n }\n\n if (deltaToolCalls) {\n for (const [i, toolCallDelta] of deltaToolCalls.entries()) {\n const index = toolCallDelta.index ?? i\n\n let toolCall = toolCallsInProgress.get(index)\n if (!toolCall) {\n toolCall = {\n id: toolCallDelta.id || '',\n name: toolCallDelta.function?.name || '',\n arguments: '',\n started: false,\n ended: false,\n }\n toolCallsInProgress.set(index, toolCall)\n }\n\n if (toolCallDelta.id) toolCall.id = toolCallDelta.id\n if (toolCallDelta.function?.name) {\n toolCall.name = toolCallDelta.function.name\n }\n\n const rawArgs = toolCallDelta.function?.arguments\n const argsDelta =\n rawArgs === undefined\n ? undefined\n : typeof rawArgs === 'string'\n ? rawArgs\n : JSON.stringify(rawArgs)\n\n if (argsDelta !== undefined) {\n toolCall.arguments += argsDelta\n }\n\n const justStarted =\n !!toolCall.id && !!toolCall.name && !toolCall.started\n if (justStarted) {\n toolCall.started = true\n yield asChunk({\n type: 'TOOL_CALL_START',\n toolCallId: toolCall.id,\n toolCallName: toolCall.name,\n toolName: toolCall.name,\n model: chunkModel,\n timestamp,\n index,\n })\n // Replay any args buffered before id+name arrived (including\n // this chunk's argsDelta, if any).\n if (toolCall.arguments.length > 0) {\n yield asChunk({\n type: 'TOOL_CALL_ARGS',\n toolCallId: toolCall.id,\n model: chunkModel,\n timestamp,\n delta: toolCall.arguments,\n })\n }\n } else if (argsDelta !== undefined && toolCall.started) {\n yield asChunk({\n type: 'TOOL_CALL_ARGS',\n toolCallId: toolCall.id,\n model: chunkModel,\n timestamp,\n delta: argsDelta,\n })\n }\n }\n }\n\n const finishReason = choice.finish_reason\n if (finishReason) {\n if (finishReason === 'tool_calls' || toolCallsInProgress.size > 0) {\n for (const [, toolCall] of toolCallsInProgress) {\n if (\n !toolCall.started ||\n !toolCall.id ||\n !toolCall.name ||\n toolCall.ended\n ) {\n continue\n }\n\n const parsedInput = parseToolCallInput(\n toolCall,\n normalizeToolInput,\n )\n\n toolCall.ended = true\n hasEmittedToolCall = true\n yield asChunk({\n type: 'TOOL_CALL_END',\n toolCallId: toolCall.id,\n toolCallName: toolCall.name,\n toolName: toolCall.name,\n model: chunkModel,\n timestamp,\n args: toolCall.arguments,\n input: parsedInput,\n })\n }\n }\n\n const computedFinishReason =\n finishReason === 'tool_calls' || hasEmittedToolCall\n ? 'tool_calls'\n : finishReason === 'length'\n ? 'length'\n : 'stop'\n\n // If the run finished while reasoning was still open (no text or\n // tool output ever followed), close reasoning before TEXT/RUN\n // finalization events.\n if (reasoningMessageId !== null && !hasClosedReasoning) {\n hasClosedReasoning = true\n yield asChunk({\n type: 'REASONING_MESSAGE_END',\n messageId: reasoningMessageId,\n model: chunkModel,\n timestamp,\n })\n yield asChunk({\n type: 'REASONING_END',\n messageId: reasoningMessageId,\n model: chunkModel,\n timestamp,\n })\n }\n\n if (hasEmittedTextMessageStart && !hasEmittedTextMessageEnd) {\n hasEmittedTextMessageEnd = true\n yield asChunk({\n type: 'TEXT_MESSAGE_END',\n messageId: aguiState.messageId,\n model: chunkModel,\n timestamp,\n })\n }\n\n const usage = chunk.usage\n hasEmittedRunFinished = true\n yield asChunk({\n type: 'RUN_FINISHED',\n ...(responseId && { responseId }),\n runId: aguiState.runId,\n threadId: aguiState.threadId,\n model: chunkModel,\n timestamp,\n usage: usage\n ? {\n promptTokens: usage.prompt_tokens || 0,\n completionTokens: usage.completion_tokens || 0,\n totalTokens: usage.total_tokens || 0,\n ...mistralCachedTokens(usage),\n }\n : undefined,\n finishReason: computedFinishReason,\n })\n }\n }\n\n // Stream ended cleanly without finish_reason — flush any open\n // lifecycle events so consumers don't see orphaned starts. This\n // happens for abrupt `[DONE]` or upstream cuts.\n if (!hasEmittedRunFinished) {\n if (reasoningMessageId !== null && !hasClosedReasoning) {\n hasClosedReasoning = true\n yield asChunk({\n type: 'REASONING_MESSAGE_END',\n messageId: reasoningMessageId,\n model: lastChunkModel,\n timestamp,\n })\n yield asChunk({\n type: 'REASONING_END',\n messageId: reasoningMessageId,\n model: lastChunkModel,\n timestamp,\n })\n }\n for (const [, toolCall] of toolCallsInProgress) {\n if (toolCall.started && !toolCall.ended) {\n // Parse before marking ended, so a parse error still lets the\n // catch below send TOOL_CALL_END with the raw args.\n const parsedInput = parseToolCallInput(toolCall, normalizeToolInput)\n toolCall.ended = true\n hasEmittedToolCall = true\n yield asChunk({\n type: 'TOOL_CALL_END',\n toolCallId: toolCall.id,\n toolCallName: toolCall.name,\n toolName: toolCall.name,\n model: lastChunkModel,\n timestamp,\n args: toolCall.arguments,\n input: parsedInput,\n })\n }\n }\n if (hasEmittedTextMessageStart && !hasEmittedTextMessageEnd) {\n hasEmittedTextMessageEnd = true\n yield asChunk({\n type: 'TEXT_MESSAGE_END',\n messageId: aguiState.messageId,\n model: lastChunkModel,\n timestamp,\n })\n }\n hasEmittedRunFinished = true\n yield asChunk({\n type: 'RUN_FINISHED',\n ...(responseId && { responseId }),\n runId: aguiState.runId,\n threadId: aguiState.threadId,\n model: lastChunkModel,\n timestamp,\n usage: undefined,\n finishReason: hasEmittedToolCall ? 'tool_calls' : 'stop',\n })\n }\n } catch (error: unknown) {\n // Lifecycle cleanup (TEXT_MESSAGE_END / TOOL_CALL_END / REASONING_END)\n // on error path so consumers don't see orphaned starts. RUN_ERROR is\n // emitted by the outer chatStream catch — emitting it here would\n // duplicate the event.\n if (reasoningMessageId !== null && !hasClosedReasoning) {\n hasClosedReasoning = true\n yield asChunk({\n type: 'REASONING_MESSAGE_END',\n messageId: reasoningMessageId,\n model: lastChunkModel,\n timestamp,\n })\n yield asChunk({\n type: 'REASONING_END',\n messageId: reasoningMessageId,\n model: lastChunkModel,\n timestamp,\n })\n }\n if (hasEmittedTextMessageStart && !hasEmittedTextMessageEnd) {\n hasEmittedTextMessageEnd = true\n yield asChunk({\n type: 'TEXT_MESSAGE_END',\n messageId: aguiState.messageId,\n model: lastChunkModel,\n timestamp,\n })\n }\n for (const [, toolCall] of toolCallsInProgress) {\n if (toolCall.started && !toolCall.ended) {\n toolCall.ended = true\n // Best-effort parse for the partial args. If invalid, leave input\n // out and send the raw args, so core reports the parse error.\n let partialInput: unknown\n try {\n partialInput = toolCall.arguments\n ? normalizeToolInput(\n toolCall.name,\n JSON.parse(toolCall.arguments),\n )\n : {}\n } catch {\n partialInput = undefined\n }\n yield asChunk({\n type: 'TOOL_CALL_END',\n toolCallId: toolCall.id,\n toolCallName: toolCall.name,\n toolName: toolCall.name,\n model: lastChunkModel,\n timestamp,\n args: toolCall.arguments,\n ...(partialInput !== undefined && { input: partialInput }),\n })\n }\n }\n throw error\n }\n }\n\n /**\n * Makes a raw fetch request to the Mistral chat completions endpoint and\n * parses the SSE stream manually, bypassing the SDK's Zod validation which\n * rejects streaming tool call chunks that omit `name` in argument deltas.\n */\n private async *fetchRawMistralStream(\n body: Record<string, unknown>,\n config: MistralClientConfig,\n wrapFetch: FetchWrapper | undefined,\n ): AsyncGenerator<MistralRawChunk> {\n const serverURL = (\n config.baseURL ??\n config.serverURL ??\n 'https://api.mistral.ai'\n )\n .replace(/\\/+$/, '')\n .replace(/\\/v1$/, '')\n const url =\n config.resolveRequestUrl?.(true) ?? `${serverURL}/v1/chat/completions`\n\n const accessToken =\n config.getAccessToken === undefined\n ? config.apiKey\n : await config.getAccessToken()\n\n const headers: Record<string, string> = {\n 'Content-Type': 'application/json',\n Authorization: `Bearer ${accessToken}`,\n ...config.defaultHeaders,\n }\n\n const send = wrapFetch ? wrapFetch(fetch) : fetch\n const response = await send(url, {\n method: 'POST',\n headers,\n body: JSON.stringify(body),\n })\n\n if (!response.ok) {\n const errorText = await response.text()\n throw new Error(`Mistral API error ${response.status}: ${errorText}`)\n }\n\n if (!response.body) {\n throw new Error(\n 'Mistral API returned a response with no body. This may indicate a proxy or runtime that does not support streaming.',\n )\n }\n\n const reader = response.body.getReader()\n const decoder = new TextDecoder()\n let buffer = ''\n\n try {\n for (;;) {\n const { done, value } = await reader.read()\n if (done) break\n\n buffer += decoder.decode(value, { stream: true })\n const lines = buffer.split('\\n')\n // split('\\n') always yields at least one element, so pop() is a\n // string here; `?? ''` only satisfies the type narrowing.\n buffer = lines.pop() ?? ''\n\n for (const line of lines) {\n const trimmed = line.trim()\n if (!trimmed.startsWith('data:')) continue\n const data = trimmed.slice(5).trimStart()\n if (data === '[DONE]') return\n\n let parsed: unknown\n try {\n parsed = JSON.parse(data)\n } catch (e) {\n if (e instanceof SyntaxError) {\n console.warn(\n `[mistral] skipped unparseable SSE chunk: ${data.slice(0, 200)}`,\n )\n continue\n }\n throw e\n }\n\n // Mistral signals mid-stream errors via an `error` field. Surface\n // them as RUN_ERROR rather than swallowing them as empty chunks.\n if (\n parsed &&\n typeof parsed === 'object' &&\n 'error' in parsed &&\n !('choices' in parsed)\n ) {\n const errPayload = parsed.error\n const message =\n typeof errPayload === 'string'\n ? errPayload\n : errPayload &&\n typeof errPayload === 'object' &&\n 'message' in errPayload\n ? String(errPayload.message)\n : JSON.stringify(errPayload)\n throw new Error(`Mistral stream error: ${message}`)\n }\n\n yield parsed as MistralRawChunk\n }\n }\n } finally {\n await reader.cancel().catch(() => {})\n reader.releaseLock()\n }\n }\n\n /**\n * Converts the SDK's camelCase `ChatCompletionStreamRequest` into the\n * snake_case wire body, including converting messages.\n */\n private toWireBody(\n params: ChatCompletionStreamRequest,\n ): Record<string, unknown> {\n const {\n messages,\n maxTokens,\n topP,\n randomSeed,\n responseFormat,\n toolChoice,\n parallelToolCalls,\n frequencyPenalty,\n presencePenalty,\n safePrompt,\n reasoningEffort,\n promptMode,\n stream: _stream,\n ...rest\n } = params\n\n return {\n ...rest,\n messages: messages.map(messageToWire),\n stream: true,\n // Opt in to usage on the final streaming chunk.\n stream_options: { include_usage: true },\n ...(maxTokens != null && { max_tokens: maxTokens }),\n ...(topP != null && { top_p: topP }),\n ...(randomSeed != null && { random_seed: randomSeed }),\n ...(responseFormat != null && { response_format: responseFormat }),\n ...(toolChoice != null && { tool_choice: toolChoice }),\n ...(parallelToolCalls != null && {\n parallel_tool_calls: parallelToolCalls,\n }),\n ...(frequencyPenalty != null && { frequency_penalty: frequencyPenalty }),\n ...(presencePenalty != null && { presence_penalty: presencePenalty }),\n ...(safePrompt != null && { safe_prompt: safePrompt }),\n ...(reasoningEffort != null && { reasoning_effort: reasoningEffort }),\n ...(promptMode != null && { prompt_mode: promptMode }),\n }\n }\n\n /**\n * Splits a Mistral delta content payload into text and reasoning deltas.\n * Mistral reasoning models (magistral-*) stream reasoning content as\n * `{ type: 'thinking', thinking: [{ type: 'text', text }, ...] }` content\n * parts. A single delta may contain text only, thinking only, or — rarely —\n * both (when a step transitions); both fields are returned so the caller\n * can sequence REASONING and TEXT lifecycle events in order.\n */\n private extractDeltaParts(\n content:\n | string\n | Array<{\n type: string\n text?: string\n thinking?: Array<{ type: string; text?: string }>\n }>\n | null\n | undefined,\n ): { text: string; thinking: string } {\n if (!content) return { text: '', thinking: '' }\n if (typeof content === 'string') return { text: content, thinking: '' }\n\n let text = ''\n let thinking = ''\n for (const part of content) {\n if (part.type === 'text' && typeof part.text === 'string') {\n text += part.text\n } else if (part.type === 'thinking' && Array.isArray(part.thinking)) {\n for (const inner of part.thinking) {\n if (inner.type === 'text' && typeof inner.text === 'string') {\n thinking += inner.text\n }\n }\n }\n }\n return { text, thinking }\n }\n\n /**\n * Maps common TextOptions to Mistral Chat Completions request parameters.\n */\n private mapTextOptionsToMistral(\n options: TextOptions<TProviderOptions>,\n ): ChatCompletionStreamRequest {\n const modelOptions = options.modelOptions as\n | Omit<InternalTextProviderOptions, 'tools'>\n | undefined\n\n const tools = options.tools\n ? convertToolsToProviderFormat(options.tools)\n : undefined\n\n // History from another model loses its signatures, and its tool IDs are\n // rewritten to the 9-character IDs Mistral accepts.\n const replay = transformMessagesForReplay(\n options.messages,\n { provider: this.provider, api: this.api, model: options.model },\n (id, { attempt }) => {\n const normalized = id.replace(/[^a-zA-Z0-9]/g, '')\n if (attempt === 0 && normalized.length === 9) return normalized\n const seed = normalized || id\n return hashToolCallId(attempt === 0 ? seed : `${seed}:${attempt}`)\n .replace(/[^a-zA-Z0-9]/g, '')\n .slice(0, 9)\n },\n )\n const messages: ChatCompletionStreamRequest['messages'] = []\n\n if (options.systemPrompts && options.systemPrompts.length > 0) {\n messages.push({\n role: 'system',\n content: options.systemPrompts.join('\\n'),\n })\n }\n\n for (const message of replay.messages) {\n messages.push(this.convertMessageToMistral(message))\n }\n\n // `chat({ toolChoice })` is sent only when the request has tools. It goes\n // before the `modelOptions` spread, so a `tool_choice` there wins.\n const toolChoiceField =\n tools?.length && options.toolChoice !== undefined\n ? { toolChoice: toMistralToolChoice(options.toolChoice) }\n : undefined\n\n return {\n ...toolChoiceField,\n model: this.rawConfig.requestModel ?? options.model,\n messages: messages,\n temperature: modelOptions?.temperature ?? undefined,\n maxTokens: modelOptions?.max_tokens ?? undefined,\n topP: modelOptions?.top_p ?? undefined,\n tools: tools as ChatCompletionStreamRequest['tools'],\n stream: true,\n ...mistralReasoning(\n options.model,\n options.reasoning,\n MISTRAL_MODEL_REASONING[options.model],\n ),\n ...(modelOptions && {\n ...(modelOptions.stop != null && { stop: modelOptions.stop }),\n ...(modelOptions.random_seed != null && {\n randomSeed: modelOptions.random_seed,\n }),\n ...(modelOptions.response_format != null && {\n responseFormat: modelOptions.response_format,\n }),\n ...(modelOptions.tool_choice != null && {\n toolChoice: modelOptions.tool_choice,\n }),\n ...(modelOptions.parallel_tool_calls != null && {\n parallelToolCalls: modelOptions.parallel_tool_calls,\n }),\n ...(modelOptions.frequency_penalty != null && {\n frequencyPenalty: modelOptions.frequency_penalty,\n }),\n ...(modelOptions.presence_penalty != null && {\n presencePenalty: modelOptions.presence_penalty,\n }),\n ...(modelOptions.n != null && { n: modelOptions.n }),\n ...(modelOptions.prediction != null && {\n prediction: modelOptions.prediction,\n }),\n ...(modelOptions.safe_prompt != null && {\n safePrompt: modelOptions.safe_prompt,\n }),\n }),\n }\n }\n\n /**\n * Converts a TanStack AI ModelMessage to a Mistral ChatCompletionMessageParam.\n */\n private convertMessageToMistral(\n message: ModelMessage,\n ): ChatCompletionStreamRequest['messages'][number] {\n if (message.role === 'tool') {\n if (!message.toolCallId) {\n throw new Error('Missing toolCallId for tool message')\n }\n return {\n role: 'tool',\n toolCallId: message.toolCallId,\n // Mistral accepts image chunks in a tool message, so send the parts.\n content: Array.isArray(message.content)\n ? message.content.map((part) =>\n this.convertContentPartToMistral(part),\n )\n : typeof message.content === 'string'\n ? message.content\n : JSON.stringify(message.content),\n }\n }\n\n if (message.role === 'assistant') {\n const toolCalls = message.toolCalls?.map((tc) => ({\n id: tc.id,\n type: 'function' as const,\n function: {\n name: tc.function.name,\n arguments:\n typeof tc.function.arguments === 'string'\n ? tc.function.arguments\n : JSON.stringify(tc.function.arguments),\n },\n }))\n\n return {\n role: 'assistant',\n content: this.assistantContent(message),\n ...(toolCalls && toolCalls.length > 0 ? { toolCalls } : {}),\n }\n }\n\n const contentParts = this.normalizeContent(message.content)\n\n if (contentParts.length === 1 && contentParts[0]?.type === 'text') {\n return {\n role: 'user',\n content: contentParts[0].content,\n }\n }\n\n const parts = contentParts.map((part) =>\n this.convertContentPartToMistral(part),\n )\n\n return {\n role: 'user',\n content: parts.length > 0 ? parts : '',\n }\n }\n\n /** Readable thinking and text, in the stored block order. */\n private assistantContent(message: ModelMessage): AssistantMessage['content'] {\n if (!message.thinking?.length)\n return this.extractTextContent(message.content)\n const blocks = orderedAssistantBlocks(message) ?? [\n ...message.thinking.map((thinking) => ({\n type: 'thinking' as const,\n thinking,\n })),\n { type: 'text' as const, text: this.extractTextContent(message.content) },\n ]\n const content: Array<ContentChunk> = []\n for (const block of blocks) {\n if (block.type === 'text')\n content.push({ type: 'text', text: block.text })\n else if (\n block.type === 'thinking' &&\n !block.thinking.redacted &&\n block.thinking.content.trim()\n ) {\n content.push({\n type: 'thinking',\n thinking: [{ type: 'text', text: block.thinking.content }],\n })\n }\n }\n return content\n }\n\n /**\n * Converts a ContentPart to a Mistral content part. Returns undefined for\n * unsupported part types.\n */\n private convertContentPartToMistral(\n part: ContentPart,\n ): ChatCompletionContentPart {\n if (part.type === 'text') {\n return { type: 'text', text: part.content }\n }\n\n if (part.type === 'image') {\n if (isFileSource(part.source)) {\n throw unsupportedFileSourceError('mistral')\n }\n const imageMetadata = part.metadata as MistralImageMetadata | undefined\n const imageValue = part.source.value\n const imageUrl =\n part.source.type === 'data' && !imageValue.startsWith('data:')\n ? `data:${part.source.mimeType};base64,${imageValue}`\n : imageValue\n return {\n type: 'image_url',\n imageUrl: imageMetadata?.detail\n ? { url: imageUrl, detail: imageMetadata.detail }\n : imageUrl,\n }\n }\n\n if (part.type === 'document') {\n if (isFileSource(part.source)) {\n throw unsupportedFileSourceError('mistral')\n }\n const documentValue = part.source.value\n const documentUrl =\n part.source.type === 'data' && !documentValue.startsWith('data:')\n ? `data:${part.source.mimeType};base64,${documentValue}`\n : documentValue\n return { type: 'document_url', documentUrl }\n }\n\n throw new Error(\n `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.`,\n )\n }\n\n /**\n * Normalizes message content to an array of ContentPart.\n */\n private normalizeContent(\n content: string | null | undefined | Array<ContentPart>,\n ): Array<ContentPart> {\n if (content === null || content === undefined) return []\n if (typeof content === 'string') return [{ type: 'text', content }]\n return content\n }\n\n /**\n * Extracts text content from a content value that may be string, null, or ContentPart array.\n */\n private extractTextContent(\n content: string | null | undefined | Array<ContentPart>,\n ): string {\n if (content === null || content === undefined) return ''\n if (typeof content === 'string') return content\n return content\n .filter((p) => p.type === 'text')\n .map((p) => p.content)\n .join('')\n }\n}\n\n/**\n * Snake-cases a Mistral SDK message into the wire format expected by the API.\n */\nfunction messageToWire(msg: ChatCompletionStreamRequest['messages'][number]) {\n if (msg.role === 'tool') {\n return {\n role: 'tool',\n tool_call_id: msg.toolCallId,\n content: Array.isArray(msg.content)\n ? msg.content.map(contentPartToWire)\n : msg.content,\n ...(msg.name !== undefined ? { name: msg.name } : {}),\n }\n }\n if (msg.role === 'assistant') {\n const base: Record<string, unknown> = {\n role: 'assistant',\n content: msg.content ?? null,\n }\n if (msg.toolCalls && msg.toolCalls.length > 0) {\n base.tool_calls = msg.toolCalls.map((tc) => ({\n id: tc.id,\n type: tc.type ?? 'function',\n function: tc.function,\n }))\n }\n if (msg.prefix !== undefined) base.prefix = msg.prefix\n return base\n }\n if (msg.role === 'user' && Array.isArray(msg.content)) {\n return {\n role: 'user',\n content: msg.content.map(contentPartToWire),\n }\n }\n return msg\n}\n\n/**\n * Snake-cases one content chunk of a user or tool message.\n */\nfunction contentPartToWire(part: ContentChunk) {\n if (part.type === 'image_url') {\n return { type: 'image_url', image_url: part.imageUrl }\n }\n if (part.type === 'document_url') {\n return { type: 'document_url', document_url: part.documentUrl }\n }\n return part\n}\n\n/**\n * Creates a Mistral text adapter with explicit API key.\n *\n * @param model - The model name (e.g., 'mistral-large-latest')\n * @param apiKey - Your Mistral API key\n * @param config - Optional additional configuration\n * @returns Configured Mistral text adapter instance\n *\n * @example\n * ```typescript\n * const adapter = createMistralText('mistral-large-latest', 'api_key');\n * ```\n */\nexport function createMistralText<\n TModel extends (typeof MISTRAL_CHAT_MODELS)[number],\n>(\n model: TModel,\n apiKey: string,\n config?: Omit<MistralTextConfig, 'apiKey'>,\n): MistralTextAdapter<TModel> {\n return new MistralTextAdapter({ apiKey, ...config }, model)\n}\n\n/**\n * Creates a Mistral text adapter using the `MISTRAL_API_KEY` environment variable.\n *\n * @param model - The model name (e.g., 'mistral-large-latest')\n * @param config - Optional configuration (excluding apiKey)\n * @returns Configured Mistral text adapter instance\n * @throws Error if MISTRAL_API_KEY is not found in environment\n *\n * @example\n * ```typescript\n * const adapter = mistralText('mistral-large-latest');\n * ```\n */\nexport function mistralText<\n TModel extends (typeof MISTRAL_CHAT_MODELS)[number],\n>(\n model: TModel,\n config?: Omit<MistralTextConfig, 'apiKey'>,\n): MistralTextAdapter<TModel> {\n const apiKey = getMistralApiKeyFromEnv()\n return createMistralText(model, apiKey, config)\n}\n"],"mappings":";;;;;;;;;;;;AAiEA,IAAM,WAAW,UAEf;;;;;;AAOF,SAAS,mBACP,UAKA,oBACS;CACT,IAAI,CAAC,SAAS,WAAW,OAAO,CAAC;CACjC,IAAI;EACF,OAAO,mBAAmB,SAAS,MAAM,KAAK,MAAM,SAAS,SAAS,CAAC;CACzE,SAAS,OAAO;EACd,MAAM,UAAU,SAAS,UAAU,MAAM,GAAG,GAAG;EAC/C,MAAM,WAAW,SAAS,UAAU,SAAS,MAAM,QAAQ;EAC3D,MAAM,IAAI,MACR,iDAAiD,SAAS,KAAK,SAAS,SAAS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kB,OADV,wBACiB,GAAQ,MAAM;AAChD"}
1
+ {"version":3,"file":"text.js","names":[],"sources":["../../../src/adapters/text.ts"],"sourcesContent":["import { isFileSource, unsupportedFileSourceError } from '@tanstack/ai'\nimport { BaseTextAdapter } from '@tanstack/ai/adapters'\nimport { undoNullWidening } from '@tanstack/ai-utils'\nimport { convertToolsToProviderFormat } from '../tools/tool-converter'\nimport {\n createMistralClient,\n generateId,\n getMistralApiKeyFromEnv,\n} from '../utils/client'\nimport { makeMistralStructuredOutputCompatibleWithMap } from '../utils/schema-converter'\nimport { createToolInputNormalizer } from '../utils/tool-input-normalizer'\nimport {\n MISTRAL_MODEL_INPUT_MODALITIES,\n MISTRAL_MODEL_REASONING,\n} from '../model-meta'\nimport {\n hashToolCallId,\n orderedAssistantBlocks,\n resolveReasoning,\n transformMessagesForReplay,\n} from '@tanstack/ai/adapter-internals'\nimport type {\n ContentPart,\n FetchWrapper,\n Modality,\n ModelMessage,\n AdapterYieldChunk,\n ModelReasoning,\n ReasoningRequest,\n ResolvedPromptCache,\n TextOptions,\n ToolChoice,\n} from '@tanstack/ai'\nimport type {\n MISTRAL_CHAT_MODELS,\n MistralChatModelProviderOptionsByName,\n MistralModelInputModalitiesByName,\n MistralModelReasoningByName,\n MistralTextAdapterModel,\n} from '../model-meta'\nimport type {\n StructuredOutputOptions,\n StructuredOutputResult,\n} from '@tanstack/ai/adapters'\nimport type { Mistral } from '@mistralai/mistralai'\nimport type {\n AssistantMessage,\n ChatCompletionStreamRequest,\n ContentChunk,\n ReasoningEffort,\n} from '@mistralai/mistralai/models/components'\nimport type {\n ExternalTextProviderOptions,\n InternalTextProviderOptions,\n} from '../text/text-provider-options'\nimport type {\n ChatCompletionContentPart,\n MistralImageMetadata,\n MistralMessageMetadataByModality,\n} from '../message-types'\nimport type { MistralClientConfig } from '../utils/client'\nimport type { ToolInputNormalizer } from '../utils/tool-input-normalizer'\n\n/** Cast an event object to StreamChunk. Adapters construct events with string\n * literal types which are structurally compatible with the EventType enum. */\nconst asChunk = (chunk: Record<string, unknown>) =>\n // 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\n chunk as unknown as AdapterYieldChunk\n\n/**\n * Parse the accumulated streaming arguments for a tool call. Throws a clear\n * error if the JSON is malformed — silently substituting `{}` would let a\n * tool fire with empty inputs, masking truncated streams or mis-shaped output.\n */\nfunction parseToolCallInput(\n toolCall: {\n id: string\n name: string\n arguments: string\n },\n normalizeToolInput: ToolInputNormalizer,\n): unknown {\n if (!toolCall.arguments) return {}\n try {\n return normalizeToolInput(toolCall.name, JSON.parse(toolCall.arguments))\n } catch (cause) {\n const preview = toolCall.arguments.slice(0, 200)\n const ellipsis = toolCall.arguments.length > 200 ? '...' : ''\n throw new Error(\n `Failed to parse tool call arguments for tool '${toolCall.name}' (id: ${toolCall.id}). Arguments: ${preview}${ellipsis}`,\n { cause },\n )\n }\n}\n\n/**\n * Configuration for Mistral text adapter.\n */\nexport type MistralTextConfig = MistralClientConfig\n\n/**\n * Alias for TextProviderOptions for external use.\n */\nexport type MistralTextProviderOptions = ExternalTextProviderOptions\n\n// ===========================\n// Type Resolution Helpers\n// ===========================\n\ntype ResolveProviderOptions<TModel extends string> =\n TModel extends keyof MistralChatModelProviderOptionsByName\n ? MistralChatModelProviderOptionsByName[TModel]\n : MistralTextProviderOptions\n\n/** The reasoning levels of a model, for `chat({ reasoning })`. `never`: none. */\ntype ResolveReasoning<TModel extends string> =\n TModel extends keyof MistralModelReasoningByName\n ? MistralModelReasoningByName[TModel]\n : never\n\n/**\n * The Mistral reasoning fields for `chat({ reasoning })`, by pi's rule:\n * - a model with effort levels (Mistral Small, Mistral Medium):\n * `reasoningEffort` with the level's value, `none` for `off`.\n * - Magistral: `promptMode: 'reasoning'`, and nothing for `off`.\n */\nfunction mistralReasoning(\n model: string,\n request: ReasoningRequest | undefined,\n reasoning: ModelReasoning | undefined,\n): Pick<ChatCompletionStreamRequest, 'promptMode' | 'reasoningEffort'> {\n const resolved = resolveReasoning(request, reasoning)\n if (!resolved) return {}\n if (model.startsWith('magistral')) {\n return resolved.level === 'off' ? {} : { promptMode: 'reasoning' }\n }\n // `ReasoningEffort` is an open enum, so a newer value still goes out.\n return { reasoningEffort: resolved.value as ReasoningEffort }\n}\n\n/** Maps `chat({ toolChoice })` to the Mistral `toolChoice`. */\nfunction toMistralToolChoice(\n choice: ToolChoice,\n): NonNullable<ChatCompletionStreamRequest['toolChoice']> {\n if (typeof choice === 'string') return choice\n return { type: 'function', function: { name: choice.name } }\n}\n\n/**\n * The Mistral wire field for `chat({ promptCache })`. Mistral caches without\n * a flag, so only the key goes out. There is no key for `'none'`. Send the\n * key only to `api.mistral.ai`. The SDK request schema drops unknown fields,\n * so structured output adds the key after that schema runs.\n */\nfunction mistralPromptCacheKey(promptCache: ResolvedPromptCache | undefined) {\n if (!promptCache?.key || promptCache.retention === 'none') return undefined\n return promptCache.key\n}\n\nfunction mistralOwnApi(config: MistralClientConfig, provider: string) {\n if (provider === 'google-vertex') return false\n const serverURL =\n config.baseURL ?? config.serverURL ?? 'https://api.mistral.ai'\n try {\n return new URL(serverURL).hostname === 'api.mistral.ai'\n } catch {\n return false\n }\n}\n\n/** Add `prompt_cache_key` to a JSON body the SDK has already serialized. */\nfunction withPromptCacheKey(next: typeof fetch, key: string): typeof fetch {\n return async (input, init) => {\n const body = init?.body\n const text =\n typeof body === 'string'\n ? body\n : body instanceof ArrayBuffer\n ? new TextDecoder().decode(body)\n : undefined\n if (text === undefined) return next(input, init)\n let parsed: unknown\n try {\n parsed = JSON.parse(text)\n } catch {\n return next(input, init)\n }\n if (\n typeof parsed !== 'object' ||\n parsed === null ||\n Array.isArray(parsed)\n ) {\n return next(input, init)\n }\n return next(input, {\n ...init,\n body: JSON.stringify({ ...parsed, prompt_cache_key: key }),\n })\n }\n}\n\n/**\n * `promptTokensDetails.cachedTokens` when Mistral read prompt tokens from the\n * cache. Mistral sends the count in `prompt_tokens_details.cached_tokens` or\n * in `num_cached_tokens`. The SDK keeps these raw keys on `usage` with no\n * types, so the values are checked here.\n */\nfunction mistralCachedTokens(usage: Record<string, unknown>) {\n const details = usage.prompt_tokens_details\n const hasDetailsCount =\n typeof details === 'object' &&\n details !== null &&\n 'cached_tokens' in details\n const cachedTokens = hasDetailsCount\n ? details.cached_tokens\n : usage.num_cached_tokens\n return typeof cachedTokens === 'number' && cachedTokens > 0\n ? { promptTokensDetails: { cachedTokens } }\n : {}\n}\n\ntype ResolveInputModalities<TModel extends string> =\n TModel extends keyof MistralModelInputModalitiesByName\n ? MistralModelInputModalitiesByName[TModel]\n : readonly ['text']\n\n// ===========================\n// Wire-format chunk types\n// ===========================\n\n/**\n * Snake-case shape of a Mistral chat completion stream chunk as returned on the\n * wire. We bypass the SDK's `chat.stream` because its Zod validation rejects\n * tool-call argument deltas that omit `function.name` (only the first chunk in\n * a tool call carries the name).\n */\ninterface MistralRawToolCall {\n id?: string\n type?: string\n index?: number\n function?: {\n name?: string\n arguments?: string | Record<string, unknown>\n }\n}\n\ninterface MistralRawChoice {\n index?: number\n delta?: {\n role?: string | null\n content?:\n | string\n | Array<{\n type: string\n text?: string\n // Mistral magistral models stream reasoning as content parts of\n // type 'thinking' whose `thinking` field is itself an array of\n // text/reference chunks. See Mistral SDK ThinkChunk type.\n thinking?: Array<{ type: string; text?: string }>\n }>\n | null\n // Some OpenAI-compatible deployments (DeepSeek, Groq for reasoning\n // models, and aimock-based test environments) emit reasoning via a\n // separate `reasoning_content` delta field rather than as a content\n // part. Accept both shapes — they cannot collide because real Mistral\n // never sets the OpenAI-compat field, and aimock never sets the\n // thinking content part.\n reasoning_content?: string | null\n tool_calls?: Array<MistralRawToolCall>\n }\n finish_reason?: string | null\n}\n\ninterface MistralRawChunk {\n id?: string\n model?: string\n choices?: Array<MistralRawChoice>\n usage?: {\n prompt_tokens?: number\n completion_tokens?: number\n total_tokens?: number\n // Cache reads. Mistral sends one of these two.\n prompt_tokens_details?: { cached_tokens?: number } | null\n num_cached_tokens?: number | null\n }\n}\n\n// ===========================\n// Adapter Implementation\n// ===========================\n\n/**\n * Mistral Text (Chat) Adapter.\n *\n * Tree-shakeable adapter for Mistral chat/text completion functionality.\n */\nexport class MistralTextAdapter<\n TModel extends MistralTextAdapterModel,\n TProviderOptions extends Record<string, any> = ResolveProviderOptions<TModel>,\n TInputModalities extends ReadonlyArray<Modality> =\n ResolveInputModalities<TModel>,\n> extends BaseTextAdapter<\n TModel,\n TProviderOptions,\n TInputModalities,\n MistralMessageMetadataByModality,\n ReadonlyArray<string>,\n unknown,\n never,\n ResolveReasoning<TModel>\n> {\n readonly name = 'mistral' as const\n override readonly api = 'mistral-conversations' as const\n override readonly provider: string\n override readonly inputModalities = MISTRAL_MODEL_INPUT_MODALITIES[this.model]\n\n private readonly client: Mistral\n private readonly rawConfig: MistralClientConfig\n\n constructor(config: MistralTextConfig, model: TModel) {\n super(config, model)\n // The SDK client is retained for `structuredOutput` (non-streaming). The\n // streaming path bypasses the SDK and uses `fetchRawMistralStream` because\n // the SDK's Zod schemas reject partial tool-call argument deltas.\n this.client = createMistralClient(config)\n this.rawConfig = config\n this.provider =\n config.getAccessToken && config.resolveRequestUrl\n ? 'google-vertex'\n : this.name\n }\n\n async *chatStream(\n options: TextOptions<TProviderOptions>,\n ): AsyncIterable<AdapterYieldChunk> {\n const requestParams = this.mapTextOptionsToMistral(options)\n const timestamp = Date.now()\n\n const aguiState = {\n runId: options.runId ?? generateId(this.name),\n threadId: options.threadId,\n messageId: generateId(this.name),\n timestamp,\n hasEmittedRunStarted: false,\n }\n\n try {\n const cacheKey = mistralOwnApi(this.rawConfig, this.provider)\n ? mistralPromptCacheKey(options.promptCache)\n : undefined\n const body = {\n ...this.toWireBody(requestParams),\n ...(cacheKey !== undefined && { prompt_cache_key: cacheKey }),\n }\n const stream = this.fetchRawMistralStream(\n body,\n this.rawConfig,\n options.wrapFetch,\n )\n for await (const chunk of this.processMistralStreamChunks(\n stream,\n options,\n aguiState,\n )) {\n yield chunk.type === 'RUN_STARTED' || chunk.type === 'RUN_ERROR'\n ? {\n ...chunk,\n metadata: {\n ...chunk.metadata,\n tanstack: {\n ...chunk.metadata?.tanstack,\n source: {\n provider: this.provider,\n api: this.api,\n model: options.model,\n },\n },\n },\n }\n : chunk\n }\n } catch (error: unknown) {\n const err = error as Error & { code?: string }\n\n if (!aguiState.hasEmittedRunStarted) {\n aguiState.hasEmittedRunStarted = true\n yield asChunk({\n type: 'RUN_STARTED',\n runId: aguiState.runId,\n threadId: aguiState.threadId,\n metadata: {\n tanstack: {\n source: {\n provider: this.provider,\n api: this.api,\n model: options.model,\n },\n },\n },\n model: options.model,\n timestamp,\n })\n }\n\n yield asChunk({\n type: 'RUN_ERROR',\n metadata: {\n tanstack: {\n source: {\n provider: this.provider,\n api: this.api,\n model: options.model,\n },\n },\n },\n runId: aguiState.runId,\n model: options.model,\n timestamp,\n message: err.message || 'Unknown error',\n code: err.code,\n error: {\n message: err.message || 'Unknown error',\n code: err.code,\n },\n })\n\n throw err\n }\n }\n\n /**\n * Generate structured output using Mistral's JSON Schema response format.\n */\n async structuredOutput(\n options: StructuredOutputOptions<TProviderOptions>,\n ): Promise<StructuredOutputResult<unknown>> {\n const { chatOptions, outputSchema } = options\n const { stream: _stream, ...nonStreamParams } =\n this.mapTextOptionsToMistral(chatOptions)\n\n const {\n schema: jsonSchema,\n nullWideningMap,\n strict,\n } = makeMistralStructuredOutputCompatibleWithMap(\n outputSchema,\n outputSchema.required || [],\n )\n\n const cacheKey = mistralOwnApi(this.rawConfig, this.provider)\n ? mistralPromptCacheKey(chatOptions.promptCache)\n : undefined\n const next = chatOptions.wrapFetch ? chatOptions.wrapFetch(fetch) : fetch\n const client = cacheKey\n ? createMistralClient(this.rawConfig, withPromptCacheKey(next, cacheKey))\n : chatOptions.wrapFetch\n ? createMistralClient(this.rawConfig, next)\n : this.client\n const response = await client.chat.complete({\n ...nonStreamParams,\n responseFormat: {\n type: 'json_schema',\n jsonSchema: {\n name: 'structured_output',\n schemaDefinition: jsonSchema,\n strict,\n },\n },\n })\n\n // A response cut off at the output cap is a truncated JSON document;\n // report it before the parse error (issue #1426).\n if (response.choices[0]?.finishReason === 'length') {\n throw new Error(\n 'mistral.structuredOutput: the response was cut off because the maximum token limit was reached (finish_reason=length); raise modelOptions.max_tokens',\n )\n }\n\n const rawText = response.choices[0]?.message?.content\n const textContent = typeof rawText === 'string' ? rawText : ''\n\n let parsed: unknown\n try {\n parsed = JSON.parse(textContent)\n } catch {\n throw new Error(\n `Failed to parse structured output as JSON. Content: ${textContent.slice(0, 200)}${textContent.length > 200 ? '...' : ''}`,\n )\n }\n\n const usage = response.usage\n return {\n data: undoNullWidening(parsed, nullWideningMap),\n ...(response.id && { responseId: response.id }),\n ...(response.model && { model: response.model }),\n rawText: textContent,\n ...(usage && {\n usage: {\n promptTokens: usage.promptTokens ?? 0,\n completionTokens: usage.completionTokens ?? 0,\n totalTokens: usage.totalTokens ?? 0,\n ...mistralCachedTokens(usage),\n },\n }),\n }\n }\n\n /**\n * Processes streaming chunks from the Mistral API and yields AG-UI stream events.\n */\n private async *processMistralStreamChunks(\n stream: AsyncIterable<MistralRawChunk>,\n options: TextOptions,\n aguiState: {\n runId: string\n threadId: string\n messageId: string\n timestamp: number\n hasEmittedRunStarted: boolean\n },\n ): AsyncIterable<AdapterYieldChunk> {\n let accumulatedContent = ''\n const timestamp = aguiState.timestamp\n let hasEmittedTextMessageStart = false\n let hasEmittedTextMessageEnd = false\n let hasEmittedToolCall = false\n let hasEmittedRunFinished = false\n let lastChunkModel = options.model\n let responseId: string | undefined\n const normalizeToolInput = createToolInputNormalizer(options.tools)\n\n // Reasoning lifecycle (magistral-* models stream `thinking` content\n // parts before any text). Mirrors the anthropic adapter's pattern:\n // open REASONING_* events on the first thinking delta, close them when\n // text/tool content begins or the run finishes.\n let reasoningMessageId: string | null = null\n let hasClosedReasoning = false\n\n const toolCallsInProgress = new Map<\n number,\n {\n id: string\n name: string\n arguments: string\n started: boolean\n ended: boolean\n }\n >()\n\n try {\n for await (const chunk of stream) {\n lastChunkModel = chunk.model || lastChunkModel\n if (chunk.id) responseId = chunk.id\n const choice = chunk.choices?.[0]\n if (!choice) continue\n\n const chunkModel = chunk.model || options.model\n\n if (!aguiState.hasEmittedRunStarted) {\n aguiState.hasEmittedRunStarted = true\n yield asChunk({\n type: 'RUN_STARTED',\n runId: aguiState.runId,\n threadId: aguiState.threadId,\n model: chunkModel,\n timestamp,\n })\n }\n\n const delta = choice.delta\n const { text: deltaContent, thinking: deltaThinkingFromContent } =\n this.extractDeltaParts(delta?.content)\n // Reasoning may also arrive as a separate top-level field\n // (`delta.reasoning_content`) on OpenAI-compatible deployments.\n const deltaThinking =\n deltaThinkingFromContent +\n (typeof delta?.reasoning_content === 'string'\n ? delta.reasoning_content\n : '')\n const deltaToolCalls = delta?.tool_calls\n\n // Emit reasoning events FIRST so they always precede the matching\n // text or tool deltas in the same chunk.\n if (deltaThinking) {\n if (reasoningMessageId === null) {\n reasoningMessageId = generateId(this.name)\n yield asChunk({\n type: 'REASONING_START',\n messageId: reasoningMessageId,\n model: chunkModel,\n timestamp,\n })\n yield asChunk({\n type: 'REASONING_MESSAGE_START',\n messageId: reasoningMessageId,\n role: 'reasoning',\n model: chunkModel,\n timestamp,\n })\n }\n yield asChunk({\n type: 'REASONING_MESSAGE_CONTENT',\n messageId: reasoningMessageId,\n model: chunkModel,\n timestamp,\n delta: deltaThinking,\n })\n }\n\n // Close reasoning before any text/tool output starts in this chunk.\n const aboutToEmitOutput =\n !!deltaContent || (!!deltaToolCalls && deltaToolCalls.length > 0)\n if (\n reasoningMessageId !== null &&\n !hasClosedReasoning &&\n aboutToEmitOutput\n ) {\n hasClosedReasoning = true\n yield asChunk({\n type: 'REASONING_MESSAGE_END',\n messageId: reasoningMessageId,\n model: chunkModel,\n timestamp,\n })\n yield asChunk({\n type: 'REASONING_END',\n messageId: reasoningMessageId,\n model: chunkModel,\n timestamp,\n })\n }\n\n if (deltaContent) {\n if (!hasEmittedTextMessageStart) {\n hasEmittedTextMessageStart = true\n yield asChunk({\n type: 'TEXT_MESSAGE_START',\n messageId: aguiState.messageId,\n model: chunkModel,\n timestamp,\n role: 'assistant',\n })\n }\n\n accumulatedContent += deltaContent\n\n yield asChunk({\n type: 'TEXT_MESSAGE_CONTENT',\n messageId: aguiState.messageId,\n model: chunkModel,\n timestamp,\n delta: deltaContent,\n content: accumulatedContent,\n })\n }\n\n if (deltaToolCalls) {\n for (const [i, toolCallDelta] of deltaToolCalls.entries()) {\n const index = toolCallDelta.index ?? i\n\n let toolCall = toolCallsInProgress.get(index)\n if (!toolCall) {\n toolCall = {\n id: toolCallDelta.id || '',\n name: toolCallDelta.function?.name || '',\n arguments: '',\n started: false,\n ended: false,\n }\n toolCallsInProgress.set(index, toolCall)\n }\n\n if (toolCallDelta.id) toolCall.id = toolCallDelta.id\n if (toolCallDelta.function?.name) {\n toolCall.name = toolCallDelta.function.name\n }\n\n const rawArgs = toolCallDelta.function?.arguments\n const argsDelta =\n rawArgs === undefined\n ? undefined\n : typeof rawArgs === 'string'\n ? rawArgs\n : JSON.stringify(rawArgs)\n\n if (argsDelta !== undefined) {\n toolCall.arguments += argsDelta\n }\n\n const justStarted =\n !!toolCall.id && !!toolCall.name && !toolCall.started\n if (justStarted) {\n toolCall.started = true\n yield asChunk({\n type: 'TOOL_CALL_START',\n toolCallId: toolCall.id,\n toolCallName: toolCall.name,\n model: chunkModel,\n timestamp,\n index,\n })\n // Replay any args buffered before id+name arrived (including\n // this chunk's argsDelta, if any).\n if (toolCall.arguments.length > 0) {\n yield asChunk({\n type: 'TOOL_CALL_ARGS',\n toolCallId: toolCall.id,\n model: chunkModel,\n timestamp,\n delta: toolCall.arguments,\n })\n }\n } else if (argsDelta !== undefined && toolCall.started) {\n yield asChunk({\n type: 'TOOL_CALL_ARGS',\n toolCallId: toolCall.id,\n model: chunkModel,\n timestamp,\n delta: argsDelta,\n })\n }\n }\n }\n\n const finishReason = choice.finish_reason\n if (finishReason) {\n if (finishReason === 'tool_calls' || toolCallsInProgress.size > 0) {\n for (const [, toolCall] of toolCallsInProgress) {\n if (\n !toolCall.started ||\n !toolCall.id ||\n !toolCall.name ||\n toolCall.ended\n ) {\n continue\n }\n\n const parsedInput = parseToolCallInput(\n toolCall,\n normalizeToolInput,\n )\n\n toolCall.ended = true\n hasEmittedToolCall = true\n yield asChunk({\n type: 'TOOL_CALL_END',\n toolCallId: toolCall.id,\n toolCallName: toolCall.name,\n model: chunkModel,\n timestamp,\n args: toolCall.arguments,\n input: parsedInput,\n })\n }\n }\n\n const computedFinishReason =\n finishReason === 'tool_calls' || hasEmittedToolCall\n ? 'tool_calls'\n : finishReason === 'length'\n ? 'length'\n : 'stop'\n\n // If the run finished while reasoning was still open (no text or\n // tool output ever followed), close reasoning before TEXT/RUN\n // finalization events.\n if (reasoningMessageId !== null && !hasClosedReasoning) {\n hasClosedReasoning = true\n yield asChunk({\n type: 'REASONING_MESSAGE_END',\n messageId: reasoningMessageId,\n model: chunkModel,\n timestamp,\n })\n yield asChunk({\n type: 'REASONING_END',\n messageId: reasoningMessageId,\n model: chunkModel,\n timestamp,\n })\n }\n\n if (hasEmittedTextMessageStart && !hasEmittedTextMessageEnd) {\n hasEmittedTextMessageEnd = true\n yield asChunk({\n type: 'TEXT_MESSAGE_END',\n messageId: aguiState.messageId,\n model: chunkModel,\n timestamp,\n })\n }\n\n const usage = chunk.usage\n hasEmittedRunFinished = true\n yield asChunk({\n type: 'RUN_FINISHED',\n ...(responseId && { responseId }),\n runId: aguiState.runId,\n threadId: aguiState.threadId,\n model: chunkModel,\n timestamp,\n usage: usage\n ? {\n promptTokens: usage.prompt_tokens || 0,\n completionTokens: usage.completion_tokens || 0,\n totalTokens: usage.total_tokens || 0,\n ...mistralCachedTokens(usage),\n }\n : undefined,\n finishReason: computedFinishReason,\n })\n }\n }\n\n // Stream ended cleanly without finish_reason — flush any open\n // lifecycle events so consumers don't see orphaned starts. This\n // happens for abrupt `[DONE]` or upstream cuts.\n if (!hasEmittedRunFinished) {\n if (reasoningMessageId !== null && !hasClosedReasoning) {\n hasClosedReasoning = true\n yield asChunk({\n type: 'REASONING_MESSAGE_END',\n messageId: reasoningMessageId,\n model: lastChunkModel,\n timestamp,\n })\n yield asChunk({\n type: 'REASONING_END',\n messageId: reasoningMessageId,\n model: lastChunkModel,\n timestamp,\n })\n }\n for (const [, toolCall] of toolCallsInProgress) {\n if (toolCall.started && !toolCall.ended) {\n // Parse before marking ended, so a parse error still lets the\n // catch below send TOOL_CALL_END with the raw args.\n const parsedInput = parseToolCallInput(toolCall, normalizeToolInput)\n toolCall.ended = true\n hasEmittedToolCall = true\n yield asChunk({\n type: 'TOOL_CALL_END',\n toolCallId: toolCall.id,\n toolCallName: toolCall.name,\n model: lastChunkModel,\n timestamp,\n args: toolCall.arguments,\n input: parsedInput,\n })\n }\n }\n if (hasEmittedTextMessageStart && !hasEmittedTextMessageEnd) {\n hasEmittedTextMessageEnd = true\n yield asChunk({\n type: 'TEXT_MESSAGE_END',\n messageId: aguiState.messageId,\n model: lastChunkModel,\n timestamp,\n })\n }\n hasEmittedRunFinished = true\n yield asChunk({\n type: 'RUN_FINISHED',\n ...(responseId && { responseId }),\n runId: aguiState.runId,\n threadId: aguiState.threadId,\n model: lastChunkModel,\n timestamp,\n usage: undefined,\n finishReason: hasEmittedToolCall ? 'tool_calls' : 'stop',\n })\n }\n } catch (error: unknown) {\n // Lifecycle cleanup (TEXT_MESSAGE_END / TOOL_CALL_END / REASONING_END)\n // on error path so consumers don't see orphaned starts. RUN_ERROR is\n // emitted by the outer chatStream catch — emitting it here would\n // duplicate the event.\n if (reasoningMessageId !== null && !hasClosedReasoning) {\n hasClosedReasoning = true\n yield asChunk({\n type: 'REASONING_MESSAGE_END',\n messageId: reasoningMessageId,\n model: lastChunkModel,\n timestamp,\n })\n yield asChunk({\n type: 'REASONING_END',\n messageId: reasoningMessageId,\n model: lastChunkModel,\n timestamp,\n })\n }\n if (hasEmittedTextMessageStart && !hasEmittedTextMessageEnd) {\n hasEmittedTextMessageEnd = true\n yield asChunk({\n type: 'TEXT_MESSAGE_END',\n messageId: aguiState.messageId,\n model: lastChunkModel,\n timestamp,\n })\n }\n for (const [, toolCall] of toolCallsInProgress) {\n if (toolCall.started && !toolCall.ended) {\n toolCall.ended = true\n // Best-effort parse for the partial args. If invalid, leave input\n // out and send the raw args, so core reports the parse error.\n let partialInput: unknown\n try {\n partialInput = toolCall.arguments\n ? normalizeToolInput(\n toolCall.name,\n JSON.parse(toolCall.arguments),\n )\n : {}\n } catch {\n partialInput = undefined\n }\n yield asChunk({\n type: 'TOOL_CALL_END',\n toolCallId: toolCall.id,\n toolCallName: toolCall.name,\n model: lastChunkModel,\n timestamp,\n args: toolCall.arguments,\n ...(partialInput !== undefined && { input: partialInput }),\n })\n }\n }\n throw error\n }\n }\n\n /**\n * Makes a raw fetch request to the Mistral chat completions endpoint and\n * parses the SSE stream manually, bypassing the SDK's Zod validation which\n * rejects streaming tool call chunks that omit `name` in argument deltas.\n */\n private async *fetchRawMistralStream(\n body: Record<string, unknown>,\n config: MistralClientConfig,\n wrapFetch: FetchWrapper | undefined,\n ): AsyncGenerator<MistralRawChunk> {\n const serverURL = (\n config.baseURL ??\n config.serverURL ??\n 'https://api.mistral.ai'\n )\n .replace(/\\/+$/, '')\n .replace(/\\/v1$/, '')\n const url =\n config.resolveRequestUrl?.(true) ?? `${serverURL}/v1/chat/completions`\n\n const accessToken =\n config.getAccessToken === undefined\n ? config.apiKey\n : await config.getAccessToken()\n\n const headers: Record<string, string> = {\n 'Content-Type': 'application/json',\n Authorization: `Bearer ${accessToken}`,\n ...config.defaultHeaders,\n }\n\n const send = wrapFetch ? wrapFetch(fetch) : fetch\n const response = await send(url, {\n method: 'POST',\n headers,\n body: JSON.stringify(body),\n })\n\n if (!response.ok) {\n const errorText = await response.text()\n throw new Error(`Mistral API error ${response.status}: ${errorText}`)\n }\n\n if (!response.body) {\n throw new Error(\n 'Mistral API returned a response with no body. This may indicate a proxy or runtime that does not support streaming.',\n )\n }\n\n const reader = response.body.getReader()\n const decoder = new TextDecoder()\n let buffer = ''\n\n try {\n for (;;) {\n const { done, value } = await reader.read()\n if (done) break\n\n buffer += decoder.decode(value, { stream: true })\n const lines = buffer.split('\\n')\n // split('\\n') always yields at least one element, so pop() is a\n // string here; `?? ''` only satisfies the type narrowing.\n buffer = lines.pop() ?? ''\n\n for (const line of lines) {\n const trimmed = line.trim()\n if (!trimmed.startsWith('data:')) continue\n const data = trimmed.slice(5).trimStart()\n if (data === '[DONE]') return\n\n let parsed: unknown\n try {\n parsed = JSON.parse(data)\n } catch (e) {\n if (e instanceof SyntaxError) {\n console.warn(\n `[mistral] skipped unparseable SSE chunk: ${data.slice(0, 200)}`,\n )\n continue\n }\n throw e\n }\n\n // Mistral signals mid-stream errors via an `error` field. Surface\n // them as RUN_ERROR rather than swallowing them as empty chunks.\n if (\n parsed &&\n typeof parsed === 'object' &&\n 'error' in parsed &&\n !('choices' in parsed)\n ) {\n const errPayload = parsed.error\n const message =\n typeof errPayload === 'string'\n ? errPayload\n : errPayload &&\n typeof errPayload === 'object' &&\n 'message' in errPayload\n ? String(errPayload.message)\n : JSON.stringify(errPayload)\n throw new Error(`Mistral stream error: ${message}`)\n }\n\n yield parsed as MistralRawChunk\n }\n }\n } finally {\n await reader.cancel().catch(() => {})\n reader.releaseLock()\n }\n }\n\n /**\n * Converts the SDK's camelCase `ChatCompletionStreamRequest` into the\n * snake_case wire body, including converting messages.\n */\n private toWireBody(\n params: ChatCompletionStreamRequest,\n ): Record<string, unknown> {\n const {\n messages,\n maxTokens,\n topP,\n randomSeed,\n responseFormat,\n toolChoice,\n parallelToolCalls,\n frequencyPenalty,\n presencePenalty,\n safePrompt,\n reasoningEffort,\n promptMode,\n stream: _stream,\n ...rest\n } = params\n\n return {\n ...rest,\n messages: messages.map(messageToWire),\n stream: true,\n // Opt in to usage on the final streaming chunk.\n stream_options: { include_usage: true },\n ...(maxTokens != null && { max_tokens: maxTokens }),\n ...(topP != null && { top_p: topP }),\n ...(randomSeed != null && { random_seed: randomSeed }),\n ...(responseFormat != null && { response_format: responseFormat }),\n ...(toolChoice != null && { tool_choice: toolChoice }),\n ...(parallelToolCalls != null && {\n parallel_tool_calls: parallelToolCalls,\n }),\n ...(frequencyPenalty != null && { frequency_penalty: frequencyPenalty }),\n ...(presencePenalty != null && { presence_penalty: presencePenalty }),\n ...(safePrompt != null && { safe_prompt: safePrompt }),\n ...(reasoningEffort != null && { reasoning_effort: reasoningEffort }),\n ...(promptMode != null && { prompt_mode: promptMode }),\n }\n }\n\n /**\n * Splits a Mistral delta content payload into text and reasoning deltas.\n * Mistral reasoning models (magistral-*) stream reasoning content as\n * `{ type: 'thinking', thinking: [{ type: 'text', text }, ...] }` content\n * parts. A single delta may contain text only, thinking only, or — rarely —\n * both (when a step transitions); both fields are returned so the caller\n * can sequence REASONING and TEXT lifecycle events in order.\n */\n private extractDeltaParts(\n content:\n | string\n | Array<{\n type: string\n text?: string\n thinking?: Array<{ type: string; text?: string }>\n }>\n | null\n | undefined,\n ): { text: string; thinking: string } {\n if (!content) return { text: '', thinking: '' }\n if (typeof content === 'string') return { text: content, thinking: '' }\n\n let text = ''\n let thinking = ''\n for (const part of content) {\n if (part.type === 'text' && typeof part.text === 'string') {\n text += part.text\n } else if (part.type === 'thinking' && Array.isArray(part.thinking)) {\n for (const inner of part.thinking) {\n if (inner.type === 'text' && typeof inner.text === 'string') {\n thinking += inner.text\n }\n }\n }\n }\n return { text, thinking }\n }\n\n /**\n * Maps common TextOptions to Mistral Chat Completions request parameters.\n */\n private mapTextOptionsToMistral(\n options: TextOptions<TProviderOptions>,\n ): ChatCompletionStreamRequest {\n const modelOptions = options.modelOptions as\n | Omit<InternalTextProviderOptions, 'tools'>\n | undefined\n\n const tools = options.tools\n ? convertToolsToProviderFormat(options.tools)\n : undefined\n\n // History from another model loses its signatures, and its tool IDs are\n // rewritten to the 9-character IDs Mistral accepts.\n const replay = transformMessagesForReplay(\n options.messages,\n { provider: this.provider, api: this.api, model: options.model },\n (id, { attempt }) => {\n const normalized = id.replace(/[^a-zA-Z0-9]/g, '')\n if (attempt === 0 && normalized.length === 9) return normalized\n const seed = normalized || id\n return hashToolCallId(attempt === 0 ? seed : `${seed}:${attempt}`)\n .replace(/[^a-zA-Z0-9]/g, '')\n .slice(0, 9)\n },\n )\n const messages: ChatCompletionStreamRequest['messages'] = []\n\n if (options.systemPrompts && options.systemPrompts.length > 0) {\n messages.push({\n role: 'system',\n content: options.systemPrompts.join('\\n'),\n })\n }\n\n for (const message of replay.messages) {\n messages.push(this.convertMessageToMistral(message))\n }\n\n // `chat({ toolChoice })` is sent only when the request has tools. It goes\n // before the `modelOptions` spread, so a `tool_choice` there wins.\n const toolChoiceField =\n tools?.length && options.toolChoice !== undefined\n ? { toolChoice: toMistralToolChoice(options.toolChoice) }\n : undefined\n\n return {\n ...toolChoiceField,\n model: this.rawConfig.requestModel ?? options.model,\n messages: messages,\n temperature: modelOptions?.temperature ?? undefined,\n maxTokens: modelOptions?.max_tokens ?? undefined,\n topP: modelOptions?.top_p ?? undefined,\n tools: tools as ChatCompletionStreamRequest['tools'],\n stream: true,\n ...mistralReasoning(\n options.model,\n options.reasoning,\n MISTRAL_MODEL_REASONING[options.model],\n ),\n ...(modelOptions && {\n ...(modelOptions.stop != null && { stop: modelOptions.stop }),\n ...(modelOptions.random_seed != null && {\n randomSeed: modelOptions.random_seed,\n }),\n ...(modelOptions.response_format != null && {\n responseFormat: modelOptions.response_format,\n }),\n ...(modelOptions.tool_choice != null && {\n toolChoice: modelOptions.tool_choice,\n }),\n ...(modelOptions.parallel_tool_calls != null && {\n parallelToolCalls: modelOptions.parallel_tool_calls,\n }),\n ...(modelOptions.frequency_penalty != null && {\n frequencyPenalty: modelOptions.frequency_penalty,\n }),\n ...(modelOptions.presence_penalty != null && {\n presencePenalty: modelOptions.presence_penalty,\n }),\n ...(modelOptions.n != null && { n: modelOptions.n }),\n ...(modelOptions.prediction != null && {\n prediction: modelOptions.prediction,\n }),\n ...(modelOptions.safe_prompt != null && {\n safePrompt: modelOptions.safe_prompt,\n }),\n }),\n }\n }\n\n /**\n * Converts a TanStack AI ModelMessage to a Mistral ChatCompletionMessageParam.\n */\n private convertMessageToMistral(\n message: ModelMessage,\n ): ChatCompletionStreamRequest['messages'][number] {\n if (message.role === 'tool') {\n if (!message.toolCallId) {\n throw new Error('Missing toolCallId for tool message')\n }\n return {\n role: 'tool',\n toolCallId: message.toolCallId,\n // Mistral accepts image chunks in a tool message, so send the parts.\n content: Array.isArray(message.content)\n ? message.content.map((part) =>\n this.convertContentPartToMistral(part),\n )\n : typeof message.content === 'string'\n ? message.content\n : JSON.stringify(message.content),\n }\n }\n\n if (message.role === 'assistant') {\n const toolCalls = message.toolCalls?.map((tc) => ({\n id: tc.id,\n type: 'function' as const,\n function: {\n name: tc.function.name,\n arguments:\n typeof tc.function.arguments === 'string'\n ? tc.function.arguments\n : JSON.stringify(tc.function.arguments),\n },\n }))\n\n return {\n role: 'assistant',\n content: this.assistantContent(message),\n ...(toolCalls && toolCalls.length > 0 ? { toolCalls } : {}),\n }\n }\n\n const contentParts = this.normalizeContent(message.content)\n\n if (contentParts.length === 1 && contentParts[0]?.type === 'text') {\n return {\n role: 'user',\n content: contentParts[0].content,\n }\n }\n\n const parts = contentParts.map((part) =>\n this.convertContentPartToMistral(part),\n )\n\n return {\n role: 'user',\n content: parts.length > 0 ? parts : '',\n }\n }\n\n /** Readable thinking and text, in the stored block order. */\n private assistantContent(message: ModelMessage): AssistantMessage['content'] {\n if (!message.thinking?.length)\n return this.extractTextContent(message.content)\n const blocks = orderedAssistantBlocks(message) ?? [\n ...message.thinking.map((thinking) => ({\n type: 'thinking' as const,\n thinking,\n })),\n { type: 'text' as const, text: this.extractTextContent(message.content) },\n ]\n const content: Array<ContentChunk> = []\n for (const block of blocks) {\n if (block.type === 'text')\n content.push({ type: 'text', text: block.text })\n else if (\n block.type === 'thinking' &&\n !block.thinking.redacted &&\n block.thinking.content.trim()\n ) {\n content.push({\n type: 'thinking',\n thinking: [{ type: 'text', text: block.thinking.content }],\n })\n }\n }\n return content\n }\n\n /**\n * Converts a ContentPart to a Mistral content part. Returns undefined for\n * unsupported part types.\n */\n private convertContentPartToMistral(\n part: ContentPart,\n ): ChatCompletionContentPart {\n if (part.type === 'text') {\n return { type: 'text', text: part.content }\n }\n\n if (part.type === 'image') {\n if (isFileSource(part.source)) {\n throw unsupportedFileSourceError('mistral')\n }\n const imageMetadata = part.metadata as MistralImageMetadata | undefined\n const imageValue = part.source.value\n const imageUrl =\n part.source.type === 'data' && !imageValue.startsWith('data:')\n ? `data:${part.source.mimeType};base64,${imageValue}`\n : imageValue\n return {\n type: 'image_url',\n imageUrl: imageMetadata?.detail\n ? { url: imageUrl, detail: imageMetadata.detail }\n : imageUrl,\n }\n }\n\n if (part.type === 'document') {\n if (isFileSource(part.source)) {\n throw unsupportedFileSourceError('mistral')\n }\n const documentValue = part.source.value\n const documentUrl =\n part.source.type === 'data' && !documentValue.startsWith('data:')\n ? `data:${part.source.mimeType};base64,${documentValue}`\n : documentValue\n return { type: 'document_url', documentUrl }\n }\n\n throw new Error(\n `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.`,\n )\n }\n\n /**\n * Normalizes message content to an array of ContentPart.\n */\n private normalizeContent(\n content: string | null | undefined | Array<ContentPart>,\n ): Array<ContentPart> {\n if (content === null || content === undefined) return []\n if (typeof content === 'string') return [{ type: 'text', content }]\n return content\n }\n\n /**\n * Extracts text content from a content value that may be string, null, or ContentPart array.\n */\n private extractTextContent(\n content: string | null | undefined | Array<ContentPart>,\n ): string {\n if (content === null || content === undefined) return ''\n if (typeof content === 'string') return content\n return content\n .filter((p) => p.type === 'text')\n .map((p) => p.content)\n .join('')\n }\n}\n\n/**\n * Snake-cases a Mistral SDK message into the wire format expected by the API.\n */\nfunction messageToWire(msg: ChatCompletionStreamRequest['messages'][number]) {\n if (msg.role === 'tool') {\n return {\n role: 'tool',\n tool_call_id: msg.toolCallId,\n content: Array.isArray(msg.content)\n ? msg.content.map(contentPartToWire)\n : msg.content,\n ...(msg.name !== undefined ? { name: msg.name } : {}),\n }\n }\n if (msg.role === 'assistant') {\n const base: Record<string, unknown> = {\n role: 'assistant',\n content: msg.content ?? null,\n }\n if (msg.toolCalls && msg.toolCalls.length > 0) {\n base.tool_calls = msg.toolCalls.map((tc) => ({\n id: tc.id,\n type: tc.type ?? 'function',\n function: tc.function,\n }))\n }\n if (msg.prefix !== undefined) base.prefix = msg.prefix\n return base\n }\n if (msg.role === 'user' && Array.isArray(msg.content)) {\n return {\n role: 'user',\n content: msg.content.map(contentPartToWire),\n }\n }\n return msg\n}\n\n/**\n * Snake-cases one content chunk of a user or tool message.\n */\nfunction contentPartToWire(part: ContentChunk) {\n if (part.type === 'image_url') {\n return { type: 'image_url', image_url: part.imageUrl }\n }\n if (part.type === 'document_url') {\n return { type: 'document_url', document_url: part.documentUrl }\n }\n return part\n}\n\n/**\n * Creates a Mistral text adapter with explicit API key.\n *\n * @param model - The model name (e.g., 'mistral-large-latest')\n * @param apiKey - Your Mistral API key\n * @param config - Optional additional configuration\n * @returns Configured Mistral text adapter instance\n *\n * @example\n * ```typescript\n * const adapter = createMistralText('mistral-large-latest', 'api_key');\n * ```\n */\nexport function createMistralText<\n TModel extends (typeof MISTRAL_CHAT_MODELS)[number],\n>(\n model: TModel,\n apiKey: string,\n config?: Omit<MistralTextConfig, 'apiKey'>,\n): MistralTextAdapter<TModel> {\n return new MistralTextAdapter({ apiKey, ...config }, model)\n}\n\n/**\n * Creates a Mistral text adapter using the `MISTRAL_API_KEY` environment variable.\n *\n * @param model - The model name (e.g., 'mistral-large-latest')\n * @param config - Optional configuration (excluding apiKey)\n * @returns Configured Mistral text adapter instance\n * @throws Error if MISTRAL_API_KEY is not found in environment\n *\n * @example\n * ```typescript\n * const adapter = mistralText('mistral-large-latest');\n * ```\n */\nexport function mistralText<\n TModel extends (typeof MISTRAL_CHAT_MODELS)[number],\n>(\n model: TModel,\n config?: Omit<MistralTextConfig, 'apiKey'>,\n): MistralTextAdapter<TModel> {\n const apiKey = getMistralApiKeyFromEnv()\n return createMistralText(model, apiKey, config)\n}\n"],"mappings":";;;;;;;;;;;;AAiEA,IAAM,WAAW,UAEf;;;;;;AAOF,SAAS,mBACP,UAKA,oBACS;CACT,IAAI,CAAC,SAAS,WAAW,OAAO,CAAC;CACjC,IAAI;EACF,OAAO,mBAAmB,SAAS,MAAM,KAAK,MAAM,SAAS,SAAS,CAAC;CACzE,SAAS,OAAO;EACd,MAAM,UAAU,SAAS,UAAU,MAAM,GAAG,GAAG;EAC/C,MAAM,WAAW,SAAS,UAAU,SAAS,MAAM,QAAQ;EAC3D,MAAM,IAAI,MACR,iDAAiD,SAAS,KAAK,SAAS,SAAS,GAAG,gBAAgB,UAAU,YAC9G,EAAE,MAAM,CACV;CACF;AACF;;;;;;;AAiCA,SAAS,iBACP,OACA,SACA,WACqE;CACrE,MAAM,WAAW,iBAAiB,SAAS,SAAS;CACpD,IAAI,CAAC,UAAU,OAAO,CAAC;CACvB,IAAI,MAAM,WAAW,WAAW,GAC9B,OAAO,SAAS,UAAU,QAAQ,CAAC,IAAI,EAAE,YAAY,YAAY;CAGnE,OAAO,EAAE,iBAAiB,SAAS,MAAyB;AAC9D;;AAGA,SAAS,oBACP,QACwD;CACxD,IAAI,OAAO,WAAW,UAAU,OAAO;CACvC,OAAO;EAAE,MAAM;EAAY,UAAU,EAAE,MAAM,OAAO,KAAK;CAAE;AAC7D;;;;;;;AAQA,SAAS,sBAAsB,aAA8C;CAC3E,IAAI,CAAC,aAAa,OAAO,YAAY,cAAc,QAAQ,OAAO,KAAA;CAClE,OAAO,YAAY;AACrB;AAEA,SAAS,cAAc,QAA6B,UAAkB;CACpE,IAAI,aAAa,iBAAiB,OAAO;CACzC,MAAM,YAC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,IAAI,OAAO,GAClD,OAAO;EACL,MAAM;EACN,SAAS,IAAI,QAAQ,IAAI,iBAAiB;CAC5C;CAEF,OAAO;AACT;;;;AAKA,SAAS,kBAAkB,MAAoB;CAC7C,IAAI,KAAK,SAAS,aAChB,OAAO;EAAE,MAAM;EAAa,WAAW,KAAK;CAAS;CAEvD,IAAI,KAAK,SAAS,gBAChB,OAAO;EAAE,MAAM;EAAgB,cAAc,KAAK;CAAY;CAEhE,OAAO;AACT;;;;;;;;;;;;;;AAeA,SAAgB,kBAGd,OACA,QACA,QAC4B;CAC5B,OAAO,IAAI,mBAAmB;EAAE;EAAQ,GAAG;CAAO,GAAG,KAAK;AAC5D;;;;;;;;;;;;;;AAeA,SAAgB,YAGd,OACA,QAC4B;CAE5B,OAAO,kBAAkB,OADV,wBACiB,GAAQ,MAAM;AAChD"}
@@ -2,7 +2,7 @@ import { Modality, ModelReasoning } from '@tanstack/ai';
2
2
  import { ModelReasoningCapability } from '@tanstack/ai/adapter-internals';
3
3
  import { MistralTextProviderOptions } from './text/text-provider-options.js';
4
4
  import { CodestralEmbedProviderOptions, MistralEmbedProviderOptions } from './embedding/embedding-provider-options.js';
5
- /** Provider options for vision-capable Mistral models (pixtral-*). */
5
+ /** Provider options for vision-capable Mistral models. */
6
6
  export type MistralVisionProviderOptions = MistralTextProviderOptions;
7
7
  /** Provider options for reasoning-capable Mistral models (magistral-*). */
8
8
  export type MistralReasoningProviderOptions = MistralTextProviderOptions;
@@ -134,44 +134,6 @@ declare const CODESTRAL_LATEST: {
134
134
  readonly features: ["streaming", "tools", "json_object", "json_schema", "code"];
135
135
  };
136
136
  };
137
- declare const PIXTRAL_LARGE_LATEST: {
138
- readonly name: "pixtral-large-latest";
139
- readonly context_window: 131072;
140
- readonly max_completion_tokens: 8192;
141
- readonly pricing: {
142
- readonly input: {
143
- readonly normal: 2;
144
- };
145
- readonly output: {
146
- readonly normal: 6;
147
- };
148
- };
149
- readonly supports: {
150
- readonly input: ["text", "image", "document"];
151
- readonly output: ["text"];
152
- readonly endpoints: ["chat"];
153
- readonly features: ["streaming", "tools", "json_object", "json_schema", "vision"];
154
- };
155
- };
156
- declare const PIXTRAL_12B_2409: {
157
- readonly name: "pixtral-12b-2409";
158
- readonly context_window: 131072;
159
- readonly max_completion_tokens: 8192;
160
- readonly pricing: {
161
- readonly input: {
162
- readonly normal: 0.15;
163
- };
164
- readonly output: {
165
- readonly normal: 0.15;
166
- };
167
- };
168
- readonly supports: {
169
- readonly input: ["text", "image", "document"];
170
- readonly output: ["text"];
171
- readonly endpoints: ["chat"];
172
- readonly features: ["streaming", "tools", "json_object", "vision"];
173
- };
174
- };
175
137
  declare const MAGISTRAL_MEDIUM_LATEST: {
176
138
  readonly name: "magistral-medium-latest";
177
139
  readonly context_window: 40000;
@@ -224,25 +186,6 @@ declare const MAGISTRAL_SMALL_LATEST: {
224
186
  readonly budget: false;
225
187
  };
226
188
  };
227
- declare const OPEN_MISTRAL_NEMO: {
228
- readonly name: "open-mistral-nemo";
229
- readonly context_window: 131072;
230
- readonly max_completion_tokens: 8192;
231
- readonly pricing: {
232
- readonly input: {
233
- readonly normal: 0.15;
234
- };
235
- readonly output: {
236
- readonly normal: 0.15;
237
- };
238
- };
239
- readonly supports: {
240
- readonly input: ["text"];
241
- readonly output: ["text"];
242
- readonly endpoints: ["chat"];
243
- readonly features: ["streaming", "tools", "json_object"];
244
- };
245
- };
246
189
  declare const MISTRAL_MEDIUM_3: {
247
190
  readonly name: "mistral-medium-3";
248
191
  readonly context_window: 131072;
@@ -303,7 +246,7 @@ declare const CODESTRAL_2: {
303
246
  /**
304
247
  * All supported Mistral chat model identifiers.
305
248
  */
306
- export declare const MISTRAL_CHAT_MODELS: readonly ["mistral-large-latest", "mistral-medium-latest", "mistral-small-latest", "ministral-8b-latest", "ministral-3b-latest", "codestral-latest", "pixtral-large-latest", "pixtral-12b-2409", "magistral-medium-latest", "magistral-small-latest", "open-mistral-nemo"];
249
+ export declare const MISTRAL_CHAT_MODELS: readonly ["mistral-large-latest", "mistral-medium-latest", "mistral-small-latest", "ministral-8b-latest", "ministral-3b-latest", "codestral-latest", "magistral-medium-latest", "magistral-small-latest"];
307
250
  /**
308
251
  * Union type of all supported Mistral chat model names.
309
252
  */
@@ -326,11 +269,8 @@ export type MistralModelInputModalitiesByName = {
326
269
  [MINISTRAL_8B_LATEST.name]: typeof MINISTRAL_8B_LATEST.supports.input;
327
270
  [MINISTRAL_3B_LATEST.name]: typeof MINISTRAL_3B_LATEST.supports.input;
328
271
  [CODESTRAL_LATEST.name]: typeof CODESTRAL_LATEST.supports.input;
329
- [PIXTRAL_LARGE_LATEST.name]: typeof PIXTRAL_LARGE_LATEST.supports.input;
330
- [PIXTRAL_12B_2409.name]: typeof PIXTRAL_12B_2409.supports.input;
331
272
  [MAGISTRAL_MEDIUM_LATEST.name]: typeof MAGISTRAL_MEDIUM_LATEST.supports.input;
332
273
  [MAGISTRAL_SMALL_LATEST.name]: typeof MAGISTRAL_SMALL_LATEST.supports.input;
333
- [OPEN_MISTRAL_NEMO.name]: typeof OPEN_MISTRAL_NEMO.supports.input;
334
274
  [MISTRAL_MEDIUM_3.name]: typeof MISTRAL_MEDIUM_3.supports.input;
335
275
  [MISTRAL_SMALL_2503.name]: typeof MISTRAL_SMALL_2503.supports.input;
336
276
  [CODESTRAL_2.name]: typeof CODESTRAL_2.supports.input;
@@ -351,11 +291,8 @@ export type MistralChatModelProviderOptionsByName = {
351
291
  [MINISTRAL_8B_LATEST.name]: MistralTextProviderOptions;
352
292
  [MINISTRAL_3B_LATEST.name]: MistralTextProviderOptions;
353
293
  [CODESTRAL_LATEST.name]: MistralTextProviderOptions;
354
- [PIXTRAL_LARGE_LATEST.name]: MistralVisionProviderOptions;
355
- [PIXTRAL_12B_2409.name]: MistralVisionProviderOptions;
356
294
  [MAGISTRAL_MEDIUM_LATEST.name]: MistralReasoningProviderOptions;
357
295
  [MAGISTRAL_SMALL_LATEST.name]: MistralReasoningProviderOptions;
358
- [OPEN_MISTRAL_NEMO.name]: MistralTextProviderOptions;
359
296
  [MISTRAL_MEDIUM_3.name]: MistralVisionProviderOptions;
360
297
  [MISTRAL_SMALL_2503.name]: MistralVisionProviderOptions;
361
298
  [CODESTRAL_2.name]: MistralTextProviderOptions;
@@ -146,55 +146,6 @@ var CODESTRAL_LATEST = {
146
146
  ]
147
147
  }
148
148
  };
149
- var PIXTRAL_LARGE_LATEST = {
150
- name: "pixtral-large-latest",
151
- context_window: 131072,
152
- max_completion_tokens: 8192,
153
- pricing: {
154
- input: { normal: 2 },
155
- output: { normal: 6 }
156
- },
157
- supports: {
158
- input: [
159
- "text",
160
- "image",
161
- "document"
162
- ],
163
- output: ["text"],
164
- endpoints: ["chat"],
165
- features: [
166
- "streaming",
167
- "tools",
168
- "json_object",
169
- "json_schema",
170
- "vision"
171
- ]
172
- }
173
- };
174
- var PIXTRAL_12B_2409 = {
175
- name: "pixtral-12b-2409",
176
- context_window: 131072,
177
- max_completion_tokens: 8192,
178
- pricing: {
179
- input: { normal: .15 },
180
- output: { normal: .15 }
181
- },
182
- supports: {
183
- input: [
184
- "text",
185
- "image",
186
- "document"
187
- ],
188
- output: ["text"],
189
- endpoints: ["chat"],
190
- features: [
191
- "streaming",
192
- "tools",
193
- "json_object",
194
- "vision"
195
- ]
196
- }
197
- };
198
149
  var MAGISTRAL_MEDIUM_LATEST = {
199
150
  name: "magistral-medium-latest",
200
151
  context_window: 4e4,
@@ -239,25 +190,6 @@ var MAGISTRAL_SMALL_LATEST = {
239
190
  },
240
191
  reasoning: EFFORT_OFF_HIGH
241
192
  };
242
- var OPEN_MISTRAL_NEMO = {
243
- name: "open-mistral-nemo",
244
- context_window: 131072,
245
- max_completion_tokens: 8192,
246
- pricing: {
247
- input: { normal: .15 },
248
- output: { normal: .15 }
249
- },
250
- supports: {
251
- input: ["text"],
252
- output: ["text"],
253
- endpoints: ["chat"],
254
- features: [
255
- "streaming",
256
- "tools",
257
- "json_object"
258
- ]
259
- }
260
- };
261
193
  var MISTRAL_MEDIUM_3 = {
262
194
  name: "mistral-medium-3",
263
195
  context_window: 131072,
@@ -339,11 +271,8 @@ var MISTRAL_CHAT_MODELS = [
339
271
  MINISTRAL_8B_LATEST.name,
340
272
  MINISTRAL_3B_LATEST.name,
341
273
  CODESTRAL_LATEST.name,
342
- PIXTRAL_LARGE_LATEST.name,
343
- PIXTRAL_12B_2409.name,
344
274
  MAGISTRAL_MEDIUM_LATEST.name,
345
- MAGISTRAL_SMALL_LATEST.name,
346
- OPEN_MISTRAL_NEMO.name
275
+ MAGISTRAL_SMALL_LATEST.name
347
276
  ];
348
277
  /**
349
278
  * Mistral chat models on Vertex AI / Gemini Enterprise Agent Platform.
@@ -367,11 +296,8 @@ var MISTRAL_MODEL_INPUT_MODALITIES = {
367
296
  [MINISTRAL_8B_LATEST.name]: MINISTRAL_8B_LATEST.supports.input,
368
297
  [MINISTRAL_3B_LATEST.name]: MINISTRAL_3B_LATEST.supports.input,
369
298
  [CODESTRAL_LATEST.name]: CODESTRAL_LATEST.supports.input,
370
- [PIXTRAL_LARGE_LATEST.name]: PIXTRAL_LARGE_LATEST.supports.input,
371
- [PIXTRAL_12B_2409.name]: PIXTRAL_12B_2409.supports.input,
372
299
  [MAGISTRAL_MEDIUM_LATEST.name]: MAGISTRAL_MEDIUM_LATEST.supports.input,
373
300
  [MAGISTRAL_SMALL_LATEST.name]: MAGISTRAL_SMALL_LATEST.supports.input,
374
- [OPEN_MISTRAL_NEMO.name]: OPEN_MISTRAL_NEMO.supports.input,
375
301
  [MISTRAL_MEDIUM_3.name]: MISTRAL_MEDIUM_3.supports.input,
376
302
  [MISTRAL_SMALL_2503.name]: MISTRAL_SMALL_2503.supports.input,
377
303
  [CODESTRAL_2.name]: CODESTRAL_2.supports.input
@@ -1 +1 @@
1
- {"version":3,"file":"model-meta.js","names":[],"sources":["../../src/model-meta.ts"],"sourcesContent":["import type { Modality, ModelReasoning } from '@tanstack/ai'\nimport type { ModelReasoningCapability } from '@tanstack/ai/adapter-internals'\nimport type { MistralTextProviderOptions } from './text/text-provider-options'\nimport type {\n CodestralEmbedProviderOptions,\n MistralEmbedProviderOptions,\n} from './embedding/embedding-provider-options'\n\n// Reasoning shapes: the levels a model has for `chat({ reasoning })`, and\n// the provider value to send for each. Each model points at one of them.\nconst EFFORT_NONE_HIGH = {\n levels: { off: 'none', high: 'high' },\n budget: false,\n} as const\nconst EFFORT_OFF_HIGH = {\n levels: { off: 'off', high: 'high' },\n budget: false,\n} as const\n\n/** Provider options for vision-capable Mistral models (pixtral-*). */\nexport type MistralVisionProviderOptions = MistralTextProviderOptions\n\n/** Provider options for reasoning-capable Mistral models (magistral-*). */\nexport type MistralReasoningProviderOptions = MistralTextProviderOptions\n\n/**\n * Internal metadata structure describing a Mistral model's capabilities\n * and approximate pricing (USD per million tokens).\n */\ninterface ModelMeta<TProviderOptions = unknown> {\n name: string\n context_window?: number\n max_completion_tokens?: number\n pricing: {\n input?: { normal: number; cached?: number }\n output?: { normal: number }\n }\n supports: {\n input: Array<'text' | 'image' | 'audio' | 'document'>\n output: Array<'text'>\n endpoints: Array<'chat' | 'embeddings'>\n\n features: Array<\n | 'streaming'\n | 'tools'\n | 'json_object'\n | 'json_schema'\n | 'reasoning'\n | 'vision'\n | 'code'\n >\n }\n providerOptions?: TProviderOptions\n /** The model's data for `chat({ reasoning })`. None: it does not reason. */\n reasoning?: ModelReasoning\n}\n\nconst MISTRAL_LARGE_LATEST = {\n name: 'mistral-large-latest',\n context_window: 131_072,\n max_completion_tokens: 8_192,\n pricing: {\n input: { normal: 0.5 },\n output: { normal: 1.5 },\n },\n supports: {\n input: ['text'],\n output: ['text'],\n endpoints: ['chat'],\n features: ['streaming', 'tools', 'json_object', 'json_schema'],\n },\n} as const satisfies ModelMeta<MistralTextProviderOptions>\n\nconst MISTRAL_MEDIUM_LATEST = {\n name: 'mistral-medium-latest',\n context_window: 131_072,\n max_completion_tokens: 8_192,\n pricing: {\n input: { normal: 0.4 },\n output: { normal: 2 },\n },\n supports: {\n input: ['text', 'image', 'document'],\n output: ['text'],\n endpoints: ['chat'],\n features: ['streaming', 'tools', 'json_object', 'json_schema', 'vision'],\n },\n reasoning: EFFORT_NONE_HIGH,\n} as const satisfies ModelMeta<MistralTextProviderOptions>\n\nconst MISTRAL_SMALL_LATEST = {\n name: 'mistral-small-latest',\n context_window: 131_072,\n max_completion_tokens: 8_192,\n pricing: {\n input: { normal: 0.1 },\n output: { normal: 0.3 },\n },\n supports: {\n input: ['text', 'image', 'document'],\n output: ['text'],\n endpoints: ['chat'],\n features: ['streaming', 'tools', 'json_object', 'json_schema', 'vision'],\n },\n reasoning: EFFORT_NONE_HIGH,\n} as const satisfies ModelMeta<MistralTextProviderOptions>\n\nconst MINISTRAL_8B_LATEST = {\n name: 'ministral-8b-latest',\n context_window: 131_072,\n max_completion_tokens: 8_192,\n pricing: {\n input: { normal: 0.1 },\n output: { normal: 0.1 },\n },\n supports: {\n input: ['text'],\n output: ['text'],\n endpoints: ['chat'],\n features: ['streaming', 'tools', 'json_object', 'json_schema'],\n },\n} as const satisfies ModelMeta<MistralTextProviderOptions>\n\nconst MINISTRAL_3B_LATEST = {\n name: 'ministral-3b-latest',\n context_window: 131_072,\n max_completion_tokens: 8_192,\n pricing: {\n input: { normal: 0.04 },\n output: { normal: 0.04 },\n },\n supports: {\n input: ['text'],\n output: ['text'],\n endpoints: ['chat'],\n features: ['streaming', 'tools', 'json_object', 'json_schema'],\n },\n} as const satisfies ModelMeta<MistralTextProviderOptions>\n\nconst CODESTRAL_LATEST = {\n name: 'codestral-latest',\n context_window: 256_000,\n max_completion_tokens: 8_192,\n pricing: {\n input: { normal: 0.3 },\n output: { normal: 0.9 },\n },\n supports: {\n input: ['text'],\n output: ['text'],\n endpoints: ['chat'],\n features: ['streaming', 'tools', 'json_object', 'json_schema', 'code'],\n },\n} as const satisfies ModelMeta<MistralTextProviderOptions>\n\nconst PIXTRAL_LARGE_LATEST = {\n name: 'pixtral-large-latest',\n context_window: 131_072,\n max_completion_tokens: 8_192,\n pricing: {\n input: { normal: 2 },\n output: { normal: 6 },\n },\n supports: {\n input: ['text', 'image', 'document'],\n output: ['text'],\n endpoints: ['chat'],\n features: ['streaming', 'tools', 'json_object', 'json_schema', 'vision'],\n },\n} as const satisfies ModelMeta<MistralTextProviderOptions>\n\nconst PIXTRAL_12B_2409 = {\n name: 'pixtral-12b-2409',\n context_window: 131_072,\n max_completion_tokens: 8_192,\n pricing: {\n input: { normal: 0.15 },\n output: { normal: 0.15 },\n },\n supports: {\n input: ['text', 'image', 'document'],\n output: ['text'],\n endpoints: ['chat'],\n features: ['streaming', 'tools', 'json_object', 'vision'],\n },\n} as const satisfies ModelMeta<MistralTextProviderOptions>\n\nconst MAGISTRAL_MEDIUM_LATEST = {\n name: 'magistral-medium-latest',\n context_window: 40_000,\n max_completion_tokens: 40_000,\n pricing: {\n input: { normal: 2 },\n output: { normal: 5 },\n },\n supports: {\n input: ['text'],\n output: ['text'],\n endpoints: ['chat'],\n features: ['streaming', 'tools', 'reasoning', 'json_object', 'json_schema'],\n },\n reasoning: EFFORT_OFF_HIGH,\n} as const satisfies ModelMeta<MistralTextProviderOptions>\n\nconst MAGISTRAL_SMALL_LATEST = {\n name: 'magistral-small-latest',\n context_window: 40_000,\n max_completion_tokens: 40_000,\n pricing: {\n input: { normal: 0.5 },\n output: { normal: 1.5 },\n },\n supports: {\n input: ['text'],\n output: ['text'],\n endpoints: ['chat'],\n features: ['streaming', 'tools', 'reasoning', 'json_object', 'json_schema'],\n },\n // Not in models.dev. The same as Magistral Medium: prompt_mode only.\n reasoning: EFFORT_OFF_HIGH,\n} as const satisfies ModelMeta<MistralTextProviderOptions>\n\nconst OPEN_MISTRAL_NEMO = {\n name: 'open-mistral-nemo',\n context_window: 131_072,\n max_completion_tokens: 8_192,\n pricing: {\n input: { normal: 0.15 },\n output: { normal: 0.15 },\n },\n supports: {\n input: ['text'],\n output: ['text'],\n endpoints: ['chat'],\n features: ['streaming', 'tools', 'json_object'],\n },\n} as const satisfies ModelMeta<MistralTextProviderOptions>\n\n// Vertex Model Garden IDs. These are not the Mistral API catalog.\n// Source: https://docs.cloud.google.com/gemini-enterprise-agent-platform/models/partner-models/mistral\nconst MISTRAL_MEDIUM_3 = {\n name: 'mistral-medium-3',\n context_window: 131_072,\n max_completion_tokens: 8_192,\n pricing: {\n input: { normal: 0.4 },\n output: { normal: 2 },\n },\n supports: {\n input: ['text', 'image', 'document'],\n output: ['text'],\n endpoints: ['chat'],\n features: ['streaming', 'tools', 'json_object', 'json_schema', 'vision'],\n },\n} as const satisfies ModelMeta<MistralTextProviderOptions>\n\nconst MISTRAL_SMALL_2503 = {\n name: 'mistral-small-2503',\n context_window: 131_072,\n max_completion_tokens: 8_192,\n pricing: {\n input: { normal: 0.1 },\n output: { normal: 0.3 },\n },\n supports: {\n input: ['text', 'image', 'document'],\n output: ['text'],\n endpoints: ['chat'],\n features: ['streaming', 'tools', 'json_object', 'json_schema', 'vision'],\n },\n} as const satisfies ModelMeta<MistralTextProviderOptions>\n\nconst CODESTRAL_2 = {\n name: 'codestral-2',\n context_window: 131_072,\n max_completion_tokens: 8_192,\n pricing: {\n input: { normal: 0.3 },\n output: { normal: 0.9 },\n },\n supports: {\n input: ['text'],\n output: ['text'],\n endpoints: ['chat'],\n features: ['streaming', 'tools', 'json_object', 'json_schema', 'code'],\n },\n} as const satisfies ModelMeta<MistralTextProviderOptions>\n\n/**\n * All supported Mistral chat model identifiers.\n */\nexport const MISTRAL_CHAT_MODELS = [\n MISTRAL_LARGE_LATEST.name,\n MISTRAL_MEDIUM_LATEST.name,\n MISTRAL_SMALL_LATEST.name,\n MINISTRAL_8B_LATEST.name,\n MINISTRAL_3B_LATEST.name,\n CODESTRAL_LATEST.name,\n PIXTRAL_LARGE_LATEST.name,\n PIXTRAL_12B_2409.name,\n MAGISTRAL_MEDIUM_LATEST.name,\n MAGISTRAL_SMALL_LATEST.name,\n OPEN_MISTRAL_NEMO.name,\n] as const\n\n/**\n * Union type of all supported Mistral chat model names.\n */\nexport type MistralChatModels = (typeof MISTRAL_CHAT_MODELS)[number]\n\n/**\n * Mistral chat models on Vertex AI / Gemini Enterprise Agent Platform.\n * This list is the Google partner catalog, not the Mistral API catalog.\n * OCR (`mistral-ocr-2505`) is not a chat model.\n */\nexport const MISTRAL_VERTEX_CHAT_MODELS = [\n MISTRAL_MEDIUM_3.name,\n MISTRAL_SMALL_2503.name,\n CODESTRAL_2.name,\n] as const\n\nexport type MistralVertexChatModel = (typeof MISTRAL_VERTEX_CHAT_MODELS)[number]\nexport type MistralTextAdapterModel = MistralChatModels | MistralVertexChatModel\n\n/**\n * Type-only map from Mistral chat model name to its supported input modalities.\n */\nexport type MistralModelInputModalitiesByName = {\n [MISTRAL_LARGE_LATEST.name]: typeof MISTRAL_LARGE_LATEST.supports.input\n [MISTRAL_MEDIUM_LATEST.name]: typeof MISTRAL_MEDIUM_LATEST.supports.input\n [MISTRAL_SMALL_LATEST.name]: typeof MISTRAL_SMALL_LATEST.supports.input\n [MINISTRAL_8B_LATEST.name]: typeof MINISTRAL_8B_LATEST.supports.input\n [MINISTRAL_3B_LATEST.name]: typeof MINISTRAL_3B_LATEST.supports.input\n [CODESTRAL_LATEST.name]: typeof CODESTRAL_LATEST.supports.input\n [PIXTRAL_LARGE_LATEST.name]: typeof PIXTRAL_LARGE_LATEST.supports.input\n [PIXTRAL_12B_2409.name]: typeof PIXTRAL_12B_2409.supports.input\n [MAGISTRAL_MEDIUM_LATEST.name]: typeof MAGISTRAL_MEDIUM_LATEST.supports.input\n [MAGISTRAL_SMALL_LATEST.name]: typeof MAGISTRAL_SMALL_LATEST.supports.input\n [OPEN_MISTRAL_NEMO.name]: typeof OPEN_MISTRAL_NEMO.supports.input\n [MISTRAL_MEDIUM_3.name]: typeof MISTRAL_MEDIUM_3.supports.input\n [MISTRAL_SMALL_2503.name]: typeof MISTRAL_SMALL_2503.supports.input\n [CODESTRAL_2.name]: typeof CODESTRAL_2.supports.input\n}\n\n/**\n * Runtime map from chat model name to its supported input modalities, for the\n * text adapter's `inputModalities`. `satisfies` keeps it equal to\n * {@link MistralModelInputModalitiesByName}. An unknown name gives `undefined`.\n */\nexport const MISTRAL_MODEL_INPUT_MODALITIES: Readonly<\n Record<string, ReadonlyArray<Modality>>\n> = {\n [MISTRAL_LARGE_LATEST.name]: MISTRAL_LARGE_LATEST.supports.input,\n [MISTRAL_MEDIUM_LATEST.name]: MISTRAL_MEDIUM_LATEST.supports.input,\n [MISTRAL_SMALL_LATEST.name]: MISTRAL_SMALL_LATEST.supports.input,\n [MINISTRAL_8B_LATEST.name]: MINISTRAL_8B_LATEST.supports.input,\n [MINISTRAL_3B_LATEST.name]: MINISTRAL_3B_LATEST.supports.input,\n [CODESTRAL_LATEST.name]: CODESTRAL_LATEST.supports.input,\n [PIXTRAL_LARGE_LATEST.name]: PIXTRAL_LARGE_LATEST.supports.input,\n [PIXTRAL_12B_2409.name]: PIXTRAL_12B_2409.supports.input,\n [MAGISTRAL_MEDIUM_LATEST.name]: MAGISTRAL_MEDIUM_LATEST.supports.input,\n [MAGISTRAL_SMALL_LATEST.name]: MAGISTRAL_SMALL_LATEST.supports.input,\n [OPEN_MISTRAL_NEMO.name]: OPEN_MISTRAL_NEMO.supports.input,\n [MISTRAL_MEDIUM_3.name]: MISTRAL_MEDIUM_3.supports.input,\n [MISTRAL_SMALL_2503.name]: MISTRAL_SMALL_2503.supports.input,\n [CODESTRAL_2.name]: CODESTRAL_2.supports.input,\n} satisfies MistralModelInputModalitiesByName\n\n/**\n * Type-only map from Mistral chat model name to its provider options type.\n */\nexport type MistralChatModelProviderOptionsByName = {\n [MISTRAL_LARGE_LATEST.name]: MistralTextProviderOptions\n [MISTRAL_MEDIUM_LATEST.name]: MistralVisionProviderOptions\n [MISTRAL_SMALL_LATEST.name]: MistralVisionProviderOptions\n [MINISTRAL_8B_LATEST.name]: MistralTextProviderOptions\n [MINISTRAL_3B_LATEST.name]: MistralTextProviderOptions\n [CODESTRAL_LATEST.name]: MistralTextProviderOptions\n [PIXTRAL_LARGE_LATEST.name]: MistralVisionProviderOptions\n [PIXTRAL_12B_2409.name]: MistralVisionProviderOptions\n [MAGISTRAL_MEDIUM_LATEST.name]: MistralReasoningProviderOptions\n [MAGISTRAL_SMALL_LATEST.name]: MistralReasoningProviderOptions\n [OPEN_MISTRAL_NEMO.name]: MistralTextProviderOptions\n [MISTRAL_MEDIUM_3.name]: MistralVisionProviderOptions\n [MISTRAL_SMALL_2503.name]: MistralVisionProviderOptions\n [CODESTRAL_2.name]: MistralTextProviderOptions\n}\n\n/**\n * Embedding models (based on endpoints: \"embeddings\")\n */\nexport const MISTRAL_EMBEDDING_MODELS = [\n 'mistral-embed',\n 'codestral-embed',\n] as const\n\n/**\n * Union type of all supported Mistral embedding model names.\n */\nexport type MistralEmbeddingModel = (typeof MISTRAL_EMBEDDING_MODELS)[number]\n\n/**\n * Type-only map from embedding model name to its provider options type.\n *\n * `mistral-embed` accepts no provider options (fixed 1024-dim output);\n * `codestral-embed` additionally supports `outputDtype`.\n */\nexport type MistralEmbeddingModelProviderOptionsByName = {\n 'mistral-embed': MistralEmbedProviderOptions\n 'codestral-embed': CodestralEmbedProviderOptions\n}\n\n/**\n * Per-model input modalities for embedding models. Mistral embedding models\n * are text-only, so image inputs fail at compile time.\n */\nexport type MistralEmbeddingModelInputModalitiesByName = {\n 'mistral-embed': readonly ['text']\n 'codestral-embed': readonly ['text']\n}\n\n/**\n * Resolves the provider options type for a specific Mistral model.\n */\nexport type ResolveProviderOptions<TModel extends string> =\n TModel extends keyof MistralChatModelProviderOptionsByName\n ? MistralChatModelProviderOptionsByName[TModel]\n : MistralTextProviderOptions\n\n/**\n * Resolve input modalities for a specific model.\n */\nexport type ResolveInputModalities<TModel extends string> =\n TModel extends keyof MistralModelInputModalitiesByName\n ? MistralModelInputModalitiesByName[TModel]\n : readonly ['text']\n\n// Reasoning\n//\n// Each model's `reasoning` field holds its data for `chat({ reasoning })`: the\n// levels it has, with the provider value for each, and whether it takes a\n// thinking token budget. The data comes from models.dev. The generator that\n// writes it comes with the model catalog later. Until then, the sync scripts\n// keep these fields as they are.\n\nconst MISTRAL_REASONING = {\n [MISTRAL_MEDIUM_LATEST.name]: MISTRAL_MEDIUM_LATEST.reasoning,\n [MISTRAL_SMALL_LATEST.name]: MISTRAL_SMALL_LATEST.reasoning,\n [MAGISTRAL_MEDIUM_LATEST.name]: MAGISTRAL_MEDIUM_LATEST.reasoning,\n [MAGISTRAL_SMALL_LATEST.name]: MAGISTRAL_SMALL_LATEST.reasoning,\n}\n\n/**\n * Each chat model's reasoning levels, and whether it takes a token budget,\n * for `chat({ reasoning })`. Derived from the `reasoning` field. A model\n * that is not here does not reason.\n */\nexport type MistralModelReasoningByName = {\n [K in keyof typeof MISTRAL_REASONING]: ModelReasoningCapability<\n (typeof MISTRAL_REASONING)[K]\n >\n}\n\n/**\n * Runtime map from chat model name to its reasoning data, for the text adapter.\n * An unknown name gives `undefined`: the adapter sends no reasoning field.\n */\nexport const MISTRAL_MODEL_REASONING: Readonly<Record<string, ModelReasoning>> =\n MISTRAL_REASONING\n"],"mappings":";AAUA,IAAM,mBAAmB;CACvB,QAAQ;EAAE,KAAK;EAAQ,MAAM;CAAO;CACpC,QAAQ;AACV;AACA,IAAM,kBAAkB;CACtB,QAAQ;EAAE,KAAK;EAAO,MAAM;CAAO;CACnC,QAAQ;AACV;AAwCA,IAAM,uBAAuB;CAC3B,MAAM;CACN,gBAAgB;CAChB,uBAAuB;CACvB,SAAS;EACP,OAAO,EAAE,QAAQ,GAAI;EACrB,QAAQ,EAAE,QAAQ,IAAI;CACxB;CACA,UAAU;EACR,OAAO,CAAC,MAAM;EACd,QAAQ,CAAC,MAAM;EACf,WAAW,CAAC,MAAM;EAClB,UAAU;GAAC;GAAa;GAAS;GAAe;EAAa;CAC/D;AACF;AAEA,IAAM,wBAAwB;CAC5B,MAAM;CACN,gBAAgB;CAChB,uBAAuB;CACvB,SAAS;EACP,OAAO,EAAE,QAAQ,GAAI;E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B;CACrB,sBAAsB;CACtB,qBAAqB;CACrB,oBAAoB;CACpB,oBAAoB;CACpB,iBAAiB;CACjB,qBAAqB;CACrB,iBAAiB;CACjB,wBAAwB;CACxB,uBAAuB;CACvB,kBAAkB;AACpB;;;;;;AAYA,IAAa,6BAA6B;CACxC,iBAAiB;CACjB,mBAAmB;CACnB,YAAY;AACd;;;;;;AA8BA,IAAa,iCAET;EACD,qBAAqB,OAAO,qBAAqB,SAAS;EAC1D,sBAAsB,OAAO,sBAAsB,SAAS;EAC5D,qBAAqB,OAAO,qBAAqB,SAAS;EAC1D,oBAAoB,OAAO,oBAAoB,SAAS;EACxD,oBAAoB,OAAO,oBAAoB,SAAS;EACxD,iBAAiB,OAAO,iBAAiB,SAAS;EAClD,qBAAqB,OAAO,qBAAqB,SAAS;EAC1D,iBAAiB,OAAO,iBAAiB,SAAS;EAClD,wBAAwB,OAAO,wBAAwB,SAAS;EAChE,uBAAuB,OAAO,uBAAuB,SAAS;EAC9D,kBAAkB,OAAO,kBAAkB,SAAS;EACpD,iBAAiB,OAAO,iBAAiB,SAAS;EAClD,mBAAmB,OAAO,mBAAmB,SAAS;EACtD,YAAY,OAAO,YAAY,SAAS;AAC3C;;;;AAyBA,IAAa,2BAA2B,CACtC,iBACA,iBACF;;;;;AAyEA,IAAa,0BACX;EAtBC,sBAAsB,OAAO,sBAAsB;EACnD,qBAAqB,OAAO,qBAAqB;EACjD,wBAAwB,OAAO,wBAAwB;EACvD,uBAAuB,OAAO,uBAAuB;AAmBtD"}
1
+ {"version":3,"file":"model-meta.js","names":[],"sources":["../../src/model-meta.ts"],"sourcesContent":["import type { Modality, ModelReasoning } from '@tanstack/ai'\nimport type { ModelReasoningCapability } from '@tanstack/ai/adapter-internals'\nimport type { MistralTextProviderOptions } from './text/text-provider-options'\nimport type {\n CodestralEmbedProviderOptions,\n MistralEmbedProviderOptions,\n} from './embedding/embedding-provider-options'\n\n// Reasoning shapes: the levels a model has for `chat({ reasoning })`, and\n// the provider value to send for each. Each model points at one of them.\nconst EFFORT_NONE_HIGH = {\n levels: { off: 'none', high: 'high' },\n budget: false,\n} as const\nconst EFFORT_OFF_HIGH = {\n levels: { off: 'off', high: 'high' },\n budget: false,\n} as const\n\n/** Provider options for vision-capable Mistral models. */\nexport type MistralVisionProviderOptions = MistralTextProviderOptions\n\n/** Provider options for reasoning-capable Mistral models (magistral-*). */\nexport type MistralReasoningProviderOptions = MistralTextProviderOptions\n\n/**\n * Internal metadata structure describing a Mistral model's capabilities\n * and approximate pricing (USD per million tokens).\n */\ninterface ModelMeta<TProviderOptions = unknown> {\n name: string\n context_window?: number\n max_completion_tokens?: number\n pricing: {\n input?: { normal: number; cached?: number }\n output?: { normal: number }\n }\n supports: {\n input: Array<'text' | 'image' | 'audio' | 'document'>\n output: Array<'text'>\n endpoints: Array<'chat' | 'embeddings'>\n\n features: Array<\n | 'streaming'\n | 'tools'\n | 'json_object'\n | 'json_schema'\n | 'reasoning'\n | 'vision'\n | 'code'\n >\n }\n providerOptions?: TProviderOptions\n /** The model's data for `chat({ reasoning })`. None: it does not reason. */\n reasoning?: ModelReasoning\n}\n\nconst MISTRAL_LARGE_LATEST = {\n name: 'mistral-large-latest',\n context_window: 131_072,\n max_completion_tokens: 8_192,\n pricing: {\n input: { normal: 0.5 },\n output: { normal: 1.5 },\n },\n supports: {\n input: ['text'],\n output: ['text'],\n endpoints: ['chat'],\n features: ['streaming', 'tools', 'json_object', 'json_schema'],\n },\n} as const satisfies ModelMeta<MistralTextProviderOptions>\n\nconst MISTRAL_MEDIUM_LATEST = {\n name: 'mistral-medium-latest',\n context_window: 131_072,\n max_completion_tokens: 8_192,\n pricing: {\n input: { normal: 0.4 },\n output: { normal: 2 },\n },\n supports: {\n input: ['text', 'image', 'document'],\n output: ['text'],\n endpoints: ['chat'],\n features: ['streaming', 'tools', 'json_object', 'json_schema', 'vision'],\n },\n reasoning: EFFORT_NONE_HIGH,\n} as const satisfies ModelMeta<MistralTextProviderOptions>\n\nconst MISTRAL_SMALL_LATEST = {\n name: 'mistral-small-latest',\n context_window: 131_072,\n max_completion_tokens: 8_192,\n pricing: {\n input: { normal: 0.1 },\n output: { normal: 0.3 },\n },\n supports: {\n input: ['text', 'image', 'document'],\n output: ['text'],\n endpoints: ['chat'],\n features: ['streaming', 'tools', 'json_object', 'json_schema', 'vision'],\n },\n reasoning: EFFORT_NONE_HIGH,\n} as const satisfies ModelMeta<MistralTextProviderOptions>\n\nconst MINISTRAL_8B_LATEST = {\n name: 'ministral-8b-latest',\n context_window: 131_072,\n max_completion_tokens: 8_192,\n pricing: {\n input: { normal: 0.1 },\n output: { normal: 0.1 },\n },\n supports: {\n input: ['text'],\n output: ['text'],\n endpoints: ['chat'],\n features: ['streaming', 'tools', 'json_object', 'json_schema'],\n },\n} as const satisfies ModelMeta<MistralTextProviderOptions>\n\nconst MINISTRAL_3B_LATEST = {\n name: 'ministral-3b-latest',\n context_window: 131_072,\n max_completion_tokens: 8_192,\n pricing: {\n input: { normal: 0.04 },\n output: { normal: 0.04 },\n },\n supports: {\n input: ['text'],\n output: ['text'],\n endpoints: ['chat'],\n features: ['streaming', 'tools', 'json_object', 'json_schema'],\n },\n} as const satisfies ModelMeta<MistralTextProviderOptions>\n\nconst CODESTRAL_LATEST = {\n name: 'codestral-latest',\n context_window: 256_000,\n max_completion_tokens: 8_192,\n pricing: {\n input: { normal: 0.3 },\n output: { normal: 0.9 },\n },\n supports: {\n input: ['text'],\n output: ['text'],\n endpoints: ['chat'],\n features: ['streaming', 'tools', 'json_object', 'json_schema', 'code'],\n },\n} as const satisfies ModelMeta<MistralTextProviderOptions>\n\nconst MAGISTRAL_MEDIUM_LATEST = {\n name: 'magistral-medium-latest',\n context_window: 40_000,\n max_completion_tokens: 40_000,\n pricing: {\n input: { normal: 2 },\n output: { normal: 5 },\n },\n supports: {\n input: ['text'],\n output: ['text'],\n endpoints: ['chat'],\n features: ['streaming', 'tools', 'reasoning', 'json_object', 'json_schema'],\n },\n reasoning: EFFORT_OFF_HIGH,\n} as const satisfies ModelMeta<MistralTextProviderOptions>\n\nconst MAGISTRAL_SMALL_LATEST = {\n name: 'magistral-small-latest',\n context_window: 40_000,\n max_completion_tokens: 40_000,\n pricing: {\n input: { normal: 0.5 },\n output: { normal: 1.5 },\n },\n supports: {\n input: ['text'],\n output: ['text'],\n endpoints: ['chat'],\n features: ['streaming', 'tools', 'reasoning', 'json_object', 'json_schema'],\n },\n // Not in models.dev. The same as Magistral Medium: prompt_mode only.\n reasoning: EFFORT_OFF_HIGH,\n} as const satisfies ModelMeta<MistralTextProviderOptions>\n\n// Vertex Model Garden IDs. These are not the Mistral API catalog.\n// Source: https://docs.cloud.google.com/gemini-enterprise-agent-platform/models/partner-models/mistral\nconst MISTRAL_MEDIUM_3 = {\n name: 'mistral-medium-3',\n context_window: 131_072,\n max_completion_tokens: 8_192,\n pricing: {\n input: { normal: 0.4 },\n output: { normal: 2 },\n },\n supports: {\n input: ['text', 'image', 'document'],\n output: ['text'],\n endpoints: ['chat'],\n features: ['streaming', 'tools', 'json_object', 'json_schema', 'vision'],\n },\n} as const satisfies ModelMeta<MistralTextProviderOptions>\n\nconst MISTRAL_SMALL_2503 = {\n name: 'mistral-small-2503',\n context_window: 131_072,\n max_completion_tokens: 8_192,\n pricing: {\n input: { normal: 0.1 },\n output: { normal: 0.3 },\n },\n supports: {\n input: ['text', 'image', 'document'],\n output: ['text'],\n endpoints: ['chat'],\n features: ['streaming', 'tools', 'json_object', 'json_schema', 'vision'],\n },\n} as const satisfies ModelMeta<MistralTextProviderOptions>\n\nconst CODESTRAL_2 = {\n name: 'codestral-2',\n context_window: 131_072,\n max_completion_tokens: 8_192,\n pricing: {\n input: { normal: 0.3 },\n output: { normal: 0.9 },\n },\n supports: {\n input: ['text'],\n output: ['text'],\n endpoints: ['chat'],\n features: ['streaming', 'tools', 'json_object', 'json_schema', 'code'],\n },\n} as const satisfies ModelMeta<MistralTextProviderOptions>\n\n/**\n * All supported Mistral chat model identifiers.\n */\nexport const MISTRAL_CHAT_MODELS = [\n MISTRAL_LARGE_LATEST.name,\n MISTRAL_MEDIUM_LATEST.name,\n MISTRAL_SMALL_LATEST.name,\n MINISTRAL_8B_LATEST.name,\n MINISTRAL_3B_LATEST.name,\n CODESTRAL_LATEST.name,\n MAGISTRAL_MEDIUM_LATEST.name,\n MAGISTRAL_SMALL_LATEST.name,\n] as const\n\n/**\n * Union type of all supported Mistral chat model names.\n */\nexport type MistralChatModels = (typeof MISTRAL_CHAT_MODELS)[number]\n\n/**\n * Mistral chat models on Vertex AI / Gemini Enterprise Agent Platform.\n * This list is the Google partner catalog, not the Mistral API catalog.\n * OCR (`mistral-ocr-2505`) is not a chat model.\n */\nexport const MISTRAL_VERTEX_CHAT_MODELS = [\n MISTRAL_MEDIUM_3.name,\n MISTRAL_SMALL_2503.name,\n CODESTRAL_2.name,\n] as const\n\nexport type MistralVertexChatModel = (typeof MISTRAL_VERTEX_CHAT_MODELS)[number]\nexport type MistralTextAdapterModel = MistralChatModels | MistralVertexChatModel\n\n/**\n * Type-only map from Mistral chat model name to its supported input modalities.\n */\nexport type MistralModelInputModalitiesByName = {\n [MISTRAL_LARGE_LATEST.name]: typeof MISTRAL_LARGE_LATEST.supports.input\n [MISTRAL_MEDIUM_LATEST.name]: typeof MISTRAL_MEDIUM_LATEST.supports.input\n [MISTRAL_SMALL_LATEST.name]: typeof MISTRAL_SMALL_LATEST.supports.input\n [MINISTRAL_8B_LATEST.name]: typeof MINISTRAL_8B_LATEST.supports.input\n [MINISTRAL_3B_LATEST.name]: typeof MINISTRAL_3B_LATEST.supports.input\n [CODESTRAL_LATEST.name]: typeof CODESTRAL_LATEST.supports.input\n [MAGISTRAL_MEDIUM_LATEST.name]: typeof MAGISTRAL_MEDIUM_LATEST.supports.input\n [MAGISTRAL_SMALL_LATEST.name]: typeof MAGISTRAL_SMALL_LATEST.supports.input\n [MISTRAL_MEDIUM_3.name]: typeof MISTRAL_MEDIUM_3.supports.input\n [MISTRAL_SMALL_2503.name]: typeof MISTRAL_SMALL_2503.supports.input\n [CODESTRAL_2.name]: typeof CODESTRAL_2.supports.input\n}\n\n/**\n * Runtime map from chat model name to its supported input modalities, for the\n * text adapter's `inputModalities`. `satisfies` keeps it equal to\n * {@link MistralModelInputModalitiesByName}. An unknown name gives `undefined`.\n */\nexport const MISTRAL_MODEL_INPUT_MODALITIES: Readonly<\n Record<string, ReadonlyArray<Modality>>\n> = {\n [MISTRAL_LARGE_LATEST.name]: MISTRAL_LARGE_LATEST.supports.input,\n [MISTRAL_MEDIUM_LATEST.name]: MISTRAL_MEDIUM_LATEST.supports.input,\n [MISTRAL_SMALL_LATEST.name]: MISTRAL_SMALL_LATEST.supports.input,\n [MINISTRAL_8B_LATEST.name]: MINISTRAL_8B_LATEST.supports.input,\n [MINISTRAL_3B_LATEST.name]: MINISTRAL_3B_LATEST.supports.input,\n [CODESTRAL_LATEST.name]: CODESTRAL_LATEST.supports.input,\n [MAGISTRAL_MEDIUM_LATEST.name]: MAGISTRAL_MEDIUM_LATEST.supports.input,\n [MAGISTRAL_SMALL_LATEST.name]: MAGISTRAL_SMALL_LATEST.supports.input,\n [MISTRAL_MEDIUM_3.name]: MISTRAL_MEDIUM_3.supports.input,\n [MISTRAL_SMALL_2503.name]: MISTRAL_SMALL_2503.supports.input,\n [CODESTRAL_2.name]: CODESTRAL_2.supports.input,\n} satisfies MistralModelInputModalitiesByName\n\n/**\n * Type-only map from Mistral chat model name to its provider options type.\n */\nexport type MistralChatModelProviderOptionsByName = {\n [MISTRAL_LARGE_LATEST.name]: MistralTextProviderOptions\n [MISTRAL_MEDIUM_LATEST.name]: MistralVisionProviderOptions\n [MISTRAL_SMALL_LATEST.name]: MistralVisionProviderOptions\n [MINISTRAL_8B_LATEST.name]: MistralTextProviderOptions\n [MINISTRAL_3B_LATEST.name]: MistralTextProviderOptions\n [CODESTRAL_LATEST.name]: MistralTextProviderOptions\n [MAGISTRAL_MEDIUM_LATEST.name]: MistralReasoningProviderOptions\n [MAGISTRAL_SMALL_LATEST.name]: MistralReasoningProviderOptions\n [MISTRAL_MEDIUM_3.name]: MistralVisionProviderOptions\n [MISTRAL_SMALL_2503.name]: MistralVisionProviderOptions\n [CODESTRAL_2.name]: MistralTextProviderOptions\n}\n\n/**\n * Embedding models (based on endpoints: \"embeddings\")\n */\nexport const MISTRAL_EMBEDDING_MODELS = [\n 'mistral-embed',\n 'codestral-embed',\n] as const\n\n/**\n * Union type of all supported Mistral embedding model names.\n */\nexport type MistralEmbeddingModel = (typeof MISTRAL_EMBEDDING_MODELS)[number]\n\n/**\n * Type-only map from embedding model name to its provider options type.\n *\n * `mistral-embed` accepts no provider options (fixed 1024-dim output);\n * `codestral-embed` additionally supports `outputDtype`.\n */\nexport type MistralEmbeddingModelProviderOptionsByName = {\n 'mistral-embed': MistralEmbedProviderOptions\n 'codestral-embed': CodestralEmbedProviderOptions\n}\n\n/**\n * Per-model input modalities for embedding models. Mistral embedding models\n * are text-only, so image inputs fail at compile time.\n */\nexport type MistralEmbeddingModelInputModalitiesByName = {\n 'mistral-embed': readonly ['text']\n 'codestral-embed': readonly ['text']\n}\n\n/**\n * Resolves the provider options type for a specific Mistral model.\n */\nexport type ResolveProviderOptions<TModel extends string> =\n TModel extends keyof MistralChatModelProviderOptionsByName\n ? MistralChatModelProviderOptionsByName[TModel]\n : MistralTextProviderOptions\n\n/**\n * Resolve input modalities for a specific model.\n */\nexport type ResolveInputModalities<TModel extends string> =\n TModel extends keyof MistralModelInputModalitiesByName\n ? MistralModelInputModalitiesByName[TModel]\n : readonly ['text']\n\n// Reasoning\n//\n// Each model's `reasoning` field holds its data for `chat({ reasoning })`: the\n// levels it has, with the provider value for each, and whether it takes a\n// thinking token budget. The data comes from models.dev. The generator that\n// writes it comes with the model catalog later. Until then, the sync scripts\n// keep these fields as they are.\n\nconst MISTRAL_REASONING = {\n [MISTRAL_MEDIUM_LATEST.name]: MISTRAL_MEDIUM_LATEST.reasoning,\n [MISTRAL_SMALL_LATEST.name]: MISTRAL_SMALL_LATEST.reasoning,\n [MAGISTRAL_MEDIUM_LATEST.name]: MAGISTRAL_MEDIUM_LATEST.reasoning,\n [MAGISTRAL_SMALL_LATEST.name]: MAGISTRAL_SMALL_LATEST.reasoning,\n}\n\n/**\n * Each chat model's reasoning levels, and whether it takes a token budget,\n * for `chat({ reasoning })`. Derived from the `reasoning` field. A model\n * that is not here does not reason.\n */\nexport type MistralModelReasoningByName = {\n [K in keyof typeof MISTRAL_REASONING]: ModelReasoningCapability<\n (typeof MISTRAL_REASONING)[K]\n >\n}\n\n/**\n * Runtime map from chat model name to its reasoning data, for the text adapter.\n * An unknown name gives `undefined`: the adapter sends no reasoning field.\n */\nexport const MISTRAL_MODEL_REASONING: Readonly<Record<string, ModelReasoning>> =\n MISTRAL_REASONING\n"],"mappings":";AAUA,IAAM,mBAAmB;CACvB,QAAQ;EAAE,KAAK;EAAQ,MAAM;CAAO;CACpC,QAAQ;AACV;AACA,IAAM,kBAAkB;CACtB,QAAQ;EAAE,KAAK;EAAO,MAAM;CAAO;CACnC,QAAQ;AACV;AAwCA,IAAM,uBAAuB;CAC3B,MAAM;CACN,gBAAgB;CAChB,uBAAuB;CACvB,SAAS;EACP,OAAO,EAAE,QAAQ,GAAI;EACrB,QAAQ,EAAE,QAAQ,IAAI;CACxB;CACA,UAAU;EACR,OAAO,CAAC,MAAM;EACd,QAAQ,CAAC,MAAM;EACf,WAAW,CAAC,MAAM;EAClB,UAAU;GAAC;GAAa;GAAS;GAAe;EAAa;CAC/D;AACF;AAEA,IAAM,wBAAwB;CAC5B,MAAM;CACN,gBAAgB;CAChB,uBAAuB;CACvB,SAAS;EACP,OAAO,EAAE,QAAQ,GAAI;EACrB,QAAQ,EAAE,QAAQ,EAAE;CACtB;CACA,UAAU;EACR,OAAO;GAAC;GAAQ;GAAS;EAAU;EACnC,QAAQ,CAAC,MAAM;EACf,WAAW,CAAC,MAAM;EAClB,UAAU;GAAC;GAAa;GAAS;GAAe;GAAe;EAAQ;CACzE;CACA,WA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ACxB;CACA,UAAU;EACR,OAAO,CAAC,MAAM;EACd,QAAQ,CAAC,MAAM;EACf,WAAW,CAAC,MAAM;EAClB,UAAU;GAAC;GAAa;GAAS;GAAe;GAAe;EAAM;CACvE;AACF;;;;AAKA,IAAa,sBAAsB;CACjC,qBAAqB;CACrB,sBAAsB;CACtB,qBAAqB;CACrB,oBAAoB;CACpB,oBAAoB;CACpB,iBAAiB;CACjB,wBAAwB;CACxB,uBAAuB;AACzB;;;;;;AAYA,IAAa,6BAA6B;CACxC,iBAAiB;CACjB,mBAAmB;CACnB,YAAY;AACd;;;;;;AA2BA,IAAa,iCAET;EACD,qBAAqB,OAAO,qBAAqB,SAAS;EAC1D,sBAAsB,OAAO,sBAAsB,SAAS;EAC5D,qBAAqB,OAAO,qBAAqB,SAAS;EAC1D,oBAAoB,OAAO,oBAAoB,SAAS;EACxD,oBAAoB,OAAO,oBAAoB,SAAS;EACxD,iBAAiB,OAAO,iBAAiB,SAAS;EAClD,wBAAwB,OAAO,wBAAwB,SAAS;EAChE,uBAAuB,OAAO,uBAAuB,SAAS;EAC9D,iBAAiB,OAAO,iBAAiB,SAAS;EAClD,mBAAmB,OAAO,mBAAmB,SAAS;EACtD,YAAY,OAAO,YAAY,SAAS;AAC3C;;;;AAsBA,IAAa,2BAA2B,CACtC,iBACA,iBACF;;;;;AAyEA,IAAa,0BACX;EAtBC,sBAAsB,OAAO,sBAAsB;EACnD,qBAAqB,OAAO,qBAAqB;EACjD,wBAAwB,OAAO,wBAAwB;EACvD,uBAAuB,OAAO,uBAAuB;AAmBtD"}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@tanstack/ai-mistral",
3
- "version": "0.7.1",
3
+ "version": "1.0.0",
4
4
  "type": "module",
5
5
  "description": "Mistral adapter for TanStack AI",
6
6
  "author": "",
@@ -48,11 +48,11 @@
48
48
  "@vitest/coverage-v8": "4.1.10",
49
49
  "google-auth-library": "^10.5.0",
50
50
  "vite": "^8.2.1",
51
- "@tanstack/ai": "0.70.0"
51
+ "@tanstack/ai": "1.0.0"
52
52
  },
53
53
  "peerDependencies": {
54
54
  "google-auth-library": "^10.5.0",
55
- "@tanstack/ai": "^0.70.0"
55
+ "@tanstack/ai": "^1.0.0"
56
56
  },
57
57
  "peerDependenciesMeta": {
58
58
  "google-auth-library": {
@@ -61,7 +61,7 @@
61
61
  },
62
62
  "dependencies": {
63
63
  "@mistralai/mistralai": "2.2.0",
64
- "@tanstack/ai-utils": "0.5.0"
64
+ "@tanstack/ai-utils": "^1.0.0"
65
65
  },
66
66
  "scripts": {
67
67
  "build": "vite build",
@@ -338,7 +338,7 @@ export class MistralTextAdapter<
338
338
 
339
339
  const aguiState = {
340
340
  runId: options.runId ?? generateId(this.name),
341
- threadId: options.threadId ?? generateId(this.name),
341
+ threadId: options.threadId,
342
342
  messageId: generateId(this.name),
343
343
  timestamp,
344
344
  hasEmittedRunStarted: false,
@@ -695,7 +695,6 @@ export class MistralTextAdapter<
695
695
  type: 'TOOL_CALL_START',
696
696
  toolCallId: toolCall.id,
697
697
  toolCallName: toolCall.name,
698
- toolName: toolCall.name,
699
698
  model: chunkModel,
700
699
  timestamp,
701
700
  index,
@@ -747,7 +746,6 @@ export class MistralTextAdapter<
747
746
  type: 'TOOL_CALL_END',
748
747
  toolCallId: toolCall.id,
749
748
  toolCallName: toolCall.name,
750
- toolName: toolCall.name,
751
749
  model: chunkModel,
752
750
  timestamp,
753
751
  args: toolCall.arguments,
@@ -844,7 +842,6 @@ export class MistralTextAdapter<
844
842
  type: 'TOOL_CALL_END',
845
843
  toolCallId: toolCall.id,
846
844
  toolCallName: toolCall.name,
847
- toolName: toolCall.name,
848
845
  model: lastChunkModel,
849
846
  timestamp,
850
847
  args: toolCall.arguments,
@@ -922,7 +919,6 @@ export class MistralTextAdapter<
922
919
  type: 'TOOL_CALL_END',
923
920
  toolCallId: toolCall.id,
924
921
  toolCallName: toolCall.name,
925
- toolName: toolCall.name,
926
922
  model: lastChunkModel,
927
923
  timestamp,
928
924
  args: toolCall.arguments,
@@ -10,7 +10,7 @@ describe('Mistral text adapter inputModalities', () => {
10
10
  new MistralTextAdapter(config, 'mistral-large-latest').inputModalities,
11
11
  ).toEqual(['text'])
12
12
  expect(
13
- new MistralTextAdapter(config, 'pixtral-large-latest').inputModalities,
13
+ new MistralTextAdapter(config, 'mistral-medium-latest').inputModalities,
14
14
  ).toEqual(['text', 'image', 'document'])
15
15
  })
16
16
 
package/src/model-meta.ts CHANGED
@@ -17,7 +17,7 @@ const EFFORT_OFF_HIGH = {
17
17
  budget: false,
18
18
  } as const
19
19
 
20
- /** Provider options for vision-capable Mistral models (pixtral-*). */
20
+ /** Provider options for vision-capable Mistral models. */
21
21
  export type MistralVisionProviderOptions = MistralTextProviderOptions
22
22
 
23
23
  /** Provider options for reasoning-capable Mistral models (magistral-*). */
@@ -153,38 +153,6 @@ const CODESTRAL_LATEST = {
153
153
  },
154
154
  } as const satisfies ModelMeta<MistralTextProviderOptions>
155
155
 
156
- const PIXTRAL_LARGE_LATEST = {
157
- name: 'pixtral-large-latest',
158
- context_window: 131_072,
159
- max_completion_tokens: 8_192,
160
- pricing: {
161
- input: { normal: 2 },
162
- output: { normal: 6 },
163
- },
164
- supports: {
165
- input: ['text', 'image', 'document'],
166
- output: ['text'],
167
- endpoints: ['chat'],
168
- features: ['streaming', 'tools', 'json_object', 'json_schema', 'vision'],
169
- },
170
- } as const satisfies ModelMeta<MistralTextProviderOptions>
171
-
172
- const PIXTRAL_12B_2409 = {
173
- name: 'pixtral-12b-2409',
174
- context_window: 131_072,
175
- max_completion_tokens: 8_192,
176
- pricing: {
177
- input: { normal: 0.15 },
178
- output: { normal: 0.15 },
179
- },
180
- supports: {
181
- input: ['text', 'image', 'document'],
182
- output: ['text'],
183
- endpoints: ['chat'],
184
- features: ['streaming', 'tools', 'json_object', 'vision'],
185
- },
186
- } as const satisfies ModelMeta<MistralTextProviderOptions>
187
-
188
156
  const MAGISTRAL_MEDIUM_LATEST = {
189
157
  name: 'magistral-medium-latest',
190
158
  context_window: 40_000,
@@ -220,22 +188,6 @@ const MAGISTRAL_SMALL_LATEST = {
220
188
  reasoning: EFFORT_OFF_HIGH,
221
189
  } as const satisfies ModelMeta<MistralTextProviderOptions>
222
190
 
223
- const OPEN_MISTRAL_NEMO = {
224
- name: 'open-mistral-nemo',
225
- context_window: 131_072,
226
- max_completion_tokens: 8_192,
227
- pricing: {
228
- input: { normal: 0.15 },
229
- output: { normal: 0.15 },
230
- },
231
- supports: {
232
- input: ['text'],
233
- output: ['text'],
234
- endpoints: ['chat'],
235
- features: ['streaming', 'tools', 'json_object'],
236
- },
237
- } as const satisfies ModelMeta<MistralTextProviderOptions>
238
-
239
191
  // Vertex Model Garden IDs. These are not the Mistral API catalog.
240
192
  // Source: https://docs.cloud.google.com/gemini-enterprise-agent-platform/models/partner-models/mistral
241
193
  const MISTRAL_MEDIUM_3 = {
@@ -296,11 +248,8 @@ export const MISTRAL_CHAT_MODELS = [
296
248
  MINISTRAL_8B_LATEST.name,
297
249
  MINISTRAL_3B_LATEST.name,
298
250
  CODESTRAL_LATEST.name,
299
- PIXTRAL_LARGE_LATEST.name,
300
- PIXTRAL_12B_2409.name,
301
251
  MAGISTRAL_MEDIUM_LATEST.name,
302
252
  MAGISTRAL_SMALL_LATEST.name,
303
- OPEN_MISTRAL_NEMO.name,
304
253
  ] as const
305
254
 
306
255
  /**
@@ -332,11 +281,8 @@ export type MistralModelInputModalitiesByName = {
332
281
  [MINISTRAL_8B_LATEST.name]: typeof MINISTRAL_8B_LATEST.supports.input
333
282
  [MINISTRAL_3B_LATEST.name]: typeof MINISTRAL_3B_LATEST.supports.input
334
283
  [CODESTRAL_LATEST.name]: typeof CODESTRAL_LATEST.supports.input
335
- [PIXTRAL_LARGE_LATEST.name]: typeof PIXTRAL_LARGE_LATEST.supports.input
336
- [PIXTRAL_12B_2409.name]: typeof PIXTRAL_12B_2409.supports.input
337
284
  [MAGISTRAL_MEDIUM_LATEST.name]: typeof MAGISTRAL_MEDIUM_LATEST.supports.input
338
285
  [MAGISTRAL_SMALL_LATEST.name]: typeof MAGISTRAL_SMALL_LATEST.supports.input
339
- [OPEN_MISTRAL_NEMO.name]: typeof OPEN_MISTRAL_NEMO.supports.input
340
286
  [MISTRAL_MEDIUM_3.name]: typeof MISTRAL_MEDIUM_3.supports.input
341
287
  [MISTRAL_SMALL_2503.name]: typeof MISTRAL_SMALL_2503.supports.input
342
288
  [CODESTRAL_2.name]: typeof CODESTRAL_2.supports.input
@@ -356,11 +302,8 @@ export const MISTRAL_MODEL_INPUT_MODALITIES: Readonly<
356
302
  [MINISTRAL_8B_LATEST.name]: MINISTRAL_8B_LATEST.supports.input,
357
303
  [MINISTRAL_3B_LATEST.name]: MINISTRAL_3B_LATEST.supports.input,
358
304
  [CODESTRAL_LATEST.name]: CODESTRAL_LATEST.supports.input,
359
- [PIXTRAL_LARGE_LATEST.name]: PIXTRAL_LARGE_LATEST.supports.input,
360
- [PIXTRAL_12B_2409.name]: PIXTRAL_12B_2409.supports.input,
361
305
  [MAGISTRAL_MEDIUM_LATEST.name]: MAGISTRAL_MEDIUM_LATEST.supports.input,
362
306
  [MAGISTRAL_SMALL_LATEST.name]: MAGISTRAL_SMALL_LATEST.supports.input,
363
- [OPEN_MISTRAL_NEMO.name]: OPEN_MISTRAL_NEMO.supports.input,
364
307
  [MISTRAL_MEDIUM_3.name]: MISTRAL_MEDIUM_3.supports.input,
365
308
  [MISTRAL_SMALL_2503.name]: MISTRAL_SMALL_2503.supports.input,
366
309
  [CODESTRAL_2.name]: CODESTRAL_2.supports.input,
@@ -376,11 +319,8 @@ export type MistralChatModelProviderOptionsByName = {
376
319
  [MINISTRAL_8B_LATEST.name]: MistralTextProviderOptions
377
320
  [MINISTRAL_3B_LATEST.name]: MistralTextProviderOptions
378
321
  [CODESTRAL_LATEST.name]: MistralTextProviderOptions
379
- [PIXTRAL_LARGE_LATEST.name]: MistralVisionProviderOptions
380
- [PIXTRAL_12B_2409.name]: MistralVisionProviderOptions
381
322
  [MAGISTRAL_MEDIUM_LATEST.name]: MistralReasoningProviderOptions
382
323
  [MAGISTRAL_SMALL_LATEST.name]: MistralReasoningProviderOptions
383
- [OPEN_MISTRAL_NEMO.name]: MistralTextProviderOptions
384
324
  [MISTRAL_MEDIUM_3.name]: MistralVisionProviderOptions
385
325
  [MISTRAL_SMALL_2503.name]: MistralVisionProviderOptions
386
326
  [CODESTRAL_2.name]: MistralTextProviderOptions