-
Notifications
You must be signed in to change notification settings - Fork 2.2k
/
vectorstores.ts
483 lines (433 loc) Β· 14.2 KB
/
vectorstores.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
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
import type {
createCluster,
createClient,
RediSearchSchema,
SearchOptions,
} from "redis";
import { SchemaFieldTypes, VectorAlgorithms } from "redis";
import type { EmbeddingsInterface } from "@langchain/core/embeddings";
import { VectorStore } from "@langchain/core/vectorstores";
import { Document } from "@langchain/core/documents";
// Adapated from internal redis types which aren't exported
/**
* Type for creating a schema vector field. It includes the algorithm,
* distance metric, and initial capacity.
*/
export type CreateSchemaVectorField<
T extends VectorAlgorithms,
A extends Record<string, unknown>
> = {
ALGORITHM: T;
DISTANCE_METRIC: "L2" | "IP" | "COSINE";
INITIAL_CAP?: number;
} & A;
/**
* Type for creating a flat schema vector field. It extends
* CreateSchemaVectorField with a block size property.
*/
export type CreateSchemaFlatVectorField = CreateSchemaVectorField<
VectorAlgorithms.FLAT,
{
BLOCK_SIZE?: number;
}
>;
/**
* Type for creating a HNSW schema vector field. It extends
* CreateSchemaVectorField with M, EF_CONSTRUCTION, and EF_RUNTIME
* properties.
*/
export type CreateSchemaHNSWVectorField = CreateSchemaVectorField<
VectorAlgorithms.HNSW,
{
M?: number;
EF_CONSTRUCTION?: number;
EF_RUNTIME?: number;
}
>;
type CreateIndexOptions = NonNullable<
Parameters<ReturnType<typeof createClient>["ft"]["create"]>[3]
>;
export type RedisSearchLanguages = `${NonNullable<
CreateIndexOptions["LANGUAGE"]
>}`;
export type RedisVectorStoreIndexOptions = Omit<
CreateIndexOptions,
"LANGUAGE"
> & { LANGUAGE?: RedisSearchLanguages };
/**
* Interface for the configuration of the RedisVectorStore. It includes
* the Redis client, index name, index options, key prefix, content key,
* metadata key, vector key, and filter.
*/
export interface RedisVectorStoreConfig {
redisClient:
| ReturnType<typeof createClient>
| ReturnType<typeof createCluster>;
indexName: string;
indexOptions?: CreateSchemaFlatVectorField | CreateSchemaHNSWVectorField;
createIndexOptions?: Omit<RedisVectorStoreIndexOptions, "PREFIX">; // PREFIX must be set with keyPrefix
keyPrefix?: string;
contentKey?: string;
metadataKey?: string;
vectorKey?: string;
filter?: RedisVectorStoreFilterType;
}
/**
* Interface for the options when adding documents to the
* RedisVectorStore. It includes keys and batch size.
*/
export interface RedisAddOptions {
keys?: string[];
batchSize?: number;
}
/**
* Type for the filter used in the RedisVectorStore. It is an array of
* strings.
* If a string is passed instead of an array the value is used directly, this
* allows custom filters to be passed.
*/
export type RedisVectorStoreFilterType = string[] | string;
/**
* Class representing a RedisVectorStore. It extends the VectorStore class
* and includes methods for adding documents and vectors, performing
* similarity searches, managing the index, and more.
*/
export class RedisVectorStore extends VectorStore {
declare FilterType: RedisVectorStoreFilterType;
private redisClient:
| ReturnType<typeof createClient>
| ReturnType<typeof createCluster>;
indexName: string;
indexOptions: CreateSchemaFlatVectorField | CreateSchemaHNSWVectorField;
createIndexOptions: CreateIndexOptions;
keyPrefix: string;
contentKey: string;
metadataKey: string;
vectorKey: string;
filter?: RedisVectorStoreFilterType;
_vectorstoreType(): string {
return "redis";
}
constructor(
embeddings: EmbeddingsInterface,
_dbConfig: RedisVectorStoreConfig
) {
super(embeddings, _dbConfig);
this.redisClient = _dbConfig.redisClient;
this.indexName = _dbConfig.indexName;
this.indexOptions = _dbConfig.indexOptions ?? {
ALGORITHM: VectorAlgorithms.HNSW,
DISTANCE_METRIC: "COSINE",
};
this.keyPrefix = _dbConfig.keyPrefix ?? `doc:${this.indexName}:`;
this.contentKey = _dbConfig.contentKey ?? "content";
this.metadataKey = _dbConfig.metadataKey ?? "metadata";
this.vectorKey = _dbConfig.vectorKey ?? "content_vector";
this.filter = _dbConfig.filter;
this.createIndexOptions = {
ON: "HASH",
PREFIX: this.keyPrefix,
...(_dbConfig.createIndexOptions as CreateIndexOptions),
};
}
/**
* Method for adding documents to the RedisVectorStore. It first converts
* the documents to texts and then adds them as vectors.
* @param documents The documents to add.
* @param options Optional parameters for adding the documents.
* @returns A promise that resolves when the documents have been added.
*/
async addDocuments(documents: Document[], options?: RedisAddOptions) {
const texts = documents.map(({ pageContent }) => pageContent);
return this.addVectors(
await this.embeddings.embedDocuments(texts),
documents,
options
);
}
/**
* Method for adding vectors to the RedisVectorStore. It checks if the
* index exists and creates it if it doesn't, then adds the vectors in
* batches.
* @param vectors The vectors to add.
* @param documents The documents associated with the vectors.
* @param keys Optional keys for the vectors.
* @param batchSize The size of the batches in which to add the vectors. Defaults to 1000.
* @returns A promise that resolves when the vectors have been added.
*/
async addVectors(
vectors: number[][],
documents: Document[],
{ keys, batchSize = 1000 }: RedisAddOptions = {}
) {
if (!vectors.length || !vectors[0].length) {
throw new Error("No vectors provided");
}
// check if the index exists and create it if it doesn't
await this.createIndex(vectors[0].length);
const info = await this.redisClient.ft.info(this.indexName);
const lastKeyCount = parseInt(info.numDocs, 10) || 0;
const multi = this.redisClient.multi();
vectors.map(async (vector, idx) => {
const key =
keys && keys.length
? keys[idx]
: `${this.keyPrefix}${idx + lastKeyCount}`;
const metadata =
documents[idx] && documents[idx].metadata
? documents[idx].metadata
: {};
multi.hSet(key, {
[this.vectorKey]: this.getFloat32Buffer(vector),
[this.contentKey]: documents[idx].pageContent,
[this.metadataKey]: this.escapeSpecialChars(JSON.stringify(metadata)),
});
// write batch
if (idx % batchSize === 0) {
await multi.exec();
}
});
// insert final batch
await multi.exec();
}
/**
* Method for performing a similarity search in the RedisVectorStore. It
* returns the documents and their scores.
* @param query The query vector.
* @param k The number of nearest neighbors to return.
* @param filter Optional filter to apply to the search.
* @returns A promise that resolves to an array of documents and their scores.
*/
async similaritySearchVectorWithScore(
query: number[],
k: number,
filter?: RedisVectorStoreFilterType
): Promise<[Document, number][]> {
if (filter && this.filter) {
throw new Error("cannot provide both `filter` and `this.filter`");
}
const _filter = filter ?? this.filter;
const results = await this.redisClient.ft.search(
this.indexName,
...this.buildQuery(query, k, _filter)
);
const result: [Document, number][] = [];
if (results.total) {
for (const res of results.documents) {
if (res.value) {
const document = res.value;
if (document.vector_score) {
result.push([
new Document({
pageContent: (document[this.contentKey] ?? "") as string,
metadata: JSON.parse(
this.unEscapeSpecialChars(
(document.metadata ?? "{}") as string
)
),
}),
Number(document.vector_score),
]);
}
}
}
}
return result;
}
/**
* Static method for creating a new instance of RedisVectorStore from
* texts. It creates documents from the texts and metadata, then adds them
* to the RedisVectorStore.
* @param texts The texts to add.
* @param metadatas The metadata associated with the texts.
* @param embeddings The embeddings to use.
* @param dbConfig The configuration for the RedisVectorStore.
* @param docsOptions The document options to use.
* @returns A promise that resolves to a new instance of RedisVectorStore.
*/
static fromTexts(
texts: string[],
metadatas: object[] | object,
embeddings: EmbeddingsInterface,
dbConfig: RedisVectorStoreConfig,
docsOptions?: RedisAddOptions
): Promise<RedisVectorStore> {
const docs: Document[] = [];
for (let i = 0; i < texts.length; i += 1) {
const metadata = Array.isArray(metadatas) ? metadatas[i] : metadatas;
const newDoc = new Document({
pageContent: texts[i],
metadata,
});
docs.push(newDoc);
}
return RedisVectorStore.fromDocuments(
docs,
embeddings,
dbConfig,
docsOptions
);
}
/**
* Static method for creating a new instance of RedisVectorStore from
* documents. It adds the documents to the RedisVectorStore.
* @param docs The documents to add.
* @param embeddings The embeddings to use.
* @param dbConfig The configuration for the RedisVectorStore.
* @param docsOptions The document options to use.
* @returns A promise that resolves to a new instance of RedisVectorStore.
*/
static async fromDocuments(
docs: Document[],
embeddings: EmbeddingsInterface,
dbConfig: RedisVectorStoreConfig,
docsOptions?: RedisAddOptions
): Promise<RedisVectorStore> {
const instance = new this(embeddings, dbConfig);
await instance.addDocuments(docs, docsOptions);
return instance;
}
/**
* Method for checking if an index exists in the RedisVectorStore.
* @returns A promise that resolves to a boolean indicating whether the index exists.
*/
async checkIndexExists() {
try {
await this.redisClient.ft.info(this.indexName);
} catch (err) {
// eslint-disable-next-line @typescript-eslint/no-explicit-any
if ((err as any)?.message.includes("unknown command")) {
throw new Error(
"Failed to run FT.INFO command. Please ensure that you are running a RediSearch-capable Redis instance: https://js.langchain.com/docs/modules/data_connection/vectorstores/integrations/redis#setup"
);
}
// index doesn't exist
return false;
}
return true;
}
/**
* Method for creating an index in the RedisVectorStore. If the index
* already exists, it does nothing.
* @param dimensions The dimensions of the index
* @returns A promise that resolves when the index has been created.
*/
async createIndex(dimensions = 1536): Promise<void> {
if (await this.checkIndexExists()) {
return;
}
const schema: RediSearchSchema = {
[this.vectorKey]: {
type: SchemaFieldTypes.VECTOR,
TYPE: "FLOAT32",
DIM: dimensions,
...this.indexOptions,
},
[this.contentKey]: SchemaFieldTypes.TEXT,
[this.metadataKey]: SchemaFieldTypes.TEXT,
};
await this.redisClient.ft.create(
this.indexName,
schema,
this.createIndexOptions
);
}
/**
* Method for dropping an index from the RedisVectorStore.
* @param deleteDocuments Optional boolean indicating whether to drop the associated documents.
* @returns A promise that resolves to a boolean indicating whether the index was dropped.
*/
async dropIndex(deleteDocuments?: boolean): Promise<boolean> {
try {
const options = deleteDocuments ? { DD: deleteDocuments } : undefined;
await this.redisClient.ft.dropIndex(this.indexName, options);
return true;
} catch (err) {
return false;
}
}
/**
* Deletes vectors from the vector store.
* @param params The parameters for deleting vectors.
* @returns A promise that resolves when the vectors have been deleted.
*/
async delete(params: { deleteAll: boolean }): Promise<void> {
if (params.deleteAll) {
await this.dropIndex(true);
} else {
throw new Error(`Invalid parameters passed to "delete".`);
}
}
private buildQuery(
query: number[],
k: number,
filter?: RedisVectorStoreFilterType
): [string, SearchOptions] {
const vectorScoreField = "vector_score";
let hybridFields = "*";
// if a filter is set, modify the hybrid query
if (filter && filter.length) {
// `filter` is a list of strings, then it's applied using the OR operator in the metadata key
// for example: filter = ['foo', 'bar'] => this will filter all metadata containing either 'foo' OR 'bar'
hybridFields = `@${this.metadataKey}:(${this.prepareFilter(filter)})`;
}
const baseQuery = `${hybridFields} => [KNN ${k} @${this.vectorKey} $vector AS ${vectorScoreField}]`;
const returnFields = [this.metadataKey, this.contentKey, vectorScoreField];
const options: SearchOptions = {
PARAMS: {
vector: this.getFloat32Buffer(query),
},
RETURN: returnFields,
SORTBY: vectorScoreField,
DIALECT: 2,
LIMIT: {
from: 0,
size: k,
},
};
return [baseQuery, options];
}
private prepareFilter(filter: RedisVectorStoreFilterType) {
if (Array.isArray(filter)) {
return filter.map(this.escapeSpecialChars).join("|");
}
return filter;
}
/**
* Escapes all '-', ':', and '"' characters.
* RediSearch considers these all as special characters, so we need
* to escape them
* @see https://redis.io/docs/stack/search/reference/query_syntax
*
* @param str
* @returns
*/
private escapeSpecialChars(str: string) {
return str
.replaceAll("-", "\\-")
.replaceAll(":", "\\:")
.replaceAll(`"`, `\\"`);
}
/**
* Unescapes all '-', ':', and '"' characters, returning the original string
*
* @param str
* @returns
*/
private unEscapeSpecialChars(str: string) {
return str
.replaceAll("\\-", "-")
.replaceAll("\\:", ":")
.replaceAll(`\\"`, `"`);
}
/**
* Converts the vector to the buffer Redis needs to
* correctly store an embedding
*
* @param vector
* @returns Buffer
*/
private getFloat32Buffer(vector: number[]) {
return Buffer.from(new Float32Array(vector).buffer);
}
}