Elffuss BraidHub

kikocis/continue public

main · 5.4 KiBRawPermalink
1import { BaseContextProvider } from "../";
2import {
3 Chunk,
4 ContextItem,
5 ContextProviderDescription,
6 ContextProviderExtras,
7 ContextSubmenuItem,
8 IDE,
9 LoadSubmenuItemsArgs,
10} from "../..";
11import DocsService from "../../indexing/docs/DocsService";
12
13import { INSTRUCTIONS_BASE_ITEM } from "./utils";
14
15class DocsContextProvider extends BaseContextProvider {
16 static nRetrieve = 30;
17 static nFinal = 15;
18 static description: ContextProviderDescription = {
19 title: "docs",
20 displayTitle: "Docs",
21 description: "Type to search docs",
22 type: "submenu",
23 // Todo: consider a different renderInline so that when multiple docs are referenced in one message,
24 // Or the doc has an odd name unrelated to the content
25 // The name of the doc itself doesn't skew the embedding results
26 renderInlineAs: "",
27 };
28
29 constructor(options: any) {
30 super(options);
31 const docsService = DocsService.getSingleton();
32 docsService?.setGithubToken(this.options?.githubToken);
33 }
34
35 private async _rerankChunks(
36 chunks: Chunk[],
37 reranker: NonNullable<ContextProviderExtras["reranker"]>,
38 fullInput: ContextProviderExtras["fullInput"],
39 ide: IDE,
40 ) {
41 let chunksCopy = [...chunks];
42
43 try {
44 const scores = await reranker.rerank(fullInput, chunksCopy);
45
46 if (Array.isArray(scores)) {
47 // reranker model has returned a valid array
48 chunksCopy.sort(
49 (a, b) =>
50 scores[chunksCopy.indexOf(b)] - scores[chunksCopy.indexOf(a)],
51 );
52 }
53
54 chunksCopy = chunksCopy.splice(
55 0,
56 this.options?.nFinal ?? DocsContextProvider.nFinal,
57 );
58 } catch (e) {
59 void ide.showToast("warning", `Failed to rerank retrieval results\n${e}`);
60
61 chunksCopy = chunksCopy.splice(
62 0,
63 this.options?.nFinal ?? DocsContextProvider.nFinal,
64 );
65 }
66
67 return chunksCopy;
68 }
69
70 private _sortAlphabetically(
71 submenuItems: ContextSubmenuItem[],
72 ): ContextSubmenuItem[] {
73 // Sort submenu items alphabetically by title
74 return submenuItems.sort((a, b) => {
75 return a.title.toString().localeCompare(b.title.toString());
76 });
77 }
78
79 async getContextItems(
80 query: string,
81 extras: ContextProviderExtras,
82 ): Promise<ContextItem[]> {
83 const nRetrieve = this.options?.nRetrieve ?? DocsContextProvider.nRetrieve;
84 const useReranking = this.options?.useReranking ?? true;
85
86 // Get docs service
87 const docsService = DocsService.getSingleton();
88 if (!docsService) {
89 console.error(`${DocsService.name} has not been initialized`);
90 return [];
91 }
92 await docsService.isInitialized;
93
94 // Get chunks
95 let chunks = await docsService.retrieveChunksFromQuery(
96 extras.fullInput, // confusing: fullInput = the query, query = startUrl in this case
97 query,
98 nRetrieve,
99 );
100 if (!chunks?.length) {
101 return [];
102 }
103
104 // We found chunks, so check if there's a favicon for the docs page
105 const favicon = await docsService.getFavicon(query);
106
107 // Rerank if there's a reranker
108 if (useReranking && extras.reranker) {
109 chunks = await this._rerankChunks(
110 chunks,
111 extras.reranker,
112 extras.fullInput,
113 extras.ide,
114 );
115 }
116
117 return [
118 ...chunks
119 .map((chunk) => ({
120 icon: favicon,
121 name: chunk.filepath.includes("/tree/main") // For display of GitHub files
122 ? chunk.filepath
123 .split("/")
124 .slice(1)
125 .join("/")
126 .split("/tree/main/")
127 .slice(1)
128 .join("/")
129 : chunk.otherMetadata?.title || chunk.filepath,
130 description: chunk.filepath,
131 content: chunk.content,
132 uri: {
133 type: "url" as const,
134 value: chunk.filepath,
135 },
136 }))
137 .reverse(),
138 {
139 ...INSTRUCTIONS_BASE_ITEM,
140 content:
141 "Use the above documentation to answer the following question. You should not reference " +
142 "anything outside of what is shown, unless it is a commonly known concept. Reference URLs " +
143 "whenever possible using markdown formatting. If there isn't enough information to answer " +
144 "the question, suggest where the user might look to learn more.",
145 },
146 ];
147 }
148
149 async loadSubmenuItems(
150 args: LoadSubmenuItemsArgs,
151 ): Promise<ContextSubmenuItem[]> {
152 const { config } = args;
153 // This set is used to filter out the docs that is not in docs config but exist in sqlite metadata
154 const configDocsSet = new Set(
155 config.docs?.map((doc) => doc.startUrl) || [],
156 );
157 // Get docs service
158 const docsService = DocsService.getSingleton();
159 if (!docsService) {
160 console.error(`${DocsService.name} has not been initialized`);
161 return [];
162 }
163 await docsService.isInitialized;
164
165 // Create an array to hold submenu items
166 const submenuItems: ContextSubmenuItem[] = [];
167
168 // Get all indexed docs from the database
169 const docs = (await docsService.listMetadata()) ?? [];
170 for (const { startUrl, title, favicon } of docs) {
171 if (configDocsSet.has(startUrl)) {
172 submenuItems.push({
173 title,
174 id: startUrl,
175 description: new URL(startUrl).hostname,
176 icon: favicon,
177 });
178 }
179 }
180
181 // Sort alphabetically
182 return this._sortAlphabetically(submenuItems);
183 }
184}
185
186export default DocsContextProvider;