import {z} from 'zod' export type Function = {name: string, description?: string | undefined, strict?: boolean | undefined, parameters: {[key: string]: unknown}}; export type ToolTypes = 'function'; export type Tool = {function: Function, type?: ToolTypes | undefined}; export type JsonSchema = {schema: {[key: string]: unknown}, name: string, description?: (string | null) | undefined, strict?: boolean | undefined}; export type ResponseFormats = 'text' | 'json_object' | 'json_schema'; export type ResponseFormat = {json_schema?: JsonSchema | undefined, type?: ResponseFormats | undefined}; export type Prediction = {type?: string | undefined, content?: string | undefined}; export type TextChunk = {text: string, type?: 'text' | undefined}; export type SystemMessage = {role?: 'system' | undefined, content: string | Array}; export type ImageURLChunk = {image_url: {detail?: (string | null) | undefined, url: string} | string, type?: 'image_url' | undefined}; export type DocumentURLChunk = {document_name?: (string | null) | undefined, type?: string | undefined, document_url: string}; export type ReferenceChunk = {reference_ids: Array, type?: 'reference' | undefined}; export type ContentChunk = TextChunk | ImageURLChunk | DocumentURLChunk | ReferenceChunk; export type UserMessage = {role?: 'user' | undefined, content: string | Array | null}; export type FunctionCall = {name: string, arguments: {[key: string]: unknown} | string}; export type ToolCall = {function: FunctionCall, index?: number | undefined, id?: string | undefined, type?: ToolTypes | undefined}; export type AssistantMessage = {role?: 'assistant' | undefined, prefix?: boolean | undefined, tool_calls?: (Array | null) | undefined, content?: (string | Array | null) | undefined}; export type ToolMessage = {role?: 'tool' | undefined, tool_call_id?: (string | null) | undefined, name?: (string | null) | undefined, content: string | Array | null}; export type FunctionName = {name: string}; export type ChatCompletionRequest = {random_seed?: (number | null) | undefined, safe_prompt?: boolean | undefined, max_tokens?: (number | null) | undefined, presence_penalty?: number | undefined, tools?: (Array | null) | undefined, n?: (number | null) | undefined, top_p?: number | undefined, response_format?: ResponseFormat | undefined, frequency_penalty?: number | undefined, stop?: (string | Array) | undefined, stream?: boolean | undefined, temperature?: (number | null) | undefined, prediction?: Prediction | undefined, messages: Array, tool_choice?: ({function: FunctionName, type?: ToolTypes | undefined} | 'auto' | 'none' | 'any' | 'required') | undefined, model: string}; export type CreateApiChatCompletionsArgs = {body: ChatCompletionRequest}; export type CreateApiChatCompletionsOptions = {baseUrl?: string | undefined, ApiKey?: string | undefined, fetch?: typeof fetch | undefined}; export const usageInfo = z.object({completion_tokens: z.number().int(), prompt_tokens: z.number().int(), total_tokens: z.number().int()}); export const functionCall = z.object({name: z.string(), arguments: z.union([z.record(z.string(), z.unknown()), z.string()])}); export const toolTypes = z.literal("function"); export const toolCall = z.object({function: functionCall, index: z.number().int().optional(), id: z.string().optional(), type: toolTypes.optional()}); export const textChunk = z.object({text: z.string(), type: z.literal("text").optional()}); export const imageURLChunk = z.object({image_url: z.union([z.object({detail: z.string().nullable().optional(), url: z.string()}), z.string()]), type: z.literal("image_url").optional()}); export const documentURLChunk = z.object({document_name: z.string().nullable().optional(), type: z.string().optional(), document_url: z.string()}); export const referenceChunk = z.object({reference_ids: z.array(z.number().int()), type: z.literal("reference").optional()}); export const contentChunk = z.discriminatedUnion("type", [textChunk, imageURLChunk, documentURLChunk, referenceChunk]); export const assistantMessage = z.object({role: z.literal("assistant").optional(), prefix: z.boolean().optional(), tool_calls: z.array(toolCall).nullable().optional(), content: z.union([z.string(), z.array(contentChunk)]).nullable().optional()}); export const chatCompletionChoice = z.object({finish_reason: z.enum(["stop", "length", "model_length", "error", "tool_calls"]), index: z.number().int(), message: assistantMessage}); export const chatCompletionResponse = z.object({usage: usageInfo, model: z.string(), id: z.string(), object: z.string(), created: z.number().int().optional(), choices: z.array(chatCompletionChoice).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 }; /** * Chat Completion * * POST /chat/completions */ export const createApiChatCompletions = async (args: CreateApiChatCompletionsArgs, options?: CreateApiChatCompletionsOptions) => { const {baseUrl = "https://api.mistral.ai/v1", 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(/\/+$/, '')}/chat/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()) };