Merge branch 'main' into nate/yaml-loading
This commit is contained in:
commit
79474eb0cc
64 changed files with 1964 additions and 920 deletions
18
.github/workflows/jetbrains-release.yaml
vendored
18
.github/workflows/jetbrains-release.yaml
vendored
|
|
@ -6,7 +6,13 @@ name: JetBrains Release
|
|||
|
||||
on:
|
||||
release:
|
||||
types: [prereleased]
|
||||
types: [ prereleased ]
|
||||
workflow_dispatch:
|
||||
inputs:
|
||||
publish_build:
|
||||
description: 'Whether or not to publish the built extension to the JetBrains marketplace'
|
||||
required: true
|
||||
default: false
|
||||
|
||||
defaults:
|
||||
run:
|
||||
|
|
@ -34,7 +40,7 @@ jobs:
|
|||
# Prepare and publish the plugin to JetBrains Marketplace repository
|
||||
build:
|
||||
needs: check_release_name
|
||||
if: needs.check_release_name.outputs.should_run == 'true'
|
||||
if: needs.check_release_name.outputs.should_run == 'true' || github.event_name == 'workflow_dispatch'
|
||||
name: Build Plugin
|
||||
runs-on: macos-latest
|
||||
permissions:
|
||||
|
|
@ -175,6 +181,7 @@ jobs:
|
|||
|
||||
# Publish the plugin to JetBrains Marketplace
|
||||
- name: Publish EAP Plugin
|
||||
if: github.event_name == 'release' || github.event.inputs.publish_build == 'true'
|
||||
env:
|
||||
PUBLISH_TOKEN: ${{ secrets.JETBRAINS_PUBLISH_TOKEN }}
|
||||
CERTIFICATE_CHAIN: ${{ secrets.JETBRAINS_CERTIFICATE_CHAIN }}
|
||||
|
|
@ -184,6 +191,7 @@ jobs:
|
|||
run: ./gradlew publishPlugin
|
||||
|
||||
- name: Publish Stable Plugin
|
||||
if: github.event_name == 'release' || github.event.inputs.publish_build == 'true'
|
||||
env:
|
||||
PUBLISH_TOKEN: ${{ secrets.JETBRAINS_PUBLISH_TOKEN }}
|
||||
CERTIFICATE_CHAIN: ${{ secrets.JETBRAINS_CERTIFICATE_CHAIN }}
|
||||
|
|
@ -337,7 +345,7 @@ jobs:
|
|||
# Run tests and upload a code coverage report
|
||||
test:
|
||||
name: Test
|
||||
needs: [build]
|
||||
needs: [ build ]
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
# Check out current repository
|
||||
|
|
@ -379,7 +387,7 @@ jobs:
|
|||
inspectCode:
|
||||
if: false
|
||||
name: Inspect code
|
||||
needs: [build]
|
||||
needs: [ build ]
|
||||
runs-on: ubuntu-latest
|
||||
permissions:
|
||||
contents: write
|
||||
|
|
@ -414,7 +422,7 @@ jobs:
|
|||
verify:
|
||||
if: false
|
||||
name: Verify plugin
|
||||
needs: [build]
|
||||
needs: [ build ]
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
# Free GitHub Actions Environment Disk Space
|
||||
|
|
|
|||
10
.github/workflows/main.yaml
vendored
10
.github/workflows/main.yaml
vendored
|
|
@ -4,6 +4,13 @@ on:
|
|||
release:
|
||||
types: [released]
|
||||
|
||||
workflow_dispatch:
|
||||
inputs:
|
||||
publish_build:
|
||||
description: "Whether or not to publish the built extension to the VS Code marketplace"
|
||||
required: true
|
||||
default: false
|
||||
|
||||
jobs:
|
||||
check_release_name:
|
||||
runs-on: ubuntu-latest
|
||||
|
|
@ -21,7 +28,7 @@ jobs:
|
|||
|
||||
build:
|
||||
needs: check_release_name
|
||||
if: needs.check_release_name.outputs.should_run == 'true'
|
||||
if: needs.check_release_name.outputs.should_run == 'true' || github.event_name == 'workflow_dispatch'
|
||||
strategy:
|
||||
matrix:
|
||||
include:
|
||||
|
|
@ -201,6 +208,7 @@ jobs:
|
|||
runs-on: ubuntu-latest
|
||||
needs:
|
||||
- build
|
||||
if: github.event.inputs.publish_build == 'true'
|
||||
permissions:
|
||||
contents: write
|
||||
steps:
|
||||
|
|
|
|||
3
.vscode/settings.json
vendored
3
.vscode/settings.json
vendored
|
|
@ -42,5 +42,6 @@
|
|||
"extensions/.continue-debug": true
|
||||
// "sync/**": true
|
||||
},
|
||||
"eslint.workingDirectories": ["./core"]
|
||||
"eslint.workingDirectories": ["./core"],
|
||||
"typescript.tsdk": "node_modules/typescript/lib"
|
||||
}
|
||||
|
|
|
|||
|
|
@ -33,14 +33,46 @@ class IPCMessengerBase<
|
|||
response &&
|
||||
typeof response[Symbol.asyncIterator] === "function"
|
||||
) {
|
||||
for await (const update of response) {
|
||||
this.send(msg.messageType, update, msg.messageId);
|
||||
let next = await response.next();
|
||||
while (!next.done) {
|
||||
this.send(
|
||||
msg.messageType,
|
||||
{
|
||||
done: false,
|
||||
content: next.value,
|
||||
status: "success",
|
||||
},
|
||||
msg.messageId,
|
||||
);
|
||||
next = await response.next();
|
||||
}
|
||||
this.send(msg.messageType, { done: true }, msg.messageId);
|
||||
this.send(
|
||||
msg.messageType,
|
||||
{
|
||||
done: true,
|
||||
content: next.value,
|
||||
status: "success",
|
||||
},
|
||||
msg.messageId,
|
||||
);
|
||||
} else {
|
||||
this.send(msg.messageType, response, msg.messageId);
|
||||
this.send(
|
||||
msg.messageType,
|
||||
{
|
||||
done: true,
|
||||
content: response,
|
||||
status: "success",
|
||||
},
|
||||
msg.messageId,
|
||||
);
|
||||
}
|
||||
} catch (e: any) {
|
||||
this.send(
|
||||
msg.messageType,
|
||||
{ done: true, error: e.message, status: "error" },
|
||||
msg.messageId,
|
||||
);
|
||||
|
||||
console.warn(`Error running handler for "${msg.messageType}": `, e);
|
||||
this._onErrorHandlers.forEach((handler) => {
|
||||
handler(e);
|
||||
|
|
@ -62,6 +94,7 @@ class IPCMessengerBase<
|
|||
}
|
||||
|
||||
private _unfinishedLine: string | undefined = undefined;
|
||||
|
||||
protected _handleData(data: Buffer) {
|
||||
const d = data.toString();
|
||||
const lines = d.split(/\r\n/).filter((line) => line.trim() !== "");
|
||||
|
|
@ -169,6 +202,7 @@ export class IpcMessenger<
|
|||
process.exit(1);
|
||||
});
|
||||
}
|
||||
|
||||
_sendMsg(msg: Message) {
|
||||
const d = JSON.stringify(msg);
|
||||
// console.log("[info] Sending message: ", d);
|
||||
|
|
|
|||
|
|
@ -69,14 +69,46 @@ export class TcpMessenger<
|
|||
response &&
|
||||
typeof response[Symbol.asyncIterator] === "function"
|
||||
) {
|
||||
for await (const update of response) {
|
||||
this.send(msg.messageType, update, msg.messageId);
|
||||
let next = await response.next();
|
||||
while (!next.done) {
|
||||
this.send(
|
||||
msg.messageType,
|
||||
{
|
||||
done: false,
|
||||
content: next.value,
|
||||
status: "success",
|
||||
},
|
||||
msg.messageId,
|
||||
);
|
||||
next = await response.next();
|
||||
}
|
||||
this.send(msg.messageType, { done: true }, msg.messageId);
|
||||
this.send(
|
||||
msg.messageType,
|
||||
{
|
||||
done: true,
|
||||
content: next.value,
|
||||
status: "success",
|
||||
},
|
||||
msg.messageId,
|
||||
);
|
||||
} else {
|
||||
this.send(msg.messageType, response || {}, msg.messageId);
|
||||
this.send(
|
||||
msg.messageType,
|
||||
{
|
||||
done: true,
|
||||
content: response,
|
||||
status: "success",
|
||||
},
|
||||
msg.messageId,
|
||||
);
|
||||
}
|
||||
} catch (e: any) {
|
||||
this.send(
|
||||
msg.messageType,
|
||||
{ done: true, error: e.message, status: "error" },
|
||||
msg.messageId,
|
||||
);
|
||||
|
||||
console.warn(`Error running handler for "${msg.messageType}": `, e);
|
||||
this._onErrorHandlers.forEach((handler) => {
|
||||
handler(e);
|
||||
|
|
@ -98,6 +130,7 @@ export class TcpMessenger<
|
|||
}
|
||||
|
||||
private _unfinishedLine: string | undefined = undefined;
|
||||
|
||||
private _handleData(data: Buffer) {
|
||||
const d = data.toString();
|
||||
const lines = d.split(/\r\n/).filter((line) => line.trim() !== "");
|
||||
|
|
@ -151,6 +184,7 @@ export class TcpMessenger<
|
|||
data,
|
||||
});
|
||||
}
|
||||
|
||||
request<T extends keyof FromProtocol>(
|
||||
messageType: T,
|
||||
data: FromProtocol[T][0],
|
||||
|
|
|
|||
|
|
@ -37,16 +37,21 @@ export function slashFromCustomCommand(
|
|||
|
||||
if (
|
||||
Array.isArray(content) &&
|
||||
content.some((part) =>
|
||||
part.text?.startsWith(`/${customCommand.name}`),
|
||||
content.some(
|
||||
(part) =>
|
||||
"text" in part && part.text?.startsWith(`/${customCommand.name}`),
|
||||
)
|
||||
) {
|
||||
messages[i] = {
|
||||
...message,
|
||||
content: content.map((part) => {
|
||||
return part.text?.startsWith(`/${customCommand.name}`)
|
||||
? { ...part, text: promptUserInput }
|
||||
: part;
|
||||
if (
|
||||
"text" in part &&
|
||||
part.text.startsWith(`/${customCommand.name}`)
|
||||
) {
|
||||
return { type: "text", text: promptUserInput };
|
||||
}
|
||||
return part;
|
||||
}),
|
||||
};
|
||||
break;
|
||||
|
|
|
|||
|
|
@ -220,18 +220,10 @@ declare global {
|
|||
export interface SiteIndexingConfig {
|
||||
title: string;
|
||||
startUrl: string;
|
||||
rootUrl?: string;
|
||||
maxDepth?: number;
|
||||
faviconUrl?: string;
|
||||
}
|
||||
|
||||
export interface SiteIndexingConfig {
|
||||
startUrl: string;
|
||||
rootUrl?: string;
|
||||
title: string;
|
||||
maxDepth?: number;
|
||||
}
|
||||
|
||||
export interface IContextProvider {
|
||||
get description(): ContextProviderDescription;
|
||||
|
||||
|
|
|
|||
|
|
@ -24,6 +24,8 @@ class DocsContextProvider extends BaseContextProvider {
|
|||
|
||||
constructor(options: any) {
|
||||
super(options);
|
||||
const docsService = DocsService.getSingleton();
|
||||
docsService?.setGithubToken(this.options?.githubToken);
|
||||
}
|
||||
|
||||
private async _rerankChunks(
|
||||
|
|
@ -173,6 +175,10 @@ class DocsContextProvider extends BaseContextProvider {
|
|||
const canUsePreindexedDocs = await docsService.canUsePreindexedDocs();
|
||||
if (canUsePreindexedDocs) {
|
||||
for (const { startUrl, title } of Object.values(preIndexedDocs)) {
|
||||
// Skip if overridden in config
|
||||
if (docs.find((d) => d.startUrl === startUrl)) {
|
||||
continue;
|
||||
}
|
||||
submenuItemsMap.set(startUrl, {
|
||||
title,
|
||||
id: startUrl,
|
||||
|
|
|
|||
42
core/core.ts
42
core/core.ts
|
|
@ -43,7 +43,15 @@ import { Telemetry } from "./util/posthog";
|
|||
import { getSymbolsForManyFiles } from "./util/treeSitter";
|
||||
import { TTS } from "./util/tts";
|
||||
|
||||
import { type ContextItemId, type IDE, type IndexingProgressUpdate } from ".";
|
||||
import {
|
||||
ChatMessage,
|
||||
DiffLine,
|
||||
PromptLog,
|
||||
type ContextItemId,
|
||||
type IDE,
|
||||
type IndexingProgressUpdate,
|
||||
} from ".";
|
||||
|
||||
import { usePlatform } from "./control-plane/flags";
|
||||
import type { FromCoreProtocol, ToCoreProtocol } from "./protocol";
|
||||
import type { IMessenger, Message } from "./protocol/messenger";
|
||||
|
|
@ -396,7 +404,7 @@ export class Core {
|
|||
configHandler: ConfigHandler,
|
||||
abortedMessageIds: Set<string>,
|
||||
msg: Message<ToCoreProtocol["llm/streamChat"][0]>,
|
||||
) {
|
||||
): AsyncGenerator<ChatMessage, PromptLog> {
|
||||
const { config } = await configHandler.loadConfig();
|
||||
if (!config) {
|
||||
throw new Error("Config not loaded");
|
||||
|
|
@ -432,7 +440,7 @@ export class Core {
|
|||
|
||||
const chunk = next.value;
|
||||
|
||||
yield { content: chunk };
|
||||
yield chunk;
|
||||
next = await gen.next();
|
||||
}
|
||||
|
||||
|
|
@ -449,7 +457,11 @@ export class Core {
|
|||
true,
|
||||
);
|
||||
|
||||
return { done: true, content: next.value };
|
||||
if (!next.done) {
|
||||
throw new Error("Will never happen");
|
||||
}
|
||||
|
||||
return next.value;
|
||||
}
|
||||
|
||||
on("llm/streamChat", (msg) =>
|
||||
|
|
@ -459,9 +471,8 @@ export class Core {
|
|||
async function* llmStreamComplete(
|
||||
configHandler: ConfigHandler,
|
||||
abortedMessageIds: Set<string>,
|
||||
|
||||
msg: Message<ToCoreProtocol["llm/streamComplete"][0]>,
|
||||
) {
|
||||
): AsyncGenerator<string, PromptLog> {
|
||||
const model = await configHandler.llmFromTitle(msg.data.title);
|
||||
const gen = model.streamComplete(
|
||||
msg.data.prompt,
|
||||
|
|
@ -483,11 +494,13 @@ export class Core {
|
|||
});
|
||||
break;
|
||||
}
|
||||
yield { content: next.value };
|
||||
yield next.value;
|
||||
next = await gen.next();
|
||||
}
|
||||
|
||||
return { done: true, content: next.value };
|
||||
if (!next.done) {
|
||||
throw new Error("This will never happen");
|
||||
}
|
||||
return next.value;
|
||||
}
|
||||
|
||||
on("llm/streamComplete", (msg) =>
|
||||
|
|
@ -549,7 +562,7 @@ export class Core {
|
|||
abortedMessageIds: Set<string>,
|
||||
msg: Message<ToCoreProtocol["command/run"][0]>,
|
||||
messenger: IMessenger<ToCoreProtocol, FromCoreProtocol>,
|
||||
) {
|
||||
): AsyncGenerator<string> {
|
||||
const {
|
||||
input,
|
||||
history,
|
||||
|
|
@ -614,7 +627,7 @@ export class Core {
|
|||
break;
|
||||
}
|
||||
if (content) {
|
||||
yield { content };
|
||||
yield content;
|
||||
}
|
||||
}
|
||||
} catch (e) {
|
||||
|
|
@ -622,7 +635,6 @@ export class Core {
|
|||
} finally {
|
||||
clearInterval(checkActiveInterval);
|
||||
}
|
||||
yield { done: true, content: "" };
|
||||
}
|
||||
on("command/run", (msg) =>
|
||||
runNodeJsSlashCommand(
|
||||
|
|
@ -653,7 +665,7 @@ export class Core {
|
|||
configHandler: ConfigHandler,
|
||||
abortedMessageIds: Set<string>,
|
||||
msg: Message<ToCoreProtocol["streamDiffLines"][0]>,
|
||||
) {
|
||||
): AsyncGenerator<DiffLine> {
|
||||
const data = msg.data;
|
||||
const llm = await configHandler.llmFromTitle(msg.data.modelTitle);
|
||||
for await (const diffLine of streamDiffLines(
|
||||
|
|
@ -668,10 +680,8 @@ export class Core {
|
|||
abortedMessageIds.delete(msg.messageId);
|
||||
break;
|
||||
}
|
||||
yield { content: diffLine };
|
||||
yield diffLine;
|
||||
}
|
||||
|
||||
return { done: true };
|
||||
}
|
||||
|
||||
on("streamDiffLines", (msg) =>
|
||||
|
|
|
|||
26
core/index.d.ts
vendored
26
core/index.d.ts
vendored
|
|
@ -223,16 +223,10 @@ export interface ContextSubmenuItemWithProvider extends ContextSubmenuItem {
|
|||
export interface SiteIndexingConfig {
|
||||
title: string;
|
||||
startUrl: string;
|
||||
rootUrl?: string;
|
||||
maxDepth?: number;
|
||||
faviconUrl?: string;
|
||||
}
|
||||
|
||||
export interface SiteIndexingConfig {
|
||||
startUrl: string;
|
||||
rootUrl?: string;
|
||||
title: string;
|
||||
maxDepth?: number;
|
||||
useLocalCrawling?: boolean;
|
||||
rootUrl?: string; // Currently only used by preindexed docs
|
||||
}
|
||||
|
||||
export interface IContextProvider {
|
||||
|
|
@ -306,11 +300,17 @@ export interface CompletionOptions extends BaseCompletionOptions {
|
|||
|
||||
export type ChatMessageRole = "user" | "assistant" | "system" | "tool";
|
||||
|
||||
export interface MessagePart {
|
||||
type: "text" | "imageUrl";
|
||||
text?: string;
|
||||
imageUrl?: { url: string };
|
||||
}
|
||||
export type TextMessagePart = {
|
||||
type: "text";
|
||||
text: string;
|
||||
};
|
||||
|
||||
export type ImageMessagePart = {
|
||||
type: "imageUrl";
|
||||
imageUrl: { url: string };
|
||||
};
|
||||
|
||||
export type MessagePart = TextMessagePart | ImageMessagePart;
|
||||
|
||||
export type MessageContent = string | MessagePart[];
|
||||
|
||||
|
|
|
|||
|
|
@ -1,142 +0,0 @@
|
|||
import os from "os";
|
||||
|
||||
import { jest } from "@jest/globals";
|
||||
|
||||
import { ContinueConfig } from "../..";
|
||||
import { testConfigHandler } from "../../test/fixtures";
|
||||
import FileSystemIde from "../../util/filesystem";
|
||||
|
||||
import DocsCrawler, { ChromiumInstaller, type PageData } from "./DocsCrawler";
|
||||
import preIndexedDocs from "./preIndexedDocs";
|
||||
|
||||
// Temporary workaround until we have better caching of Chromium
|
||||
// download between test runs
|
||||
const TIMEOUT_MS = 1_000_000_000;
|
||||
|
||||
// Overwrite the Chromium download path to `os.tmpdir()`
|
||||
// so that we don't delete the Chromium install between tests
|
||||
ChromiumInstaller.PCR_CONFIG = { downloadPath: os.tmpdir() };
|
||||
|
||||
// Skipped until we have a better way to cache Chromium installs
|
||||
// between tests and in CI
|
||||
describe.skip("DocsCrawler", () => {
|
||||
const NUM_PAGES_TO_CRAWL = 5;
|
||||
|
||||
let config: ContinueConfig;
|
||||
let mockIde: FileSystemIde;
|
||||
let chromiumInstaller;
|
||||
let docsCrawler: DocsCrawler;
|
||||
|
||||
beforeAll(async () => {
|
||||
const result = await testConfigHandler.loadConfig();
|
||||
config = result.config!;
|
||||
mockIde = new FileSystemIde(process.cwd());
|
||||
chromiumInstaller = new ChromiumInstaller(mockIde, config);
|
||||
docsCrawler = new DocsCrawler(mockIde, config);
|
||||
|
||||
// Make sure we have Chromium pulled down before beginning tests
|
||||
await chromiumInstaller.install();
|
||||
}, TIMEOUT_MS);
|
||||
|
||||
function crawlTest(
|
||||
urls: string[],
|
||||
numPagesToCrawl: number = NUM_PAGES_TO_CRAWL,
|
||||
) {
|
||||
const numUrlsToTest = 5;
|
||||
const randomUrls = urls
|
||||
.sort(() => 0.5 - Math.random())
|
||||
.slice(0, numUrlsToTest);
|
||||
|
||||
randomUrls.forEach((url) => {
|
||||
it(
|
||||
`Crawl test for ${url}`,
|
||||
async () => {
|
||||
const crawlResults: PageData[] = [];
|
||||
|
||||
for await (const page of docsCrawler.crawl(
|
||||
new URL(url),
|
||||
NUM_PAGES_TO_CRAWL,
|
||||
)) {
|
||||
crawlResults.push(page);
|
||||
}
|
||||
|
||||
expect(crawlResults.length).toBeGreaterThanOrEqual(numPagesToCrawl);
|
||||
},
|
||||
TIMEOUT_MS,
|
||||
);
|
||||
});
|
||||
}
|
||||
|
||||
describe("GitHub Crawler", () => {
|
||||
const repoUrl =
|
||||
"https://github.com/Patrick-Erichsen/test-github-repo-for-crawling";
|
||||
|
||||
let crawlResults: PageData[];
|
||||
|
||||
beforeAll(async () => {
|
||||
crawlResults = [];
|
||||
|
||||
for await (const page of docsCrawler.crawl(new URL(repoUrl))) {
|
||||
crawlResults.push(page);
|
||||
}
|
||||
}, TIMEOUT_MS);
|
||||
|
||||
test("finds expected markdown files", async () => {
|
||||
expect(crawlResults.some((page) => page.path.endsWith("README.md"))).toBe(
|
||||
true,
|
||||
);
|
||||
|
||||
expect(
|
||||
crawlResults.some((page) => page.path.endsWith("docs-depth-1.md")),
|
||||
).toBe(true);
|
||||
});
|
||||
|
||||
test("html includes the correct content", async () => {
|
||||
const doc = crawlResults.find((page) =>
|
||||
page.path.endsWith("docs-depth-1.md"),
|
||||
);
|
||||
|
||||
expect(doc?.content.includes("Test body")).toBe(true);
|
||||
expect(doc?.content.includes("Test H2 Header")).toBe(true);
|
||||
});
|
||||
|
||||
test("ignores non-markdown files, e.g. `test.js` at the root", async () => {
|
||||
expect(crawlResults.some((page) => page.path.endsWith("test.js"))).toBe(
|
||||
false,
|
||||
);
|
||||
});
|
||||
});
|
||||
|
||||
describe("Chromium Crawler", () => {
|
||||
let shouldUseChromiumSpy: any;
|
||||
|
||||
beforeAll(() => {
|
||||
shouldUseChromiumSpy = jest
|
||||
.spyOn(docsCrawler as any, "shouldUseChromium")
|
||||
.mockReturnValue(true);
|
||||
});
|
||||
|
||||
afterAll(() => {
|
||||
shouldUseChromiumSpy.mockRestore();
|
||||
});
|
||||
|
||||
describe("Pre-indexed Docs", () => {
|
||||
crawlTest(Object.keys(preIndexedDocs));
|
||||
});
|
||||
|
||||
describe("Running list of common sites", () => {
|
||||
crawlTest([
|
||||
"https://docs.nestjs.com/",
|
||||
"https://go.dev/doc/",
|
||||
"https://clickhouse.com/docs",
|
||||
"https://www.tensorflow.org/api_docs",
|
||||
// "https://www.rust-lang.org/learn", TODO: This is failing
|
||||
"https://docs.anthropic.com/en/docs",
|
||||
]);
|
||||
});
|
||||
});
|
||||
|
||||
describe("Cheerio Crawler", () => {
|
||||
crawlTest(["https://amplified.dev/"], 1);
|
||||
});
|
||||
});
|
||||
|
|
@ -1,100 +0,0 @@
|
|||
import { URL } from "node:url";
|
||||
|
||||
// @ts-ignore
|
||||
// @prettier-ignore
|
||||
import { ContinueConfig, IDE } from "../..";
|
||||
|
||||
import CheerioCrawler from "./crawlers/CheerioCrawler";
|
||||
import { ChromiumCrawler, ChromiumInstaller } from "./crawlers/ChromiumCrawler";
|
||||
import { DefaultCrawler } from "./crawlers/DefaultCrawler";
|
||||
import GitHubCrawler from "./crawlers/GitHubCrawler";
|
||||
|
||||
export type PageData = {
|
||||
url: string;
|
||||
path: string;
|
||||
content: string;
|
||||
};
|
||||
|
||||
class DocsCrawler {
|
||||
private readonly MAX_REQUESTS_PER_CRAWL = 1000;
|
||||
private readonly GITHUB_HOST = "github.com";
|
||||
private readonly chromiumInstaller: ChromiumInstaller;
|
||||
|
||||
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(
|
||||
startUrl: URL,
|
||||
maxRequestsPerCrawl: number = this.MAX_REQUESTS_PER_CRAWL,
|
||||
): AsyncGenerator<PageData, undefined, undefined> {
|
||||
if (startUrl.host === this.GITHUB_HOST) {
|
||||
yield* new GitHubCrawler(startUrl).crawl();
|
||||
return;
|
||||
}
|
||||
|
||||
try {
|
||||
const pageData = await new DefaultCrawler(startUrl).crawl();
|
||||
if (pageData.length > 0) {
|
||||
yield* pageData;
|
||||
return;
|
||||
}
|
||||
} catch (e) {
|
||||
console.error("Default crawler failed, trying backup: ", e);
|
||||
}
|
||||
|
||||
if (this.shouldUseChromium()) {
|
||||
yield* new ChromiumCrawler(startUrl, maxRequestsPerCrawl).crawl();
|
||||
} else {
|
||||
let didCrawlSinglePage = false;
|
||||
|
||||
for await (const pageData of new CheerioCrawler(
|
||||
startUrl,
|
||||
maxRequestsPerCrawl,
|
||||
).crawl()) {
|
||||
yield pageData;
|
||||
didCrawlSinglePage = true;
|
||||
}
|
||||
|
||||
// We assume that if we failed to crawl a single page,
|
||||
// it was due to an error that using Chromium can resolve
|
||||
const shouldProposeUseChromium =
|
||||
!didCrawlSinglePage &&
|
||||
this.chromiumInstaller.shouldProposeUseChromiumOnCrawlFailure();
|
||||
|
||||
if (shouldProposeUseChromium) {
|
||||
const didInstall =
|
||||
await this.chromiumInstaller.proposeAndAttemptInstall(
|
||||
startUrl.toString(),
|
||||
);
|
||||
|
||||
if (didInstall) {
|
||||
void this.ide.showToast(
|
||||
"info",
|
||||
`Successfully installed Chromium! Retrying crawl of: ${startUrl.toString()}`,
|
||||
);
|
||||
|
||||
yield* new ChromiumCrawler(startUrl, maxRequestsPerCrawl).crawl();
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
export default DocsCrawler;
|
||||
export {
|
||||
CheerioCrawler,
|
||||
ChromiumCrawler,
|
||||
ChromiumInstaller,
|
||||
GitHubCrawler,
|
||||
};
|
||||
|
|
@ -105,28 +105,28 @@ describe.skip("DocsService Integration Tests", () => {
|
|||
expect(retrievedChunks.length).toBe(0);
|
||||
});
|
||||
|
||||
test("Reindexes when changing embeddings provider", async () => {
|
||||
const originalEmbeddingsProvider =
|
||||
await docsService.getEmbeddingsProvider();
|
||||
// test("Reindexes when changing embeddings provider", async () => {
|
||||
// const originalEmbeddingsProvider =
|
||||
// await docsService.getEmbeddingsProvider();
|
||||
|
||||
// Change embeddings provider
|
||||
editConfigJson((config) => ({
|
||||
...config,
|
||||
embeddingsProvider: {
|
||||
provider: FreeTrial.providerName,
|
||||
},
|
||||
}));
|
||||
// // Change embeddings provider
|
||||
// editConfigJson((config) => ({
|
||||
// ...config,
|
||||
// embeddingsProvider: {
|
||||
// provider: FreeTrial.providerName,
|
||||
// },
|
||||
// }));
|
||||
|
||||
await getReloadedConfig();
|
||||
// await getReloadedConfig();
|
||||
|
||||
const newEmbeddingsProvider = await docsService.getEmbeddingsProvider();
|
||||
// const { provider, isPreindexed} = await docsService.getEmbeddingsProvider();
|
||||
|
||||
// Verify reindexing
|
||||
const [originalVector] = await originalEmbeddingsProvider.embed(["test"]);
|
||||
const [newMockVector] = await newEmbeddingsProvider.embed(["test"]);
|
||||
// // Verify reindexing
|
||||
// const [originalVector] = await originalEmbeddingsProvider.embed(["test"]);
|
||||
// const [newMockVector] = await provider.embed(["test"]);
|
||||
|
||||
expect(originalVector).not.toEqual(newMockVector);
|
||||
});
|
||||
// expect(originalVector).not.toEqual(newMockVector);
|
||||
// });
|
||||
|
||||
test("Handles pulling down and adding pre-indexed docs", async () => {
|
||||
const preIndexedDoc = Object.values(preIndexedDocs)[0];
|
||||
|
|
|
|||
|
|
@ -25,9 +25,13 @@ import {
|
|||
} from "../../util/paths";
|
||||
import { Telemetry } from "../../util/posthog";
|
||||
|
||||
import {
|
||||
ArticleWithChunks,
|
||||
htmlPageToArticleWithChunks,
|
||||
markdownPageToArticleWithChunks,
|
||||
} from "./article";
|
||||
import DocsCrawler, { DocsCrawlerType, PageData } from "./crawlers/DocsCrawler";
|
||||
import { ConfigResult } from "@continuedev/config-yaml";
|
||||
import { Article, chunkArticle, pageToArticle } from "./article";
|
||||
import DocsCrawler from "./DocsCrawler";
|
||||
import { runLanceMigrations, runSqliteMigrations } from "./migrations";
|
||||
import {
|
||||
downloadFromS3,
|
||||
|
|
@ -73,8 +77,6 @@ export type AddParams = {
|
|||
- delete
|
||||
- reindex all
|
||||
- add/index one
|
||||
- Currently a full reindex deletes all docs rather than storing PER embeddings provider
|
||||
- The last successful embeddings provider is stored in global context and updated AFTER an indexing process is successful
|
||||
*/
|
||||
export default class DocsService {
|
||||
static lanceTableName = "docs";
|
||||
|
|
@ -92,8 +94,8 @@ export default class DocsService {
|
|||
private config!: ContinueConfig;
|
||||
private sqliteDb?: Database;
|
||||
|
||||
private docsCrawler!: DocsCrawler;
|
||||
private ideInfoPromise: Promise<IdeInfo>;
|
||||
private githubToken?: string;
|
||||
|
||||
constructor(
|
||||
configHandler: ConfigHandler,
|
||||
|
|
@ -104,6 +106,10 @@ export default class DocsService {
|
|||
this.isInitialized = this.init(configHandler);
|
||||
}
|
||||
|
||||
setGithubToken(token: string) {
|
||||
this.githubToken = token;
|
||||
}
|
||||
|
||||
// Singleton pattern: only one service globally
|
||||
private static instance?: DocsService;
|
||||
static createSingleton(
|
||||
|
|
@ -196,6 +202,7 @@ export default class DocsService {
|
|||
}
|
||||
}
|
||||
|
||||
// Used to check periodically during indexing if should cancel indexing
|
||||
shouldCancel(startUrl: string, startedWithEmbedder: string) {
|
||||
// Check if aborted
|
||||
const isAborted = this.statuses.get(startUrl)?.status === "aborted";
|
||||
|
|
@ -215,21 +222,6 @@ export default class DocsService {
|
|||
return false;
|
||||
}
|
||||
|
||||
// NOTE Pausing not supported for docs yet
|
||||
// setPaused(startUrl: string, pause: boolean) {
|
||||
// const status = this.statuses.get(startUrl);
|
||||
// if (status) {
|
||||
// this.handleStatusUpdate({
|
||||
// ...status,
|
||||
// status: pause ? "paused" : "indexing",
|
||||
// });
|
||||
// }
|
||||
// }
|
||||
|
||||
// isPaused(startUrl: string) {
|
||||
// return this.statuses.get(startUrl)?.status === "paused";
|
||||
// }
|
||||
|
||||
/*
|
||||
* Currently, we generate and host embeddings for pre-indexed docs using transformers.
|
||||
* However, we don't ship transformers with the JetBrains extension.
|
||||
|
|
@ -251,14 +243,29 @@ export default class DocsService {
|
|||
return isPreIndexedDocsProvider && !canUsePreindexedDocs;
|
||||
}
|
||||
|
||||
async getEmbeddingsProvider(isPreIndexedDoc: boolean = false): Promise<ILLM> {
|
||||
const canUsePreindexedDocs = await this.canUsePreindexedDocs();
|
||||
// Determines if using preIndexed and returns proper embeddings provider
|
||||
async getEmbeddingsProvider(startUrl: string) {
|
||||
// Conditions for using a pre-indexed doc
|
||||
|
||||
if (canUsePreindexedDocs && isPreIndexedDoc) {
|
||||
return DocsService.preIndexedDocsEmbeddingsProvider;
|
||||
// Must be in pre indexed docs file
|
||||
const preIndexedDoc = preIndexedDocs[startUrl];
|
||||
if (preIndexedDoc) {
|
||||
// Most not be overriden by config
|
||||
if (!this.config?.docs?.find((doc) => doc.startUrl === startUrl)) {
|
||||
// Must be supported
|
||||
const canUsePreindexedDocs = await this.canUsePreindexedDocs();
|
||||
if (canUsePreindexedDocs) {
|
||||
return {
|
||||
provider: DocsService.preIndexedDocsEmbeddingsProvider,
|
||||
isPreindexed: true,
|
||||
};
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return this.config.embeddingsProvider;
|
||||
return {
|
||||
provider: this.config.embeddingsProvider,
|
||||
isPreindexed: false,
|
||||
};
|
||||
}
|
||||
|
||||
private async handleConfigUpdate({
|
||||
|
|
@ -268,8 +275,6 @@ export default class DocsService {
|
|||
const oldConfig = this.config;
|
||||
this.config = newConfig; // IMPORTANT - need to set up top, other methods below use this without passing it in
|
||||
|
||||
this.docsCrawler = new DocsCrawler(this.ide, newConfig);
|
||||
|
||||
if (this.config.disableIndexing) {
|
||||
return;
|
||||
}
|
||||
|
|
@ -365,16 +370,13 @@ export default class DocsService {
|
|||
console.warn("Attempting to add/index docs when indexing is disabled");
|
||||
return;
|
||||
}
|
||||
const { startUrl } = siteIndexingConfig;
|
||||
const { startUrl, useLocalCrawling, maxDepth } = siteIndexingConfig;
|
||||
|
||||
const canUsePreindexedDocs = await this.canUsePreindexedDocs();
|
||||
if (canUsePreindexedDocs) {
|
||||
const preIndexedDoc = preIndexedDocs[startUrl];
|
||||
const isPreIndexedDoc = !!preIndexedDoc;
|
||||
if (isPreIndexedDoc) {
|
||||
console.warn("Can not override pre-indexed start urls");
|
||||
return;
|
||||
}
|
||||
const { isPreindexed, provider } =
|
||||
await this.getEmbeddingsProvider(startUrl);
|
||||
if (isPreindexed) {
|
||||
console.warn("Attempted to indexAndAdd pre-indexed doc");
|
||||
return;
|
||||
}
|
||||
|
||||
// Queue - indexAndAdd is invoked circularly by config edits. This prevents duplicate runs
|
||||
|
|
@ -382,8 +384,7 @@ export default class DocsService {
|
|||
return;
|
||||
}
|
||||
|
||||
const embeddingsProvider = await this.getEmbeddingsProvider();
|
||||
const startedWithEmbedder = this.config.embeddingsProvider.embeddingId;
|
||||
const startedWithEmbedder = provider.embeddingId;
|
||||
const indexExists = await this.hasMetadata(startUrl);
|
||||
|
||||
// Build status update - most of it is fixed values
|
||||
|
|
@ -393,7 +394,7 @@ export default class DocsService {
|
|||
> = {
|
||||
type: "docs",
|
||||
id: siteIndexingConfig.startUrl,
|
||||
embeddingsProviderId: embeddingsProvider.embeddingId,
|
||||
embeddingsProviderId: provider.embeddingId,
|
||||
isReindexing: reIndex && indexExists,
|
||||
title: siteIndexingConfig.title,
|
||||
debugInfo: `max depth: ${siteIndexingConfig.maxDepth}`,
|
||||
|
|
@ -429,47 +430,81 @@ export default class DocsService {
|
|||
progress: 0,
|
||||
});
|
||||
|
||||
const articles: Article[] = [];
|
||||
// Crawl pages to get page data
|
||||
const pages: PageData[] = [];
|
||||
let processedPages = 0;
|
||||
let estimatedProgress = 0;
|
||||
let done = false;
|
||||
let usedCrawler: DocsCrawlerType | undefined = undefined;
|
||||
|
||||
// Crawl pages and retrieve info as articles
|
||||
for await (const page of this.docsCrawler.crawl(new URL(startUrl))) {
|
||||
estimatedProgress += 1 / 2 ** (processedPages + 1);
|
||||
const docsCrawler = new DocsCrawler(
|
||||
this.ide,
|
||||
this.config,
|
||||
maxDepth,
|
||||
undefined,
|
||||
useLocalCrawling,
|
||||
this.githubToken,
|
||||
);
|
||||
const crawlerGen = docsCrawler.crawl(new URL(startUrl));
|
||||
|
||||
// NOTE - during "indexing" phase, check if aborted before each status update
|
||||
if (this.shouldCancel(startUrl, startedWithEmbedder)) {
|
||||
return;
|
||||
while (!done) {
|
||||
const result = await crawlerGen.next();
|
||||
if (result.done) {
|
||||
done = true;
|
||||
usedCrawler = result.value;
|
||||
} else {
|
||||
const page = result.value;
|
||||
estimatedProgress += 1 / 2 ** (processedPages + 1);
|
||||
|
||||
// NOTE - during "indexing" phase, check if aborted before each status update
|
||||
if (this.shouldCancel(startUrl, startedWithEmbedder)) {
|
||||
return;
|
||||
}
|
||||
this.handleStatusUpdate({
|
||||
...fixedStatus,
|
||||
description: `Finding subpages (${page.path})`,
|
||||
status: "indexing",
|
||||
progress:
|
||||
0.15 * estimatedProgress +
|
||||
Math.min(0.35, (0.35 * processedPages) / 500),
|
||||
// For the first 50%, 15% is sum of series 1/(2^n) and the other 35% is based on number of files/ 500 max
|
||||
});
|
||||
|
||||
pages.push(page);
|
||||
|
||||
processedPages++;
|
||||
|
||||
// Locks down GUI if no sleeping
|
||||
// Wait proportional to how many docs are indexing
|
||||
const toWait = 100 * this.docsIndexingQueue.size + 50;
|
||||
await new Promise((resolve) => setTimeout(resolve, toWait));
|
||||
}
|
||||
this.handleStatusUpdate({
|
||||
...fixedStatus,
|
||||
description: `Finding subpages (${page.path})`,
|
||||
status: "indexing",
|
||||
progress:
|
||||
0.15 * estimatedProgress +
|
||||
Math.min(0.35, (0.35 * processedPages) / 500),
|
||||
// For the first 50%, 15% is sum of series 1/(2^n) and the other 35% is based on number of files/ 500 max
|
||||
});
|
||||
|
||||
const article = pageToArticle(page);
|
||||
if (!article) {
|
||||
continue;
|
||||
}
|
||||
articles.push(article);
|
||||
|
||||
processedPages++;
|
||||
|
||||
// Locks down GUI if no sleeping
|
||||
// Wait proportional to how many docs are indexing
|
||||
const toWait = 100 * this.docsIndexingQueue.size + 50;
|
||||
await new Promise((resolve) => setTimeout(resolve, toWait));
|
||||
}
|
||||
|
||||
void Telemetry.capture("docs_pages_crawled", {
|
||||
count: processedPages,
|
||||
});
|
||||
|
||||
// Chunk pages based on which crawler was used
|
||||
const articles: ArticleWithChunks[] = [];
|
||||
const chunks: Chunk[] = [];
|
||||
const articleChunker =
|
||||
usedCrawler === "github"
|
||||
? markdownPageToArticleWithChunks
|
||||
: htmlPageToArticleWithChunks;
|
||||
for (const page of pages) {
|
||||
const articleWithChunks = await articleChunker(
|
||||
page,
|
||||
provider.maxEmbeddingChunkSize,
|
||||
);
|
||||
if (articleWithChunks) {
|
||||
articles.push(articleWithChunks);
|
||||
}
|
||||
const toWait = 20 * this.docsIndexingQueue.size + 10;
|
||||
await new Promise((resolve) => setTimeout(resolve, toWait));
|
||||
}
|
||||
|
||||
// const chunks: Chunk[] = [];
|
||||
const embeddings: number[][] = [];
|
||||
|
||||
// Create embeddings of retrieved articles
|
||||
|
|
@ -482,35 +517,26 @@ export default class DocsService {
|
|||
this.handleStatusUpdate({
|
||||
...fixedStatus,
|
||||
status: "indexing",
|
||||
description: `Creating Embeddings: ${article.subpath}`,
|
||||
description: `Creating Embeddings: ${article.article.subpath}`,
|
||||
progress: 0.5 + 0.3 * (i / articles.length), // 50% -> 80%
|
||||
});
|
||||
|
||||
try {
|
||||
const chunkedArticle = chunkArticle(
|
||||
article,
|
||||
embeddingsProvider.maxEmbeddingChunkSize,
|
||||
const subpathEmbeddings = await provider.embed(
|
||||
article.chunks.map((c) => c.content),
|
||||
);
|
||||
|
||||
const chunkedArticleContents = chunkedArticle.map(
|
||||
(chunk) => chunk.content,
|
||||
);
|
||||
|
||||
chunks.push(...chunkedArticle);
|
||||
|
||||
const subpathEmbeddings = await embeddingsProvider.embed(
|
||||
chunkedArticleContents,
|
||||
);
|
||||
|
||||
chunks.push(...article.chunks);
|
||||
embeddings.push(...subpathEmbeddings);
|
||||
const toWait = 100 * this.docsIndexingQueue.size + 50;
|
||||
await new Promise((resolve) => setTimeout(resolve, toWait));
|
||||
} catch (e) {
|
||||
console.warn("Error chunking article: ", e);
|
||||
console.warn("Error embedding article chunks: ", e);
|
||||
}
|
||||
}
|
||||
|
||||
if (embeddings.length === 0) {
|
||||
console.error(
|
||||
`No embeddings were created for site: ${siteIndexingConfig.startUrl}\n Num chunks: ${chunks.length}`,
|
||||
`No embeddings were created for site: ${startUrl}\n Num chunks: ${chunks.length}`,
|
||||
);
|
||||
|
||||
if (this.shouldCancel(startUrl, startedWithEmbedder)) {
|
||||
|
|
@ -518,7 +544,7 @@ export default class DocsService {
|
|||
}
|
||||
this.handleStatusUpdate({
|
||||
...fixedStatus,
|
||||
description: `No embeddings were created for site: ${siteIndexingConfig.startUrl}`,
|
||||
description: `No embeddings were created for site: ${startUrl}`,
|
||||
status: "failed",
|
||||
progress: 1,
|
||||
});
|
||||
|
|
@ -584,10 +610,19 @@ export default class DocsService {
|
|||
providers: ["docs"],
|
||||
});
|
||||
} catch (e) {
|
||||
let description = `Error getting docs from: ${siteIndexingConfig.startUrl}`;
|
||||
if (e instanceof Error) {
|
||||
if (
|
||||
e.message.includes("github.com") &&
|
||||
e.message.includes("rate limit")
|
||||
) {
|
||||
description = "Github rate limit exceeded";
|
||||
}
|
||||
}
|
||||
console.error("Error indexing docs", e);
|
||||
this.handleStatusUpdate({
|
||||
...fixedStatus,
|
||||
description: `Error getting docs from: ${siteIndexingConfig.startUrl}`,
|
||||
description,
|
||||
status: "failed",
|
||||
progress: 1,
|
||||
});
|
||||
|
|
@ -600,11 +635,12 @@ export default class DocsService {
|
|||
// And pre-indexed embeddings are supported
|
||||
// Fetch pre-indexed embeddings from S3, add to Lance, and then search those
|
||||
private async fetchAndAddPreIndexedDocEmbeddings(title: string) {
|
||||
const embeddingsProvider = await this.getEmbeddingsProvider(true);
|
||||
|
||||
const data = await downloadFromS3(
|
||||
S3Buckets.continueIndexedDocs,
|
||||
getS3Filename(embeddingsProvider.embeddingId, title),
|
||||
getS3Filename(
|
||||
DocsService.preIndexedDocsEmbeddingsProvider.embeddingId,
|
||||
title,
|
||||
),
|
||||
);
|
||||
|
||||
const siteEmbeddings = JSON.parse(data) as SiteIndexingResults;
|
||||
|
|
@ -645,19 +681,18 @@ export default class DocsService {
|
|||
return [];
|
||||
}
|
||||
|
||||
const preIndexedDoc = preIndexedDocs[startUrl];
|
||||
if (!!preIndexedDoc) {
|
||||
const { isPreindexed, provider } =
|
||||
await this.getEmbeddingsProvider(startUrl);
|
||||
|
||||
if (isPreindexed) {
|
||||
void Telemetry.capture("docs_pre_indexed_doc_used", {
|
||||
doc: preIndexedDoc["title"],
|
||||
doc: preIndexedDocs[startUrl]!["title"],
|
||||
});
|
||||
}
|
||||
|
||||
const embeddingsProvider =
|
||||
await this.getEmbeddingsProvider(!!preIndexedDoc);
|
||||
const [vector] = await provider.embed([query]);
|
||||
|
||||
const [vector] = await embeddingsProvider.embed([query]);
|
||||
|
||||
return await this.retrieveChunks(startUrl, vector, nRetrieve);
|
||||
return await this.retrieveChunks(startUrl, vector, nRetrieve, isPreindexed);
|
||||
}
|
||||
|
||||
// This is split into its own function so that it can be recursive
|
||||
|
|
@ -666,15 +701,13 @@ export default class DocsService {
|
|||
startUrl: string,
|
||||
vector: number[],
|
||||
nRetrieve: number,
|
||||
isPreindexed: boolean,
|
||||
isRetry: boolean = false,
|
||||
): Promise<Chunk[]> {
|
||||
const preIndexedDoc = preIndexedDocs[startUrl];
|
||||
const isPreIndexedDoc = !!preIndexedDoc;
|
||||
|
||||
// Lance doesn't have an embeddingsprovider column, instead it includes it in the table name
|
||||
const table = await this.getOrCreateLanceTable({
|
||||
initializationVector: vector,
|
||||
isPreIndexedDoc,
|
||||
startUrl,
|
||||
});
|
||||
|
||||
let docs: LanceDbDocsRow[] = [];
|
||||
|
|
@ -689,18 +722,14 @@ export default class DocsService {
|
|||
}
|
||||
|
||||
// No docs are found for preindexed? try fetching once
|
||||
if (docs.length === 0 && isPreIndexedDoc) {
|
||||
if (docs.length === 0 && isPreindexed) {
|
||||
if (isRetry) {
|
||||
return [];
|
||||
}
|
||||
await this.fetchAndAddPreIndexedDocEmbeddings(preIndexedDoc.title);
|
||||
return await this.retrieveChunks(startUrl, vector, nRetrieve, true);
|
||||
}
|
||||
|
||||
if (isPreIndexedDoc) {
|
||||
void Telemetry.capture("docs_pre_indexed_doc_used", {
|
||||
doc: preIndexedDoc["title"],
|
||||
});
|
||||
await this.fetchAndAddPreIndexedDocEmbeddings(
|
||||
preIndexedDocs[startUrl]!["title"],
|
||||
);
|
||||
return await this.retrieveChunks(startUrl, vector, nRetrieve, true, true);
|
||||
}
|
||||
|
||||
return docs.map((doc) => ({
|
||||
|
|
@ -802,13 +831,10 @@ export default class DocsService {
|
|||
const oldConfigDoc = oldConfigDocs.find(
|
||||
(d) => d.startUrl === doc.startUrl,
|
||||
);
|
||||
// const currentStatus = this.statuses.get(doc.startUrl);
|
||||
|
||||
if (
|
||||
// currentStatus?.status === "complete" &&
|
||||
oldConfigDoc &&
|
||||
(oldConfigDoc.maxDepth !== doc.maxDepth ||
|
||||
oldConfigDoc.title !== doc.title ||
|
||||
oldConfigDoc.faviconUrl !== doc.faviconUrl)
|
||||
!this.siteIndexingConfigsAreEqual(oldConfigDoc, doc)
|
||||
) {
|
||||
changedDocs.push(doc);
|
||||
} else {
|
||||
|
|
@ -828,7 +854,10 @@ export default class DocsService {
|
|||
});
|
||||
}
|
||||
} else {
|
||||
newDocs.push(doc);
|
||||
const currentStatus = this.statuses.get(doc.startUrl);
|
||||
if (currentStatus?.status !== "failed") {
|
||||
newDocs.push(doc);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
|
@ -892,10 +921,7 @@ export default class DocsService {
|
|||
return name.replace(/[^a-zA-Z0-9_.-]/g, "_");
|
||||
}
|
||||
|
||||
private async getLanceTableName(isPreIndexedDoc: boolean) {
|
||||
const embeddingsProvider =
|
||||
await this.getEmbeddingsProvider(isPreIndexedDoc);
|
||||
|
||||
private async getLanceTableName(embeddingsProvider: ILLM) {
|
||||
const tableName = this.sanitizeLanceTableName(
|
||||
`${DocsService.lanceTableName}${embeddingsProvider.embeddingId}`,
|
||||
);
|
||||
|
|
@ -905,15 +931,16 @@ export default class DocsService {
|
|||
|
||||
private async getOrCreateLanceTable({
|
||||
initializationVector,
|
||||
isPreIndexedDoc,
|
||||
startUrl,
|
||||
}: {
|
||||
initializationVector: number[];
|
||||
isPreIndexedDoc?: boolean;
|
||||
startUrl: string;
|
||||
}) {
|
||||
const conn = await lancedb.connect(getLanceDbPath());
|
||||
const tableNames = await conn.tableNames();
|
||||
const { provider } = await this.getEmbeddingsProvider(startUrl);
|
||||
const tableNameFromEmbeddingsProvider =
|
||||
await this.getLanceTableName(!!isPreIndexedDoc);
|
||||
await this.getLanceTableName(provider);
|
||||
|
||||
if (!tableNames.includes(tableNameFromEmbeddingsProvider)) {
|
||||
if (initializationVector) {
|
||||
|
|
@ -944,16 +971,16 @@ export default class DocsService {
|
|||
embeddings,
|
||||
}: AddParams) {
|
||||
const sampleVector = embeddings[0];
|
||||
const isPreIndexedDoc = !!preIndexedDocs[siteIndexingConfig.startUrl];
|
||||
const { startUrl } = siteIndexingConfig;
|
||||
|
||||
const table = await this.getOrCreateLanceTable({
|
||||
isPreIndexedDoc,
|
||||
startUrl,
|
||||
initializationVector: sampleVector,
|
||||
});
|
||||
|
||||
const rows: LanceDbDocsRow[] = chunks.map((chunk, i) => ({
|
||||
vector: embeddings[i],
|
||||
starturl: siteIndexingConfig.startUrl,
|
||||
starturl: startUrl,
|
||||
title: chunk.otherMetadata?.title || siteIndexingConfig.title,
|
||||
content: chunk.content,
|
||||
path: chunk.filepath,
|
||||
|
|
@ -978,16 +1005,24 @@ export default class DocsService {
|
|||
);
|
||||
}
|
||||
|
||||
private siteIndexingConfigsAreEqual(
|
||||
config1: SiteIndexingConfig,
|
||||
config2: SiteIndexingConfig,
|
||||
) {
|
||||
return (
|
||||
config1.startUrl === config2.startUrl &&
|
||||
config1.faviconUrl === config2.faviconUrl &&
|
||||
config1.title === config2.title &&
|
||||
config1.maxDepth === config2.maxDepth &&
|
||||
config1.useLocalCrawling === config2.useLocalCrawling
|
||||
);
|
||||
}
|
||||
|
||||
private addToConfig(siteIndexingConfig: SiteIndexingConfig) {
|
||||
// Handles the case where a user has manually added the doc to config.json
|
||||
// so it already exists in the file
|
||||
const doesEquivalentDocExist = this.config.docs?.some(
|
||||
(doc) =>
|
||||
doc.startUrl === siteIndexingConfig.startUrl &&
|
||||
doc.faviconUrl === siteIndexingConfig.faviconUrl &&
|
||||
siteIndexingConfig.title === doc.title,
|
||||
// siteIndexingConfig.maxDepth === doc.maxDepth &&
|
||||
// doc.rootUrl === siteIndexingConfig.rootUrl,
|
||||
const doesEquivalentDocExist = this.config.docs?.some((doc) =>
|
||||
this.siteIndexingConfigsAreEqual(doc, siteIndexingConfig),
|
||||
);
|
||||
|
||||
if (!doesEquivalentDocExist) {
|
||||
|
|
@ -1045,7 +1080,7 @@ export default class DocsService {
|
|||
}
|
||||
}
|
||||
|
||||
async deleteIndexes(startUrl: string) {
|
||||
private async deleteIndexes(startUrl: string) {
|
||||
await this.deleteEmbeddingsFromLance(startUrl);
|
||||
await this.deleteMetadataFromSqlite(startUrl);
|
||||
}
|
||||
|
|
|
|||
|
|
@ -2,9 +2,9 @@ import { Readability } from "@mozilla/readability";
|
|||
import { JSDOM } from "jsdom";
|
||||
|
||||
import { Chunk } from "../../";
|
||||
import { cleanFragment, cleanHeader } from "../chunk/markdown";
|
||||
import { cleanFragment, cleanHeader, markdownChunker } from "../chunk/markdown";
|
||||
|
||||
import { type PageData } from "./DocsCrawler";
|
||||
import { type PageData } from "./crawlers/DocsCrawler";
|
||||
|
||||
export type ArticleComponent = {
|
||||
title: string;
|
||||
|
|
@ -18,6 +18,11 @@ export type Article = {
|
|||
article_components: ArticleComponent[];
|
||||
};
|
||||
|
||||
export type ArticleWithChunks = {
|
||||
article: Article;
|
||||
chunks: Chunk[];
|
||||
};
|
||||
|
||||
function breakdownArticleComponent(
|
||||
url: string,
|
||||
article: ArticleComponent,
|
||||
|
|
@ -99,78 +104,100 @@ function breakdownArticleComponent(
|
|||
return chunks.filter((c) => c.content.trim().length > 20);
|
||||
}
|
||||
|
||||
export function chunkArticle(
|
||||
articleResult: Article,
|
||||
maxChunkSize: number,
|
||||
): Chunk[] {
|
||||
let chunks: Chunk[] = [];
|
||||
function chunkArticle(article: Article, maxChunkSize: number): Chunk[] {
|
||||
const chunks: Chunk[] = [];
|
||||
|
||||
for (const article of articleResult.article_components) {
|
||||
for (const component of article.article_components) {
|
||||
const articleChunks = breakdownArticleComponent(
|
||||
articleResult.url,
|
||||
article,
|
||||
articleResult.subpath,
|
||||
article.url,
|
||||
component,
|
||||
article.subpath,
|
||||
maxChunkSize,
|
||||
);
|
||||
chunks = [...chunks, ...articleChunks];
|
||||
chunks.push(...articleChunks);
|
||||
}
|
||||
|
||||
return chunks;
|
||||
}
|
||||
|
||||
function extractTitlesAndBodies(html: string): ArticleComponent[] {
|
||||
const dom = new JSDOM(html);
|
||||
const document = dom.window.document;
|
||||
|
||||
const titles = Array.from(document.querySelectorAll("h2"));
|
||||
const result = titles.map((titleElement) => {
|
||||
const title = titleElement.textContent || "";
|
||||
let body = "";
|
||||
let nextSibling = titleElement.nextElementSibling;
|
||||
|
||||
while (nextSibling && nextSibling.tagName !== "H2") {
|
||||
body += nextSibling.textContent || "";
|
||||
nextSibling = nextSibling.nextElementSibling;
|
||||
}
|
||||
|
||||
return { title, body };
|
||||
});
|
||||
|
||||
return result;
|
||||
}
|
||||
export function stringToArticle(
|
||||
url: string,
|
||||
html: string,
|
||||
subpath: string,
|
||||
): Article | undefined {
|
||||
export async function htmlPageToArticleWithChunks(
|
||||
page: PageData,
|
||||
maxChunkSize: number,
|
||||
): Promise<ArticleWithChunks | undefined> {
|
||||
try {
|
||||
const html = page.content;
|
||||
const subpath = page.path;
|
||||
const url = page.url;
|
||||
|
||||
const dom = new JSDOM(html);
|
||||
const reader = new Readability(dom.window.document);
|
||||
const article = reader.parse();
|
||||
const readability = reader.parse();
|
||||
|
||||
if (!readability) {
|
||||
console.error("Docs indexing: Error getting readability for URL", url);
|
||||
|
||||
if (!article) {
|
||||
return undefined;
|
||||
}
|
||||
|
||||
const article_components = extractTitlesAndBodies(article.content);
|
||||
const titles = Array.from(dom.window.document.querySelectorAll("h2"));
|
||||
const article_components = titles.map((titleElement) => {
|
||||
const title = titleElement.textContent || "";
|
||||
let body = "";
|
||||
let nextSibling = titleElement.nextElementSibling;
|
||||
|
||||
return {
|
||||
while (nextSibling && nextSibling.tagName !== "H2") {
|
||||
body += nextSibling.textContent || "";
|
||||
nextSibling = nextSibling.nextElementSibling;
|
||||
}
|
||||
|
||||
return { title, body };
|
||||
});
|
||||
|
||||
const article = {
|
||||
url,
|
||||
subpath,
|
||||
title: article.title,
|
||||
title: readability.title,
|
||||
article_components,
|
||||
};
|
||||
return {
|
||||
article,
|
||||
chunks: chunkArticle(article, maxChunkSize),
|
||||
};
|
||||
} catch (err) {
|
||||
console.error("Error converting URL to article components", err);
|
||||
return undefined;
|
||||
}
|
||||
}
|
||||
|
||||
export function pageToArticle(page: PageData): Article | undefined {
|
||||
export async function markdownPageToArticleWithChunks(
|
||||
page: PageData,
|
||||
maxChunkSize: number,
|
||||
): Promise<ArticleWithChunks | undefined> {
|
||||
try {
|
||||
return stringToArticle(page.url, page.content, page.path);
|
||||
let index = 0;
|
||||
const chunks: Chunk[] = [];
|
||||
const chunker = markdownChunker(page.content, maxChunkSize, 1);
|
||||
for await (const chunk of chunker) {
|
||||
const fullUrl = new URL(page.url);
|
||||
fullUrl.hash = `#${cleanFragment(chunk.otherMetadata?.title)}`;
|
||||
|
||||
chunks.push({
|
||||
...chunk,
|
||||
index,
|
||||
filepath: fullUrl.toString(),
|
||||
digest: fullUrl.toString(),
|
||||
});
|
||||
index++;
|
||||
}
|
||||
return {
|
||||
article: {
|
||||
url: page.url,
|
||||
subpath: page.path,
|
||||
article_components: [], // TODO: markdown chunker just skips this for now since not used outside, only for html chunker
|
||||
title: chunks[0]?.otherMetadata?.title || page.path,
|
||||
},
|
||||
chunks,
|
||||
};
|
||||
} catch (err) {
|
||||
console.error("Error converting URL to article components", err);
|
||||
return undefined;
|
||||
console.error(`Docs indexing: failed to chunk markdown from ${page.url}`);
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -2,7 +2,7 @@ import { URL } from "node:url";
|
|||
|
||||
import * as cheerio from "cheerio";
|
||||
|
||||
import { PageData } from "../DocsCrawler";
|
||||
import { PageData } from "./DocsCrawler";
|
||||
|
||||
export default class CheerioCrawler {
|
||||
private readonly IGNORE_PATHS_ENDING_IN = [
|
||||
|
|
@ -21,23 +21,18 @@ export default class CheerioCrawler {
|
|||
constructor(
|
||||
private readonly startUrl: URL,
|
||||
private readonly maxRequestsPerCrawl: number,
|
||||
private readonly maxDepth: number,
|
||||
) {}
|
||||
|
||||
async *crawl(): AsyncGenerator<PageData> {
|
||||
yield* this.crawlPage(this.startUrl);
|
||||
}
|
||||
|
||||
private async *crawlPage(
|
||||
url: URL,
|
||||
maxDepth: number = 3,
|
||||
): AsyncGenerator<PageData> {
|
||||
let currentPageCount = 0;
|
||||
console.log(
|
||||
`[${
|
||||
(this.constructor as any).name
|
||||
}] Starting crawl from: ${url} - Max Depth: ${maxDepth}`,
|
||||
}] Starting crawl from: ${this.startUrl} - Max Depth: ${this.maxDepth}`,
|
||||
);
|
||||
|
||||
const { baseUrl, basePath } = this.splitUrl(url);
|
||||
const { baseUrl, basePath } = this.splitUrl(this.startUrl);
|
||||
|
||||
let paths: { path: string; depth: number }[] = [
|
||||
{ path: basePath, depth: 0 },
|
||||
|
|
@ -63,11 +58,16 @@ export default class CheerioCrawler {
|
|||
path,
|
||||
depth,
|
||||
} of results) {
|
||||
if (html !== "" && depth <= maxDepth) {
|
||||
yield { url: url.toString(), path, content: html };
|
||||
if (html !== "" && depth <= this.maxDepth) {
|
||||
yield { url: this.startUrl.toString(), path, content: html };
|
||||
currentPageCount++;
|
||||
if (currentPageCount >= this.maxRequestsPerCrawl) {
|
||||
console.log("Crawl completed - max requests reached");
|
||||
return;
|
||||
}
|
||||
}
|
||||
|
||||
if (depth < maxDepth) {
|
||||
if (depth < this.maxDepth) {
|
||||
for (let link of linksArray) {
|
||||
if (!paths.some((p) => p.path === link)) {
|
||||
paths.push({ path: link, depth: depth + 1 });
|
||||
|
|
|
|||
|
|
@ -13,7 +13,7 @@ import {
|
|||
getChromiumPath,
|
||||
getContinueUtilsPath,
|
||||
} from "../../../util/paths";
|
||||
import { PageData } from "../DocsCrawler";
|
||||
import { PageData } from "./DocsCrawler";
|
||||
|
||||
export class ChromiumCrawler {
|
||||
private readonly LINK_GROUP_SIZE = 2;
|
||||
|
|
@ -22,6 +22,7 @@ export class ChromiumCrawler {
|
|||
constructor(
|
||||
private readonly startUrl: URL,
|
||||
private readonly maxRequestsPerCrawl: number,
|
||||
private readonly maxDepth: number,
|
||||
) {}
|
||||
|
||||
static setUseChromiumForDocsCrawling(useChromiumForDocsCrawling: boolean) {
|
||||
|
|
@ -49,7 +50,7 @@ export class ChromiumCrawler {
|
|||
const page = await browser.newPage();
|
||||
|
||||
try {
|
||||
yield* this.crawlSitePages(page, this.startUrl);
|
||||
yield* this.crawlSitePages(page, this.startUrl, 0);
|
||||
} catch (e) {
|
||||
console.debug("Error getting links: ", e);
|
||||
console.debug(
|
||||
|
|
@ -97,6 +98,7 @@ export class ChromiumCrawler {
|
|||
private async *crawlSitePages(
|
||||
page: Page,
|
||||
curUrl: URL,
|
||||
depth: number,
|
||||
visitedLinks: Set<string> = new Set(),
|
||||
): AsyncGenerator<PageData> {
|
||||
const urlStr = curUrl.toString();
|
||||
|
|
@ -124,9 +126,17 @@ export class ChromiumCrawler {
|
|||
|
||||
for (const link of linkGroup) {
|
||||
enqueuedLinkCount++;
|
||||
console.log({ enqueuedLinkCount, url: this.startUrl.toString() });
|
||||
if (enqueuedLinkCount <= this.maxRequestsPerCrawl) {
|
||||
yield* this.crawlSitePages(page, new URL(link), visitedLinks);
|
||||
// console.log({ enqueuedLinkCount, url: this.startUrl.toString() });
|
||||
if (
|
||||
enqueuedLinkCount <= this.maxRequestsPerCrawl &&
|
||||
depth <= this.maxDepth
|
||||
) {
|
||||
yield* this.crawlSitePages(
|
||||
page,
|
||||
new URL(link),
|
||||
depth + 1,
|
||||
visitedLinks,
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -2,10 +2,14 @@ import { URL } from "node:url";
|
|||
|
||||
import { getHeaders } from "../../../continueServer/stubs/headers";
|
||||
import { TRIAL_PROXY_URL } from "../../../control-plane/client";
|
||||
import { PageData } from "../DocsCrawler";
|
||||
import { PageData } from "./DocsCrawler";
|
||||
|
||||
export class DefaultCrawler {
|
||||
constructor(private readonly startUrl: URL) {}
|
||||
constructor(
|
||||
private readonly startUrl: URL,
|
||||
private readonly maxRequestsPerCrawl: number,
|
||||
private readonly maxDepth: number,
|
||||
) {}
|
||||
|
||||
async crawl(): Promise<PageData[]> {
|
||||
const resp = await fetch(new URL("crawl", TRIAL_PROXY_URL).toString(), {
|
||||
|
|
@ -14,7 +18,11 @@ export class DefaultCrawler {
|
|||
"Content-Type": "application/json",
|
||||
...(await getHeaders()),
|
||||
},
|
||||
body: JSON.stringify({ startUrl: this.startUrl.toString() }),
|
||||
body: JSON.stringify({
|
||||
startUrl: this.startUrl.toString(),
|
||||
maxDepth: this.maxDepth,
|
||||
limit: this.maxRequestsPerCrawl,
|
||||
}),
|
||||
});
|
||||
if (!resp.ok) {
|
||||
const text = await resp.text();
|
||||
|
|
|
|||
177
core/indexing/docs/crawlers/DocsCrawler.test.ts
Normal file
177
core/indexing/docs/crawlers/DocsCrawler.test.ts
Normal file
|
|
@ -0,0 +1,177 @@
|
|||
import os from "os";
|
||||
|
||||
import { ContinueConfig } from "../../..";
|
||||
import { testConfigHandler } from "../../../test/fixtures";
|
||||
import FileSystemIde from "../../../util/filesystem";
|
||||
|
||||
import DocsCrawler, {
|
||||
ChromiumInstaller,
|
||||
DocsCrawlerType,
|
||||
type PageData,
|
||||
} from "./DocsCrawler";
|
||||
import { commonDocsSites } from "./crawl-test-cases";
|
||||
|
||||
// Temporary workaround until we have better caching of Chromium
|
||||
// download between test runs
|
||||
const TIMEOUT_MS = 1_000_000_000;
|
||||
|
||||
// Overwrite the Chromium download path to `os.tmpdir()`
|
||||
// so that we don't delete the Chromium install between tests
|
||||
ChromiumInstaller.PCR_CONFIG = { downloadPath: os.tmpdir() };
|
||||
|
||||
describe("DocsCrawler", () => {
|
||||
let config: ContinueConfig;
|
||||
let mockIde: FileSystemIde;
|
||||
let chromiumInstaller: ChromiumInstaller;
|
||||
let docsCrawler: DocsCrawler;
|
||||
|
||||
beforeAll(async () => {
|
||||
const result = await testConfigHandler.loadConfig();
|
||||
config = result.config!;
|
||||
mockIde = new FileSystemIde(process.cwd());
|
||||
chromiumInstaller = new ChromiumInstaller(mockIde, config);
|
||||
docsCrawler = new DocsCrawler(mockIde, config);
|
||||
}, TIMEOUT_MS);
|
||||
|
||||
async function runCrawl(url: string) {
|
||||
const pages: PageData[] = [];
|
||||
const generator = docsCrawler.crawl(new URL(url));
|
||||
let done = false;
|
||||
let crawler: DocsCrawlerType = "default";
|
||||
while (!done) {
|
||||
const result = await generator.next();
|
||||
if (result.done) {
|
||||
done = true;
|
||||
crawler = result.value;
|
||||
} else {
|
||||
pages.push(result.value);
|
||||
}
|
||||
}
|
||||
return {
|
||||
pages,
|
||||
crawler,
|
||||
};
|
||||
}
|
||||
|
||||
describe("GitHub Crawler", () => {
|
||||
const repoUrl =
|
||||
"https://github.com/Patrick-Erichsen/test-github-repo-for-crawling";
|
||||
|
||||
let crawlResults: PageData[];
|
||||
let crawlerUsed: DocsCrawlerType;
|
||||
|
||||
beforeAll(async () => {
|
||||
docsCrawler = new DocsCrawler(mockIde, config, 5, 5, false);
|
||||
const { pages, crawler } = await runCrawl(repoUrl);
|
||||
crawlerUsed = crawler;
|
||||
crawlResults = pages;
|
||||
}, TIMEOUT_MS);
|
||||
|
||||
test(
|
||||
"finds expected markdown files",
|
||||
async () => {
|
||||
expect(
|
||||
crawlResults.some((page) => page.path.endsWith("README.md")),
|
||||
).toBe(true);
|
||||
|
||||
expect(
|
||||
crawlResults.some((page) => page.path.endsWith("docs-depth-1.md")),
|
||||
).toBe(true);
|
||||
},
|
||||
TIMEOUT_MS,
|
||||
);
|
||||
|
||||
test(
|
||||
"html includes the correct content",
|
||||
async () => {
|
||||
const doc = crawlResults.find((page) =>
|
||||
page.path.endsWith("docs-depth-1.md"),
|
||||
);
|
||||
|
||||
expect(doc?.content.includes("Test body")).toBe(true);
|
||||
expect(doc?.content.includes("Test H2 Header")).toBe(true);
|
||||
},
|
||||
TIMEOUT_MS,
|
||||
);
|
||||
|
||||
test(
|
||||
"ignores non-markdown files, e.g. `test.js` at the root",
|
||||
async () => {
|
||||
expect(crawlResults.some((page) => page.path.endsWith("test.js"))).toBe(
|
||||
false,
|
||||
);
|
||||
},
|
||||
TIMEOUT_MS,
|
||||
);
|
||||
});
|
||||
|
||||
// Skipped until we have a better way to cache Chromium installs
|
||||
// between tests and in CI
|
||||
// Run this periodically to make sure it's still working
|
||||
describe.skip("Chromium Crawler", () => {
|
||||
let shouldUseChromiumSpy: any;
|
||||
|
||||
beforeAll(async () => {
|
||||
docsCrawler = new DocsCrawler(mockIde, config, 5, 5, true);
|
||||
await chromiumInstaller.install();
|
||||
shouldUseChromiumSpy = jest
|
||||
.spyOn(docsCrawler as any, "shouldUseChromium")
|
||||
.mockReturnValue(true);
|
||||
}, TIMEOUT_MS);
|
||||
|
||||
afterAll(() => {
|
||||
shouldUseChromiumSpy.mockRestore();
|
||||
}, TIMEOUT_MS);
|
||||
|
||||
commonDocsSites.forEach((url) => {
|
||||
test(
|
||||
`Chromium crawler common site: ${url}`,
|
||||
async () => {
|
||||
const { pages, crawler } = await runCrawl(url);
|
||||
expect(pages.length).toBeGreaterThanOrEqual(1);
|
||||
expect(crawler).toEqual("chromium");
|
||||
},
|
||||
TIMEOUT_MS,
|
||||
);
|
||||
});
|
||||
});
|
||||
|
||||
describe("Default Crawler", () => {
|
||||
beforeAll(() => {
|
||||
docsCrawler = new DocsCrawler(mockIde, config, 2, 2, false);
|
||||
});
|
||||
|
||||
test(
|
||||
"works on static site",
|
||||
async () => {
|
||||
const { pages, crawler } = await runCrawl("https://amplified.dev/");
|
||||
expect(pages.length).toBeGreaterThanOrEqual(1);
|
||||
expect(crawler).toEqual("default");
|
||||
},
|
||||
TIMEOUT_MS,
|
||||
);
|
||||
|
||||
commonDocsSites.forEach((url) => {
|
||||
test(`Default crawler common site: ${url}`, async () => {
|
||||
const { pages, crawler } = await runCrawl(url);
|
||||
expect(pages.length).toBeGreaterThanOrEqual(1);
|
||||
expect(crawler).toEqual("default");
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
describe("Cheerio Crawler", () => {
|
||||
beforeAll(() => {
|
||||
docsCrawler = new DocsCrawler(mockIde, config, 2, 2, true);
|
||||
});
|
||||
test(
|
||||
"works on static site",
|
||||
async () => {
|
||||
const { pages, crawler } = await runCrawl("https://amplified.dev/");
|
||||
expect(pages.length).toBeGreaterThanOrEqual(1);
|
||||
expect(crawler).toEqual("cheerio");
|
||||
},
|
||||
TIMEOUT_MS,
|
||||
);
|
||||
});
|
||||
});
|
||||
119
core/indexing/docs/crawlers/DocsCrawler.ts
Normal file
119
core/indexing/docs/crawlers/DocsCrawler.ts
Normal file
|
|
@ -0,0 +1,119 @@
|
|||
import { URL } from "node:url";
|
||||
|
||||
import { ContinueConfig, IDE } from "../../..";
|
||||
|
||||
import CheerioCrawler from "./CheerioCrawler";
|
||||
import { ChromiumCrawler, ChromiumInstaller } from "./ChromiumCrawler";
|
||||
import { DefaultCrawler } from "./DefaultCrawler";
|
||||
import GitHubCrawler from "./GitHubCrawler";
|
||||
|
||||
export type PageData = {
|
||||
url: string;
|
||||
path: string;
|
||||
content: string;
|
||||
};
|
||||
|
||||
export type DocsCrawlerType = "default" | "cheerio" | "chromium" | "github";
|
||||
|
||||
class DocsCrawler {
|
||||
private readonly GITHUB_HOST = "github.com";
|
||||
private readonly chromiumInstaller: ChromiumInstaller;
|
||||
|
||||
constructor(
|
||||
private readonly ide: IDE,
|
||||
private readonly config: ContinueConfig,
|
||||
private readonly maxDepth: number = 4,
|
||||
private readonly maxRequestsPerCrawl: number = 1000,
|
||||
private readonly useLocalCrawling: boolean = false,
|
||||
private readonly githubToken: string | undefined = undefined,
|
||||
) {
|
||||
this.chromiumInstaller = new ChromiumInstaller(this.ide, this.config);
|
||||
}
|
||||
|
||||
private shouldUseChromium() {
|
||||
return (
|
||||
this.config.experimental?.useChromiumForDocsCrawling &&
|
||||
this.chromiumInstaller.isInstalled()
|
||||
);
|
||||
}
|
||||
|
||||
/*
|
||||
Returns the type of crawler used in the end
|
||||
*/
|
||||
async *crawl(
|
||||
startUrl: URL,
|
||||
): AsyncGenerator<PageData, DocsCrawlerType, undefined> {
|
||||
if (startUrl.host === this.GITHUB_HOST) {
|
||||
yield* new GitHubCrawler(startUrl, this.githubToken).crawl();
|
||||
return "github";
|
||||
}
|
||||
|
||||
if (!this.useLocalCrawling) {
|
||||
try {
|
||||
const pageData = await new DefaultCrawler(
|
||||
startUrl,
|
||||
this.maxRequestsPerCrawl,
|
||||
this.maxDepth,
|
||||
).crawl();
|
||||
if (pageData.length > 0) {
|
||||
yield* pageData;
|
||||
return "default";
|
||||
}
|
||||
} catch (e) {
|
||||
console.error("Default crawler failed, trying backup: ", e);
|
||||
}
|
||||
}
|
||||
|
||||
if (this.shouldUseChromium()) {
|
||||
yield* new ChromiumCrawler(
|
||||
startUrl,
|
||||
this.maxRequestsPerCrawl,
|
||||
this.maxDepth,
|
||||
).crawl();
|
||||
return "chromium";
|
||||
} else {
|
||||
let didCrawlSinglePage = false;
|
||||
|
||||
for await (const pageData of new CheerioCrawler(
|
||||
startUrl,
|
||||
this.maxRequestsPerCrawl,
|
||||
this.maxDepth,
|
||||
).crawl()) {
|
||||
yield pageData;
|
||||
didCrawlSinglePage = true;
|
||||
}
|
||||
|
||||
// We assume that if we failed to crawl a single page,
|
||||
// it was due to an error that using Chromium can resolve
|
||||
const shouldProposeUseChromium =
|
||||
!didCrawlSinglePage &&
|
||||
this.chromiumInstaller.shouldProposeUseChromiumOnCrawlFailure();
|
||||
|
||||
if (shouldProposeUseChromium) {
|
||||
const didInstall =
|
||||
await this.chromiumInstaller.proposeAndAttemptInstall(
|
||||
startUrl.toString(),
|
||||
);
|
||||
|
||||
if (didInstall) {
|
||||
void this.ide.showToast(
|
||||
"info",
|
||||
`Successfully installed Chromium! Retrying crawl of: ${startUrl.toString()}`,
|
||||
);
|
||||
|
||||
yield* new ChromiumCrawler(
|
||||
startUrl,
|
||||
this.maxRequestsPerCrawl,
|
||||
this.maxDepth,
|
||||
).crawl();
|
||||
return "chromium";
|
||||
}
|
||||
}
|
||||
|
||||
return "cheerio";
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
export default DocsCrawler;
|
||||
export { CheerioCrawler, ChromiumCrawler, ChromiumInstaller, GitHubCrawler };
|
||||
|
|
@ -2,13 +2,19 @@ import { URL } from "node:url";
|
|||
|
||||
import { Octokit } from "@octokit/rest";
|
||||
|
||||
import { PageData } from "../DocsCrawler";
|
||||
import { PageData } from "./DocsCrawler";
|
||||
|
||||
class GitHubCrawler {
|
||||
private readonly markdownRegex = new RegExp(/\.(md|mdx)$/);
|
||||
private octokit = new Octokit({ auth: undefined });
|
||||
private octokit: Octokit;
|
||||
private FILES_TO_SKIP = [/TEMPLATE\.md$/, /template\.md$/];
|
||||
|
||||
constructor(private readonly startUrl: URL) {}
|
||||
constructor(
|
||||
private readonly startUrl: URL,
|
||||
private readonly githubToken: string | undefined,
|
||||
) {
|
||||
this.octokit = new Octokit({ auth: this.githubToken });
|
||||
}
|
||||
|
||||
async *crawl(): AsyncGenerator<PageData> {
|
||||
console.debug(
|
||||
|
|
@ -16,14 +22,20 @@ class GitHubCrawler {
|
|||
(this.constructor as any).name
|
||||
}] Crawling GitHub repo: ${this.startUrl.toString()}`,
|
||||
);
|
||||
const urlStr = this.startUrl.toString();
|
||||
const [_, owner, repo] = this.startUrl.pathname.split("/");
|
||||
const branch = await this.getGithubRepoDefaultBranch(owner, repo);
|
||||
|
||||
const paths = await this.getGitHubRepoPaths(owner, repo, branch);
|
||||
|
||||
for await (const path of paths) {
|
||||
if (this.FILES_TO_SKIP.some((skip) => skip.test(path))) {
|
||||
continue;
|
||||
}
|
||||
const content = await this.getGithubRepoFileContent(path, owner, repo);
|
||||
yield { path, url: urlStr, content: content ?? "" };
|
||||
|
||||
const fullUrl = new URL(this.startUrl.toString());
|
||||
fullUrl.pathname += `/tree/${branch}/${path}`;
|
||||
yield { path, url: fullUrl.toString(), content: content ?? "" };
|
||||
}
|
||||
}
|
||||
|
||||
|
|
|
|||
64
core/indexing/docs/crawlers/crawl-test-cases.ts
Normal file
64
core/indexing/docs/crawlers/crawl-test-cases.ts
Normal file
|
|
@ -0,0 +1,64 @@
|
|||
export const commonDocsRepos: string[] = [
|
||||
// "https://github.com/freeCodeCamp/freeCodeCamp",
|
||||
"https://github.com/996icu/996.ICU",
|
||||
// "https://github.com/vuejs/vue",
|
||||
// "https://github.com/tensorflow/tensorflow",
|
||||
"https://github.com/sindresorhus/awesome",
|
||||
"https://github.com/twbs/bootstrap",
|
||||
// "https://github.com/facebook/react",
|
||||
// "https://github.com/torvalds/linux",
|
||||
// "https://github.com/nodejs/node",
|
||||
// "https://github.com/microsoft/vscode",
|
||||
// "https://github.com/ohmyzsh/ohmyzsh",
|
||||
// "https://github.com/kamranahmedse/developer-roadmap",
|
||||
// "https://github.com/electron/electron",
|
||||
// "https://github.com/apache/spark",
|
||||
// "https://github.com/tensorflow/models",
|
||||
// "https://github.com/ansible/ansible",
|
||||
// "https://github.com/airbnb/javascript",
|
||||
// "https://github.com/torvalds/subsurface-for-dirk",
|
||||
// "https://github.com/scikit-learn/scikit-learn",
|
||||
// "https://github.com/denoland/deno",
|
||||
// "https://github.com/donnemartin/system-design-primer",
|
||||
// "https://github.com/reduxjs/redux",
|
||||
// "https://github.com/nvie/gitflow",
|
||||
// "https://github.com/pallets/flask",
|
||||
// "https://github.com/keras-team/keras",
|
||||
// "https://github.com/spring-projects/spring-boot",
|
||||
// "https://github.com/JetBrains/kotlin",
|
||||
// "https://github.com/saltstack/salt",
|
||||
// "https://github.com/apache/kafka",
|
||||
// "https://github.com/moby/moby",
|
||||
// "https://github.com/ansible/ansible-lint",
|
||||
// "https://github.com/angular/angular",
|
||||
// "https://github.com/microsoft/Terminal",
|
||||
// "https://github.com/EbookFoundation/free-programming-books",
|
||||
// "https://github.com/hashicorp/terraform",
|
||||
// "https://github.com/grafana/grafana",
|
||||
// "https://github.com/flutter/flutter",
|
||||
// "https://github.com/kubernetes/kubernetes",
|
||||
"https://github.com/jquery/jquery",
|
||||
// "https://github.com/laravel/laravel",
|
||||
// "https://github.com/mrdoob/three.js",
|
||||
// "https://github.com/prometheus/prometheus",
|
||||
// "https://github.com/nltk/nltk",
|
||||
// "https://github.com/facebook/react-native",
|
||||
// "https://github.com/jekyll/jekyll",
|
||||
// "https://github.com/wesbos/awesome-dev-podcasts",
|
||||
// "https://github.com/expressjs/express",
|
||||
// "https://github.com/elastic/elasticsearch",
|
||||
// "https://github.com/RocketChat/Rocket.Chat",
|
||||
// "https://github.com/open-source-labs/reactime",
|
||||
];
|
||||
|
||||
export const commonDocsSites = [
|
||||
"https://docs.nestjs.com/",
|
||||
"https://go.dev/doc/",
|
||||
"https://clickhouse.com/docs",
|
||||
];
|
||||
|
||||
export const failingDocsSites = [
|
||||
"https://www.tensorflow.org/api_docs",
|
||||
"https://docs.anthropic.com/en/docs",
|
||||
"https://www.rust-lang.org/learn",
|
||||
];
|
||||
|
|
@ -106,9 +106,12 @@ function countTokens(
|
|||
const encoding = encodingForModel(modelName);
|
||||
if (Array.isArray(content)) {
|
||||
return content.reduce((acc, part) => {
|
||||
return acc + part.type === "imageUrl"
|
||||
? countImageTokens(part)
|
||||
: encoding.encode(part.text ?? "", "all", []).length;
|
||||
return (
|
||||
acc +
|
||||
(part.type === "text"
|
||||
? encoding.encode(part.text ?? "", "all", []).length
|
||||
: countImageTokens(part))
|
||||
);
|
||||
}, 0);
|
||||
} else {
|
||||
return encoding.encode(content ?? "", "all", []).length;
|
||||
|
|
@ -335,7 +338,7 @@ function messageIsEmpty(message: ChatMessage): boolean {
|
|||
}
|
||||
if (Array.isArray(message.content)) {
|
||||
return message.content.every(
|
||||
(item) => !item.imageUrl && item.text?.trim() === "",
|
||||
(item) => item.type === "text" && item.text?.trim() === "",
|
||||
);
|
||||
}
|
||||
return false;
|
||||
|
|
|
|||
|
|
@ -1,4 +1,9 @@
|
|||
import { ChatMessage, CompletionOptions, LLMOptions } from "../../index.js";
|
||||
import {
|
||||
ChatMessage,
|
||||
CompletionOptions,
|
||||
LLMOptions,
|
||||
TextMessagePart,
|
||||
} from "../../index.js";
|
||||
import { BaseLLM } from "../index.js";
|
||||
|
||||
class Asksage extends BaseLLM {
|
||||
|
|
@ -14,8 +19,8 @@ class Asksage extends BaseLLM {
|
|||
"gpt4-gov": "gpt4-gov", // Works
|
||||
"gpt-gov": "gpt-gov", // Works
|
||||
"gpt-4o": "gpt-4o", // Works
|
||||
"gpt-4o-mini": "gpt-4o-mini", // Works
|
||||
"gpt4": "gpt4", // Works
|
||||
"gpt-4o-mini": "gpt-4o-mini", // Works
|
||||
gpt4: "gpt4", // Works
|
||||
"gpt4-32k": "gpt4-32k",
|
||||
"gpt-o1": "gpt-o1", // Works
|
||||
"gpt-o1-mini": "gpt-o1-mini", // Works
|
||||
|
|
@ -25,7 +30,7 @@ class Asksage extends BaseLLM {
|
|||
"claude-3-opus-20240229": "claude-3-opus", // Works
|
||||
"claude-3-sonnet-20240229": "claude-3-sonnet", // Works
|
||||
"grok-beta": "xai-grok",
|
||||
"groq-llama33": "groq-llama33",
|
||||
"groq-llama33": "groq-llama33",
|
||||
"groq-70b": "groq-70b",
|
||||
"mistral-large-latest": "mistral-large", // Works
|
||||
"llama3-70b": "llma3", // Works
|
||||
|
|
@ -50,7 +55,10 @@ class Asksage extends BaseLLM {
|
|||
message:
|
||||
typeof message.content === "string"
|
||||
? message.content
|
||||
: message.content.map((part) => part.text).join(""),
|
||||
: message.content
|
||||
.filter((part) => part.type === "text")
|
||||
.map((part) => (part as TextMessagePart).text)
|
||||
.join(""),
|
||||
};
|
||||
}
|
||||
|
||||
|
|
|
|||
|
|
@ -113,10 +113,18 @@ class FreeTrial extends BaseLLM {
|
|||
}
|
||||
|
||||
const parts = message.content.map((part) => {
|
||||
if (part.type === "imageUrl") {
|
||||
return {
|
||||
type: "image_url",
|
||||
image_url: {
|
||||
url: part.imageUrl.url,
|
||||
detail: "low",
|
||||
},
|
||||
};
|
||||
}
|
||||
return {
|
||||
type: part.type,
|
||||
type: "text",
|
||||
text: part.text,
|
||||
image_url: { ...part.imageUrl, detail: "low" },
|
||||
};
|
||||
});
|
||||
return {
|
||||
|
|
|
|||
|
|
@ -1,12 +1,23 @@
|
|||
import { r } from "tar";
|
||||
import {
|
||||
AssistantChatMessage,
|
||||
ChatMessage,
|
||||
CompletionOptions,
|
||||
LLMOptions,
|
||||
MessagePart,
|
||||
ToolCallDelta,
|
||||
} from "../../index.js";
|
||||
import { renderChatMessage } from "../../util/messageContent.js";
|
||||
import { BaseLLM } from "../index.js";
|
||||
import { streamResponse } from "../stream.js";
|
||||
import {
|
||||
GeminiChatContentPart,
|
||||
GeminiChatRequestBody,
|
||||
GeminiChatResponse,
|
||||
GeminiGenerationConfig,
|
||||
GeminiToolFunctionDeclaration,
|
||||
} from "./gemini-types.js";
|
||||
import { findLast } from "../../util/findLast.js";
|
||||
|
||||
class Gemini extends BaseLLM {
|
||||
static providerName = "gemini";
|
||||
|
|
@ -19,7 +30,7 @@ class Gemini extends BaseLLM {
|
|||
};
|
||||
|
||||
// Function to convert completion options to Gemini format
|
||||
public convertArgs(options: CompletionOptions) {
|
||||
public convertArgs(options: CompletionOptions): GeminiGenerationConfig {
|
||||
// should be public for use within VertexAI
|
||||
const finalOptions: any = {}; // Initialize an empty object
|
||||
|
||||
|
|
@ -42,7 +53,7 @@ class Gemini extends BaseLLM {
|
|||
.slice(0, this.maxStopWords ?? Gemini.defaultOptions.maxStopWords);
|
||||
}
|
||||
|
||||
return { generationConfig: finalOptions }; // Wrap options under 'generationConfig'
|
||||
return finalOptions;
|
||||
}
|
||||
|
||||
protected async *_streamComplete(
|
||||
|
|
@ -59,7 +70,7 @@ class Gemini extends BaseLLM {
|
|||
}
|
||||
}
|
||||
|
||||
public removeSystemMessage(messages: ChatMessage[]) {
|
||||
public removeSystemMessage(messages: ChatMessage[]): ChatMessage[] {
|
||||
// should be public for use within VertexAI
|
||||
const msgs = [...messages];
|
||||
|
||||
|
|
@ -92,8 +103,8 @@ class Gemini extends BaseLLM {
|
|||
? this.removeSystemMessage(messages)
|
||||
: messages;
|
||||
|
||||
if (options.model.includes("gemini")) {
|
||||
for await (const message of this.streamChatGemini(
|
||||
if (options.model.includes("bison")) {
|
||||
for await (const message of this.streamChatBison(
|
||||
convertedMsgs,
|
||||
signal,
|
||||
options,
|
||||
|
|
@ -101,7 +112,7 @@ class Gemini extends BaseLLM {
|
|||
yield message;
|
||||
}
|
||||
} else {
|
||||
for await (const message of this.streamChatBison(
|
||||
for await (const message of this.streamChatGemini(
|
||||
convertedMsgs,
|
||||
signal,
|
||||
options,
|
||||
|
|
@ -111,7 +122,7 @@ class Gemini extends BaseLLM {
|
|||
}
|
||||
}
|
||||
|
||||
continuePartToGeminiPart(part: MessagePart) {
|
||||
continuePartToGeminiPart(part: MessagePart): GeminiChatContentPart {
|
||||
return part.type === "text"
|
||||
? {
|
||||
text: part.text,
|
||||
|
|
@ -135,39 +146,129 @@ class Gemini extends BaseLLM {
|
|||
);
|
||||
// This feels hacky to repeat code from above function but was the quickest
|
||||
// way to ensure system message re-formatting isn't done if user has specified v1
|
||||
const apiBase =
|
||||
this.apiBase ||
|
||||
Gemini.defaultOptions?.apiBase ||
|
||||
"https://generativelanguage.googleapis.com/v1beta/"; // Determine if it's a v1 API call based on apiBase
|
||||
const apiBase = this.apiBase || Gemini.defaultOptions.apiBase!; // Determine if it's a v1 API call based on apiBase
|
||||
const isV1API = apiBase.includes("/v1/");
|
||||
|
||||
const contents = messages
|
||||
.map((msg) => {
|
||||
if (msg.role === "system" && !isV1API) {
|
||||
return null; // Don't include system message in contents
|
||||
}
|
||||
if (msg.role === "tool") {
|
||||
return null;
|
||||
}
|
||||
return {
|
||||
role: msg.role === "assistant" ? "model" : "user",
|
||||
parts:
|
||||
typeof msg.content === "string"
|
||||
? [{ text: msg.content }]
|
||||
: msg.content.map(this.continuePartToGeminiPart),
|
||||
};
|
||||
})
|
||||
.filter((c) => c !== null);
|
||||
// Convert chat messages to contents
|
||||
const body: GeminiChatRequestBody = {
|
||||
contents: messages
|
||||
.filter((msg) => !(msg.role === "system" && isV1API))
|
||||
.map((msg) => {
|
||||
if (msg.role === "tool") {
|
||||
let fn_name = "";
|
||||
const lastToolCallMessage = findLast(
|
||||
messages,
|
||||
(msg) => "toolCalls" in msg && msg.toolCalls?.[0]?.function?.name,
|
||||
) as AssistantChatMessage;
|
||||
if (lastToolCallMessage) {
|
||||
fn_name = lastToolCallMessage.toolCalls![0]!.function!.name!;
|
||||
}
|
||||
if (!fn_name) {
|
||||
console.warn(
|
||||
"Sending tool call response for unidentified tool call",
|
||||
);
|
||||
}
|
||||
return {
|
||||
role: "user",
|
||||
parts: [
|
||||
{
|
||||
functionResponse: {
|
||||
name: fn_name || "unknown",
|
||||
response: {
|
||||
output: msg.content, // "output" key is opinionated - not all functions will output objects
|
||||
},
|
||||
},
|
||||
},
|
||||
],
|
||||
};
|
||||
}
|
||||
const assistantMsg = {
|
||||
role:
|
||||
msg.role === "assistant" ? ("model" as const) : ("user" as const),
|
||||
parts:
|
||||
typeof msg.content === "string"
|
||||
? [{ text: msg.content }]
|
||||
: msg.content.map(this.continuePartToGeminiPart),
|
||||
};
|
||||
if (msg.role === "assistant" && msg.toolCalls) {
|
||||
msg.toolCalls.forEach((toolCall) => {
|
||||
if (toolCall.function?.name && toolCall.function?.arguments) {
|
||||
assistantMsg.parts.push({
|
||||
functionCall: {
|
||||
name: toolCall.function.name,
|
||||
args: JSON.parse(toolCall.function.arguments),
|
||||
},
|
||||
});
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
const body = {
|
||||
...this.convertArgs(options),
|
||||
contents,
|
||||
// if this.systemMessage is defined, reformat it for Gemini API
|
||||
...(this.systemMessage &&
|
||||
!isV1API && {
|
||||
systemInstruction: { parts: [{ text: this.systemMessage }] },
|
||||
return assistantMsg;
|
||||
}),
|
||||
};
|
||||
if (options) {
|
||||
body.generationConfig = this.convertArgs(options);
|
||||
}
|
||||
|
||||
// https://ai.google.dev/gemini-api/docs/api-versions
|
||||
if (!isV1API) {
|
||||
if (this.systemMessage) {
|
||||
body.systemInstruction = { parts: [{ text: this.systemMessage }] };
|
||||
}
|
||||
// Convert and add tools if present
|
||||
if (options.tools?.length) {
|
||||
// Choosing to map all tools to the functionDeclarations of one tool
|
||||
// Rather than map each tool to its own tool + functionDeclaration
|
||||
// Same difference
|
||||
const functions: GeminiToolFunctionDeclaration[] = [];
|
||||
options.tools.forEach((tool) => {
|
||||
if (tool.function.description && tool.function.name) {
|
||||
const fn: GeminiToolFunctionDeclaration = {
|
||||
description: tool.function.description,
|
||||
name: tool.function.name,
|
||||
};
|
||||
|
||||
if (
|
||||
tool.function.parameters &&
|
||||
"type" in tool.function.parameters
|
||||
// && typeof tool.function.parameters.type === "string"
|
||||
) {
|
||||
// const paramType = "TYPE_UNSPECIFIED"
|
||||
// | "STRING"
|
||||
// | "NUMBER"
|
||||
// | "INTEGER"
|
||||
// | "BOOLEAN"
|
||||
// | "ARRAY"
|
||||
// | "OBJECT"
|
||||
|
||||
if (tool.function.parameters.type === "object") {
|
||||
// Gemini can't take an empty object
|
||||
// So if empty object param is present just don't add parameters
|
||||
if (
|
||||
JSON.stringify(tool.function.parameters.properties) === "{}"
|
||||
) {
|
||||
functions.push(fn);
|
||||
return;
|
||||
}
|
||||
}
|
||||
fn.parameters = {
|
||||
type: tool.function.parameters.type.toUpperCase(),
|
||||
...tool.function.parameters,
|
||||
};
|
||||
}
|
||||
functions.push(fn);
|
||||
}
|
||||
});
|
||||
if (functions.length) {
|
||||
body.tools = [
|
||||
{
|
||||
functionDeclarations: functions,
|
||||
},
|
||||
];
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
const response = await this.fetch(apiURL, {
|
||||
method: "POST",
|
||||
body: JSON.stringify(body),
|
||||
|
|
@ -192,24 +293,68 @@ class Gemini extends BaseLLM {
|
|||
let foundIncomplete = false;
|
||||
for (let i = 0; i < parts.length; i++) {
|
||||
const part = parts[i];
|
||||
let data;
|
||||
let data: GeminiChatResponse;
|
||||
try {
|
||||
data = JSON.parse(part);
|
||||
data = JSON.parse(part) as GeminiChatResponse;
|
||||
} catch (e) {
|
||||
foundIncomplete = true;
|
||||
continue; // yo!
|
||||
}
|
||||
if (data.error) {
|
||||
|
||||
if ("error" in data) {
|
||||
throw new Error(data.error.message);
|
||||
}
|
||||
|
||||
// Check for existence of each level before accessing the final 'text' property
|
||||
if (data?.candidates?.[0]?.content?.parts?.[0]?.text) {
|
||||
// Incrementally stream the content to make it smoother
|
||||
const content = data.candidates[0].content.parts[0].text;
|
||||
yield {
|
||||
role: "assistant",
|
||||
content,
|
||||
};
|
||||
const content = data?.candidates?.[0]?.content;
|
||||
if (content) {
|
||||
const supportedParts: MessagePart[] = [];
|
||||
const toolCalls: ToolCallDelta[] = [];
|
||||
|
||||
for (const part of content.parts) {
|
||||
if ("text" in part) {
|
||||
supportedParts.push({ type: "text", text: part.text });
|
||||
} else if ("inlineData" in part) {
|
||||
// TODO does this image url conversion actually work?
|
||||
supportedParts.push({
|
||||
type: "imageUrl",
|
||||
imageUrl: {
|
||||
url: `data:image/jpeg;base64,${part.inlineData.data}`,
|
||||
},
|
||||
});
|
||||
} else if ("functionCall" in part) {
|
||||
// Handle function call
|
||||
toolCalls.push({
|
||||
type: "function",
|
||||
id: "", // Not supported by gemini
|
||||
function: {
|
||||
name: part.functionCall.name,
|
||||
arguments:
|
||||
typeof part.functionCall.args === "string"
|
||||
? part.functionCall.args
|
||||
: JSON.stringify(part.functionCall.args),
|
||||
},
|
||||
});
|
||||
} else if ("functionResponse" in part) {
|
||||
// TODO hypothetically order could be off here
|
||||
// Where function response is in the middle of something
|
||||
yield {
|
||||
role: "tool",
|
||||
content: part.functionResponse.response.output as string,
|
||||
toolCallId: part.functionResponse.name,
|
||||
};
|
||||
} else {
|
||||
console.warn("Unsupported gemini part type received", part);
|
||||
}
|
||||
}
|
||||
if (supportedParts.length || toolCalls.length) {
|
||||
// Incrementally stream the content to make it smoother
|
||||
yield {
|
||||
role: "assistant",
|
||||
content: supportedParts.length ? supportedParts : "",
|
||||
...(toolCalls.length ? { toolCalls } : {}),
|
||||
};
|
||||
}
|
||||
} else {
|
||||
// Handle the case where the expected data structure is not found
|
||||
console.warn("Unexpected response format:", data);
|
||||
|
|
|
|||
|
|
@ -1,4 +1,4 @@
|
|||
import { JSONSchema7Object, JSONSchema7Type } from "json-schema";
|
||||
import { JSONSchema7, JSONSchema7Object } from "json-schema";
|
||||
|
||||
import { ChatMessage, CompletionOptions, LLMOptions } from "../../index.js";
|
||||
import { renderChatMessage } from "../../util/messageContent.js";
|
||||
|
|
@ -12,7 +12,7 @@ type OllamaChatMessage = {
|
|||
tool_calls?: {
|
||||
function: {
|
||||
name: string;
|
||||
arguments: Record<string, JSONSchema7Type>;
|
||||
arguments: JSONSchema7Object;
|
||||
};
|
||||
}[];
|
||||
};
|
||||
|
|
@ -119,7 +119,7 @@ interface OllamaTool {
|
|||
function: {
|
||||
name: string;
|
||||
description?: string;
|
||||
parameters?: JSONSchema7Object;
|
||||
parameters?: JSONSchema7;
|
||||
};
|
||||
}
|
||||
|
||||
|
|
@ -273,10 +273,8 @@ class Ollama extends BaseLLM {
|
|||
content: "",
|
||||
};
|
||||
|
||||
if (typeof message.content === "string") {
|
||||
ollamaMessage.content = message.content;
|
||||
} else {
|
||||
ollamaMessage.content = renderChatMessage(message);
|
||||
ollamaMessage.content = renderChatMessage(message);
|
||||
if (Array.isArray(message.content)) {
|
||||
const images: string[] = [];
|
||||
message.content.forEach((part) => {
|
||||
if (part.type === "imageUrl" && part.imageUrl) {
|
||||
|
|
|
|||
|
|
@ -124,7 +124,7 @@ class VertexAI extends BaseLLM {
|
|||
}
|
||||
|
||||
for await (const value of streamSse(response)) {
|
||||
if (value.type == "message_start") {
|
||||
if (value.type === "message_start") {
|
||||
console.log(value);
|
||||
}
|
||||
if (value.delta?.text) {
|
||||
|
|
@ -389,11 +389,11 @@ class VertexAI extends BaseLLM {
|
|||
const convertedMsgs = isV1API
|
||||
? this.geminiInstance.removeSystemMessage(messages)
|
||||
: messages;
|
||||
if (this.vertexProvider == "gemini") {
|
||||
if (this.vertexProvider === "gemini") {
|
||||
yield* this.streamChatGemini(convertedMsgs, options);
|
||||
} else if (this.vertexProvider == "mistral") {
|
||||
} else if (this.vertexProvider === "mistral") {
|
||||
yield* this.StreamChatMistral(messages, options);
|
||||
} else if (this.vertexProvider == "anthropic") {
|
||||
} else if (this.vertexProvider === "anthropic") {
|
||||
yield* this.StreamChatAnthropic(messages, options);
|
||||
} else {
|
||||
if (options.model.includes("bison")) {
|
||||
|
|
|
|||
|
|
@ -95,15 +95,16 @@ class WatsonX extends BaseLLM {
|
|||
}
|
||||
|
||||
const parts = message.content.map((part) => {
|
||||
const msg: any = {
|
||||
type: part.type,
|
||||
if (part.type === "imageUrl") {
|
||||
return {
|
||||
type: "image_url",
|
||||
image_url: { ...part.imageUrl, detail: "low" },
|
||||
};
|
||||
}
|
||||
return {
|
||||
type: "text",
|
||||
text: part.text,
|
||||
};
|
||||
if (part.type === "imageUrl") {
|
||||
msg.image_url = { ...part.imageUrl, detail: "low" };
|
||||
msg.type = "image_url";
|
||||
}
|
||||
return msg;
|
||||
});
|
||||
return {
|
||||
...message,
|
||||
|
|
|
|||
268
core/llm/llms/gemini-types.ts
Normal file
268
core/llm/llms/gemini-types.ts
Normal file
|
|
@ -0,0 +1,268 @@
|
|||
import { JSONSchema7Object } from "json-schema";
|
||||
|
||||
// https://ai.google.dev/api/generate-content
|
||||
export interface GeminiGenerationConfig {
|
||||
stopSequences?: string[];
|
||||
responseMimeType?: string;
|
||||
candidateCount?: number;
|
||||
maxOutputTokens?: number;
|
||||
temperature?: number;
|
||||
topP?: number;
|
||||
topK?: number;
|
||||
presencePenalty?: number;
|
||||
frequencyPenalty?: number;
|
||||
responseLogprobs?: boolean;
|
||||
logprobs?: number;
|
||||
// responseSchema?: object; // https://ai.google.dev/api/caching#Schema
|
||||
}
|
||||
|
||||
export interface GeminiFunctionSchema {
|
||||
type:
|
||||
| "TYPE_UNSPECIFIED"
|
||||
| "STRING"
|
||||
| "NUMBER"
|
||||
| "INTEGER"
|
||||
| "BOOLEAN"
|
||||
| "ARRAY"
|
||||
| "OBJECT";
|
||||
format?: string;
|
||||
description?: string;
|
||||
nullable?: boolean;
|
||||
enum?: string[];
|
||||
maxItems?: string;
|
||||
minItems?: string;
|
||||
properties?: Record<string, GeminiFunctionSchema>;
|
||||
required?: string[];
|
||||
items?: GeminiFunctionSchema;
|
||||
}
|
||||
|
||||
export type GeminiChatContentPart =
|
||||
| {
|
||||
text: string;
|
||||
}
|
||||
| {
|
||||
inlineData: {
|
||||
mimeType: string;
|
||||
data: string;
|
||||
};
|
||||
}
|
||||
| {
|
||||
functionCall: {
|
||||
name: string;
|
||||
args: JSONSchema7Object;
|
||||
};
|
||||
}
|
||||
| {
|
||||
functionResponse: {
|
||||
name: string;
|
||||
response: JSONSchema7Object;
|
||||
};
|
||||
}
|
||||
| {
|
||||
fileData: {
|
||||
fileUri: string;
|
||||
mimeType: string; // See possible values here: https://cloud.google.com/vertex-ai/generative-ai/docs/model-reference/inference#filedata
|
||||
};
|
||||
}
|
||||
| {
|
||||
executableCode: {
|
||||
language: "PYTHON" | "LANGUAGE_UNSPECIFIED";
|
||||
code: string;
|
||||
};
|
||||
}
|
||||
| {
|
||||
codeExecutionResult: {
|
||||
outcome:
|
||||
| "OUTCOME_UNSPECIFIED"
|
||||
| "OUTCOME_OK"
|
||||
| "OUTCOME_FAILED"
|
||||
| "OUTCOME_DEADLINE_EXCEEDED";
|
||||
output: string;
|
||||
};
|
||||
};
|
||||
export interface GeminiChatContent {
|
||||
role?: "user" | "model";
|
||||
parts: GeminiChatContentPart[];
|
||||
}
|
||||
|
||||
export interface GeminiToolFunctionDeclaration {
|
||||
name: string;
|
||||
description: string;
|
||||
parameters?: GeminiFunctionSchema;
|
||||
}
|
||||
export interface GeminiTool {
|
||||
functionDeclarations?: GeminiToolFunctionDeclaration[];
|
||||
googleSearchRetrieval?: {
|
||||
dynamicRetrievalConfig: {
|
||||
mode?: "MODE_DYNAMIC" | "MODE_UNSPECIFIED";
|
||||
dynamicThreshold?: number;
|
||||
};
|
||||
};
|
||||
codeExecution?: {};
|
||||
}
|
||||
|
||||
export interface GeminiToolConfig {
|
||||
functionCallingConfig?: {
|
||||
mode?: "NONE" | "ANY" | "AUTO";
|
||||
allowedFunctionNames?: string[];
|
||||
};
|
||||
}
|
||||
|
||||
// https://ai.google.dev/api/generate-content#request-body
|
||||
export interface GeminiChatRequestBody {
|
||||
contents: GeminiChatContent[];
|
||||
tools?: GeminiTool[];
|
||||
toolConfig?: GeminiToolConfig;
|
||||
systemInstruction?: GeminiChatContent;
|
||||
generationConfig?: GeminiGenerationConfig;
|
||||
// cachedContent?: string;
|
||||
}
|
||||
|
||||
export interface GeminiChatResponseSuccess {
|
||||
candidates: Candidate[];
|
||||
promptFeedback: PromptFeedback;
|
||||
usageMetadata: UsageMetadata;
|
||||
}
|
||||
|
||||
export interface GeminiChatResponseError {
|
||||
error: {
|
||||
message: string;
|
||||
};
|
||||
}
|
||||
|
||||
export type GeminiChatResponse =
|
||||
| GeminiChatResponseError
|
||||
| GeminiChatResponseSuccess;
|
||||
|
||||
interface PromptFeedback {
|
||||
blockReason?: BlockReason;
|
||||
safetyRatings: SafetyRating[];
|
||||
}
|
||||
|
||||
enum BlockReason {
|
||||
BLOCK_REASON_UNSPECIFIED = "BLOCK_REASON_UNSPECIFIED",
|
||||
SAFETY = "SAFETY",
|
||||
OTHER = "OTHER",
|
||||
BLOCKLIST = "BLOCKLIST",
|
||||
PROHIBITED_CONTENT = "PROHIBITED_CONTENT",
|
||||
}
|
||||
|
||||
interface SafetyRating {
|
||||
harmCategory: HarmCategory;
|
||||
harmProbability: HarmProbability;
|
||||
blocked: boolean;
|
||||
}
|
||||
|
||||
enum HarmCategory {
|
||||
HARM_CATEGORY_UNSPECIFIED = "HARM_CATEGORY_UNSPECIFIED",
|
||||
HARM_CATEGORY_DEROGATORY = "HARM_CATEGORY_DEROGATORY",
|
||||
HARM_CATEGORY_TOXICITY = "HARM_CATEGORY_TOXICITY",
|
||||
HARM_CATEGORY_VIOLENCE = "HARM_CATEGORY_VIOLENCE",
|
||||
HARM_CATEGORY_SEXUAL = "HARM_CATEGORY_SEXUAL",
|
||||
HARM_CATEGORY_MEDICAL = "HARM_CATEGORY_MEDICAL",
|
||||
HARM_CATEGORY_DANGEROUS = "HARM_CATEGORY_DANGEROUS",
|
||||
HARM_CATEGORY_HARASSMENT = "HARM_CATEGORY_HARASSMENT",
|
||||
HARM_CATEGORY_HATE_SPEECH = "HARM_CATEGORY_HATE_SPEECH",
|
||||
HARM_CATEGORY_SEXUALLY_EXPLICIT = "HARM_CATEGORY_SEXUALLY_EXPLICIT",
|
||||
HARM_CATEGORY_DANGEROUS_CONTENT = "HARM_CATEGORY_DANGEROUS_CONTENT",
|
||||
HARM_CATEGORY_CIVIC_INTEGRITY = "HARM_CATEGORY_CIVIC_INTEGRITY",
|
||||
}
|
||||
|
||||
enum HarmProbability {
|
||||
HARM_PROBABILITY_UNSPECIFIED = "HARM_PROBABILITY_UNSPECIFIED",
|
||||
NEGLIGIBLE = "NEGLIGIBLE",
|
||||
LOW = "LOW",
|
||||
MEDIUM = "MEDIUM",
|
||||
HIGH = "HIGH",
|
||||
}
|
||||
|
||||
interface UsageMetadata {
|
||||
promptTokenCount: number;
|
||||
cachedContentTokenCount: number;
|
||||
candidatesTokenCount: number;
|
||||
totalTokenCount: number;
|
||||
}
|
||||
|
||||
interface Candidate {
|
||||
content: GeminiChatContent;
|
||||
finishReason: FinishReason;
|
||||
safetyRatings: SafetyRating[];
|
||||
tokenCount: number;
|
||||
groundingAttribution?: GroundingAttribution;
|
||||
groundingMetadata?: GroundingMetadata;
|
||||
avgLogprobs?: number;
|
||||
logprobs?: LogprobsResult;
|
||||
index: number;
|
||||
}
|
||||
|
||||
enum FinishReason {
|
||||
FINISH_REASON_UNSPECIFIED = "FINISH_REASON_UNSPECIFIED",
|
||||
STOP = "STOP",
|
||||
MAX_TOKENS = "MAX_TOKENS",
|
||||
SAFETY = "SAFETY",
|
||||
RECITATION = "RECITATION",
|
||||
LANGUAGE = "LANGUAGE",
|
||||
OTHER = "OTHER",
|
||||
BLOCKLIST = "BLOCKLIST",
|
||||
PROHIBITED_CONTENT = "PROHIBITED_CONTENT",
|
||||
SPII = "SPII",
|
||||
MALFORMED_FUNCTION_CALL = "MALFORMED_FUNCTION_CALL",
|
||||
}
|
||||
|
||||
interface GroundingAttribution {
|
||||
attributionSourceId: AttributionSourceId;
|
||||
groundingSourceContent: string;
|
||||
}
|
||||
|
||||
interface AttributionSourceId {
|
||||
groundingPassage?: GroundingPassageId;
|
||||
semanticRetrieverChunk?: SemanticRetrieverChunk;
|
||||
}
|
||||
|
||||
interface GroundingPassageId {
|
||||
passageId: string;
|
||||
partIndex: number;
|
||||
}
|
||||
|
||||
interface SemanticRetrieverChunk {
|
||||
source: string;
|
||||
chunk: string;
|
||||
}
|
||||
|
||||
interface GroundingMetadata {
|
||||
groundingSupport?: GroundingSupport[];
|
||||
webSearchQueries?: string[];
|
||||
searchEntryPoint?: SearchEntryPoint;
|
||||
retrievalMetadata?: RetrievalMetadata;
|
||||
}
|
||||
|
||||
interface SearchEntryPoint {
|
||||
renderedContent?: string;
|
||||
sdkBlob?: string;
|
||||
}
|
||||
|
||||
interface RetrievalMetadata {
|
||||
googleSearchDynamicRetrievalScore?: number;
|
||||
}
|
||||
|
||||
interface GroundingSupport {
|
||||
groundingChunkIndices: number[];
|
||||
confidenceScores: number[];
|
||||
segment: Segment;
|
||||
}
|
||||
|
||||
interface Segment {
|
||||
partIndex: number;
|
||||
startIndex: number;
|
||||
endIndex: number;
|
||||
text: string;
|
||||
}
|
||||
|
||||
interface LogprobsResult {
|
||||
topCandidates: TopCandidates[];
|
||||
chosenCandidates: Candidate[];
|
||||
}
|
||||
|
||||
interface TopCandidates {
|
||||
candidates: Candidate[];
|
||||
}
|
||||
|
|
@ -1,13 +1,21 @@
|
|||
import { FimCreateParamsStreaming } from "@continuedev/openai-adapters/dist/apis/base";
|
||||
import {
|
||||
Chat,
|
||||
ChatCompletion,
|
||||
ChatCompletionAssistantMessageParam,
|
||||
ChatCompletionChunk,
|
||||
ChatCompletionCreateParams,
|
||||
ChatCompletionMessageParam,
|
||||
ChatCompletionUserMessageParam,
|
||||
CompletionCreateParams,
|
||||
} from "openai/resources/index";
|
||||
|
||||
import { ChatMessage, CompletionOptions } from "..";
|
||||
import {
|
||||
ChatMessage,
|
||||
CompletionOptions,
|
||||
MessageContent,
|
||||
TextMessagePart,
|
||||
} from "..";
|
||||
|
||||
export function toChatMessage(
|
||||
message: ChatMessage,
|
||||
|
|
@ -26,43 +34,55 @@ export function toChatMessage(
|
|||
};
|
||||
}
|
||||
|
||||
let msg: ChatCompletionMessageParam = {
|
||||
role: message.role,
|
||||
content:
|
||||
typeof message.content === "string"
|
||||
? message.content || " " // LM Studio (and other providers) don't accept empty content
|
||||
: !message.content.some((item) => item.type !== "text")
|
||||
? // If no multi-media is in the message, just send as text
|
||||
if (message.role === "assistant") {
|
||||
const msg: ChatCompletionAssistantMessageParam = {
|
||||
role: "assistant",
|
||||
content:
|
||||
typeof message.content === "string"
|
||||
? message.content || " " // LM Studio (and other providers) don't accept empty content
|
||||
: message.content
|
||||
.filter((part) => part.type === "text")
|
||||
.map((part) => part as TextMessagePart), // can remove with newer typescript version
|
||||
};
|
||||
|
||||
if (message.toolCalls) {
|
||||
msg.tool_calls = message.toolCalls.map((toolCall) => ({
|
||||
id: toolCall.id!,
|
||||
type: toolCall.type!,
|
||||
function: {
|
||||
name: toolCall.function?.name!,
|
||||
arguments: toolCall.function?.arguments!,
|
||||
},
|
||||
}));
|
||||
}
|
||||
return msg;
|
||||
} else {
|
||||
return {
|
||||
role: "user",
|
||||
content:
|
||||
typeof message.content === "string"
|
||||
? message.content || " " // LM Studio (and other providers) don't accept empty content
|
||||
: // If no multi-media is in the message, just send as text
|
||||
// for compatibility with OpenAI-"compatible" servers
|
||||
// that don't support multi-media format
|
||||
message.content.map((item) => item.text).join("") || " "
|
||||
: message.content.map((part) => {
|
||||
const msg: any = {
|
||||
type: part.type,
|
||||
text: part.text,
|
||||
};
|
||||
if (part.type === "imageUrl") {
|
||||
msg.image_url = { ...part.imageUrl, detail: "auto" };
|
||||
msg.type = "image_url";
|
||||
}
|
||||
return msg;
|
||||
}),
|
||||
};
|
||||
if (
|
||||
msg.role === "assistant" &&
|
||||
message.role === "assistant" &&
|
||||
message.toolCalls
|
||||
) {
|
||||
msg.tool_calls = message.toolCalls.map((toolCall) => ({
|
||||
id: toolCall.id!,
|
||||
type: toolCall.type!,
|
||||
function: {
|
||||
name: toolCall.function?.name!,
|
||||
arguments: toolCall.function?.arguments!,
|
||||
},
|
||||
}));
|
||||
message.content.some((item) => item.type !== "text")
|
||||
? message.content
|
||||
.map((item) => (item as TextMessagePart).text)
|
||||
.join("") || " "
|
||||
: message.content.map((part) => {
|
||||
if (part.type === "imageUrl") {
|
||||
return {
|
||||
type: "image_url" as const,
|
||||
image_url: {
|
||||
url: part.imageUrl.url,
|
||||
detail: "auto" as const,
|
||||
},
|
||||
};
|
||||
}
|
||||
return part;
|
||||
}),
|
||||
};
|
||||
}
|
||||
return msg;
|
||||
}
|
||||
|
||||
export function toChatBody(
|
||||
|
|
|
|||
|
|
@ -17,6 +17,10 @@ export const PROVIDER_TOOL_SUPPORT: Record<
|
|||
return true;
|
||||
}
|
||||
},
|
||||
gemini: (model) => {
|
||||
// All gemini models support function calling
|
||||
return model.toLowerCase().includes("gemini");
|
||||
},
|
||||
// https://ollama.com/search?c=tools
|
||||
ollama: (model) => {
|
||||
if (
|
||||
|
|
|
|||
|
|
@ -1,6 +1,3 @@
|
|||
import { AutocompleteInput } from "../autocomplete/util/types";
|
||||
import { ProfileDescription } from "../config/ConfigHandler";
|
||||
|
||||
import { ConfigResult } from "@continuedev/config-yaml";
|
||||
import type {
|
||||
BrowserSerializedContinueConfig,
|
||||
|
|
@ -15,6 +12,7 @@ import type {
|
|||
LLMFullCompletionOptions,
|
||||
ModelDescription,
|
||||
ModelRoles,
|
||||
PromptLog,
|
||||
RangeInFile,
|
||||
SerializedContinueConfig,
|
||||
Session,
|
||||
|
|
@ -22,27 +20,8 @@ import type {
|
|||
SiteIndexingConfig,
|
||||
ToolCall,
|
||||
} from "../";
|
||||
|
||||
export type ProtocolGeneratorYield<T> = {
|
||||
done?: boolean;
|
||||
content: T;
|
||||
};
|
||||
export type ProtocolGeneratorType<Y> = AsyncGenerator<
|
||||
ProtocolGeneratorYield<Y>
|
||||
>;
|
||||
|
||||
export type AsyncGeneratorYieldType<T> =
|
||||
T extends AsyncGenerator<infer Y, any, any>
|
||||
? Y extends ProtocolGeneratorYield<infer PR>
|
||||
? PR
|
||||
: never
|
||||
: never;
|
||||
// export type AsyncGeneratorReturnType<T> =
|
||||
// T extends AsyncGenerator<any, infer R, any>
|
||||
// ? R extends ProtocolGeneratorYield<infer PR>
|
||||
// ? PR
|
||||
// : never
|
||||
// : never;
|
||||
import { AutocompleteInput } from "../autocomplete/util/types";
|
||||
import { ProfileDescription } from "../config/ConfigHandler";
|
||||
|
||||
export type OnboardingModes =
|
||||
| "Local"
|
||||
|
|
@ -120,7 +99,7 @@ export type ToCoreFromIdeOrWebviewProtocol = {
|
|||
historyIndex: number;
|
||||
selectedCode: RangeInFile[];
|
||||
},
|
||||
ProtocolGeneratorType<string>,
|
||||
AsyncGenerator<string>,
|
||||
];
|
||||
"llm/complete": [
|
||||
{
|
||||
|
|
@ -137,7 +116,7 @@ export type ToCoreFromIdeOrWebviewProtocol = {
|
|||
completionOptions: LLMFullCompletionOptions;
|
||||
title: string;
|
||||
},
|
||||
ProtocolGeneratorType<string>,
|
||||
AsyncGenerator<string>,
|
||||
];
|
||||
"llm/streamChat": [
|
||||
{
|
||||
|
|
@ -145,7 +124,7 @@ export type ToCoreFromIdeOrWebviewProtocol = {
|
|||
completionOptions: LLMFullCompletionOptions;
|
||||
title: string;
|
||||
},
|
||||
ProtocolGeneratorType<ChatMessage>,
|
||||
AsyncGenerator<ChatMessage, PromptLog>,
|
||||
];
|
||||
streamDiffLines: [
|
||||
{
|
||||
|
|
@ -156,7 +135,7 @@ export type ToCoreFromIdeOrWebviewProtocol = {
|
|||
language: string | undefined;
|
||||
modelTitle: string | undefined;
|
||||
},
|
||||
ProtocolGeneratorType<DiffLine>,
|
||||
AsyncGenerator<DiffLine>,
|
||||
];
|
||||
"chatDescriber/describe": [
|
||||
{
|
||||
|
|
|
|||
|
|
@ -66,6 +66,7 @@ export const WEBVIEW_TO_CORE_PASS_THROUGH: (keyof ToCoreFromWebviewProtocol)[] =
|
|||
export const CORE_TO_WEBVIEW_PASS_THROUGH: (keyof ToWebviewFromCoreProtocol)[] =
|
||||
[
|
||||
"configUpdate",
|
||||
"configError",
|
||||
"getDefaultModelTitle",
|
||||
"indexProgress", // Codebase
|
||||
"indexing/statusUpdate", // Docs, etc.
|
||||
|
|
|
|||
|
|
@ -1,17 +1,53 @@
|
|||
import { FromWebviewProtocol } from ".";
|
||||
|
||||
interface ErrorWebviewMessengerResult {
|
||||
done: boolean;
|
||||
export interface ErrorWebviewMessage {
|
||||
status: "error";
|
||||
error: string;
|
||||
done: true;
|
||||
}
|
||||
|
||||
interface SuccessWebviewMessengerResult<T extends keyof FromWebviewProtocol> {
|
||||
done: boolean;
|
||||
export interface SuccessWebviewSingleMessage<T> {
|
||||
done: true;
|
||||
status: "success";
|
||||
content: FromWebviewProtocol[T][1];
|
||||
content: T;
|
||||
}
|
||||
|
||||
export type WebviewMessengerResult<T extends keyof FromWebviewProtocol> =
|
||||
| ErrorWebviewMessengerResult
|
||||
| SuccessWebviewMessengerResult<T>;
|
||||
export type WebviewSingleMessage<T> =
|
||||
| ErrorWebviewMessage
|
||||
| SuccessWebviewSingleMessage<T>;
|
||||
|
||||
export type WebviewSingleProtocolMessage<T extends keyof FromWebviewProtocol> =
|
||||
WebviewSingleMessage<FromWebviewProtocol[T][1]>;
|
||||
|
||||
// Generators
|
||||
export type GeneratorYieldType<T> =
|
||||
T extends AsyncGenerator<infer Yield, any, any> ? Yield : never;
|
||||
export type GeneratorReturnType<T> =
|
||||
T extends AsyncGenerator<any, infer Return, any> ? Return : never;
|
||||
|
||||
type SuccessWebviewGeneratorMessage<T, R> =
|
||||
| {
|
||||
status: "success";
|
||||
done: false;
|
||||
content: T;
|
||||
}
|
||||
| {
|
||||
status: "success";
|
||||
done: true;
|
||||
content: R;
|
||||
};
|
||||
|
||||
export type WebviewGeneratorMessage<T, R> =
|
||||
| SuccessWebviewGeneratorMessage<T, R>
|
||||
| ErrorWebviewMessage;
|
||||
|
||||
export type WebviewProtocolGeneratorMessage<
|
||||
T extends keyof FromWebviewProtocol,
|
||||
> = WebviewGeneratorMessage<
|
||||
GeneratorYieldType<FromWebviewProtocol[T][1]>,
|
||||
GeneratorReturnType<FromWebviewProtocol[T][1]>
|
||||
>;
|
||||
|
||||
export type WebviewMessage<T = unknown, R = unknown> =
|
||||
| WebviewSingleMessage<T>
|
||||
| WebviewGeneratorMessage<T, R>;
|
||||
|
|
|
|||
|
|
@ -13,7 +13,7 @@ export const searchWebTool: Tool = {
|
|||
"Performs a web search, returning top results. This tool should only be called for questions that require external knowledge. Common programming questions do not require web search.",
|
||||
parameters: {
|
||||
type: "object",
|
||||
required: ["query"],
|
||||
required: ["repo_url"],
|
||||
properties: {
|
||||
repo_url: {
|
||||
type: "string",
|
||||
|
|
|
|||
|
|
@ -12,3 +12,14 @@ export function findLastIndex(
|
|||
}
|
||||
return lastIndex;
|
||||
}
|
||||
|
||||
export function findLast<T>(
|
||||
arr: T[],
|
||||
criterion: (item: T) => any,
|
||||
): T | undefined {
|
||||
for (let i = arr.length - 1; i >= 0; i--) {
|
||||
if (criterion(arr[i])) {
|
||||
return arr[i];
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -3,6 +3,7 @@ import {
|
|||
ContextItem,
|
||||
MessageContent,
|
||||
MessagePart,
|
||||
TextMessagePart,
|
||||
} from "../index";
|
||||
|
||||
export function stripImages(messageContent: MessageContent): string {
|
||||
|
|
@ -12,7 +13,7 @@ export function stripImages(messageContent: MessageContent): string {
|
|||
|
||||
return messageContent
|
||||
.filter((part) => part.type === "text")
|
||||
.map((part) => part.text)
|
||||
.map((part) => (part as TextMessagePart).text)
|
||||
.join("\n");
|
||||
}
|
||||
|
||||
|
|
|
|||
|
|
@ -1,18 +1,28 @@
|
|||
---
|
||||
description: Learn how to access and search your project's documentation directly within Continue
|
||||
keywords: [documentation, indexing, context provider, embeddings, docs]
|
||||
keywords:
|
||||
[
|
||||
documentation,
|
||||
indexing,
|
||||
context provider,
|
||||
embeddings,
|
||||
docs,
|
||||
embedder,
|
||||
embeddings provider,
|
||||
documentation,
|
||||
]
|
||||
toc_max_heading_level: 5
|
||||
---
|
||||
|
||||
# @Docs
|
||||
|
||||
The [`@Docs` context provider](customize/context-providers.md#docs) allows you to interact with your documentation directly within Continue. This feature enables you to index any static site or GitHub markdown pages, making it easier to access and utilize your documentation while coding.
|
||||
The [`@Docs` context provider](customize/context-providers.md#docs) allows you to efficiently reference locally-indexed documentation directly within Continue.
|
||||
|
||||
## Enabling the `@Docs` context provider
|
||||
|
||||
To enable the `@Docs` context provider, you need to add it to the list of context providers in your `config.json` file.
|
||||
To enable the `@Docs` context provider, add it to the list of context providers in your `config.json` file.
|
||||
|
||||
```json
|
||||
```json title="config.json"
|
||||
{
|
||||
"contextProviders": [
|
||||
{
|
||||
|
|
@ -24,54 +34,73 @@ To enable the `@Docs` context provider, you need to add it to the list of contex
|
|||
|
||||
## How It Works
|
||||
|
||||
The `@Docs` context provider works by crawling specified documentation sites, generating embeddings, and storing them locally for you. This process allows for quick and efficient access to your documentation content.
|
||||
The `@Docs` context provider works by
|
||||
|
||||
1. We crawl the specified documentation site
|
||||
2. Generate embeddings for the content
|
||||
3. Store the embeddings locally on your machine
|
||||
4. Provide access to the indexed content through the `@Docs` context provider
|
||||
1. Crawling specified documentation sites
|
||||
2. Generating embeddings for the chunked content
|
||||
3. Storing the embeddings locally on your machine
|
||||
4. Embedding chat input to include similar documentation chunks as context
|
||||
|
||||
## Pre-indexed Documentation Sites
|
||||
|
||||
We offer a selection of pre-indexed documentation sites for popular frameworks and libraries. You can view the list of [available pre-indexed sites and request additions here](https://github.com/continuedev/continue/blob/main/core/indexing/docs/preIndexedDocs.ts).
|
||||
In VS Code, Continue offers a selection of pre-indexed documentation sites for popular frameworks and libraries. You can view the list of [available pre-indexed sites and request additions here](https://github.com/continuedev/continue/blob/main/core/indexing/docs/preIndexedDocs.ts).
|
||||
|
||||
Pre-indexed docs are only available in VS Code because the VS Code extension ships with the Transformers.js embedder built in, while Jetbrains currently does not. You can override a pre-indexed doc to index it with your own embeddings provider by adding it to your config (unique by `startUrl`). Otherwise, it will always use Transformers.js for queries.
|
||||
|
||||
## Indexing Your Own Documentation
|
||||
|
||||
### Through the `@Docs` Context Provider
|
||||
|
||||
To add a single documentation site, we recommend using the `@Docs` context provider.
|
||||
To add a single documentation site, we recommend using the **Add Documentation** Form within the GUI. This can be accessed
|
||||
|
||||
1. Type `@Docs` in the chat panel, hit enter
|
||||
2. Type "add" and select the "Add Docs" option
|
||||
3. Enter the required information into the dialog
|
||||
- from the `@Docs` context provider - type `@Docs` in the chat, hit `Enter`, and search for `Add Docs`
|
||||
- from the `More` page (three dots icon) in the `@docs indexes` section
|
||||
the `@Docs` context provider.
|
||||
|
||||
Indexing will begin upon submission.
|
||||
In the **Add Documentation** Form, enter a `Title` and `Start URL` for the site.
|
||||
|
||||
### Through `config.json`
|
||||
- `Title`: The name of the documentation site, used for identification in the UI
|
||||
- `Start URL`: The URL where the indexing process should begin.
|
||||
|
||||
To add multiple documentation sites, we recommend adding them in bulk to your `config.json` file. Indexing will kick off upon file save.
|
||||
Indexing will begin upon submission. Progress can be viewed in the form or later in the `@docs indexes` section of the `More` page.
|
||||
|
||||
The [configuration schema for docs](https://github.com/continuedev/continue/blob/v0.9.212-vscode/extensions/vscode/config_schema.json#L1943-L1973) is as follows:
|
||||
Documentation sources may be suggested based on package files in your repo. This currently works for Python `requirements.txt` files and Node.js (Javascript/Typescript) `package.json` files.
|
||||
|
||||
```json
|
||||
"docs": [
|
||||
- Packages with a valid documentation URL (with a `+` icon) can be clicked to immediately kick off indexing
|
||||
- Packages with partial information (with a pen icon) can be clicked to fill the form with the available information
|
||||
- Note that you can hover over the information icon to see where the package suggestion was found.
|
||||
|
||||

|
||||
|
||||
### Through global configuration
|
||||
|
||||
For bulk documentation site adds or edits, we recommend editing your global configuration file directly. Documentation sites are stored in an array within `docs` in your global configuration, as follows:
|
||||
|
||||
```json title="config.json"
|
||||
{
|
||||
"docs": [
|
||||
{
|
||||
"title": "Continue",
|
||||
"startUrl": "https://docs.continue.dev/intro",
|
||||
"rootUrl": "https://docs.continue.dev",
|
||||
"faviconUrl": "https://docs.continue.dev/favicon.ico",
|
||||
}
|
||||
]
|
||||
"title": "Nest.js",
|
||||
"startUrl": "https://docs.nestjs.com/",
|
||||
"faviconUrl": "https://docs.nestjs.com/favicon.ico"
|
||||
}
|
||||
]
|
||||
}
|
||||
```
|
||||
|
||||
- `title`: The name of the documentation site, used for identification in the UI.
|
||||
- `startUrl`: The URL where the indexing process should begin.
|
||||
- `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.
|
||||
See [the config reference](../../reference) for all documentation site configuration options.
|
||||
|
||||
Indexing will re-sync upon saving the configuration file.
|
||||
|
||||
## Configuration
|
||||
|
||||
As with [@Codebase context provider configuration](https://docs.continue.dev/customize/deep-dives/codebase#configuration), you can adjust the behavior of the docs context provider with the `nRetrieve`, `nFinal`, and `useReranking`
|
||||
### Using Your Embeddings Provider
|
||||
|
||||
If you have set up an [embeddings provider](../model-types/embeddings.md), @docs will use your embeddings provider. Switching embeddings providers will trigger a re-index of all documentation sites in your configuration.
|
||||
|
||||
### Reranking
|
||||
|
||||
As with [@Codebase context provider configuration](./codebase#configuration), you can adjust the reranking behavior of the `@Docs` context provider with the `nRetrieve`, `nFinal`, and `useReranking`.
|
||||
|
||||
```json title="config.json"
|
||||
{
|
||||
|
|
@ -79,20 +108,52 @@ As with [@Codebase context provider configuration](https://docs.continue.dev/cus
|
|||
{
|
||||
"name": "docs",
|
||||
"params": {
|
||||
"nRetrieve": 25,
|
||||
"nFinal": 5,
|
||||
"useReranking": true
|
||||
"nRetrieve": 25, // The number of docs to retreive from the embeddings query
|
||||
"nFinal": 5, // The number of docs chunks to return IF reranking
|
||||
"useReranking": true // use reranking if a reranker is configured (defaults to true)
|
||||
}
|
||||
}
|
||||
]
|
||||
}
|
||||
```
|
||||
|
||||
## Crawling dynamically generated sites with `useChromiumForDocsCrawling`
|
||||
### Github
|
||||
|
||||
By default, we use a lighter weight tool to crawl documentation sites that cannot render sites that are dynamically generated using JavaScript.
|
||||
The Github API rate limits public requests to 60 per hour. If you want to reliably index Github repos, you can add a github token to your config file:
|
||||
|
||||
If you want 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"
|
||||
{
|
||||
"contextProviders": [
|
||||
{
|
||||
"name": "docs",
|
||||
"params": {
|
||||
"githubToken": "github_..."
|
||||
}
|
||||
}
|
||||
]
|
||||
}
|
||||
```
|
||||
|
||||
### Local Crawling
|
||||
|
||||
By default, Continue crawls documentation sites using a specialized crawling service that provides the best experience for most users and documentation sites.
|
||||
|
||||
If your documentation is private, you can skip the default crawler and use a local crawler instead by setting `useLocalCrawling` to `true`.
|
||||
|
||||
```json title="config.json"
|
||||
{
|
||||
"docs": [
|
||||
{
|
||||
"title": "My Private Docs",
|
||||
"startUrl": "http://10.2.1.2/docs",
|
||||
"faviconUrl": "http://10.2.1.2/docs/assets/favicon.ico",
|
||||
"useLocalCrawling": true
|
||||
}
|
||||
]
|
||||
}
|
||||
```
|
||||
|
||||
The default local crawler is a lightweight tool that cannot render sites that are dynamically generated using JavaScript. If your sites need to be rendered, you can enable the experimental `useChromiumForDocsCrawling` feature in your `config.json`. This will download and install Chromium to `~/.continue/.utils`, and use it as the local crawler.
|
||||
|
||||
```json title="config.json"
|
||||
"experimental": {
|
||||
|
|
@ -100,8 +161,118 @@ If you want to crawl a site that is dynamically generated, or you get an error w
|
|||
}
|
||||
```
|
||||
|
||||
## FAQ
|
||||
Further notes:
|
||||
|
||||
### How often is the indexed content updated?
|
||||
- If the site is only locally accessible, the default crawler will fail anyways and fall back to the local crawler. `useLocalCrawling` is especially useful if the URL itself is confidential.
|
||||
- For Github Repos this has no effect because only the Github Crawler will be used, and if the repo is private it can only be accessed with a priveleged Github token anyways.
|
||||
|
||||
Currently we do not automatically re-index your docs. If you would like to force a re-index, you can use the following command: `Continue: Docs Force Re-Index`.
|
||||
## Managing your docs indexes
|
||||
|
||||
You can view indexing statuses and manage your documentation sites from the `@docs indexes` section of the `More` page (three dots)
|
||||
|
||||
- Continue does not automatically re-index your docs. Use `Click to re-index` to trigger a reindex for a specific source
|
||||
- While a site is indexing, click `Cancel indexing` to cancel the process
|
||||
- Failed indexing attempts will show an error status bar and icon
|
||||
- Delete a documentation site from your configuration using the trash icon
|
||||
|
||||

|
||||
|
||||
You can also view the overall status of currently indexing docs from a hideable progress bar at the bottom of the chat page
|
||||

|
||||
|
||||
You can also use the following IDE command to force a re-index of all docs: `Continue: Docs Force Re-Index`.
|
||||
|
||||
## Examples
|
||||
|
||||
### VS Code minimal setup
|
||||
|
||||
The following configuration example works out of the box for VS Code. This uses the built-in embeddings provider with no reranking. Pre-indexed docs will be accessible.
|
||||
|
||||
```json title="config.json"
|
||||
"contextProviders": [
|
||||
{
|
||||
"name": "docs",
|
||||
}
|
||||
],
|
||||
"docs": [
|
||||
{
|
||||
"title": "Nest.js",
|
||||
"startUrl": "https://docs.nestjs.com/",
|
||||
},
|
||||
],
|
||||
```
|
||||
|
||||
### Jetbrains minimal setup
|
||||
|
||||
Here is the equivalent minimal example for Jetbrains, which requires setting up an [embeddings provider](../model-types/embeddings.md). Pre-indexed docs will _not_ be accessible.
|
||||
|
||||
```json title="config.json"
|
||||
"contextProviders": [
|
||||
{
|
||||
"name": "docs",
|
||||
}
|
||||
],
|
||||
"docs": [
|
||||
{
|
||||
"title": "Nest.js",
|
||||
"startUrl": "https://docs.nestjs.com/",
|
||||
},
|
||||
],
|
||||
"embeddingsProvider": {
|
||||
"provider": "lmstudio",
|
||||
"model": "nomic-ai/nomic-embed-text-v1.5-GGUF"
|
||||
},
|
||||
```
|
||||
|
||||
### Full-power setup (VS Code or Jetbrains)
|
||||
|
||||
The following configuration example includes:
|
||||
|
||||
- Examples of both public and private documentation sources
|
||||
- A custom embeddings provider
|
||||
- A reranker model available, with reranking parameters customized
|
||||
- A Github token to enable Github crawling
|
||||
- Chromium enabled as a backup for private documentation
|
||||
|
||||
```json title="config.json"
|
||||
{
|
||||
"contextProviders": [
|
||||
{
|
||||
"name": "docs",
|
||||
"params": {
|
||||
"githubToken": "github_...",
|
||||
"nRetrieve": 25,
|
||||
"nFinal": 5,
|
||||
"useReranking": true
|
||||
}
|
||||
}
|
||||
],
|
||||
"docs": [
|
||||
{
|
||||
"title": "Nest.js",
|
||||
"startUrl": "https://docs.nestjs.com/"
|
||||
},
|
||||
{
|
||||
"title": "My Private Docs",
|
||||
"startUrl": "http://10.2.1.2/docs",
|
||||
"faviconUrl": "http://10.2.1.2/docs/assets/favicon.ico",
|
||||
"maxDepth": 4,
|
||||
"useLocalCrawling": true
|
||||
}
|
||||
],
|
||||
"reranker": {
|
||||
"name": "voyage",
|
||||
"params": {
|
||||
"model": "rerank-2",
|
||||
"apiKey": "<VOYAGE_API_KEY>"
|
||||
}
|
||||
},
|
||||
"embeddingsProvider": {
|
||||
"provider": "lmstudio",
|
||||
"model": "nomic-ai/nomic-embed-text-v1.5-GGUF"
|
||||
},
|
||||
"experimental": {
|
||||
"useChromiumForDocsCrawling": true
|
||||
}
|
||||
}
|
||||
```
|
||||
|
|
|
|||
|
|
@ -234,9 +234,10 @@ List of documentation sites to index.
|
|||
|
||||
- `title` (**required**): Title of the documentation site, displayed in dropdowns, etc.
|
||||
- `startUrl` (**required**): Start page for crawling - usually root or intro page for docs
|
||||
- `rootUrl`: Crawler will only index docs within this domain - pages that contain this URL
|
||||
- `maxDepth`: Maximum depth for crawling. Default `3`
|
||||
<!-- - `rootUrl`: Crawler will only index docs within this domain - pages that contain this URL -->
|
||||
- `maxDepth`: Maximum link depth for crawling. Default `4`
|
||||
- `favicon`: URL for site favicon (default is `/favicon.ico` from `startUrl`).
|
||||
- `useLocalCrawling`: Skip the default crawler and only crawl using a local crawler.
|
||||
|
||||
Example
|
||||
|
||||
|
|
@ -245,7 +246,6 @@ Example
|
|||
{
|
||||
"title": "Continue",
|
||||
"startUrl": "https://docs.continue.dev/intro",
|
||||
"rootUrl": "https://docs.continue.dev",
|
||||
"faviconUrl": "https://docs.continue.dev/favicon.ico",
|
||||
}
|
||||
]
|
||||
|
|
|
|||
|
|
@ -179,8 +179,10 @@ List of documentation sites to index.
|
|||
|
||||
- `name` (**required**): Name of the documentation site, displayed in dropdowns, etc.
|
||||
- `startUrl` (**required**): Start page for crawling - usually root or intro page for docs
|
||||
- `rootUrl`: Crawler will only index docs within this domain - pages that contain this URL
|
||||
<!-- - `rootUrl`: Crawler will only index docs within this domain - pages that contain this URL -->
|
||||
- `favicon`: URL for site favicon (default is `/favicon.ico` from `startUrl`).
|
||||
- `maxDepth`: M
|
||||
- `useLocalCrawling`: Force use of local crawling
|
||||
|
||||
Example
|
||||
|
||||
|
|
@ -188,7 +190,6 @@ Example
|
|||
docs:
|
||||
- name: Continue
|
||||
startUrl: https://docs.continue.dev/intro
|
||||
rootUrl: https://docs.continue.dev
|
||||
favicon: https://docs.continue.dev/favicon.ico
|
||||
```
|
||||
|
||||
|
|
@ -307,7 +308,6 @@ context:
|
|||
- uses: docs
|
||||
with:
|
||||
startUrl: https://docs.example.com/introduction
|
||||
rootUrl: https://docs.example.com
|
||||
maxDepth: 3
|
||||
|
||||
mcpServers:
|
||||
|
|
|
|||
|
|
@ -58,7 +58,6 @@ toc_max_heading_level: 5
|
|||
{
|
||||
"title": "Continue",
|
||||
"startUrl": "https://docs.continue.dev/intro",
|
||||
"rootUrl": "https://docs.continue.dev",
|
||||
"faviconUrl": "https://docs.continue.dev/favicon.ico",
|
||||
}
|
||||
]
|
||||
|
|
@ -66,7 +65,7 @@ toc_max_heading_level: 5
|
|||
|
||||
- `title`: 文档网站的名称,用来在 UI 中进行识别。
|
||||
- `startUrl`: 索引进程开始的 URL 。
|
||||
- `rootUrl`: 文档网站的基本 URL ,用来确定哪个页面索引。
|
||||
<!-- - `rootUrl`: 文档网站的基本 URL ,用来确定哪个页面索引。 -->
|
||||
- `faviconUrl`: 网站 favicon 的 URL ,用来在 UI 中进行视觉识别。
|
||||
|
||||
## 使用 `useChromiumForDocsCrawling` 爬取动态生成的网站
|
||||
|
|
|
|||
|
|
@ -233,8 +233,8 @@ List of documentation sites to index.
|
|||
|
||||
- `title` (**required**): Title of the documentation site, displayed in dropdowns, etc.
|
||||
- `startUrl` (**required**): Start page for crawling - usually root or intro page for docs
|
||||
- `rootUrl`: Crawler will only index docs within this domain - pages that contain this URL
|
||||
- `maxDepth`: Maximum depth for crawling. Default `3`
|
||||
<!-- - `rootUrl`: Crawler will only index docs within this domain - pages that contain this URL -->
|
||||
- `maxDepth`: Maximum link depth for crawling. Default `4`
|
||||
- `favicon`: URL for site favicon (default is `/favicon.ico` from `startUrl`).
|
||||
|
||||
Example
|
||||
|
|
@ -244,7 +244,6 @@ Example
|
|||
{
|
||||
"title": "Continue",
|
||||
"startUrl": "https://docs.continue.dev/intro",
|
||||
"rootUrl": "https://docs.continue.dev",
|
||||
"faviconUrl": "https://docs.continue.dev/favicon.ico",
|
||||
}
|
||||
]
|
||||
|
|
|
|||
BIN
docs/static/img/docs-form.png
vendored
Normal file
BIN
docs/static/img/docs-form.png
vendored
Normal file
Binary file not shown.
|
After Width: | Height: | Size: 62 KiB |
BIN
docs/static/img/docs-indexes.png
vendored
Normal file
BIN
docs/static/img/docs-indexes.png
vendored
Normal file
Binary file not shown.
|
After Width: | Height: | Size: 24 KiB |
BIN
docs/static/img/docs-indexing-peek.png
vendored
Normal file
BIN
docs/static/img/docs-indexing-peek.png
vendored
Normal file
Binary file not shown.
|
After Width: | Height: | Size: 13 KiB |
|
|
@ -79,7 +79,7 @@ fun getContinuePluginService(project: Project?): ContinuePluginService? {
|
|||
fun focusContinueInput(project: Project?) {
|
||||
val continuePluginService = getContinuePluginService(project) ?: return
|
||||
continuePluginService.continuePluginWindow?.content?.components?.get(0)?.requestFocus()
|
||||
continuePluginService.sendToWebview("focusContinueInputWithNewSession", null)
|
||||
continuePluginService.sendToWebview("focusContinueInputWithoutClear", null)
|
||||
|
||||
continuePluginService.ideProtocolClient?.sendHighlightedCode()
|
||||
}
|
||||
|
|
|
|||
|
|
@ -2,13 +2,6 @@ package com.github.continuedev.continueintellijextension.constants
|
|||
|
||||
class MessageTypes {
|
||||
companion object {
|
||||
val generatorTypes = listOf(
|
||||
"llm/streamComplete",
|
||||
"llm/streamChat",
|
||||
"command/run",
|
||||
"streamDiffLines"
|
||||
)
|
||||
|
||||
val ideMessageTypes = listOf(
|
||||
"readRangeInFile",
|
||||
"isTelemetryEnabled",
|
||||
|
|
@ -53,6 +46,7 @@ class MessageTypes {
|
|||
// Note: If updating these values, make a corresponding update in
|
||||
// core/protocol/passThrough.ts
|
||||
val PASS_THROUGH_TO_WEBVIEW = listOf(
|
||||
"configError",
|
||||
"configUpdate",
|
||||
"getDefaultModelTitle",
|
||||
"indexProgress", // Codebase
|
||||
|
|
|
|||
|
|
@ -87,13 +87,9 @@ class CoreMessenger(
|
|||
// Responses for messageId
|
||||
responseListeners[messageId]?.let { listener ->
|
||||
listener(data)
|
||||
if (MessageTypes.generatorTypes.contains(messageType)) {
|
||||
val done = (data as Map<String, Boolean?>)["done"]
|
||||
if (done == true) {
|
||||
responseListeners.remove(messageId)
|
||||
} else {
|
||||
}
|
||||
} else {
|
||||
val done = (data as Map<String, Boolean>)["done"]
|
||||
|
||||
if (done == true) {
|
||||
responseListeners.remove(messageId)
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -55,19 +55,7 @@ class ContinueBrowser(val project: Project, url: String) {
|
|||
|
||||
|
||||
val respond = fun(data: Any?) {
|
||||
// This matches the way that we expect receive messages in IdeMessenger.ts (gui)
|
||||
// and the way they are sent in VS Code (webviewProtocol.ts)
|
||||
var result: Map<String, Any?>? = if (MessageTypes.generatorTypes.contains(messageType)) {
|
||||
data as? Map<String, Any?>
|
||||
} else {
|
||||
mutableMapOf(
|
||||
"status" to "success",
|
||||
"done" to false,
|
||||
"content" to data
|
||||
)
|
||||
}
|
||||
|
||||
sendToWebview(messageType, result, messageId ?: uuid())
|
||||
sendToWebview(messageType, data, messageId ?: uuid())
|
||||
}
|
||||
|
||||
if (PASS_THROUGH_TO_CORE.contains(messageType)) {
|
||||
|
|
|
|||
|
|
@ -2389,7 +2389,7 @@
|
|||
"if": {
|
||||
"properties": {
|
||||
"name": {
|
||||
"enum": ["codebase", "folder", "docs"]
|
||||
"enum": ["codebase", "folder"]
|
||||
}
|
||||
}
|
||||
},
|
||||
|
|
@ -2420,6 +2420,46 @@
|
|||
}
|
||||
}
|
||||
},
|
||||
{
|
||||
"if": {
|
||||
"properties": {
|
||||
"name": {
|
||||
"enum": ["docs"]
|
||||
}
|
||||
}
|
||||
},
|
||||
"then": {
|
||||
"properties": {
|
||||
"params": {
|
||||
"properties": {
|
||||
"nRetrieve": {
|
||||
"title": "N Retrieve",
|
||||
"description": "Number of docs results to initially retrieve from vector database",
|
||||
"default": 50,
|
||||
"type": "integer"
|
||||
},
|
||||
"nFinal": {
|
||||
"title": "N Final",
|
||||
"description": "Final number of docs results to include after re-ranking",
|
||||
"default": 10,
|
||||
"type": "integer"
|
||||
},
|
||||
"useReranking": {
|
||||
"title": "Use Reranking",
|
||||
"description": "Whether to use re-ranking, which will allow initial selection of nRetrieve results, then will use an LLM to select the top nFinal results. Disabling re-ranking will give faster, but less accurate, results.",
|
||||
"default": true,
|
||||
"type": "boolean"
|
||||
},
|
||||
"githubToken": {
|
||||
"type": "string",
|
||||
"title": "Github Token",
|
||||
"description": "Include to crawl Github repositories for documentation"
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
{
|
||||
"if": {
|
||||
"properties": {
|
||||
|
|
@ -2563,17 +2603,17 @@
|
|||
"type": "string",
|
||||
"description": "The starting URL for indexing the documentation"
|
||||
},
|
||||
"rootUrl": {
|
||||
"type": "string",
|
||||
"description": "The root URL of the documentation site"
|
||||
},
|
||||
"maxDepth": {
|
||||
"type": "integer",
|
||||
"description": "The maximum depth to crawl the documentation site"
|
||||
"description": "The maximum link depth when crawling the documentation site"
|
||||
},
|
||||
"faviconUrl": {
|
||||
"type": "string",
|
||||
"description": "The URL path to a favicon for the site - by default, it will be `/favicon.ico` path from the Start URL"
|
||||
},
|
||||
"useLocalCrawling": {
|
||||
"type": "boolean",
|
||||
"description": "Only use local crawling for this documentation site"
|
||||
}
|
||||
},
|
||||
"required": ["title", "startUrl"]
|
||||
|
|
|
|||
|
|
@ -2,7 +2,7 @@
|
|||
"name": "continue",
|
||||
"icon": "media/icon.png",
|
||||
"author": "Continue Dev, Inc",
|
||||
"version": "0.9.252",
|
||||
"version": "0.9.253",
|
||||
"repository": {
|
||||
"type": "git",
|
||||
"url": "https://github.com/continuedev/continue"
|
||||
|
|
|
|||
|
|
@ -1,6 +1,5 @@
|
|||
import { FromWebviewProtocol, ToWebviewProtocol } from "core/protocol";
|
||||
import { Message } from "core/protocol/messenger";
|
||||
import { WebviewMessengerResult } from "core/protocol/util";
|
||||
import { extractMinimalStackTraceInfo } from "core/util/extractMinimalStackTraceInfo";
|
||||
import { Telemetry } from "core/util/posthog";
|
||||
import { v4 as uuidv4 } from "uuid";
|
||||
|
|
@ -11,8 +10,7 @@ import { IMessenger } from "../../../core/protocol/messenger";
|
|||
import { showFreeTrialLoginMessage } from "./util/messages";
|
||||
|
||||
export class VsCodeWebviewProtocol
|
||||
implements IMessenger<FromWebviewProtocol, ToWebviewProtocol>
|
||||
{
|
||||
implements IMessenger<FromWebviewProtocol, ToWebviewProtocol> {
|
||||
listeners = new Map<
|
||||
keyof FromWebviewProtocol,
|
||||
((message: Message) => any)[]
|
||||
|
|
@ -51,34 +49,40 @@ export class VsCodeWebviewProtocol
|
|||
this._webview = webView;
|
||||
this._webviewListener?.dispose();
|
||||
|
||||
this._webviewListener = this._webview.onDidReceiveMessage(async (msg) => {
|
||||
if (!msg.messageType || !msg.messageId) {
|
||||
const handleMessage = async (msg: Message): Promise<void> => {
|
||||
if (!("messageType" in msg) || !("messageId" in msg)) {
|
||||
throw new Error(`Invalid webview protocol msg: ${JSON.stringify(msg)}`);
|
||||
}
|
||||
|
||||
const respond = (message: WebviewMessengerResult<any>) =>
|
||||
const respond = (message: any) =>
|
||||
this.send(msg.messageType, message, msg.messageId);
|
||||
|
||||
const handlers = this.listeners.get(msg.messageType) || [];
|
||||
const handlers =
|
||||
this.listeners.get(msg.messageType as keyof FromWebviewProtocol) || [];
|
||||
for (const handler of handlers) {
|
||||
try {
|
||||
const response = await handler(msg);
|
||||
// For generator types e.g. llm/streamChat
|
||||
if (
|
||||
response &&
|
||||
typeof response[Symbol.asyncIterator] === "function"
|
||||
) {
|
||||
let next = await response.next();
|
||||
while (!next.done) {
|
||||
respond(next.value);
|
||||
respond({
|
||||
done: false,
|
||||
content: next.value,
|
||||
status: "success",
|
||||
});
|
||||
next = await response.next();
|
||||
}
|
||||
respond({
|
||||
done: true,
|
||||
content: next.value?.content,
|
||||
content: next.value,
|
||||
status: "success",
|
||||
});
|
||||
} else {
|
||||
respond({ done: true, content: response ?? {}, status: "success" });
|
||||
respond({ done: true, content: response, status: "success" });
|
||||
}
|
||||
} catch (e: any) {
|
||||
respond({ done: true, error: e.message, status: "error" });
|
||||
|
|
@ -92,7 +96,6 @@ export class VsCodeWebviewProtocol
|
|||
stringified.includes("llm/streamChat") ||
|
||||
stringified.includes("chatDescriber/describe")
|
||||
) {
|
||||
// handle these errors in the GUI
|
||||
return;
|
||||
}
|
||||
|
||||
|
|
@ -111,7 +114,8 @@ export class VsCodeWebviewProtocol
|
|||
message = message.split("\n").filter((l: string) => l !== "")[1];
|
||||
try {
|
||||
message = JSON.parse(message).message;
|
||||
} catch {}
|
||||
} catch {
|
||||
}
|
||||
if (message.includes("exceeded")) {
|
||||
message +=
|
||||
" To keep using Continue, you can set up a local model or use your own API key.";
|
||||
|
|
@ -143,10 +147,14 @@ export class VsCodeWebviewProtocol
|
|||
}
|
||||
}
|
||||
}
|
||||
});
|
||||
};
|
||||
|
||||
this._webviewListener = this._webview.onDidReceiveMessage(handleMessage);
|
||||
}
|
||||
|
||||
constructor(private readonly reloadConfig: () => void) {
|
||||
}
|
||||
|
||||
constructor(private readonly reloadConfig: () => void) {}
|
||||
invoke<T extends keyof FromWebviewProtocol>(
|
||||
messageType: T,
|
||||
data: FromWebviewProtocol[T][0],
|
||||
|
|
|
|||
|
|
@ -47,6 +47,7 @@ function AddDocsDialog() {
|
|||
|
||||
const sortedDocsSuggestions = useMemo(() => {
|
||||
const docsFromConfig = configDocs ?? [];
|
||||
// Don't show suggestions that are already in the config, indexing, and/or pre-indexed
|
||||
const filtered = docsSuggestions.filter((sug) => {
|
||||
const startUrl = sug.details?.docsLink;
|
||||
return (
|
||||
|
|
|
|||
|
|
@ -176,9 +176,23 @@ function DocsIndexingStatus({ docConfig }: IndexingStatusViewerProps) {
|
|||
}[status?.status]}
|
||||
</span>
|
||||
|
||||
<span className="lines lines-1 text-right text-xs text-stone-500">
|
||||
{status?.description}
|
||||
</span>
|
||||
{status?.description === "Github rate limit exceeded" ? (
|
||||
<span
|
||||
className="lines lines-1 cursor-pointer text-right text-xs text-stone-500 underline"
|
||||
onClick={() =>
|
||||
ideMessenger.post(
|
||||
"openUrl",
|
||||
"https://docs.continue.dev/customize/deep-dives/docs#github",
|
||||
)
|
||||
}
|
||||
>
|
||||
{status.description}
|
||||
</span>
|
||||
) : (
|
||||
<span className="lines lines-1 text-right text-xs text-stone-500">
|
||||
{status?.description}
|
||||
</span>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
|
|
|
|||
|
|
@ -6,6 +6,7 @@ import {
|
|||
MessageContent,
|
||||
MessagePart,
|
||||
RangeInFile,
|
||||
TextMessagePart,
|
||||
} from "core";
|
||||
import { stripImages } from "core/util/messageContent";
|
||||
import { IIdeMessenger } from "../../context/IdeMessenger";
|
||||
|
|
@ -65,7 +66,7 @@ async function resolveEditorContent({
|
|||
}
|
||||
|
||||
if (parts[parts.length - 1]?.type === "text") {
|
||||
parts[parts.length - 1].text += "\n" + text;
|
||||
(parts[parts.length - 1] as TextMessagePart).text += "\n" + text;
|
||||
} else {
|
||||
parts.push({ type: "text", text });
|
||||
}
|
||||
|
|
@ -88,7 +89,7 @@ async function resolveEditorContent({
|
|||
contextItem.content +
|
||||
"\n```";
|
||||
if (parts[parts.length - 1]?.type === "text") {
|
||||
parts[parts.length - 1].text += "\n" + text;
|
||||
(parts[parts.length - 1] as TextMessagePart).text += "\n" + text;
|
||||
} else {
|
||||
parts.push({
|
||||
type: "text",
|
||||
|
|
@ -181,9 +182,10 @@ async function resolveEditorContent({
|
|||
|
||||
if (slashCommand) {
|
||||
let lastTextIndex = findLastIndex(parts, (part) => part.type === "text");
|
||||
const lastPart = `${slashCommand} ${parts[lastTextIndex]?.text || ""}`;
|
||||
const lastTextPart = parts[lastTextIndex] as TextMessagePart;
|
||||
const lastPart = `${slashCommand} ${lastTextPart?.text || ""}`;
|
||||
if (parts.length > 0) {
|
||||
parts[lastTextIndex].text = lastPart;
|
||||
lastTextPart.text = lastPart;
|
||||
} else {
|
||||
parts = [{ type: "text", text: lastPart }];
|
||||
}
|
||||
|
|
|
|||
|
|
@ -1,16 +1,19 @@
|
|||
import { ChatMessage, IDE, LLMFullCompletionOptions, PromptLog } from "core";
|
||||
import type { FromWebviewProtocol, ToWebviewProtocol } from "core/protocol";
|
||||
import { WebviewMessengerResult } from "core/protocol/util";
|
||||
import {
|
||||
GeneratorReturnType,
|
||||
GeneratorYieldType,
|
||||
WebviewMessage,
|
||||
WebviewProtocolGeneratorMessage,
|
||||
WebviewSingleMessage,
|
||||
WebviewSingleProtocolMessage,
|
||||
} from "core/protocol/util";
|
||||
import { MessageIde } from "core/protocol/messenger/messageIde";
|
||||
import { Message } from "core/protocol/messenger";
|
||||
import { createContext } from "react";
|
||||
import { v4 as uuidv4 } from "uuid";
|
||||
import "vscode-webview";
|
||||
import { isJetBrains } from "../util";
|
||||
import {
|
||||
AsyncGeneratorYieldType,
|
||||
ProtocolGeneratorYield,
|
||||
} from "core/protocol/core";
|
||||
|
||||
interface vscode {
|
||||
postMessage(message: any): vscode;
|
||||
|
|
@ -35,20 +38,23 @@ export interface IIdeMessenger {
|
|||
request<T extends keyof FromWebviewProtocol>(
|
||||
messageType: T,
|
||||
data: FromWebviewProtocol[T][0],
|
||||
): Promise<WebviewMessengerResult<T>>;
|
||||
): Promise<WebviewSingleProtocolMessage<T>>;
|
||||
|
||||
streamRequest<T extends keyof FromWebviewProtocol>(
|
||||
messageType: T,
|
||||
data: FromWebviewProtocol[T][0],
|
||||
cancelToken?: AbortSignal,
|
||||
): AsyncGenerator<unknown[]>;
|
||||
): AsyncGenerator<
|
||||
GeneratorYieldType<FromWebviewProtocol[T][1]>[],
|
||||
GeneratorReturnType<FromWebviewProtocol[T][1]> | undefined
|
||||
>;
|
||||
|
||||
llmStreamChat(
|
||||
modelTitle: string,
|
||||
cancelToken: AbortSignal | undefined,
|
||||
messages: ChatMessage[],
|
||||
options?: LLMFullCompletionOptions,
|
||||
): AsyncGenerator<ChatMessage[], PromptLog, unknown>;
|
||||
): AsyncGenerator<ChatMessage[], PromptLog | undefined>;
|
||||
|
||||
ide: IDE;
|
||||
}
|
||||
|
|
@ -140,14 +146,14 @@ export class IdeMessenger implements IIdeMessenger {
|
|||
request<T extends keyof FromWebviewProtocol>(
|
||||
messageType: T,
|
||||
data: FromWebviewProtocol[T][0],
|
||||
): Promise<WebviewMessengerResult<T>> {
|
||||
): Promise<WebviewSingleMessage<T>> {
|
||||
const messageId = uuidv4();
|
||||
|
||||
return new Promise((resolve) => {
|
||||
const handler = (event: any) => {
|
||||
if (event.data.messageId === messageId) {
|
||||
window.removeEventListener("message", handler);
|
||||
resolve(event.data.data as WebviewMessengerResult<T>);
|
||||
resolve(event.data.data as WebviewSingleMessage<T>);
|
||||
}
|
||||
};
|
||||
window.addEventListener("message", handler);
|
||||
|
|
@ -168,24 +174,33 @@ export class IdeMessenger implements IIdeMessenger {
|
|||
messageType: T,
|
||||
data: FromWebviewProtocol[T][0],
|
||||
cancelToken?: AbortSignal,
|
||||
): AsyncGenerator<AsyncGeneratorYieldType<FromWebviewProtocol[T][1]>[], any> {
|
||||
type GenYield = AsyncGeneratorYieldType<FromWebviewProtocol[T][1]>;
|
||||
// type GenReturn = AsyncGeneratorReturnType<FromWebviewProtocol[T][1]>;
|
||||
|
||||
): AsyncGenerator<
|
||||
GeneratorYieldType<FromWebviewProtocol[T][1]>[],
|
||||
GeneratorReturnType<FromWebviewProtocol[T][1]> | undefined
|
||||
> {
|
||||
const messageId = uuidv4();
|
||||
|
||||
this.post(messageType, data, messageId);
|
||||
|
||||
const buffer: GenYield[] = [];
|
||||
const buffer: GeneratorYieldType<FromWebviewProtocol[T][1]>[] = [];
|
||||
let index = 0;
|
||||
let done = false;
|
||||
let returnVal = undefined;
|
||||
let returnVal: GeneratorReturnType<FromWebviewProtocol[T][1]> | undefined =
|
||||
undefined;
|
||||
let error: string | null = null;
|
||||
|
||||
// This handler receieves individual WebviewMessengerResults
|
||||
// And pushes them to buffer
|
||||
const handler = (event: {
|
||||
data: Message<ProtocolGeneratorYield<GenYield>>;
|
||||
data: Message<WebviewProtocolGeneratorMessage<T>>;
|
||||
}) => {
|
||||
if (event.data.messageId === messageId) {
|
||||
const responseData = event.data.data;
|
||||
if ("error" in responseData) {
|
||||
error = responseData.error;
|
||||
return;
|
||||
// throw new Error(responseData.error);
|
||||
}
|
||||
if (responseData.done) {
|
||||
window.removeEventListener("message", handler);
|
||||
done = true;
|
||||
|
|
@ -204,6 +219,9 @@ export class IdeMessenger implements IIdeMessenger {
|
|||
|
||||
try {
|
||||
while (!done) {
|
||||
if (error) {
|
||||
throw error;
|
||||
}
|
||||
if (buffer.length > index) {
|
||||
const chunks = buffer.slice(index);
|
||||
index = buffer.length;
|
||||
|
|
@ -217,6 +235,9 @@ export class IdeMessenger implements IIdeMessenger {
|
|||
yield chunks;
|
||||
}
|
||||
|
||||
if (!returnVal) {
|
||||
return undefined;
|
||||
}
|
||||
return returnVal;
|
||||
} catch (e) {
|
||||
throw e;
|
||||
|
|
@ -230,7 +251,7 @@ export class IdeMessenger implements IIdeMessenger {
|
|||
cancelToken: AbortSignal | undefined,
|
||||
messages: ChatMessage[],
|
||||
options: LLMFullCompletionOptions = {},
|
||||
): AsyncGenerator<ChatMessage[], PromptLog> {
|
||||
): AsyncGenerator<ChatMessage[], PromptLog | undefined> {
|
||||
const gen = this.streamRequest(
|
||||
"llm/streamChat",
|
||||
{
|
||||
|
|
@ -246,17 +267,7 @@ export class IdeMessenger implements IIdeMessenger {
|
|||
yield next.value;
|
||||
next = await gen.next();
|
||||
}
|
||||
|
||||
if (!next.done) {
|
||||
throw new Error();
|
||||
}
|
||||
|
||||
return {
|
||||
modelTitle: next.value.content?.modelTitle,
|
||||
prompt: next.value.content?.prompt,
|
||||
completion: next.value.content?.completion,
|
||||
completionOptions: next.value.content?.completionOptions,
|
||||
};
|
||||
return next.value;
|
||||
}
|
||||
}
|
||||
|
||||
|
|
|
|||
|
|
@ -28,12 +28,10 @@ interface SubtextContextProvidersContextType {
|
|||
providerTitle: string | undefined,
|
||||
query: string,
|
||||
) => ContextSubmenuItemWithProvider[];
|
||||
initialLoadComplete: boolean;
|
||||
}
|
||||
|
||||
const initialContextProviders: SubtextContextProvidersContextType = {
|
||||
getSubmenuContextItems: () => [],
|
||||
initialLoadComplete: false,
|
||||
};
|
||||
|
||||
const SubmenuContextProvidersContext =
|
||||
|
|
@ -118,8 +116,7 @@ export const SubmenuContextProvidersProvider = ({
|
|||
};
|
||||
}, [ideMessenger]);
|
||||
|
||||
const [initialLoadComplete, setInitialLoadComplete] = useState(false);
|
||||
const [isLoading, setIsLoading] = useState(false);
|
||||
const providersLoading = useRef(new Set<string>()).current;
|
||||
|
||||
const getSubmenuContextItems = useCallback(
|
||||
(
|
||||
|
|
@ -176,8 +173,8 @@ export const SubmenuContextProvidersProvider = ({
|
|||
};
|
||||
});
|
||||
|
||||
if (fallbackItems.length === 0 && !initialLoadComplete) {
|
||||
return [
|
||||
if (fallbackItems.length === 0) {
|
||||
const loadingFiller = [
|
||||
{
|
||||
id: "loading",
|
||||
title: "Loading...",
|
||||
|
|
@ -185,6 +182,19 @@ export const SubmenuContextProvidersProvider = ({
|
|||
providerTitle: providerTitle || "unknown",
|
||||
},
|
||||
];
|
||||
|
||||
// If getting for all providers
|
||||
if (!providerTitle) {
|
||||
// then show loading if ANY loading
|
||||
if (providersLoading.size > 0) {
|
||||
return loadingFiller;
|
||||
}
|
||||
} else {
|
||||
// Otherwise just check if the provider is loading
|
||||
if (providersLoading.has(providerTitle)) {
|
||||
return loadingFiller;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return fallbackItems;
|
||||
|
|
@ -203,124 +213,124 @@ export const SubmenuContextProvidersProvider = ({
|
|||
return [];
|
||||
}
|
||||
},
|
||||
[fallbackResults, minisearches, initialLoadComplete],
|
||||
[fallbackResults, minisearches],
|
||||
);
|
||||
|
||||
const loadSubmenuItems = useCallback(
|
||||
async (providers: "dependsOnIndexing" | "all" | ContextProviderName[]) => {
|
||||
setIsLoading(true);
|
||||
|
||||
await Promise.allSettled(
|
||||
submenuContextProviders.map(
|
||||
async (description: ContextProviderDescription) => {
|
||||
try {
|
||||
const refreshProvider =
|
||||
providers === "all"
|
||||
? true
|
||||
: providers === "dependsOnIndexing"
|
||||
? description.dependsOnIndexing
|
||||
: providers.includes(description.title);
|
||||
|
||||
if (!refreshProvider) {
|
||||
return;
|
||||
}
|
||||
|
||||
if (description.dependsOnIndexing && disableIndexing) {
|
||||
console.debug(
|
||||
`Skipping ${description.title} provider due to disabled indexing`,
|
||||
);
|
||||
return;
|
||||
}
|
||||
const result = await ideMessenger.request(
|
||||
"context/loadSubmenuItems",
|
||||
{
|
||||
title: description.title,
|
||||
},
|
||||
);
|
||||
|
||||
if (result.status === "error") {
|
||||
throw new Error(result.error);
|
||||
}
|
||||
const submenuItems = result.content;
|
||||
const providerTitle = description.title;
|
||||
|
||||
const itemsWithProvider = submenuItems.map((item) => ({
|
||||
...item,
|
||||
providerTitle,
|
||||
}));
|
||||
|
||||
const minisearch = new MiniSearch<ContextSubmenuItemWithProvider>(
|
||||
{
|
||||
fields: ["title", "description"],
|
||||
storeFields: ["id", "title", "description", "providerTitle"],
|
||||
},
|
||||
);
|
||||
|
||||
minisearch.addAll(
|
||||
submenuItems.map((item) => ({ ...item, providerTitle })),
|
||||
);
|
||||
|
||||
setMinisearches((prev) => ({
|
||||
...prev,
|
||||
[providerTitle]: minisearch,
|
||||
}));
|
||||
|
||||
if (providerTitle === "file") {
|
||||
setFallbackResults((prev) => ({
|
||||
...prev,
|
||||
file: deduplicateArray(
|
||||
[...lastOpenFilesRef.current, ...(prev.file ?? [])],
|
||||
(a, b) => a.id === b.id,
|
||||
),
|
||||
}));
|
||||
} else {
|
||||
setFallbackResults((prev) => ({
|
||||
...prev,
|
||||
[providerTitle]: itemsWithProvider,
|
||||
}));
|
||||
}
|
||||
} catch (error) {
|
||||
console.error(
|
||||
`Error loading items for ${description.title}:`,
|
||||
error,
|
||||
);
|
||||
console.error(
|
||||
"Error details:",
|
||||
JSON.stringify(error, Object.getOwnPropertyNames(error)),
|
||||
);
|
||||
(providers: "dependsOnIndexing" | "all" | ContextProviderName[]) => {
|
||||
submenuContextProviders.forEach(
|
||||
async (description: ContextProviderDescription) => {
|
||||
try {
|
||||
if (providersLoading.has(description.title)) {
|
||||
return;
|
||||
}
|
||||
},
|
||||
),
|
||||
providersLoading.add(description.title);
|
||||
|
||||
const refreshProvider =
|
||||
providers === "all"
|
||||
? true
|
||||
: providers === "dependsOnIndexing"
|
||||
? description.dependsOnIndexing
|
||||
: providers.includes(description.title);
|
||||
|
||||
if (!refreshProvider) {
|
||||
return;
|
||||
}
|
||||
|
||||
if (description.dependsOnIndexing && disableIndexing) {
|
||||
console.debug(
|
||||
`Skipping ${description.title} provider due to disabled indexing`,
|
||||
);
|
||||
return;
|
||||
}
|
||||
const result = await ideMessenger.request(
|
||||
"context/loadSubmenuItems",
|
||||
{
|
||||
title: description.title,
|
||||
},
|
||||
);
|
||||
|
||||
if (result.status === "error") {
|
||||
throw new Error(result.error);
|
||||
}
|
||||
const submenuItems = result.content;
|
||||
const providerTitle = description.title;
|
||||
|
||||
const itemsWithProvider = submenuItems.map((item) => ({
|
||||
...item,
|
||||
providerTitle,
|
||||
}));
|
||||
|
||||
const minisearch = new MiniSearch<ContextSubmenuItemWithProvider>({
|
||||
fields: ["title", "description"],
|
||||
storeFields: ["id", "title", "description", "providerTitle"],
|
||||
});
|
||||
|
||||
minisearch.addAll(
|
||||
submenuItems.map((item) => ({ ...item, providerTitle })),
|
||||
);
|
||||
|
||||
setMinisearches((prev) => ({
|
||||
...prev,
|
||||
[providerTitle]: minisearch,
|
||||
}));
|
||||
|
||||
if (providerTitle === "file") {
|
||||
setFallbackResults((prev) => ({
|
||||
...prev,
|
||||
file: deduplicateArray(
|
||||
[...lastOpenFilesRef.current, ...(prev.file ?? [])],
|
||||
(a, b) => a.id === b.id,
|
||||
),
|
||||
}));
|
||||
} else {
|
||||
setFallbackResults((prev) => ({
|
||||
...prev,
|
||||
[providerTitle]: itemsWithProvider,
|
||||
}));
|
||||
}
|
||||
} catch (error) {
|
||||
console.error(
|
||||
`Error loading items for ${description.title}:`,
|
||||
error,
|
||||
);
|
||||
console.error(
|
||||
"Error details:",
|
||||
JSON.stringify(error, Object.getOwnPropertyNames(error)),
|
||||
);
|
||||
} finally {
|
||||
providersLoading.delete(description.title);
|
||||
}
|
||||
},
|
||||
);
|
||||
setInitialLoadComplete(true);
|
||||
setIsLoading(false);
|
||||
},
|
||||
[submenuContextProviders, disableIndexing],
|
||||
[submenuContextProviders, disableIndexing, providersLoading],
|
||||
);
|
||||
|
||||
useWebviewListener(
|
||||
"refreshSubmenuItems",
|
||||
async (data) => {
|
||||
if (isLoading) {
|
||||
return;
|
||||
}
|
||||
if (data.providers === "all") {
|
||||
setInitialLoadComplete(false);
|
||||
}
|
||||
await loadSubmenuItems(data.providers);
|
||||
loadSubmenuItems(data.providers);
|
||||
},
|
||||
[isLoading, loadSubmenuItems],
|
||||
[loadSubmenuItems],
|
||||
);
|
||||
|
||||
// Reload all submenu items on the initial config load
|
||||
// TODO - could refresh on any change
|
||||
const initialLoad = useRef(false);
|
||||
const config = useAppSelector((store) => store.config.config);
|
||||
useEffect(() => {
|
||||
if (!config?.contextProviders?.length || initialLoad.current) {
|
||||
return;
|
||||
}
|
||||
void loadSubmenuItems("all");
|
||||
}, []);
|
||||
initialLoad.current = true;
|
||||
}, [loadSubmenuItems, config, initialLoad]);
|
||||
|
||||
return (
|
||||
<SubmenuContextProvidersContext.Provider
|
||||
value={{
|
||||
getSubmenuContextItems,
|
||||
initialLoadComplete,
|
||||
}}
|
||||
>
|
||||
{children}
|
||||
|
|
|
|||
|
|
@ -44,6 +44,15 @@ function useSetup() {
|
|||
return;
|
||||
}
|
||||
hasLoadedConfig.current = true;
|
||||
// window.postMessage(
|
||||
// {
|
||||
// messageType: "refreshSubmenuItems",
|
||||
// data: {
|
||||
// providers: "all",
|
||||
// },
|
||||
// },
|
||||
// "*",
|
||||
// );
|
||||
dispatch(setConfigResult(configResult));
|
||||
dispatch(setSelectedProfileId(profileId));
|
||||
|
||||
|
|
|
|||
|
|
@ -332,13 +332,13 @@ export const sessionSlice = createSlice({
|
|||
const historyItem: ChatHistoryItemWithMessageId = {
|
||||
message: {
|
||||
...message,
|
||||
content: renderChatMessage(message),
|
||||
id: uuidv4(),
|
||||
},
|
||||
contextItems: [],
|
||||
};
|
||||
if (message.role === "assistant" && message.toolCalls?.[0]) {
|
||||
const toolCallDelta = message.toolCalls[0];
|
||||
|
||||
if (
|
||||
toolCallDelta.id &&
|
||||
toolCallDelta.function?.arguments &&
|
||||
|
|
@ -356,6 +356,8 @@ export const sessionSlice = createSlice({
|
|||
} else {
|
||||
// Add to the existing message
|
||||
if (message.content) {
|
||||
// Note this only works because new message above
|
||||
// was already rendered from parts to string
|
||||
lastMessage.content += renderChatMessage(message);
|
||||
} else if (
|
||||
message.role === "assistant" &&
|
||||
|
|
|
|||
|
|
@ -96,7 +96,7 @@ export const gatherContext = createAsyncThunk<
|
|||
if (promptPreamble) {
|
||||
if (typeof content === "string") {
|
||||
content = promptPreamble + content;
|
||||
} else {
|
||||
} else if (content[0].type === "text") {
|
||||
content[0].text = promptPreamble + content[0].text;
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -52,13 +52,12 @@ export const streamNormalInput = createAsyncThunk<
|
|||
break;
|
||||
}
|
||||
|
||||
const updates = next.value;
|
||||
dispatch(streamUpdate(updates));
|
||||
dispatch(streamUpdate(next.value));
|
||||
next = await gen.next();
|
||||
}
|
||||
|
||||
// Attach prompt log
|
||||
if (next.done) {
|
||||
if (next.done && next.value) {
|
||||
dispatch(addPromptCompletionPair([next.value]));
|
||||
}
|
||||
|
||||
|
|
|
|||
|
|
@ -1,6 +1,11 @@
|
|||
import { createAsyncThunk, unwrapResult } from "@reduxjs/toolkit";
|
||||
import { JSONContent } from "@tiptap/core";
|
||||
import { InputModifiers, MessageContent, SlashCommandDescription } from "core";
|
||||
import {
|
||||
InputModifiers,
|
||||
MessageContent,
|
||||
SlashCommandDescription,
|
||||
TextMessagePart,
|
||||
} from "core";
|
||||
import { constructMessages } from "core/llm/constructMessages";
|
||||
import { renderChatMessage } from "core/util/messageContent";
|
||||
import posthog from "posthog-js";
|
||||
|
|
@ -28,7 +33,11 @@ const getSlashCommandForInput = (
|
|||
let lastText =
|
||||
typeof input === "string"
|
||||
? input
|
||||
: input.filter((part) => part.type === "text").slice(-1)[0]?.text || "";
|
||||
: (
|
||||
input.filter((part) => part.type === "text").slice(-1)[0] as
|
||||
| TextMessagePart
|
||||
| undefined
|
||||
)?.text || "";
|
||||
|
||||
if (lastText.startsWith("/")) {
|
||||
slashCommandName = lastText.split(" ")[0].substring(1);
|
||||
|
|
|
|||
|
|
@ -57,7 +57,7 @@ export const modelDescriptionSchema = z.object({
|
|||
"azure",
|
||||
"continue-proxy",
|
||||
"nebius",
|
||||
"scaleway"
|
||||
"scaleway",
|
||||
]),
|
||||
model: z.string(),
|
||||
apiKey: z.string().optional(),
|
||||
|
|
@ -202,10 +202,11 @@ export type DevData = z.infer<typeof devDataSchema>;
|
|||
|
||||
export const siteIndexingConfigSchema = z.object({
|
||||
startUrl: z.string(),
|
||||
rootUrl: z.string(),
|
||||
// rootUrl: z.string(),
|
||||
title: z.string(),
|
||||
maxDepth: z.string().optional(),
|
||||
faviconUrl: z.string().optional(),
|
||||
useLocalCrawling: z.boolean().optional(),
|
||||
});
|
||||
|
||||
export const controlPlaneConfigSchema = z.object({
|
||||
|
|
|
|||
Loading…
Add table
Reference in a new issue