import {z} from 'zod' export type MessageContentPart = {type: 'text' | 'image_url' | 'video_url', text?: string | undefined, image_url?: ({url: string, detail?: ('low' | 'default' | 'high') | undefined, max_long_side_pixel?: number | undefined}) | undefined, video_url?: ({url: string, detail?: ('low' | 'default' | 'high') | undefined, fps?: number | undefined, max_long_side_pixel?: number | undefined}) | undefined}; export type ToolCall = {id: string, type: 'function', function: {name: string, arguments: string}}; export type Message = {role: 'system' | 'user' | 'assistant' | 'tool', name?: string | undefined, content?: (string | Array) | undefined, tool_calls?: Array | undefined, tool_call_id?: string | undefined}; export type ChatCompletionReq = {model: 'MiniMax-M3.1-Flash' | 'MiniMax-M3', service_tier?: ('standard' | 'priority') | undefined, messages: Array, thinking?: ({type?: ('disabled' | 'adaptive') | undefined}) | undefined, reasoning_effort?: ('low' | 'medium' | 'high' | 'xhigh' | 'max') | undefined, reasoning_split?: boolean | undefined, stream?: boolean | undefined, stream_options?: ({include_usage?: boolean | undefined}) | undefined, max_completion_tokens?: number | undefined, temperature?: number | undefined, top_p?: number | undefined, tools?: (Array<{type: 'function', function: {name: string, description?: string | undefined, parameters: Record}}>) | undefined, max_tokens?: number | undefined}; export type CreateApiV1ChatCompletionsArgs = {'Content-Type': 'application/json', body: ChatCompletionReq}; export type CreateApiV1ChatCompletionsOptions = {baseUrl?: string | undefined, bearerAuth?: string | undefined, fetch?: typeof fetch | undefined}; export const toolCall = z.object({id: z.string(), type: z.literal("function"), function: z.object({name: z.string(), arguments: z.string()})}); export const usage = z.object({total_tokens: z.number().int().optional()}); export const chatCompletionResp = z.object({id: z.string().optional(), choices: z.array(z.object({finish_reason: z.enum(["stop", "length", "content_filter", "tool_calls"]).optional(), index: z.number().int().optional(), message: z.object({content: z.string(), reasoning_content: z.string().optional(), role: z.literal("assistant"), tool_calls: z.array(toolCall).optional()}).optional()})).optional(), created: z.number().int().optional(), model: z.string().optional(), object: z.enum(["chat.completion", "chat.completion.chunk"]).optional(), usage: usage.optional(), input_sensitive: z.boolean().optional(), input_sensitive_type: z.number().int().optional(), output_sensitive: z.boolean().optional(), output_sensitive_type: z.number().int().optional(), base_resp: z.object({status_code: z.number().int().optional(), status_msg: z.string().optional()}).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 }; /** * Text Generation OpenAI * * POST /v1/chat/completions */ export const createApiV1ChatCompletions = async (args: CreateApiV1ChatCompletionsArgs, options?: CreateApiV1ChatCompletionsOptions) => { const {baseUrl = "https://api.minimax.io", fetch: fetchFn = fetch, bearerAuth} = options ?? {} const query = new URLSearchParams() const headers = new Headers() headers.set('content-type', "application/json") headers.set('accept', "application/json") if (args['Content-Type'] != null) headers.set("Content-Type", String(args['Content-Type'])) if (bearerAuth !== undefined) headers.set('authorization', `Bearer ${bearerAuth}`) const url = `${baseUrl.replace(/\/+$/, '')}/v1/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(chatCompletionResp, await res.json()) };