-
Notifications
You must be signed in to change notification settings - Fork 2.2k
/
astradb.ts
362 lines (314 loc) Β· 10.8 KB
/
astradb.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
import * as uuid from "uuid";
import {
Collection,
DataAPIClient,
CreateCollectionOptions,
Db,
} from "@datastax/astra-db-ts";
import {
AsyncCaller,
AsyncCallerParams,
} from "@langchain/core/utils/async_caller";
import { Document } from "@langchain/core/documents";
import type { EmbeddingsInterface } from "@langchain/core/embeddings";
import { chunkArray } from "@langchain/core/utils/chunk_array";
import { maximalMarginalRelevance } from "@langchain/core/utils/math";
import {
MaxMarginalRelevanceSearchOptions,
VectorStore,
} from "@langchain/core/vectorstores";
export type CollectionFilter = Record<string, unknown>;
export interface AstraLibArgs extends AsyncCallerParams {
token: string;
endpoint: string;
collection: string;
namespace?: string;
idKey?: string;
contentKey?: string;
skipCollectionProvisioning?: boolean;
collectionOptions?: CreateCollectionOptions<any>;
batchSize?: number;
}
export type AstraDeleteParams = {
ids: string[];
};
export class AstraDBVectorStore extends VectorStore {
declare FilterType: CollectionFilter;
private astraDBClient: Db;
private collectionName: string;
private collection: Collection | undefined;
private collectionOptions: CreateCollectionOptions<any> | undefined;
private readonly idKey: string;
private readonly contentKey: string; // if undefined the entirety of the content aside from the id and embedding will be stored as content
private readonly batchSize: number; // insertMany has a limit of 20 documents
caller: AsyncCaller;
private readonly skipCollectionProvisioning: boolean;
_vectorstoreType(): string {
return "astradb";
}
constructor(embeddings: EmbeddingsInterface, args: AstraLibArgs) {
super(embeddings, args);
const {
token,
endpoint,
collection,
collectionOptions,
namespace,
idKey,
contentKey,
batchSize,
skipCollectionProvisioning,
...callerArgs
} = args;
const dataAPIClient = new DataAPIClient(token, { caller: ["langchainjs"] });
this.astraDBClient = dataAPIClient.db(endpoint, { namespace });
this.skipCollectionProvisioning = skipCollectionProvisioning ?? false;
if (this.skipCollectionProvisioning && collectionOptions) {
throw new Error(
"If 'skipCollectionProvisioning' has been set to true, 'collectionOptions' must not be defined"
);
}
this.collectionName = collection;
this.collectionOptions =
AstraDBVectorStore.applyCollectionOptionsDefaults(collectionOptions);
this.idKey = idKey ?? "_id";
this.contentKey = contentKey ?? "text";
this.batchSize = batchSize && batchSize <= 20 ? batchSize : 20;
this.caller = new AsyncCaller(callerArgs);
}
private static applyCollectionOptionsDefaults(
fromUser?: CreateCollectionOptions<any>
): CreateCollectionOptions<any> {
const copy: CreateCollectionOptions<any> = fromUser ? { ...fromUser } : {};
if (copy.checkExists === undefined) {
copy.checkExists = false;
}
if (copy.indexing === undefined) {
// same default as langchain python AstraDBVectorStore.
// this enables to create the collection in python/ts and use it in ts/python with default options.
copy.indexing = { allow: ["metadata"] };
}
return copy;
}
/**
* Create a new collection in your Astra DB vector database and then connects to it.
* If the collection already exists, it will connect to it as well.
*
* @returns Promise that resolves if connected to the collection.
*/
async initialize(): Promise<void> {
if (!this.skipCollectionProvisioning) {
await this.astraDBClient.createCollection(
this.collectionName,
this.collectionOptions
);
}
this.collection = await this.astraDBClient.collection(this.collectionName);
console.debug("Connected to Astra DB collection");
}
/**
* Method to save vectors to AstraDB.
*
* @param vectors Vectors to save.
* @param documents The documents associated with the vectors.
* @returns Promise that resolves when the vectors have been added.
*/
async addVectors(
vectors: number[][],
documents: Document[],
options?: string[]
) {
if (!this.collection) {
throw new Error("Must connect to a collection before adding vectors");
}
const docs = vectors.map((embedding, idx) => ({
[this.idKey]: options?.[idx] ?? uuid.v4(),
[this.contentKey]: documents[idx].pageContent,
$vector: embedding,
...documents[idx].metadata,
}));
const chunkedDocs = chunkArray(docs, this.batchSize);
const batchCalls = chunkedDocs.map((chunk) =>
this.caller.call(async () => this.collection?.insertMany(chunk))
);
await Promise.all(batchCalls);
}
/**
* Method that adds documents to AstraDB.
*
* @param documents Array of documents to add to AstraDB.
* @param options Optional ids for the documents.
* @returns Promise that resolves the documents have been added.
*/
async addDocuments(documents: Document[], options?: string[]) {
if (!this.collection) {
throw new Error("Must connect to a collection before adding vectors");
}
return this.addVectors(
await this.embeddings.embedDocuments(documents.map((d) => d.pageContent)),
documents,
options
);
}
/**
* Method that deletes documents from AstraDB.
*
* @param params AstraDeleteParameters for the delete.
* @returns Promise that resolves when the documents have been deleted.
*/
async delete(params: AstraDeleteParams) {
if (!this.collection) {
throw new Error("Must connect to a collection before deleting");
}
for (const id of params.ids) {
console.debug(`Deleting document with id ${id}`);
await this.collection.deleteOne({
[this.idKey]: id,
});
}
}
/**
* Method that performs a similarity search in AstraDB and returns and similarity scores.
*
* @param query Query vector for the similarity search.
* @param k Number of top results to return.
* @param filter Optional filter to apply to the search.
* @returns Promise that resolves with an array of documents and their scores.
*/
async similaritySearchVectorWithScore(
query: number[],
k: number,
filter?: CollectionFilter
): Promise<[Document, number][]> {
if (!this.collection) {
throw new Error("Must connect to a collection before adding vectors");
}
const cursor = await this.collection.find(filter ?? {}, {
sort: { $vector: query },
limit: k,
includeSimilarity: true,
});
const results: [Document, number][] = [];
for await (const row of cursor) {
const {
$similarity: similarity,
[this.contentKey]: content,
...metadata
} = row;
const doc = new Document({
pageContent: content as string,
metadata,
});
results.push([doc, similarity as number]);
}
return results;
}
/**
* Return documents selected using the maximal marginal relevance.
* Maximal marginal relevance optimizes for similarity to the query AND diversity
* among selected documents.
*
* @param {string} query - Text to look up documents similar to.
* @param {number} options.k - Number of documents to return.
* @param {number} options.fetchK - Number of documents to fetch before passing to the MMR algorithm.
* @param {number} options.lambda - Number between 0 and 1 that determines the degree of diversity among the results,
* where 0 corresponds to maximum diversity and 1 to minimum diversity.
* @param {CollectionFilter} options.filter - Optional filter
*
* @returns {Promise<Document[]>} - List of documents selected by maximal marginal relevance.
*/
async maxMarginalRelevanceSearch(
query: string,
options: MaxMarginalRelevanceSearchOptions<this["FilterType"]>
): Promise<Document[]> {
if (!this.collection) {
throw new Error("Must connect to a collection before adding vectors");
}
const queryEmbedding = await this.embeddings.embedQuery(query);
const cursor = await this.collection.find(options.filter ?? {}, {
sort: { $vector: queryEmbedding },
limit: options.k,
includeSimilarity: true,
});
const results = (await cursor.toArray()) ?? [];
const embeddingList: number[][] = results.map(
(row) => row.$vector as number[]
);
const mmrIndexes = maximalMarginalRelevance(
queryEmbedding,
embeddingList,
options.lambda,
options.k
);
const topMmrMatches = mmrIndexes.map((idx) => results[idx]);
const docs: Document[] = [];
topMmrMatches.forEach((match) => {
const { [this.contentKey]: content, ...metadata } = match;
const doc: Document = {
pageContent: content as string,
metadata,
};
docs.push(doc);
});
return docs;
}
/**
* Static method to create an instance of AstraDBVectorStore from texts.
*
* @param texts The texts to use.
* @param metadatas The metadata associated with the texts.
* @param embeddings The embeddings to use.
* @param dbConfig The arguments for the AstraDBVectorStore.
* @returns Promise that resolves with a new instance of AstraDBVectorStore.
*/
static async fromTexts(
texts: string[],
metadatas: object[] | object,
embeddings: EmbeddingsInterface,
dbConfig: AstraLibArgs
): Promise<AstraDBVectorStore> {
const docs: Document[] = [];
for (let i = 0; i < texts.length; i += 1) {
const metadata = Array.isArray(metadatas) ? metadatas[i] : metadatas;
const doc = new Document({
pageContent: texts[i],
metadata,
});
docs.push(doc);
}
return AstraDBVectorStore.fromDocuments(docs, embeddings, dbConfig);
}
/**
* Static method to create an instance of AstraDBVectorStore from documents.
*
* @param docs The Documents to use.
* @param embeddings The embeddings to use.
* @param dbConfig The arguments for the AstraDBVectorStore.
* @returns Promise that resolves with a new instance of AstraDBVectorStore.
*/
static async fromDocuments(
docs: Document[],
embeddings: EmbeddingsInterface,
dbConfig: AstraLibArgs
): Promise<AstraDBVectorStore> {
const instance = new this(embeddings, dbConfig);
await instance.initialize();
await instance.addDocuments(docs);
return instance;
}
/**
* Static method to create an instance of AstraDBVectorStore from an existing index.
*
* @param embeddings The embeddings to use.
* @param dbConfig The arguments for the AstraDBVectorStore.
* @returns Promise that resolves with a new instance of AstraDBVectorStore.
*/
static async fromExistingIndex(
embeddings: EmbeddingsInterface,
dbConfig: AstraLibArgs
): Promise<AstraDBVectorStore> {
const instance = new this(embeddings, dbConfig);
await instance.initialize();
return instance;
}
}