import {z} from 'zod' export type CreateApiExtractionsArgs = {'Idempotency-Key': string, body: BodyInit}; export type CreateApiExtractionsOptions = {baseUrl: string, fetch?: typeof fetch | undefined}; export const pageClassification = z.object({page: z.number().int().gte(1), documentRole: z.enum(["MAIN", "SUPPORTING", "OTHER"]), documentType: z.enum(["FORM", "INVOICE", "CREDIT_NOTE", "REMINDER", "QUOTE", "PRESCRIPTION", "REPORT", "COVER_LETTER", "POWER_OF_ATTORNEY", "OTHER"]).optional(), formId: z.string().max(35).optional(), confidence: z.number().gte(0).lte(1).optional(), evidence: z.string().optional()}); export const extractedField = z.object({value: z.string(), confidence: z.number().gte(0).lte(1).optional(), page: z.number().int().optional(), evidence: z.string().optional()}); export const extractionResponse = z.object({profile: z.string().optional(), documentType: z.string().optional(), pages: z.array(pageClassification).optional(), fields: z.record(z.string(), extractedField).optional(), collections: z.record(z.string(), z.array(z.record(z.string(), extractedField))).optional(), warnings: z.array(z.string()).optional()}); export const extractionJob = z.object({jobId: z.string(), status: z.enum(["PENDING", "RUNNING", "SUCCEEDED", "FAILED"]), submittedAt: z.string().optional(), result: extractionResponse.optional(), error: z.object({code: z.enum(["UNREADABLE_DOCUMENT", "EXTRACTION_FAILED", "INTERNAL_ERROR"]).optional(), message: z.string().optional()}).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 }; /** * Submit the extraction of values from a document (async, vision model, structured output) * * POST /extractions */ export const createApiExtractions = async (args: CreateApiExtractionsArgs, options: CreateApiExtractionsOptions) => { const {baseUrl, fetch: fetchFn = fetch} = options ?? {} const query = new URLSearchParams() const headers = new Headers() headers.set('accept', "application/json") if (args['Idempotency-Key'] != null) headers.set("Idempotency-Key", String(args['Idempotency-Key'])) const url = `${baseUrl.replace(/\/+$/, '')}/extractions${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(extractionJob, await res.json()) };