import {z} from 'zod' export type CreateApiV1BatchesArgs = {body: {input_file_id: string, endpoint: '/v1/chat/completions' | '/v1/responses' | '/v1/embeddings', completion_window: '24h', metadata?: ({[key: string]: string} | null) | undefined}}; export type CreateApiV1BatchesOptions = {baseUrl?: string | undefined, bearerAuth?: string | undefined, fetch?: typeof fetch | undefined}; export const batch = z.object({id: z.string(), object: z.literal("batch"), endpoint: z.enum(["/v1/chat/completions", "/v1/responses", "/v1/embeddings"]), errors: z.object({object: z.literal("list"), data: z.array(z.object({code: z.string(), message: z.string(), param: z.string().nullable(), line: z.number().nullable()}))}).nullable(), input_file_id: z.string(), completion_window: z.string(), status: z.enum(["validating", "failed", "in_progress", "finalizing", "completed", "expired", "cancelling", "cancelled"]), output_file_id: z.string().nullable(), error_file_id: z.string().nullable(), created_at: z.number(), in_progress_at: z.number().nullable(), expires_at: z.number().nullable(), finalizing_at: z.number().nullable(), completed_at: z.number().nullable(), failed_at: z.number().nullable(), expired_at: z.number().nullable(), cancelling_at: z.number().nullable(), cancelled_at: z.number().nullable(), request_counts: z.object({total: z.number(), completed: z.number(), failed: z.number()}), metadata: z.record(z.string(), z.string()).nullable()}); 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 batch * * POST /v1/batches */ export const createApiV1Batches = async (args: CreateApiV1BatchesArgs, options?: CreateApiV1BatchesOptions) => { const {baseUrl = "https://api.llmgateway.io", 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/batches${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(batch, await res.json()) };