import {z} from 'zod' export type DistanceTypeEnum = 'cosine' | 'l2'; export type QueryRequest = {model?: string | undefined, query: string, tags?: Array | undefined, top_k?: number | undefined, threshold?: number | undefined, distance_type?: DistanceTypeEnum | undefined}; export type CreateApiV1DocumentsQueryArgs = {model?: string | undefined, name?: string | undefined, tag?: string | undefined, body: QueryRequest}; export type CreateApiV1DocumentsQueryOptions = {baseUrl: string, BearerAuth?: string | undefined, fetch?: typeof fetch | undefined}; export const statusEnum = z.enum(["pending", "processing", "available", "deleted", "error"]); export const documentList = z.object({id: z.string(), created_at: z.string(), status: statusEnum, name: z.string().max(255), model: z.string(), chunk_size: z.number().int(), chunk_count: z.number().int(), tags: z.array(z.string()).optional(), error_message: z.string()}); export const queryResultChunk = z.object({document: documentList, chunk_index: z.number().int(), distance: z.number(), content: z.string(), metadata: z.record(z.string(), z.unknown())}); export const paginatedQueryResultChunkList = z.object({results: z.array(queryResultChunk)}); 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 }; /** * POST /v1/documents/query/ */ export const createApiV1DocumentsQuery = async (args: CreateApiV1DocumentsQueryArgs, options: CreateApiV1DocumentsQueryOptions) => { const {baseUrl, 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.model != null) query.append("model", String(args.model)) if (args.name != null) query.append("name", String(args.name)) if (args.tag != null) query.append("tag", String(args.tag)) if (BearerAuth !== undefined) headers.set('authorization', `Bearer ${BearerAuth}`) const url = `${baseUrl.replace(/\/+$/, '')}/v1/documents/query/${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(paginatedQueryResultChunkList, await res.json()) };