import {z} from 'zod' export type GetApiAskArgs = {query: string, query_id?: string | undefined, streaming?: boolean | undefined}; export type GetApiAskOptions = {baseUrl?: string | undefined, fetch?: typeof fetch | undefined}; export const nlwebAnswerMeta = z.object({response_type: z.literal("answer"), version: z.literal("0.55"), streaming: z.boolean().optional()}); export const nlwebResult = z.object({url: z.string(), name: z.string(), site: z.string(), score: z.number(), description: z.string(), schema_object: z.record(z.string(), z.unknown())}); export const nlwebAnswer = z.object({query_id: z.string(), _meta: nlwebAnswerMeta, results: z.array(nlwebResult)}); 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 }; /** * Search c15t documentation * * GET /ask */ export const getApiAsk = async (args: GetApiAskArgs, options?: GetApiAskOptions) => { const {baseUrl = "https://c15t.com", fetch: fetchFn = fetch} = options ?? {} const query = new URLSearchParams() const headers = new Headers() headers.set('accept', "application/json") if (args.query != null) query.append("query", String(args.query)) if (args.query_id != null) query.append("query_id", String(args.query_id)) if (args.streaming != null) query.append("streaming", String(args.streaming)) const url = `${baseUrl.replace(/\/+$/, '')}/ask${query.size > 0 ? `?${query}` : ''}` const res = await fetchFn(url, {method: "GET", headers}) if (!res.ok) throw new Error(`Request failed with status ${res.status}`, {cause: {status: res.status, body: await res.text()}}) return validateResponse(nlwebAnswer, await res.json()) };