import {z} from 'zod' export type TextChunk = {type?: 'text' | undefined, text: string}; 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 BuiltInConnectors = 'web_search' | 'web_search_premium' | 'code_interpreter' | 'image_generation' | 'document_library' | 'mistral_mcp'; export type ToolFileChunk = {type?: 'tool_file' | undefined, tool: BuiltInConnectors | string, file_id: string, file_name?: (string | null) | undefined, file_type?: (string | null) | undefined}; export type DocumentURLChunk = {type?: 'document_url' | undefined, document_url: string, document_name?: (string | null) | undefined}; 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 MessageInputContentChunks = Array; export type MessageInputEntry = {object?: 'entry' | undefined, type?: 'message.input' | undefined, created_at?: string | undefined, completed_at?: (string | null) | undefined, id?: string | undefined, role: 'assistant' | 'user', content: string | MessageInputContentChunks, prefix?: boolean | undefined}; export type MessageOutputContentChunks = Array; export type MessageOutputEntry = {object?: 'entry' | undefined, type?: 'message.output' | undefined, created_at?: string | undefined, completed_at?: (string | null) | undefined, agent_id?: (string | null) | undefined, model?: (string | null) | undefined, id?: string | undefined, role?: 'assistant' | undefined, content: string | MessageOutputContentChunks}; export type FunctionResultEntry = {object?: 'entry' | undefined, type?: 'function.result' | undefined, created_at?: string | undefined, completed_at?: (string | null) | undefined, id?: string | undefined, tool_call_id: string, result: string}; export type FunctionCallEntryArguments = {[key: string]: unknown} | string; export type FunctionCallEntry = {object?: 'entry' | undefined, type?: 'function.call' | undefined, created_at?: string | undefined, completed_at?: (string | null) | undefined, agent_id?: (string | null) | undefined, model?: (string | null) | undefined, id?: string | undefined, tool_call_id: string, name: string, arguments: FunctionCallEntryArguments, confirmation_status?: ('pending' | 'allowed' | 'denied' | null) | undefined}; export type ToolExecutionInfo = {[key: string]: unknown}; export type ToolExecutionEntry = {object?: 'entry' | undefined, type?: 'tool.execution' | undefined, created_at?: string | undefined, completed_at?: (string | null) | undefined, agent_id?: (string | null) | undefined, model?: (string | null) | undefined, id?: string | undefined, name: BuiltInConnectors | string, arguments: string, info?: ToolExecutionInfo | undefined}; export type AgentHandoffEntry = {object?: 'entry' | undefined, type?: 'agent.handoff' | undefined, created_at?: string | undefined, completed_at?: (string | null) | undefined, id?: string | undefined, previous_agent_id: string, previous_agent_name: string, next_agent_id: string, next_agent_name: string}; export type InputEntries = Array; export type ConversationInputs = string | InputEntries; export type Function = {name: string, description?: string | undefined, strict?: boolean | undefined, parameters: {[key: string]: unknown}}; export type FunctionTool = {type?: 'function' | undefined, function: Function}; export type ToolConfiguration = {exclude?: (Array | null) | undefined, include?: (Array | null) | undefined, requires_confirmation?: (Array | null) | undefined}; export type WebSearchTool = {tool_configuration?: (ToolConfiguration | null) | undefined, type?: 'web_search' | undefined}; export type WebSearchPremiumTool = {tool_configuration?: (ToolConfiguration | null) | undefined, type?: 'web_search_premium' | undefined}; export type CodeInterpreterTool = {tool_configuration?: (ToolConfiguration | null) | undefined, type?: 'code_interpreter' | 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 CompletionArgsStop = string | Array | null; export type Prediction = {type?: 'content' | undefined, content?: string | 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 ToolChoiceEnum = 'auto' | 'none' | 'any' | 'required'; export type ReasoningEffort = 'none' | 'minimal' | 'low' | 'medium' | 'high' | 'xhigh'; export type CompletionArgs = {stop?: CompletionArgsStop | undefined, presence_penalty?: (number | null) | undefined, frequency_penalty?: (number | null) | undefined, temperature?: (number | null) | undefined, top_p?: (number | null) | undefined, max_tokens?: (number | null) | undefined, random_seed?: (number | null) | undefined, prediction?: (Prediction | null) | undefined, response_format?: (ResponseFormat | null) | undefined, tool_choice?: ToolChoiceEnum | undefined, reasoning_effort?: (ReasoningEffort | null) | undefined}; 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 MetadataDict = {[key: string]: unknown}; export type ConversationRequest = {inputs: ConversationInputs, stream?: (false | null) | undefined, store?: (boolean | null) | undefined, handoff_execution?: ('client' | 'server' | null) | undefined, instructions?: (string | null) | undefined, tools?: (Array | null) | undefined, completion_args?: (CompletionArgs | null) | undefined, guardrails?: (Array | null) | undefined, name?: (string | null) | undefined, description?: (string | null) | undefined, metadata?: (MetadataDict | null) | undefined, agent_id?: (string | null) | undefined, agent_version?: (string | number | null) | undefined, model?: (string | null) | undefined}; export type CreateApiV1ConversationsArgs = {body: ConversationRequest}; export type CreateApiV1ConversationsOptions = {baseUrl?: string | undefined, ApiKey?: string | undefined, fetch?: typeof fetch | undefined}; 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 builtInConnectors = z.enum(["web_search", "web_search_premium", "code_interpreter", "image_generation", "document_library", "mistral_mcp"]); export const toolFileChunk = z.object({type: z.literal("tool_file").optional(), tool: z.union([builtInConnectors, z.string()]), file_id: z.string(), file_name: z.string().nullable().optional(), file_type: z.string().nullable().optional()}); export const documentURLChunk = z.object({type: z.literal("document_url").optional(), document_url: z.string(), document_name: z.string().nullable().optional()}); 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 referenceChunk = z.object({type: z.literal("reference").optional(), reference_ids: z.array(z.union([z.number().int(), z.string()]))}); 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 messageOutputContentChunks = z.array(z.union([textChunk, imageURLChunk, toolFileChunk, documentURLChunk, thinkChunk, toolReferenceChunk])); export const messageOutputEntry = z.object({object: z.literal("entry").optional(), type: z.literal("message.output").optional(), created_at: z.string().optional(), completed_at: z.string().nullable().optional(), agent_id: z.string().nullable().optional(), model: z.string().nullable().optional(), id: z.string().optional(), role: z.literal("assistant").optional(), content: z.union([z.string(), messageOutputContentChunks])}); export const toolExecutionInfo = z.record(z.string(), z.unknown()); export const toolExecutionEntry = z.object({object: z.literal("entry").optional(), type: z.literal("tool.execution").optional(), created_at: z.string().optional(), completed_at: z.string().nullable().optional(), agent_id: z.string().nullable().optional(), model: z.string().nullable().optional(), id: z.string().optional(), name: z.union([builtInConnectors, z.string()]), arguments: z.string(), info: toolExecutionInfo.optional()}); export const functionCallEntryArguments = z.union([z.record(z.string(), z.unknown()), z.string()]); export const functionCallEntry = z.object({object: z.literal("entry").optional(), type: z.literal("function.call").optional(), created_at: z.string().optional(), completed_at: z.string().nullable().optional(), agent_id: z.string().nullable().optional(), model: z.string().nullable().optional(), id: z.string().optional(), tool_call_id: z.string(), name: z.string(), arguments: functionCallEntryArguments, confirmation_status: z.enum(["pending", "allowed", "denied"]).nullable().optional()}); export const agentHandoffEntry = z.object({object: z.literal("entry").optional(), type: z.literal("agent.handoff").optional(), created_at: z.string().optional(), completed_at: z.string().nullable().optional(), id: z.string().optional(), previous_agent_id: z.string(), previous_agent_name: z.string(), next_agent_id: z.string(), next_agent_name: z.string()}); export const conversationUsageInfo = z.object({prompt_tokens: z.number().int().optional(), completion_tokens: z.number().int().optional(), total_tokens: z.number().int().optional(), connector_tokens: z.number().int().nullable().optional(), connectors: z.record(z.string(), z.number().int()).nullable().optional()}); export const conversationResponse = z.object({object: z.literal("conversation.response").optional(), conversation_id: z.string(), outputs: z.array(z.union([messageOutputEntry, toolExecutionEntry, functionCallEntry, agentHandoffEntry])), usage: conversationUsageInfo, guardrails: z.array(z.record(z.string(), z.unknown())).nullable().optional()}); 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 }; /** * Create a conversation and append entries to it. * * POST /v1/conversations */ export const createApiV1Conversations = async (args: CreateApiV1ConversationsArgs, options?: CreateApiV1ConversationsOptions) => { 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/conversations${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(conversationResponse, await res.json()) };