-
Notifications
You must be signed in to change notification settings - Fork 2.6k
/
Copy pathDocsContextProvider.ts
175 lines (154 loc) · 4.98 KB
/
DocsContextProvider.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
import { BaseContextProvider } from "../";
import {
Chunk,
ContextItem,
ContextProviderDescription,
ContextProviderExtras,
ContextSubmenuItem,
IDE,
LoadSubmenuItemsArgs,
} from "../..";
import DocsService from "../../indexing/docs/DocsService";
import { INSTRUCTIONS_BASE_ITEM } from "./utils";
class DocsContextProvider extends BaseContextProvider {
static nRetrieve = 30;
static nFinal = 15;
static description: ContextProviderDescription = {
title: "docs",
displayTitle: "Docs",
description: "Type to search docs",
type: "submenu",
// Todo: consider a different renderInline so that when multiple docs are referenced in one message,
// Or the doc has an odd name unrelated to the content
// The name of the doc itself doesn't skew the embedding results
renderInlineAs: "",
};
constructor(options: any) {
super(options);
const docsService = DocsService.getSingleton();
docsService?.setGithubToken(this.options?.githubToken);
}
private async _rerankChunks(
chunks: Chunk[],
reranker: NonNullable<ContextProviderExtras["reranker"]>,
fullInput: ContextProviderExtras["fullInput"],
ide: IDE,
) {
let chunksCopy = [...chunks];
try {
const scores = await reranker.rerank(fullInput, chunksCopy);
chunksCopy.sort(
(a, b) => scores[chunksCopy.indexOf(b)] - scores[chunksCopy.indexOf(a)],
);
chunksCopy = chunksCopy.splice(
0,
this.options?.nFinal ?? DocsContextProvider.nFinal,
);
} catch (e) {
void ide.showToast("warning", `Failed to rerank retrieval results\n${e}`);
chunksCopy = chunksCopy.splice(
0,
this.options?.nFinal ?? DocsContextProvider.nFinal,
);
}
return chunksCopy;
}
private _sortAlphabetically(
submenuItems: ContextSubmenuItem[],
): ContextSubmenuItem[] {
// Sort submenu items alphabetically by title
return submenuItems.sort((a, b) => {
return a.title.toString().localeCompare(b.title.toString());
});
}
async getContextItems(
query: string,
extras: ContextProviderExtras,
): Promise<ContextItem[]> {
const nRetrieve = this.options?.nRetrieve ?? DocsContextProvider.nRetrieve;
const useReranking = this.options?.useReranking ?? true;
// Get docs service
const docsService = DocsService.getSingleton();
if (!docsService) {
console.error(`${DocsService.name} has not been initialized`);
return [];
}
await docsService.isInitialized;
// Get chunks
let chunks = await docsService.retrieveChunksFromQuery(
extras.fullInput, // confusing: fullInput = the query, query = startUrl in this case
query,
nRetrieve,
);
if (!chunks?.length) {
return [];
}
// We found chunks, so check if there's a favicon for the docs page
const favicon = await docsService.getFavicon(query);
// Rerank if there's a reranker
if (useReranking && extras.reranker) {
chunks = await this._rerankChunks(
chunks,
extras.reranker,
extras.fullInput,
extras.ide,
);
}
return [
...chunks
.map((chunk) => ({
icon: favicon,
name: chunk.filepath.includes("/tree/main") // For display of GitHub files
? chunk.filepath
.split("/")
.slice(1)
.join("/")
.split("/tree/main/")
.slice(1)
.join("/")
: chunk.otherMetadata?.title || chunk.filepath,
description: chunk.filepath,
content: chunk.content,
uri: {
type: "url" as const,
value: chunk.filepath,
},
}))
.reverse(),
{
...INSTRUCTIONS_BASE_ITEM,
content:
"Use the above documentation to answer the following question. You should not reference " +
"anything outside of what is shown, unless it is a commonly known concept. Reference URLs " +
"whenever possible using markdown formatting. If there isn't enough information to answer " +
"the question, suggest where the user might look to learn more.",
},
];
}
async loadSubmenuItems(
args: LoadSubmenuItemsArgs,
): Promise<ContextSubmenuItem[]> {
// Get docs service
const docsService = DocsService.getSingleton();
if (!docsService) {
console.error(`${DocsService.name} has not been initialized`);
return [];
}
await docsService.isInitialized;
// Create an array to hold submenu items
const submenuItems: ContextSubmenuItem[] = [];
// Get all indexed docs from the database
const docs = (await docsService.listMetadata()) ?? [];
for (const { startUrl, title, favicon } of docs) {
submenuItems.push({
title,
id: startUrl,
description: new URL(startUrl).hostname,
icon: favicon,
});
}
// Sort alphabetically
return this._sortAlphabetically(submenuItems);
}
}
export default DocsContextProvider;