@tanstack/ai-mistral 1.1.1 → 1.1.2
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/esm/adapters/embedding.js +1 -2
- package/dist/esm/adapters/text.js +17 -8
- package/dist/esm/adapters/text.js.map +1 -1
- package/dist/esm/byok.js +1 -2
- package/dist/esm/client/index.js +1 -2
- package/dist/esm/index.js +1 -1
- package/dist/esm/model-meta.js +1 -2
- package/dist/esm/tools/function-tool.js +1 -2
- package/dist/esm/tools/tool-converter.js +1 -2
- package/dist/esm/utils/client.js +1 -2
- package/dist/esm/utils/client.js.map +1 -1
- package/dist/esm/utils/schema-converter.js +1 -2
- package/dist/esm/utils/tool-input-normalizer.js +1 -2
- package/dist/esm/vertex/auth.js +1 -2
- package/dist/esm/vertex/index.js +2 -3
- package/package.json +5 -5
- package/src/adapters/text.ts +40 -11
|
@@ -3,7 +3,7 @@ import { generateId, getMistralApiKeyFromEnv } from "../utils/client.js";
|
|
|
3
3
|
import { requireTextOnlyEmbeddingInput } from "@tanstack/ai";
|
|
4
4
|
import { BaseEmbeddingAdapter } from "@tanstack/ai/adapters";
|
|
5
5
|
import { toRunErrorPayload } from "@tanstack/ai/adapter-internals";
|
|
6
|
-
|
|
6
|
+
// src/adapters/embedding.ts
|
|
7
7
|
/**
|
|
8
8
|
* Mistral Embedding Adapter
|
|
9
9
|
*
|
|
@@ -117,7 +117,6 @@ function createMistralEmbedding(model, apiKey, config) {
|
|
|
117
117
|
function mistralEmbedding(model, config) {
|
|
118
118
|
return createMistralEmbedding(model, getMistralApiKeyFromEnv(), config);
|
|
119
119
|
}
|
|
120
|
-
//#endregion
|
|
121
120
|
export { MistralEmbeddingAdapter, createMistralEmbedding, mistralEmbedding };
|
|
122
121
|
|
|
123
122
|
//# sourceMappingURL=embedding.js.map
|
|
@@ -1,14 +1,14 @@
|
|
|
1
|
-
import { makeMistralStructuredOutputCompatibleWithMap } from "../utils/schema-converter.js";
|
|
2
1
|
import { convertToolsToProviderFormat } from "../tools/tool-converter.js";
|
|
3
2
|
import { createMistralClient } from "../client/index.js";
|
|
4
3
|
import { generateId, getMistralApiKeyFromEnv } from "../utils/client.js";
|
|
4
|
+
import { makeMistralStructuredOutputCompatibleWithMap } from "../utils/schema-converter.js";
|
|
5
5
|
import { createToolInputNormalizer } from "../utils/tool-input-normalizer.js";
|
|
6
6
|
import { MISTRAL_MODEL_INPUT_MODALITIES, MISTRAL_MODEL_REASONING } from "../model-meta.js";
|
|
7
|
-
import { isFileSource, unsupportedFileSourceError } from "@tanstack/ai";
|
|
7
|
+
import { CONTEXT_OVERFLOW_CODE, isFileSource, unsupportedFileSourceError } from "@tanstack/ai";
|
|
8
8
|
import { BaseTextAdapter } from "@tanstack/ai/adapters";
|
|
9
9
|
import { undoNullWidening } from "@tanstack/ai-utils";
|
|
10
10
|
import { hashToolCallId, orderedAssistantBlocks, resolveReasoning, transformMessagesForReplay } from "@tanstack/ai/adapter-internals";
|
|
11
|
-
|
|
11
|
+
// src/adapters/text.ts
|
|
12
12
|
/** Cast an event object to StreamChunk. Adapters construct events with string
|
|
13
13
|
* literal types which are structurally compatible with the EventType enum. */
|
|
14
14
|
var asChunk = (chunk) => chunk;
|
|
@@ -216,7 +216,9 @@ var MistralTextAdapter = class extends BaseTextAdapter {
|
|
|
216
216
|
totalTokens: response.usage.totalTokens ?? 0,
|
|
217
217
|
...mistralCachedTokens(response.usage)
|
|
218
218
|
};
|
|
219
|
-
|
|
219
|
+
const structuredFinishReason = response.choices[0]?.finishReason;
|
|
220
|
+
if (structuredFinishReason === "model_length") throw Object.assign(/* @__PURE__ */ new Error("mistral.structuredOutput: the response was cut off because the model reached the end of its context window (finish_reason=model_length); shorten the prompt or use a model with a larger context window"), { code: CONTEXT_OVERFLOW_CODE }, usage && { usage });
|
|
221
|
+
if (structuredFinishReason === "length") throw Object.assign(/* @__PURE__ */ new Error("mistral.structuredOutput: the response was cut off because the maximum token limit was reached (finish_reason=length); raise modelOptions.max_tokens"), usage && { usage });
|
|
220
222
|
const rawText = response.choices[0]?.message?.content;
|
|
221
223
|
const textContent = typeof rawText === "string" ? rawText : "";
|
|
222
224
|
let parsed;
|
|
@@ -391,10 +393,18 @@ var MistralTextAdapter = class extends BaseTextAdapter {
|
|
|
391
393
|
});
|
|
392
394
|
}
|
|
393
395
|
const finishReason = choice.finish_reason;
|
|
396
|
+
if (finishReason === "model_length") throw Object.assign(/* @__PURE__ */ new Error("The response was cut off because the model reached the end of its context window."), { code: CONTEXT_OVERFLOW_CODE });
|
|
394
397
|
if (finishReason) {
|
|
395
398
|
if (finishReason === "tool_calls" || toolCallsInProgress.size > 0) for (const [, toolCall] of toolCallsInProgress) {
|
|
396
399
|
if (!toolCall.started || !toolCall.id || !toolCall.name || toolCall.ended) continue;
|
|
397
|
-
|
|
400
|
+
let parsedInput;
|
|
401
|
+
let parsed = false;
|
|
402
|
+
try {
|
|
403
|
+
parsedInput = parseToolCallInput(toolCall, normalizeToolInput);
|
|
404
|
+
parsed = true;
|
|
405
|
+
} catch (error) {
|
|
406
|
+
if (finishReason !== "length") throw error;
|
|
407
|
+
}
|
|
398
408
|
toolCall.ended = true;
|
|
399
409
|
hasEmittedToolCall = true;
|
|
400
410
|
yield asChunk({
|
|
@@ -404,10 +414,10 @@ var MistralTextAdapter = class extends BaseTextAdapter {
|
|
|
404
414
|
model: chunkModel,
|
|
405
415
|
timestamp,
|
|
406
416
|
args: toolCall.arguments,
|
|
407
|
-
input: parsedInput
|
|
417
|
+
...parsed ? { input: parsedInput } : {}
|
|
408
418
|
});
|
|
409
419
|
}
|
|
410
|
-
const computedFinishReason = finishReason === "
|
|
420
|
+
const computedFinishReason = finishReason === "length" ? "length" : finishReason === "tool_calls" || hasEmittedToolCall ? "tool_calls" : "stop";
|
|
411
421
|
if (reasoningMessageId !== null && !hasClosedReasoning) {
|
|
412
422
|
hasClosedReasoning = true;
|
|
413
423
|
yield asChunk({
|
|
@@ -898,7 +908,6 @@ function createMistralText(model, apiKey, config) {
|
|
|
898
908
|
function mistralText(model, config) {
|
|
899
909
|
return createMistralText(model, getMistralApiKeyFromEnv(), config);
|
|
900
910
|
}
|
|
901
|
-
//#endregion
|
|
902
911
|
export { MistralTextAdapter, createMistralText, mistralText };
|
|
903
912
|
|
|
904
913
|
//# sourceMappingURL=text.js.map
|
|
@@ -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 { createMistralClient } from '../client/index'\nimport { generateId, getMistralApiKeyFromEnv } 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 TokenUsage,\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 {\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 { MistralClient } from '../client/index'\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: MistralClient\n private readonly rawConfig: MistralClientConfig\n\n constructor(config: MistralTextConfig, model: TModel) {\n super(config, model)\n // The client serves `structuredOutput` (non-streaming). The streaming\n // path uses `fetchRawMistralStream`, which reads partial tool-call\n // argument deltas as they come.\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: string\n threadId: string\n messageId: string\n timestamp: number\n hasEmittedRunStarted: boolean\n usage?: TokenUsage\n } = {\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 options.request?.signal ?? undefined,\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 ...(aguiState.usage && { usage: aguiState.usage }),\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 // The SDK drops its default 30 s timeout when the request has a signal\n // (lib/sdks.js), so keep that timeout next to the caller signal.\n const signal = chatOptions.request?.signal\n const timeoutMs = this.rawConfig.timeoutMs || 30_000\n const params = {\n ...nonStreamParams,\n responseFormat: {\n type: 'json_schema' as const,\n jsonSchema: {\n name: 'structured_output',\n schemaDefinition: jsonSchema,\n strict,\n },\n },\n }\n const response = signal\n ? await client.chat.complete(params, {\n signal:\n timeoutMs > 0\n ? AbortSignal.any([signal, AbortSignal.timeout(timeoutMs)])\n : signal,\n })\n : await client.chat.complete(params)\n\n const usage = response.usage && {\n promptTokens: response.usage.promptTokens ?? 0,\n completionTokens: response.usage.completionTokens ?? 0,\n totalTokens: response.usage.totalTokens ?? 0,\n ...mistralCachedTokens(response.usage),\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). The errors carry the\n // usage, because the provider already billed the tokens.\n if (response.choices[0]?.finishReason === 'length') {\n throw Object.assign(\n 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 usage && { usage },\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 Object.assign(\n new Error(\n `Failed to parse structured output as JSON. Content: ${textContent.slice(0, 200)}${textContent.length > 200 ? '...' : ''}`,\n ),\n usage && { usage },\n )\n }\n\n return {\n data: undoNullWidening(parsed, nullWideningMap),\n ...(response.id && { responseId: response.id }),\n ...(response.model && { model: response.model }),\n rawText: textContent,\n ...(usage && { usage }),\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 usage?: TokenUsage\n },\n ): AsyncIterable<AdapterYieldChunk> {\n let accumulatedContent = ''\n // RUN_FINISHED waits for the end of the stream, so usage from a\n // trailing usage-only chunk (`choices: []`) is included.\n let finished:\n | { model: string; finishReason: 'tool_calls' | 'length' | 'stop' }\n | undefined\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 if (chunk.usage) {\n aguiState.usage = {\n promptTokens: chunk.usage.prompt_tokens || 0,\n completionTokens: chunk.usage.completion_tokens || 0,\n totalTokens: chunk.usage.total_tokens || 0,\n ...mistralCachedTokens(chunk.usage),\n }\n }\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 let index = toolCallDelta.index ?? i\n // Mistral can send each parallel call whole with the same `index`\n // (the SDK fills a missing one with 0), so an id that differs from\n // the one already in the slot starts a new call. A repeated id goes\n // back to its own slot.\n if (toolCallDelta.id) {\n const occupant = toolCallsInProgress.get(index)\n if (occupant?.id && occupant.id !== toolCallDelta.id) {\n const sameId = [...toolCallsInProgress].find(\n ([, call]) => call.id === toolCallDelta.id,\n )\n if (sameId) {\n index = sameId[0]\n } else {\n while (toolCallsInProgress.has(index)) index += 1\n }\n }\n }\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 hasEmittedRunFinished = true\n finished = { model: chunkModel, finishReason: computedFinishReason }\n }\n }\n\n if (finished) {\n yield asChunk({\n type: 'RUN_FINISHED',\n ...(responseId && { responseId }),\n runId: aguiState.runId,\n threadId: aguiState.threadId,\n model: finished.model,\n timestamp,\n ...(aguiState.usage && { usage: aguiState.usage }),\n finishReason: finished.finishReason,\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 ...(aguiState.usage && { usage: aguiState.usage }),\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 signal: AbortSignal | 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 signal,\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":";;;;;;;;;;;;;AA+DA,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,YACJ,OAAO,WAAW,OAAO,aAAa;CACxC,IA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B;EAAE;EAAQ,GAAG;CAAO,GAAG,KAAK;AAC5D;;;;;;;;;;;;;;AAeA,SAAgB,YAGd,OACA,QAC4B;CAE5B,OAAO,kBAAkB,OADV,wBACiB,GAAQ,MAAM;AAChD"}
|
|
1
|
+
{"version":3,"file":"text.js","names":[],"sources":["../../../src/adapters/text.ts"],"sourcesContent":["import {\n CONTEXT_OVERFLOW_CODE,\n isFileSource,\n unsupportedFileSourceError,\n} from '@tanstack/ai'\nimport { BaseTextAdapter } from '@tanstack/ai/adapters'\nimport { undoNullWidening } from '@tanstack/ai-utils'\nimport { convertToolsToProviderFormat } from '../tools/tool-converter'\nimport { createMistralClient } from '../client/index'\nimport { generateId, getMistralApiKeyFromEnv } 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 TokenUsage,\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 {\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 { MistralClient } from '../client/index'\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: MistralClient\n private readonly rawConfig: MistralClientConfig\n\n constructor(config: MistralTextConfig, model: TModel) {\n super(config, model)\n // The client serves `structuredOutput` (non-streaming). The streaming\n // path uses `fetchRawMistralStream`, which reads partial tool-call\n // argument deltas as they come.\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: string\n threadId: string\n messageId: string\n timestamp: number\n hasEmittedRunStarted: boolean\n usage?: TokenUsage\n } = {\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 options.request?.signal ?? undefined,\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 ...(aguiState.usage && { usage: aguiState.usage }),\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 // The SDK drops its default 30 s timeout when the request has a signal\n // (lib/sdks.js), so keep that timeout next to the caller signal.\n const signal = chatOptions.request?.signal\n const timeoutMs = this.rawConfig.timeoutMs || 30_000\n const params = {\n ...nonStreamParams,\n responseFormat: {\n type: 'json_schema' as const,\n jsonSchema: {\n name: 'structured_output',\n schemaDefinition: jsonSchema,\n strict,\n },\n },\n }\n const response = signal\n ? await client.chat.complete(params, {\n signal:\n timeoutMs > 0\n ? AbortSignal.any([signal, AbortSignal.timeout(timeoutMs)])\n : signal,\n })\n : await client.chat.complete(params)\n\n const usage = response.usage && {\n promptTokens: response.usage.promptTokens ?? 0,\n completionTokens: response.usage.completionTokens ?? 0,\n totalTokens: response.usage.totalTokens ?? 0,\n ...mistralCachedTokens(response.usage),\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). The errors carry the\n // usage, because the provider already billed the tokens.\n const structuredFinishReason = response.choices[0]?.finishReason\n if (structuredFinishReason === 'model_length') {\n throw Object.assign(\n new Error(\n 'mistral.structuredOutput: the response was cut off because the model reached the end of its context window (finish_reason=model_length); shorten the prompt or use a model with a larger context window',\n ),\n { code: CONTEXT_OVERFLOW_CODE },\n usage && { usage },\n )\n }\n if (structuredFinishReason === 'length') {\n throw Object.assign(\n 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 usage && { usage },\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 Object.assign(\n new Error(\n `Failed to parse structured output as JSON. Content: ${textContent.slice(0, 200)}${textContent.length > 200 ? '...' : ''}`,\n ),\n usage && { usage },\n )\n }\n\n return {\n data: undoNullWidening(parsed, nullWideningMap),\n ...(response.id && { responseId: response.id }),\n ...(response.model && { model: response.model }),\n rawText: textContent,\n ...(usage && { usage }),\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 usage?: TokenUsage\n },\n ): AsyncIterable<AdapterYieldChunk> {\n let accumulatedContent = ''\n // RUN_FINISHED waits for the end of the stream, so usage from a\n // trailing usage-only chunk (`choices: []`) is included.\n let finished:\n | { model: string; finishReason: 'tool_calls' | 'length' | 'stop' }\n | undefined\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 if (chunk.usage) {\n aguiState.usage = {\n promptTokens: chunk.usage.prompt_tokens || 0,\n completionTokens: chunk.usage.completion_tokens || 0,\n totalTokens: chunk.usage.total_tokens || 0,\n ...mistralCachedTokens(chunk.usage),\n }\n }\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 let index = toolCallDelta.index ?? i\n // Mistral can send each parallel call whole with the same `index`\n // (the SDK fills a missing one with 0), so an id that differs from\n // the one already in the slot starts a new call. A repeated id goes\n // back to its own slot.\n if (toolCallDelta.id) {\n const occupant = toolCallsInProgress.get(index)\n if (occupant?.id && occupant.id !== toolCallDelta.id) {\n const sameId = [...toolCallsInProgress].find(\n ([, call]) => call.id === toolCallDelta.id,\n )\n if (sameId) {\n index = sameId[0]\n } else {\n while (toolCallsInProgress.has(index)) index += 1\n }\n }\n }\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 === 'model_length') {\n // Not max_tokens. code context_overflow is what withCompaction retries.\n throw Object.assign(\n new Error(\n 'The response was cut off because the model reached the end of its context window.',\n ),\n { code: CONTEXT_OVERFLOW_CODE },\n )\n }\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 // Complete JSON is normalized. Incomplete JSON throws, except\n // on `length`, where the raw args stay and `input` is omitted.\n let parsedInput: unknown\n let parsed = false\n try {\n parsedInput = parseToolCallInput(toolCall, normalizeToolInput)\n parsed = true\n } catch (error) {\n if (finishReason !== 'length') throw error\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 ...(parsed ? { input: parsedInput } : {}),\n })\n }\n }\n\n const computedFinishReason =\n finishReason === 'length'\n ? 'length'\n : finishReason === 'tool_calls' || hasEmittedToolCall\n ? 'tool_calls'\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 hasEmittedRunFinished = true\n finished = { model: chunkModel, finishReason: computedFinishReason }\n }\n }\n\n if (finished) {\n yield asChunk({\n type: 'RUN_FINISHED',\n ...(responseId && { responseId }),\n runId: aguiState.runId,\n threadId: aguiState.threadId,\n model: finished.model,\n timestamp,\n ...(aguiState.usage && { usage: aguiState.usage }),\n finishReason: finished.finishReason,\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 ...(aguiState.usage && { usage: aguiState.usage }),\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 signal: AbortSignal | 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 signal,\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":";;;;;;;;;;;;;AAmEA,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;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,SAAS,KAAA,IAAY,EAAE,MAAM,IAAI,KAAK,IAAI,CAAC;CACrD;CAEF,IAAI,IAAI,SAAS,aAAa;EAC5B,MAAM,OAAgC;GACpC,MAAM;GACN,SAAS,IAAI,WAAW;EAC1B;EACA,IAAI,IAAI,aAAa,IAAI,UAAU,SAAS,GAC1C,KAAK,aAAa,IAAI,UAAU,KAAK,QAAQ;GAC3C,IAAI,GAAG;GACP,MAAM,GAAG,QAAQ;GACjB,UAAU,GAAG;EACf,EAAE;EAEJ,IAAI,IAAI,WAAW,KAAA,GAAW,KAAK,SAAS,IAAI;EAChD,OAAO;CACT;CACA,IAAI,IAAI,SAAS,UAAU,MAAM,QAAQ,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"}
|
package/dist/esm/byok.js
CHANGED
|
@@ -1,11 +1,10 @@
|
|
|
1
1
|
import { defineByokProvider } from "@tanstack/ai/byok";
|
|
2
|
-
|
|
2
|
+
// src/byok.ts
|
|
3
3
|
var mistralByok = defineByokProvider({
|
|
4
4
|
id: "mistral",
|
|
5
5
|
label: "Mistral",
|
|
6
6
|
env: "MISTRAL_API_KEY"
|
|
7
7
|
});
|
|
8
|
-
//#endregion
|
|
9
8
|
export { mistralByok };
|
|
10
9
|
|
|
11
10
|
//# sourceMappingURL=byok.js.map
|
package/dist/esm/client/index.js
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
import { MistralError } from "@mistralai/mistralai/models/errors/mistralerror.js";
|
|
2
2
|
import { SDKError } from "@mistralai/mistralai/models/errors/sdkerror.js";
|
|
3
3
|
import { ConnectionError, RequestAbortedError, RequestTimeoutError, UnexpectedClientError } from "@mistralai/mistralai/models/errors/httpclienterrors.js";
|
|
4
|
-
|
|
4
|
+
// src/client/index.ts
|
|
5
5
|
function chunkToWire(chunk) {
|
|
6
6
|
switch (chunk.type) {
|
|
7
7
|
case "image_url": return {
|
|
@@ -379,7 +379,6 @@ function createMistralClient(config, fetcher) {
|
|
|
379
379
|
embeddings: { create: async (request, options) => embeddingResponseFromWire(await post("v1/embeddings", embeddingRequestToWire(request), options)) }
|
|
380
380
|
};
|
|
381
381
|
}
|
|
382
|
-
//#endregion
|
|
383
382
|
export { HTTPValidationError, chatCompletionRequestToWire, chatCompletionResponseFromWire, createMistralClient, embeddingRequestToWire, embeddingResponseFromWire };
|
|
384
383
|
|
|
385
384
|
//# sourceMappingURL=index.js.map
|
package/dist/esm/index.js
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { MISTRAL_CHAT_MODELS, MISTRAL_EMBEDDING_MODELS, MISTRAL_VERTEX_CHAT_MODELS } from "./model-meta.js";
|
|
2
1
|
import { MistralTextAdapter, createMistralText, mistralText } from "./adapters/text.js";
|
|
3
2
|
import { MistralEmbeddingAdapter, createMistralEmbedding, mistralEmbedding } from "./adapters/embedding.js";
|
|
3
|
+
import { MISTRAL_CHAT_MODELS, MISTRAL_EMBEDDING_MODELS, MISTRAL_VERTEX_CHAT_MODELS } from "./model-meta.js";
|
|
4
4
|
export { MISTRAL_CHAT_MODELS, MISTRAL_EMBEDDING_MODELS, MISTRAL_VERTEX_CHAT_MODELS, MistralEmbeddingAdapter, MistralTextAdapter, createMistralEmbedding, createMistralText, mistralEmbedding, mistralText };
|
package/dist/esm/model-meta.js
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
|
|
1
|
+
// src/model-meta.ts
|
|
2
2
|
var EFFORT_NONE_HIGH = {
|
|
3
3
|
levels: {
|
|
4
4
|
off: "none",
|
|
@@ -316,7 +316,6 @@ var MISTRAL_MODEL_REASONING = {
|
|
|
316
316
|
[MAGISTRAL_MEDIUM_LATEST.name]: MAGISTRAL_MEDIUM_LATEST.reasoning,
|
|
317
317
|
[MAGISTRAL_SMALL_LATEST.name]: MAGISTRAL_SMALL_LATEST.reasoning
|
|
318
318
|
};
|
|
319
|
-
//#endregion
|
|
320
319
|
export { MISTRAL_CHAT_MODELS, MISTRAL_EMBEDDING_MODELS, MISTRAL_MODEL_INPUT_MODALITIES, MISTRAL_MODEL_REASONING, MISTRAL_VERTEX_CHAT_MODELS };
|
|
321
320
|
|
|
322
321
|
//# sourceMappingURL=model-meta.js.map
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import { makeMistralStructuredOutputCompatibleWithMap } from "../utils/schema-converter.js";
|
|
2
|
-
|
|
2
|
+
// src/tools/function-tool.ts
|
|
3
3
|
/**
|
|
4
4
|
* Converts a standard Tool to Mistral ChatCompletionTool format.
|
|
5
5
|
*
|
|
@@ -29,7 +29,6 @@ function convertFunctionToolToAdapterFormat(tool) {
|
|
|
29
29
|
}
|
|
30
30
|
};
|
|
31
31
|
}
|
|
32
|
-
//#endregion
|
|
33
32
|
export { convertFunctionToolToAdapterFormat };
|
|
34
33
|
|
|
35
34
|
//# sourceMappingURL=function-tool.js.map
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import { convertFunctionToolToAdapterFormat } from "./function-tool.js";
|
|
2
|
-
|
|
2
|
+
// src/tools/tool-converter.ts
|
|
3
3
|
/**
|
|
4
4
|
* Converts an array of standard Tools to Mistral-specific format.
|
|
5
5
|
*/
|
|
@@ -8,7 +8,6 @@ function convertToolsToProviderFormat(tools) {
|
|
|
8
8
|
return convertFunctionToolToAdapterFormat(tool);
|
|
9
9
|
});
|
|
10
10
|
}
|
|
11
|
-
//#endregion
|
|
12
11
|
export { convertToolsToProviderFormat };
|
|
13
12
|
|
|
14
13
|
//# sourceMappingURL=tool-converter.js.map
|
package/dist/esm/utils/client.js
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
|
|
1
|
+
// src/utils/client.ts
|
|
2
2
|
/**
|
|
3
3
|
* Gets Mistral API key from environment variables.
|
|
4
4
|
* @throws Error if MISTRAL_API_KEY is not found
|
|
@@ -16,7 +16,6 @@ function getMistralApiKeyFromEnv() {
|
|
|
16
16
|
function generateId(prefix) {
|
|
17
17
|
return `${prefix}-${crypto.randomUUID()}`;
|
|
18
18
|
}
|
|
19
|
-
//#endregion
|
|
20
19
|
export { generateId, getMistralApiKeyFromEnv };
|
|
21
20
|
|
|
22
21
|
//# sourceMappingURL=client.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"client.js","names":[],"sources":["../../../src/utils/client.ts"],"sourcesContent":["export interface MistralClientConfig {\n /** Mistral API key. */\n apiKey: string\n\n /**\n * Base URL for every request. Same option name as the other adapters, so a\n * gateway config can be spread into any of them. Wins over `serverURL` when\n * both are set.\n */\n baseURL?: string\n\n /** Alias of `baseURL`. */\n serverURL?: string\n\n /** Optional request timeout (ms). */\n timeoutMs?: number\n\n /** Optional default headers to include with every request. */\n defaultHeaders?: Record<string, string>\n\n /**\n * Optional Google / Vertex access token. When set, it replaces\n * `apiKey` on the Authorization header.\n */\n getAccessToken?: () => Promise<string>\n\n /**\n * Optional chat completions URL. Vertex uses this for\n * `:rawPredict` and `:streamRawPredict`.\n */\n resolveRequestUrl?: (stream: boolean) => string\n\n /** Optional model id sent on the wire. Vertex uses publisher model ids. */\n requestModel?: string\n}\n\n/**\n * Gets Mistral API key from environment variables.\n * @throws Error if MISTRAL_API_KEY is not found\n */\nexport function getMistralApiKeyFromEnv(): string {\n let key: string | undefined\n\n if (typeof process !== 'undefined' && typeof process.env !== 'undefined') {\n key = process.env.MISTRAL_API_KEY\n } else {\n const g = globalThis as { window?: { env?: Record<string, string> } }\n key = g.window?.env?.MISTRAL_API_KEY\n }\n\n if (!key) {\n throw new Error(\n 'MISTRAL_API_KEY is required. In Node.js set it as an environment variable; in browser environments inject it via window.env.MISTRAL_API_KEY or use the factory function with an explicit API key.',\n )\n }\n\n return key\n}\n\n/**\n * Generates a unique ID with a prefix.\n */\nexport function generateId(prefix: string): string {\n return `${prefix}-${crypto.randomUUID()}`\n}\n"],"mappings":";;;;;AAwCA,SAAgB,0BAAkC;CAChD,IAAI;CAEJ,IAAI,OAAO,YAAY,eAAe,OAAO,QAAQ,QAAQ,aAC3D,MAAM,QAAQ,IAAI;MAGlB,
|
|
1
|
+
{"version":3,"file":"client.js","names":["g"],"sources":["../../../src/utils/client.ts"],"sourcesContent":["export interface MistralClientConfig {\n /** Mistral API key. */\n apiKey: string\n\n /**\n * Base URL for every request. Same option name as the other adapters, so a\n * gateway config can be spread into any of them. Wins over `serverURL` when\n * both are set.\n */\n baseURL?: string\n\n /** Alias of `baseURL`. */\n serverURL?: string\n\n /** Optional request timeout (ms). */\n timeoutMs?: number\n\n /** Optional default headers to include with every request. */\n defaultHeaders?: Record<string, string>\n\n /**\n * Optional Google / Vertex access token. When set, it replaces\n * `apiKey` on the Authorization header.\n */\n getAccessToken?: () => Promise<string>\n\n /**\n * Optional chat completions URL. Vertex uses this for\n * `:rawPredict` and `:streamRawPredict`.\n */\n resolveRequestUrl?: (stream: boolean) => string\n\n /** Optional model id sent on the wire. Vertex uses publisher model ids. */\n requestModel?: string\n}\n\n/**\n * Gets Mistral API key from environment variables.\n * @throws Error if MISTRAL_API_KEY is not found\n */\nexport function getMistralApiKeyFromEnv(): string {\n let key: string | undefined\n\n if (typeof process !== 'undefined' && typeof process.env !== 'undefined') {\n key = process.env.MISTRAL_API_KEY\n } else {\n const g = globalThis as { window?: { env?: Record<string, string> } }\n key = g.window?.env?.MISTRAL_API_KEY\n }\n\n if (!key) {\n throw new Error(\n 'MISTRAL_API_KEY is required. In Node.js set it as an environment variable; in browser environments inject it via window.env.MISTRAL_API_KEY or use the factory function with an explicit API key.',\n )\n }\n\n return key\n}\n\n/**\n * Generates a unique ID with a prefix.\n */\nexport function generateId(prefix: string): string {\n return `${prefix}-${crypto.randomUUID()}`\n}\n"],"mappings":";;;;;AAwCA,SAAgB,0BAAkC;CAChD,IAAI;CAEJ,IAAI,OAAO,YAAY,eAAe,OAAO,QAAQ,QAAQ,aAC3D,MAAM,QAAQ,IAAI;MAGlB,MAAMA,WAAE,QAAQ,KAAK;CAGvB,IAAI,CAAC,KACH,MAAM,IAAI,MACR,mMACF;CAGF,OAAO;AACT;;;;AAKA,SAAgB,WAAW,QAAwB;CACjD,OAAO,GAAG,OAAO,GAAG,OAAO,WAAW;AACxC"}
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
|
|
1
|
+
// src/utils/schema-converter.ts
|
|
2
2
|
/**
|
|
3
3
|
* Convert a schema for Mistral strict mode and record how to invert it.
|
|
4
4
|
*
|
|
@@ -194,7 +194,6 @@ function coerceMistralStrictSchema(schema, originalRequired) {
|
|
|
194
194
|
hasUntrackableAnyOfWidening
|
|
195
195
|
};
|
|
196
196
|
}
|
|
197
|
-
//#endregion
|
|
198
197
|
export { makeMistralStructuredOutputCompatibleWithMap };
|
|
199
198
|
|
|
200
199
|
//# sourceMappingURL=schema-converter.js.map
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
import { makeMistralStructuredOutputCompatibleWithMap } from "./schema-converter.js";
|
|
2
2
|
import { undoNullWidening } from "@tanstack/ai-utils";
|
|
3
|
-
|
|
3
|
+
// src/utils/tool-input-normalizer.ts
|
|
4
4
|
/**
|
|
5
5
|
* Per-request inverse of Mistral optional-null widening. Recomputes maps from
|
|
6
6
|
* each tool's input schema; duplicate names and non-strict schemas are left
|
|
@@ -28,7 +28,6 @@ function createToolInputNormalizer(tools) {
|
|
|
28
28
|
}
|
|
29
29
|
return (toolName, input) => undoNullWidening(input, maps.get(toolName));
|
|
30
30
|
}
|
|
31
|
-
//#endregion
|
|
32
31
|
export { createToolInputNormalizer };
|
|
33
32
|
|
|
34
33
|
//# sourceMappingURL=tool-input-normalizer.js.map
|
package/dist/esm/vertex/auth.js
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
|
|
1
|
+
// src/vertex/auth.ts
|
|
2
2
|
var MistralVertexAuthError = class extends Error {
|
|
3
3
|
constructor(message, options) {
|
|
4
4
|
super(message, options);
|
|
@@ -56,7 +56,6 @@ async function resolveMistralVertexAccessToken(config) {
|
|
|
56
56
|
throw new MistralVertexAuthError("Mistral Vertex could not load a Google access token from Application Default Credentials.", { cause: error });
|
|
57
57
|
}
|
|
58
58
|
}
|
|
59
|
-
//#endregion
|
|
60
59
|
export { MistralVertexAuthError, resolveMistralVertexAccessToken, resolveMistralVertexLocation, resolveMistralVertexModelUrl, resolveMistralVertexProject };
|
|
61
60
|
|
|
62
61
|
//# sourceMappingURL=auth.js.map
|
package/dist/esm/vertex/index.js
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
|
-
import { MISTRAL_VERTEX_CHAT_MODELS } from "../model-meta.js";
|
|
2
1
|
import { MistralTextAdapter } from "../adapters/text.js";
|
|
3
2
|
import { MistralVertexAuthError, resolveMistralVertexAccessToken, resolveMistralVertexLocation, resolveMistralVertexModelUrl, resolveMistralVertexProject } from "./auth.js";
|
|
4
|
-
|
|
3
|
+
import { MISTRAL_VERTEX_CHAT_MODELS } from "../model-meta.js";
|
|
4
|
+
// src/vertex/index.ts
|
|
5
5
|
/**
|
|
6
6
|
* Creates a Mistral chat adapter that talks to Mistral on Vertex AI.
|
|
7
7
|
*
|
|
@@ -20,7 +20,6 @@ function mistralVertexText(model, config = {}) {
|
|
|
20
20
|
defaultHeaders: config.defaultHeaders
|
|
21
21
|
}, model);
|
|
22
22
|
}
|
|
23
|
-
//#endregion
|
|
24
23
|
export { MISTRAL_VERTEX_CHAT_MODELS, MistralVertexAuthError, mistralVertexText, resolveMistralVertexAccessToken, resolveMistralVertexLocation, resolveMistralVertexModelUrl, resolveMistralVertexProject };
|
|
25
24
|
|
|
26
25
|
//# sourceMappingURL=index.js.map
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@tanstack/ai-mistral",
|
|
3
|
-
"version": "1.1.
|
|
3
|
+
"version": "1.1.2",
|
|
4
4
|
"type": "module",
|
|
5
5
|
"description": "Mistral adapter for TanStack AI",
|
|
6
6
|
"author": "",
|
|
@@ -46,14 +46,14 @@
|
|
|
46
46
|
"adapter"
|
|
47
47
|
],
|
|
48
48
|
"devDependencies": {
|
|
49
|
-
"@vitest/coverage-v8": "4.1.
|
|
49
|
+
"@vitest/coverage-v8": "4.1.12",
|
|
50
50
|
"google-auth-library": "^10.5.0",
|
|
51
|
-
"vite": "^8.
|
|
52
|
-
"@tanstack/ai": "1.
|
|
51
|
+
"vite": "^8.3.8",
|
|
52
|
+
"@tanstack/ai": "1.5.0"
|
|
53
53
|
},
|
|
54
54
|
"peerDependencies": {
|
|
55
55
|
"google-auth-library": "^10.5.0",
|
|
56
|
-
"@tanstack/ai": "^1.
|
|
56
|
+
"@tanstack/ai": "^1.5.0"
|
|
57
57
|
},
|
|
58
58
|
"peerDependenciesMeta": {
|
|
59
59
|
"google-auth-library": {
|
package/src/adapters/text.ts
CHANGED
|
@@ -1,4 +1,8 @@
|
|
|
1
|
-
import {
|
|
1
|
+
import {
|
|
2
|
+
CONTEXT_OVERFLOW_CODE,
|
|
3
|
+
isFileSource,
|
|
4
|
+
unsupportedFileSourceError,
|
|
5
|
+
} from '@tanstack/ai'
|
|
2
6
|
import { BaseTextAdapter } from '@tanstack/ai/adapters'
|
|
3
7
|
import { undoNullWidening } from '@tanstack/ai-utils'
|
|
4
8
|
import { convertToolsToProviderFormat } from '../tools/tool-converter'
|
|
@@ -497,7 +501,17 @@ export class MistralTextAdapter<
|
|
|
497
501
|
// A response cut off at the output cap is a truncated JSON document;
|
|
498
502
|
// report it before the parse error (issue #1426). The errors carry the
|
|
499
503
|
// usage, because the provider already billed the tokens.
|
|
500
|
-
|
|
504
|
+
const structuredFinishReason = response.choices[0]?.finishReason
|
|
505
|
+
if (structuredFinishReason === 'model_length') {
|
|
506
|
+
throw Object.assign(
|
|
507
|
+
new Error(
|
|
508
|
+
'mistral.structuredOutput: the response was cut off because the model reached the end of its context window (finish_reason=model_length); shorten the prompt or use a model with a larger context window',
|
|
509
|
+
),
|
|
510
|
+
{ code: CONTEXT_OVERFLOW_CODE },
|
|
511
|
+
usage && { usage },
|
|
512
|
+
)
|
|
513
|
+
}
|
|
514
|
+
if (structuredFinishReason === 'length') {
|
|
501
515
|
throw Object.assign(
|
|
502
516
|
new Error(
|
|
503
517
|
'mistral.structuredOutput: the response was cut off because the maximum token limit was reached (finish_reason=length); raise modelOptions.max_tokens',
|
|
@@ -779,6 +793,15 @@ export class MistralTextAdapter<
|
|
|
779
793
|
}
|
|
780
794
|
|
|
781
795
|
const finishReason = choice.finish_reason
|
|
796
|
+
if (finishReason === 'model_length') {
|
|
797
|
+
// Not max_tokens. code context_overflow is what withCompaction retries.
|
|
798
|
+
throw Object.assign(
|
|
799
|
+
new Error(
|
|
800
|
+
'The response was cut off because the model reached the end of its context window.',
|
|
801
|
+
),
|
|
802
|
+
{ code: CONTEXT_OVERFLOW_CODE },
|
|
803
|
+
)
|
|
804
|
+
}
|
|
782
805
|
if (finishReason) {
|
|
783
806
|
if (finishReason === 'tool_calls' || toolCallsInProgress.size > 0) {
|
|
784
807
|
for (const [, toolCall] of toolCallsInProgress) {
|
|
@@ -791,10 +814,16 @@ export class MistralTextAdapter<
|
|
|
791
814
|
continue
|
|
792
815
|
}
|
|
793
816
|
|
|
794
|
-
|
|
795
|
-
|
|
796
|
-
|
|
797
|
-
|
|
817
|
+
// Complete JSON is normalized. Incomplete JSON throws, except
|
|
818
|
+
// on `length`, where the raw args stay and `input` is omitted.
|
|
819
|
+
let parsedInput: unknown
|
|
820
|
+
let parsed = false
|
|
821
|
+
try {
|
|
822
|
+
parsedInput = parseToolCallInput(toolCall, normalizeToolInput)
|
|
823
|
+
parsed = true
|
|
824
|
+
} catch (error) {
|
|
825
|
+
if (finishReason !== 'length') throw error
|
|
826
|
+
}
|
|
798
827
|
|
|
799
828
|
toolCall.ended = true
|
|
800
829
|
hasEmittedToolCall = true
|
|
@@ -805,16 +834,16 @@ export class MistralTextAdapter<
|
|
|
805
834
|
model: chunkModel,
|
|
806
835
|
timestamp,
|
|
807
836
|
args: toolCall.arguments,
|
|
808
|
-
input: parsedInput,
|
|
837
|
+
...(parsed ? { input: parsedInput } : {}),
|
|
809
838
|
})
|
|
810
839
|
}
|
|
811
840
|
}
|
|
812
841
|
|
|
813
842
|
const computedFinishReason =
|
|
814
|
-
finishReason === '
|
|
815
|
-
? '
|
|
816
|
-
: finishReason === '
|
|
817
|
-
? '
|
|
843
|
+
finishReason === 'length'
|
|
844
|
+
? 'length'
|
|
845
|
+
: finishReason === 'tool_calls' || hasEmittedToolCall
|
|
846
|
+
? 'tool_calls'
|
|
818
847
|
: 'stop'
|
|
819
848
|
|
|
820
849
|
// If the run finished while reasoning was still open (no text or
|