💫 Documentation context provider (#786)

* 💄 image drag and drop improvements

* 💄 further improvement to drag/drop hints

* 🐛 fix image selector insertion

* 🐛 fix dropdown width being larger than window width

* 🐛 respect disableIndexing

* 🐛 fix context items not refreshing when editing past message

* ✨ llava chat template

* 🩹 multiple small fixes

* 🐛 a few docs crawling fixes

* 🔊 log docs url

* 🐛 small fixes to DocsContextProvider

* 📝 update changelog and docs for DocsContextProvider

* 🐛 show new docs in submenu after it is loaded
This commit is contained in:
Nate Sesti 2024-01-30 13:01:50 -08:00 • committed by GitHub
parent 636b2a1d6b
commit f1ab9bf936
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
16 changed files with 146 additions and 40 deletions

View file

@ -0,0 +1,4 @@
project: extensions/vscode
kind: Added
body: Docs context provider
time: 2024-01-30T12:31:43.521306-08:00

0
Icon Normal file
View file

View file

@ -36,13 +36,15 @@ class DocsContextProvider extends BaseContextProvider {
return [
...chunks
.map((chunk) => ({
name: chunk.filepath
.split("/")
.slice(1)
.join("/")
.split("/tree/main/")
.slice(1)
.join("/"), // chunk.otherMetadata?.title || chunk.filepath,
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: new URL(chunk.filepath, query).toString(),
content: chunk.content,
}))

View file

@ -58,14 +58,29 @@ export async function* markdownChunker(
hLevel: number
): AsyncGenerator<ChunkWithoutID> {
if (countTokens(content, "gpt-4") <= maxChunkSize) {
const header = findHeader(content.split("\n"));
yield {
content,
startLine: 0,
endLine: content.split("\n").length,
otherMetadata: {
fragment: cleanFragment(header),
title: cleanHeader(header),
},
};
return;
} else if (hLevel > 4) {
yield* basicChunker(content, maxChunkSize);
const header = findHeader(content.split("\n"));
for (const chunk of basicChunker(content, maxChunkSize)) {
yield {
...chunk,
otherMetadata: {
fragment: cleanFragment(header),
title: cleanHeader(header),
},
};
}
return;
}

View file

@ -43,11 +43,16 @@ function shouldFilterPath(pathname: string, baseUrl: URL): boolean {
return false;
}
async function crawlLinks(path: string, baseUrl: URL, visited: Set<string>) {
async function* crawlLinks(
path: string,
baseUrl: URL,
visited: Set<string>
): AsyncGenerator<number> {
if (visited.has(path) || shouldFilterPath(path, baseUrl)) {
return;
}
visited.add(path);
yield visited.size;
const response = await fetch(new URL(path, baseUrl));
const text = await response.text();
@ -71,8 +76,12 @@ async function crawlLinks(path: string, baseUrl: URL, visited: Set<string>) {
});
await Promise.all(
children.map((child) => crawlLinks(child, baseUrl, visited))
children.map(async (child) => {
for await (const _ of crawlLinks(child, baseUrl, visited)) {
}
})
);
yield visited.size;
}
async function crawlGithubRepo(baseUrl: URL) {
@ -116,25 +125,44 @@ async function crawlGithubRepo(baseUrl: URL) {
return paths;
}
export async function crawlSubpages(baseUrl: URL) {
export async function* crawlSubpages(
baseUrl: URL
): AsyncGenerator<number, string[]> {
// Special case for GitHub repos
if (baseUrl.hostname === "github.com") {
return crawlGithubRepo(baseUrl);
}
// First, check if the parent of the path redirects to the same page
const parentUrl = new URL(baseUrl);
parentUrl.pathname = parentUrl.pathname.split("/").slice(0, -1).join("/");
const response = await fetch(parentUrl);
let useParent = response.url === baseUrl.toString();
if (baseUrl.pathname.endsWith("/")) {
baseUrl.pathname = baseUrl.pathname.slice(0, -1);
}
let realBaseUrl = new URL(baseUrl);
while (true) {
let parentUrl = new URL(realBaseUrl);
parentUrl.pathname = parentUrl.pathname.split("/").slice(0, -1).join("/");
if (
parentUrl.pathname === realBaseUrl.pathname ||
parentUrl.pathname === ""
) {
break;
}
const response = await fetch(parentUrl);
const redirected = response.url.toString() === baseUrl.toString() + "/";
if (!redirected) {
break;
}
realBaseUrl = parentUrl;
}
const visited = new Set<string>();
await crawlLinks(
(useParent ? parentUrl.pathname : baseUrl.pathname) || "/",
baseUrl,
for await (const count of crawlLinks(
realBaseUrl.pathname || "/",
realBaseUrl,
visited
);
)) {
yield count;
}
return [...visited];
}

View file

@ -22,7 +22,7 @@ async function createDocsTable(db: Database<sqlite3.Database>) {
db.exec(`CREATE TABLE IF NOT EXISTS docs (
id INTEGER PRIMARY KEY AUTOINCREMENT,
title STRING NOT NULL,
baseUrl STRING NOT NULL
baseUrl STRING NOT NULL UNIQUE
)`);
}

View file

@ -16,7 +16,7 @@ export async function* indexDocs(
embeddingsProvider: EmbeddingsProvider
): AsyncGenerator<IndexingProgressUpdate> {
const existingDocs = await listDocs();
if (existingDocs.find((doc) => doc.title === title)) {
if (existingDocs.find((doc) => doc.baseUrl === baseUrl.toString())) {
yield {
progress: 1,
desc: "Already indexed",
@ -29,8 +29,23 @@ export async function* indexDocs(
desc: "Finding subpages",
};
let subpaths = await crawlSubpages(baseUrl);
console.log("Found subpaths", subpaths);
const subpathGenerator = crawlSubpages(baseUrl);
let { value, done } = await subpathGenerator.next();
while (true) {
if (done) {
break;
}
yield {
progress: 0,
desc: `Finding subpages (${value})`,
};
const next = await subpathGenerator.next();
value = next.value;
done = next.done;
}
let subpaths = value as string[];
const chunks: Chunk[] = [];
const embeddings: number[][] = [];
@ -53,7 +68,7 @@ export async function* indexDocs(
for (let i = 0; i < subpaths.length; i++) {
const subpath = subpaths[i];
yield {
progress: 1 / (subpaths.length + 1),
progress: Math.max(1, Math.floor(100 / (subpaths.length + 1))),
desc: `${subpath}`,
};
@ -75,6 +90,7 @@ export async function* indexDocs(
(chunk.otherMetadata?.fragment
? `#${chunk.otherMetadata.fragment}`
: ""),
otherMetadata: chunk.otherMetadata,
index,
digest: subpath,
});

View file

@ -32,6 +32,14 @@ Type '@terminal' to reference the contents of your IDE's terminal.
{ "name": "terminal" }
```
### Documentation
Type `@docs` to index and retrieve snippets from any documentation site. You can add any site by selecting "Add Docs" in the dropdown, then entering the root URL of the documentation site and a title to remember it by. After the site has been indexed, you can type `@docs`, select your documentation from the dropdown, and Continue will use similarity search to automatically find important sections when answering your question.
```json
{ "name": "docs" }
```
### Open Files
Type '@open' to reference the contents of all of your open files. Set `onlyPinned` to `true` to only reference pinned files.

View file

@ -968,6 +968,7 @@
"problems",
"folder",
"issue",
"docs",
"tree"
],
"markdownEnumDescriptions": [
@ -982,6 +983,7 @@
"Include important files from a folder in the prompt, as determined by similarity search",
"Reference GitHub issues from a repository",
"Retrieve important pages from a documentation website, as determined by similarity search",
"Index and retrieve the contents of any documentation site, using embeddings to find important snippets",
"Display a file tree of the current workspace"
],
"type": "string"

View file

@ -968,6 +968,7 @@
"problems",
"folder",
"issue",
"docs",
"tree"
],
"markdownEnumDescriptions": [
@ -982,6 +983,7 @@
"Include important files from a folder in the prompt, as determined by similarity search",
"Reference GitHub issues from a repository",
"Retrieve important pages from a documentation website, as determined by similarity search",
"Index and retrieve the contents of any documentation site, using embeddings to find important snippets",
"Display a file tree of the current workspace"
],
"type": "string"

View file

@ -674,7 +674,7 @@ export function getSidebarContent(
embeddingsProvider
)) {
progress.report({
increment: update.progress * 100,
increment: update.progress,
message: update.desc,
});
}
@ -682,6 +682,10 @@ export function getSidebarContent(
vscode.window.showInformationMessage(
`🎉 Successfully indexed ${title}`
);
debugPanelWebview?.postMessage({
type: "refreshSubmenuItems",
});
}
);
break;

View file

@ -71,8 +71,6 @@ export async function vsCodeIndexCodebase(workspaceDirs: string[]) {
(filepath) => ideProtocolClient.readFile(filepath)
);
console.log("RESULTS: ", codebaseIndex.artifactId, results);
for await (let { progress, desc } of codebaseIndex.update(
tag,
results,

View file

@ -66,19 +66,28 @@ const router = createMemoryRouter([
},
]);
export const SubmenuContextProvidersContext = createContext<
(providerTitle: string | undefined, query: string) => ContextSubmenuItem[]
>(() => []);
export const SubmenuContextProvidersContext = createContext<{
getSubmenuContextItems: (
providerTitle: string | undefined,
query: string
) => ContextSubmenuItem[];
addItem: (providerTitle: string, item: ContextSubmenuItem) => void;
}>({
getSubmenuContextItems: () => [],
addItem: () => {},
});
function App() {
const dispatch = useDispatch();
useSetup(dispatch);
const { getSubmenuContextItems } = useSubmenuContextProviders();
const submenuContextProvidersMethods = useSubmenuContextProviders();
return (
<SubmenuContextProvidersContext.Provider value={getSubmenuContextItems}>
<SubmenuContextProvidersContext.Provider
value={submenuContextProvidersMethods}
>
<RouterProvider router={router} />
</SubmenuContextProvidersContext.Provider>
);

View file

@ -1,9 +1,10 @@
import { postToIde } from "core/ide/messaging";
import React, { useLayoutEffect } from "react";
import { usePostHog } from "posthog-js/react";
import React, { useContext, useLayoutEffect } from "react";
import { useDispatch } from "react-redux";
import styled from "styled-components";
import { Button, Input } from "..";
import useSubmenuContextProviders from "../../hooks/useSubmenuContextProviders";
import { SubmenuContextProvidersContext } from "../../App";
import { setShowDialog } from "../../redux/slices/uiStateSlice";
const GridDiv = styled.div`
@ -19,14 +20,17 @@ function AddDocsDialog() {
const [urlValid, setUrlValid] = React.useState(false);
const dispatch = useDispatch();
const { addItem } = useSubmenuContextProviders();
const { addItem } = useContext(SubmenuContextProvidersContext);
const ref = React.useRef<HTMLInputElement>(null);
const posthog = usePostHog();
useLayoutEffect(() => {
if (ref.current) {
ref.current.focus();
}
setTimeout(() => {
if (ref.current) {
ref.current.focus();
}
}, 100);
}, [ref]);
return (
@ -63,6 +67,7 @@ function AddDocsDialog() {
title: docsTitle,
description: new URL(docsUrl).hostname,
});
posthog.capture("add_docs", { url: docsUrl });
}}
>
Done

View file

@ -123,7 +123,7 @@ interface TipTapEditorProps {
function TipTapEditor(props: TipTapEditorProps) {
const dispatch = useDispatch();
const getSubmenuContextItems = useContext(SubmenuContextProvidersContext);
const { getSubmenuContextItems } = useContext(SubmenuContextProvidersContext);
const historyLength = useSelector(
(store: RootStore) => store.state.history.length

View file

@ -43,6 +43,19 @@ function useSubmenuContextProviders() {
});
}
useEffect(() => {
const handler = (e) => {
if (e.data.type !== "refreshSubmenuItems") {
return;
}
setLoaded(false);
};
window.addEventListener("message", handler);
return () => {
window.removeEventListener("message", handler);
};
}, []);
function addItem(providerTitle: string, item: ContextSubmenuItem) {
console.log("Adding item", item, providerTitle, Object.keys(minisearches));
if (!minisearches[providerTitle]) {