forked from continuedev/continue
-
Notifications
You must be signed in to change notification settings - Fork 0
/
DocsContextProvider.ts
215 lines (181 loc) · 5.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
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
import { BaseContextProvider } from "../";
import {
Chunk,
ContextItem,
ContextProviderDescription,
ContextProviderExtras,
ContextSubmenuItem,
LoadSubmenuItemsArgs,
} from "../..";
import DocsService from "../../indexing/docs/DocsService";
import preIndexedDocs from "../../indexing/docs/preIndexedDocs";
import { Telemetry } from "../../util/posthog";
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",
};
constructor(options: any) {
super(options);
}
private async _rerankChunks(
chunks: Chunk[],
reranker: NonNullable<ContextProviderExtras["reranker"]>,
fullInput: ContextProviderExtras["fullInput"],
) {
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) {
console.warn(`Failed to rerank docs results: ${e}`);
chunksCopy = chunksCopy.splice(
0,
this.options?.nFinal ?? DocsContextProvider.nFinal,
);
}
return chunksCopy;
}
private _sortByPreIndexedDocs(
submenuItems: ContextSubmenuItem[],
): ContextSubmenuItem[] {
// Sort submenuItems such that the objects with titles which don't occur in configs occur first, and alphabetized
return submenuItems.sort((a, b) => {
const aTitleInConfigs = a.metadata?.preIndexed ?? false;
const bTitleInConfigs = b.metadata?.preIndexed ?? false;
// Primary criterion: Items not in configs come first
if (!aTitleInConfigs && bTitleInConfigs) {
return -1;
} else if (aTitleInConfigs && !bTitleInConfigs) {
return 1;
} else {
// Secondary criterion: Alphabetical order when both items are in the same category
return a.title.toString().localeCompare(b.title.toString());
}
});
}
async getContextItems(
query: string,
extras: ContextProviderExtras,
): Promise<ContextItem[]> {
const docsService = DocsService.getSingleton();
if (!docsService) {
console.error(`${DocsService.name} has not been initialized`);
return [];
}
const isJetBrainsAndPreIndexedDocsProvider =
await docsService.isJetBrainsAndPreIndexedDocsProvider();
if (isJetBrainsAndPreIndexedDocsProvider) {
await extras.ide.showToast(
"error",
`${DocsService.preIndexedDocsEmbeddingsProvider.id} is configured as ` +
"the embeddings provider, but it cannot be used with JetBrains. " +
"Please select a different embeddings provider to use the '@docs' " +
"context provider.",
);
return [];
}
const preIndexedDoc = preIndexedDocs[query];
if (!!preIndexedDoc) {
void Telemetry.capture("docs_pre_indexed_doc_used", {
doc: preIndexedDoc["title"],
});
}
const embeddingsProvider = await docsService.getEmbeddingsProvider(
!!preIndexedDoc,
);
const [vector] = await embeddingsProvider.embed([extras.fullInput]);
let chunks = await docsService.retrieveChunks(
query,
vector,
this.options?.nRetrieve ?? DocsContextProvider.nRetrieve,
);
const favicon = await docsService.getFavicon(query);
if (extras.reranker) {
chunks = await this._rerankChunks(
chunks,
extras.reranker,
extras.fullInput,
);
}
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[]> {
const docsService = DocsService.getSingleton();
if (!docsService) {
console.error(`${DocsService.name} has not been initialized`);
return [];
}
const docs = (await docsService.list()) ?? [];
const canUsePreindexedDocs = await docsService.canUsePreindexedDocs();
const submenuItemsMap = new Map<string, ContextSubmenuItem>();
if (canUsePreindexedDocs) {
for (const { startUrl, title } of Object.values(preIndexedDocs)) {
submenuItemsMap.set(startUrl, {
title,
id: startUrl,
description: new URL(startUrl).hostname,
metadata: {
preIndexed: true,
},
});
}
}
for (const { startUrl, title, favicon } of docs) {
submenuItemsMap.set(startUrl, {
title,
id: startUrl,
description: new URL(startUrl).hostname,
icon: favicon,
});
}
const submenuItems = Array.from(submenuItemsMap.values());
if (canUsePreindexedDocs) {
return this._sortByPreIndexedDocs(submenuItems);
}
return submenuItems;
}
}
export default DocsContextProvider;