-
Notifications
You must be signed in to change notification settings - Fork 47
/
UpstashVectorStore.js
70 lines (59 loc) · 1.71 KB
/
UpstashVectorStore.js
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
import { VectorStore } from "@langchain/core/vectorstores";
import { Document } from "@langchain/core/documents";
import { Index } from "@upstash/vector";
import { maximalMarginalRelevance } from "@langchain/core/utils/math";
export class UpstashVectorStore extends VectorStore {
_vectorstoreType() {
return "upstash";
}
constructor(embeddings) {
super(embeddings);
this.index = new Index({
url: process.env.UPSTASH_VECTOR_URL,
token: process.env.UPSTASH_VECTOR_TOKEN,
});
}
async similaritySearchVectorWithScore(query, k, filter) {
const result = await this.index.query({
vector: query,
topK: k,
includeVectors: false,
includeMetadata: true,
});
const results = [];
for (let i = 0; i < result.length; i++) {
results.push([
new Document({
pageContent: JSON.stringify(result[i]?.metadata) || "",
}),
]);
}
return results;
}
async maxMarginalRelevanceSearch(query, options) {
const queryEmbedding = await this.embeddings.embedQuery(query);
const result = await this.index.query({
vector: queryEmbedding,
topK: options.fetchK ?? 20,
includeVectors: true,
includeMetadata: true,
});
const embeddingList = result.map((r) => r.vector)
const mmrIndexes = maximalMarginalRelevance(
queryEmbedding,
embeddingList,
options.lambda,
options.k
);
const topMmrMatches = mmrIndexes.map((idx) => result[idx]);
const results = [];
for (let i = 0; i < topMmrMatches.length; i++) {
results.push(
new Document({
pageContent: JSON.stringify(topMmrMatches[i]?.metadata) || "",
}),
);
}
return results;
}
}