This commit is contained in:
Test 2024-09-05 12:04:36 -07:00
parent a80135f6a0
commit 8b9153012a
7 changed files with 247 additions and 47 deletions

View file

@ -1,5 +1,5 @@
import { ModelDescription } from "../index.js";
import { editConfigJson } from "../util/paths.js";
import { ContextProviderWithParams, ModelDescription } from "../";
import { editConfigJson } from "../util/paths";
function stringify(obj: any, indentation?: number): string {
return JSON.stringify(
@ -11,6 +11,18 @@ function stringify(obj: any, indentation?: number): string {
);
}
export function addContextProvider(provider: ContextProviderWithParams) {
editConfigJson((config) => {
if (!config.contextProviders) {
config.contextProviders = [provider];
} else {
config.contextProviders.push(provider);
}
return config;
});
}
export function addModel(model: ModelDescription) {
editConfigJson((config) => {
if (config.models?.some((m: any) => stringify(m) === stringify(model))) {

View file

@ -5,7 +5,7 @@ import type {
CustomContextProvider,
IContextProvider,
LoadSubmenuItemsArgs,
} from "../../index.js";
} from "../../";
class CustomContextProviderClass implements IContextProvider {
custom: CustomContextProvider;

19
core/index.d.ts vendored
View file

@ -121,7 +121,7 @@ export interface ILLM extends LLMOptions {
export type ContextProviderType = "normal" | "query" | "submenu";
export interface ContextProviderDescription {
title: string;
title: ContextProviderName;
displayTitle: string;
description: string;
renderInlineAs?: string;
@ -574,7 +574,15 @@ type ContextProviderName =
| "docs"
| "gitlab-mr"
| "os"
| "currentFile";
| "currentFile"
| "outline"
| "continue-proxy"
| "highlights"
| "file"
| "issue"
| "repo-map"
| "url"
| string;
type TemplateType =
| "llama2"
@ -918,6 +926,13 @@ interface ExperimentalConfig {
* Automatically read LLM chat responses aloud using system TTS models
*/
readResponseTTS?: boolean;
/**
* If set to true, we will attempt to pull down and install an instance of Chromium
* that is compatible with the current version of Puppeteer.
* This is needed to crawl a large number of documentation sites that are dynamically rendered.
*/
useChromiumForDocsCrawling?: boolean;
}
interface AnalyticsConfig {

View file

@ -1,7 +1,7 @@
import { Octokit } from "@octokit/rest";
import * as fs from "fs";
import { URL } from "node:url";
import { Page } from "puppeteer";
import { Handler, HTTPResponse, Page } from "puppeteer";
import {
getChromiumPath,
getContinueUtilsPath,
@ -12,7 +12,7 @@ import {
import PCR from "puppeteer-chromium-resolver";
import * as cheerio from "cheerio";
import fetch from "node-fetch";
import { GlobalContext } from "../../util/GlobalContext";
import { ContinueConfig, IDE } from "../..";
export type PageData = {
url: string;
@ -23,10 +23,20 @@ export type PageData = {
class DocsCrawler {
private readonly MAX_REQUESTS_PER_CRAWL = 1000;
private readonly GITHUB_HOST = "github.com";
private useChromiumPromise: Promise<boolean> | undefined = undefined;
private readonly chromiumInstaller: ChromiumInstaller;
constructor() {
this.useChromiumPromise = ChromiumCrawler.verifyOrInstallChromium();
constructor(
private readonly ide: IDE,
private readonly config: ContinueConfig,
) {
this.chromiumInstaller = new ChromiumInstaller(this.ide, this.config);
}
private shouldUseChromium() {
return (
this.config.experimental?.useChromiumForDocsCrawling &&
this.chromiumInstaller.isInstalled()
);
}
async *crawl(
@ -35,11 +45,39 @@ class DocsCrawler {
): AsyncGenerator<PageData> {
if (startUrl.host === this.GITHUB_HOST) {
yield* new GitHubCrawler(startUrl).crawl();
} else if (this.shouldUseChromium()) {
yield* new ChromiumCrawler(startUrl, maxRequestsPerCrawl).crawl();
} else {
if (await this.useChromiumPromise) {
yield* new ChromiumCrawler(startUrl, maxRequestsPerCrawl).crawl();
} else {
yield* new CheerioCrawler(startUrl, maxRequestsPerCrawl).crawl();
let didCrawlSinglePage = false;
for await (const pageData of new CheerioCrawler(
startUrl,
maxRequestsPerCrawl,
).crawl()) {
yield pageData;
didCrawlSinglePage = true;
}
// We assume that if they failed to crawl a single page,
// it was due to an error that using Chromium can resolve
const shouldAttemptChromiumInstall =
!didCrawlSinglePage &&
this.chromiumInstaller.shouldInstallOnCrawlFailure();
if (shouldAttemptChromiumInstall) {
const didInstall =
await this.chromiumInstaller.proposeAndAttemptInstall(
startUrl.toString(),
);
if (didInstall) {
this.ide.showToast(
"info",
`Successfully installed Chromium! Retrying crawl of: ${startUrl.toString()}`,
);
yield* new ChromiumCrawler(startUrl, maxRequestsPerCrawl).crawl();
}
}
}
}
@ -152,12 +190,15 @@ class CheerioCrawler {
(this.constructor as any).name
}] Starting crawl from: ${url} - Max Depth: ${maxDepth}`,
);
const { baseUrl, basePath } = this.splitUrl(url);
let paths: { path: string; depth: number }[] = [
{ path: basePath, depth: 0 },
];
let index = 0;
while (index < paths.length) {
const batch = paths.slice(index, index + 50);
@ -189,15 +230,12 @@ class CheerioCrawler {
}
}
} catch (e) {
if (e instanceof TypeError) {
console.warn("Error while crawling page: ", e);
} else {
console.error("Error while crawling page: ", e);
}
console.debug("Error while crawling page: ", e);
}
index += batch.length;
}
console.log("Crawl completed");
}
@ -264,20 +302,28 @@ class CheerioCrawler {
class ChromiumCrawler {
private readonly LINK_GROUP_SIZE = 2;
private static PCR_CONFIG = { downloadPath: getContinueUtilsPath() };
constructor(
private readonly startUrl: URL,
private readonly maxRequestsPerCrawl: number,
) {}
static setUseChromiumForDocsCrawling(useChromiumForDocsCrawling: boolean) {
editConfigJson((config) => ({
...config,
experimental: {
...config.experimental,
useChromiumForDocsCrawling,
},
}));
}
async *crawl(): AsyncGenerator<PageData> {
console.debug(
`[${(this.constructor as any).name}] Crawling site repo: ${
this.startUrl
}`,
`[${(this.constructor as any).name}] Crawling site: ${this.startUrl}`,
);
const stats = await PCR(ChromiumCrawler.PCR_CONFIG);
const stats = await PCR(ChromiumInstaller.PCR_CONFIG);
const browser = await stats.puppeteer.launch({
args: [
"--user-agent=Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/88.0.4324.150 Safari/537.36",
@ -290,17 +336,54 @@ class ChromiumCrawler {
yield* this.crawlSitePages(page, this.startUrl);
} catch (e) {
console.debug("Error getting links: ", e);
console.debug(
`Setting 'useChromiumForDocsCrawling' to 'false' in config.json`,
);
ChromiumCrawler.setUseChromiumForDocsCrawling(false);
} finally {
await browser.close();
}
}
/**
* We need to handle redirects manually, otherwise there are race conditions.
*/
private async gotoPageAndHandleRedirects(page: Page, url: string) {
const MAX_PAGE_WAIT_MS = 5000;
await page.goto(url, {
timeout: 0,
waitUntil: "networkidle2",
});
let responseEventOccurred = false;
const responseHandler: Handler<HTTPResponse> = (event) =>
(responseEventOccurred = true);
const responseWatcher = new Promise<void>(function (resolve, reject) {
setTimeout(() => {
if (!responseEventOccurred) {
resolve();
} else {
setTimeout(() => resolve(), MAX_PAGE_WAIT_MS);
}
}, 500);
});
page.on("response", responseHandler);
await Promise.race([responseWatcher, page.waitForNavigation()]);
}
private async *crawlSitePages(
page: Page,
curUrl: URL,
visitedLinks: Set<string> = new Set(),
curRequestCount: number = 0,
): AsyncGenerator<PageData> {
const urlStr = curUrl.toString();
if (curRequestCount >= this.maxRequestsPerCrawl) {
console.warn(
`[${
@ -310,25 +393,25 @@ class ChromiumCrawler {
return;
}
if (visitedLinks.has(curUrl.toString())) {
if (visitedLinks.has(urlStr)) {
return;
}
console.debug(
`[${(this.constructor as any).name}] Crawling page: ${curUrl.toString()}`,
`[${(this.constructor as any).name}] Crawling page: ${urlStr}`,
);
await page.goto(curUrl.toString());
await this.gotoPageAndHandleRedirects(page, urlStr);
const htmlContent = await page.content();
const linkGroups = await this.getLinkGroupsFromPage(page, curUrl);
const requestCount = curRequestCount + 1;
visitedLinks.add(curUrl.toString());
visitedLinks.add(urlStr);
yield {
path: curUrl.pathname,
url: curUrl.toString(),
url: urlStr,
content: htmlContent,
};
@ -395,34 +478,90 @@ class ChromiumCrawler {
return groups;
}
}
static async verifyOrInstallChromium() {
const globalContext = new GlobalContext();
class ChromiumInstaller {
static PCR_CONFIG = { downloadPath: getContinueUtilsPath() };
// If we previously failed to install Chromium, don't try again
if (globalContext.get("didPrevChromiumInstallFail")) {
return false;
constructor(
private readonly ide: IDE,
private readonly config: ContinueConfig,
) {
if (this.shouldInstallOnStartup()) {
console.log("Installing Chromium");
this.install();
}
}
if (fs.existsSync(getChromiumPath())) {
return true;
isInstalled() {
return fs.existsSync(getChromiumPath());
}
shouldInstallOnStartup() {
return (
!this.isInstalled() &&
this.config.experimental?.useChromiumForDocsCrawling
);
}
shouldInstallOnCrawlFailure() {
const { experimental } = this.config;
return (
!this.isInstalled() &&
(experimental?.useChromiumForDocsCrawling === undefined ||
experimental.useChromiumForDocsCrawling)
);
}
async proposeAndAttemptInstall(site: string) {
const userAcceptedInstall = await this.proposeInstall(site);
if (userAcceptedInstall) {
const didInstall = await this.install();
return didInstall;
}
}
private async install() {
try {
await PCR(ChromiumCrawler.PCR_CONFIG);
await PCR(ChromiumInstaller.PCR_CONFIG);
ChromiumCrawler.setUseChromiumForDocsCrawling(true);
return true;
} catch (error) {
console.debug("Error installing Chromium : ", error);
console.debug(
`Setting 'didPrevChromiumInstallFail' to 'true' in ${globalContext.constructor.name}`,
`Setting 'useChromiumForDocsCrawling' to 'false' in config.json`,
);
globalContext.update("didPrevChromiumInstallFail", true);
ChromiumCrawler.setUseChromiumForDocsCrawling(false);
this.ide.showToast("error", "Failed to install Chromium");
return false;
}
}
private async proposeInstall(site: string) {
const msg =
`Unable to crawl documentation site: ${site}\n` +
"We recommend installing Chromium. " +
"Download progress can be viewed in the developer console.";
const actionMsg = "Install Chromium";
const res = await this.ide.showToast("warning", msg, actionMsg);
return res === actionMsg;
}
}
export default DocsCrawler;
export { CheerioCrawler, ChromiumCrawler, GitHubCrawler };
export {
CheerioCrawler,
ChromiumCrawler,
GitHubCrawler,
ChromiumInstaller as ChromiumInstaller,
};

View file

@ -31,6 +31,7 @@ import {
SiteIndexingResults,
} from "./preIndexed";
import preIndexedDocs from "./preIndexedDocs";
import { addContextProvider } from "../../config/util";
// Purposefully lowercase because lancedb converts
export interface LanceDbDocsRow {
@ -139,13 +140,34 @@ export default class DocsService {
return !!title;
}
async showAddDocsContextProviderToast() {
const actionMsg = "Add 'docs' context provider";
const res = await this.ide.showToast(
"info",
"Starting docs indexing",
actionMsg,
);
if (res === actionMsg) {
addContextProvider({
name: DocsContextProvider.description.title,
params: {},
});
this.ide.showToast("info", "Successfuly added docs context provider");
}
return res === actionMsg;
}
async indexAllDocs(reIndex: boolean = false) {
if (!this.hasDocsContextProvider()) {
this.ide.showToast(
"info",
"No 'docs' provider configured under 'contextProviders' in config.json",
);
return;
const didAddDocsContextProvider =
await this.showAddDocsContextProviderToast();
if (!didAddDocsContextProvider) {
return;
}
}
const docs = await this.list();
@ -384,7 +406,7 @@ export default class DocsService {
private async init(configHandler: ConfigHandler) {
this.config = await configHandler.loadConfig();
this.docsCrawler = new DocsCrawler();
this.docsCrawler = new DocsCrawler(this.ide, this.config);
const embeddingsProvider = await this.getEmbeddingsProvider();

View file

@ -5,7 +5,6 @@ import { EmbeddingsProvider } from "../index.js";
export type GlobalContextType = {
indexingPaused: boolean;
selectedTabAutocompleteModel: string;
didPrevChromiumInstallFail: boolean;
lastSelectedProfileForWorkspace: { [workspaceIdentifier: string]: string };
/**
* This is needed to handle the case where a JetBrains user has created

View file

@ -71,6 +71,19 @@ The configuration schema is as follows:
- `rootUrl`: The base URL of the documentation site, used to determine which pages to index.
- `faviconUrl`: The URL of the site's favicon, used for visual identification in the UI.
## Crawling dynamically generated sites with `useChromiumForDocsCrawling`
By default, we use a lighter weight tool to crawl documentation sites that cannot render sites that are dynamically generated using Javascript.
If you wish to crawl a site that is dynamically generated, or you get an error while attempting to crawl a site, you can enable the experimental `useChromiumForDocsCrawling`
feature in your `config.json`. This will download and install Chromium to `~/.continue/.utils`.
```json title=config.json
"experimental": {
"useChromiumForDocsCrawling": true
}
```
## FAQ
### How often is the indexed content updated?