import {z} from 'zod' export type DocumentURLChunk = {document_name?: (string | null) | undefined, type?: string | undefined, document_url: string}; export type ImageURLChunk = {image_url: {detail?: (string | null) | undefined, url: string} | string, type?: 'image_url' | undefined}; export type OCRRequest = {pages?: (Array | null) | undefined, image_min_size?: (number | null) | undefined, document: DocumentURLChunk | ImageURLChunk, include_image_base64?: (boolean | null) | undefined, image_limit?: (number | null) | undefined, model: string | null, id?: string | undefined}; export type CreateApiOcrArgs = {body: OCRRequest}; export type CreateApiOcrOptions = {baseUrl?: string | undefined, ApiKey?: string | undefined, fetch?: typeof fetch | undefined}; export const oCRImageObject = z.object({bottom_right_x: z.number().int().gte(0).nullable(), bottom_right_y: z.number().int().gte(0).nullable(), image_base64: z.string().nullable().optional(), top_left_y: z.number().int().gte(0).nullable(), id: z.string(), top_left_x: z.number().int().gte(0).nullable()}); export const oCRPageDimensions = z.object({width: z.number().int().gte(0), dpi: z.number().int().gte(0), height: z.number().int().gte(0)}); export const oCRPageObject = z.object({images: z.array(oCRImageObject), markdown: z.string(), index: z.number().int().gte(0), dimensions: oCRPageDimensions}); export const oCRUsageInfo = z.object({pages_processed: z.number().int().gte(0), doc_size_bytes: z.number().int().nullable().optional()}); export const oCRResponse = z.object({pages: z.array(oCRPageObject), model: z.string(), usage_info: oCRUsageInfo}); 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 }; /** * OCR * * POST /ocr */ export const createApiOcr = async (args: CreateApiOcrArgs, options?: CreateApiOcrOptions) => { 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(/\/+$/, '')}/ocr${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(oCRResponse, await res.json()) };