import {z} from 'zod' export type ConstraintFuzzyConfig = {constraint_candidates_k: number, constraint_min_score: number, w_jaro_winkler: number, w_jaro: number, w_levenshtein: number, w_contains: number, vector_min_score?: (number | null) | undefined, vector_margin?: (number | null) | undefined}; export type CSPConfig = {use_csp?: boolean | undefined, vector_k?: number | undefined, vector_k_multiplier?: number | undefined, propagation_budget_ms?: number | undefined, max_propagation_rounds?: number | undefined, max_widening_attempts?: number | undefined, widening_min_time_ms?: number | undefined, include_diagnostics?: boolean | undefined, edge_first?: boolean | undefined, allow_path_recovery?: boolean | undefined}; export type IntentMatchOptions = {max_matches: number, max_expansions: number, timeout_ms: number, beam_width?: (number | null) | undefined, response_mode: string, max_evidence: number, max_documents: number, include_raw_properties?: boolean | undefined, candidates_max?: number | undefined, candidates_min_relations?: number | undefined, candidates_include_exact?: boolean | undefined, constraint_fuzzy: ConstraintFuzzyConfig, csp?: (CSPConfig | null) | undefined, query_type?: (string | null) | undefined, cursor?: (string | null) | undefined, page_size?: (number | null) | undefined}; export type NLQExecuteRequest = {query: string, enable_pruning?: boolean | undefined, use_local_intelligence?: boolean | undefined, execute?: boolean | undefined, enrich?: boolean | undefined, enrich_limit?: number | undefined, compact?: boolean | undefined, require_helix_ql?: boolean | undefined, intent_match_options?: (IntentMatchOptions | null) | undefined}; export type CreateApiNlqExecuteArgs = {body: NLQExecuteRequest}; export type CreateApiNlqExecuteOptions = {baseUrl: string, HTTPBearer?: string | undefined, fetch?: typeof fetch | undefined}; export const nLQEvidence = z.object({text: z.string(), source: z.enum(["graph", "vector"]), score: z.number().nullable().optional()}); export const nLQAnswer = z.object({status: z.enum(["answered", "no_match", "no_data"]), source: z.enum(["graph", "vector"]).nullable().optional(), text: z.string(), entities: z.array(z.string()).optional(), evidence: z.array(nLQEvidence).optional(), unresolved: z.array(z.record(z.string(), z.string())).optional()}); export const queryPlanResponse = z.object({query_plan: z.object({}), query_type: z.string(), constraint_embeddings: z.record(z.string(), z.array(z.number())).nullable().optional(), complexity_hints: z.object({}).nullable().optional(), latency_ms: z.number(), helix_ql: z.string().nullable().optional(), entity: z.object({}).nullable().optional(), planner_version: z.string().nullable().optional()}); export const typedVariable = z.object({name: z.string(), type: z.string(), constraint: z.string().nullable().optional()}); export const relationHole = z.object({from_var: z.string(), to_var: z.string(), role: z.string()}); export const intentGraph = z.object({root: typedVariable, goals: z.array(typedVariable), required_relations: z.array(relationHole).optional()}); export const agentBinding = z.object({label: z.string(), canonical_id: z.string().nullable().optional(), entity_name: z.string().nullable().optional()}); export const evidenceItem = z.object({kind: z.string(), text: z.string()}); export const intentMatch = z.object({bindings: z.record(z.string(), agentBinding), documents: z.array(agentBinding).optional(), evidence: z.array(evidenceItem).optional(), match_key: z.string(), raw_bindings: z.object({}).nullable().optional(), raw_documents: z.array(z.unknown()).nullable().optional(), score: z.number().nullable().optional()}); export const intentMatchStats = z.object({matches_emitted: z.number().int(), expansions: z.number().int(), documents_found: z.number().int(), elapsed_ms: z.number().int(), warnings: z.array(z.string()).optional(), constraint_resolution: z.array(z.object({})).optional(), unverified_relations: z.array(z.object({})).optional()}); export const intentMatchesResponse = z.object({success: z.boolean(), matches: z.array(intentMatch).optional(), candidates: z.array(z.object({})).optional(), stats: intentMatchStats, error: z.string().nullable().optional()}); export const searchResultItem = z.object({id: z.string(), score: z.number(), text: z.string(), type: z.string(), metadata: z.record(z.string(), z.string()).nullable().optional(), inferences: z.array(z.string()).nullable().optional()}); export const searchResponse = z.object({results: z.array(searchResultItem).optional(), query_embedding_ms: z.number().int().optional(), search_ms: z.number().int().optional()}); export const nLQExecuteResponse = z.object({answer: nLQAnswer.nullable().optional(), planner: queryPlanResponse.nullable().optional(), executed: z.boolean(), intent_graph: intentGraph.nullable().optional(), intent_matches: intentMatchesResponse.nullable().optional(), rag: searchResponse.nullable().optional(), helixdb_query: z.string().nullable().optional(), chunks: z.array(z.object({})).optional(), unresolved_chunk_ids: z.array(z.string()).optional(), context: z.object({}).optional(), helixdb_result: z.object({}).nullable().optional(), helixdb_error: z.string().nullable().optional(), nlq_status: z.enum(["ok", "degraded", "failed", "not_executed", "no_data"]).optional(), degraded_reasons: z.array(z.string()).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 }; /** * Nlq Execute * * POST /nlq/execute */ export const createApiNlqExecute = async (args: CreateApiNlqExecuteArgs, options: CreateApiNlqExecuteOptions) => { 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(/\/+$/, '')}/nlq/execute${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(nLQExecuteResponse, await res.json()) };