import {z} from 'zod' export type QueryLogic = 'AND' | 'OR'; export type AppRoutesV3RagKeywordConfig = {logic: QueryLogic, keywords: Array}; export type AppRoutesV3RagDateRange = {from?: (string | null) | undefined, to?: (string | null) | undefined}; export type BodyQueryRagDirectApiV3RagQueryDirectPost = {keyword_config?: (AppRoutesV3RagKeywordConfig | null) | undefined, date_range?: (AppRoutesV3RagDateRange | null) | undefined}; export type CreateApiApiV3RagQueryDirectArgs = {unique_id: string, description: string, search_category: string, body: BodyQueryRagDirectApiV3RagQueryDirectPost}; export type CreateApiApiV3RagQueryDirectOptions = {baseUrl: string, HTTPBearer?: string | undefined, fetch?: typeof fetch | undefined}; export const ragQueryResponse = z.object({type: z.string(), content: z.string(), citations: z.array(z.record(z.string(), z.unknown())), summary: z.string(), is_starred: z.boolean()}); 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 }; /** * Query Rag Direct * * POST /api/v3/rag/query-direct */ export const createApiApiV3RagQueryDirect = async (args: CreateApiApiV3RagQueryDirectArgs, options: CreateApiApiV3RagQueryDirectOptions) => { const {baseUrl, fetch: fetchFn = fetch, HTTPBearer} = options ?? {} const query = new URLSearchParams() const headers = new Headers() headers.set('content-type', "application/json") headers.set('accept', "application/json") if (args.unique_id != null) query.append("unique_id", String(args.unique_id)) if (args.description != null) query.append("description", String(args.description)) if (args.search_category != null) query.append("search_category", String(args.search_category)) if (HTTPBearer !== undefined) headers.set('authorization', `Bearer ${HTTPBearer}`) const url = `${baseUrl.replace(/\/+$/, '')}/api/v3/rag/query-direct${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(ragQueryResponse, await res.json()) };