-
Notifications
You must be signed in to change notification settings - Fork 2.3k
/
Copy pathmomento_vector_index.ts
344 lines (315 loc) Β· 10.8 KB
/
momento_vector_index.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
/* eslint-disable no-instanceof/no-instanceof */
/* eslint-disable @typescript-eslint/no-explicit-any */
import {
ALL_VECTOR_METADATA,
IVectorIndexClient,
VectorIndexItem,
CreateVectorIndex,
VectorUpsertItemBatch,
VectorDeleteItemBatch,
VectorSearch,
} from "@gomomento/sdk-core";
import * as uuid from "uuid";
import { Document } from "../document.js";
import { Embeddings } from "../embeddings/base.js";
import { VectorStore } from "./base.js";
export interface DocumentProps {
ids: string[];
}
export interface MomentoVectorIndexLibArgs {
/**
* The Momento Vector Index client.
*/
client: IVectorIndexClient;
/**
* The name of the index to use to store the data.
* Defaults to "default".
*/
indexName?: string;
/**
* The name of the metadata field to use to store the text of the document.
* Defaults to "text".
*/
textField?: string;
/**
* Whether to create the index if it does not already exist.
* Defaults to true.
*/
ensureIndexExists?: boolean;
}
export interface DeleteProps {
/**
* The ids of the documents to delete.
*/
ids: string[];
}
/**
* A vector store that uses the Momento Vector Index.
*
* @remarks
* To sign up for a free Momento account, visit https://console.gomomento.com.
*/
export class MomentoVectorIndex extends VectorStore {
private client: IVectorIndexClient;
private indexName: string;
private textField: string;
private _ensureIndexExists: boolean;
_vectorstoreType(): string {
return "momento";
}
/**
* Creates a new `MomentoVectorIndex` instance.
* @param embeddings The embeddings instance to use to generate embeddings from documents.
* @param args The arguments to use to configure the vector store.
*/
constructor(embeddings: Embeddings, args: MomentoVectorIndexLibArgs) {
super(embeddings, args);
this.embeddings = embeddings;
this.client = args.client;
this.indexName = args.indexName ?? "default";
this.textField = args.textField ?? "text";
this._ensureIndexExists = args.ensureIndexExists ?? true;
}
/**
* Returns the Momento Vector Index client.
* @returns The Momento Vector Index client.
*/
public getClient(): IVectorIndexClient {
return this.client;
}
/**
* Creates the index if it does not already exist.
* @param numDimensions The number of dimensions of the vectors to be stored in the index.
* @returns Promise that resolves to true if the index was created, false if it already existed.
*/
private async ensureIndexExists(numDimensions: number): Promise<boolean> {
const response = await this.client.createIndex(
this.indexName,
numDimensions
);
if (response instanceof CreateVectorIndex.Success) {
return true;
} else if (response instanceof CreateVectorIndex.AlreadyExists) {
return false;
} else if (response instanceof CreateVectorIndex.Error) {
throw new Error(response.toString());
} else {
throw new Error(`Unknown response type: ${response.toString()}`);
}
}
/**
* Converts the documents to a format that can be stored in the index.
*
* This is necessary because the Momento Vector Index requires that the metadata
* be a map of strings to strings.
* @param vectors The vectors to convert.
* @param documents The documents to convert.
* @param ids The ids to convert.
* @returns The converted documents.
*/
private prepareItemBatch(
vectors: number[][],
documents: Document<Record<string, any>>[],
ids: string[]
): VectorIndexItem[] {
return vectors.map((vector, idx) => ({
id: ids[idx],
vector,
metadata: {
...documents[idx].metadata,
[this.textField]: documents[idx].pageContent,
},
}));
}
/**
* Adds vectors to the index.
*
* @remarks If the index does not already exist, it will be created if `ensureIndexExists` is true.
* @param vectors The vectors to add to the index.
* @param documents The documents to add to the index.
* @param documentProps The properties of the documents to add to the index, specifically the ids.
* @returns Promise that resolves when the vectors have been added to the index. Also returns the ids of the
* documents that were added.
*/
public async addVectors(
vectors: number[][],
documents: Document<Record<string, any>>[],
documentProps?: DocumentProps
): Promise<void | string[]> {
if (vectors.length === 0) {
return;
}
if (documents.length !== vectors.length) {
throw new Error(
`Number of vectors (${vectors.length}) does not equal number of documents (${documents.length})`
);
}
if (vectors.some((v) => v.length !== vectors[0].length)) {
throw new Error("All vectors must have the same length");
}
if (
documentProps?.ids !== undefined &&
documentProps.ids.length !== vectors.length
) {
throw new Error(
`Number of ids (${
documentProps?.ids?.length || "null"
}) does not equal number of vectors (${vectors.length})`
);
}
if (this._ensureIndexExists) {
await this.ensureIndexExists(vectors[0].length);
}
const documentIds = documentProps?.ids ?? documents.map(() => uuid.v4());
const batchSize = 128;
const numBatches = Math.ceil(vectors.length / batchSize);
// Add each batch of vectors to the index
for (let i = 0; i < numBatches; i += 1) {
const [startIndex, endIndex] = [
i * batchSize,
Math.min((i + 1) * batchSize, vectors.length),
];
const batchVectors = vectors.slice(startIndex, endIndex);
const batchDocuments = documents.slice(startIndex, endIndex);
const batchDocumentIds = documentIds.slice(startIndex, endIndex);
// Insert the items to the index
const response = await this.client.upsertItemBatch(
this.indexName,
this.prepareItemBatch(batchVectors, batchDocuments, batchDocumentIds)
);
if (response instanceof VectorUpsertItemBatch.Success) {
// eslint-disable-next-line no-continue
continue;
} else if (response instanceof VectorUpsertItemBatch.Error) {
throw new Error(response.toString());
} else {
throw new Error(`Unknown response type: ${response.toString()}`);
}
}
}
/**
* Adds vectors to the index. Generates embeddings from the documents
* using the `Embeddings` instance passed to the constructor.
* @param documents Array of `Document` instances to be added to the index.
* @returns Promise that resolves when the documents have been added to the index.
*/
async addDocuments(
documents: Document[],
documentProps?: DocumentProps
): Promise<void> {
const texts = documents.map(({ pageContent }) => pageContent);
await this.addVectors(
await this.embeddings.embedDocuments(texts),
documents,
documentProps
);
}
/**
* Deletes vectors from the index by id.
* @param params The parameters to use to delete the vectors, specifically the ids.
*/
public async delete(params: DeleteProps): Promise<void> {
const response = await this.client.deleteItemBatch(
this.indexName,
params.ids
);
if (response instanceof VectorDeleteItemBatch.Success) {
// pass
} else if (response instanceof VectorDeleteItemBatch.Error) {
throw new Error(response.toString());
} else {
throw new Error(`Unknown response type: ${response.toString()}`);
}
}
/**
* Searches the index for the most similar vectors to the query vector.
* @param query The query vector.
* @param k The number of results to return.
* @returns Promise that resolves to the documents of the most similar vectors
* to the query vector.
*/
public async similaritySearchVectorWithScore(
query: number[],
k: number
): Promise<[Document<Record<string, any>>, number][]> {
const response = await this.client.search(this.indexName, query, {
topK: k,
metadataFields: ALL_VECTOR_METADATA,
});
if (response instanceof VectorSearch.Success) {
if (response.hits === undefined) {
return [];
}
return response.hits().map((hit) => [
new Document({
pageContent: hit.metadata[this.textField]?.toString() ?? "",
metadata: Object.fromEntries(
Object.entries(hit.metadata).filter(
([key]) => key !== this.textField
)
),
}),
hit.score,
]);
} else if (response instanceof VectorSearch.Error) {
throw new Error(response.toString());
} else {
throw new Error(`Unknown response type: ${response.toString()}`);
}
}
/**
* Stores the documents in the index.
*
* Converts the documents to vectors using the `Embeddings` instance passed.
* @param texts The texts to store in the index.
* @param metadatas The metadata to store in the index.
* @param embeddings The embeddings instance to use to generate embeddings from the documents.
* @param dbConfig The configuration to use to instantiate the vector store.
* @param documentProps The properties of the documents to add to the index, specifically the ids.
* @returns Promise that resolves to the vector store.
*/
public static async fromTexts(
texts: string[],
metadatas: object[] | object,
embeddings: Embeddings,
dbConfig: MomentoVectorIndexLibArgs,
documentProps?: DocumentProps
): Promise<MomentoVectorIndex> {
if (Array.isArray(metadatas) && texts.length !== metadatas.length) {
throw new Error(
`Number of texts (${texts.length}) does not equal number of metadatas (${metadatas.length})`
);
}
const docs: Document[] = [];
for (let i = 0; i < texts.length; i += 1) {
// eslint-disable-next-line @typescript-eslint/no-unsafe-assignment
const metadata: object = Array.isArray(metadatas)
? metadatas[i]
: metadatas;
const newDoc = new Document({
pageContent: texts[i],
metadata,
});
docs.push(newDoc);
}
return await this.fromDocuments(docs, embeddings, dbConfig, documentProps);
}
/**
* Stores the documents in the index.
* @param docs The documents to store in the index.
* @param embeddings The embeddings instance to use to generate embeddings from the documents.
* @param dbConfig The configuration to use to instantiate the vector store.
* @param documentProps The properties of the documents to add to the index, specifically the ids.
* @returns Promise that resolves to the vector store.
*/
public static async fromDocuments(
docs: Document[],
embeddings: Embeddings,
dbConfig: MomentoVectorIndexLibArgs,
documentProps?: DocumentProps
): Promise<MomentoVectorIndex> {
const vectorStore = new MomentoVectorIndex(embeddings, dbConfig);
await vectorStore.addDocuments(docs, documentProps);
return vectorStore;
}
}