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 CreateApiV1OcrArgs = {body: OCRRequest}; export type CreateApiV1OcrOptions = {baseUrl?: string | undefined, BearerAuth?: string | undefined, fetch?: typeof fetch | undefined}; export const oCRPageImage = z.object({id: z.string(), top_left_x: z.number(), top_left_y: z.number(), bottom_right_x: z.number(), bottom_right_y: z.number(), image_base64: z.string().optional()}); export const oCRPageDimensions = z.object({dpi: z.number().int(), height: z.number().int(), width: z.number().int()}); export const oCRPage = z.object({index: z.number().int().gte(0), markdown: z.string(), images: z.array(oCRPageImage).optional(), dimensions: oCRPageDimensions.optional(), tables: z.array(z.object({})).nullable().optional(), header: z.string().nullable().optional(), footer: z.string().nullable().optional(), confidence_scores: z.object({average_page_confidence_score: z.number().optional(), minimum_page_confidence_score: z.number().optional(), word_confidence_scores: z.array(z.number()).optional()}).nullable().optional()}); export const oCRUsageInfo = z.object({pages_processed: z.number().int(), doc_size_bytes: z.number().int()}); 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 bifrostCacheDebug = z.object({cache_hit: z.boolean().optional(), cache_id: z.string().optional(), hit_type: z.string().optional(), requested_provider: z.string().optional(), requested_model: z.string().optional(), provider_used: z.string().optional(), model_used: z.string().optional(), input_tokens: z.number().int().optional(), threshold: z.number().optional(), similarity: z.number().optional()}); export const bifrostResponseExtraFields = z.object({request_type: z.string().optional(), provider: modelProvider.optional(), model_requested: z.string().optional(), model_deployment: z.string().optional(), latency: z.number().int().optional(), chunk_index: z.number().int().optional(), raw_request: z.object({}).optional(), raw_response: z.object({}).optional(), cache_debug: bifrostCacheDebug.optional()}); export const oCRResponse = z.object({model: z.string(), pages: z.array(oCRPage), usage_info: oCRUsageInfo.optional(), document_annotation: z.string().optional(), extra_fields: bifrostResponseExtraFields.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 }; /** * Perform OCR * * POST /v1/ocr * * Also accepts auth: BasicAuth, VirtualKeyAuth, ApiKeyAuth */ export const createApiV1Ocr = async (args: CreateApiV1OcrArgs, options?: CreateApiV1OcrOptions) => { 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 (BearerAuth !== undefined) headers.set('authorization', `Bearer ${BearerAuth}`) const url = `${baseUrl.replace(/\/+$/, '')}/v1/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()) };