import {z} from 'zod' export type OCRRequest = {model: string, messages: Array<{role?: string | undefined, content?: (Array<{type?: string | undefined, text?: string | undefined, image_url?: ({url?: string | undefined}) | undefined}>) | undefined}>, max_tokens?: number | undefined, temperature?: number | undefined, top_p?: number | undefined, stream?: boolean | undefined}; export type CreateApiChatCompletionsArgs = {body: OCRRequest}; export type CreateApiChatCompletionsOptions = {baseUrl?: string | undefined, BearerAuth?: string | undefined, fetch?: typeof fetch | undefined}; export const oCRResponse = z.object({id: z.string().optional(), object: z.string().optional(), created: z.number().int().optional(), model: z.string().optional(), choices: z.array(z.object({index: z.number().int().optional(), message: z.object({role: z.string().optional(), content: z.string().optional()}).optional(), finish_reason: 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 }; /** * Extract Text from Images with OCR * * POST /chat/completions */ export const createApiChatCompletions = async (args: CreateApiChatCompletionsArgs, options?: CreateApiChatCompletionsOptions) => { const {baseUrl = "https://platform.qubrid.com/v1", 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(/\/+$/, '')}/chat/completions${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()) };