-
Notifications
You must be signed in to change notification settings - Fork 295
/
index.ts
379 lines (334 loc) · 11.7 KB
/
index.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
import type { BaseNode, Document, NodeWithScore } from "../../Node.js";
import { MetadataMode } from "../../Node.js";
import type {
KeywordExtractPrompt,
QueryKeywordExtractPrompt,
} from "../../Prompt.js";
import {
defaultKeywordExtractPrompt,
defaultQueryKeywordExtractPrompt,
} from "../../Prompt.js";
import type { BaseRetriever, RetrieveParams } from "../../Retriever.js";
import type { ServiceContext } from "../../ServiceContext.js";
import { serviceContextFromDefaults } from "../../ServiceContext.js";
import { RetrieverQueryEngine } from "../../engines/query/index.js";
import type { BaseNodePostprocessor } from "../../postprocessors/index.js";
import type { StorageContext } from "../../storage/StorageContext.js";
import { storageContextFromDefaults } from "../../storage/StorageContext.js";
import type { BaseDocumentStore } from "../../storage/docStore/types.js";
import type { BaseSynthesizer } from "../../synthesizers/index.js";
import type { QueryEngine } from "../../types.js";
import type { BaseIndexInit } from "../BaseIndex.js";
import { BaseIndex, KeywordTable } from "../BaseIndex.js";
import { IndexStructType } from "../json-to-index-struct.js";
import {
extractKeywordsGivenResponse,
rakeExtractKeywords,
simpleExtractKeywords,
} from "./utils.js";
import { llmFromSettingsOrContext } from "../../Settings.js";
import type { LLM } from "../../llm/types.js";
export interface KeywordIndexOptions {
nodes?: BaseNode[];
indexStruct?: KeywordTable;
indexId?: string;
serviceContext?: ServiceContext;
llm?: LLM;
storageContext?: StorageContext;
}
export enum KeywordTableRetrieverMode {
DEFAULT = "DEFAULT",
SIMPLE = "SIMPLE",
RAKE = "RAKE",
}
// Base Keyword Table Retriever
abstract class BaseKeywordTableRetriever implements BaseRetriever {
protected index: KeywordTableIndex;
protected indexStruct: KeywordTable;
protected docstore: BaseDocumentStore;
protected llm: LLM;
protected maxKeywordsPerQuery: number; // Maximum number of keywords to extract from query.
protected numChunksPerQuery: number; // Maximum number of text chunks to query.
protected keywordExtractTemplate: KeywordExtractPrompt; // A Keyword Extraction Prompt
protected queryKeywordExtractTemplate: QueryKeywordExtractPrompt; // A Query Keyword Extraction Prompt
constructor({
index,
keywordExtractTemplate,
queryKeywordExtractTemplate,
maxKeywordsPerQuery = 10,
numChunksPerQuery = 10,
}: {
index: KeywordTableIndex;
keywordExtractTemplate?: KeywordExtractPrompt;
queryKeywordExtractTemplate?: QueryKeywordExtractPrompt;
maxKeywordsPerQuery: number;
numChunksPerQuery: number;
}) {
this.index = index;
this.indexStruct = index.indexStruct;
this.docstore = index.docStore;
this.llm = llmFromSettingsOrContext(index.serviceContext);
this.maxKeywordsPerQuery = maxKeywordsPerQuery;
this.numChunksPerQuery = numChunksPerQuery;
this.keywordExtractTemplate =
keywordExtractTemplate || defaultKeywordExtractPrompt;
this.queryKeywordExtractTemplate =
queryKeywordExtractTemplate || defaultQueryKeywordExtractPrompt;
}
abstract getKeywords(query: string): Promise<string[]>;
async retrieve({ query }: RetrieveParams): Promise<NodeWithScore[]> {
const keywords = await this.getKeywords(query);
const chunkIndicesCount: { [key: string]: number } = {};
const filteredKeywords = keywords.filter((keyword) =>
this.indexStruct.table.has(keyword),
);
for (const keyword of filteredKeywords) {
for (const nodeId of this.indexStruct.table.get(keyword) || []) {
chunkIndicesCount[nodeId] = (chunkIndicesCount[nodeId] ?? 0) + 1;
}
}
const sortedChunkIndices = Object.keys(chunkIndicesCount)
.sort((a, b) => chunkIndicesCount[b] - chunkIndicesCount[a])
.slice(0, this.numChunksPerQuery);
const sortedNodes = await this.docstore.getNodes(sortedChunkIndices);
return sortedNodes.map((node) => ({ node }));
}
}
// Extracts keywords using LLMs.
export class KeywordTableLLMRetriever extends BaseKeywordTableRetriever {
async getKeywords(query: string): Promise<string[]> {
const response = await this.llm.complete({
prompt: this.queryKeywordExtractTemplate({
question: query,
maxKeywords: this.maxKeywordsPerQuery,
}),
});
const keywords = extractKeywordsGivenResponse(response.text, "KEYWORDS:");
return [...keywords];
}
}
// Extracts keywords using simple regex-based keyword extractor.
export class KeywordTableSimpleRetriever extends BaseKeywordTableRetriever {
getKeywords(query: string): Promise<string[]> {
return Promise.resolve([
...simpleExtractKeywords(query, this.maxKeywordsPerQuery),
]);
}
}
// Extracts keywords using RAKE keyword extractor
export class KeywordTableRAKERetriever extends BaseKeywordTableRetriever {
getKeywords(query: string): Promise<string[]> {
return Promise.resolve([
...rakeExtractKeywords(query, this.maxKeywordsPerQuery),
]);
}
}
const KeywordTableRetrieverMap = {
[KeywordTableRetrieverMode.DEFAULT]: KeywordTableLLMRetriever,
[KeywordTableRetrieverMode.SIMPLE]: KeywordTableSimpleRetriever,
[KeywordTableRetrieverMode.RAKE]: KeywordTableRAKERetriever,
};
/**
* The KeywordTableIndex, an index that extracts keywords from each Node and builds a mapping from each keyword to the corresponding Nodes of that keyword.
*/
export class KeywordTableIndex extends BaseIndex<KeywordTable> {
constructor(init: BaseIndexInit<KeywordTable>) {
super(init);
}
static async init(options: KeywordIndexOptions): Promise<KeywordTableIndex> {
const storageContext =
options.storageContext ?? (await storageContextFromDefaults({}));
const serviceContext = options.serviceContext;
const { docStore, indexStore } = storageContext;
// Setup IndexStruct from storage
const indexStructs = (await indexStore.getIndexStructs()) as KeywordTable[];
let indexStruct: KeywordTable | null;
if (options.indexStruct && indexStructs.length > 0) {
throw new Error(
"Cannot initialize index with both indexStruct and indexStore",
);
}
if (options.indexStruct) {
indexStruct = options.indexStruct;
} else if (indexStructs.length == 1) {
indexStruct = indexStructs[0];
} else if (indexStructs.length > 1 && options.indexId) {
indexStruct = (await indexStore.getIndexStruct(
options.indexId,
)) as KeywordTable;
} else {
indexStruct = null;
}
// check indexStruct type
if (indexStruct && indexStruct.type !== IndexStructType.KEYWORD_TABLE) {
throw new Error(
"Attempting to initialize KeywordTableIndex with non-keyword table indexStruct",
);
}
if (indexStruct) {
if (options.nodes) {
throw new Error(
"Cannot initialize KeywordTableIndex with both nodes and indexStruct",
);
}
} else {
if (!options.nodes) {
throw new Error(
"Cannot initialize KeywordTableIndex without nodes or indexStruct",
);
}
indexStruct = await KeywordTableIndex.buildIndexFromNodes(
options.nodes,
storageContext.docStore,
serviceContext,
);
await indexStore.addIndexStruct(indexStruct);
}
return new KeywordTableIndex({
storageContext,
serviceContext,
docStore,
indexStore,
indexStruct,
});
}
asRetriever(options?: any): BaseRetriever {
const { mode = KeywordTableRetrieverMode.DEFAULT, ...otherOptions } =
options ?? {};
const KeywordTableRetriever =
KeywordTableRetrieverMap[mode as KeywordTableRetrieverMode];
if (KeywordTableRetriever) {
return new KeywordTableRetriever({ index: this, ...otherOptions });
}
throw new Error(`Unknown retriever mode: ${mode}`);
}
asQueryEngine(options?: {
retriever?: BaseRetriever;
responseSynthesizer?: BaseSynthesizer;
preFilters?: unknown;
nodePostprocessors?: BaseNodePostprocessor[];
}): QueryEngine {
const { retriever, responseSynthesizer } = options ?? {};
return new RetrieverQueryEngine(
retriever ?? this.asRetriever(),
responseSynthesizer,
options?.preFilters,
options?.nodePostprocessors,
);
}
static async extractKeywords(
text: string,
serviceContext?: ServiceContext,
): Promise<Set<string>> {
const llm = llmFromSettingsOrContext(serviceContext);
const response = await llm.complete({
prompt: defaultKeywordExtractPrompt({
context: text,
}),
});
return extractKeywordsGivenResponse(response.text, "KEYWORDS:");
}
/**
* High level API: split documents, get keywords, and build index.
* @param documents
* @param storageContext
* @param serviceContext
* @returns
*/
static async fromDocuments(
documents: Document[],
args: {
storageContext?: StorageContext;
serviceContext?: ServiceContext;
} = {},
): Promise<KeywordTableIndex> {
let { storageContext, serviceContext } = args;
storageContext = storageContext ?? (await storageContextFromDefaults({}));
serviceContext = serviceContext ?? serviceContextFromDefaults({});
const docStore = storageContext.docStore;
await docStore.addDocuments(documents, true);
for (const doc of documents) {
docStore.setDocumentHash(doc.id_, doc.hash);
}
const nodes = serviceContext.nodeParser.getNodesFromDocuments(documents);
const index = await KeywordTableIndex.init({
nodes,
storageContext,
serviceContext,
});
return index;
}
/**
* Get keywords for nodes and place them into the index.
* @param nodes
* @param serviceContext
* @param vectorStore
* @returns
*/
static async buildIndexFromNodes(
nodes: BaseNode[],
docStore: BaseDocumentStore,
serviceContext?: ServiceContext,
): Promise<KeywordTable> {
const indexStruct = new KeywordTable();
await docStore.addDocuments(nodes, true);
for (const node of nodes) {
const keywords = await KeywordTableIndex.extractKeywords(
node.getContent(MetadataMode.LLM),
serviceContext,
);
indexStruct.addNode([...keywords], node.id_);
}
return indexStruct;
}
async insertNodes(nodes: BaseNode[]) {
for (const node of nodes) {
const keywords = await KeywordTableIndex.extractKeywords(
node.getContent(MetadataMode.LLM),
this.serviceContext,
);
this.indexStruct.addNode([...keywords], node.id_);
}
}
deleteNode(nodeId: string): void {
const keywordsToDelete: Set<string> = new Set();
for (const [keyword, existingNodeIds] of Object.entries(
this.indexStruct.table,
)) {
const index = existingNodeIds.indexOf(nodeId);
if (index !== -1) {
existingNodeIds.splice(index, 1);
// Delete keywords that have zero nodes
if (existingNodeIds.length === 0) {
keywordsToDelete.add(keyword);
}
}
}
this.indexStruct.deleteNode([...keywordsToDelete], nodeId);
}
async deleteNodes(nodeIds: string[], deleteFromDocStore: boolean) {
nodeIds.forEach((nodeId) => {
this.deleteNode(nodeId);
});
if (deleteFromDocStore) {
for (const nodeId of nodeIds) {
await this.docStore.deleteDocument(nodeId, false);
}
}
await this.storageContext.indexStore.addIndexStruct(this.indexStruct);
}
async deleteRefDoc(
refDocId: string,
deleteFromDocStore?: boolean,
): Promise<void> {
const refDocInfo = await this.docStore.getRefDocInfo(refDocId);
if (!refDocInfo) {
return;
}
await this.deleteNodes(refDocInfo.nodeIds, false);
if (deleteFromDocStore) {
await this.docStore.deleteRefDoc(refDocId, false);
}
return;
}
}