-
Notifications
You must be signed in to change notification settings - Fork 367
/
DefaultContextGenerator.ts
100 lines (87 loc) · 2.67 KB
/
DefaultContextGenerator.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
import type { MessageContent, MessageType } from "@llamaindex/core/llms";
import {
type ContextSystemPrompt,
defaultContextSystemPrompt,
type ModuleRecord,
PromptMixin,
} from "@llamaindex/core/prompts";
import { MetadataMode, type NodeWithScore } from "@llamaindex/core/schema";
import type { BaseNodePostprocessor } from "../../postprocessors/index.js";
import type { BaseRetriever } from "../../Retriever.js";
import { createMessageContent } from "../../synthesizers/utils.js";
import type { Context, ContextGenerator } from "./types.js";
export class DefaultContextGenerator
extends PromptMixin
implements ContextGenerator
{
retriever: BaseRetriever;
contextSystemPrompt: ContextSystemPrompt;
nodePostprocessors: BaseNodePostprocessor[];
contextRole: MessageType;
metadataMode?: MetadataMode;
constructor(init: {
retriever: BaseRetriever;
contextSystemPrompt?: ContextSystemPrompt | undefined;
nodePostprocessors?: BaseNodePostprocessor[] | undefined;
contextRole?: MessageType | undefined;
metadataMode?: MetadataMode | undefined;
}) {
super();
this.retriever = init.retriever;
this.contextSystemPrompt =
init?.contextSystemPrompt ?? defaultContextSystemPrompt;
this.nodePostprocessors = init.nodePostprocessors || [];
this.contextRole = init.contextRole ?? "system";
this.metadataMode = init.metadataMode ?? MetadataMode.NONE;
}
protected _getPromptModules(): ModuleRecord {
return {};
}
protected _getPrompts(): { contextSystemPrompt: ContextSystemPrompt } {
return {
contextSystemPrompt: this.contextSystemPrompt,
};
}
protected _updatePrompts(promptsDict: {
contextSystemPrompt: ContextSystemPrompt;
}): void {
if (promptsDict.contextSystemPrompt) {
this.contextSystemPrompt = promptsDict.contextSystemPrompt;
}
}
private async applyNodePostprocessors(
nodes: NodeWithScore[],
query: MessageContent,
) {
let nodesWithScore = nodes;
for (const postprocessor of this.nodePostprocessors) {
nodesWithScore = await postprocessor.postprocessNodes(
nodesWithScore,
query,
);
}
return nodesWithScore;
}
async generate(message: MessageContent): Promise<Context> {
const sourceNodesWithScore = await this.retriever.retrieve({
query: message,
});
const nodes = await this.applyNodePostprocessors(
sourceNodesWithScore,
message,
);
const content = await createMessageContent(
this.contextSystemPrompt,
nodes.map((r) => r.node),
undefined,
this.metadataMode,
);
return {
message: {
content,
role: this.contextRole,
},
nodes,
};
}
}