import {z} from 'zod' export type Meta = {limit?: number | undefined, page?: number | undefined}; export type VectorSearchRequestSchema = {query: string, db_id?: (string | null) | undefined, knowledge_id?: (string | null) | undefined, vector_db_ids?: (Array | null) | undefined, search_type?: (string | null) | undefined, max_results?: (number | null) | undefined, filters?: ({[key: string]: unknown} | null) | undefined, meta?: (Meta | null) | undefined}; export type CreateApiKnowledgeSearchArgs = {body: VectorSearchRequestSchema}; export type CreateApiKnowledgeSearchOptions = {baseUrl: string, HTTPBearer?: string | undefined, fetch?: typeof fetch | undefined}; export const vectorSearchResult = z.object({id: z.string(), content: z.string(), name: z.string().nullable().optional(), meta_data: z.record(z.string(), z.unknown()).nullable().optional(), usage: z.record(z.string(), z.unknown()).nullable().optional(), reranking_score: z.number().gte(0).lte(1).nullable().optional(), content_id: z.string().nullable().optional(), content_origin: z.string().nullable().optional(), size: z.number().int().gte(0).nullable().optional()}); export const paginationInfo = z.object({page: z.number().int().gte(0).optional(), limit: z.number().int().gte(1).optional(), total_pages: z.number().int().gte(0).optional(), total_count: z.number().int().gte(0).optional(), search_time_ms: z.number().gte(0).optional()}); export const paginatedResponseVectorSearchResult = z.object({data: z.array(vectorSearchResult), meta: paginationInfo}); 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 Knowledge * * POST /knowledge/search */ export const createApiKnowledgeSearch = async (args: CreateApiKnowledgeSearchArgs, options: CreateApiKnowledgeSearchOptions) => { 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 (HTTPBearer !== undefined) headers.set('authorization', `Bearer ${HTTPBearer}`) const url = `${baseUrl.replace(/\/+$/, '')}/knowledge/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(paginatedResponseVectorSearchResult, await res.json()) };