import {z} from 'zod' export type WriteOrdering = 'weak' | 'medium' | 'strong'; export type ExtendedPointId = number | string; export type SparseVector = {indices: Array, values: Array}; export type TokenizerType = 'prefix' | 'whitespace' | 'word' | 'multilingual' | 'code'; export type Language = 'arabic' | 'azerbaijani' | 'basque' | 'bengali' | 'catalan' | 'chinese' | 'danish' | 'dutch' | 'english' | 'finnish' | 'french' | 'german' | 'greek' | 'hebrew' | 'hinglish' | 'hungarian' | 'indonesian' | 'italian' | 'japanese' | 'kazakh' | 'nepali' | 'norwegian' | 'portuguese' | 'romanian' | 'russian' | 'slovene' | 'spanish' | 'swedish' | 'tajik' | 'turkish'; export type StopwordsSet = {languages?: (Array | null) | undefined, custom?: (Array | null) | undefined}; export type StopwordsInterface = Language | StopwordsSet; export type Snowball = 'snowball'; export type SnowballLanguage = 'arabic' | 'armenian' | 'danish' | 'dutch' | 'english' | 'finnish' | 'french' | 'german' | 'greek' | 'hungarian' | 'italian' | 'norwegian' | 'portuguese' | 'romanian' | 'russian' | 'spanish' | 'swedish' | 'tamil' | 'turkish'; export type SnowballParams = {type: Snowball, language: SnowballLanguage}; export type NoStemmer = 'none'; export type DisabledStemmerParams = {type: NoStemmer}; export type StemmingAlgorithm = SnowballParams | DisabledStemmerParams; export type Bm25Config = {k?: number | undefined, b?: number | undefined, avg_len?: number | undefined, tokenizer?: TokenizerType | undefined, language?: (string | null) | undefined, lowercase?: (boolean | null) | undefined, ascii_folding?: (boolean | null) | undefined, stopwords?: (StopwordsInterface | unknown) | undefined, stemmer?: (StemmingAlgorithm | unknown) | undefined, min_token_len?: (number | null) | undefined, max_token_len?: (number | null) | undefined}; export type DocumentOptions = {[key: string]: unknown} | Bm25Config; export type Document = {text: string, model: string, options?: (DocumentOptions | unknown) | undefined}; export type Image = {image: string, model: string, options?: ({[key: string]: unknown} | null) | undefined}; export type InferenceObject = {object: unknown, model: string, options?: ({[key: string]: unknown} | null) | undefined}; export type Vector = Array | SparseVector | Array> | Document | Image | InferenceObject; export type BatchVectorStruct = Array> | Array>> | {[key: string]: Array} | Array | Array | Array; export type Payload = {[key: string]: unknown}; export type Batch = {ids: Array, vectors: BatchVectorStruct, payloads?: (Array | null) | undefined}; export type ShardKey = string | number; export type ShardKeyWithFallback = {target: ShardKey, fallback: ShardKey}; export type ShardKeySelector = ShardKey | Array | ShardKeyWithFallback; export type ValueVariants = string | number | boolean; export type MatchValue = {value: ValueVariants}; export type MatchText = {text: string}; export type MatchTextAny = {text_any: string}; export type MatchPhrase = {phrase: string}; export type MatchPrefix = {prefix: string}; export type MatchSubstring = {substring: string}; export type AnyVariants = Array | Array; export type MatchAny = {any: AnyVariants}; export type MatchExcept = {except: AnyVariants}; export type Match = MatchValue | MatchText | MatchTextAny | MatchPhrase | MatchPrefix | MatchSubstring | MatchAny | MatchExcept; export type Range = {lt?: (number | null) | undefined, gt?: (number | null) | undefined, gte?: (number | null) | undefined, lte?: (number | null) | undefined}; export type DatetimeRange = {lt?: (string | null) | undefined, gt?: (string | null) | undefined, gte?: (string | null) | undefined, lte?: (string | null) | undefined}; export type RangeInterface = Range | DatetimeRange; export type GeoPoint = {lon: number, lat: number}; export type GeoBoundingBox = {top_left: GeoPoint, bottom_right: GeoPoint}; export type GeoRadius = {center: GeoPoint, radius: number}; export type GeoLineString = {points: Array}; export type GeoPolygon = {exterior: GeoLineString, interiors?: (Array | null) | undefined}; export type ValuesCount = {lt?: (number | null) | undefined, gt?: (number | null) | undefined, gte?: (number | null) | undefined, lte?: (number | null) | undefined}; export type FieldCondition = {key: string, match?: (Match | unknown) | undefined, range?: (RangeInterface | unknown) | undefined, geo_bounding_box?: (GeoBoundingBox | unknown) | undefined, geo_radius?: (GeoRadius | unknown) | undefined, geo_polygon?: (GeoPolygon | unknown) | undefined, values_count?: (ValuesCount | unknown) | undefined, is_empty?: (boolean | null) | undefined, is_null?: (boolean | null) | undefined}; export type PayloadField = {key: string}; export type IsEmptyCondition = {is_empty: PayloadField}; export type IsNullCondition = {is_null: PayloadField}; export type HasIdCondition = {has_id: Array}; export type HasVectorCondition = {has_vector: string}; export type Slice = {total: number, index: number}; export type SliceCondition = {slice: Slice}; export type Nested = {key: string, filter: Filter}; export type NestedCondition = {nested: Nested}; export type Condition = FieldCondition | IsEmptyCondition | IsNullCondition | HasIdCondition | HasVectorCondition | SliceCondition | NestedCondition | Filter; export type MinShould = {conditions: Array, min_count: number}; export type Filter = {should?: (Condition | Array | unknown) | undefined, min_should?: (MinShould | unknown) | undefined, must?: (Condition | Array | unknown) | undefined, must_not?: (Condition | Array | unknown) | undefined}; export type UpdateMode = 'upsert' | 'insert_only' | 'update_only'; export type PointsBatch = {batch: Batch, shard_key?: (ShardKeySelector | unknown) | undefined, update_filter?: (Filter | unknown) | undefined, update_mode?: (UpdateMode | unknown) | undefined}; export type VectorStruct = Array | Array> | {[key: string]: Vector} | Document | Image | InferenceObject; export type PointStruct = {id: ExtendedPointId, vector: VectorStruct, payload?: (Payload | unknown) | undefined}; export type PointsList = {points: Array, shard_key?: (ShardKeySelector | unknown) | undefined, update_filter?: (Filter | unknown) | undefined, update_mode?: (UpdateMode | unknown) | undefined}; export type PointInsertOperations = PointsBatch | PointsList; export type UpdateApiCollectionsCollectionNamePointsArgs = {collection_name: string, wait?: boolean | undefined, ordering?: WriteOrdering | undefined, timeout?: number | undefined, body: PointInsertOperations}; export type UpdateApiCollectionsCollectionNamePointsOptions = {baseUrl?: string | undefined, apiKey?: string | undefined, fetch?: typeof fetch | undefined}; export const hardwareUsage = z.object({cpu: z.number().int().gte(0), payload_io_read: z.number().int().gte(0), payload_io_write: z.number().int().gte(0), payload_index_io_read: z.number().int().gte(0), payload_index_io_write: z.number().int().gte(0), vector_io_read: z.number().int().gte(0), vector_io_write: z.number().int().gte(0)}); export const modelUsage = z.object({tokens: z.number().int().gte(0)}); export const inferenceUsage = z.object({models: z.record(z.string(), modelUsage)}); export const usage = z.object({hardware: z.union([hardwareUsage, z.unknown()]).optional(), inference: z.union([inferenceUsage, z.unknown()]).optional()}); export const updateStatus = z.enum(["acknowledged", "completed", "wait_timeout"]); export const updateResult = z.object({operation_id: z.number().int().gte(0).nullable().optional(), status: updateStatus}); export const updateApiCollectionsCollectionNamePointsResponse = z.object({usage: z.union([usage, z.unknown()]).optional(), time: z.number().optional(), status: z.string().optional(), result: updateResult.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 }; /** * Upsert points * * PUT /collections/{collection_name}/points * * Also accepts auth: bearerAuth */ export const updateApiCollectionsCollectionNamePoints = async (args: UpdateApiCollectionsCollectionNamePointsArgs, options?: UpdateApiCollectionsCollectionNamePointsOptions) => { const {baseUrl = "http://localhost:6333", 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 (args.wait != null) query.append("wait", String(args.wait)) if (args.ordering != null) query.append("ordering", String(args.ordering)) if (args.timeout != null) query.append("timeout", String(args.timeout)) if (apiKey !== undefined) headers.set("api-key", apiKey) const url = `${baseUrl.replace(/\/+$/, '')}/collections/${encodeURIComponent(String(args.collection_name))}/points${query.size > 0 ? `?${query}` : ''}` const res = await fetchFn(url, {method: "PUT", 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(updateApiCollectionsCollectionNamePointsResponse, await res.json()) };