import {z} from 'zod' export type VectorEncoding = 'float' | 'base64'; export type IncludeAttributes = boolean | Array; export type DistanceMetric = 'cosine_distance' | 'euclidean_squared'; export type Limit = {total: number, per?: {attributes: Array, limit: number} | undefined}; export type Query = {rank_by: unknown, top_k?: number | undefined, offset?: number | undefined, filters: unknown, include_attributes?: IncludeAttributes | undefined, exclude_attributes?: Array | undefined, aggregate_by?: {[key: string]: unknown} | undefined, group_by?: Array | undefined, compute_attributes?: {[key: string]: unknown} | undefined, distance_metric?: DistanceMetric | undefined, limit?: (number | Limit) | undefined}; export type RerankLimit = {total: number}; export type CreateApiV2NamespacesNamespaceQueryStainlessOverloadMultiQueryArgs = {namespace: string, body: {vector_encoding?: VectorEncoding | undefined, consistency?: ({level: 'strong'} | {level: 'eventual', max_staleness_seconds?: number | undefined}) | undefined, queries: Array, rerank_by: unknown, limit?: (number | RerankLimit) | undefined, offset?: number | undefined}}; export type CreateApiV2NamespacesNamespaceQueryStainlessOverloadMultiQueryOptions = {baseUrl?: string | undefined, bearerAuth?: string | undefined, fetch?: typeof fetch | undefined}; export const aggregationGroup = z.record(z.string(), z.unknown()); export const id = z.union([z.string(), z.string(), z.number().int().gte(0)]); export const vector = z.union([z.array(z.number()), z.string()]); export const row = z.object({id: id, vector: vector.optional()}).and(z.record(z.string(), z.unknown())); export const singleQueryResult = z.object({aggregations: z.record(z.string(), z.unknown()).optional(), aggregation_groups: z.array(aggregationGroup).optional(), rows: z.array(row).optional()}); export const queryPerformance = z.object({cache_hit_ratio: z.number(), cache_temperature: z.string(), server_total_ms: z.number().int().gte(0), query_execution_ms: z.number().int().gte(0), exhaustive_search_count: z.number().int().gte(0), approx_namespace_size: z.number().int().gte(0), embedding_tokens: z.number().int().gte(0).optional(), embedding_ms: z.number().int().gte(0).optional()}); export const queryBilling = z.object({billable_logical_bytes_queried: z.number().int().gte(0), billable_logical_bytes_returned: z.number().int().gte(0)}); export const multiQueryResult = z.object({results: z.array(singleQueryResult), performance: queryPerformance, billing: queryBilling}); 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 }; /** * Issue multiple concurrent queries filter or search documents. * * POST /v2/namespaces/{namespace}/query?stainless_overload=multiQuery */ export const createApiV2NamespacesNamespaceQueryStainlessOverloadMultiQuery = async (args: CreateApiV2NamespacesNamespaceQueryStainlessOverloadMultiQueryArgs, options?: CreateApiV2NamespacesNamespaceQueryStainlessOverloadMultiQueryOptions) => { const {baseUrl = "https://undefined.turbopuffer.com", fetch: fetchFn = fetch, bearerAuth} = options ?? {} const query = new URLSearchParams() const headers = new Headers() headers.set('content-type', "application/json") headers.set('accept', "application/json") if (bearerAuth !== undefined) headers.set('authorization', `Bearer ${bearerAuth}`) const url = `${baseUrl.replace(/\/+$/, '')}/v2/namespaces/${encodeURIComponent(String(args.namespace))}/query?stainless_overload=multiQuery${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(multiQueryResult, await res.json()) };