import {z} from 'zod' export type CreateApiV1FilesArgs = {body: BodyInit}; export type CreateApiV1FilesOptions = {baseUrl?: string | undefined, ApiKey?: string | undefined, fetch?: typeof fetch | undefined}; export const filePurpose = z.enum(["fine-tune", "batch", "ocr", "agentic_safety"]); export const sampleType = z.enum(["pretrain", "instruct", "batch_request", "batch_result", "batch_error"]); export const source = z.enum(["upload", "repository", "mistral"]); export const fileVisibility = z.enum(["workspace", "user"]); export const createFileResponse = z.object({id: z.string(), object: z.string(), bytes: z.number().int(), created_at: z.number().int(), filename: z.string(), purpose: filePurpose, sample_type: sampleType, num_lines: z.number().int().nullable().optional(), mimetype: z.string().nullable().optional(), source: source, signature: z.string().nullable().optional(), expires_at: z.number().int().nullable().optional(), visibility: fileVisibility.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 }; /** * Upload File * * POST /v1/files */ export const createApiV1Files = async (args: CreateApiV1FilesArgs, options?: CreateApiV1FilesOptions) => { const {baseUrl = "https://api.mistral.ai", fetch: fetchFn = fetch, ApiKey} = options ?? {} const query = new URLSearchParams() const headers = new Headers() headers.set('accept', "application/json") if (ApiKey !== undefined) headers.set('authorization', `Bearer ${ApiKey}`) const url = `${baseUrl.replace(/\/+$/, '')}/v1/files${query.size > 0 ? `?${query}` : ''}` const res = await fetchFn(url, {method: "POST", headers, body: args.body}) if (!res.ok) throw new Error(`Request failed with status ${res.status}`, {cause: {status: res.status, body: await res.text()}}) return validateResponse(createFileResponse, await res.json()) };