forked from run-llama/LlamaIndexTS
-
Notifications
You must be signed in to change notification settings - Fork 0
/
RouterQueryEngine.ts
189 lines (159 loc) · 5.02 KB
/
RouterQueryEngine.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
import {
BaseQueryEngine,
type QueryBundle,
type QueryType,
} from "@llamaindex/core/query-engine";
import {
BaseSynthesizer,
getResponseSynthesizer,
} from "@llamaindex/core/response-synthesizers";
import { EngineResponse, type NodeWithScore } from "@llamaindex/core/schema";
import { extractText } from "@llamaindex/core/utils";
import type { ServiceContext } from "../../ServiceContext.js";
import { llmFromSettingsOrContext } from "../../Settings.js";
import type { BaseSelector } from "../../selectors/index.js";
import { LLMSingleSelector } from "../../selectors/index.js";
type RouterQueryEngineTool = {
queryEngine: BaseQueryEngine;
description: string;
};
type RouterQueryEngineMetadata = {
description: string;
};
async function combineResponses(
summarizer: BaseSynthesizer,
responses: EngineResponse[],
queryBundle: QueryBundle,
verbose: boolean = false,
): Promise<EngineResponse> {
if (verbose) {
console.log("Combining responses from multiple query engines.");
}
const sourceNodes: NodeWithScore[] = [];
for (const response of responses) {
if (response?.sourceNodes) {
sourceNodes.push(...response.sourceNodes);
}
}
return await summarizer.synthesize({
query: queryBundle,
nodes: sourceNodes,
});
}
/**
* A query engine that uses multiple query engines and selects the best one.
*/
export class RouterQueryEngine extends BaseQueryEngine {
private selector: BaseSelector;
private queryEngines: BaseQueryEngine[];
private metadatas: RouterQueryEngineMetadata[];
private summarizer: BaseSynthesizer;
private verbose: boolean;
constructor(init: {
selector: BaseSelector;
queryEngineTools: RouterQueryEngineTool[];
serviceContext?: ServiceContext | undefined;
summarizer?: BaseSynthesizer | undefined;
verbose?: boolean | undefined;
}) {
super();
this.selector = init.selector;
this.queryEngines = init.queryEngineTools.map((tool) => tool.queryEngine);
this.metadatas = init.queryEngineTools.map((tool) => ({
description: tool.description,
}));
this.summarizer =
init.summarizer || getResponseSynthesizer("tree_summarize");
this.verbose = init.verbose ?? false;
}
override async _query(strOrQueryBundle: QueryType, stream?: boolean) {
const response = await this.queryRoute(
typeof strOrQueryBundle === "string"
? { query: strOrQueryBundle }
: strOrQueryBundle,
);
if (stream) {
throw new Error("Streaming is not supported yet.");
}
return response;
}
protected _getPrompts() {
return {};
}
protected _updatePrompts() {}
protected _getPromptModules() {
return {
selector: this.selector,
summarizer: this.summarizer,
};
}
static fromDefaults(init: {
queryEngineTools: RouterQueryEngineTool[];
selector?: BaseSelector;
serviceContext?: ServiceContext;
summarizer?: BaseSynthesizer;
verbose?: boolean;
}) {
const serviceContext = init.serviceContext;
return new RouterQueryEngine({
selector:
init.selector ??
new LLMSingleSelector({
llm: llmFromSettingsOrContext(serviceContext),
}),
queryEngineTools: init.queryEngineTools,
serviceContext,
summarizer: init.summarizer,
verbose: init.verbose,
});
}
private async queryRoute(query: QueryBundle): Promise<EngineResponse> {
const result = await this.selector.select(this.metadatas, query);
if (result.selections.length > 1) {
const responses: EngineResponse[] = [];
for (let i = 0; i < result.selections.length; i++) {
const engineInd = result.selections[i]!;
const logStr = `Selecting query engine ${engineInd.index}: ${result.selections[i]!.index}.`;
if (this.verbose) {
console.log(logStr + "\n");
}
const selectedQueryEngine = this.queryEngines[engineInd.index]!;
responses.push(
await selectedQueryEngine.query({ query, stream: false }),
);
}
if (responses.length > 1) {
const finalResponse = await combineResponses(
this.summarizer,
responses,
query,
this.verbose,
);
return finalResponse;
} else {
return responses[0]!;
}
} else {
let selectedQueryEngine;
try {
selectedQueryEngine = this.queryEngines[result.selections[0]!.index];
const logStr = `Selecting query engine ${result.selections[0]!.index}: ${result.selections[0]!.reason}`;
if (this.verbose) {
console.log(logStr + "\n");
}
} catch (e) {
throw new Error("Failed to select query engine");
}
if (!selectedQueryEngine) {
throw new Error("Selected query engine is null");
}
const finalResponse = await selectedQueryEngine.query({
query: extractText(query),
});
// add selected result
finalResponse.metadata = finalResponse.metadata || {};
finalResponse.metadata["selectorResult"] = result;
return finalResponse;
}
}
}