-
Notifications
You must be signed in to change notification settings - Fork 324
/
SimpleVectorStore.ts
218 lines (190 loc) · 6.18 KB
/
SimpleVectorStore.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
import { fs, path } from "@llamaindex/env";
import type { BaseNode } from "../../Node.js";
import { BaseEmbedding } from "../../embeddings/index.js";
import {
getTopKEmbeddings,
getTopKEmbeddingsLearner,
getTopKMMREmbeddings,
} from "../../embeddings/utils.js";
import { exists } from "../FileSystem.js";
import { DEFAULT_PERSIST_DIR } from "../constants.js";
import {
VectorStoreBase,
VectorStoreQueryMode,
type IEmbedModel,
type VectorStoreNoEmbedModel,
type VectorStoreQuery,
type VectorStoreQueryResult,
} from "./types.js";
const LEARNER_MODES = new Set<VectorStoreQueryMode>([
VectorStoreQueryMode.SVM,
VectorStoreQueryMode.LINEAR_REGRESSION,
VectorStoreQueryMode.LOGISTIC_REGRESSION,
]);
const MMR_MODE = VectorStoreQueryMode.MMR;
class SimpleVectorStoreData {
embeddingDict: Record<string, number[]> = {};
textIdToRefDocId: Record<string, string> = {};
}
export class SimpleVectorStore
extends VectorStoreBase
implements VectorStoreNoEmbedModel
{
storesText: boolean = false;
private data: SimpleVectorStoreData;
private persistPath: string | undefined;
constructor(init?: { data?: SimpleVectorStoreData } & Partial<IEmbedModel>) {
super(init?.embedModel);
this.data = init?.data || new SimpleVectorStoreData();
}
static async fromPersistDir(
persistDir: string = DEFAULT_PERSIST_DIR,
embedModel?: BaseEmbedding,
): Promise<SimpleVectorStore> {
const persistPath = path.join(persistDir, "vector_store.json");
return await SimpleVectorStore.fromPersistPath(persistPath, embedModel);
}
get client(): any {
return null;
}
async get(textId: string): Promise<number[]> {
return this.data.embeddingDict[textId];
}
async add(embeddingResults: BaseNode[]): Promise<string[]> {
for (const node of embeddingResults) {
this.data.embeddingDict[node.id_] = node.getEmbedding();
if (!node.sourceNode) {
continue;
}
this.data.textIdToRefDocId[node.id_] = node.sourceNode?.nodeId;
}
if (this.persistPath) {
await this.persist(this.persistPath);
}
return embeddingResults.map((result) => result.id_);
}
async delete(refDocId: string): Promise<void> {
const textIdsToDelete = Object.keys(this.data.textIdToRefDocId).filter(
(textId) => this.data.textIdToRefDocId[textId] === refDocId,
);
for (const textId of textIdsToDelete) {
delete this.data.embeddingDict[textId];
delete this.data.textIdToRefDocId[textId];
}
if (this.persistPath) {
await this.persist(this.persistPath);
}
return Promise.resolve();
}
async query(query: VectorStoreQuery): Promise<VectorStoreQueryResult> {
if (!(query.filters == null)) {
throw new Error(
"Metadata filters not implemented for SimpleVectorStore yet.",
);
}
const items = Object.entries(this.data.embeddingDict);
let nodeIds: string[], embeddings: number[][];
if (query.docIds) {
const availableIds = new Set(query.docIds);
const queriedItems = items.filter((item) => availableIds.has(item[0]));
nodeIds = queriedItems.map((item) => item[0]);
embeddings = queriedItems.map((item) => item[1]);
} else {
// No docIds specified, so use all available items
nodeIds = items.map((item) => item[0]);
embeddings = items.map((item) => item[1]);
}
const queryEmbedding = query.queryEmbedding!;
let topSimilarities: number[], topIds: string[];
if (LEARNER_MODES.has(query.mode)) {
[topSimilarities, topIds] = getTopKEmbeddingsLearner(
queryEmbedding,
embeddings,
query.similarityTopK,
nodeIds,
);
} else if (query.mode === MMR_MODE) {
const mmrThreshold = query.mmrThreshold;
[topSimilarities, topIds] = getTopKMMREmbeddings(
queryEmbedding,
embeddings,
null,
query.similarityTopK,
nodeIds,
mmrThreshold,
);
} else if (query.mode === VectorStoreQueryMode.DEFAULT) {
[topSimilarities, topIds] = getTopKEmbeddings(
queryEmbedding,
embeddings,
query.similarityTopK,
nodeIds,
);
} else {
throw new Error(`Invalid query mode: ${query.mode}`);
}
return Promise.resolve({
similarities: topSimilarities,
ids: topIds,
});
}
async persist(
persistPath: string = path.join(DEFAULT_PERSIST_DIR, "vector_store.json"),
): Promise<void> {
await SimpleVectorStore.persistData(persistPath, this.data);
}
protected static async persistData(
persistPath: string,
data: SimpleVectorStoreData,
): Promise<void> {
const dirPath = path.dirname(persistPath);
if (!(await exists(dirPath))) {
await fs.mkdir(dirPath);
}
await fs.writeFile(persistPath, JSON.stringify(data));
}
static async fromPersistPath(
persistPath: string,
embedModel?: BaseEmbedding,
): Promise<SimpleVectorStore> {
const dirPath = path.dirname(persistPath);
if (!(await exists(dirPath))) {
await fs.mkdir(dirPath, { recursive: true });
}
let dataDict: any = {};
try {
const fileData = await fs.readFile(persistPath);
dataDict = JSON.parse(fileData.toString());
} catch (e) {
console.error(
`No valid data found at path: ${persistPath} starting new store.`,
);
// persist empty data, to ignore this error in the future
await SimpleVectorStore.persistData(
persistPath,
new SimpleVectorStoreData(),
);
}
const data = new SimpleVectorStoreData();
data.embeddingDict = dataDict.embeddingDict ?? {};
data.textIdToRefDocId = dataDict.textIdToRefDocId ?? {};
const store = new SimpleVectorStore({ data, embedModel });
store.persistPath = persistPath;
return store;
}
static fromDict(
saveDict: SimpleVectorStoreData,
embedModel?: BaseEmbedding,
): SimpleVectorStore {
const data = new SimpleVectorStoreData();
data.embeddingDict = saveDict.embeddingDict;
data.textIdToRefDocId = saveDict.textIdToRefDocId;
return new SimpleVectorStore({ data, embedModel });
}
toDict(): SimpleVectorStoreData {
return {
embeddingDict: this.data.embeddingDict,
textIdToRefDocId: this.data.textIdToRefDocId,
};
}
}