import {z} from 'zod' export type QueryFilter = {documentIds?: Array | undefined, mimeType?: Array | undefined}; export type GraphEdgeKind = 'knowledge_has_keyword' | 'section_match' | 'document_link' | 'document_summary' | 'hybrid_graph'; export type DocGeoNearJson = {lat: number, lng: number, radiusKm: number}; export type DocGeoFilterJson = {near?: (DocGeoNearJson | null) | undefined, within?: (string | null) | undefined}; export type QueryMode = 'hybrid' | 'vector' | 'bm25' | 'hybrid_graph'; export type QueryRequestJson = {decomposeQuery?: (boolean | null) | undefined, expandGraph?: boolean | undefined, filter?: (QueryFilter | null) | undefined, graphAlpha?: number | undefined, graphDepth?: number | undefined, graphEdges?: Array | undefined, k?: number | undefined, location?: (DocGeoFilterJson | null) | undefined, mode?: QueryMode | undefined, query: string, rrfK?: number | undefined, threshold?: number | undefined, useHyde?: (boolean | null) | undefined, useReranker?: (boolean | null) | undefined, vectorWeight?: number | undefined}; export type CreateApiApiV1ContextIdDocumentsQueryArgs = {context_id: string, body: QueryRequestJson}; export type CreateApiApiV1ContextIdDocumentsQueryOptions = {baseUrl: string, apiKey?: string | undefined, fetch?: typeof fetch | undefined}; export const queryHitChunkJson = z.object({charEnd: z.number().int(), charStart: z.number().int(), document: z.string(), id: z.string(), position: z.number().int(), section: z.string().nullable().optional(), text: z.string()}); export const queryHitDocumentJson = z.object({id: z.string(), source: z.string(), title: z.string()}); export const graphEdgeKind = z.enum(["knowledge_has_keyword", "section_match", "document_link", "document_summary", "hybrid_graph"]); export const graphEvidenceJson = z.object({edgeKind: graphEdgeKind, neighbourLabel: z.string(), weight: z.number()}); export const queryHitJson = z.object({chunk: queryHitChunkJson, document: queryHitDocumentJson, graphEvidence: z.array(graphEvidenceJson).nullable().optional(), graphExpansion: z.unknown(), score: z.number()}); export const queryResponseJson = z.object({queryMs: z.number().int().gte(0), results: z.array(queryHitJson)}); 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 }; /** * Runs a top-k semantic query over the Layer 0 chunks * * POST /api/v1/{context_id}/documents/query */ export const createApiApiV1ContextIdDocumentsQuery = async (args: CreateApiApiV1ContextIdDocumentsQueryArgs, options: CreateApiApiV1ContextIdDocumentsQueryOptions) => { const {baseUrl, fetch: fetchFn = fetch, apiKey} = options ?? {} const query = new URLSearchParams() const headers = new Headers() headers.set('content-type', "application/json") headers.set('accept', "application/json") if (apiKey !== undefined) headers.set('authorization', `Bearer ${apiKey}`) const url = `${baseUrl.replace(/\/+$/, '')}/api/v1/${encodeURIComponent(String(args.context_id))}/documents/query${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(queryResponseJson, await res.json()) };