import {z} from 'zod' export type CAGSearchRequest = {query: string, top_k?: number | undefined, include_constitution?: boolean | undefined, min_pot_score?: number | undefined}; export type CreateApiPotsPotIdCagSearchArgs = {pot_id: string, body: CAGSearchRequest}; export type CreateApiPotsPotIdCagSearchOptions = {baseUrl: string, fetch?: typeof fetch | undefined}; export const matchDetails = z.object({keyword_score: z.number().gte(0).lte(1), entity_score: z.number().gte(0).lte(1), matched_keywords: z.array(z.string()).optional(), matched_entities: z.array(z.string()).optional()}); export const cAGSearchResultItem = z.object({fact_id: z.string(), content: z.string(), score: z.number().gte(0).lte(1), pot_score: z.number().gte(0).lte(1), level: z.string(), domain: z.string().nullable().optional(), tags: z.array(z.string()).optional(), match_details: matchDetails}); export const cAGSearchData = z.object({results: z.array(cAGSearchResultItem).optional(), total_results: z.number().int().gte(0)}); export const searchConfidence = z.object({match_quality: z.number().gte(0).lte(1), top_score: z.number().gte(0).lte(1), results_count: z.number().int().gte(0), suggestion: z.enum(["sufficient", "consider_rag", "no_match"])}); export const cAGSearchMetadata = z.object({pot_id: z.string(), query: z.string(), retrieval_strategy: z.literal("CAG").optional(), latency_ms: z.number().int().gte(0), cache_status: z.enum(["hit", "miss", "initialized"])}); export const cAGSearchResponse = z.object({data: cAGSearchData, confidence: searchConfidence, metadata: cAGSearchMetadata}); 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 }; /** * CAG keyword/entity search * * POST /pots/{pot_id}/cag/search */ export const createApiPotsPotIdCagSearch = async (args: CreateApiPotsPotIdCagSearchArgs, options: CreateApiPotsPotIdCagSearchOptions) => { const {baseUrl, fetch: fetchFn = fetch} = options ?? {} const query = new URLSearchParams() const headers = new Headers() headers.set('content-type', "application/json") headers.set('accept', "application/json") const url = `${baseUrl.replace(/\/+$/, '')}/pots/${encodeURIComponent(String(args.pot_id))}/cag/search${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(cAGSearchResponse, await res.json()) };