import {z} from 'zod' export type GetApiV1AnalyticsKnowledgeDocumentsTopRetrievedArgs = {kb_id?: (string | null) | undefined, limit?: number | undefined, start_date: string, end_date: string}; export type GetApiV1AnalyticsKnowledgeDocumentsTopRetrievedOptions = {baseUrl: string, APIKeyHeader?: string | undefined, fetch?: typeof fetch | undefined}; export const topRetrievedDocumentRow = z.object({document_id: z.string(), kb_id: z.string(), hit_count: z.number().int(), sum_score: z.number(), avg_score: z.number(), max_score: z.number(), best_rank: z.number().int()}); export const getApiV1AnalyticsKnowledgeDocumentsTopRetrievedResponse = z.array(topRetrievedDocumentRow); 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 }; /** * Top-N most-retrieved documents in a window * * GET /v1/analytics/knowledge/documents/top-retrieved */ export const getApiV1AnalyticsKnowledgeDocumentsTopRetrieved = async (args: GetApiV1AnalyticsKnowledgeDocumentsTopRetrievedArgs, options: GetApiV1AnalyticsKnowledgeDocumentsTopRetrievedOptions) => { const {baseUrl, fetch: fetchFn = fetch, APIKeyHeader} = options ?? {} const query = new URLSearchParams() const headers = new Headers() headers.set('accept', "application/json") if (args.kb_id != null) query.append("kb_id", String(args.kb_id)) if (args.limit != null) query.append("limit", String(args.limit)) if (args.start_date != null) query.append("start_date", String(args.start_date)) if (args.end_date != null) query.append("end_date", String(args.end_date)) if (APIKeyHeader !== undefined) headers.set("x-api-key", APIKeyHeader) const url = `${baseUrl.replace(/\/+$/, '')}/v1/analytics/knowledge/documents/top-retrieved${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(getApiV1AnalyticsKnowledgeDocumentsTopRetrievedResponse, await res.json()) };