import {z} from 'zod' export type TextChunk = {type?: 'text' | undefined, text: string}; export type BuiltInConnectors = 'web_search' | 'web_search_premium' | 'code_interpreter' | 'image_generation' | 'document_library' | 'mistral_mcp'; export type ToolReferenceChunk = {type?: 'tool_reference' | undefined, tool: BuiltInConnectors | string, title: string, url?: (string | null) | undefined, favicon?: (string | null) | undefined, description?: (string | null) | undefined}; export type ReferenceChunk = {type?: 'reference' | undefined, reference_ids: Array}; export type ThinkChunk = {type?: 'thinking' | undefined, thinking: Array, signature?: (string | null) | undefined, closed?: boolean | undefined}; export type SystemMessageContentChunks = TextChunk | ThinkChunk; export type SystemMessage = {role?: 'system' | undefined, content: string | Array}; export type ImageDetail = 'low' | 'auto' | 'high'; export type ImageURL = {url: string, detail?: (ImageDetail | null) | undefined}; export type ImageURLChunk = {type?: 'image_url' | undefined, image_url: ImageURL | string}; export type DocumentURLChunk = {type?: 'document_url' | undefined, document_url: string, document_name?: (string | null) | undefined}; export type FileChunk = {type?: 'file' | undefined, file_id: string}; export type AudioChunk = {type?: 'input_audio' | undefined, input_audio: string | string}; export type ResourceChunk = {type?: 'resource' | undefined, uri: string, content: TextChunk | ImageURLChunk}; export type ResourceLinkChunk = {type?: 'resource_link' | undefined, uri: string, metadata?: ({[key: string]: string | number | number | boolean} | null) | undefined}; export type ContentChunk = TextChunk | ImageURLChunk | DocumentURLChunk | ReferenceChunk | FileChunk | ThinkChunk | AudioChunk | ResourceChunk | ResourceLinkChunk; export type UserMessage = {role?: 'user' | undefined, content: string | Array | null}; export type ToolTypes = 'function'; export type FunctionCall = {name: string, arguments: {[key: string]: unknown} | string}; export type ToolCall = {id?: string | undefined, type?: ToolTypes | undefined, function: FunctionCall, index?: number | undefined}; export type AssistantMessage = {role?: 'assistant' | undefined, content?: (string | Array | null) | undefined, tool_calls?: (Array | null) | undefined, prefix?: boolean | undefined}; export type ToolMessage = {role?: 'tool' | undefined, content: string | Array | null, tool_call_id?: (string | null) | undefined, name?: (string | null) | undefined}; export type ResponseFormats = 'text' | 'json_object' | 'json_schema'; export type JsonSchema = {name: string, description?: (string | null) | undefined, schema: {[key: string]: unknown}, strict?: boolean | undefined}; export type ResponseFormat = {type?: ResponseFormats | undefined, json_schema?: (JsonSchema | null) | undefined}; export type Function = {name: string, description?: string | undefined, strict?: boolean | undefined, parameters: {[key: string]: unknown}}; export type Tool = {type?: ToolTypes | undefined, function: Function}; export type ToolConfiguration = {exclude?: (Array | null) | undefined, include?: (Array | null) | undefined, requires_confirmation?: (Array | null) | undefined}; export type ImageGenerationTool = {tool_configuration?: (ToolConfiguration | null) | undefined, type?: 'image_generation' | undefined}; export type DocumentLibraryTool = {tool_configuration?: (ToolConfiguration | null) | undefined, type?: 'document_library' | undefined, library_ids: Array}; export type OAuth2TokenAuth = {type?: 'oauth2-token' | undefined, value: string}; export type APIKeyAuth = {type?: 'api-key' | undefined, value: string}; export type CustomConnector = {type?: 'connector' | undefined, connector_id: string, authorization?: (OAuth2TokenAuth | APIKeyAuth | null) | undefined, tool_configuration?: (ToolConfiguration | null) | undefined}; export type FunctionName = {name: string}; export type ToolChoice = {type?: ToolTypes | undefined, function: FunctionName}; export type ToolChoiceEnum = 'auto' | 'none' | 'any' | 'required'; export type Prediction = {type?: 'content' | undefined, content?: string | undefined}; export type ReasoningEffort = 'none' | 'minimal' | 'low' | 'medium' | 'high' | 'xhigh'; export type MistralPromptMode = 'reasoning'; export type ModerationLLMV1CategoryThresholds = {sexual?: (number | null) | undefined, hate_and_discrimination?: (number | null) | undefined, violence_and_threats?: (number | null) | undefined, dangerous_and_criminal_content?: (number | null) | undefined, selfharm?: (number | null) | undefined, health?: (number | null) | undefined, financial?: (number | null) | undefined, law?: (number | null) | undefined, pii?: (number | null) | undefined}; export type ModerationLLMAction = 'none' | 'block'; export type ModerationLLMV1Config = {model_name?: string | undefined, custom_category_thresholds?: (ModerationLLMV1CategoryThresholds | null) | undefined, ignore_other_categories?: boolean | undefined, action?: ModerationLLMAction | undefined}; export type ModerationLLMV2CategoryThresholds = {sexual?: (number | null) | undefined, hate_and_discrimination?: (number | null) | undefined, violence_and_threats?: (number | null) | undefined, dangerous?: (number | null) | undefined, criminal?: (number | null) | undefined, selfharm?: (number | null) | undefined, health?: (number | null) | undefined, financial?: (number | null) | undefined, law?: (number | null) | undefined, pii?: (number | null) | undefined, jailbreaking?: (number | null) | undefined}; export type ModerationLLMV2Config = {model_name?: string | undefined, custom_category_thresholds?: (ModerationLLMV2CategoryThresholds | null) | undefined, ignore_other_categories?: boolean | undefined, action?: ModerationLLMAction | undefined}; export type GuardrailConfig = {block_on_error?: boolean | undefined, moderation_llm_v1?: (ModerationLLMV1Config | null) | undefined, moderation_llm_v2?: (ModerationLLMV2Config | null) | undefined}; export type RequestedServiceTier = 'auto' | 'standard_only'; export type AgentsCompletionRequest = {max_tokens?: (number | null) | undefined, stream?: boolean | undefined, stop?: (string | Array | null) | undefined, random_seed?: (number | null) | undefined, metadata?: ({[key: string]: unknown} | null) | undefined, messages: Array, response_format?: ResponseFormat | undefined, tools?: (Array | null) | undefined, tool_choice?: (ToolChoice | ToolChoiceEnum) | undefined, presence_penalty?: (number | null) | undefined, frequency_penalty?: (number | null) | undefined, min_tokens?: (number | null) | undefined, repetition_penalty?: (number | null) | undefined, top_k?: (number | null) | undefined, logprobs?: (boolean | null) | undefined, top_logprobs?: (number | null) | undefined, prompt_logprobs?: (boolean | null) | undefined, top_prompt_logprobs?: (number | null) | undefined, n?: (number | null) | undefined, prediction?: Prediction | undefined, parallel_tool_calls?: boolean | undefined, reasoning_effort?: (ReasoningEffort | null) | undefined, prompt_mode?: (MistralPromptMode | null) | undefined, guardrails?: (Array | null) | undefined, prompt_cache_key?: (string | null) | undefined, service_tier?: (RequestedServiceTier | null) | undefined, agent_id: string}; export type CreateApiV1AgentsCompletionsArgs = {body: AgentsCompletionRequest}; export type CreateApiV1AgentsCompletionsOptions = {baseUrl?: string | undefined, ApiKey?: string | undefined, fetch?: typeof fetch | undefined}; export const usageInfo = z.object({prompt_tokens: z.number().int(), completion_tokens: z.number().int(), total_tokens: z.number().int(), prompt_audio_seconds: z.number().int().nullable().optional(), service_tier: z.string().nullable().optional()}); export const textChunk = z.object({type: z.literal("text").optional(), text: z.string()}); export const imageDetail = z.enum(["low", "auto", "high"]); export const imageURL = z.object({url: z.string(), detail: imageDetail.nullable().optional()}); export const imageURLChunk = z.object({type: z.literal("image_url").optional(), image_url: z.union([imageURL, z.string()])}); export const documentURLChunk = z.object({type: z.literal("document_url").optional(), document_url: z.string(), document_name: z.string().nullable().optional()}); export const referenceChunk = z.object({type: z.literal("reference").optional(), reference_ids: z.array(z.union([z.number().int(), z.string()]))}); export const fileChunk = z.object({type: z.literal("file").optional(), file_id: z.string()}); export const builtInConnectors = z.enum(["web_search", "web_search_premium", "code_interpreter", "image_generation", "document_library", "mistral_mcp"]); export const toolReferenceChunk = z.object({type: z.literal("tool_reference").optional(), tool: z.union([builtInConnectors, z.string()]), title: z.string(), url: z.string().nullable().optional(), favicon: z.string().nullable().optional(), description: z.string().nullable().optional()}); export const thinkChunk = z.object({type: z.literal("thinking").optional(), thinking: z.array(z.union([textChunk, toolReferenceChunk, referenceChunk])), signature: z.string().nullable().optional(), closed: z.boolean().optional()}); export const audioChunk = z.object({type: z.literal("input_audio").optional(), input_audio: z.union([z.string(), z.string()])}); export const resourceChunk = z.object({type: z.literal("resource").optional(), uri: z.string(), content: z.discriminatedUnion("type", [textChunk, imageURLChunk])}); export const resourceLinkChunk = z.object({type: z.literal("resource_link").optional(), uri: z.string(), metadata: z.record(z.string(), z.union([z.string(), z.number().int(), z.number(), z.boolean()])).nullable().optional()}); export const contentChunk = z.discriminatedUnion("type", [textChunk, imageURLChunk, documentURLChunk, referenceChunk, fileChunk, thinkChunk, audioChunk, resourceChunk, resourceLinkChunk]); export const toolTypes = z.literal("function"); export const functionCall = z.object({name: z.string(), arguments: z.union([z.record(z.string(), z.unknown()), z.string()])}); export const toolCall = z.object({id: z.string().optional(), type: toolTypes.optional(), function: functionCall, index: z.number().int().optional()}); export const assistantMessage = z.object({role: z.literal("assistant").optional(), content: z.union([z.string(), z.array(contentChunk)]).nullable().optional(), tool_calls: z.array(toolCall).nullable().optional(), prefix: z.boolean().optional()}); export const deltaMessage = z.object({role: z.string().nullable().optional(), content: z.union([z.string(), z.array(contentChunk)]).nullable().optional(), tool_calls: z.array(toolCall).nullable().optional(), tool_call_id: z.string().nullable().optional(), index: z.number().int().gte(0).nullable().optional(), metadata: z.record(z.string(), z.unknown()).nullable().optional()}); export const chatCompletionResponseTokenLogprobs = z.object({token: z.string(), logprob: z.number(), bytes: z.array(z.number().int()), token_id: z.number().int()}); export const chatCompletionResponseTokenLogprobsTopK = z.object({token: z.string(), logprob: z.number(), bytes: z.array(z.number().int()), token_id: z.number().int(), top_logprobs: z.array(chatCompletionResponseTokenLogprobs).nullable().optional()}); export const chatCompletionResponseChoiceLogprobs = z.object({content: z.array(chatCompletionResponseTokenLogprobsTopK)}); export const chatCompletionChoice = z.object({index: z.number().int(), message: assistantMessage.optional(), messages: z.array(deltaMessage).optional(), finish_reason: z.enum(["stop", "length", "model_length", "error", "tool_calls"]), logprobs: chatCompletionResponseChoiceLogprobs.nullable().optional(), prompt_logprobs: chatCompletionResponseChoiceLogprobs.nullable().optional()}); export const chatCompletionResponse = z.object({id: z.string(), object: z.string(), model: z.string(), usage: usageInfo, created: z.number().int(), choices: z.array(chatCompletionChoice)}); export const validateResponse = async ( schema: { readonly '~standard': { readonly validate: (value: unknown) => ({ readonly value: Output; readonly issues?: undefined } | { readonly issues: ReadonlyArray<{ readonly message: string; readonly path?: ReadonlyArray | undefined }> }) | Promise<{ readonly value: Output; readonly issues?: undefined } | { readonly issues: ReadonlyArray<{ readonly message: string; readonly path?: ReadonlyArray | undefined }> }> } }, value: unknown ): Promise => { const result = await schema['~standard'].validate(value) if (result.issues !== undefined) { const detail = result.issues .map(({ message, path }) => path?.length ? `${path.map((segment) => String(typeof segment === 'object' ? segment.key : segment)).join('.')}: ${message}` : message ) .join('; ') throw new Error(`Response does not match the schema: ${detail}`, { cause: { issues: result.issues } }) } return result.value }; /** * Agents Completion * * POST /v1/agents/completions */ export const createApiV1AgentsCompletions = async (args: CreateApiV1AgentsCompletionsArgs, options?: CreateApiV1AgentsCompletionsOptions) => { const {baseUrl = "https://api.mistral.ai", fetch: fetchFn = fetch, ApiKey} = options ?? {} const query = new URLSearchParams() const headers = new Headers() headers.set('content-type', "application/json") headers.set('accept', "application/json") if (ApiKey !== undefined) headers.set('authorization', `Bearer ${ApiKey}`) const url = `${baseUrl.replace(/\/+$/, '')}/v1/agents/completions${query.size > 0 ? `?${query}` : ''}` const res = await fetchFn(url, {method: "POST", headers, body: JSON.stringify(args.body)}) if (!res.ok) throw new Error(`Request failed with status ${res.status}`, {cause: {status: res.status, body: await res.text()}}) return validateResponse(chatCompletionResponse, await res.json()) };