import type { HierarchicalNSW as HierarchicalNSWT, SpaceName } from 'closevector-hnswlib-node'; import { CloseVectorEmbeddings, CloseVectorSaveableVectorStore, CloseVectorDocument, SynchronousInMemoryDocstore, CloseVectorHNSWLibBase, CloseVectorHNSWLibArgs, CloseVectorCredentials, } from 'closevector-common'; export { CloseVectorEmbeddings, CloseVectorHNSWLibArgs, CloseVectorSaveableVectorStore, CloseVectorDocument, SynchronousInMemoryDocstore, CloseVectorHNSWLibBase, CloseVectorCredentials, } from 'closevector-common'; import { upsertIndex, getIndex } from './io'; export type { HierarchicalNSW as HierarchicalNSWT } from 'closevector-hnswlib-node'; export class CloseVectorHNSWNode extends CloseVectorSaveableVectorStore { declare FilterType: (doc: CloseVectorDocument) => boolean; _index?: HierarchicalNSWT; docstore: SynchronousInMemoryDocstore; args: CloseVectorHNSWLibBase; _uuid?: string; _vectorstoreType(): string { return 'hnswlib'; } constructor(embeddings: CloseVectorEmbeddings, args: CloseVectorHNSWLibArgs & { credentials?: CloseVectorCredentials }) { super(embeddings, args.credentials); this._index = args.index; this.args = args; this.embeddings = embeddings; this.docstore = args?.docstore ?? new SynchronousInMemoryDocstore(); } async addDocuments(documents: CloseVectorDocument[]): Promise { const texts = documents.map(({ pageContent }) => pageContent); return this.addVectors(await this.embeddings.embedDocuments(texts), documents); } private static async getHierarchicalNSW(args: CloseVectorHNSWLibBase) { const { HierarchicalNSW } = await CloseVectorHNSWNode.imports(); if (!args.space) { throw new Error('closevector-hnswlib-node requires a space argument'); } if (args.numDimensions === undefined) { throw new Error('closevector-hnswlib-node requires a numDimensions argument'); } return new HierarchicalNSW(args.space, args.numDimensions); } private async initIndex(vectors: number[][]) { if (!this._index) { if (this.args.numDimensions === undefined) { this.args.numDimensions = vectors[0].length; } this.index = await CloseVectorHNSWNode.getHierarchicalNSW(this.args); } if (!this.index.getCurrentCount()) { this.index.initIndex(vectors.length, 48, 200, 100); this.index.setEf(32); } } public get index(): HierarchicalNSWT { if (!this._index) { throw new Error('Vector store not initialised yet. Try calling `addTexts` first.'); } return this._index; } private set index(index: HierarchicalNSWT) { this._index = index; } public get uuid(): string { return this._uuid; } private set uuid(uuid: string) { this._uuid = uuid; } async addVectors(vectors: number[][], documents: CloseVectorDocument[]) { if (vectors.length === 0) { return; } await this.initIndex(vectors); // TODO here we could optionally normalise the vectors to unit length // so that dot product is equivalent to cosine similarity, like this // https://github.com/nmslib/hnswlib/issues/384#issuecomment-1155737730 // While we only support OpenAI embeddings this isn't necessary if (vectors.length !== documents.length) { throw new Error(`Vectors and metadatas must have the same length`); } if (vectors[0].length !== this.args.numDimensions) { throw new Error( `Vectors must have the same length as the number of dimensions (${this.args.numDimensions})` ); } const capacity = this.index.getMaxElements(); const needed = this.index.getCurrentCount() + vectors.length; if (needed > capacity) { this.index.resizeIndex(needed); } const docstoreSize = this.index.getCurrentCount(); const toSave: Record = {}; for (let i = 0; i < vectors.length; i += 1) { this.index.addPoint(vectors[i], docstoreSize + i); toSave[docstoreSize + i] = documents[i]; } this.docstore.add(toSave); } async similaritySearchVectorWithScore(query: number[], k: number, filter?: this['FilterType']) { if (this.args.numDimensions && !this._index) { await this.initIndex([[]]); } if (query.length !== this.args.numDimensions) { throw new Error( `Query vector must have the same length as the number of dimensions (${this.args.numDimensions})` ); } if (k > this.index.getCurrentCount()) { const total = this.index.getCurrentCount(); console.warn( `k (${k}) is greater than the number of elements in the index (${total}), setting k to ${total}` ); // eslint-disable-next-line no-param-reassign k = total; } const filterFunction = (label: number): boolean => { if (!filter) { return true; } const document = this.docstore.search(String(label)); // eslint-disable-next-line no-instanceof/no-instanceof if (typeof document !== 'string') { const resp = filter(document); return resp; } return false; }; const result = this.index.searchKnn(query, k, filter ? filterFunction : undefined); return result.neighbors.map( (docIndex, resultIndex) => [this.docstore.search(String(docIndex)), result.distances[resultIndex]] as [ CloseVectorDocument, number, ] ); } async delete(params: { directory: string }) { const fs = await import('node:fs/promises'); const path = await import('node:path'); try { await fs.access(path.join(params.directory, 'hnswlib.index')); } catch (err) { throw new Error(`Directory ${params.directory} does not contain a hnswlib.index file.`); } await Promise.all([ await fs.rm(path.join(params.directory, 'hnswlib.index'), { force: true, }), await fs.rm(path.join(params.directory, 'docstore.json'), { force: true, }), await fs.rm(path.join(params.directory, 'args.json'), { force: true }), ]); } async saveToCloud(options?: { uuid?: string; public?: boolean; description?: string; credentials?: CloseVectorCredentials; onProgress?: (progress: { loaded: number; total: number }) => void; }) { const _credentials = options?.credentials ?? this.credentials; if (!_credentials) { throw new Error('No credentials set'); } const _options = { uuid: options?.uuid ?? this.uuid, // default as date as string description: options?.description ?? new Date().toISOString(), accessKey: _credentials.key, secret: _credentials.secret } const uuid = await upsertIndex(this, { ..._options, onProgress(progress) { if (options?.onProgress) { const total = progress.total; const loaded = progress.loaded; options.onProgress({ loaded, total }); } }, }); this.uuid = uuid; return uuid; } async save(directory: string) { const fs = await import('node:fs/promises'); const path = await import('node:path'); await fs.mkdir(directory, { recursive: true }); await Promise.all([ this.index.writeIndex(path.join(directory, 'hnswlib.index')), await fs.writeFile(path.join(directory, 'args.json'), JSON.stringify(this.args)), await fs.writeFile( path.join(directory, 'docstore.json'), JSON.stringify(Array.from(this.docstore._docs.entries())) ), ]); } static async loadFromCloud(options: { embeddings: CloseVectorEmbeddings; uuid: string; credentials?: CloseVectorCredentials, onProgress?: (progress: { loaded: number; total: number }) => void; }) { const { key, secret } = options.credentials ?? {}; if (!key || !secret) { throw new Error('No accessKey or secret set'); } const instance = await getIndex({ uuid: options.uuid, accessKey: options.credentials.key, secret: options.credentials.secret, embeddings: options.embeddings, onProgress(progress) { if (options.onProgress) { const total = progress.total; const loaded = progress.loaded; options.onProgress({ loaded, total }); } }, }); instance.credentials = options.credentials; instance.uuid = options.uuid; return instance; } static async load(directory: string, embeddings: CloseVectorEmbeddings) { const fs = await import('node:fs/promises'); const path = await import('node:path'); const args = JSON.parse(await fs.readFile(path.join(directory, 'args.json'), 'utf8')); const index = await CloseVectorHNSWNode.getHierarchicalNSW(args); const [docstoreFiles] = await Promise.all([ fs.readFile(path.join(directory, 'docstore.json'), 'utf8').then(JSON.parse), index.readIndex(path.join(directory, 'hnswlib.index')), ]); args.docstore = new SynchronousInMemoryDocstore(new Map(docstoreFiles)); args.index = index; return new CloseVectorHNSWNode(embeddings, args); } static async fromTexts( texts: string[], metadatas: object[] | object, embeddings: CloseVectorEmbeddings, dbConfig?: { docstore?: SynchronousInMemoryDocstore; } ): Promise { const docs: CloseVectorDocument[] = []; for (let i = 0; i < texts.length; i += 1) { const metadata = Array.isArray(metadatas) ? metadatas[i] : metadatas; const newDoc = { pageContent: texts[i], metadata, }; docs.push(newDoc); } return CloseVectorHNSWNode.fromDocuments(docs, embeddings, dbConfig); } static async fromDocuments( docs: CloseVectorDocument[], embeddings: CloseVectorEmbeddings, dbConfig?: { docstore?: SynchronousInMemoryDocstore; } ): Promise { const args: CloseVectorHNSWLibArgs = { docstore: dbConfig?.docstore, space: 'cosine', }; const instance = new this(embeddings, args); await instance.addDocuments(docs); return instance; } static async imports(): Promise<{ HierarchicalNSW: typeof HierarchicalNSWT; }> { try { const { default: { HierarchicalNSW }, } = await import('closevector-hnswlib-node'); return { HierarchicalNSW }; // eslint-disable-next-line @typescript-eslint/no-explicit-any } catch (err: any) { throw new Error( `Could not import closevector-hnswlib-node. Please install closevector-hnswlib-node as a dependency with, e.g. \`npm install -S closevector-hnswlib-node\`.\n\nError: ${err?.message}` ); } } } export const HNSWLib = CloseVectorHNSWNode;