-
Notifications
You must be signed in to change notification settings - Fork 295
/
SummaryIndex.ts
265 lines (225 loc) · 6.92 KB
/
SummaryIndex.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
import _ from "lodash";
import { BaseNode, Document } from "../../Node";
import { BaseQueryEngine, RetrieverQueryEngine } from "../../QueryEngine";
import {
CompactAndRefine,
ResponseSynthesizer,
} from "../../ResponseSynthesizer";
import { BaseRetriever } from "../../Retriever";
import {
ServiceContext,
serviceContextFromDefaults,
} from "../../ServiceContext";
import { BaseDocumentStore, RefDocInfo } from "../../storage/docStore/types";
import {
StorageContext,
storageContextFromDefaults,
} from "../../storage/StorageContext";
import {
BaseIndex,
BaseIndexInit,
IndexList,
IndexStructType,
} from "../BaseIndex";
import { BaseNodePostprocessor } from "../BaseNodePostprocessor";
import {
SummaryIndexLLMRetriever,
SummaryIndexRetriever,
} from "./SummaryIndexRetriever";
export enum SummaryRetrieverMode {
DEFAULT = "default",
// EMBEDDING = "embedding",
LLM = "llm",
}
export interface SummaryIndexOptions {
nodes?: BaseNode[];
indexStruct?: IndexList;
indexId?: string;
serviceContext?: ServiceContext;
storageContext?: StorageContext;
}
/**
* A SummaryIndex keeps nodes in a sequential order for use with summarization.
*/
export class SummaryIndex extends BaseIndex<IndexList> {
constructor(init: BaseIndexInit<IndexList>) {
super(init);
}
static async init(options: SummaryIndexOptions): Promise<SummaryIndex> {
const storageContext =
options.storageContext ?? (await storageContextFromDefaults({}));
const serviceContext =
options.serviceContext ?? serviceContextFromDefaults({});
const { docStore, indexStore } = storageContext;
// Setup IndexStruct from storage
let indexStructs = (await indexStore.getIndexStructs()) as IndexList[];
let indexStruct: IndexList | 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 IndexList;
} else {
indexStruct = null;
}
// check indexStruct type
if (indexStruct && indexStruct.type !== IndexStructType.LIST) {
throw new Error(
"Attempting to initialize SummaryIndex with non-list indexStruct",
);
}
if (indexStruct) {
if (options.nodes) {
throw new Error(
"Cannot initialize SummaryIndex with both nodes and indexStruct",
);
}
} else {
if (!options.nodes) {
throw new Error(
"Cannot initialize SummaryIndex without nodes or indexStruct",
);
}
indexStruct = await SummaryIndex.buildIndexFromNodes(
options.nodes,
storageContext.docStore,
);
await indexStore.addIndexStruct(indexStruct);
}
return new SummaryIndex({
storageContext,
serviceContext,
docStore,
indexStore,
indexStruct,
});
}
static async fromDocuments(
documents: Document[],
args: {
storageContext?: StorageContext;
serviceContext?: ServiceContext;
} = {},
): Promise<SummaryIndex> {
let { storageContext, serviceContext } = args;
storageContext = storageContext ?? (await storageContextFromDefaults({}));
serviceContext = serviceContext ?? serviceContextFromDefaults({});
const docStore = storageContext.docStore;
docStore.addDocuments(documents, true);
for (const doc of documents) {
docStore.setDocumentHash(doc.id_, doc.hash);
}
const nodes = serviceContext.nodeParser.getNodesFromDocuments(documents);
const index = await SummaryIndex.init({
nodes,
storageContext,
serviceContext,
});
return index;
}
asRetriever(options?: { mode: SummaryRetrieverMode }): BaseRetriever {
const { mode = SummaryRetrieverMode.DEFAULT } = options ?? {};
switch (mode) {
case SummaryRetrieverMode.DEFAULT:
return new SummaryIndexRetriever(this);
case SummaryRetrieverMode.LLM:
return new SummaryIndexLLMRetriever(this);
default:
throw new Error(`Unknown retriever mode: ${mode}`);
}
}
asQueryEngine(options?: {
retriever?: BaseRetriever;
responseSynthesizer?: ResponseSynthesizer;
preFilters?: unknown;
nodePostprocessors?: BaseNodePostprocessor[];
}): BaseQueryEngine {
let { retriever, responseSynthesizer } = options ?? {};
if (!retriever) {
retriever = this.asRetriever();
}
if (!responseSynthesizer) {
let responseBuilder = new CompactAndRefine(this.serviceContext);
responseSynthesizer = new ResponseSynthesizer({
serviceContext: this.serviceContext,
responseBuilder,
});
}
return new RetrieverQueryEngine(
retriever,
responseSynthesizer,
options?.preFilters,
options?.nodePostprocessors,
);
}
static async buildIndexFromNodes(
nodes: BaseNode[],
docStore: BaseDocumentStore,
indexStruct?: IndexList,
): Promise<IndexList> {
indexStruct = indexStruct || new IndexList();
await docStore.addDocuments(nodes, true);
for (const node of nodes) {
indexStruct.addNode(node);
}
return indexStruct;
}
async insertNodes(nodes: BaseNode[]): Promise<void> {
for (const node of nodes) {
this.indexStruct.addNode(node);
}
}
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;
}
async deleteNodes(nodeIds: string[], deleteFromDocStore: boolean) {
this.indexStruct.nodes = this.indexStruct.nodes.filter(
(existingNodeId: string) => !nodeIds.includes(existingNodeId),
);
if (deleteFromDocStore) {
for (const nodeId of nodeIds) {
await this.docStore.deleteDocument(nodeId, false);
}
}
await this.storageContext.indexStore.addIndexStruct(this.indexStruct);
}
async getRefDocInfo(): Promise<Record<string, RefDocInfo>> {
const nodeDocIds = this.indexStruct.nodes;
const nodes = await this.docStore.getNodes(nodeDocIds);
const refDocInfoMap: Record<string, RefDocInfo> = {};
for (const node of nodes) {
const refNode = node.sourceNode;
if (_.isNil(refNode)) {
continue;
}
const refDocInfo = await this.docStore.getRefDocInfo(refNode.nodeId);
if (_.isNil(refDocInfo)) {
continue;
}
refDocInfoMap[refNode.nodeId] = refDocInfo;
}
return refDocInfoMap;
}
}
// Legacy
export type ListIndex = SummaryIndex;
export type ListRetrieverMode = SummaryRetrieverMode;