import {z} from 'zod' export type OCRDocument = {type: 'document_url', document_url: string, image_url?: string | undefined} | {type: 'image_url', document_url?: string | undefined, image_url: string}; export type OCRRequest = {model: string, id?: string | undefined, document: OCRDocument, fallbacks?: Array | undefined, include_image_base64?: boolean | undefined, pages?: Array | undefined, image_limit?: number | undefined, image_min_size?: number | undefined, table_format?: string | undefined, extract_header?: boolean | undefined, extract_footer?: boolean | undefined, confidence_scores_granularity?: ('page' | 'block' | 'word' | 'document') | undefined, bbox_annotation_format?: ({type: 'text' | 'json_object', json_schema?: ({schema?: Record | undefined, name?: string | undefined, strict?: boolean | undefined}) | undefined} | {type: 'json_schema', json_schema: {schema?: Record | undefined, name?: string | undefined, strict?: boolean | undefined}}) | undefined, document_annotation_format?: ({type: 'text' | 'json_object', json_schema?: ({schema?: Record | undefined, name?: string | undefined, strict?: boolean | undefined}) | undefined} | {type: 'json_schema', json_schema: {schema?: Record | undefined, name?: string | undefined, strict?: boolean | undefined}}) | undefined, document_annotation_prompt?: string | undefined}; export type CreateApiV1AsyncOcrArgs = {'x-bf-async-job-result-ttl'?: number | undefined, body: OCRRequest}; export type CreateApiV1AsyncOcrOptions = {baseUrl?: string | undefined, BearerAuth?: string | undefined, fetch?: typeof fetch | undefined}; export const asyncJobStatus = z.enum(["pending", "processing", "completed", "failed"]); export const errorField = z.object({type: z.string().optional(), code: z.string().optional(), message: z.string().optional(), param: z.string().optional(), event_id: z.string().optional()}); export const modelProvider = z.enum(["openai", "azure", "anthropic", "bedrock", "cohere", "vertex", "vllm", "mistral", "ollama", "groq", "sgl", "parasail", "perplexity", "replicate", "cerebras", "deepseek", "gemini", "openrouter", "elevenlabs", "huggingface", "nebius", "xai", "runway", "fireworks"]); export const bifrostErrorExtraFields = z.object({provider: modelProvider.optional(), model_requested: z.string().optional(), request_type: z.string().optional()}); export const bifrostError = z.object({event_id: z.string().optional(), type: z.string().optional(), is_bifrost_error: z.boolean().optional(), status_code: z.number().int().optional(), error: errorField.optional(), extra_fields: bifrostErrorExtraFields.optional()}); export const asyncJobResponse = z.object({id: z.string(), status: asyncJobStatus, expires_at: z.string().optional(), created_at: z.string(), completed_at: z.string().optional(), status_code: z.number().int().optional(), result: z.unknown(), error: bifrostError.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 async OCR job * * POST /v1/async/ocr * * Also accepts auth: BasicAuth, VirtualKeyAuth, ApiKeyAuth */ export const createApiV1AsyncOcr = async (args: CreateApiV1AsyncOcrArgs, options?: CreateApiV1AsyncOcrOptions) => { const {baseUrl = "http://localhost:8080", 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['x-bf-async-job-result-ttl'] != null) headers.set("x-bf-async-job-result-ttl", String(args['x-bf-async-job-result-ttl'])) if (BearerAuth !== undefined) headers.set('authorization', `Bearer ${BearerAuth}`) const url = `${baseUrl.replace(/\/+$/, '')}/v1/async/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(asyncJobResponse, await res.json()) };