import {z} from 'zod' export type GetApiApiSearchArgs = {query: string, stream?: boolean | undefined, session_id?: string | undefined, image?: string | undefined, key?: string | undefined}; export type GetApiApiSearchOptions = {baseUrl?: string | undefined, BearerAuth?: string | undefined, fetch?: typeof fetch | undefined}; export const chatResponse = z.object({id: z.string().optional(), object: z.literal("chat.completion").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.literal("assistant").optional(), content: z.string().optional()}).optional(), finish_reason: z.literal("stop").optional()})).optional(), usage: z.object({prompt_tokens: z.number().int().optional(), completion_tokens: z.number().int().optional(), total_tokens: z.number().int().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 }; /** * Search (GET) * * GET /api/search * * Also accepts auth: ApiKeyHeader, ApiKeyQuery */ export const getApiApiSearch = async (args: GetApiApiSearchArgs, options?: GetApiApiSearchOptions) => { const {baseUrl = "https://search.elixpo.com", fetch: fetchFn = fetch, BearerAuth} = 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.stream != null) query.append("stream", String(args.stream)) if (args.session_id != null) query.append("session_id", String(args.session_id)) if (args.image != null) query.append("image", String(args.image)) if (args.key != null) query.append("key", String(args.key)) if (BearerAuth !== undefined) headers.set('authorization', `Bearer ${BearerAuth}`) const url = `${baseUrl.replace(/\/+$/, '')}/api/search${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(chatResponse, await res.json()) };