UNPKG

@ai-sdk/mistral

Version:

The **[Mistral provider](https://ai-sdk.dev/providers/ai-sdk-providers/mistral)** for the [AI SDK](https://ai-sdk.dev/docs) contains language model, embedding model, and speech model support for Mistral APIs.

1,154 lines (1,137 loc) 35.6 kB
// src/mistral-provider.ts import { NoSuchModelError } from "@ai-sdk/provider"; import { loadApiKey, withoutTrailingSlash, withUserAgentSuffix } from "@ai-sdk/provider-utils"; // src/mistral-chat-language-model.ts import { combineHeaders, createEventSourceResponseHandler, createJsonResponseHandler, generateId, injectJsonInstructionIntoMessages, isCustomReasoning, mapReasoningToProviderEffort, parseProviderOptions, postJsonToApi, serializeModelOptions, WORKFLOW_SERIALIZE, WORKFLOW_DESERIALIZE } from "@ai-sdk/provider-utils"; import { z as z3 } from "zod/v4"; // src/convert-mistral-usage.ts function convertMistralUsage(usage) { var _a, _b, _c, _d, _e; if (usage == null) { return { inputTokens: { total: void 0, noCache: void 0, cacheRead: void 0, cacheWrite: void 0 }, outputTokens: { total: void 0, text: void 0, reasoning: void 0 }, raw: void 0 }; } const promptTokens = usage.prompt_tokens; const completionTokens = usage.completion_tokens; const cacheReadTokens = (_e = (_d = (_b = usage.num_cached_tokens) != null ? _b : (_a = usage.prompt_tokens_details) == null ? void 0 : _a.cached_tokens) != null ? _d : (_c = usage.prompt_token_details) == null ? void 0 : _c.cached_tokens) != null ? _e : 0; return { inputTokens: { total: promptTokens, noCache: promptTokens - cacheReadTokens, cacheRead: cacheReadTokens || void 0, cacheWrite: void 0 }, outputTokens: { total: completionTokens, text: completionTokens, reasoning: void 0 }, raw: usage }; } // src/convert-to-mistral-chat-messages.ts import { UnsupportedFunctionalityError } from "@ai-sdk/provider"; import { convertToBase64, getTopLevelMediaType, resolveFullMediaType } from "@ai-sdk/provider-utils"; function formatFileUrl({ part }) { if (part.data.type === "url") { return part.data.url.toString(); } if (part.data.type === "data") { return `data:${resolveFullMediaType({ part })};base64,${convertToBase64(part.data.data)}`; } throw new UnsupportedFunctionalityError({ functionality: `file part data type ${part.data.type}` }); } function convertToMistralChatMessages(prompt) { var _a; const messages = []; for (let i = 0; i < prompt.length; i++) { const { role, content } = prompt[i]; const isLastMessage = i === prompt.length - 1; switch (role) { case "system": { messages.push({ role: "system", content }); break; } case "user": { messages.push({ role: "user", content: content.map((part) => { switch (part.type) { case "text": { return { type: "text", text: part.text }; } case "file": { switch (part.data.type) { case "reference": { throw new UnsupportedFunctionalityError({ functionality: "file parts with provider references" }); } case "text": { throw new UnsupportedFunctionalityError({ functionality: "text file parts" }); } case "url": case "data": { const topLevel = getTopLevelMediaType(part.mediaType); if (topLevel === "image") { return { type: "image_url", image_url: formatFileUrl({ part }) }; } else { if (part.data.type === "data") { const fullMediaType = resolveFullMediaType({ part }); if (fullMediaType !== "application/pdf") { throw new UnsupportedFunctionalityError({ functionality: "Only images and PDF file parts are supported" }); } } else if (part.mediaType !== "application/pdf") { throw new UnsupportedFunctionalityError({ functionality: "Only images and PDF file parts are supported" }); } return { type: "document_url", document_url: formatFileUrl({ part }) }; } } } } } }) }); break; } case "assistant": { let text = ""; const toolCalls = []; for (const part of content) { switch (part.type) { case "text": { text += part.text; break; } case "tool-call": { toolCalls.push({ id: part.toolCallId, type: "function", function: { name: part.toolName, arguments: JSON.stringify(part.input) } }); break; } case "reasoning": { text += part.text; break; } default: { throw new Error( `Unsupported content type in assistant message: ${part.type}` ); } } } messages.push({ role: "assistant", content: text, prefix: isLastMessage ? true : void 0, tool_calls: toolCalls.length > 0 ? toolCalls : void 0 }); break; } case "tool": { for (const toolResponse of content) { if (toolResponse.type === "tool-approval-response") { continue; } const output = toolResponse.output; let contentValue; switch (output.type) { case "text": case "error-text": contentValue = output.value; break; case "execution-denied": contentValue = (_a = output.reason) != null ? _a : "Tool call execution denied."; break; case "content": case "json": case "error-json": contentValue = JSON.stringify(output.value); break; } messages.push({ role: "tool", name: toolResponse.toolName, tool_call_id: toolResponse.toolCallId, content: contentValue }); } break; } default: { const _exhaustiveCheck = role; throw new Error(`Unsupported role: ${_exhaustiveCheck}`); } } } return messages; } // src/get-response-metadata.ts function getResponseMetadata({ id, model, created }) { return { id: id != null ? id : void 0, modelId: model != null ? model : void 0, timestamp: created != null ? new Date(created * 1e3) : void 0 }; } // src/map-mistral-finish-reason.ts function mapMistralFinishReason(finishReason) { switch (finishReason) { case "stop": return "stop"; case "length": case "model_length": return "length"; case "tool_calls": return "tool-calls"; default: return "other"; } } // src/mistral-chat-language-model-options.ts import { z } from "zod/v4"; var mistralLanguageModelChatOptions = z.object({ /** * Whether to inject a safety prompt before all conversations. * * Defaults to `false`. */ safePrompt: z.boolean().optional(), documentImageLimit: z.number().optional(), documentPageLimit: z.number().optional(), /** * Whether to use structured outputs. * * @default true */ structuredOutputs: z.boolean().optional(), /** * Whether to use strict JSON schema validation. * * @default false */ strictJsonSchema: z.boolean().optional(), /** * Whether to enable parallel function calling during tool use. * When set to false, the model will use at most one tool per response. * * @default true */ parallelToolCalls: z.boolean().optional(), /** * Controls the reasoning effort for models that support adjustable reasoning. * * - `'high'`: Enable reasoning * - `'none'`: Disable reasoning */ reasoningEffort: z.enum(["high", "none"]).optional() }); // src/mistral-error.ts import { createJsonErrorResponseHandler } from "@ai-sdk/provider-utils"; import { z as z2 } from "zod/v4"; var mistralErrorDataSchema = z2.object({ object: z2.literal("error"), message: z2.string(), type: z2.string(), param: z2.string().nullable(), code: z2.string().nullable() }); var mistralFailedResponseHandler = createJsonErrorResponseHandler({ errorSchema: mistralErrorDataSchema, errorToMessage: (data) => data.message }); // src/mistral-prepare-tools.ts import { UnsupportedFunctionalityError as UnsupportedFunctionalityError2 } from "@ai-sdk/provider"; function prepareTools({ tools, toolChoice }) { tools = (tools == null ? void 0 : tools.length) ? tools : void 0; const toolWarnings = []; if (tools == null) { return { tools: void 0, toolChoice: void 0, toolWarnings }; } const mistralTools = []; for (const tool of tools) { if (tool.type === "provider") { toolWarnings.push({ type: "unsupported", feature: `provider-defined tool ${tool.id}` }); } else { mistralTools.push({ type: "function", function: { name: tool.name, description: tool.description, parameters: tool.inputSchema, ...tool.strict != null ? { strict: tool.strict } : {} } }); } } if (toolChoice == null) { return { tools: mistralTools, toolChoice: void 0, toolWarnings }; } const type = toolChoice.type; switch (type) { case "auto": case "none": return { tools: mistralTools, toolChoice: type, toolWarnings }; case "required": return { tools: mistralTools, toolChoice: "any", toolWarnings }; // mistral does not support tool mode directly, // so we filter the tools and force the tool choice through 'any' case "tool": return { tools: mistralTools.filter( (tool) => tool.function.name === toolChoice.toolName ), toolChoice: "any", toolWarnings }; default: { const _exhaustiveCheck = type; throw new UnsupportedFunctionalityError2({ functionality: `tool choice type: ${_exhaustiveCheck}` }); } } } // src/mistral-chat-language-model.ts var MistralChatLanguageModel = class _MistralChatLanguageModel { constructor(modelId, config) { this.specificationVersion = "v4"; this.supportedUrls = { "application/pdf": [/^https:\/\/.*$/] }; var _a; this.modelId = modelId; this.config = config; this.generateId = (_a = config.generateId) != null ? _a : generateId; } static [WORKFLOW_SERIALIZE](model) { return serializeModelOptions({ modelId: model.modelId, config: model.config }); } static [WORKFLOW_DESERIALIZE](options) { return new _MistralChatLanguageModel(options.modelId, options.config); } get provider() { return this.config.provider; } async getArgs({ prompt, maxOutputTokens, temperature, topP, topK, frequencyPenalty, presencePenalty, reasoning, stopSequences, responseFormat, seed, providerOptions, tools, toolChoice }) { var _a, _b, _c, _d, _e; const warnings = []; const options = (_a = await parseProviderOptions({ provider: "mistral", providerOptions, schema: mistralLanguageModelChatOptions })) != null ? _a : {}; if (topK != null) { warnings.push({ type: "unsupported", feature: "topK" }); } const supportsReasoningEffort = this.modelId === "mistral-small-latest" || this.modelId === "mistral-small-2603" || this.modelId === "mistral-medium-3" || this.modelId === "mistral-medium-3.5"; let resolvedReasoningEffort; if (supportsReasoningEffort) { resolvedReasoningEffort = (_b = options.reasoningEffort) != null ? _b : isCustomReasoning(reasoning) ? reasoning === "none" ? "none" : mapReasoningToProviderEffort({ reasoning, effortMap: { minimal: "high", low: "high", medium: "high", high: "high", xhigh: "high" }, warnings }) : void 0; } else if (isCustomReasoning(reasoning)) { warnings.push({ type: "unsupported", feature: "reasoning", details: "This model does not support reasoning configuration." }); } const structuredOutputs = (_c = options.structuredOutputs) != null ? _c : true; const strictJsonSchema = (_d = options.strictJsonSchema) != null ? _d : false; if ((responseFormat == null ? void 0 : responseFormat.type) === "json" && !(responseFormat == null ? void 0 : responseFormat.schema)) { prompt = injectJsonInstructionIntoMessages({ messages: prompt, schema: responseFormat.schema }); } const baseArgs = { // model id: model: this.modelId, // model specific settings: safe_prompt: options.safePrompt, // standardized settings: max_tokens: maxOutputTokens, temperature, top_p: topP, ...frequencyPenalty != null ? { frequency_penalty: frequencyPenalty } : {}, ...presencePenalty != null ? { presence_penalty: presencePenalty } : {}, stop: stopSequences, random_seed: seed, reasoning_effort: resolvedReasoningEffort, // response format: response_format: (responseFormat == null ? void 0 : responseFormat.type) === "json" ? structuredOutputs && (responseFormat == null ? void 0 : responseFormat.schema) != null ? { type: "json_schema", json_schema: { schema: responseFormat.schema, strict: strictJsonSchema, name: (_e = responseFormat.name) != null ? _e : "response", description: responseFormat.description } } : { type: "json_object" } : void 0, // mistral-specific provider options: document_image_limit: options.documentImageLimit, document_page_limit: options.documentPageLimit, // messages: messages: convertToMistralChatMessages(prompt) }; const { tools: mistralTools, toolChoice: mistralToolChoice, toolWarnings } = prepareTools({ tools, toolChoice }); return { args: { ...baseArgs, tools: mistralTools, tool_choice: mistralToolChoice, ...mistralTools != null && options.parallelToolCalls !== void 0 ? { parallel_tool_calls: options.parallelToolCalls } : {} }, warnings: [...warnings, ...toolWarnings] }; } async doGenerate(options) { var _a, _b, _c; const { args: body, warnings } = await this.getArgs(options); const { responseHeaders, value: response, rawValue: rawResponse } = await postJsonToApi({ url: `${this.config.baseURL}/chat/completions`, headers: combineHeaders((_b = (_a = this.config).headers) == null ? void 0 : _b.call(_a), options.headers), body, failedResponseHandler: mistralFailedResponseHandler, successfulResponseHandler: createJsonResponseHandler( mistralChatResponseSchema ), abortSignal: options.abortSignal, fetch: this.config.fetch }); const choice = response.choices[0]; const content = []; if (choice.message.content != null && Array.isArray(choice.message.content)) { for (const part of choice.message.content) { if (part.type === "thinking") { const reasoningText = extractReasoningContent(part.thinking); if (reasoningText.length > 0) { content.push({ type: "reasoning", text: reasoningText }); } } else if (part.type === "text") { if (part.text.length > 0) { content.push({ type: "text", text: part.text }); } } } } else { const text = extractTextContent(choice.message.content); if (text != null && text.length > 0) { content.push({ type: "text", text }); } } if (choice.message.tool_calls != null) { for (const toolCall of choice.message.tool_calls) { content.push({ type: "tool-call", toolCallId: toolCall.id, toolName: toolCall.function.name, input: toolCall.function.arguments }); } } return { content, finishReason: { unified: mapMistralFinishReason(choice.finish_reason), raw: (_c = choice.finish_reason) != null ? _c : void 0 }, usage: convertMistralUsage(response.usage), request: { body }, response: { ...getResponseMetadata(response), headers: responseHeaders, body: rawResponse }, warnings }; } async doStream(options) { var _a, _b; const { args, warnings } = await this.getArgs(options); const body = { ...args, stream: true }; const { responseHeaders, value: response } = await postJsonToApi({ url: `${this.config.baseURL}/chat/completions`, headers: combineHeaders((_b = (_a = this.config).headers) == null ? void 0 : _b.call(_a), options.headers), body, failedResponseHandler: mistralFailedResponseHandler, successfulResponseHandler: createEventSourceResponseHandler( mistralChatChunkSchema ), abortSignal: options.abortSignal, fetch: this.config.fetch }); let finishReason = { unified: "other", raw: void 0 }; let usage = void 0; let isFirstChunk = true; let activeText = false; let activeReasoningId = null; const generateId2 = this.generateId; return { stream: response.pipeThrough( new TransformStream({ start(controller) { controller.enqueue({ type: "stream-start", warnings }); }, transform(chunk, controller) { if (options.includeRawChunks) { controller.enqueue({ type: "raw", rawValue: chunk.rawValue }); } if (!chunk.success) { controller.enqueue({ type: "error", error: chunk.error }); return; } const value = chunk.value; if (isFirstChunk) { isFirstChunk = false; controller.enqueue({ type: "response-metadata", ...getResponseMetadata(value) }); } if (value.usage != null) { usage = value.usage; } const choice = value.choices[0]; const delta = choice.delta; const textContent = extractTextContent(delta.content); if (delta.content != null && Array.isArray(delta.content)) { for (const part of delta.content) { if (part.type === "thinking") { const reasoningDelta = extractReasoningContent(part.thinking); if (reasoningDelta.length > 0) { if (activeReasoningId == null) { if (activeText) { controller.enqueue({ type: "text-end", id: "0" }); activeText = false; } activeReasoningId = generateId2(); controller.enqueue({ type: "reasoning-start", id: activeReasoningId }); } controller.enqueue({ type: "reasoning-delta", id: activeReasoningId, delta: reasoningDelta }); } } } } if (textContent != null && textContent.length > 0) { if (!activeText) { if (activeReasoningId != null) { controller.enqueue({ type: "reasoning-end", id: activeReasoningId }); activeReasoningId = null; } controller.enqueue({ type: "text-start", id: "0" }); activeText = true; } controller.enqueue({ type: "text-delta", id: "0", delta: textContent }); } if ((delta == null ? void 0 : delta.tool_calls) != null) { for (const toolCall of delta.tool_calls) { const toolCallId = toolCall.id; const toolName = toolCall.function.name; const input = toolCall.function.arguments; controller.enqueue({ type: "tool-input-start", id: toolCallId, toolName }); controller.enqueue({ type: "tool-input-delta", id: toolCallId, delta: input }); controller.enqueue({ type: "tool-input-end", id: toolCallId }); controller.enqueue({ type: "tool-call", toolCallId, toolName, input }); } } if (choice.finish_reason != null) { finishReason = { unified: mapMistralFinishReason(choice.finish_reason), raw: choice.finish_reason }; } }, flush(controller) { if (activeReasoningId != null) { controller.enqueue({ type: "reasoning-end", id: activeReasoningId }); } if (activeText) { controller.enqueue({ type: "text-end", id: "0" }); } controller.enqueue({ type: "finish", finishReason, usage: convertMistralUsage(usage) }); } }) ), request: { body }, response: { headers: responseHeaders } }; } }; function extractReasoningContent(thinking) { return thinking.filter((chunk) => chunk.type === "text").map((chunk) => chunk.text).join(""); } function extractTextContent(content) { if (typeof content === "string") { return content; } if (content == null) { return void 0; } const textContent = []; for (const chunk of content) { const { type } = chunk; switch (type) { case "text": textContent.push(chunk.text); break; case "thinking": case "image_url": case "reference": break; default: { const _exhaustiveCheck = type; throw new Error(`Unsupported type: ${_exhaustiveCheck}`); } } } return textContent.length ? textContent.join("") : void 0; } var mistralContentSchema = z3.union([ z3.string(), z3.array( z3.discriminatedUnion("type", [ z3.object({ type: z3.literal("text"), text: z3.string() }), z3.object({ type: z3.literal("image_url"), image_url: z3.union([ z3.string(), z3.object({ url: z3.string(), detail: z3.string().nullable() }) ]) }), z3.object({ type: z3.literal("reference"), reference_ids: z3.array(z3.union([z3.string(), z3.number()])) }), z3.object({ type: z3.literal("thinking"), thinking: z3.array( z3.object({ type: z3.literal("text"), text: z3.string() }) ) }) ]) ) ]).nullish(); var mistralUsageSchema = z3.object({ prompt_tokens: z3.number(), completion_tokens: z3.number(), total_tokens: z3.number(), num_cached_tokens: z3.number().nullish(), prompt_tokens_details: z3.object({ cached_tokens: z3.number().nullish() }).nullish(), prompt_token_details: z3.object({ cached_tokens: z3.number().nullish() }).nullish() }); var mistralChatResponseSchema = z3.object({ id: z3.string().nullish(), created: z3.number().nullish(), model: z3.string().nullish(), choices: z3.array( z3.object({ message: z3.object({ role: z3.literal("assistant"), content: mistralContentSchema, tool_calls: z3.array( z3.object({ id: z3.string(), function: z3.object({ name: z3.string(), arguments: z3.string() }) }) ).nullish() }), index: z3.number(), finish_reason: z3.string().nullish() }) ), object: z3.literal("chat.completion"), usage: mistralUsageSchema }); var mistralChatChunkSchema = z3.object({ id: z3.string().nullish(), created: z3.number().nullish(), model: z3.string().nullish(), choices: z3.array( z3.object({ delta: z3.object({ role: z3.enum(["assistant"]).optional(), content: mistralContentSchema, tool_calls: z3.array( z3.object({ id: z3.string(), function: z3.object({ name: z3.string(), arguments: z3.string() }) }) ).nullish() }), finish_reason: z3.string().nullish(), index: z3.number() }) ), usage: mistralUsageSchema.nullish() }); // src/mistral-embedding-model.ts import { TooManyEmbeddingValuesForCallError } from "@ai-sdk/provider"; import { combineHeaders as combineHeaders2, createJsonResponseHandler as createJsonResponseHandler2, parseProviderOptions as parseProviderOptions2, postJsonToApi as postJsonToApi2, serializeModelOptions as serializeModelOptions2, WORKFLOW_SERIALIZE as WORKFLOW_SERIALIZE2, WORKFLOW_DESERIALIZE as WORKFLOW_DESERIALIZE2 } from "@ai-sdk/provider-utils"; import { z as z5 } from "zod/v4"; // src/mistral-embedding-model-options.ts import { z as z4 } from "zod/v4"; var mistralEmbeddingModelOptions = z4.object({ /** * Additional metadata to attach to the embedding request. */ metadata: z4.record(z4.string(), z4.any()).optional(), /** * The dimension of the output embeddings when supported by the model. */ outputDimension: z4.number().int().positive().optional(), /** * The data type of the output embeddings when supported by the model. */ outputDtype: z4.enum(["float", "int8", "uint8", "binary", "ubinary"]).optional() }); // src/mistral-embedding-model.ts var MistralEmbeddingModel = class _MistralEmbeddingModel { constructor(modelId, config) { this.specificationVersion = "v4"; this.maxEmbeddingsPerCall = 32; this.supportsParallelCalls = false; this.modelId = modelId; this.config = config; } get provider() { return this.config.provider; } static [WORKFLOW_SERIALIZE2](model) { return serializeModelOptions2({ modelId: model.modelId, config: model.config }); } static [WORKFLOW_DESERIALIZE2](options) { return new _MistralEmbeddingModel(options.modelId, options.config); } async doEmbed({ values, abortSignal, headers, providerOptions }) { var _a, _b, _c; if (values.length > this.maxEmbeddingsPerCall) { throw new TooManyEmbeddingValuesForCallError({ provider: this.provider, modelId: this.modelId, maxEmbeddingsPerCall: this.maxEmbeddingsPerCall, values }); } const mistralOptions = (_a = await parseProviderOptions2({ provider: "mistral", providerOptions, schema: mistralEmbeddingModelOptions })) != null ? _a : {}; const { responseHeaders, value: response, rawValue } = await postJsonToApi2({ url: `${this.config.baseURL}/embeddings`, headers: combineHeaders2((_c = (_b = this.config).headers) == null ? void 0 : _c.call(_b), headers), body: { model: this.modelId, input: values, metadata: mistralOptions.metadata, output_dimension: mistralOptions.outputDimension, output_dtype: mistralOptions.outputDtype, encoding_format: "float" }, failedResponseHandler: mistralFailedResponseHandler, successfulResponseHandler: createJsonResponseHandler2( MistralTextEmbeddingResponseSchema ), abortSignal, fetch: this.config.fetch }); return { warnings: [], embeddings: response.data.map((item) => item.embedding), usage: response.usage ? { tokens: response.usage.prompt_tokens } : void 0, response: { headers: responseHeaders, body: rawValue } }; } }; var MistralTextEmbeddingResponseSchema = z5.object({ data: z5.array(z5.object({ embedding: z5.array(z5.number()) })), usage: z5.object({ prompt_tokens: z5.number() }).nullish() }); // src/mistral-speech-model.ts import { combineHeaders as combineHeaders3, createJsonResponseHandler as createJsonResponseHandler3, parseProviderOptions as parseProviderOptions3, postToApi, serializeModelOptions as serializeModelOptions3, WORKFLOW_DESERIALIZE as WORKFLOW_DESERIALIZE3, WORKFLOW_SERIALIZE as WORKFLOW_SERIALIZE3 } from "@ai-sdk/provider-utils"; import { z as z7 } from "zod/v4"; // src/mistral-speech-model-options.ts import { z as z6 } from "zod/v4"; var mistralSpeechModelOptions = z6.object({ /** * Base64-encoded reference audio for one-off voice cloning. * * When provided, this takes precedence over the standard `voice` option. */ refAudio: z6.string().min(1).optional() }); // src/mistral-speech-model.ts var MistralSpeechModel = class _MistralSpeechModel { constructor(modelId, config) { this.modelId = modelId; this.config = config; this.specificationVersion = "v4"; } static [WORKFLOW_SERIALIZE3](model) { return serializeModelOptions3({ modelId: model.modelId, config: model.config }); } static [WORKFLOW_DESERIALIZE3](options) { return new _MistralSpeechModel(options.modelId, options.config); } get provider() { return this.config.provider; } async getArgs({ text, voice, outputFormat = "mp3", instructions, speed, language, providerOptions }) { const warnings = []; const mistralOptions = await parseProviderOptions3({ provider: "mistral", providerOptions, schema: mistralSpeechModelOptions }); let responseFormat = "mp3"; if (["pcm", "wav", "mp3", "flac", "opus"].includes(outputFormat)) { responseFormat = outputFormat; } else { warnings.push({ type: "unsupported", feature: "outputFormat", details: `Unsupported output format: ${outputFormat}. Using mp3 instead.` }); } if (instructions != null) { warnings.push({ type: "unsupported", feature: "instructions", details: "Mistral speech models do not support the `instructions` option. Use a reference audio clip to guide delivery." }); } if (speed != null) { warnings.push({ type: "unsupported", feature: "speed", details: "Mistral speech models do not support the `speed` option. It was ignored." }); } if (language != null) { warnings.push({ type: "unsupported", feature: "language", details: "Mistral speech models do not support the `language` option. Language is inferred from the input text and voice." }); } const refAudio = mistralOptions == null ? void 0 : mistralOptions.refAudio; const requestBody = { model: this.modelId, input: text, voice_id: refAudio == null ? voice : void 0, ref_audio: refAudio, response_format: responseFormat, stream: false }; const requestBodyValues = { ...requestBody, ref_audio: refAudio == null ? void 0 : "[redacted]" }; return { requestBody, requestBodyValues, warnings }; } async doGenerate(options) { var _a, _b, _c, _d, _e; const currentDate = (_c = (_b = (_a = this.config._internal) == null ? void 0 : _a.currentDate) == null ? void 0 : _b.call(_a)) != null ? _c : /* @__PURE__ */ new Date(); const { requestBody, requestBodyValues, warnings } = await this.getArgs(options); const { value: response, responseHeaders, rawValue: rawResponse } = await postToApi({ url: `${this.config.baseURL}/audio/speech`, headers: combineHeaders3( { "Content-Type": "application/json" }, (_e = (_d = this.config).headers) == null ? void 0 : _e.call(_d), options.headers ), body: { content: JSON.stringify(requestBody), values: requestBodyValues }, failedResponseHandler: mistralFailedResponseHandler, successfulResponseHandler: createJsonResponseHandler3( mistralSpeechResponseSchema ), abortSignal: options.abortSignal, fetch: this.config.fetch }); return { audio: response.audio_data, warnings, request: { body: JSON.stringify(requestBodyValues) }, response: { timestamp: currentDate, modelId: this.modelId, headers: responseHeaders, body: rawResponse } }; } }; var mistralSpeechResponseSchema = z7.object({ audio_data: z7.string() }); // src/version.ts var VERSION = true ? "4.0.14" : "0.0.0-test"; // src/mistral-provider.ts function createMistral(options = {}) { var _a; const baseURL = (_a = withoutTrailingSlash(options.baseURL)) != null ? _a : "https://api.mistral.ai/v1"; const getHeaders = () => withUserAgentSuffix( { Authorization: `Bearer ${loadApiKey({ apiKey: options.apiKey, environmentVariableName: "MISTRAL_API_KEY", description: "Mistral" })}`, ...options.headers }, `ai-sdk/mistral/${VERSION}` ); const createChatModel = (modelId) => new MistralChatLanguageModel(modelId, { provider: "mistral.chat", baseURL, headers: getHeaders, fetch: options.fetch, generateId: options.generateId }); const createEmbeddingModel = (modelId) => new MistralEmbeddingModel(modelId, { provider: "mistral.embedding", baseURL, headers: getHeaders, fetch: options.fetch }); const createSpeechModel = (modelId) => new MistralSpeechModel(modelId, { provider: "mistral.speech", baseURL, headers: getHeaders, fetch: options.fetch }); const provider = function(modelId) { if (new.target) { throw new Error( "The Mistral model function cannot be called with the new keyword." ); } return createChatModel(modelId); }; provider.specificationVersion = "v4"; provider.languageModel = createChatModel; provider.chat = createChatModel; provider.embedding = createEmbeddingModel; provider.embeddingModel = createEmbeddingModel; provider.textEmbedding = createEmbeddingModel; provider.textEmbeddingModel = createEmbeddingModel; provider.speech = createSpeechModel; provider.speechModel = createSpeechModel; provider.imageModel = (modelId) => { throw new NoSuchModelError({ modelId, modelType: "imageModel" }); }; return provider; } var mistral = createMistral(); export { VERSION, createMistral, mistral }; //# sourceMappingURL=index.js.map