-
Notifications
You must be signed in to change notification settings - Fork 2.2k
/
rockset.ts
452 lines (417 loc) Β· 13.3 KB
/
rockset.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
import { MainApi } from "@rockset/client";
import type { CreateCollectionRequest } from "@rockset/client/dist/codegen/api.d.ts";
import { Collection } from "@rockset/client/dist/codegen/api.js";
import type { EmbeddingsInterface } from "@langchain/core/embeddings";
import { VectorStore } from "@langchain/core/vectorstores";
import { Document } from "@langchain/core/documents";
/**
* Generic Rockset vector storage error
*/
export class RocksetStoreError extends Error {
/**
* Constructs a RocksetStoreError
* @param message The error message
*/
constructor(message: string) {
super(message);
this.name = this.constructor.name;
}
}
/**
* Error that is thrown when a RocksetStore function is called
* after `destroy()` is called (meaning the collection would be
* deleted).
*/
export class RocksetStoreDestroyedError extends RocksetStoreError {
constructor() {
super("The Rockset store has been destroyed");
this.name = this.constructor.name;
}
}
/**
* Functions to measure vector distance/similarity by.
* See https://rockset.com/docs/vector-functions/#vector-distance-functions
* @enum SimilarityMetric
*/
export const SimilarityMetric = {
CosineSimilarity: "COSINE_SIM",
EuclideanDistance: "EUCLIDEAN_DIST",
DotProduct: "DOT_PRODUCT",
} as const;
export type SimilarityMetric =
(typeof SimilarityMetric)[keyof typeof SimilarityMetric];
interface CollectionNotFoundError {
message_key: string;
}
/**
* Vector store arguments
* @interface RocksetStore
*/
export interface RocksetLibArgs {
/**
* The rockset client object constructed with `rocksetConfigure`
* @type {MainAPI}
*/
client: MainApi;
/**
* The name of the Rockset collection to store vectors
* @type {string}
*/
collectionName: string;
/**
* The name of othe Rockset workspace that holds @member collectionName
* @type {string}
*/
workspaceName?: string;
/**
* The name of the collection column to contain page contnent of documents
* @type {string}
*/
textKey?: string;
/**
* The name of the collection column to contain vectors
* @type {string}
*/
embeddingKey?: string;
/**
* The SQL `WHERE` clause to filter by
* @type {string}
*/
filter?: string;
/**
* The metric used to measure vector relationship
* @type {SimilarityMetric}
*/
similarityMetric?: SimilarityMetric;
}
/**
* Exposes Rockset's vector store/search functionality
*/
export class RocksetStore extends VectorStore {
declare FilterType: string;
client: MainApi;
collectionName: string;
workspaceName: string;
textKey: string;
embeddingKey: string;
filter?: string;
private _similarityMetric: SimilarityMetric;
private similarityOrder: "ASC" | "DESC";
private destroyed: boolean;
/**
* Gets a string representation of the type of this VectorStore
* @returns {"rockset"}
*/
_vectorstoreType(): "rockset" {
return "rockset";
}
/**
* Constructs a new RocksetStore
* @param {Embeddings} embeddings Object used to embed queries and
* page content
* @param {RocksetLibArgs} args
*/
constructor(embeddings: EmbeddingsInterface, args: RocksetLibArgs) {
super(embeddings, args);
this.embeddings = embeddings;
this.client = args.client;
this.collectionName = args.collectionName;
this.workspaceName = args.workspaceName ?? "commons";
this.textKey = args.textKey ?? "text";
this.embeddingKey = args.embeddingKey ?? "embedding";
this.filter = args.filter;
this.similarityMetric =
args.similarityMetric ?? SimilarityMetric.CosineSimilarity;
this.setSimilarityOrder();
}
/**
* Sets the object's similarity order based on what
* SimilarityMetric is being used
*/
private setSimilarityOrder() {
this.checkIfDestroyed();
this.similarityOrder =
this.similarityMetric === SimilarityMetric.EuclideanDistance
? "ASC"
: "DESC";
}
/**
* Embeds and adds Documents to the store.
* @param {Documents[]} documents The documents to store
* @returns {Promise<string[]?>} The _id's of the documents added
*/
async addDocuments(documents: Document[]): Promise<string[] | undefined> {
const texts = documents.map(({ pageContent }) => pageContent);
return await this.addVectors(
await this.embeddings.embedDocuments(texts),
documents
);
}
/**
* Adds vectors to the store given their corresponding Documents
* @param {number[][]} vectors The vectors to store
* @param {Document[]} documents The Documents they represent
* @return {Promise<string[]?>} The _id's of the added documents
*/
async addVectors(vectors: number[][], documents: Document[]) {
this.checkIfDestroyed();
const rocksetDocs = [];
for (let i = 0; i < documents.length; i += 1) {
const currDoc = documents[i];
const currVector = vectors[i];
rocksetDocs.push({
[this.textKey]: currDoc.pageContent,
[this.embeddingKey]: currVector,
...currDoc.metadata,
});
}
return (
await this.client.documents.addDocuments(
this.workspaceName,
this.collectionName,
{
data: rocksetDocs,
}
)
).data?.map((docStatus) => docStatus._id || "");
}
/**
* Deletes Rockset documements given their _id's
* @param {string[]} ids The IDS to remove documents with
*/
async delete(ids: string[]): Promise<void> {
this.checkIfDestroyed();
await this.client.documents.deleteDocuments(
this.workspaceName,
this.collectionName,
{
data: ids.map((id) => ({ _id: id })),
}
);
}
/**
* Gets the most relevant documents to a query along
* with their similarity score. The returned documents
* are ordered by similarity (most similar at the first
* index)
* @param {number[]} query The embedded query to search
* the store by
* @param {number} k The number of documents to retreive
* @param {string?} filter The SQL `WHERE` clause to filter by
*/
async similaritySearchVectorWithScore(
query: number[],
k: number,
filter?: string
): Promise<[Document, number][]> {
this.checkIfDestroyed();
if (filter && this.filter) {
throw new RocksetStoreError(
"cannot provide both `filter` and `this.filter`"
);
}
const similarityKey = "similarity";
const _filter = filter ?? this.filter;
return (
(
await this.client.queries.query({
sql: {
query: `
SELECT
* EXCEPT("${this.embeddingKey}"),
"${this.textKey}",
${this.similarityMetric}(:query, "${
this.embeddingKey
}") AS "${similarityKey}"
FROM
"${this.workspaceName}"."${this.collectionName}"
${_filter ? `WHERE ${_filter}` : ""}
ORDER BY
"${similarityKey}" ${this.similarityOrder}
LIMIT
${k}
`,
parameters: [
{
name: "query",
type: "",
value: `[${query.toString()}]`,
},
],
},
})
).results?.map((rocksetDoc) => [
new Document<Record<string, object>>({
pageContent: rocksetDoc[this.textKey],
metadata: (({
[this.textKey]: t,
[similarityKey]: s,
...rocksetDoc
}) => rocksetDoc)(rocksetDoc),
}),
rocksetDoc[similarityKey] as number,
]) ?? []
);
}
/**
* Constructs and returns a RocksetStore object given texts to store.
* @param {string[]} texts The texts to store
* @param {object[] | object} metadatas The metadatas that correspond
* to @param texts
* @param {Embeddings} embeddings The object used to embed queries
* and page content
* @param {RocksetLibArgs} dbConfig The options to be passed into the
* RocksetStore constructor
* @returns {RocksetStore}
*/
static async fromTexts(
texts: string[],
metadatas: object[] | object,
embeddings: EmbeddingsInterface,
dbConfig: RocksetLibArgs
): Promise<RocksetStore> {
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 RocksetStore.fromDocuments(docs, embeddings, dbConfig);
}
/**
* Constructs, adds docs to, and returns a RocksetStore object
* @param {Document[]} docs The Documents to store
* @param {Embeddings} embeddings The object used to embed queries
* and page content
* @param {RocksetLibArgs} dbConfig The options to be passed into the
* RocksetStore constructor
* @returns {RocksetStore}
*/
static async fromDocuments(
docs: Document[],
embeddings: EmbeddingsInterface,
dbConfig: RocksetLibArgs
): Promise<RocksetStore> {
const args = { ...dbConfig, textKey: dbConfig.textKey ?? "text" };
const instance = new this(embeddings, args);
await instance.addDocuments(docs);
return instance;
}
/**
* Checks if a Rockset collection exists.
* @param {RocksetLibArgs} dbConfig The object containing the collection
* and workspace names
* @return {boolean} whether the collection exists
*/
private static async collectionExists(dbConfig: RocksetLibArgs) {
try {
await dbConfig.client.collections.getCollection(
dbConfig.workspaceName ?? "commons",
dbConfig.collectionName
);
} catch (err) {
if (
(err as CollectionNotFoundError).message_key ===
"COLLECTION_DOES_NOT_EXIST"
) {
return false;
}
throw err;
}
return true;
}
/**
* Checks whether a Rockset collection is ready to be queried.
* @param {RocksetLibArgs} dbConfig The object containing the collection
* name and workspace
* @return {boolean} whether the collection is ready
*/
private static async collectionReady(dbConfig: RocksetLibArgs) {
return (
(
await dbConfig.client.collections.getCollection(
dbConfig.workspaceName ?? "commons",
dbConfig.collectionName
)
).data?.status === Collection.StatusEnum.READY
);
}
/**
* Deletes the collection this RocksetStore uses
* @param {boolean?} waitUntilDeletion Whether to sleep until the
* collection is ready to be
* queried
*/
async destroy(waitUntilDeletion?: boolean) {
await this.client.collections.deleteCollection(
this.workspaceName,
this.collectionName
);
this.destroyed = true;
if (waitUntilDeletion) {
while (
await RocksetStore.collectionExists({
collectionName: this.collectionName,
client: this.client,
})
);
}
}
/**
* Checks if this RocksetStore has been destroyed.
* @throws {RocksetStoreDestroyederror} if it has.
*/
private checkIfDestroyed() {
if (this.destroyed) {
throw new RocksetStoreDestroyedError();
}
}
/**
* Creates a new Rockset collection and returns a RocksetStore that
* uses it
* @param {Embeddings} embeddings Object used to embed queries and
* page content
* @param {RocksetLibArgs} dbConfig The options to be passed into the
* RocksetStore constructor
* @param {CreateCollectionRequest?} collectionOptions The arguments to sent with the
* HTTP request when creating the
* collection. Setting a field mapping
* that `VECTOR_ENFORCE`s is recommended
* when using this function. See
* https://rockset.com/docs/vector-functions/#vector_enforce
* @returns {RocsketStore}
*/
static async withNewCollection(
embeddings: EmbeddingsInterface,
dbConfig: RocksetLibArgs,
collectionOptions?: CreateCollectionRequest
): Promise<RocksetStore> {
if (
collectionOptions?.name &&
dbConfig.collectionName !== collectionOptions?.name
) {
throw new RocksetStoreError(
"`dbConfig.name` and `collectionOptions.name` do not match"
);
}
await dbConfig.client.collections.createCollection(
dbConfig.workspaceName ?? "commons",
collectionOptions || { name: dbConfig.collectionName }
);
while (
!(await this.collectionExists(dbConfig)) ||
!(await this.collectionReady(dbConfig))
);
return new this(embeddings, dbConfig);
}
public get similarityMetric() {
return this._similarityMetric;
}
public set similarityMetric(metric: SimilarityMetric) {
this._similarityMetric = metric;
this.setSimilarityOrder();
}
}