-
Notifications
You must be signed in to change notification settings - Fork 2.2k
/
convex.ts
376 lines (357 loc) Β· 11.3 KB
/
convex.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
// eslint-disable-next-line import/no-extraneous-dependencies
import {
DocumentByInfo,
FieldPaths,
FilterExpression,
FunctionReference,
GenericActionCtx,
GenericDataModel,
GenericTableInfo,
NamedTableInfo,
NamedVectorIndex,
TableNamesInDataModel,
VectorFilterBuilder,
VectorIndexNames,
makeFunctionReference,
} from "convex/server";
import type { EmbeddingsInterface } from "@langchain/core/embeddings";
import { VectorStore } from "@langchain/core/vectorstores";
import { Document } from "@langchain/core/documents";
/**
* Type that defines the config required to initialize the
* ConvexVectorStore class. It includes the table name,
* index name, text field name, and embedding field name.
*/
export type ConvexVectorStoreConfig<
DataModel extends GenericDataModel,
TableName extends TableNamesInDataModel<DataModel>,
IndexName extends VectorIndexNames<NamedTableInfo<DataModel, TableName>>,
TextFieldName extends FieldPaths<NamedTableInfo<DataModel, TableName>>,
EmbeddingFieldName extends FieldPaths<NamedTableInfo<DataModel, TableName>>,
MetadataFieldName extends FieldPaths<NamedTableInfo<DataModel, TableName>>,
InsertMutation extends FunctionReference<
"mutation",
"internal",
{ table: string; document: object }
>,
GetQuery extends FunctionReference<
"query",
"internal",
{ id: string },
object | null
>
> = {
readonly ctx: GenericActionCtx<DataModel>;
/**
* Defaults to "documents"
*/
readonly table?: TableName;
/**
* Defaults to "byEmbedding"
*/
readonly index?: IndexName;
/**
* Defaults to "text"
*/
readonly textField?: TextFieldName;
/**
* Defaults to "embedding"
*/
readonly embeddingField?: EmbeddingFieldName;
/**
* Defaults to "metadata"
*/
readonly metadataField?: MetadataFieldName;
/**
* Defaults to `internal.langchain.db.insert`
*/
readonly insert?: InsertMutation;
/**
* Defaults to `internal.langchain.db.get`
*/
readonly get?: GetQuery;
};
/**
* Class that is a wrapper around Convex storage and vector search. It is used
* to insert embeddings in Convex documents with a vector search index,
* and perform a vector search on them.
*
* ConvexVectorStore does NOT implement maxMarginalRelevanceSearch.
*/
export class ConvexVectorStore<
DataModel extends GenericDataModel,
TableName extends TableNamesInDataModel<DataModel>,
IndexName extends VectorIndexNames<NamedTableInfo<DataModel, TableName>>,
TextFieldName extends FieldPaths<NamedTableInfo<DataModel, TableName>>,
EmbeddingFieldName extends FieldPaths<NamedTableInfo<DataModel, TableName>>,
MetadataFieldName extends FieldPaths<NamedTableInfo<DataModel, TableName>>,
InsertMutation extends FunctionReference<
"mutation",
"internal",
{ table: string; document: object }
>,
GetQuery extends FunctionReference<
"query",
"internal",
{ id: string },
object | null
>
> extends VectorStore {
/**
* Type that defines the filter used in the
* similaritySearchVectorWithScore and maxMarginalRelevanceSearch methods.
* It includes limit, filter and a flag to include embeddings.
*/
declare FilterType: {
filter?: (
q: VectorFilterBuilder<
DocumentByInfo<GenericTableInfo>,
NamedVectorIndex<NamedTableInfo<DataModel, TableName>, IndexName>
>
) => FilterExpression<boolean>;
includeEmbeddings?: boolean;
};
private readonly ctx: GenericActionCtx<DataModel>;
private readonly table: TableName;
private readonly index: IndexName;
private readonly textField: TextFieldName;
private readonly embeddingField: EmbeddingFieldName;
private readonly metadataField: MetadataFieldName;
private readonly insert: InsertMutation;
private readonly get: GetQuery;
_vectorstoreType(): string {
return "convex";
}
constructor(
embeddings: EmbeddingsInterface,
config: ConvexVectorStoreConfig<
DataModel,
TableName,
IndexName,
TextFieldName,
EmbeddingFieldName,
MetadataFieldName,
InsertMutation,
GetQuery
>
) {
super(embeddings, config);
this.ctx = config.ctx;
this.table = config.table ?? ("documents" as TableName);
this.index = config.index ?? ("byEmbedding" as IndexName);
this.textField = config.textField ?? ("text" as TextFieldName);
this.embeddingField =
config.embeddingField ?? ("embedding" as EmbeddingFieldName);
this.metadataField =
config.metadataField ?? ("metadata" as MetadataFieldName);
this.insert =
// eslint-disable-next-line @typescript-eslint/no-explicit-any
config.insert ?? (makeFunctionReference("langchain/db:insert") as any);
// eslint-disable-next-line @typescript-eslint/no-explicit-any
this.get = config.get ?? (makeFunctionReference("langchain/db:get") as any);
}
/**
* Add vectors and their corresponding documents to the Convex table.
* @param vectors Vectors to be added.
* @param documents Corresponding documents to be added.
* @returns Promise that resolves when the vectors and documents have been added.
*/
async addVectors(vectors: number[][], documents: Document[]): Promise<void> {
const convexDocuments = vectors.map((embedding, idx) => ({
[this.textField]: documents[idx].pageContent,
[this.embeddingField]: embedding,
[this.metadataField]: documents[idx].metadata,
}));
// TODO: Remove chunking when Convex handles the concurrent requests correctly
const PAGE_SIZE = 16;
for (let i = 0; i < convexDocuments.length; i += PAGE_SIZE) {
await Promise.all(
convexDocuments.slice(i, i + PAGE_SIZE).map((document) =>
this.ctx.runMutation(this.insert, {
table: this.table,
document,
// eslint-disable-next-line @typescript-eslint/no-explicit-any
} as any)
)
);
}
}
/**
* Add documents to the Convex table. It first converts
* the documents to vectors using the embeddings and then calls the
* addVectors method.
* @param documents Documents to be added.
* @returns Promise that resolves when the documents have been added.
*/
async addDocuments(documents: Document[]): Promise<void> {
const texts = documents.map(({ pageContent }) => pageContent);
return this.addVectors(
await this.embeddings.embedDocuments(texts),
documents
);
}
/**
* Similarity search on the vectors stored in the
* Convex table. It returns a list of documents and their
* corresponding similarity scores.
* @param query Query vector for the similarity search.
* @param k Number of nearest neighbors to return.
* @param filter Optional filter to be applied.
* @returns Promise that resolves to a list of documents and their corresponding similarity scores.
*/
async similaritySearchVectorWithScore(
query: number[],
k: number,
filter?: this["FilterType"]
): Promise<[Document, number][]> {
const idsAndScores = await this.ctx.vectorSearch(this.table, this.index, {
vector: query,
limit: k,
filter: filter?.filter,
});
const documents = await Promise.all(
idsAndScores.map(({ _id }) =>
// eslint-disable-next-line @typescript-eslint/no-explicit-any
this.ctx.runQuery(this.get, { id: _id } as any)
)
);
return documents.map(
(
{
[this.textField]: text,
[this.embeddingField]: embedding,
[this.metadataField]: metadata,
},
idx
) => [
new Document({
pageContent: text as string,
metadata: {
...metadata,
...(filter?.includeEmbeddings ? { embedding } : null),
},
}),
idsAndScores[idx]._score,
]
);
}
/**
* Static method to create an instance of ConvexVectorStore from a
* list of texts. It first converts the texts to vectors and then adds
* them to the Convex table.
* @param texts List of texts to be converted to vectors.
* @param metadatas Metadata for the texts.
* @param embeddings Embeddings to be used for conversion.
* @param dbConfig Database configuration for Convex.
* @returns Promise that resolves to a new instance of ConvexVectorStore.
*/
static async fromTexts<
DataModel extends GenericDataModel,
TableName extends TableNamesInDataModel<DataModel>,
IndexName extends VectorIndexNames<NamedTableInfo<DataModel, TableName>>,
TextFieldName extends FieldPaths<NamedTableInfo<DataModel, TableName>>,
EmbeddingFieldName extends FieldPaths<NamedTableInfo<DataModel, TableName>>,
MetadataFieldName extends FieldPaths<NamedTableInfo<DataModel, TableName>>,
InsertMutation extends FunctionReference<
"mutation",
"internal",
{ table: string; document: object }
>,
GetQuery extends FunctionReference<
"query",
"internal",
{ id: string },
object | null
>
>(
texts: string[],
metadatas: object[] | object,
embeddings: EmbeddingsInterface,
dbConfig: ConvexVectorStoreConfig<
DataModel,
TableName,
IndexName,
TextFieldName,
EmbeddingFieldName,
MetadataFieldName,
InsertMutation,
GetQuery
>
): Promise<
ConvexVectorStore<
DataModel,
TableName,
IndexName,
TextFieldName,
EmbeddingFieldName,
MetadataFieldName,
InsertMutation,
GetQuery
>
> {
const docs = texts.map(
(text, i) =>
new Document({
pageContent: text,
metadata: Array.isArray(metadatas) ? metadatas[i] : metadatas,
})
);
return ConvexVectorStore.fromDocuments(docs, embeddings, dbConfig);
}
/**
* Static method to create an instance of ConvexVectorStore from a
* list of documents. It first converts the documents to vectors and then
* adds them to the Convex table.
* @param docs List of documents to be converted to vectors.
* @param embeddings Embeddings to be used for conversion.
* @param dbConfig Database configuration for Convex.
* @returns Promise that resolves to a new instance of ConvexVectorStore.
*/
static async fromDocuments<
DataModel extends GenericDataModel,
TableName extends TableNamesInDataModel<DataModel>,
IndexName extends VectorIndexNames<NamedTableInfo<DataModel, TableName>>,
TextFieldName extends FieldPaths<NamedTableInfo<DataModel, TableName>>,
EmbeddingFieldName extends FieldPaths<NamedTableInfo<DataModel, TableName>>,
MetadataFieldName extends FieldPaths<NamedTableInfo<DataModel, TableName>>,
InsertMutation extends FunctionReference<
"mutation",
"internal",
{ table: string; document: object }
>,
GetQuery extends FunctionReference<
"query",
"internal",
{ id: string },
object | null
>
>(
docs: Document[],
embeddings: EmbeddingsInterface,
dbConfig: ConvexVectorStoreConfig<
DataModel,
TableName,
IndexName,
TextFieldName,
EmbeddingFieldName,
MetadataFieldName,
InsertMutation,
GetQuery
>
): Promise<
ConvexVectorStore<
DataModel,
TableName,
IndexName,
TextFieldName,
EmbeddingFieldName,
MetadataFieldName,
InsertMutation,
GetQuery
>
> {
const instance = new this(embeddings, dbConfig);
await instance.addDocuments(docs);
return instance;
}
}