Elffuss BraidHub

kikocis/continue public

627d7d0d1f85 · 5.3 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 chunksCopy.sort(
47 (a, b) => scores[chunksCopy.indexOf(b)] - scores[chunksCopy.indexOf(a)],
48 );
49
50 chunksCopy = chunksCopy.splice(
51 0,
52 this.options?.nFinal ?? DocsContextProvider.nFinal,
53 );
54 } catch (e) {
55 void ide.showToast("warning", `Failed to rerank retrieval results\n${e}`);
56
57 chunksCopy = chunksCopy.splice(
58 0,
59 this.options?.nFinal ?? DocsContextProvider.nFinal,
60 );
61 }
62
63 return chunksCopy;
64 }
65
66 private _sortAlphabetically(
67 submenuItems: ContextSubmenuItem[],
68 ): ContextSubmenuItem[] {
69 // Sort submenu items alphabetically by title
70 return submenuItems.sort((a, b) => {
71 return a.title.toString().localeCompare(b.title.toString());
72 });
73 }
74
75 async getContextItems(
76 query: string,
77 extras: ContextProviderExtras,
78 ): Promise<ContextItem[]> {
79 const nRetrieve = this.options?.nRetrieve ?? DocsContextProvider.nRetrieve;
80 const useReranking = this.options?.useReranking ?? true;
81
82 // Get docs service
83 const docsService = DocsService.getSingleton();
84 if (!docsService) {
85 console.error(`${DocsService.name} has not been initialized`);
86 return [];
87 }
88 await docsService.isInitialized;
89
90 // Get chunks
91 let chunks = await docsService.retrieveChunksFromQuery(
92 extras.fullInput, // confusing: fullInput = the query, query = startUrl in this case
93 query,
94 nRetrieve,
95 );
96 if (!chunks?.length) {
97 return [];
98 }
99
100 // We found chunks, so check if there's a favicon for the docs page
101 const favicon = await docsService.getFavicon(query);
102
103 // Rerank if there's a reranker
104 if (useReranking && extras.reranker) {
105 chunks = await this._rerankChunks(
106 chunks,
107 extras.reranker,
108 extras.fullInput,
109 extras.ide,
110 );
111 }
112
113 return [
114 ...chunks
115 .map((chunk) => ({
116 icon: favicon,
117 name: chunk.filepath.includes("/tree/main") // For display of GitHub files
118 ? chunk.filepath
119 .split("/")
120 .slice(1)
121 .join("/")
122 .split("/tree/main/")
123 .slice(1)
124 .join("/")
125 : chunk.otherMetadata?.title || chunk.filepath,
126 description: chunk.filepath,
127 content: chunk.content,
128 uri: {
129 type: "url" as const,
130 value: chunk.filepath,
131 },
132 }))
133 .reverse(),
134 {
135 ...INSTRUCTIONS_BASE_ITEM,
136 content:
137 "Use the above documentation to answer the following question. You should not reference " +
138 "anything outside of what is shown, unless it is a commonly known concept. Reference URLs " +
139 "whenever possible using markdown formatting. If there isn't enough information to answer " +
140 "the question, suggest where the user might look to learn more.",
141 },
142 ];
143 }
144
145 async loadSubmenuItems(
146 args: LoadSubmenuItemsArgs,
147 ): Promise<ContextSubmenuItem[]> {
148 const { config } = args;
149 // This set is used to filter out the docs that is not in docs config but exist in sqlite metadata
150 const configDocsSet = new Set(
151 config.docs?.map((doc) => doc.startUrl) || [],
152 );
153 // Get docs service
154 const docsService = DocsService.getSingleton();
155 if (!docsService) {
156 console.error(`${DocsService.name} has not been initialized`);
157 return [];
158 }
159 await docsService.isInitialized;
160
161 // Create an array to hold submenu items
162 const submenuItems: ContextSubmenuItem[] = [];
163
164 // Get all indexed docs from the database
165 const docs = (await docsService.listMetadata()) ?? [];
166 for (const { startUrl, title, favicon } of docs) {
167 if (configDocsSet.has(startUrl)) {
168 submenuItems.push({
169 title,
170 id: startUrl,
171 description: new URL(startUrl).hostname,
172 icon: favicon,
173 });
174 }
175 }
176
177 // Sort alphabetically
178 return this._sortAlphabetically(submenuItems);
179 }
180}
181
182export default DocsContextProvider;