import {z} from 'zod' export type BatchRequest = {custom_id?: (string | null) | undefined, body: {[key: string]: unknown}}; export type ApiEndpoint = '/v1/chat/completions' | '/v1/embeddings' | '/v1/fim/completions' | '/v1/moderations' | '/v1/chat/moderations' | '/v1/ocr' | '/v1/classifications' | '/v1/chat/classifications' | '/v1/conversations' | '/v1/audio/transcriptions'; export type CreateBatchJobRequest = {input_files?: (Array | null) | undefined, requests?: (Array | null) | undefined, endpoint: ApiEndpoint, model?: (string | null) | undefined, agent_id?: (string | null) | undefined, metadata?: ({[key: string]: string} | null) | undefined, timeout_hours?: number | undefined}; export type CreateApiV1BatchJobsArgs = {body: CreateBatchJobRequest}; export type CreateApiV1BatchJobsOptions = {baseUrl?: string | undefined, ApiKey?: string | undefined, fetch?: typeof fetch | undefined}; export const batchError = z.object({message: z.string(), count: z.number().int().optional()}); export const batchJobStatus = z.enum(["QUEUED", "RUNNING", "SUCCESS", "FAILED", "TIMEOUT_EXCEEDED", "CANCELLATION_REQUESTED", "CANCELLED"]); export const batchJob = z.object({id: z.string(), object: z.literal("batch").optional(), input_files: z.array(z.string()), metadata: z.record(z.string(), z.unknown()).nullable().optional(), endpoint: z.string(), model: z.string().nullable().optional(), agent_id: z.string().nullable().optional(), output_file: z.string().nullable().optional(), error_file: z.string().nullable().optional(), errors: z.array(batchError), outputs: z.array(z.record(z.string(), z.unknown())).nullable().optional(), status: batchJobStatus, created_at: z.number().int(), total_requests: z.number().int(), completed_requests: z.number().int(), succeeded_requests: z.number().int(), failed_requests: z.number().int(), started_at: z.number().int().nullable().optional(), completed_at: z.number().int().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 Batch Job * * POST /v1/batch/jobs */ export const createApiV1BatchJobs = async (args: CreateApiV1BatchJobsArgs, options?: CreateApiV1BatchJobsOptions) => { 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/batch/jobs${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(batchJob, await res.json()) };