import {z} from 'zod' export type ResponsesOutputTextLogprobTopLogprob = {token: string, bytes: Array, logprob: number} | {[key: string]: unknown}; export type ResponsesOutputTextLogprob = {token: string, bytes: Array, logprob: number, top_logprobs: Array} | {[key: string]: unknown}; export type ResponsesSummary = {text: string, type: 'summary_text'} | {[key: string]: unknown}; export type ResponsesContent = {text: string, type: 'reasoning_text'} | {[key: string]: unknown}; export type CreateResponseRequest = {model: string, input: string | Array<{content: string | Array<{text: string, type: 'input_text', prompt_cache_breakpoint?: ({mode: 'explicit'} | {[key: string]: unknown} | null) | undefined} | {[key: string]: unknown} | {detail: 'low' | 'high' | 'auto' | 'original', type: 'input_image', file_id?: (string | null) | undefined, image_url?: (string | null) | undefined, prompt_cache_breakpoint?: ({mode: 'explicit'} | {[key: string]: unknown} | null) | undefined} | {[key: string]: unknown} | {type: 'input_file', detail?: ('auto' | 'low' | 'high' | null) | undefined, file_data?: (string | null) | undefined, file_id?: (string | null) | undefined, file_url?: (string | null) | undefined, filename?: (string | null) | undefined, prompt_cache_breakpoint?: ({mode: 'explicit'} | {[key: string]: unknown} | null) | undefined} | {[key: string]: unknown}>, role: 'user' | 'assistant' | 'system' | 'developer', phase?: ('commentary' | 'final_answer' | null) | undefined, type?: ('message' | null) | undefined} | {[key: string]: unknown} | {content: Array<{text: string, type: 'input_text', prompt_cache_breakpoint?: ({mode: 'explicit'} | {[key: string]: unknown} | null) | undefined} | {[key: string]: unknown} | {detail: 'low' | 'high' | 'auto' | 'original', type: 'input_image', file_id?: (string | null) | undefined, image_url?: (string | null) | undefined, prompt_cache_breakpoint?: ({mode: 'explicit'} | {[key: string]: unknown} | null) | undefined} | {[key: string]: unknown} | {type: 'input_file', detail?: ('auto' | 'low' | 'high' | null) | undefined, file_data?: (string | null) | undefined, file_id?: (string | null) | undefined, file_url?: (string | null) | undefined, filename?: (string | null) | undefined, prompt_cache_breakpoint?: ({mode: 'explicit'} | {[key: string]: unknown} | null) | undefined} | {[key: string]: unknown}>, role: 'user' | 'system' | 'developer', status?: ('in_progress' | 'completed' | 'incomplete' | null) | undefined, type?: ('message' | null) | undefined} | {[key: string]: unknown} | {id: string, content: Array<{annotations: Array<{file_id: string, filename: string, index: number, type: 'file_citation'} | {[key: string]: unknown} | {end_index: number, start_index: number, title: string, type: 'url_citation', url: string} | {[key: string]: unknown} | {container_id: string, end_index: number, file_id: string, filename: string, start_index: number, type: 'container_file_citation'} | {[key: string]: unknown} | {file_id: string, index: number, type: 'file_path'} | {[key: string]: unknown}>, text: string, type: 'output_text', logprobs?: (Array | null) | undefined} | {[key: string]: unknown} | {refusal: string, type: 'refusal'} | {[key: string]: unknown}>, role: 'assistant', status: 'in_progress' | 'completed' | 'incomplete', type: 'message', phase?: ('commentary' | 'final_answer' | null) | undefined} | {[key: string]: unknown} | {arguments: string, call_id: string, name: string, type: 'function_call', id?: (string | null) | undefined, caller?: ({type: 'direct'} | {[key: string]: unknown} | {caller_id: string, type: 'program'} | {[key: string]: unknown} | null) | undefined, namespace?: (string | null) | undefined, status?: ('in_progress' | 'completed' | 'incomplete' | null) | undefined} | {[key: string]: unknown} | {call_id: string, output: string | Array<{text: string, type: 'input_text', prompt_cache_breakpoint?: ({mode: 'explicit'} | {[key: string]: unknown} | null) | undefined} | {[key: string]: unknown} | {type: 'input_image', detail?: ('low' | 'high' | 'auto' | 'original' | null) | undefined, file_id?: (string | null) | undefined, image_url?: (string | null) | undefined, prompt_cache_breakpoint?: ({mode: 'explicit'} | {[key: string]: unknown} | null) | undefined} | {[key: string]: unknown} | {type: 'input_file', detail?: ('auto' | 'low' | 'high' | null) | undefined, file_data?: (string | null) | undefined, file_id?: (string | null) | undefined, file_url?: (string | null) | undefined, filename?: (string | null) | undefined, prompt_cache_breakpoint?: ({mode: 'explicit'} | {[key: string]: unknown} | null) | undefined} | {[key: string]: unknown}>, type: 'function_call_output', id?: (string | null) | undefined, caller?: ({type: 'direct'} | {[key: string]: unknown} | {caller_id: string, type: 'program'} | {[key: string]: unknown} | null) | undefined, status?: ('in_progress' | 'completed' | 'incomplete' | null) | undefined} | {[key: string]: unknown} | {id: string, summary: Array, type: 'reasoning', content?: (Array | null) | undefined, encrypted_content?: (string | null) | undefined, status?: ('in_progress' | 'completed' | 'incomplete' | null) | undefined} | {[key: string]: unknown}>, instructions?: (string | null) | undefined, parallel_tool_calls?: boolean | undefined, previous_response_id: unknown, truncation?: 'disabled' | undefined, tools?: (Array<{name: string, parameters?: ({[key: string]: unknown} | null) | undefined, strict?: (boolean | null) | undefined, type: 'function', allowed_callers?: (Array<'direct' | 'programmatic'> | null) | undefined, defer_loading?: (boolean | null) | undefined, description?: (string | null) | undefined, output_schema?: ({[key: string]: unknown} | null) | undefined} | {[key: string]: unknown} | {description: string, name: string, tools: Array<{name: string, type: 'function', allowed_callers?: (Array<'direct' | 'programmatic'> | null) | undefined, defer_loading?: (boolean | null) | undefined, description?: (string | null) | undefined, output_schema?: ({[key: string]: unknown} | null) | undefined, parameters: unknown, strict?: (boolean | null) | undefined} | {[key: string]: unknown} | {name: string, type: 'custom', allowed_callers?: (Array<'direct' | 'programmatic'> | null) | undefined, defer_loading?: (boolean | null) | undefined, description?: (string | null) | undefined, format?: ({type: 'text'} | {[key: string]: unknown} | {definition: string, syntax: 'lark' | 'regex', type: 'grammar'} | {[key: string]: unknown} | null) | undefined} | {[key: string]: unknown}>, type: 'namespace'} | {[key: string]: unknown}>) | undefined, tool_choice?: ('none' | 'auto' | 'required' | {name: string, type: 'function'} | {[key: string]: unknown}) | undefined, reasoning?: ({effort?: ('none' | 'minimal' | 'low' | 'medium' | 'high' | 'xhigh' | 'max' | null) | undefined} | null) | undefined, conversation: unknown, prompt: unknown, text?: ({format?: ({type: 'text'} | {[key: string]: unknown} | {name: string, schema: {[key: string]: unknown}, type: 'json_schema', description?: (string | null) | undefined, strict?: (boolean | null) | undefined} | {[key: string]: unknown} | {type: 'json_object'} | {[key: string]: unknown} | null) | undefined, verbosity?: ('low' | 'medium' | 'high' | null) | undefined} | {[key: string]: unknown} | null) | undefined, background?: false | undefined, stream?: boolean | undefined, store?: (false | null) | undefined, max_output_tokens?: (number | null) | undefined, temperature?: (number | null) | undefined, top_p?: (number | null) | undefined, metadata?: ({[key: string]: string} | null) | undefined, prompt_cache_key?: (string | null) | undefined, max_tool_calls?: (number | null) | undefined, moderation: unknown, top_logprobs?: (0 | null) | undefined} | {[key: string]: unknown}; export type CreateApiV1ResponsesArgs = {body: CreateResponseRequest}; export type CreateApiV1ResponsesOptions = {baseUrl?: string | undefined, ApiKey?: string | undefined, fetch?: typeof fetch | undefined}; export const responsesOutputTextLogprobTopLogprob = z.object({token: z.string(), bytes: z.array(z.number().int()), logprob: z.number()}).and(z.record(z.string(), z.unknown())); export const responsesOutputTextLogprob = z.object({token: z.string(), bytes: z.array(z.number().int()), logprob: z.number(), top_logprobs: z.array(responsesOutputTextLogprobTopLogprob)}).and(z.record(z.string(), z.unknown())); export const responsesSummary = z.object({text: z.string(), type: z.literal("summary_text")}).and(z.record(z.string(), z.unknown())); export const responsesContent = z.object({text: z.string(), type: z.literal("reasoning_text")}).and(z.record(z.string(), z.unknown())); export const responsesInputTokensDetails = z.object({cache_write_tokens: z.number().int(), cached_tokens: z.number().int()}).and(z.record(z.string(), z.unknown())); export const responsesOutputTokensDetails = z.object({reasoning_tokens: z.number().int()}).and(z.record(z.string(), z.unknown())); export const createResponseResponse = z.object({id: z.string(), created_at: z.number(), error: z.object({code: z.enum(["server_error", "rate_limit_exceeded", "invalid_prompt", "bio_policy", "vector_store_timeout", "invalid_image", "invalid_image_format", "invalid_base64_image", "invalid_image_url", "image_too_large", "image_too_small", "image_parse_error", "image_content_policy_violation", "invalid_image_mode", "image_file_too_large", "unsupported_image_media_type", "empty_image_file", "failed_to_download_image", "image_file_not_found"]), message: z.string()}).and(z.record(z.string(), z.unknown())).nullable().optional(), incomplete_details: z.object({reason: z.enum(["max_output_tokens", "content_filter"]).nullable().optional()}).and(z.record(z.string(), z.unknown())).nullable().optional(), instructions: z.string().nullable().optional(), metadata: z.record(z.string(), z.string()).nullable().optional(), model: z.string(), object: z.literal("response"), output: z.array(z.union([z.object({id: z.string(), content: z.array(z.union([z.object({annotations: z.array(z.union([z.object({file_id: z.string(), filename: z.string(), index: z.number().int(), type: z.literal("file_citation")}).and(z.record(z.string(), z.unknown())), z.object({end_index: z.number().int(), start_index: z.number().int(), title: z.string(), type: z.literal("url_citation"), url: z.string()}).and(z.record(z.string(), z.unknown())), z.object({container_id: z.string(), end_index: z.number().int(), file_id: z.string(), filename: z.string(), start_index: z.number().int(), type: z.literal("container_file_citation")}).and(z.record(z.string(), z.unknown())), z.object({file_id: z.string(), index: z.number().int(), type: z.literal("file_path")}).and(z.record(z.string(), z.unknown()))])), text: z.string(), type: z.literal("output_text"), logprobs: z.array(responsesOutputTextLogprob).nullable().optional()}).and(z.record(z.string(), z.unknown())), z.object({refusal: z.string(), type: z.literal("refusal")}).and(z.record(z.string(), z.unknown()))])), role: z.literal("assistant"), status: z.enum(["in_progress", "completed", "incomplete"]), type: z.literal("message"), phase: z.enum(["commentary", "final_answer"]).nullable().optional()}).and(z.record(z.string(), z.unknown())), z.object({arguments: z.string(), call_id: z.string(), name: z.string(), type: z.literal("function_call"), id: z.string().nullable().optional(), caller: z.union([z.object({type: z.literal("direct")}).and(z.record(z.string(), z.unknown())), z.object({caller_id: z.string(), type: z.literal("program")}).and(z.record(z.string(), z.unknown()))]).nullable().optional(), namespace: z.string().nullable().optional(), status: z.enum(["in_progress", "completed", "incomplete"]).nullable().optional()}).and(z.record(z.string(), z.unknown())), z.object({id: z.string(), summary: z.array(responsesSummary), type: z.literal("reasoning"), content: z.array(responsesContent).nullable().optional(), encrypted_content: z.string().nullable().optional(), status: z.enum(["in_progress", "completed", "incomplete"]).nullable().optional()}).and(z.record(z.string(), z.unknown()))])), parallel_tool_calls: z.boolean(), temperature: z.number().nullable().optional(), tool_choice: z.union([z.enum(["none", "auto", "required"]), z.object({name: z.string(), type: z.literal("function")}).and(z.record(z.string(), z.unknown()))]), tools: z.array(z.union([z.object({name: z.string(), parameters: z.record(z.string(), z.unknown()).nullable().optional(), strict: z.boolean().nullable().optional(), type: z.literal("function"), allowed_callers: z.array(z.enum(["direct", "programmatic"])).nullable().optional(), defer_loading: z.boolean().nullable().optional(), description: z.string().nullable().optional(), output_schema: z.record(z.string(), z.unknown()).nullable().optional()}).and(z.record(z.string(), z.unknown())), z.object({description: z.string(), name: z.string(), tools: z.array(z.union([z.object({name: z.string(), type: z.literal("function"), allowed_callers: z.array(z.enum(["direct", "programmatic"])).nullable().optional(), defer_loading: z.boolean().nullable().optional(), description: z.string().nullable().optional(), output_schema: z.record(z.string(), z.unknown()).nullable().optional(), parameters: z.unknown(), strict: z.boolean().nullable().optional()}).and(z.record(z.string(), z.unknown())), z.object({name: z.string(), type: z.literal("custom"), allowed_callers: z.array(z.enum(["direct", "programmatic"])).nullable().optional(), defer_loading: z.boolean().nullable().optional(), description: z.string().nullable().optional(), format: z.union([z.object({type: z.literal("text")}).and(z.record(z.string(), z.unknown())), z.object({definition: z.string(), syntax: z.enum(["lark", "regex"]), type: z.literal("grammar")}).and(z.record(z.string(), z.unknown()))]).nullable().optional()}).and(z.record(z.string(), z.unknown()))])), type: z.literal("namespace")}).and(z.record(z.string(), z.unknown()))])), top_p: z.number().nullable().optional(), background: z.boolean().nullable().optional(), completed_at: z.number().nullable().optional(), max_output_tokens: z.number().int().nullable().optional(), max_tool_calls: z.number().int().nullable().optional(), previous_response_id: z.string().nullable().optional(), prompt_cache_key: z.string().nullable().optional(), prompt_cache_retention: z.enum(["in_memory", "24h"]).nullable().optional(), reasoning: z.object({effort: z.enum(["none", "minimal", "low", "medium", "high", "xhigh", "max"]).nullable().optional()}).nullable().optional(), safety_identifier: z.string().nullable().optional(), service_tier: z.enum(["auto", "default", "flex", "scale", "priority"]).nullable().optional(), status: z.enum(["completed", "failed", "in_progress", "cancelled", "queued", "incomplete"]).nullable().optional(), text: z.object({format: z.union([z.object({type: z.literal("text")}).and(z.record(z.string(), z.unknown())), z.object({name: z.string(), schema: z.record(z.string(), z.unknown()), type: z.literal("json_schema"), description: z.string().nullable().optional(), strict: z.boolean().nullable().optional()}).and(z.record(z.string(), z.unknown())), z.object({type: z.literal("json_object")}).and(z.record(z.string(), z.unknown()))]).nullable().optional(), verbosity: z.enum(["low", "medium", "high"]).nullable().optional()}).and(z.record(z.string(), z.unknown())).nullable().optional(), top_logprobs: z.number().int().nullable().optional(), truncation: z.enum(["auto", "disabled"]).nullable().optional(), usage: z.object({input_tokens: z.number().int(), input_tokens_details: responsesInputTokensDetails, output_tokens: z.number().int(), output_tokens_details: responsesOutputTokensDetails, total_tokens: z.number().int()}).and(z.record(z.string(), z.unknown())).nullable().optional(), user: z.string().nullable().optional()}).and(z.record(z.string(), z.unknown())); 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 Response * * POST /v1/responses */ export const createApiV1Responses = async (args: CreateApiV1ResponsesArgs, options?: CreateApiV1ResponsesOptions) => { 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/responses${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(createResponseResponse, await res.json()) };