Merge branch 'preview' into nate/no-more-undici

This commit is contained in:
Nate Sesti 2024-01-24 20:37:38 -08:00
commit a7a7bf3902
143 changed files with 14639 additions and 13262 deletions

View file

@ -85,6 +85,9 @@ jobs:
run: |
cd extensions/vscode
npm ci
env:
# https://github.com/microsoft/vscode-ripgrep/issues/9#issuecomment-643965333
GITHUB_TOKEN: ${{ secrets.CI_GITHUB_TOKEN }}
- name: Install gui Dependencies
run: |
@ -96,31 +99,22 @@ jobs:
cd core
npm ci --legacy-peer-deps
# 2.5. Pre package and download anything that needs to be built on Apple Silicon
- name: Prepare the extension
run: |
cd extensions/vscode
npm run prepackage
- name: Make the out directory
if: matrix.os == 'macos-latest' && matrix.arch == 'arm64'
# 2.5. Pre package
- name: Make the out/node_modules directory
run: |
cd extensions/vscode
mkdir out
cd out
mkdir node_modules
- name: Download node_modules for esbuild on Apple Silicon
if: matrix.os == 'macos-latest' && matrix.arch == 'arm64'
run: curl -o extensions/vscode/out/node_modules.zip https://continue-server-binaries.s3.us-west-1.amazonaws.com/node_modules.zip
- name: Set var for environment info
shell: pwsh
run: echo "target=${{ matrix.platform }}-${{ matrix.arch }}" >> $env:GITHUB_ENV
- name: Unzip node_modules for esbuild on Apple Silicon
if: matrix.os == 'macos-latest' && matrix.arch == 'arm64'
- name: Prepackage the extension
run: |
cd extensions/vscode/out
unzip node_modules.zip
- name: Remove node_modules.zip for esbuild on Apple Silicon
if: matrix.os == 'macos-latest' && matrix.arch == 'arm64'
run: rm extensions/vscode/out/node_modules.zip
cd extensions/vscode
npm run prepackage -- --target ${{ env.target }}
# 3. Run tests for the extension
@ -140,9 +134,13 @@ jobs:
# if: matrix.os != 'ubuntu-latest'
# 4. Package the extension
- shell: pwsh
run: echo "target=${{ matrix.platform }}-${{ matrix.arch }}" >> $env:GITHUB_ENV
- run: cd extensions/vscode && npx vsce package --target ${{ env.target }}
- name: Re-install esbuild
run: |
cd extensions/vscode
npm install -f esbuild
- name: Package the extension
run: cd extensions/vscode && npx vsce package --target ${{ env.target }}
# 5. Upload the .vsix as an artifact
- uses: actions/upload-artifact@v2
@ -150,14 +148,6 @@ jobs:
name: ${{ env.target }}
path: "extensions/vscode/*.vsix"
# 6. Upload continue.log as an artifact for debugging of the workflow
- name: Upload continue.log
uses: actions/upload-artifact@v2
with:
name: continue-log
path: /home/runner/.continue/continue.log
if: always()
publish:
runs-on: ubuntu-latest
needs:
@ -214,7 +204,7 @@ jobs:
# 5 Send to Discord Webhook
- name: Discord Commits
uses: Sniddl/discord-commits@v1.6
uses: Sniddl/discord-commits@1.7
with:
webhook: ${{ secrets.DISCORD_WEBHOOK }}
template: "avatar-with-link"

View file

@ -143,14 +143,6 @@ jobs:
name: ${{ env.target }}
path: "extensions/vscode/*.vsix"
# 6. Upload continue.log as an artifact for debugging of the workflow
- name: Upload continue.log
uses: actions/upload-artifact@v2
with:
name: continue-log
path: /home/runner/.continue/continue.log
if: always()
publish:
runs-on: ubuntu-latest
needs:

View file

@ -1,4 +1,5 @@
import { CustomCommand, SlashCommand, SlashCommandDescription } from "..";
import { stripImages } from "../llm/countTokens";
import SlashCommands from "./slash";
export function slashFromCustomCommand(
@ -14,7 +15,7 @@ export function slashFromCustomCommand(
for (let i = messages.length - 1; i >= 0; i--) {
if (
messages[i].role === "user" &&
messages[i].content.startsWith(`/${customCommand.name}`)
stripImages(messages[i].content).startsWith(`/${customCommand.name}`)
) {
messages[i] = { ...messages[i], content: promptUserInput };
break;
@ -22,7 +23,7 @@ export function slashFromCustomCommand(
}
for await (const chunk of llm.streamChat(messages)) {
yield chunk.content;
yield stripImages(chunk.content);
}
},
};

View file

@ -1,4 +1,5 @@
import { SlashCommand } from "../..";
import { stripImages } from "../../llm/countTokens";
const CommitMessageCommand: SlashCommand = {
name: "commit",
@ -9,7 +10,7 @@ const CommitMessageCommand: SlashCommand = {
for await (const chunk of llm.streamChat([
{ role: "user", content: prompt },
])) {
yield chunk.content;
yield stripImages(chunk.content);
}
},
};

View file

@ -1,4 +1,5 @@
import { ChatMessage, SlashCommand } from "../..";
import { stripImages } from "../../llm/countTokens";
import { removeQuotesAndEscapes } from "../../util";
const PROMPT = (
@ -43,7 +44,7 @@ const DraftIssueCommand: SlashCommand = {
for await (const chunk of llm.streamChat(messages)) {
body += chunk.content;
yield chunk.content;
yield stripImages(chunk.content);
}
const url = `${params.repositoryUrl}/issues/new?title=${encodeURIComponent(

View file

@ -1,4 +1,5 @@
import { ContextItemWithId, ILLM, SlashCommand } from "../..";
import { stripImages } from "../../llm/countTokens";
import { dedentAndGetCommonWhitespace, renderPromptTemplate } from "../../util";
import {
RangeInFileWithContents,
@ -50,11 +51,11 @@ export async function getPromptParts(
let maxTokens = Math.floor(model.contextLength / 2);
const TOKENS_TO_BE_CONSIDERED_LARGE_RANGE = tokenLimit || 1200;
if (model.countTokens(rif.contents) > TOKENS_TO_BE_CONSIDERED_LARGE_RANGE) {
throw new Error(
"\n\n**It looks like you've selected a large range to edit, which may take a while to complete. If you'd like to cancel, click the 'X' button above. If you highlight a more specific range, Continue will only edit within it.**"
);
}
// if (model.countTokens(rif.contents) > TOKENS_TO_BE_CONSIDERED_LARGE_RANGE) {
// throw new Error(
// "\n\n**It looks like you've selected a large range to edit, which may take a while to complete. If you'd like to cancel, click the 'X' button above. If you highlight a more specific range, Continue will only edit within it.**"
// );
// }
const BUFFER_FOR_FUNCTIONS = 400;
let totalTokens =
@ -457,7 +458,7 @@ const EditSlashCommand: SlashCommand = {
4096
),
})) {
yield chunk.content;
yield stripImages(chunk.content);
}
}

View file

@ -1,4 +1,5 @@
import { SlashCommand } from "../..";
import { stripImages } from "../../llm/countTokens";
const ShareSlashCommand: SlashCommand = {
name: "share",
@ -7,9 +8,9 @@ const ShareSlashCommand: SlashCommand = {
let content = `This is a session transcript from [Continue](https://continue.dev) on ${new Date().toLocaleString()}.`;
for (const msg of history) {
content += `\n\n## ${msg.role === "user" ? "User" : "Continue"}\n\n${
msg.content
}`;
content += `\n\n## ${
msg.role === "user" ? "User" : "Continue"
}\n\n${stripImages(msg.content)}`;
}
const continueDir = await ide.getContinueDir();

View file

@ -1,5 +1,5 @@
import { ChatMessageRole, SlashCommand } from "../..";
import { pruneStringFromBottom } from "../../llm/countTokens";
import { pruneStringFromBottom, stripImages } from "../../llm/countTokens";
const SERVER_URL = "https://proxy-server-l6vsfbzhba-uw.a.run.app";
const PROMPT = (
@ -114,7 +114,7 @@ const StackOverflowSlashCommand: SlashCommand = {
})),
{ role: "user", content: PROMPT(input) },
])) {
yield chunk.content;
yield stripImages(chunk.content);
}
},
};

View file

@ -1,6 +1,7 @@
import { ContextItemWithId, DiffLine, ILLM, SlashCommand } from "../..";
import { streamDiff } from "../../diff/streamDiff";
import { LineStream, streamLines } from "../../diff/util";
import { stripImages } from "../../llm/countTokens";
import { gptEditPrompt } from "../../llm/templates/edit";
import {
dedentAndGetCommonWhitespace,
@ -81,7 +82,7 @@ function constructPrompt(
});
return typeof rendered === "string"
? rendered
: rendered[rendered.length - 1].content;
: stripImages(rendered[rendered.length - 1].content);
}
async function* addIndentation(

View file

@ -13,6 +13,11 @@ declare global {
index: number; // Index of the chunk in the document at filepath
}
export interface IndexingProgressUpdate {
progress: number;
desc: string;
}
export interface LLMReturnValue {
prompt: string;
completion: string;
@ -61,30 +66,49 @@ declare global {
): Promise<ChatMessage>;
countTokens(text: string): number;
supportsImages(): boolean;
}
export type ContextProviderType = "normal" | "query" | "submenu";
export interface ContextProviderDescription {
title: string;
displayTitle: string;
description: string;
dynamic: boolean;
requiresQuery: boolean;
type: ContextProviderType;
}
interface ContextProviderExtras {
export interface ContextProviderExtras {
fullInput: string;
embeddingsProvider?: EmbeddingsProvider;
embeddingsProvider: EmbeddingsProvider;
llm: ILLM;
ide: IDE;
selectedCode: RangeInFile[];
}
export interface LoadSubmenuItemsArgs {
ide: IDE;
}
export interface CustomContextProvider {
title: string;
displayTitle?: string;
description?: string;
type?: ContextProviderType;
getContextItems(
query: string,
extras: ContextProviderExtras
): Promise<ContextItem[]>;
loadSubmenuItems?: (
args: LoadSubmenuItemsArgs
) => Promise<ContextSubmenuItem[]>;
}
export interface ContextSubmenuItem {
id: string;
title: string;
description: string;
}
export interface IContextProvider {
@ -94,6 +118,8 @@ declare global {
query: string,
extras: ContextProviderExtras
): Promise<ContextItem[]>;
loadSubmenuItems(args: LoadSubmenuItemsArgs): Promise<ContextSubmenuItem[]>;
}
export interface PersistedSessionInfo {
@ -134,24 +160,23 @@ declare global {
message: string;
}
export interface CompletionOptions {
export interface CompletionOptions extends BaseCompletionOptions {
model: string;
maxTokens: number;
temperature?: number;
topP?: number;
topK?: number;
minP?: number;
presencePenalty?: number;
frequencyPenalty?: number;
stop?: string[];
}
export type ChatMessageRole = "user" | "assistant" | "system";
export interface MessagePart {
type: "text" | "imageUrl";
text?: string;
imageUrl?: { url: string };
}
export type MessageContent = string | MessagePart[];
export interface ChatMessage {
role: ChatMessageRole;
content: string;
content: MessageContent;
}
export interface ContextItemId {
@ -187,20 +212,11 @@ declare global {
// LLM
export interface LLMFullCompletionOptions {
export interface LLMFullCompletionOptions extends BaseCompletionOptions {
raw?: boolean;
log?: boolean;
model?: string;
temperature?: number;
topP?: number;
topK?: number;
minP?: number;
presencePenalty?: number;
frequencyPenalty?: number;
stop?: string[];
maxTokens?: number;
}
export interface LLMOptions {
model: string;
@ -265,12 +281,19 @@ declare global {
line: string;
}
export class Problem {
filepath: string;
range: Range;
message: string;
}
export interface IDE {
getSerializedConfig(): Promise<SerializedContinueConfig>;
getConfigJsUrl(): Promise<string | undefined>;
getDiff(): Promise<string>;
getTerminalContents(): Promise<string>;
listWorkspaceContents(directory?: string): Promise<string[]>;
listFolders(): Promise<string[]>;
getWorkspaceDirs(): Promise<string[]>;
writeFile(path: string, contents: string): Promise<void>;
showVirtualFile(title: string, contents: string): Promise<void>;
@ -291,8 +314,10 @@ declare global {
diffLine: DiffLine
): Promise<void>;
getOpenFiles(): Promise<string[]>;
getPinnedFiles(): Promise<string[]>;
getSearchResults(query: string): Promise<string>;
subprocess(command: string): Promise<[string, string]>;
getProblems(filepath?: string | undefined): Promise<Problem[]>;
// Embeddings
/**
@ -305,10 +330,9 @@ declare global {
tags: string[]
): void;
retrieveChunks(
v: number[],
text: string,
n: number,
tags: string[],
providerId: string
directory: string | undefined
): Promise<Chunk[]>;
}
@ -320,7 +344,7 @@ declare global {
addContextItem: (item: ContextItemWithId) => void;
history: ChatMessage[];
input: string;
params?: any;
params?: { [key: string]: any } | undefined;
contextItems: ContextItemWithId[];
}
@ -359,12 +383,15 @@ declare global {
| "url"
| "tree"
| "http"
| "codebase";
| "codebase"
| "problems"
| "folder";
type TemplateType =
| "llama2"
| "alpaca"
| "zephyr"
| "phi2"
| "phind"
| "anthropic"
| "chatml"
@ -373,7 +400,7 @@ declare global {
| "deepseek"
| "xwin-coder"
| "neural-chat";
type ModelProvider =
| "openai"
| "free-trial"
@ -410,6 +437,7 @@ declare global {
| "codellama-7b"
| "codellama-13b"
| "codellama-34b"
| "phi2"
| "phind-codellama-34b"
| "wizardcoder-7b"
| "wizardcoder-13b"
@ -468,8 +496,9 @@ declare global {
minP?: number;
presencePenalty?: number;
frequencyPenalty?: number;
mirostat?: number;
stop?: string[];
maxTokens: number;
maxTokens?: number;
}
export interface ModelDescription {
@ -556,9 +585,9 @@ declare global {
disableSessionTitles?: boolean;
disableIndexing?: boolean;
userToken?: string;
embeddingsProvider?: EmbeddingsProvider;
embeddingsProvider: EmbeddingsProvider;
}
}
export {};

View file

@ -2,9 +2,10 @@ import {
ContextItem,
ContextProviderDescription,
ContextProviderExtras,
ContextSubmenuItem,
IContextProvider,
LoadSubmenuItemsArgs,
} from "..";
export abstract class BaseContextProvider implements IContextProvider {
options: { [key: string]: any };
@ -24,5 +25,9 @@ export abstract class BaseContextProvider implements IContextProvider {
extras: ContextProviderExtras
): Promise<ContextItem[]>;
abstract load(): Promise<void>;
async loadSubmenuItems(
args: LoadSubmenuItemsArgs
): Promise<ContextSubmenuItem[]> {
return [];
}
}

View file

@ -11,8 +11,7 @@ class CodebaseContextProvider extends BaseContextProvider {
title: "codebase",
displayTitle: "Codebase",
description: "Automatically find relevant files",
dynamic: false,
requiresQuery: false,
type: "normal",
};
async getContextItems(

View file

@ -4,6 +4,7 @@ import {
ContextProviderExtras,
CustomContextProvider,
IContextProvider,
LoadSubmenuItemsArgs,
} from "../..";
class CustomContextProviderClass implements IContextProvider {
@ -17,8 +18,7 @@ class CustomContextProviderClass implements IContextProvider {
title: this.custom.title,
displayTitle: this.custom.displayTitle || this.custom.title,
description: this.custom.description || "",
dynamic: true,
requiresQuery: false,
type: this.custom.type || "normal",
};
}
@ -28,7 +28,10 @@ class CustomContextProviderClass implements IContextProvider {
): Promise<ContextItem[]> {
return await this.custom.getContextItems(query, extras);
}
async load(): Promise<void> {}
async loadSubmenuItems(args: LoadSubmenuItemsArgs) {
return this.custom.loadSubmenuItems?.(args) || [];
}
}
export default CustomContextProviderClass;

View file

@ -4,22 +4,20 @@ import {
ContextProviderDescription,
ContextProviderExtras,
} from "../..";
import { ExtensionIde } from "../../ide";
class DiffContextProvider extends BaseContextProvider {
static description: ContextProviderDescription = {
title: "diff",
displayTitle: "Git Diff",
description: "Reference the current git diff",
dynamic: true,
requiresQuery: false,
type: "normal",
};
async getContextItems(
query: string,
extras: ContextProviderExtras
): Promise<ContextItem[]> {
const diff = await new ExtensionIde().getDiff();
const diff = await extras.ide.getDiff();
return [
{
description: "The current git diff",
@ -28,7 +26,6 @@ class DiffContextProvider extends BaseContextProvider {
},
];
}
async load(): Promise<void> {}
}
export default DiffContextProvider;

View file

@ -0,0 +1,72 @@
import { BaseContextProvider } from "..";
import {
ContextItem,
ContextProviderDescription,
ContextProviderExtras,
ContextSubmenuItem,
LoadSubmenuItemsArgs,
} from "../..";
import TransformersJsEmbeddingsProvider from "../../indexing/embeddings/TransformersJsEmbeddingsProvider";
class DocsContextProvider extends BaseContextProvider {
static description: ContextProviderDescription = {
title: "docs",
displayTitle: "Docs",
description: "Search documentation",
type: "submenu",
};
async getContextItems(
query: string,
extras: ContextProviderExtras
): Promise<ContextItem[]> {
const { retrieveDocs } = await import("../../indexing/docs/db");
const embeddingsProvider = new TransformersJsEmbeddingsProvider();
const [vector] = await embeddingsProvider.embed([extras.fullInput]);
const chunks = await retrieveDocs(
query,
vector,
this.options?.nRetrieve || 15
);
console.log(chunks);
return [
...chunks
.map((chunk) => ({
name: chunk.filepath
.split("/")
.slice(1)
.join("/")
.split("/tree/main/")
.slice(1)
.join("/"), // chunk.otherMetadata?.title || chunk.filepath,
description: new URL(chunk.filepath, query).toString(),
content: chunk.content,
}))
.reverse(),
{
name: "Instructions",
description: "Instructions",
content:
"Use the above documentation to answer the following question. You should not reference anything outside of what is shown, unless it is a commonly known concept. Reference URLs whenever possible. If there isn't enough information to answer the question, suggest where the user might look to learn more.",
},
];
}
async loadSubmenuItems(
args: LoadSubmenuItemsArgs
): Promise<ContextSubmenuItem[]> {
const { listDocs } = await import("../../indexing/docs/db");
const docs = await listDocs();
return docs.map((doc) => ({
title: doc.title,
description: new URL(doc.baseUrl).hostname,
id: doc.baseUrl,
}));
}
}
export default DocsContextProvider;

View file

@ -3,16 +3,17 @@ import {
ContextItem,
ContextProviderDescription,
ContextProviderExtras,
ContextSubmenuItem,
LoadSubmenuItemsArgs,
} from "../..";
import { ExtensionIde } from "../../ide";
import { getBasename, getLastNPathParts } from "../../util";
class FileContextProvider extends BaseContextProvider {
static description: ContextProviderDescription = {
title: "file",
displayTitle: "Files",
description: "Type to search",
dynamic: false,
requiresQuery: false,
type: "submenu",
};
async getContextItems(
@ -21,7 +22,7 @@ class FileContextProvider extends BaseContextProvider {
): Promise<ContextItem[]> {
// Assume the query is a filepath
query = query.trim();
const content = await new ExtensionIde().readFile(query);
const content = await extras.ide.readFile(query);
return [
{
name: query.split(/[\\/]/).pop() || query,
@ -30,7 +31,25 @@ class FileContextProvider extends BaseContextProvider {
},
];
}
async load(): Promise<void> {}
async loadSubmenuItems(
args: LoadSubmenuItemsArgs
): Promise<ContextSubmenuItem[]> {
const workspaceDirs = await args.ide.getWorkspaceDirs();
const results = await Promise.all(
workspaceDirs.map((dir) => {
return args.ide.listWorkspaceContents(dir);
})
);
const files = results.flat();
return files.map((file) => {
return {
id: file,
title: getBasename(file),
description: getLastNPathParts(file, 2),
};
});
}
}
export default FileContextProvider;

View file

@ -4,7 +4,6 @@ import {
ContextProviderDescription,
ContextProviderExtras,
} from "../..";
import { ExtensionIde } from "../../ide";
interface Directory {
name: string;
@ -40,21 +39,18 @@ class FileTreeContextProvider extends BaseContextProvider {
title: "tree",
displayTitle: "File Tree",
description: "Attach a representation of the file tree",
dynamic: true,
requiresQuery: false,
type: "normal",
};
async getContextItems(
query: string,
extras: ContextProviderExtras
): Promise<ContextItem[]> {
const workspaceDirs = await new ExtensionIde().getWorkspaceDirs();
const workspaceDirs = await extras.ide.getWorkspaceDirs();
let trees = [];
for (let workspaceDir of workspaceDirs) {
const contents = await new ExtensionIde().listWorkspaceContents(
workspaceDir
);
const contents = await extras.ide.listWorkspaceContents(workspaceDir);
const subDirTree: Directory = {
name: splitPath(workspaceDir).pop() || "",
@ -94,7 +90,6 @@ class FileTreeContextProvider extends BaseContextProvider {
},
];
}
async load(): Promise<void> {}
}
export default FileTreeContextProvider;

View file

@ -3,7 +3,10 @@ import {
ContextItem,
ContextProviderDescription,
ContextProviderExtras,
ContextSubmenuItem,
LoadSubmenuItemsArgs,
} from "../..";
import { getBasename, getLastNPathParts } from "../../util";
import { retrieveContextItemsFromEmbeddings } from "../retrieval";
class FolderContextProvider extends BaseContextProvider {
@ -11,8 +14,7 @@ class FolderContextProvider extends BaseContextProvider {
title: "folder",
displayTitle: "Folders",
description: "Type to search",
dynamic: false,
requiresQuery: false,
type: "submenu",
};
async getContextItems(
@ -21,7 +23,18 @@ class FolderContextProvider extends BaseContextProvider {
): Promise<ContextItem[]> {
return retrieveContextItemsFromEmbeddings(extras, this.options, query);
}
async load(): Promise<void> {}
async loadSubmenuItems(
args: LoadSubmenuItemsArgs
): Promise<ContextSubmenuItem[]> {
const folders = await args.ide.listFolders();
return folders.map((folder) => {
return {
id: folder,
title: getBasename(folder),
description: getLastNPathParts(folder, 2),
};
});
}
}
export default FolderContextProvider;

View file

@ -3,24 +3,92 @@ import {
ContextItem,
ContextProviderDescription,
ContextProviderExtras,
ContextSubmenuItem,
LoadSubmenuItemsArgs,
} from "../..";
class GitHubIssuesContextProvider extends BaseContextProvider {
static description: ContextProviderDescription = {
title: "github",
title: "issue",
displayTitle: "GitHub Issues",
description: "Reference GitHub issues",
dynamic: false,
requiresQuery: false,
type: "submenu",
};
async getContextItems(
query: string,
extras: ContextProviderExtras
): Promise<ContextItem[]> {
return [];
const issueId = query;
const { Octokit } = await import("@octokit/rest");
const octokit = new Octokit({
auth: this.options?.githubToken,
});
const { owner, repo, issue_number } = JSON.parse(issueId);
const issue = await octokit.issues.get({
owner,
repo,
issue_number,
});
let content = `# GitHub Issue #${issue.data.number.toString()} in ${owner}/${repo}`;
const comments = await octokit.issues.listComments({
owner,
repo,
issue_number,
});
const parts = [
issue.data.body || "No description",
...comments.data.map((comment) => comment.body),
];
content += "\n\n" + parts.join("\n\n---\n\n");
return [
{
name: issue.data.title,
content,
description: `#${issue.data.number.toString()}`,
},
];
}
async loadSubmenuItems(
args: LoadSubmenuItemsArgs
): Promise<ContextSubmenuItem[]> {
const { Octokit } = await import("@octokit/rest");
const octokit = new Octokit({
auth: this.options?.githubToken,
});
const allIssues = [];
for (const repo of this.options?.repos) {
const issues = await octokit.issues.listForRepo({
owner: repo.owner,
repo: repo.repo,
state: repo.type || "open",
});
allIssues.push(
...issues.data.map((issue) => ({
title: issue.title,
description: `#${issue.number.toString()}`,
id: JSON.stringify({
owner: repo.owner,
repo: repo.repo,
issue_number: issue.number,
}),
}))
);
}
return allIssues;
}
async load(): Promise<void> {}
}
export default GitHubIssuesContextProvider;

View file

@ -10,8 +10,7 @@ class GoogleContextProvider extends BaseContextProvider {
title: "google",
displayTitle: "Google",
description: "Attach the results of a Google search",
dynamic: true,
requiresQuery: true,
type: "query",
};
private _serperApiKey: string;
@ -61,7 +60,6 @@ class GoogleContextProvider extends BaseContextProvider {
},
];
}
async load(): Promise<void> {}
}
export default GoogleContextProvider;

View file

@ -10,8 +10,7 @@ class HttpContextProvider extends BaseContextProvider {
title: "http",
displayTitle: "HTTP",
description: "Retrieve a context item from a custom server",
dynamic: true,
requiresQuery: false,
type: "normal",
};
override get description(): ContextProviderDescription {
@ -21,8 +20,7 @@ class HttpContextProvider extends BaseContextProvider {
description:
this.options.description ||
"Retrieve a context item from a custom server",
dynamic: true,
requiresQuery: false,
type: "normal",
};
}
@ -36,7 +34,8 @@ class HttpContextProvider extends BaseContextProvider {
"Content-Type": "application/json",
},
body: JSON.stringify({
query,
query: query || "",
fullInput: extras.fullInput,
}),
});
@ -49,7 +48,6 @@ class HttpContextProvider extends BaseContextProvider {
},
];
}
async load(): Promise<void> {}
}
export default HttpContextProvider;

View file

@ -4,7 +4,6 @@ import {
ContextProviderDescription,
ContextProviderExtras,
} from "../..";
import { ExtensionIde } from "../../ide";
import { getBasename } from "../../util";
class OpenFilesContextProvider extends BaseContextProvider {
@ -12,16 +11,17 @@ class OpenFilesContextProvider extends BaseContextProvider {
title: "open",
displayTitle: "Open Files",
description: "Reference the current open files",
dynamic: true,
requiresQuery: false,
type: "normal",
};
async getContextItems(
query: string,
extras: ContextProviderExtras
): Promise<ContextItem[]> {
const ide = new ExtensionIde();
const openFiles = await ide.getOpenFiles();
const ide = extras.ide;
const openFiles = this.options?.onlyPinned
? await ide.getPinnedFiles()
: await ide.getOpenFiles();
return await Promise.all(
openFiles.map(async (filepath: string) => {
return {
@ -34,7 +34,6 @@ class OpenFilesContextProvider extends BaseContextProvider {
})
);
}
async load(): Promise<void> {}
}
export default OpenFilesContextProvider;

View file

@ -4,7 +4,6 @@ import {
ContextProviderDescription,
ContextProviderExtras,
} from "../..";
import { ExtensionIde } from "../../ide";
import { getBasename } from "../../util";
class ProblemsContextProvider extends BaseContextProvider {
@ -12,15 +11,14 @@ class ProblemsContextProvider extends BaseContextProvider {
title: "problems",
displayTitle: "Problems",
description: "Reference problems in the current file",
dynamic: true,
requiresQuery: false,
type: "normal",
};
async getContextItems(
query: string,
extras: ContextProviderExtras
): Promise<ContextItem[]> {
const ide = new ExtensionIde();
const ide = extras.ide;
const problems = await ide.getProblems();
const items = await Promise.all(
@ -46,7 +44,6 @@ class ProblemsContextProvider extends BaseContextProvider {
return items;
}
async load(): Promise<void> {}
}
export default ProblemsContextProvider;

View file

@ -4,22 +4,20 @@ import {
ContextProviderDescription,
ContextProviderExtras,
} from "../..";
import { ExtensionIde } from "../../ide";
class SearchContextProvider extends BaseContextProvider {
static description: ContextProviderDescription = {
title: "search",
displayTitle: "Search",
description: "Use ripgrep to exact search the workspace",
dynamic: true,
requiresQuery: true,
type: "query",
};
async getContextItems(
query: string,
extras: ContextProviderExtras
): Promise<ContextItem[]> {
const results = await new ExtensionIde().getSearchResults(query);
const results = await extras.ide.getSearchResults(query);
return [
{
description: "Search results",
@ -28,7 +26,6 @@ class SearchContextProvider extends BaseContextProvider {
},
];
}
async load(): Promise<void> {}
}
export default SearchContextProvider;

View file

@ -4,22 +4,20 @@ import {
ContextProviderDescription,
ContextProviderExtras,
} from "../..";
import { ExtensionIde } from "../../ide";
class TerminalContextProvider extends BaseContextProvider {
static description: ContextProviderDescription = {
title: "terminal",
displayTitle: "Terminal",
description: "Reference the contents of the terminal",
dynamic: true,
requiresQuery: false,
type: "normal",
};
async getContextItems(
query: string,
extras: ContextProviderExtras
): Promise<ContextItem[]> {
const content = await new ExtensionIde().getTerminalContents();
const content = await extras.ide.getTerminalContents();
return [
{
description: "The contents of the terminal",
@ -28,7 +26,6 @@ class TerminalContextProvider extends BaseContextProvider {
},
];
}
async load(): Promise<void> {}
}
export default TerminalContextProvider;

View file

@ -10,8 +10,7 @@ class URLContextProvider extends BaseContextProvider {
title: "url",
displayTitle: "URL",
description: "Attach the contents of a web page",
dynamic: true,
requiresQuery: true,
type: "query",
};
async getContextItems(
@ -39,7 +38,6 @@ class URLContextProvider extends BaseContextProvider {
},
];
}
async load(): Promise<void> {}
}
export default URLContextProvider;

View file

@ -11,6 +11,7 @@ from pydantic import BaseModel
class Item(BaseModel):
query: str
fullInput: str
app = FastAPI()

View file

@ -2,6 +2,7 @@ import { BaseContextProvider } from "..";
import { ContextProviderName } from "../..";
import CodebaseContextProvider from "./CodebaseContextProvider";
import DiffContextProvider from "./DiffContextProvider";
import DocsContextProvider from "./DocsContextProvider";
import FileTreeContextProvider from "./FileTreeContextProvider";
import FolderContextProvider from "./FolderContextProvider";
import GitHubIssuesContextProvider from "./GitHubIssuesContextProvider";
@ -26,6 +27,7 @@ const Providers: (typeof BaseContextProvider)[] = [
CodebaseContextProvider,
ProblemsContextProvider,
FolderContextProvider,
DocsContextProvider,
];
export function contextProviderClassFromName(

View file

@ -5,7 +5,6 @@ import {
ILLM,
ModelProvider,
} from "..";
import { ExtensionIde } from "../ide";
import { getBasename } from "../util";
const RERANK_PROMPT = (
@ -141,7 +140,7 @@ export async function retrieveContextItemsFromEmbeddings(
(options?.useReranking === undefined ? false : options?.useReranking);
// Similarity search
let results = await new ExtensionIde().retrieveChunks(
let results = await extras.ide.retrieveChunks(
extras.fullInput,
useReranking === false ? nFinal : nRetrieve,
filterDirectory

View file

@ -107,6 +107,10 @@ class FileSystemIde implements IDE {
return Promise.resolve([]);
}
getPinnedFiles(): Promise<string[]> {
return Promise.resolve([]);
}
async getSearchResults(query: string): Promise<string> {
return "";
}

View file

@ -88,6 +88,10 @@ export class ExtensionIde implements IDE {
return r("getOpenFiles");
}
getPinnedFiles(): Promise<string[]> {
return r("getPinnedFiles");
}
getSearchResults(query: string): Promise<string> {
return r("getSearchResults", { query });
}

70
core/index.d.ts vendored
View file

@ -11,6 +11,11 @@ export interface Chunk extends ChunkWithoutID {
index: number; // Index of the chunk in the document at filepath
}
export interface IndexingProgressUpdate {
progress: number;
desc: string;
}
export interface LLMReturnValue {
prompt: string;
completion: string;
@ -59,30 +64,49 @@ export interface ILLM extends LLMOptions {
): Promise<ChatMessage>;
countTokens(text: string): number;
supportsImages(): boolean;
}
export type ContextProviderType = "normal" | "query" | "submenu";
export interface ContextProviderDescription {
title: string;
displayTitle: string;
description: string;
dynamic: boolean;
requiresQuery: boolean;
type: ContextProviderType;
}
interface ContextProviderExtras {
export interface ContextProviderExtras {
fullInput: string;
embeddingsProvider?: EmbeddingsProvider;
embeddingsProvider: EmbeddingsProvider;
llm: ILLM;
ide: IDE;
selectedCode: RangeInFile[];
}
export interface LoadSubmenuItemsArgs {
ide: IDE;
}
export interface CustomContextProvider {
title: string;
displayTitle?: string;
description?: string;
type?: ContextProviderType;
getContextItems(
query: string,
extras: ContextProviderExtras
): Promise<ContextItem[]>;
loadSubmenuItems?: (
args: LoadSubmenuItemsArgs
) => Promise<ContextSubmenuItem[]>;
}
export interface ContextSubmenuItem {
id: string;
title: string;
description: string;
}
export interface IContextProvider {
@ -92,6 +116,8 @@ export interface IContextProvider {
query: string,
extras: ContextProviderExtras
): Promise<ContextItem[]>;
loadSubmenuItems(args: LoadSubmenuItemsArgs): Promise<ContextSubmenuItem[]>;
}
export interface PersistedSessionInfo {
@ -132,24 +158,23 @@ export interface ContinueError {
message: string;
}
export interface CompletionOptions {
export interface CompletionOptions extends BaseCompletionOptions {
model: string;
maxTokens: number;
temperature?: number;
topP?: number;
topK?: number;
minP?: number;
presencePenalty?: number;
frequencyPenalty?: number;
stop?: string[];
}
export type ChatMessageRole = "user" | "assistant" | "system";
export interface MessagePart {
type: "text" | "imageUrl";
text?: string;
imageUrl?: { url: string };
}
export type MessageContent = string | MessagePart[];
export interface ChatMessage {
role: ChatMessageRole;
content: string;
content: MessageContent;
}
export interface ContextItemId {
@ -185,20 +210,11 @@ export type ChatHistory = ChatHistoryItem[];
// LLM
export interface LLMFullCompletionOptions {
export interface LLMFullCompletionOptions extends BaseCompletionOptions {
raw?: boolean;
log?: boolean;
model?: string;
temperature?: number;
topP?: number;
topK?: number;
minP?: number;
presencePenalty?: number;
frequencyPenalty?: number;
stop?: string[];
maxTokens?: number;
}
export interface LLMOptions {
model: string;
@ -296,6 +312,7 @@ export interface IDE {
diffLine: DiffLine
): Promise<void>;
getOpenFiles(): Promise<string[]>;
getPinnedFiles(): Promise<string[]>;
getSearchResults(query: string): Promise<string>;
subprocess(command: string): Promise<[string, string]>;
getProblems(filepath?: string | undefined): Promise<Problem[]>;
@ -477,8 +494,9 @@ interface BaseCompletionOptions {
minP?: number;
presencePenalty?: number;
frequencyPenalty?: number;
mirostat?: number;
stop?: string[];
maxTokens: number;
maxTokens?: number;
}
export interface ModelDescription {

View file

@ -1,7 +1,8 @@
// NOTE: vectordb requirement must be listed in extensions/vscode to avoid error
import { v4 as uuidv4 } from "uuid";
import * as lancedb from "vectordb";
import { Chunk, EmbeddingsProvider } from "..";
import { Chunk, EmbeddingsProvider, IndexingProgressUpdate } from "..";
import { MAX_CHUNK_SIZE } from "../llm/constants";
import { getBasename } from "../util";
import { getLanceDbPath } from "../util/paths";
import { chunkDocument } from "./chunk/chunk";
@ -32,7 +33,7 @@ export class LanceDbIndex implements CodebaseIndex {
return "vectordb::" + this.embeddingsProvider.id;
}
static MAX_CHUNK_SIZE = 500; // 512 - buffer for safety (in case of differing tokenizers)
static MAX_CHUNK_SIZE = MAX_CHUNK_SIZE;
embeddingsProvider: EmbeddingsProvider;
readFile: (filepath: string) => Promise<string>;
@ -136,7 +137,7 @@ export class LanceDbIndex implements CodebaseIndex {
items: PathAndCacheKey[],
resultType: IndexResultType
) => void
): AsyncGenerator<{ progress: number; desc: string }> {
): AsyncGenerator<IndexingProgressUpdate> {
const tableName = this.tableNameForTag(tag);
const db = await lancedb.connect(getLanceDbPath());

View file

@ -1,4 +1,5 @@
import { Chunk, ChunkWithoutID } from "../..";
import { MAX_CHUNK_SIZE } from "../../llm/constants";
import { countTokens } from "../../llm/countTokens";
import { basicChunker } from "./basic";
import { codeChunker, supportedLanguages } from "./code";
@ -41,7 +42,7 @@ export async function* chunkDocument(
contents,
maxChunkSize
)) {
if (countTokens(chunkWithoutId.content, "gpt-4") > 512) {
if (countTokens(chunkWithoutId.content, "gpt-4") > MAX_CHUNK_SIZE) {
console.warn(
`Chunk with more than ${maxChunkSize} tokens constructed: `,
filepath,

View file

@ -0,0 +1,132 @@
import { ChunkWithoutID } from "../..";
import { countTokens } from "../../llm/countTokens";
import { basicChunker } from "./basic";
function cleanFragment(fragment: string | undefined): string | undefined {
if (!fragment) {
return undefined;
}
// Remove leading and trailing whitespaces
fragment = fragment.trim();
// If there's a ](, which would mean a link, remove everything after it
const parenIndex = fragment.indexOf("](");
if (parenIndex !== -1) {
fragment = fragment.slice(0, parenIndex);
}
// Remove all special characters except alphanumeric, hyphen, space, and underscore
fragment = fragment.replace(/[^\w\d-\s]/g, "").trim();
// Convert to lowercase
fragment = fragment.toLowerCase();
// Replace spaces with hyphens
fragment = fragment.replace(/\s+/g, "-");
return fragment;
}
function cleanHeader(header: string | undefined): string | undefined {
if (!header) {
return undefined;
}
// Remove leading and trailing whitespaces
header = header.trim();
// If there's a (, remove everything after it
const parenIndex = header.indexOf("(");
if (parenIndex !== -1) {
header = header.slice(0, parenIndex);
}
// Remove all special characters except alphanumeric, hyphen, space, and underscore
header = header.replace(/[^\w\d-\s]/g, "").trim();
return header;
}
function findHeader(lines: string[]): string | undefined {
return lines.find((line) => line.startsWith("#"))?.split("# ")[1];
}
export async function* markdownChunker(
content: string,
maxChunkSize: number,
hLevel: number
): AsyncGenerator<ChunkWithoutID> {
if (countTokens(content, "gpt-4") <= maxChunkSize) {
yield {
content,
startLine: 0,
endLine: content.split("\n").length,
};
return;
} else if (hLevel > 4) {
yield* basicChunker(content, maxChunkSize);
return;
}
const h = "#".repeat(hLevel + 1) + " ";
const lines = content.split("\n");
const sections = [];
let currentSectionStartLine = 0;
let currentSection: string[] = [];
for (let i = 0; i < lines.length; i++) {
if (lines[i].startsWith(h) || i === 0) {
if (currentSection.length) {
const isHeader = currentSection[0].startsWith(h);
sections.push({
header: isHeader ? currentSection[0] : findHeader(currentSection),
content: currentSection.slice(isHeader ? 1 : 0).join("\n"),
startLine: currentSectionStartLine,
endLine: currentSectionStartLine + currentSection.length,
});
}
currentSection = [lines[i]];
currentSectionStartLine = i;
} else {
currentSection.push(lines[i]);
}
}
if (currentSection.length) {
const isHeader = currentSection[0].startsWith(h);
sections.push({
header: isHeader ? currentSection[0] : findHeader(currentSection),
content: currentSection.slice(isHeader ? 1 : 0).join("\n"),
startLine: currentSectionStartLine,
endLine: currentSectionStartLine + currentSection.length,
});
}
for (const section of sections) {
for await (const chunk of markdownChunker(
section.content,
maxChunkSize -
(section.header ? countTokens(section.header, "gpt-4") : 0),
hLevel + 1
)) {
yield {
content: section.header + "\n" + chunk.content,
startLine: section.startLine + chunk.startLine,
endLine: section.startLine + chunk.endLine,
otherMetadata: {
fragment:
chunk.otherMetadata?.fragment || cleanFragment(section.header),
title: chunk.otherMetadata?.title || cleanHeader(section.header),
},
};
}
}
}
/**
* Recursively chunks by header level (h1-h6)
* The final chunk will always include all parent headers
* TODO: Merge together neighboring chunks if their sum doesn't exceed maxChunkSize
*/

195
core/indexing/docs/crawl.ts Normal file
View file

@ -0,0 +1,195 @@
import { Octokit } from "@octokit/rest";
import cheerio from "cheerio";
import fetch from "node-fetch";
// const HCCrawler = require("headless-chrome-crawler");
const IGNORE_PATHS_ENDING_IN = [
"favicon.ico",
"robots.txt",
".rst.txt",
"index.html", // So as not to duplicate with "/"
// ReadTheDocs
"genindex",
"py-modindex",
"search.html",
"search",
"genindex.html",
"changelog",
"changelog.html",
];
const GITHUB_PATHS_TO_TRAVERSE = ["/blob/", "/tree/"];
function shouldFilterPath(pathname: string, baseUrl: URL): boolean {
if (pathname.includes("#")) {
pathname = pathname.slice(0, pathname.indexOf("#"));
}
if (pathname.endsWith("/")) {
pathname = pathname.slice(0, -1);
}
if (baseUrl.hostname === "github.com") {
if (
pathname.split("/").length > 3 &&
!GITHUB_PATHS_TO_TRAVERSE.some((path) => pathname.includes(path))
)
return true;
return false;
}
if (IGNORE_PATHS_ENDING_IN.some((path) => pathname.endsWith(path)))
return true;
return false;
}
async function crawlLinks(path: string, baseUrl: URL, visited: Set<string>) {
if (visited.has(path) || shouldFilterPath(path, baseUrl)) {
return;
}
visited.add(path);
const response = await fetch(new URL(path, baseUrl));
const text = await response.text();
const $ = cheerio.load(text);
const children: string[] = [];
$("a").each((_, element) => {
const href = $(element).attr("href");
if (!href) {
return;
}
const parsedUrl = new URL(href, baseUrl);
if (
parsedUrl.hostname === baseUrl.hostname &&
!visited.has(parsedUrl.pathname) &&
parsedUrl.pathname.startsWith(baseUrl.pathname)
) {
children.push(parsedUrl.pathname);
}
});
await Promise.all(
children.map((child) => crawlLinks(child, baseUrl, visited))
);
}
async function crawlGithubRepo(baseUrl: URL) {
const octokit = new Octokit({
auth: undefined,
});
const [_, owner, repo] = baseUrl.pathname.split("/");
let dirContentsConfig = {
owner: owner,
repo: repo,
};
const tree = await octokit.request(
"GET /repos/{owner}/{repo}/git/trees/{tree_sha}",
{
owner,
repo,
tree_sha: "main",
headers: {
"X-GitHub-Api-Version": "2022-11-28",
},
recursive: "true",
}
);
const paths = tree.data.tree
.filter(
(file) => file.type === "blob" && file.path?.endsWith(".md")
// ||
// file.path?.endsWith(".rst") ||
// file.path?.split("/").includes("documentation") ||
// file.path?.split("/").includes("docs") ||
// file.path?.split("/").includes("doc") ||
// file.path?.split("/").includes("examples") ||
// file.path?.split("/").includes("example")
)
.map((file) => baseUrl.pathname + "/tree/main/" + file.path);
return paths;
}
export async function crawlSubpages(baseUrl: URL) {
// Special case for GitHub repos
if (baseUrl.hostname === "github.com") {
return crawlGithubRepo(baseUrl);
}
// First, check if the parent of the path redirects to the same page
const parentUrl = new URL(baseUrl);
parentUrl.pathname = parentUrl.pathname.split("/").slice(0, -1).join("/");
const response = await fetch(parentUrl);
let useParent = response.url === baseUrl.toString();
const visited = new Set<string>();
await crawlLinks(
(useParent ? parentUrl.pathname : baseUrl.pathname) || "/",
baseUrl,
visited
);
return [...visited];
}
// class NoEscapeTurndownService extends TurndownService {
// escape(str: string): string {
// return str;
// }
// }
// async function convertURLToMarkdown(url: string): Promise<string> {
// try {
// const response = await fetch(url);
// const htmlContent = await response.text();
// const turndown = new NoEscapeTurndownService({
// codeBlockStyle: "fenced",
// headingStyle: "atx",
// }).use([turndownPluginGfm.tables, turndownPluginGfm.strikethrough]);
// const markdown = turndown.turndown(htmlContent);
// return markdown;
// } catch (err) {
// console.error(err);
// throw new Error("Error converting URL to markdown");
// }
// }
// convertURLToMarkdown("https://python-socketio.readthedocs.io/en/stable").then(
// (md) => {
// console.log(md);
// }
// );
let visited = new Set<string>();
const url = new URL("https://python-socketio.readthedocs.io/en/stable");
const url2 = new URL("https://platform.openai.com/docs/api-reference");
// crawlLinks(url.pathname, url, visited).then(() => {
// console.log(visited);
// });
// async function hcCrawlLinks() {
// const results: any[] = [];
// const crawler = await HCCrawler.launch({
// // Function to be evaluated in browsers
// evaluatePage: () => ({
// title: $("title").text(),
// }),
// // Function to be called with evaluated results from browsers
// onSuccess: (result: any) => {
// console.log(result);
// results.push(result.url);
// },
// });
// // Queue a request
// await crawler.queue(url.toString());
// await crawler.onIdle(); // Resolved when no queue is left
// await crawler.close(); // Close the crawler
// return results;
// }

103
core/indexing/docs/db.ts Normal file
View file

@ -0,0 +1,103 @@
import { Database, open } from "sqlite";
import sqlite3 from "sqlite3";
import * as lancedb from "vectordb";
import { Chunk } from "../..";
import { getDocsSqlitePath, getLanceDbPath } from "../../util/paths";
const DOCS_TABLE_NAME = "docs";
interface LanceDbDocsRow {
title: string;
baseUrl: string;
// Chunk
content: string;
path: string;
startLine: number;
endLine: number;
vector: number[];
[key: string]: any;
}
async function createDocsTable(db: Database<sqlite3.Database>) {
db.exec(`CREATE TABLE IF NOT EXISTS docs (
id INTEGER PRIMARY KEY AUTOINCREMENT,
title STRING NOT NULL,
baseUrl STRING NOT NULL
)`);
}
export async function retrieveDocs(
baseUrl: string,
vector: number[],
nRetrieve: number
): Promise<Chunk[]> {
const lance = await lancedb.connect(getLanceDbPath());
const table = await lance.openTable(DOCS_TABLE_NAME);
const docs: LanceDbDocsRow[] = await table
.search(vector)
.limit(nRetrieve)
.where(`baseUrl = '${baseUrl}'`)
.execute();
return docs.map((doc) => ({
digest: doc.path,
filepath: doc.path,
startLine: doc.startLine,
endLine: doc.endLine,
index: 0,
content: doc.content,
otherMetadata: {
title: doc.title,
},
}));
}
export async function addDocs(
title: string,
baseUrl: URL,
chunks: Chunk[],
embeddings: number[][]
) {
const data: LanceDbDocsRow[] = chunks.map((chunk, i) => ({
title: chunk.otherMetadata?.title || title,
baseUrl: baseUrl.toString(),
content: chunk.content,
path: chunk.filepath,
startLine: chunk.startLine,
endLine: chunk.endLine,
vector: embeddings[i],
}));
const lance = await lancedb.connect(getLanceDbPath());
const tableNames = await lance.tableNames();
if (!tableNames.includes(DOCS_TABLE_NAME)) {
await lance.createTable(DOCS_TABLE_NAME, data);
} else {
const table = await lance.openTable(DOCS_TABLE_NAME);
await table.add(data);
}
// Only after add it to SQLite
const db = await open({
filename: getDocsSqlitePath(),
driver: sqlite3.Database,
});
await createDocsTable(db);
await db.run(
`INSERT INTO docs (title, baseUrl) VALUES (?, ?)`,
title,
baseUrl.toString()
);
}
export async function listDocs(): Promise<
{ title: string; baseUrl: string }[]
> {
const db = await open({
filename: getDocsSqlitePath(),
driver: sqlite3.Database,
});
await createDocsTable(db);
const docs = await db.all(`SELECT title, baseUrl FROM docs`);
return docs;
}

View file

@ -0,0 +1,18 @@
const esbuild = require("esbuild");
(async () => {
// Bundles the extension into one file
await esbuild.build({
entryPoints: ["crawl.ts"],
bundle: true,
outfile: "crawl.js",
external: ["jquery"],
format: "cjs",
platform: "node",
sourcemap: true,
loader: {
// eslint-disable-next-line @typescript-eslint/naming-convention
".node": "file",
},
});
})();

View file

@ -0,0 +1,91 @@
import {
Chunk,
ChunkWithoutID,
EmbeddingsProvider,
IndexingProgressUpdate,
} from "../..";
import { MAX_CHUNK_SIZE } from "../../llm/constants";
import { markdownChunker } from "../chunk/markdown";
import { crawlSubpages } from "./crawl";
import { addDocs, listDocs } from "./db";
import { convertURLToMarkdown } from "./urlToMarkdown";
export async function* indexDocs(
title: string,
baseUrl: URL,
embeddingsProvider: EmbeddingsProvider
): AsyncGenerator<IndexingProgressUpdate> {
const existingDocs = await listDocs();
if (existingDocs.find((doc) => doc.title === title)) {
yield {
progress: 1,
desc: "Already indexed",
};
return;
}
yield {
progress: 0,
desc: "Finding subpages",
};
let subpaths = await crawlSubpages(baseUrl);
console.log("Found subpaths", subpaths);
const chunks: Chunk[] = [];
const embeddings: number[][] = [];
let markdownForSubpaths = await Promise.all(
subpaths.map((subpath) => convertURLToMarkdown(new URL(subpath, baseUrl)))
);
// Filter out undefineds
let filteredSubpaths: string[] = [];
let filteredMarkdown: string[] = [];
for (let i = 0; i < subpaths.length; i++) {
if (markdownForSubpaths[i]) {
filteredSubpaths.push(subpaths[i]);
filteredMarkdown.push(markdownForSubpaths[i]!);
}
}
subpaths = filteredSubpaths;
markdownForSubpaths = filteredMarkdown;
for (let i = 0; i < subpaths.length; i++) {
const subpath = subpaths[i];
yield {
progress: 1 / (subpaths.length + 1),
desc: `${subpath}`,
};
const markdown = markdownForSubpaths[i]!;
const markdownChunks: ChunkWithoutID[] = [];
for await (const chunk of markdownChunker(markdown, MAX_CHUNK_SIZE, 0)) {
markdownChunks.push(chunk);
}
const subpathEmbeddings = await embeddingsProvider.embed(
markdownChunks.map((chunk) => chunk.content)
);
markdownChunks.forEach((chunk, index) => {
chunks.push({
...chunk,
filepath:
subpath +
(chunk.otherMetadata?.fragment
? `#${chunk.otherMetadata.fragment}`
: ""),
index,
digest: subpath,
});
});
embeddings.push(...subpathEmbeddings);
}
await addDocs(title, baseUrl, chunks, embeddings);
yield {
progress: 1,
desc: "Done",
};
}

View file

@ -0,0 +1,94 @@
import { Octokit } from "@octokit/rest";
import { NodeHtmlMarkdown, PostProcessResult } from "node-html-markdown";
const nhm = new NodeHtmlMarkdown(
{},
{
a: {
postprocess: (ctx) => {
if (ctx.node.tagName === "A") {
// Remove sections links (e.g. '<a href="#section-name" title="Link to this heading">#</a>')
if (ctx.content.length <= 1) {
return PostProcessResult.RemoveNode;
}
}
return ctx.content;
},
},
},
undefined
);
const STRIP_BEFORE = ["\n# "];
const STRIP_AFTER_AND_INCLUDING = ["Was this page helpful?"];
const octokit = new Octokit({
auth: undefined,
});
async function retrieveGitHubBlob(url: URL): Promise<string | undefined> {
const [_, owner, repo, _tree, _main, ...path] = url.pathname.split("/");
const response = await octokit.repos.getContent({
owner,
repo,
path: path.join("/"),
});
if (response.status !== 200) {
return undefined;
}
const content = Buffer.from(
(response.data as any).content || "",
"base64"
).toString();
const fileExtension = url.pathname.split(".").slice(-1)[0];
if (fileExtension === "md") {
return content;
}
return `\`\`\`${fileExtension} title=${path.join("/")}\n${content}\n\`\`\``;
}
export async function convertURLToMarkdown(
url: URL
): Promise<string | undefined> {
try {
if (url.hostname === "github.com") {
return await retrieveGitHubBlob(url);
}
const response = await fetch(url);
if (!response.ok) {
return undefined;
}
const htmlContent = await response.text();
let markdown = nhm.translate(htmlContent).trimEnd();
// Check for 404
if (markdown.includes("404 Not Found")) {
return undefined;
}
// Strip above and below certain phrases
STRIP_BEFORE.forEach((phrase) => {
const index = markdown.indexOf(phrase);
if (index !== -1) {
markdown = markdown.slice(index);
}
});
STRIP_AFTER_AND_INCLUDING.forEach((phrase) => {
const index = markdown.lastIndexOf(phrase);
if (index !== -1) {
markdown = markdown.slice(0, index);
}
});
return markdown;
} catch (err) {
console.error("Error converting URL to markdown", err);
return undefined;
}
}

View file

@ -1,6 +1,7 @@
import crypto from "crypto";
import { Database, open } from "sqlite";
import sqlite3 from "sqlite3";
import { IndexingProgressUpdate } from "..";
import { getIndexSqlitePath } from "../util/paths";
import {
CodebaseIndex,
@ -323,7 +324,7 @@ export class GlobalCacheCodeBaseIndex implements CodebaseIndex {
tag: IndexTag,
results: RefreshIndexResults,
_: MarkCompleteCallback
): AsyncGenerator<{ progress: number; desc: string }> {
): AsyncGenerator<IndexingProgressUpdate> {
const add = [...results.compute, ...results.addTag];
const remove = [...results.del, ...results.removeTag];
await Promise.all([

View file

@ -1,3 +1,5 @@
import { IndexingProgressUpdate } from "..";
export enum IndexResultType {
Compute = "compute",
Delete = "del",
@ -16,7 +18,7 @@ export interface CodebaseIndex {
tag: IndexTag,
results: RefreshIndexResults,
markComplete: MarkCompleteCallback
): AsyncGenerator<{ progress: number; desc: string }>;
): AsyncGenerator<IndexingProgressUpdate>;
}
export type PathAndCacheKey = {

View file

@ -1,7 +1,10 @@
const DEFAULT_MAX_TOKENS = 1000;
const DEFAULT_MAX_TOKENS = 1024;
const DEFAULT_CONTEXT_LENGTH = 4096;
const DEFAULT_TEMPERATURE = 0.5;
const DEFAULT_ARGS = {
max_tokens: DEFAULT_MAX_TOKENS,
temperature: 0.5,
maxTokens: DEFAULT_MAX_TOKENS,
temperature: DEFAULT_TEMPERATURE,
};
const CONTEXT_LENGTH_FOR_MODEL: { [name: string]: number } = {
@ -19,10 +22,14 @@ const CONTEXT_LENGTH_FOR_MODEL: { [name: string]: number } = {
const TOKEN_BUFFER_FOR_SAFETY = 350;
const PROXY_URL = "http://localhost:65433";
const MAX_CHUNK_SIZE = 500; // 512 - buffer for safety (in case of differing tokenizers)
export {
CONTEXT_LENGTH_FOR_MODEL,
DEFAULT_ARGS,
DEFAULT_CONTEXT_LENGTH,
DEFAULT_MAX_TOKENS,
MAX_CHUNK_SIZE,
PROXY_URL,
TOKEN_BUFFER_FOR_SAFETY,
};

View file

@ -1,16 +1,25 @@
import { ChatHistory, ChatMessage } from "..";
import { ChatHistory, ChatMessage, MessagePart } from "..";
export function constructMessages(history: ChatHistory): ChatMessage[] {
const msgs: ChatMessage[] = [];
const msgs = [];
for (const historyItem of history) {
for (const ctxItem of historyItem.contextItems) {
msgs.push({
role: historyItem.message.role,
content: ctxItem.content,
});
}
msgs.push(historyItem.message);
for (let i = 0; i < history.length; i++) {
const historyItem = history[i];
let content = Array.isArray(historyItem.message.content)
? historyItem.message.content
: [{ type: "text", text: historyItem.message.content } as MessagePart];
const ctxItems = historyItem.contextItems.map((ctxItem) => {
return { type: "text", text: ctxItem.content + "\n" } as MessagePart;
});
content = [...ctxItems, ...content];
msgs.push({
role: historyItem.message.role,
content,
});
}
return msgs;

View file

@ -1,5 +1,5 @@
import { encodingForModel as _encodingForModel, Tiktoken } from "js-tiktoken";
import { ChatMessage } from "..";
import { ChatMessage, MessageContent, MessagePart } from "..";
import { TOKEN_BUFFER_FOR_SAFETY } from "./constants";
let encoding: Tiktoken | null = null;
@ -13,9 +13,25 @@ function encodingForModel(modelName: string): Tiktoken {
return encoding;
}
function countTokens(content: string, modelName: string): number {
function countImageTokens(content: MessagePart): number {
if (content.type === "imageUrl") {
return 85;
} else {
throw new Error("Non-image content type");
}
}
function countTokens(content: MessageContent, modelName: string): number {
const encoding = encodingForModel(modelName);
return encoding.encode(content, "all", []).length;
if (Array.isArray(content)) {
return content.reduce((acc, part) => {
return acc + part.type === "imageUrl"
? countImageTokens(part)
: encoding.encode(part.text || "", "all", []).length;
}, 0);
} else {
return encoding.encode(content, "all", []).length;
}
}
function flattenMessages(msgs: ChatMessage[]): ChatMessage[] {
@ -34,6 +50,17 @@ function flattenMessages(msgs: ChatMessage[]): ChatMessage[] {
return flattened;
}
export function stripImages(content: MessageContent): string {
if (Array.isArray(content)) {
return content
.filter((part) => part.type === "text")
.map((part) => part.text)
.join("\n");
} else {
return content;
}
}
function countChatMessageTokens(
modelName: string,
chatMessage: ChatMessage
@ -97,8 +124,12 @@ function pruneRawPromptFromBottom(
return pruneStringFromBottom(modelName, maxTokens, prompt);
}
function summarize(message: string): string {
return message.substring(0, 100) + "...";
function summarize(message: MessageContent): string {
if (Array.isArray(message)) {
return stripImages(message).substring(0, 100) + "...";
} else {
return message.substring(0, 100) + "...";
}
}
function pruneChatHistory(
@ -129,7 +160,7 @@ function pruneChatHistory(
for (let i = 0; i < longerThanOneThird.length; i++) {
// Prune line-by-line from the top
const message = longerThanOneThird[i];
let lines = message.content.split("\n");
let lines = stripImages(message.content).split("\n");
let tokensRemoved = 0;
while (
tokensRemoved < distanceFromThird[i] &&
@ -190,7 +221,7 @@ function pruneChatHistory(
message.content = pruneRawPromptFromTop(
modelName,
contextLength,
message.content,
stripImages(message.content),
tokensForCompletion
);
totalTokens = contextLength;
@ -204,6 +235,7 @@ function compileChatMessages(
msgs: ChatMessage[] | undefined = undefined,
contextLength: number,
maxTokens: number,
supportsImages: boolean,
prompt: string | undefined = undefined,
functions: any[] | undefined = undefined,
systemMessage: string | undefined = undefined
@ -241,6 +273,16 @@ function compileChatMessages(
);
}
// If images not supported, convert MessagePart[] to string
if (!supportsImages) {
for (const msg of msgsCopy) {
if ("content" in msg && Array.isArray(msg.content)) {
const content = stripImages(msg.content);
msg.content = content;
}
}
}
const history = pruneChatHistory(
modelName,
msgsCopy,

View file

@ -10,10 +10,11 @@ import {
RequestOptions,
TemplateType,
} from "..";
import {
CONTEXT_LENGTH_FOR_MODEL,
DEFAULT_ARGS
DEFAULT_ARGS,
DEFAULT_CONTEXT_LENGTH,
DEFAULT_MAX_TOKENS,
} from "./constants";
import {
compileChatMessages,
@ -53,6 +54,25 @@ const PROVIDER_HANDLES_TEMPLATING: ModelProvider[] = [
"ollama",
];
const PROVIDER_SUPPORTS_IMAGES: ModelProvider[] = ["openai", "ollama"];
export function modelSupportsImages(
provider: ModelProvider,
model: string
): boolean {
if (!PROVIDER_SUPPORTS_IMAGES.includes(provider)) {
return false;
}
if (model.includes("llava")) {
return true;
}
if (["gpt-4-vision-preview"].includes(model)) {
return true;
}
return false;
}
function autodetectTemplateType(model: string): TemplateType | undefined {
const lower = model.toLowerCase();
@ -202,6 +222,10 @@ export abstract class BaseLLM implements ILLM {
return (this.constructor as typeof BaseLLM).providerName;
}
supportsImages(): boolean {
return modelSupportsImages(this.providerName, this.model);
}
uniqueId: string;
model: string;
@ -243,11 +267,11 @@ export abstract class BaseLLM implements ILLM {
this.uniqueId = options.uniqueId || "None";
this.model = options.model;
this.systemMessage = options.systemMessage;
this.contextLength = options.contextLength || 4096;
this.contextLength = options.contextLength || DEFAULT_CONTEXT_LENGTH;
this.completionOptions = {
...options.completionOptions,
model: options.model || "gpt-4",
maxTokens: options.completionOptions?.maxTokens || 1024,
maxTokens: options.completionOptions?.maxTokens || DEFAULT_MAX_TOKENS,
};
this.requestOptions = options.requestOptions;
this.promptTemplates = {
@ -286,14 +310,16 @@ export abstract class BaseLLM implements ILLM {
options.model !== this.model &&
options.model in CONTEXT_LENGTH_FOR_MODEL
) {
contextLength = CONTEXT_LENGTH_FOR_MODEL[options.model] || 4096;
contextLength =
CONTEXT_LENGTH_FOR_MODEL[options.model] || DEFAULT_CONTEXT_LENGTH;
}
return compileChatMessages(
options.model,
messages,
contextLength,
options.maxTokens,
options.maxTokens || DEFAULT_MAX_TOKENS,
this.supportsImages(),
undefined,
functions,
this.systemMessage
@ -405,7 +431,7 @@ export abstract class BaseLLM implements ILLM {
completionOptions.model,
this.contextLength,
prompt,
completionOptions.maxTokens
completionOptions.maxTokens || DEFAULT_MAX_TOKENS
);
if (!raw) {
@ -440,7 +466,7 @@ export abstract class BaseLLM implements ILLM {
completionOptions.model,
this.contextLength,
prompt,
completionOptions.maxTokens
completionOptions.maxTokens || DEFAULT_MAX_TOKENS
);
if (!raw) {

View file

@ -1,4 +1,4 @@
import socketIOClient, { Socket } from 'socket.io-client';
import socketIOClient, { Socket } from "socket.io-client";
import { BaseLLM } from "..";
import {
ChatMessage,
@ -6,6 +6,7 @@ import {
LLMOptions,
ModelProvider,
} from "../..";
import { stripImages } from "../countTokens";
interface IFlowiseApiOptions {
/** Sampling temperature to use */
@ -39,7 +40,7 @@ interface IFlowiseSocketManager {
hasNextTokenPromiseResolve: (value: boolean | PromiseLike<boolean>) => void;
hasNextTokenPromiseReject: (reason?: any) => void;
messageHistory: string[];
}
};
error?: Error;
getCurrentMessage: () => string;
}
@ -61,8 +62,8 @@ class Flowise extends BaseLLM {
apiBase: "http://localhost:3000",
};
static FlowiseMessageType = {
User: 'userMessage',
Assistant: 'apiMessage'
User: "userMessage",
Assistant: "apiMessage",
};
protected additionalFlowiseConfiguration: IFlowiseKeyValueProperty[] = [];
@ -73,7 +74,8 @@ class Flowise extends BaseLLM {
super(options);
this.timeout = options.timeout ?? 5000;
this.additionalHeaders = options.additionalHeaders ?? [];
this.additionalFlowiseConfiguration = options.additionalFlowiseConfiguration ?? [];
this.additionalFlowiseConfiguration =
options.additionalFlowiseConfiguration ?? [];
}
private _getChatUrl(): string {
@ -86,11 +88,11 @@ class Flowise extends BaseLLM {
private _getHeaders(): HeadersInit | undefined {
const headers: HeadersInit = {
"Content-Type": "application/json"
"Content-Type": "application/json",
};
if (this.apiKey) {
headers['Authorization'] = `Bearer ${this.apiKey}`;
headers["Authorization"] = `Bearer ${this.apiKey}`;
}
for (const additionalHeader of this.additionalHeaders) {
@ -118,44 +120,53 @@ class Flowise extends BaseLLM {
protected async *_streamComplete(
prompt: string,
options: CompletionOptions,
options: CompletionOptions
): AsyncGenerator<string> {
const message: ChatMessage = { role: "user", content: prompt };
for await (const chunk of this._streamChat([message], options)) {
yield chunk.content;
yield stripImages(chunk.content);
}
}
protected async *_streamChat(messages: ChatMessage[], options: CompletionOptions): AsyncGenerator<ChatMessage> {
protected async *_streamChat(
messages: ChatMessage[],
options: CompletionOptions
): AsyncGenerator<ChatMessage> {
const requestBody = this._getRequestBody(messages, options);
const { socket, socketInfo } = await this._initializeSocket();
const request = this.fetch(this._getChatUrl(), {
method: "POST",
headers: this._getHeaders(),
body: JSON.stringify({ ...requestBody, socketIOClientId: socket.id })
}).then(res => res.json());
body: JSON.stringify({ ...requestBody, socketIOClientId: socket.id }),
}).then((res) => res.json());
while (await socketInfo.hasNextToken()) {
yield { role: 'assistant', content: socketInfo.getCurrentMessage() };
yield { role: "assistant", content: socketInfo.getCurrentMessage() };
}
if (socketInfo.error) {
socket.disconnect();
try {
yield { role: 'assistant', content: (await request).text };
yield { role: "assistant", content: (await request).text };
} catch (error: any) {
yield { role: 'assistant', content: (error as Error).message ?? error };
yield { role: "assistant", content: (error as Error).message ?? error };
}
}
socket.disconnect();
}
protected _getRequestBody(messages: ChatMessage[], options: CompletionOptions): any {
protected _getRequestBody(
messages: ChatMessage[],
options: CompletionOptions
): any {
const lastMessage = messages[messages.length - 1];
const history = messages
.filter(m => m !== lastMessage)
.map(m => ({
type: m.role === 'user' ? Flowise.FlowiseMessageType.User : Flowise.FlowiseMessageType.Assistant,
message: m.content
.filter((m) => m !== lastMessage)
.map((m) => ({
type:
m.role === "user"
? Flowise.FlowiseMessageType.User
: Flowise.FlowiseMessageType.Assistant,
message: m.content,
}));
const requestBody = {
question: lastMessage.content,
@ -165,54 +176,66 @@ class Flowise extends BaseLLM {
return requestBody;
}
protected _initializeSocket(): Promise<{ socket: Socket, socketInfo: IFlowiseSocketManager }> {
protected _initializeSocket(): Promise<{
socket: Socket;
socketInfo: IFlowiseSocketManager;
}> {
return new Promise((res, rej) => {
const socket = socketIOClient(this._getSocketUrl());
const socketInfo: IFlowiseSocketManager = {
isConnected: false,
hasNextToken: () => Promise.resolve(false),
internal: { hasNextTokenPromiseResolve: () => { }, hasNextTokenPromiseReject: () => { }, messageHistory: [] },
getCurrentMessage: () => ''
internal: {
hasNextTokenPromiseResolve: () => {},
hasNextTokenPromiseReject: () => {},
messageHistory: [],
},
getCurrentMessage: () => "",
};
socketInfo.getCurrentMessage = () => socketInfo.internal.messageHistory.shift() ?? ''
socketInfo.getCurrentMessage = () =>
socketInfo.internal.messageHistory.shift() ?? "";
socketInfo.hasNextToken = () => {
return new Promise<boolean>((hasNextTokenResolve, hasNextTokenReject) => {
socketInfo.internal.hasNextTokenPromiseResolve = hasNextTokenResolve;
socketInfo.internal.hasNextTokenPromiseReject = hasNextTokenReject;
});
return new Promise<boolean>(
(hasNextTokenResolve, hasNextTokenReject) => {
socketInfo.internal.hasNextTokenPromiseResolve =
hasNextTokenResolve;
socketInfo.internal.hasNextTokenPromiseReject = hasNextTokenReject;
}
);
};
const resetTimeout = () => {
clearTimeout(socketInfo.internal.timeout);
socketInfo.internal.timeout = setTimeout(() => {
socketInfo.error = new Error('Timeout occurred');
socketInfo.error = new Error("Timeout occurred");
socketInfo.internal.hasNextTokenPromiseResolve(false);
rej(`Timeout trying to connect to socket: ${this._getSocketUrl()}`);
}, this.timeout);
};
resetTimeout();
socket.on('connect', () => {
socket.on("connect", () => {
socketInfo.isConnected = true;
resetTimeout();
res({ socket, socketInfo });
});
socket.on('token', (token) => {
socket.on("token", (token) => {
if (socketInfo.isConnected) {
socketInfo.internal.messageHistory.push(token);
resetTimeout();
socketInfo.internal.hasNextTokenPromiseResolve(true);
}
});
socket.on('error', (error) => {
socket.on("error", (error) => {
clearTimeout(socketInfo.internal.timeout);
socketInfo.error = error;
socketInfo.internal.hasNextTokenPromiseResolve(false);
rej(`Error trying to connect to socket: ${this._getSocketUrl()}`);
});
socket.on('end', () => {
socket.on("end", () => {
clearTimeout(socketInfo.internal.timeout);
socketInfo.hasNextToken = () => Promise.resolve(Boolean(socketInfo.internal.messageHistory.length));
socketInfo.hasNextToken = () =>
Promise.resolve(Boolean(socketInfo.internal.messageHistory.length));
});
socket.on('disconnect', () => {
socket.on("disconnect", () => {
socketInfo.isConnected = false;
clearTimeout(socketInfo.internal.timeout);
socketInfo.internal.hasNextTokenPromiseResolve(false);
@ -221,4 +244,4 @@ class Flowise extends BaseLLM {
}
}
export default Flowise;
export default Flowise;

View file

@ -15,11 +15,23 @@ class FreeTrial extends BaseLLM {
};
}
private _convertArgs(options: CompletionOptions): any {
return {
model: options.model,
frequency_penalty: options.frequencyPenalty,
presence_penalty: options.presencePenalty,
max_tokens: options.maxTokens,
stop: options.stop,
temperature: options.temperature,
top_p: options.topP,
};
}
protected async *_streamComplete(
prompt: string,
options: CompletionOptions
): AsyncGenerator<string> {
const args = this.collectArgs(options);
const args = this._convertArgs(this.collectArgs(options));
const response = await this.fetch(`${SERVER_URL}/stream_complete`, {
method: "POST",
@ -39,7 +51,7 @@ class FreeTrial extends BaseLLM {
messages: ChatMessage[],
options: CompletionOptions
): AsyncGenerator<ChatMessage> {
const args = this.collectArgs(options);
const args = this._convertArgs(this.collectArgs(options));
const response = await this.fetch(`${SERVER_URL}/stream_chat`, {
method: "POST",

View file

@ -5,6 +5,7 @@ import {
LLMOptions,
ModelProvider,
} from "../..";
import { stripImages } from "../countTokens";
class Gemini extends BaseLLM {
static providerName: ModelProvider = "gemini";
@ -22,7 +23,7 @@ class Gemini extends BaseLLM {
[{ role: "user", content: prompt }],
options
)) {
yield chunk.content;
yield stripImages(chunk.content);
}
}

View file

@ -5,6 +5,7 @@ import {
LLMOptions,
ModelProvider,
} from "../..";
import { stripImages } from "../countTokens";
import { streamResponse } from "../stream";
class GooglePalm extends BaseLLM {
@ -22,7 +23,7 @@ class GooglePalm extends BaseLLM {
[{ content: prompt, role: "user" }],
options
)) {
yield message.content;
yield stripImages(message.content);
}
}

View file

@ -14,6 +14,7 @@ class LlamaCpp extends BaseLLM {
frequency_penalty: options.frequencyPenalty,
presence_penalty: options.presencePenalty,
min_p: options.minP,
mirostat: options.mirostat,
};
return finalOptions;
@ -25,7 +26,7 @@ class LlamaCpp extends BaseLLM {
): AsyncGenerator<string> {
const headers = {
"Content-Type": "application/json",
"Authorization": `Bearer ${this.apiKey}`,
Authorization: `Bearer ${this.apiKey}`,
...this.requestOptions?.headers,
};

View file

@ -5,6 +5,7 @@ import {
LLMOptions,
ModelProvider,
} from "../..";
import { stripImages } from "../countTokens";
import { streamResponse } from "../stream";
class Ollama extends BaseLLM {
@ -81,6 +82,20 @@ class Ollama extends BaseLLM {
);
}
private _convertMessage(message: ChatMessage) {
if (typeof message.content === "string") {
return message;
}
return {
role: message.role,
content: stripImages(message.content),
images: message.content
.filter((part) => part.type === "imageUrl")
.map((part) => part.imageUrl?.url.split(",").at(-1)),
};
}
private _convertArgs(
options: CompletionOptions,
prompt: string | ChatMessage[]
@ -95,13 +110,14 @@ class Ollama extends BaseLLM {
num_predict: options.maxTokens,
stop: options.stop,
num_ctx: this.contextLength,
mirostat: options.mirostat,
},
};
if (typeof prompt === "string") {
finalOptions.prompt = prompt;
} else {
finalOptions.messages = prompt;
finalOptions.messages = prompt.map(this._convertMessage);
}
return finalOptions;

View file

@ -1,4 +1,3 @@
import { ChatCompletionCreateParamsBase } from "openai/resources/chat/completions";
import { BaseLLM } from "..";
import {
ChatMessage,
@ -6,6 +5,7 @@ import {
LLMOptions,
ModelProvider,
} from "../..";
import { stripImages } from "../countTokens";
import { streamSse } from "../stream";
const NON_CHAT_MODELS = [
@ -27,12 +27,27 @@ class OpenAI extends BaseLLM {
apiBase: "https://api.openai.com",
};
protected _convertArgs(
options: any,
messages: ChatMessage[]
): ChatCompletionCreateParamsBase {
const finalOptions: ChatCompletionCreateParamsBase = {
messages,
protected _convertMessage(message: ChatMessage) {
if (typeof message.content === "string") {
return message;
}
const parts = message.content.map((part) => {
return {
type: part.type,
text: part.text,
image_url: { ...part.imageUrl, detail: "low" },
};
});
return {
...message,
content: parts,
};
}
protected _convertArgs(options: any, messages: ChatMessage[]) {
const finalOptions = {
messages: messages.map(this._convertMessage),
model: options.model,
max_tokens: options.maxTokens,
temperature: options.temperature,
@ -87,7 +102,7 @@ class OpenAI extends BaseLLM {
[{ role: "user", content: prompt }],
options
)) {
yield chunk.content;
yield stripImages(chunk.content);
}
}
@ -152,7 +167,7 @@ class OpenAI extends BaseLLM {
): AsyncGenerator<ChatMessage> {
if (NON_CHAT_MODELS.includes(options.model)) {
for await (const content of this._legacystreamComplete(
messages[messages.length - 1]?.content || "",
stripImages(messages[messages.length - 1]?.content || ""),
options
)) {
yield {

View file

@ -6,6 +6,7 @@ import {
LLMOptions,
ModelProvider,
} from "../..";
import { stripImages } from "../countTokens";
class Replicate extends BaseLLM {
private static MODEL_IDS: {
@ -72,7 +73,10 @@ class Replicate extends BaseLLM {
messages: ChatMessage[],
options: CompletionOptions
): AsyncGenerator<ChatMessage> {
const resp = await this.complete(messages[0]?.content || "", options);
const resp = await this.complete(
stripImages(messages[0]?.content || ""),
options
);
}
}

View file

@ -6,6 +6,7 @@ import {
LLMOptions,
ModelDescription,
} from "../..";
import { DEFAULT_MAX_TOKENS } from "../constants";
import Anthropic from "./Anthropic";
import Bedrock from "./Bedrock";
import DeepInfra from "./DeepInfra";
@ -125,7 +126,7 @@ export async function llmFromDescription(
maxTokens:
finalCompletionOptions.maxTokens ||
cls.defaultOptions?.completionOptions?.maxTokens ||
1024,
DEFAULT_MAX_TOKENS,
},
systemMessage,
};

View file

@ -1,4 +1,5 @@
import { ChatMessage } from "../..";
import { stripImages } from "../countTokens";
function llama2TemplateMessages(msgs: ChatMessage[]): string {
if (msgs.length === 0) {
@ -14,7 +15,7 @@ function llama2TemplateMessages(msgs: ChatMessage[]): string {
let prompt = "";
let hasSystem = msgs[0].role === "system";
if (hasSystem && msgs[0].content.trim() === "") {
if (hasSystem && stripImages(msgs[0].content).trim() === "") {
hasSystem = false;
msgs = msgs.slice(1);
}
@ -123,7 +124,7 @@ function deepseekTemplateMessages(msgs: ChatMessage[]): string {
prompt +=
"You are an AI programming assistant, utilizing the DeepSeek Coder model, developed by DeepSeek Company, and you only answer questions related to computer science. For politically sensitive questions, security and privacy issues, and other non-computer science questions, you will refuse to answer.\n";
if (msgs[0].role === "system") {
system = msgs.shift()!.content;
system = stripImages(msgs.shift()!.content);
}
for (let i = 0; i < msgs.length; i++) {

838
core/package-lock.json generated

File diff suppressed because it is too large Load diff

View file

@ -10,20 +10,21 @@
"devDependencies": {
"@types/handlebars": "^4.1.0",
"@types/jest": "^29.5.11",
"@types/jquery": "^3.5.29",
"@types/mustache": "^4.2.5",
"@types/uuid": "^9.0.7",
"esbuild": "^0.19.11",
"jest": "^29.7.0",
"ts-jest": "^29.1.1"
},
"dependencies": {
"@octokit/rest": "^20.0.2",
"@types/node-fetch": "^2.6.11",
"@xenova/transformers": "^2.14.0",
"cheerio": "^1.0.0-rc.12",
"dotenv": "^16.3.1",
"fastest-levenshtein": "^1.0.16",
"handlebars": "^4.7.8",
"js-tiktoken": "^1.0.8",
"node-fetch": "^3.3.2",
"node-html-markdown": "^1.3.0",
"openai": "^4.20.1",
"replicate": "^0.23.0",
@ -34,5 +35,8 @@
"uuid": "^9.0.1",
"vectordb": "^0.4.3",
"web-tree-sitter": "^0.20.8"
},
"puppeteer": {
"chromium_revision": "119.0.6045.105"
}
}

View file

@ -63,6 +63,11 @@ export function dedentAndGetCommonWhitespace(s: string): [string, string] {
if (lines[i].trim() === "") {
continue; // hey that's us!
}
if (lcp === undefined) {
lcp = lines[i].split(lines[i].trim())[0];
}
// Iterate through the leading whitespace characters of the current line
for (let j = 0; j < lcp.length; j++) {
// If it doesn't have the same whitespace as lcp, then update lcp
@ -76,6 +81,10 @@ export function dedentAndGetCommonWhitespace(s: string): [string, string] {
}
}
if (lcp === undefined) {
return [s, ""];
}
return [lines.map((x) => x.replace(lcp, "")).join("\n"), lcp];
}
@ -111,6 +120,10 @@ export function getBasename(filepath: string): string {
return filepath.split(/[\\/]/).pop() || "";
}
export function getLastNPathParts(filepath: string, n: number): string {
return filepath.split(/[\\/]/).slice(-n).join("/");
}
export function getMarkdownLanguageTagForFile(filepath: string): string {
const ext = filepath.split(".").pop();
switch (ext) {

View file

@ -106,7 +106,7 @@ export function getTsConfigPath(): string {
target: "ESNext",
useDefineForClassFields: true,
lib: ["DOM", "DOM.Iterable", "ESNext"],
allowJs: false,
allowJs: true,
skipLibCheck: true,
esModuleInterop: false,
allowSyntheticDefaultImports: true,
@ -175,3 +175,7 @@ export function getIndexSqlitePath(): string {
export function getLanceDbPath(): string {
return path.join(getIndexFolderPath(), "lancedb");
}
export function getDocsSqlitePath(): string {
return path.join(getIndexFolderPath(), "docs.sqlite");
}

3932
core/yarn.lock Normal file

File diff suppressed because it is too large Load diff

View file

@ -8,15 +8,13 @@ keywords: [context, "@", provider, LLM]
Context Providers allow you to type '@' and see a dropdown of content that can all be fed to the LLM as context. Every context provider is a plugin, which means if you want to reference some source of information that you don't see here, you can request (or build!) a new context provider.
As an example, say you are working on solving a new GitHub Issue. You type '@issue' and select the one you are working on. Continue can now see the issue title and contents. You also know that the issue is related to the files 'readme.md' and 'helloNested.py', so you type '@readme' and '@hello' to find and select them. Now these 3 "Context Items" are displayed above the input.
As an example, say you are working on solving a new GitHub Issue. You type '@issue' and select the one you are working on. Continue can now see the issue title and contents. You also know that the issue is related to the files 'readme.md' and 'helloNested.py', so you type '@readme' and '@hello' to find and select them. Now these 3 "Context Items" are displayed inline with the rest of your input.
![Context Items](/img/context-provider-example.png)
When you enter your next input, Continue will see the full contents of each of these items, and can use them to better answer your questions throughout the conversation.
## Built-in Context Providers
To use any of the built-in context providers, open `~/.continue/config.json` (can do this with the '/config' slash command) and add it to the `contextProviders` list.
To use any of the built-in context providers, open `~/.continue/config.json` and add it to the `contextProviders` list.
### Git Diff
@ -36,34 +34,39 @@ Type '@terminal' to reference the contents of your IDE's terminal.
### Open Files
Type '@open' to reference the contents of all of your open files.
Type '@open' to reference the contents of all of your open files. Set `onlyPinned` to `true` to only reference pinned files.
```json
{ "name": "open" }
{ "name": "open", "params": { "onlyPinned": true } }
```
### Codebase Search
### Codebase Retrieval
Type '@search' to reference the results of codebase search, just like the results you would get from VS Code search.
Type '@codebase' to automatically retrieve the most relevant snippets from your codebase. Read more about indexing and retrieval [here](../walkthroughs/codebase-embeddings.md).
```json
{ "name": "codebase" }
```
### Folders
Type '@folder' to use the same retrieval mechanism as '@codebase', but only on a single folder.
```json
{ "name": "folder" }
```
### Exact Search
Type '@search' to reference the results of codebase search, just like the results you would get from VS Code search. This context provider is powered by [ripgrep](https://github.com/BurntSushi/ripgrep).
```json
{ "name": "search" }
```
### URLs
Type '@url' to reference the contents of a URL. You can either reference preset URLs, or reference one dynamically by typing '@url https://example.com'. The text contents of the page will be fetched and used as context.
```json
{
"name": "url",
"params": { "presetUrls": ["https://continue.dev/docs/customization"] }
}
```
### File Tree
Type '@tree' to reference the contents of your current workspace. The LLM will be able to see the nested directory structure of your project.
Type '@tree' to reference the structure of your current workspace. The LLM will be able to see the nested directory structure of your project.
```json
{ "name": "tree" }
@ -82,17 +85,21 @@ Type '@google' to reference the results of a Google search. For example, type "@
Note: You can get an API key for free at [serper.dev](https://serper.dev).
### GitHub
### GitHub Issues
Type '@issue' to reference the title and contents of a GitHub issue.
Type '@issue' to reference the conversation in a GitHub issue. Make sure to include your own [GitHub personal access token](https://docs.github.com/en/authentication/keeping-your-account-and-data-secure/managing-your-personal-access-tokens#creating-a-fine-grained-personal-access-token) to avoid being rate-limited:
```json
{
"name": "github",
"name": "issue",
"params": {
// Change to whichever repo you want to use
"repoName": "continuedev/continue",
"authToken": "<my_github_auth_token>"
"repos": [
{
"owner": "continuedev",
"repo": "continue"
}
],
"githubToken": "ghp_xxx"
}
}
```
@ -103,6 +110,8 @@ Not seeing what you want? Create an issue [here](https://github.com/continuedev/
## Building Your Own Context Provider
> Currently custom context providers are only supported in VS Code, but are coming soon to JetBrains IDEs.
### Introductory Example
To write your own context provider, you just have to implement the `CustomContextProvider`
@ -113,20 +122,26 @@ interface CustomContextProvider {
title: string;
displayTitle?: string;
description?: string;
getContextItems(query: string, fullInput: string): Promise<ContextItem[]>;
getContextItems(
query: string,
extras: ContextProviderExtras
): Promise<ContextItem[]>;
}
```
As an example, let's say you have a set of internal documents that have been indexed in a vector database. You've set up a simple REST API that allows internal users to query and get back relevant snippets. This context provider will send the query to this server and return the results from the vector database.
```typescript
const RagContextProvider = {
```typescript title="~/.continue/config.ts"
const RagContextProvider: CustomContextProvider = {
title: "rag",
displayTitle: "RAG",
description:
"Retrieve snippets from our vector database of internal documents",
getContextItems: async (query: string, fullInput: string) => {
getContextItems: async (
query: string,
extras: ContextProviderExtras
): Promise<ContextItem[]> => {
const response = await fetch("https://internal_rag_server.com/retrieve", {
method: "POST",
body: JSON.stringify({ query }),
@ -135,7 +150,7 @@ const RagContextProvider = {
const results = await response.json();
return results.map((result) => ({
title: result.title,
name: result.title,
description: result.title,
content: result.contents,
}));
@ -147,7 +162,32 @@ It can then be added in `config.ts` like so:
```typescript title="~/.continue/config.ts"
export function modifyConfig(config: Config): Config {
config.contextProviders.append(RagContextProvider);
if (!config.contextProviders) {
config.contextProviders = [];
}
config.contextProviders.push(RagContextProvider);
return config;
}
```
No modification in `config.json` is necessary.
### Importing outside modules
> Context providers run in a NodeJS environment, but for the time being the `modifyConfig` function will be called both from NodeJS _and_ the browser. This means that if you are importing packages requiring NodeJS, you should dynamically import them inside of the context provider (e.g. `const moduleA = await import('./moduleA');`).
To include outside Node modules in your config.ts, run `npm install <module_name>` from the `~/.continue` directory, and then import them in config.ts.
Continue will use [esbuild](https://esbuild.github.io/) to bundle your `config.ts` and any dependencies into a single Javascript file. The exact configuration used can be found [here](https://github.com/continuedev/continue/blob/5c9874400e223bbc9786a8823614a2e501fbdaf7/extensions/vscode/src/ideProtocol.ts#L45-L52).
### `CustomContextProvider` Reference
- `title`: An identifier for the context provider
- `displayTitle` (optional): The title displayed in the dropdown
- `description` (optional): The longer description displayed in the dropdown when hovered
- `getContextItems`: A function that returns the documents to include in the prompt. It should return a list of `ContextItem`s, and is given access to the following arguments:
- `extras.fullInput`: A string representing the user's full input to the text box. This can be used for example to generate an embedding to compare against a set of other embedded documents
- `extras.embeddingsProvider`: The embeddings provider has an `embed` function that will convert text (such as `fullInput`) to an embedding
- `extras.llm`: The current default LLM, which you can use to make completion requests
- `extras.ide`: An instance of the `IDE` class, which lets you gather various sources of information from the IDE, including the contents of the terminal, the list of open files, or any warnings in the currently open file.
- `query`: (not currently used) A string representing the query

View file

@ -6,13 +6,13 @@ keywords: [temperature, custom policies, custom system message]
# Other Configuration
See the [ContinueConfig Reference](../reference/config) for the full list of configuration options.
See the [config.json Reference](../reference/config) for the full list of configuration options.
## Customize System Message
You can write your own system message, a set of instructions that will always be top-of-mind for the LLM, by setting the `systemMessage` property to any string. For example, you might request "Please make all responses as concise as possible and never repeat something you have already explained."
System messages can also reference files. For example, if there is a markdown file (e.g. at `/Users/nate/Documents/docs/reference.md`) you'd like the LLM to know about, you can reference it with [Mustache](http://mustache.github.io/mustache.5.html) templating like this: "Please reference this documentation: {{ Users/nate/Documents/docs/reference.md }}". As of now, you must use an absolute path.
System messages can also reference files. For example, if there is a markdown file (e.g. at `/Users/nate/Documents/docs/reference.md`) you'd like the LLM to know about, you can reference it with [Mustache](http://mustache.github.io/mustache.5.html) templating like this: "Please reference this documentation: \{\{ Users/nate/Documents/docs/reference.md \}\}". As of now, you must use an absolute path.
## Temperature

View file

@ -11,6 +11,6 @@ Continue can be deeply customized by editing `~/.continue/config.json` (`%userpr
Currently, you can customize the following:
- [Models](../model-setup/select-model.md) and [providers](../model-setup/select-provider.md)
- [Context Providers](./context-providers.md) - Just type '@' to easily add attachments to your prompt. Define which sources you want to easily reference, including GitHub Issues, terminal output, and preset URLs.
- [Context Providers](./context-providers.md) - Type '@' to easily add attachments to your prompt. Define which sources you want to reference, including GitHub Issues, terminal output, or automatically retrieved snippets from your codebase.
- [Slash Commands](./slash-commands.md) - Call custom prompts or programs written with our SDK by typing `/`.
- [Other Configuration](./other-configuration.md) - Configure other settings like the system message and temperature.
- [Other Configuration](../reference/config.mdx) - Configure other settings like the system message and temperature.

View file

@ -6,14 +6,112 @@ keywords: [slash command, custom commands, step]
# Slash Commands
Slash commands are shortcuts that can be activated by prefacing your input with '/'. For example, the built-in '/edit' slash command let you stream edits directly into your editor.
Slash commands are shortcuts that can be activated by typing '/' and selecting from the dropdown. For example, the built-in '/edit' slash command let you stream edits directly into your editor.
![slash-commands](/img/slash-commands.png)
## Built-in Slash Commands
To use any of the built-in slash commands, open `~/.continue/config.json` and add it to the `slashCommands` list.
### `/edit`
Select code with ctrl/cmd + M (VS Code) or ctrl/cmd + J (JetBrains), and then type "/edit", followed by instructions for the edit. Continue will stream the changes into a side-by-side diff editor.
```json
{
"name": "edit",
"description": "Edit highlighted code"
}
```
### `/comment`
Comment works just like /edit, except it will automatically prompt the LLM to comment the code.
```json
{
"name": "comment",
"description": "Write comments for the highlighted code"
}
```
### `/share`
Type "/share" to generate a shareable markdown transcript of your current chat history.
```json
{
"name": "share",
"description": "Download and share this session"
}
```
### `/cmd`
Generate a shell command from natural language and (only in VS Code) automatically paste it into the terminal.
```json
{
"name": "cmd",
"description": "Generate a shell command"
}
```
### `/commit`
Shows the LLM your current git diff and asks it to generate a commit message.
```json
{
"name": "commit",
"description": "Generate a commit message for the current changes"
}
```
### `/http`
Write a custom slash command at your own HTTP endpoint. Set 'url' in the params object for the endpoint you have setup. The endpoint should return a sequence of string updates, which will be streamed to the Continue sidebar. See our basic [FastAPI example](https://github.com/continuedev/continue/blob/74002369a5e435735b83278fb965e004ae38a97d/core/context/providers/context_provider_server.py#L34-L45) for reference.
```json
{
"name": "http",
"description": "Does something custom",
"params": { "url": "<my server endpoint>" }
}
```
### `/issue`
Describe the issue you'd like to generate, and Continue will turn into a well-formatted title and body, then give you a link to the draft so you can submit. Make sure to set the URL of the repository you want to generate issues for.
```json
{
"name": "issue",
"description": "Generate a link to a drafted GitHub issue",
"params": { "repositoryUrl": "https://github.com/continuedev/continue" }
}
```
### `/so`
The StackOverflow slash command will automatically pull results from StackOverflow to answer your question, quoting links along with its answer.
```json
{
"name": "so",
"description": "Reference StackOverflow to answer the question"
}
```
## Custom Slash Commands
There are two ways to add custom slash commands:
1. With natural language prompts - this is simpler and only requires writing a string or string template.
2. With a custom function - this gives you full access to the Continue SDK and allows you to write arbitrary Typescript code.
## "Custom Commands" (Use Natural Language)
### "Custom Commands" (Use Natural Language)
You can add custom slash commands by adding to the `customCommands` property in `config.json`.
@ -31,7 +129,7 @@ customCommands=[{
}]
```
## Custom Slash Commands
### Custom Slash Commands
If you want to go a step further than writing custom commands with natural language, you can write a custom function that returns the response. This requires using `config.ts` instead of `config.json`.

View file

@ -1,5 +1,5 @@
---
title: Development data
title: 🧑‍💻 Development data
description: Collecting data on how you build software
keywords: [development data, dev data, LLM-aided development]
---

View file

@ -1,5 +1,5 @@
---
title: How to use Continue
title: 🧑‍🎓 How to use Continue
description: Using LLMs as you code with Continue
keywords: [how to, edit, refactor, boilerplate, context]
---

View file

@ -1,15 +1,25 @@
---
title: Introduction
title: 💻 Introduction
description: Continue is the open-source autopilot for software development
keywords: [introduction, intro, continue, autopilot, chatgpt]
---
# Introduction
# 💻 Introduction
![continue-cover-logo](/img/continue-cover-logo.png)
**Continue is an open-source autopilot for [VS Code](https://marketplace.visualstudio.com/items?itemName=Continue.continue) and [JetBrains](https://plugins.jetbrains.com/plugin/22707-continue-extension)—the easiest way to code with any LLM**
You determine when Large Language Models (LLMs) like [GPT-4](https://openai.com/research/gpt-4) and [Code Llama](https://about.fb.com/news/2023/08/code-llama-ai-for-coding/) should act as an autopilot, helping you complete software development tasks. You highlight some code and then use natural language instructions (and optional slash commands like `/edit`) to tell the LLM what to do.
Many developers have begun to use ChatGPT while coding; however, the experience is painful because of how much copying, pasting, and editing is required to provide the context and incorporate the generated answers into your codebase. Continue eliminates this pain by enabling LLMs to act natively in your IDE as you complete your workflows.
Many developers have begun to use ChatGPT while coding; however, the experience is painful because of how much copying, pasting, and editing is required to provide the context and incorporate the generated answers into your codebase. Continue eliminates this pain by enabling LLMs to natively act in your IDE as you complete your workflows.
Some examples of what you can achieve are:
- Use cmd/ctrl + shift + L to generate boilerplate code from natural language
- Highlight code, describe how to refactor it, and have changes streamed into your editor
- Ask high-level questions about your codebase, with Continue automatically finding relevant files
- Quickly generate unit tests for any function or class
- Ask a quick question to get immediate answers without leaving your editor
- Have your current changes reviewed for mistakes that the compiler can't catch
- Type '@' to reference dozens of different sources while communicating with the LLM
Continue lets you do all of this with any LLM, whether open-source, commercial, local, or remote. And we provide numerous points of configuration so that you can customize the extension to fit into your existing workflows.

View file

@ -1,18 +1,20 @@
# Overview
Continue is the easiest way to code with any [Large Language Model (LLM)](https://www.youtube.com/watch?v=zjkBMFhNj_g). You can use it with commercial models like GPT-4 via the OpenAI API, open-source models running on your laptop with Ollama like Code Llama, and everything in between. You have the ability to configure what model you use, what provider you use, and how you use them.
Continue is the easiest way to code with any [Large Language Model (LLM)](https://www.youtube.com/watch?v=zjkBMFhNj_g). You can use it with commercial models like GPT-4 via the OpenAI API, open-source models like CodeLlama running on your laptop with Ollama, and everything in between.
When you first install Continue, you can try it out for free using a proxy server that securely makes calls with our API key to models like GPT-4, Gemini Pro, and Phind CodeLlama via OpenAI, Google, and Together respectively.
When you first install Continue, you can try it out for free using a proxy server that securely makes calls with our API keys to models like GPT-4, Gemini Pro, and Phind CodeLlama via OpenAI, Google, and Together respectively.
Once you're ready to use your own API key or a different model / provider, press the `+` button in the bottom left to add a new model to your `config.json`.
If you are unsure what model or provider to use, here is a rule of thumb:
- Use GPT-4 via OpenAI if you want the best possible model overall right now
- Use X via Together if you want the best open-source model right now
- Use X via Ollama if you want to run a model locally on Mac or Linux
- Use X via LM Studio if you want to run a model locally on Windows
Learn more:
- [Select a provider](select-provider.md)
- [Select a model](select-model.md)
- [Configuration](configuration.md)
- [Configuration](configuration.md)

View file

@ -13,6 +13,7 @@ Continue makes it easy to swap out different LLMs. You can either click the "+"
## Open-source LLMs
The default models available in the GUI:
- [Code Llama-Instruct-7B](https://github.com/continuedev/what-llm-to-use/blob/main/README.md#1-code-llama)
- [Code Llama-Instruct-13B](https://github.com/continuedev/what-llm-to-use/blob/main/README.md#1-code-llama)
- [Code Llama-Instruct-34B](https://github.com/continuedev/what-llm-to-use/blob/main/README.md#1-code-llama)
@ -32,15 +33,16 @@ The default models available in the GUI:
- [Zephyr-7B](https://huggingface.co/huggingfaceh4/zephyr-7b-beta)
- [Neural-Chat-7B](https://huggingface.co/Intel/neural-chat-7b-v3-3)
**You can also use other open-source models**, but you will need to manually add them to your `config.json`.
**You can also use other open-source models**, you just need to manually add them to your `config.json`.
## Commercial LLMs
Models available for configuration in the GUI:
- [GPT-4](https://github.com/continuedev/what-llm-to-use/blob/main/README.md#1-gpt-4)
- [GPT-4-Turbo](https://github.com/continuedev/what-llm-to-use/blob/main/README.md#2-gpt-4-turbo)
- [GPT-3.5-Turbo](https://github.com/continuedev/what-llm-to-use/blob/main/README.md#3-gpt-35-turbo)
- [Claude-2](https://github.com/continuedev/what-llm-to-use/blob/main/README.md#4-claude-2)
- [Gemini Pro](https://github.com/continuedev/what-llm-to-use/blob/main/README.md#5-palm-2)
**You can also use other commercial models**, but you will need to manually add them to your `config.json`.
**You can also use other commercial models**, you just need to manually add them to your `config.json`.

View file

@ -33,7 +33,7 @@ You can deploy a model in your [AWS](https://github.com/continuedev/deploy-os-co
- [SkyPilot](https://github.com/continuedev/deploy-os-code-llm#skypilot)
- [Anyscale Private Endpoints](https://github.com/continuedev/deploy-os-code-llm#anyscale-private-endpoints) (OpenAI compatible API)
If the API you use is OpenAI-compatible, you will be able to use the "openai" provider in `config.json` and change the `apiBase` to point to the server. Otherwise, you will need to wire up a new LLM object in `config.ts`. Learn how to do this [here](configuration.md#defining-a-custom-llm-provider)
If the API you use is OpenAI-compatible, you will be able to use the "openai" provider in `config.json` and change the `apiBase` to point to the server. Otherwise, you may need to wire up a new LLM object in `config.ts`. Learn how to do this [here](configuration.md#defining-a-custom-llm-provider)
## SaaS
@ -56,4 +56,4 @@ You can use commercial LLMs via APIs using:
- [Anthrophic API](../reference/Model%20Providers/anthropicllm.md)
- [Google PaLM API](../reference/Model%20Providers/googlepalmapi.md)
- [OpenAI free trial](../reference/Model%20Providers/freetrial.md)
- [Mistral API](../reference/Model%20Providers/mistral.md)
- [Mistral API](../reference/Model%20Providers/mistral.md)

View file

@ -1,17 +1,33 @@
---
title: Quickstart
title: ⚡️ Quickstart
description: Getting started with Continue
keywords: [quickstart, start, install, vscode, jetbrains]
---
# ⚡️ Quickstart
## VS Code
1. Click `Install` on the **[Continue extension in the Visual Studio Marketplace](https://marketplace.visualstudio.com/items?itemName=Continue.continue)**
2. This will open the Continue extension page in VS Code, where you will need to click `Install` again
3. Once you do this, you will see the Continue logo show up on the left side bar. If you click it, then the Continue extension will then open up:
3. Once you do this, you will see the Continue logo show up on the left side bar. If you click it, the Continue extension will open up:
![vscode-install](/img/continue-screenshot.png)
> We strongly recommend moving Continue to VS Code's right sidebar. This helps keep the file explorer open while using Continue, and the sidebar can be toggled with a simple keyboard shortcut. ![move-to-right-sidebar](/img/move-to-right-sidebar.png)
4. If you have any problems, see the [troubleshooting guide](./troubleshooting.md) or ask for help in [our Discord](https://discord.gg/NWtdYexhMs).
## JetBrains
1. Open your JetBrains IDE and open settings using `cmd/ctrl + shift + ,`.
2. Select **Plugins** on the sidebar.
3. Search for "Continue" in the marketplace and click `Install`. Once installed you'll see Continue show up on the right toolbar:
![jetbrains-quickstart](/img/jetbrains-quickstart.png)
4. If you have any problems, see the [troubleshooting guide](./troubleshooting.md) or ask for help in [our Discord](https://discord.gg/NWtdYexhMs).
> Alternatively, you can install from disk after downloading from the [JetBrains Extension Marketplace](https://plugins.jetbrains.com/plugin/22707-continue-extension).

View file

@ -1,21 +0,0 @@
import ClassPropertyRef from '@site/src/components/ClassPropertyRef.tsx';
# DiffContextProvider
Type '@diff' to reference all of the changes you've made to your current branch. This is useful if you want to summarize what you've done or ask for a general review of your work before committing.
[View the source](https://github.com/continuedev/continue/blob/main/server/continuedev/plugins/context_providers/diff.py)
## Properties
<ClassPropertyRef name='workspace_dir' details='{&quot;title&quot;: &quot;Workspace Dir&quot;, &quot;description&quot;: &quot;The workspace directory in which to run `git diff`&quot;, &quot;type&quot;: &quot;string&quot;}' required={false} default=""/>
### Inherited Properties
<ClassPropertyRef name='title' details='{&quot;title&quot;: &quot;Title&quot;, &quot;default&quot;: &quot;diff&quot;, &quot;type&quot;: &quot;string&quot;}' required={false} default="diff"/>
<ClassPropertyRef name='ide' details='{&quot;title&quot;: &quot;Ide&quot;}' required={false} default=""/>
<ClassPropertyRef name='display_title' details='{&quot;title&quot;: &quot;Display Title&quot;, &quot;default&quot;: &quot;Diff&quot;, &quot;type&quot;: &quot;string&quot;}' required={false} default="Diff"/>
<ClassPropertyRef name='description' details='{&quot;title&quot;: &quot;Description&quot;, &quot;default&quot;: &quot;Output of &#x27;git diff&#x27; in current repo&quot;, &quot;type&quot;: &quot;string&quot;}' required={false} default="Output of &#x27;git diff&#x27; in current repo"/>
<ClassPropertyRef name='dynamic' details='{&quot;title&quot;: &quot;Dynamic&quot;, &quot;default&quot;: true, &quot;type&quot;: &quot;boolean&quot;}' required={false} default="True"/>
<ClassPropertyRef name='requires_query' details='{&quot;title&quot;: &quot;Requires Query&quot;, &quot;description&quot;: &quot;Indicates whether the ContextProvider requires a query. For example, the SearchContextProvider requires you to type &#x27;@search &lt;STRING_TO_SEARCH&gt;&#x27;. This will change the behavior of the UI so that it can indicate the expectation for a query.&quot;, &quot;default&quot;: false, &quot;type&quot;: &quot;boolean&quot;}' required={false} default="False"/>

View file

@ -1,20 +0,0 @@
import ClassPropertyRef from '@site/src/components/ClassPropertyRef.tsx';
# FileContextProvider
The FileContextProvider is a ContextProvider that allows you to search files in the open workspace.
[View the source](https://github.com/continuedev/continue/blob/main/server/continuedev/plugins/context_providers/file.py)
## Properties
### Inherited Properties
<ClassPropertyRef name='title' details='{&quot;title&quot;: &quot;Title&quot;, &quot;default&quot;: &quot;file&quot;, &quot;type&quot;: &quot;string&quot;}' required={false} default="file"/>
<ClassPropertyRef name='ide' details='{&quot;title&quot;: &quot;Ide&quot;}' required={false} default=""/>
<ClassPropertyRef name='display_title' details='{&quot;title&quot;: &quot;Display Title&quot;, &quot;default&quot;: &quot;Files&quot;, &quot;type&quot;: &quot;string&quot;}' required={false} default="Files"/>
<ClassPropertyRef name='description' details='{&quot;title&quot;: &quot;Description&quot;, &quot;default&quot;: &quot;Type to search the workspace&quot;, &quot;type&quot;: &quot;string&quot;}' required={false} default="Type to search the workspace"/>
<ClassPropertyRef name='dynamic' details='{&quot;title&quot;: &quot;Dynamic&quot;, &quot;default&quot;: false, &quot;type&quot;: &quot;boolean&quot;}' required={false} default="False"/>
<ClassPropertyRef name='requires_query' details='{&quot;title&quot;: &quot;Requires Query&quot;, &quot;description&quot;: &quot;Indicates whether the ContextProvider requires a query. For example, the SearchContextProvider requires you to type &#x27;@search &lt;STRING_TO_SEARCH&gt;&#x27;. This will change the behavior of the UI so that it can indicate the expectation for a query.&quot;, &quot;default&quot;: false, &quot;type&quot;: &quot;boolean&quot;}' required={false} default="False"/>

View file

@ -1,21 +0,0 @@
import ClassPropertyRef from '@site/src/components/ClassPropertyRef.tsx';
# FileTreeContextProvider
Type '@tree' to reference the contents of your current workspace. The LLM will be able to see the nested directory structure of your project.
[View the source](https://github.com/continuedev/continue/blob/main/server/continuedev/plugins/context_providers/filetree.py)
## Properties
<ClassPropertyRef name='workspace_dir' details='{&quot;title&quot;: &quot;Workspace Dir&quot;, &quot;description&quot;: &quot;The workspace directory to display&quot;, &quot;type&quot;: &quot;string&quot;}' required={false} default=""/>
### Inherited Properties
<ClassPropertyRef name='title' details='{&quot;title&quot;: &quot;Title&quot;, &quot;default&quot;: &quot;tree&quot;, &quot;type&quot;: &quot;string&quot;}' required={false} default="tree"/>
<ClassPropertyRef name='ide' details='{&quot;title&quot;: &quot;Ide&quot;}' required={false} default=""/>
<ClassPropertyRef name='display_title' details='{&quot;title&quot;: &quot;Display Title&quot;, &quot;default&quot;: &quot;File Tree&quot;, &quot;type&quot;: &quot;string&quot;}' required={false} default="File Tree"/>
<ClassPropertyRef name='description' details='{&quot;title&quot;: &quot;Description&quot;, &quot;default&quot;: &quot;Add a formatted file tree of this directory to the context&quot;, &quot;type&quot;: &quot;string&quot;}' required={false} default="Add a formatted file tree of this directory to the context"/>
<ClassPropertyRef name='dynamic' details='{&quot;title&quot;: &quot;Dynamic&quot;, &quot;default&quot;: true, &quot;type&quot;: &quot;boolean&quot;}' required={false} default="True"/>
<ClassPropertyRef name='requires_query' details='{&quot;title&quot;: &quot;Requires Query&quot;, &quot;description&quot;: &quot;Indicates whether the ContextProvider requires a query. For example, the SearchContextProvider requires you to type &#x27;@search &lt;STRING_TO_SEARCH&gt;&#x27;. This will change the behavior of the UI so that it can indicate the expectation for a query.&quot;, &quot;default&quot;: false, &quot;type&quot;: &quot;boolean&quot;}' required={false} default="False"/>

View file

@ -1,22 +0,0 @@
import ClassPropertyRef from '@site/src/components/ClassPropertyRef.tsx';
# GitHubIssuesContextProvider
The GitHubIssuesContextProvider is a ContextProvider that allows you to search GitHub issues in a repo. Type '@issue' to reference the title and contents of an issue.
[View the source](https://github.com/continuedev/continue/blob/main/server/continuedev/plugins/context_providers/github.py)
## Properties
<ClassPropertyRef name='repo_name' details='{&quot;title&quot;: &quot;Repo Name&quot;, &quot;description&quot;: &quot;The name of the GitHub repo from which to pull issues&quot;, &quot;type&quot;: &quot;string&quot;}' required={true} default=""/>
<ClassPropertyRef name='auth_token' details='{&quot;title&quot;: &quot;Auth Token&quot;, &quot;description&quot;: &quot;The GitHub auth token to use to authenticate with the GitHub API&quot;, &quot;type&quot;: &quot;string&quot;}' required={true} default=""/>
### Inherited Properties
<ClassPropertyRef name='title' details='{&quot;title&quot;: &quot;Title&quot;, &quot;default&quot;: &quot;issues&quot;, &quot;type&quot;: &quot;string&quot;}' required={false} default="issues"/>
<ClassPropertyRef name='ide' details='{&quot;title&quot;: &quot;Ide&quot;}' required={false} default=""/>
<ClassPropertyRef name='display_title' details='{&quot;title&quot;: &quot;Display Title&quot;, &quot;default&quot;: &quot;GitHub Issues&quot;, &quot;type&quot;: &quot;string&quot;}' required={false} default="GitHub Issues"/>
<ClassPropertyRef name='description' details='{&quot;title&quot;: &quot;Description&quot;, &quot;default&quot;: &quot;Reference GitHub issues&quot;, &quot;type&quot;: &quot;string&quot;}' required={false} default="Reference GitHub issues"/>
<ClassPropertyRef name='dynamic' details='{&quot;title&quot;: &quot;Dynamic&quot;, &quot;default&quot;: false, &quot;type&quot;: &quot;boolean&quot;}' required={false} default="False"/>
<ClassPropertyRef name='requires_query' details='{&quot;title&quot;: &quot;Requires Query&quot;, &quot;description&quot;: &quot;Indicates whether the ContextProvider requires a query. For example, the SearchContextProvider requires you to type &#x27;@search &lt;STRING_TO_SEARCH&gt;&#x27;. This will change the behavior of the UI so that it can indicate the expectation for a query.&quot;, &quot;default&quot;: false, &quot;type&quot;: &quot;boolean&quot;}' required={false} default="False"/>

View file

@ -1,21 +0,0 @@
import ClassPropertyRef from '@site/src/components/ClassPropertyRef.tsx';
# GoogleContextProvider
Type '@google' to reference the results of a Google search. For example, type "@google python tutorial" if you want to search and discuss ways of learning Python.
[View the source](https://github.com/continuedev/continue/blob/main/server/continuedev/plugins/context_providers/google.py)
## Properties
<ClassPropertyRef name='serper_api_key' details='{&quot;title&quot;: &quot;Serper Api Key&quot;, &quot;description&quot;: &quot;Your SerpAPI key, used to programmatically make Google searches. You can get a key at https://serper.dev.&quot;, &quot;type&quot;: &quot;string&quot;}' required={true} default=""/>
### Inherited Properties
<ClassPropertyRef name='title' details='{&quot;title&quot;: &quot;Title&quot;, &quot;default&quot;: &quot;google&quot;, &quot;type&quot;: &quot;string&quot;}' required={false} default="google"/>
<ClassPropertyRef name='ide' details='{&quot;title&quot;: &quot;Ide&quot;}' required={false} default=""/>
<ClassPropertyRef name='display_title' details='{&quot;title&quot;: &quot;Display Title&quot;, &quot;default&quot;: &quot;Google&quot;, &quot;type&quot;: &quot;string&quot;}' required={false} default="Google"/>
<ClassPropertyRef name='description' details='{&quot;title&quot;: &quot;Description&quot;, &quot;default&quot;: &quot;Search Google&quot;, &quot;type&quot;: &quot;string&quot;}' required={false} default="Search Google"/>
<ClassPropertyRef name='dynamic' details='{&quot;title&quot;: &quot;Dynamic&quot;, &quot;default&quot;: true, &quot;type&quot;: &quot;boolean&quot;}' required={false} default="True"/>
<ClassPropertyRef name='requires_query' details='{&quot;title&quot;: &quot;Requires Query&quot;, &quot;default&quot;: true, &quot;type&quot;: &quot;boolean&quot;}' required={false} default="True"/>

View file

@ -1,21 +0,0 @@
import ClassPropertyRef from '@site/src/components/ClassPropertyRef.tsx';
# SearchContextProvider
Type '@search' to reference the results of codebase search, just like the results you would get from VS Code search.
[View the source](https://github.com/continuedev/continue/blob/main/server/continuedev/plugins/context_providers/search.py)
## Properties
<ClassPropertyRef name='workspace_dir' details='{&quot;title&quot;: &quot;Workspace Dir&quot;, &quot;description&quot;: &quot;The workspace directory to search&quot;, &quot;type&quot;: &quot;string&quot;}' required={false} default=""/>
### Inherited Properties
<ClassPropertyRef name='title' details='{&quot;title&quot;: &quot;Title&quot;, &quot;default&quot;: &quot;search&quot;, &quot;type&quot;: &quot;string&quot;}' required={false} default="search"/>
<ClassPropertyRef name='ide' details='{&quot;title&quot;: &quot;Ide&quot;}' required={false} default=""/>
<ClassPropertyRef name='display_title' details='{&quot;title&quot;: &quot;Display Title&quot;, &quot;default&quot;: &quot;Search&quot;, &quot;type&quot;: &quot;string&quot;}' required={false} default="Search"/>
<ClassPropertyRef name='description' details='{&quot;title&quot;: &quot;Description&quot;, &quot;default&quot;: &quot;Search workspace for exact matches&quot;, &quot;type&quot;: &quot;string&quot;}' required={false} default="Search workspace for exact matches"/>
<ClassPropertyRef name='dynamic' details='{&quot;title&quot;: &quot;Dynamic&quot;, &quot;default&quot;: true, &quot;type&quot;: &quot;boolean&quot;}' required={false} default="True"/>
<ClassPropertyRef name='requires_query' details='{&quot;title&quot;: &quot;Requires Query&quot;, &quot;default&quot;: true, &quot;type&quot;: &quot;boolean&quot;}' required={false} default="True"/>

View file

@ -1,21 +0,0 @@
import ClassPropertyRef from '@site/src/components/ClassPropertyRef.tsx';
# TerminalContextProvider
Type '@terminal' to reference the contents of your IDE's terminal.
[View the source](https://github.com/continuedev/continue/blob/main/server/continuedev/plugins/context_providers/terminal.py)
## Properties
<ClassPropertyRef name='get_last_n_commands' details='{&quot;title&quot;: &quot;Get Last N Commands&quot;, &quot;description&quot;: &quot;The number of previous commands to reference&quot;, &quot;default&quot;: 3, &quot;type&quot;: &quot;integer&quot;}' required={false} default="3"/>
### Inherited Properties
<ClassPropertyRef name='title' details='{&quot;title&quot;: &quot;Title&quot;, &quot;default&quot;: &quot;terminal&quot;, &quot;type&quot;: &quot;string&quot;}' required={false} default="terminal"/>
<ClassPropertyRef name='ide' details='{&quot;title&quot;: &quot;Ide&quot;}' required={false} default=""/>
<ClassPropertyRef name='display_title' details='{&quot;title&quot;: &quot;Display Title&quot;, &quot;default&quot;: &quot;Terminal&quot;, &quot;type&quot;: &quot;string&quot;}' required={false} default="Terminal"/>
<ClassPropertyRef name='description' details='{&quot;title&quot;: &quot;Description&quot;, &quot;default&quot;: &quot;Reference the contents of the terminal&quot;, &quot;type&quot;: &quot;string&quot;}' required={false} default="Reference the contents of the terminal"/>
<ClassPropertyRef name='dynamic' details='{&quot;title&quot;: &quot;Dynamic&quot;, &quot;default&quot;: true, &quot;type&quot;: &quot;boolean&quot;}' required={false} default="True"/>
<ClassPropertyRef name='requires_query' details='{&quot;title&quot;: &quot;Requires Query&quot;, &quot;description&quot;: &quot;Indicates whether the ContextProvider requires a query. For example, the SearchContextProvider requires you to type &#x27;@search &lt;STRING_TO_SEARCH&gt;&#x27;. This will change the behavior of the UI so that it can indicate the expectation for a query.&quot;, &quot;default&quot;: false, &quot;type&quot;: &quot;boolean&quot;}' required={false} default="False"/>

View file

@ -1,22 +0,0 @@
import ClassPropertyRef from '@site/src/components/ClassPropertyRef.tsx';
# URLContextProvider
Type '@url' to reference the contents of a URL. You can either reference preset URLs, or reference one dynamically by typing '@url https://example.com'. The text contents of the page will be fetched and used as context.
[View the source](https://github.com/continuedev/continue/blob/main/server/continuedev/plugins/context_providers/url.py)
## Properties
<ClassPropertyRef name='preset_urls' details='{&quot;title&quot;: &quot;Preset Urls&quot;, &quot;description&quot;: &quot;A list of preset URLs that you will be able to quickly reference by typing &#x27;@url&#x27;&quot;, &quot;default&quot;: [], &quot;type&quot;: &quot;array&quot;, &quot;items&quot;: {&quot;type&quot;: &quot;string&quot;}}' required={false} default="[]"/>
<ClassPropertyRef name='static_url_context_items' details='{&quot;title&quot;: &quot;Static Url Context Items&quot;, &quot;default&quot;: [], &quot;type&quot;: &quot;array&quot;, &quot;items&quot;: {&quot;$ref&quot;: &quot;#/definitions/ContextItem&quot;}}' required={false} default="[]"/>
### Inherited Properties
<ClassPropertyRef name='title' details='{&quot;title&quot;: &quot;Title&quot;, &quot;default&quot;: &quot;url&quot;, &quot;type&quot;: &quot;string&quot;}' required={false} default="url"/>
<ClassPropertyRef name='ide' details='{&quot;title&quot;: &quot;Ide&quot;}' required={false} default=""/>
<ClassPropertyRef name='display_title' details='{&quot;title&quot;: &quot;Display Title&quot;, &quot;default&quot;: &quot;URL&quot;, &quot;type&quot;: &quot;string&quot;}' required={false} default="URL"/>
<ClassPropertyRef name='description' details='{&quot;title&quot;: &quot;Description&quot;, &quot;default&quot;: &quot;Reference the contents of a webpage&quot;, &quot;type&quot;: &quot;string&quot;}' required={false} default="Reference the contents of a webpage"/>
<ClassPropertyRef name='dynamic' details='{&quot;title&quot;: &quot;Dynamic&quot;, &quot;default&quot;: true, &quot;type&quot;: &quot;boolean&quot;}' required={false} default="True"/>
<ClassPropertyRef name='requires_query' details='{&quot;title&quot;: &quot;Requires Query&quot;, &quot;default&quot;: true, &quot;type&quot;: &quot;boolean&quot;}' required={false} default="True"/>

View file

@ -1,22 +0,0 @@
import ClassPropertyRef from '@site/src/components/ClassPropertyRef.tsx';
# Configuration Options
[View the source](https://github.com/continuedev/continue/blob/main/server/continuedev/core/config.py)
## Properties
<ClassPropertyRef name='disallowed_steps' details='{&quot;title&quot;: &quot;Disallowed Steps&quot;, &quot;description&quot;: &quot;Steps that are not allowed to be run, and will be skipped if attempted&quot;, &quot;default&quot;: [], &quot;type&quot;: &quot;array&quot;, &quot;items&quot;: {&quot;type&quot;: &quot;string&quot;}}' required={false} default="[]"/>
<ClassPropertyRef name='allow_anonymous_telemetry' details='{&quot;title&quot;: &quot;Allow Anonymous Telemetry&quot;, &quot;description&quot;: &quot;If this field is set to True, we will collect anonymous telemetry as described in the documentation page on telemetry. If set to False, we will not collect any data.&quot;, &quot;default&quot;: true, &quot;type&quot;: &quot;boolean&quot;}' required={false} default="True"/>
<ClassPropertyRef name='models' details='{&quot;title&quot;: &quot;Models&quot;, &quot;default&quot;: [{&quot;title&quot;: &quot;GPT-4 (trial)&quot;, &quot;provider&quot;: &quot;free-trial&quot;, &quot;model&quot;: &quot;gpt-4&quot;, &quot;api_key&quot;: &quot;&quot;, &quot;api_base&quot;: null, &quot;context_length&quot;: 2048, &quot;template&quot;: null, &quot;completion_options&quot;: {&quot;temperature&quot;: null, &quot;top_p&quot;: null, &quot;top_k&quot;: null, &quot;presence_penalty&quot;: null, &quot;frequency_penalty&quot;: null, &quot;stop&quot;: null, &quot;max_tokens&quot;: 1023}, &quot;system_message&quot;: null, &quot;request_options&quot;: {&quot;timeout&quot;: 300, &quot;verify_ssl&quot;: null, &quot;ca_bundle_path&quot;: null, &quot;proxy&quot;: null, &quot;headers&quot;: null}}], &quot;type&quot;: &quot;array&quot;, &quot;items&quot;: {&quot;$ref&quot;: &quot;#/definitions/ModelDescription&quot;}}' required={false} default="[{&#x27;title&#x27;: &#x27;GPT-4 (trial)&#x27;, &#x27;provider&#x27;: &#x27;free-trial&#x27;, &#x27;model&#x27;: &#x27;gpt-4&#x27;, &#x27;api_key&#x27;: &#x27;&#x27;, &#x27;api_base&#x27;: None, &#x27;context_length&#x27;: 2048, &#x27;template&#x27;: None, &#x27;completion_options&#x27;: {&#x27;temperature&#x27;: None, &#x27;top_p&#x27;: None, &#x27;top_k&#x27;: None, &#x27;presence_penalty&#x27;: None, &#x27;frequency_penalty&#x27;: None, &#x27;stop&#x27;: None, &#x27;max_tokens&#x27;: 1023}, &#x27;system_message&#x27;: None, &#x27;request_options&#x27;: {&#x27;timeout&#x27;: 300, &#x27;verify_ssl&#x27;: None, &#x27;ca_bundle_path&#x27;: None, &#x27;proxy&#x27;: None, &#x27;headers&#x27;: None}}]"/>
<ClassPropertyRef name='model_roles' details='{&quot;title&quot;: &quot;Model Roles&quot;, &quot;description&quot;: &quot;Roles for models. Each entry should be the title of a model in the models array.&quot;, &quot;default&quot;: {&quot;default&quot;: &quot;GPT-4 (trial)&quot;, &quot;chat&quot;: null, &quot;edit&quot;: null, &quot;summarize&quot;: null}, &quot;allOf&quot;: [{&quot;$ref&quot;: &quot;#/definitions/ModelRoles&quot;}]}' required={false} default="{&#x27;default&#x27;: &#x27;GPT-4 (trial)&#x27;, &#x27;chat&#x27;: None, &#x27;edit&#x27;: None, &#x27;summarize&#x27;: None}"/>
<ClassPropertyRef name='system_message' details='{&quot;title&quot;: &quot;System Message&quot;, &quot;description&quot;: &quot;A system message that will always be followed by the LLM&quot;, &quot;type&quot;: &quot;string&quot;}' required={false} default=""/>
<ClassPropertyRef name='completion_options' details='{&quot;title&quot;: &quot;Completion Options&quot;, &quot;description&quot;: &quot;Default options for completion. These will be overriden by any options set for a specific model.&quot;, &quot;default&quot;: {&quot;temperature&quot;: null, &quot;top_p&quot;: null, &quot;top_k&quot;: null, &quot;presence_penalty&quot;: null, &quot;frequency_penalty&quot;: null, &quot;stop&quot;: null, &quot;max_tokens&quot;: 1023}, &quot;allOf&quot;: [{&quot;$ref&quot;: &quot;#/definitions/BaseCompletionOptions&quot;}]}' required={false} default="{&#x27;temperature&#x27;: None, &#x27;top_p&#x27;: None, &#x27;top_k&#x27;: None, &#x27;presence_penalty&#x27;: None, &#x27;frequency_penalty&#x27;: None, &#x27;stop&#x27;: None, &#x27;max_tokens&#x27;: 1023}"/>
<ClassPropertyRef name='slash_commands' details='{&quot;title&quot;: &quot;Slash Commands&quot;, &quot;description&quot;: &quot;An array of slash commands that let you map custom Steps to a shortcut.&quot;, &quot;default&quot;: [], &quot;type&quot;: &quot;array&quot;, &quot;items&quot;: {&quot;$ref&quot;: &quot;#/definitions/SlashCommand&quot;}}' required={false} default="[]"/>
<ClassPropertyRef name='custom_commands' details='{&quot;title&quot;: &quot;Custom Commands&quot;, &quot;description&quot;: &quot;An array of custom commands that allow you to reuse prompts. Each has name, description, and prompt properties. When you enter /&lt;name&gt; in the text input, it will act as a shortcut to the prompt.&quot;, &quot;default&quot;: [{&quot;name&quot;: &quot;test&quot;, &quot;prompt&quot;: &quot;Write a comprehensive set of unit tests for the selected code. It should setup, run tests that check for correctness including important edge cases, and teardown. Ensure that the tests are complete and sophisticated. Give the tests just as chat output, don&#x27;t edit any file.&quot;, &quot;description&quot;: &quot;This is an example custom command. Use /config to edit it and create more&quot;}], &quot;type&quot;: &quot;array&quot;, &quot;items&quot;: {&quot;$ref&quot;: &quot;#/definitions/CustomCommand&quot;}}' required={false} default="[{&#x27;name&#x27;: &#x27;test&#x27;, &#x27;prompt&#x27;: &quot;Write a comprehensive set of unit tests for the selected code. It should setup, run tests that check for correctness including important edge cases, and teardown. Ensure that the tests are complete and sophisticated. Give the tests just as chat output, don&#x27;t edit any file.&quot;, &#x27;description&#x27;: &#x27;This is an example custom command. Use /config to edit it and create more&#x27;}]"/>
<ClassPropertyRef name='context_providers' details='{&quot;title&quot;: &quot;Context Providers&quot;, &quot;description&quot;: &quot;A list of ContextProvider objects that can be used to provide context to the LLM by typing &#x27;@&#x27;. Read more about ContextProviders in the documentation.&quot;, &quot;default&quot;: [], &quot;type&quot;: &quot;array&quot;, &quot;items&quot;: {&quot;$ref&quot;: &quot;#/definitions/ContextProviderWithParams&quot;}}' required={false} default="[]"/>
<ClassPropertyRef name='user_token' details='{&quot;title&quot;: &quot;User Token&quot;, &quot;description&quot;: &quot;An optional token to identify the user.&quot;, &quot;type&quot;: &quot;string&quot;}' required={false} default=""/>
<ClassPropertyRef name='data_server_url' details='{&quot;title&quot;: &quot;Data Server Url&quot;, &quot;description&quot;: &quot;The URL of the server where development data is sent. No data is sent unless you have explicitly set the `user_token` property to a valid token that we have shared.&quot;, &quot;default&quot;: &quot;https://us-west1-autodebug.cloudfunctions.net&quot;, &quot;type&quot;: &quot;string&quot;}' required={false} default="https://us-west1-autodebug.cloudfunctions.net"/>
<ClassPropertyRef name='disable_summaries' details='{&quot;title&quot;: &quot;Disable Summaries&quot;, &quot;description&quot;: &quot;If set to `True`, Continue will not generate summaries for each Step. This can be useful if you want to save on compute.&quot;, &quot;default&quot;: false, &quot;type&quot;: &quot;boolean&quot;}' required={false} default="False"/>
<ClassPropertyRef name='disable_indexing' details='{&quot;title&quot;: &quot;Disable Indexing&quot;, &quot;description&quot;: &quot;If set to `True`, Continue will not index the codebase. This is mainly used for debugging purposes.&quot;, &quot;default&quot;: false, &quot;type&quot;: &quot;boolean&quot;}' required={false} default="False"/>
<ClassPropertyRef name='retrieval_settings' details='{&quot;title&quot;: &quot;Retrieval Settings&quot;, &quot;description&quot;: &quot;Settings for the retrieval system. Read more about the retrieval system in the documentation.&quot;, &quot;default&quot;: {&quot;n_retrieve&quot;: 50, &quot;n_final&quot;: 10, &quot;use_reranking&quot;: true, &quot;rerank_group_size&quot;: 5, &quot;ignore_files&quot;: [], &quot;openai_api_key&quot;: null, &quot;api_base&quot;: null, &quot;api_type&quot;: null, &quot;api_version&quot;: null, &quot;organization_id&quot;: null}, &quot;allOf&quot;: [{&quot;$ref&quot;: &quot;#/definitions/RetrievalSettings&quot;}]}' required={false} default="{&#x27;n_retrieve&#x27;: 50, &#x27;n_final&#x27;: 10, &#x27;use_reranking&#x27;: True, &#x27;rerank_group_size&#x27;: 5, &#x27;ignore_files&#x27;: [], &#x27;openai_api_key&#x27;: None, &#x27;api_base&#x27;: None, &#x27;api_type&#x27;: None, &#x27;api_version&#x27;: None, &#x27;organization_id&#x27;: None}"/>

View file

@ -0,0 +1,16 @@
import Schema from "@site/static/schemas/config.json";
import JSONSchemaViewer from "@theme/JSONSchemaViewer";
# Configuration Options
The following shows the JSON Schema definition for `config.json`:
<JSONSchemaViewer
schema={Schema}
resolverOptions={{
jsonPointer:
"#/definitions/continuedev__core__config__serialized_config__SerializedContinueConfig",
}}
/>
[View the source](https://github.com/continuedev/continue/blob/main/extensions/vscode/config_schema.json)

View file

@ -1,5 +1,5 @@
---
title: Telemetry
title: 🦔 Telemetry
description: Continue collects anonymous usage information
keywords: [telemetry, anonymous, usage info, opt out]
---
@ -8,16 +8,15 @@ keywords: [telemetry, anonymous, usage info, opt out]
## Overview
Continue collects and reports **anonymous** usage information. This data is essential to understanding how we should improve the library. You can opt out of it at any time. We use [Posthog](https://posthog.com/), an open source platform for product analytics, to collect and store the data. You can review the code [here](https://github.com/continuedev/continue/tree/main/server/continuedev/libs/util/telemetry.py).
Continue collects and reports **anonymous** usage information. This data is essential to understanding how we should improve the product. You can opt out of it at any time. We use [Posthog](https://posthog.com/), an open source platform for product analytics, to collect and store the data. You can review the code [here](https://github.com/continuedev/continue/blob/main/gui/src/hooks/CustomPostHogProvider.tsx).
## What we track
We track
- the steps that are run and their parameters
- whether you accept or reject suggestions (not the code itself)
- the traceback when an error occurs
- the name of your OS
- the name of slash commands that are run
- the name of your OS and IDE
- the name of the default model you configured
All data is anonymous and cleaned of PII before being sent to PostHog.
@ -33,4 +32,4 @@ The `~/.continue` directory contains a `config.json` file that looks like this:
}
```
You can turn off anonymous telemetry by changing the value of `allowAnonymousTelemetry` to `false`.
You can turn off anonymous telemetry by changing the value of `allowAnonymousTelemetry` to `false`. Alternatively, you can uncheck the "Continue: Telemetry Enabled" box in VS Code settings.

View file

@ -1,5 +1,5 @@
---
title: Troubleshooting
title: ❓ Troubleshooting
description: Troubleshooting while waiting for help during beta / alpha testing
keywords: [reload, delete, manually, logs, server, console]
---
@ -18,13 +18,17 @@ To solve many problems, the first step is reading the logs to find the relevant
4. Select the `Console` tab
5. Read the console logs
## Download a Newer Version (VS Code)
## Download a Newer Version
If you are using an older version of the Continue extension, particularly one which depends on the separate Python server, we would recommend downloading the latest version of the extension, as we are constantly making bug fixes and are likely to have solved any major issues.
## Download an Older Version (VS Code)
## Download an Older Version
If you've tried everything, reported an error, know that a previous version was working for you, and are waiting to hear back, you can try downloading an older version of the extension. All versions are hosted on the Open VSX Registry [here](https://open-vsx.org/extension/Continue/continue). Once you've downloaded the extension, which will be a .vsix file, you can install it manually by following the instructions [here](https://code.visualstudio.com/docs/editor/extension-gallery#_install-from-a-vsix).
If you've tried everything, reported an error, know that a previous version was working for you, and are waiting to hear back, you can try downloading an older version of the extension.
For VS Code, All versions are hosted on the Open VSX Registry [here](https://open-vsx.org/extension/Continue/continue). Once you've downloaded the extension, which will be a .vsix file, you can install it manually by following the instructions [here](https://code.visualstudio.com/docs/editor/extension-gallery#_install-from-a-vsix).
You can find older versions of the JetBrains extension on their [marketplace](https://plugins.jetbrains.com/plugin/22707-continue), which will walk you through installing from disk.
## Still having trouble?

View file

@ -8,11 +8,19 @@ keywords: [talk, embeddings, codebase, experimental]
Continue indexes your codebase so that it can later automatically pull in the most relevant context from throughout your workspace. This is done via a combination of embeddings-based retrieval and keyword search. By default, all embeddings are calculated locally with `all-MiniLM-L6-v2` and stored locally in `~/.continue/index`.
## How to use codebase retrieval
<!-- ## How to use codebase retrieval -->
Currently, the codebase retrieval feature is available as the "codebase" context provider. You can use it by typing `@codebase` in the input box, and then asking a question. The contents of the input box will be compared with the embeddings from the rest of the codebase to determine relevant files.
Currently, the codebase retrieval feature is available as the "codebase" and "folder" context providers. You can use them by typing `@codebase` or `@folder` in the input box, and then asking a question. The contents of the input box will be compared with the embeddings from the rest of the codebase (or folder) to determine relevant files.
There are a few options that let you configure the behavior of the codebase context provider. These can be set in `config.json`:
<!-- Here are some common use cases where it can be useful:
### Asking high-level codebase questions
- -->
## Configuration
There are a few options that let you configure the behavior of the codebase context provider. These can be set in `config.json`, and are the same for the codebase and folder context providers:
```json title="~/.continue/config.json"
{
@ -73,6 +81,8 @@ We also support other methods of generating embeddings, which can be configured
### OpenAI
OpenAI's [ada-002 embeddings](https://platform.openai.com/docs/guides/embeddings) are high dimensional embeddings that give great performance on both text and code.
```json title="~/.continue/config.json"
{
"embeddingsProvider": {

View file

@ -16,29 +16,28 @@ If you need any help migrating, please reach out to us on Discord.
> Continue has moved to using Typescript configuration. To learn about this, please see [Configuration as Code](../customization/code-config.md).
For configuration that requires code, we now provide a simpler interface that works alongside config.json. In the same folder, `~/.continue`, create a file named `config.py` (the same name as before) and add a function called `modify_config`. This function should take a [`ContinueConfig`](https://github.com/continuedev/continue/blob/main/server/continuedev/core/config.py) object as its only argument, and return a `ContinueConfig` object. This object is essentially the same as the one that was previously defined in `config.py`. This allows you to modify the initial configuration object defined in your `config.json`. Here's an example that cuts the temperature in half:
For configuration that requires code, we now provide a simpler interface that works alongside config.json. In the same folder, `~/.continue`, create a file named `config.ts` and add a function called `modifyConfig`. This function should take a `Config` object as its only argument, and return a `Config` object. This object is essentially the same as the one that was previously defined in `config.py`. This allows you to modify the initial configuration object defined in your `config.json`. Here's an example that cuts the temperature in half:
```python
from continuedev.core.config import ContinueConfig
def modify_config(config: ContinueConfig) -> ContinueConfig:
config.completion_options.temperature /= 2
return config
```typescript
function modifyConfig(config: Config): Config {
config.completionOptions.temperature /= 2;
return config;
}
```
To summarize, these are the steps taken to load your configuration:
1. Load `~/.continue/config.json`
2. Convert this into a `ContinueConfig` object
3. If `~/.continue/config.py` exists and has defined `modify_config` correctly, call `modify_config` with the `ContinueConfig` object to generate the final configuration
2. Convert this into a `Config` object
3. If `~/.continue/config.ts` exists and has defined `modifyConfig` correctly, call `modifyConfig` with the `Config` object to generate the final configuration
## List of Changes
### `completion_options`
### `completionOptions`
The properties `top_p`, `top_k`, `temperature`, `presence_penalty`, and `frequency_penalty` have been moved into a single object called `completion_options`. It can be specified at the top level of the config or within a `models` object.
The properties `topP`, `topK`, `temperature`, `presencePenalty`, and `frequencyPenalty` have been moved into a single object called `completionOptions`. It can be specified at the top level of the config or within a `models` object.
### `request_options`
### `requestOptions`
The properties `timeout`, `verify_ssl`, `ca_bundle_path`, `proxy`, and `headers` have been moved into a single object called `request_options`, which can be specified for each `models` object.

View file

@ -6,7 +6,7 @@ keywords: [no internet, air-gapped, local model]
# Running Continue without Internet
Continue can be run even on an air-gapped computer if you use a local model. You'll have to make a few adjustments for this to work.
Continue can be run even on an air-gapped computer if you use a local model. Only a few adjustments are required for this to work.
1. Download the latest .vsix file from the [Open VSX Registry](https://open-vsx.org/extension/Continue/continue) and [install it to VS Code](https://code.visualstudio.com/docs/editor/extension-marketplace#_install-from-a-vsix).
2. Open `~/.continue/config.json` and set `"allowAnonymousTelemetry": false`. This will stop Continue from attempting requests to PostHog.

View file

@ -1,8 +1,9 @@
// @ts-check
// Note: type annotations allow type checking and IDEs autocompletion
const lightCodeTheme = require("prism-react-renderer/themes/github");
const darkCodeTheme = require("prism-react-renderer/themes/dracula");
const { themes } = require("prism-react-renderer");
const lightCodeTheme = themes.github;
const darkCodeTheme = themes.dracula;
/** @type {import('@docusaurus/types').Config} */
const config = {
@ -33,6 +34,8 @@ const config = {
locales: ["en"],
},
themes: [["docusaurus-json-schema-plugin", {}]],
presets: [
[
"classic",
@ -56,7 +59,13 @@ const config = {
themeConfig:
/** @type {import('@docusaurus/preset-classic').ThemeConfig} */
({
metadata: [{name: 'keywords', content: 'open source, ai, vscode, intellij, jetbrains, developer tools, chatgpt, copilot, llm'}],
metadata: [
{
name: "keywords",
content:
"open source, ai, vscode, intellij, jetbrains, developer tools, chatgpt, copilot, llm",
},
],
// Replace with your project's social card
image: "img/continue-social-card.png",
navbar: {
@ -128,6 +137,7 @@ const config = {
prism: {
theme: lightCodeTheme,
darkTheme: darkCodeTheme,
additionalLanguages: ["json"],
},
algolia: {
// The application ID provided by Algolia

17120
docs/package-lock.json generated

File diff suppressed because it is too large Load diff

View file

@ -15,17 +15,18 @@
"write-heading-ids": "docusaurus write-heading-ids"
},
"dependencies": {
"@docusaurus/core": "2.4.0",
"@docusaurus/plugin-client-redirects": "2.4.0",
"@docusaurus/preset-classic": "2.4.0",
"@mdx-js/react": "^1.6.22",
"clsx": "^1.2.1",
"prism-react-renderer": "^1.3.5",
"react": "^17.0.2",
"react-dom": "^17.0.2"
"@docusaurus/core": "3.1.0",
"@docusaurus/plugin-client-redirects": "3.1.0",
"@docusaurus/preset-classic": "3.1.0",
"@mdx-js/react": "^3.0.0",
"clsx": "^2.1.0",
"docusaurus-json-schema-plugin": "^1.11.0",
"prism-react-renderer": "^2.3.1",
"react": "^18.2.0",
"react-dom": "^18.2.0"
},
"devDependencies": {
"@docusaurus/module-type-aliases": "2.4.0"
"@docusaurus/module-type-aliases": "3.1.0"
},
"browserslist": {
"production": [

View file

@ -38,7 +38,6 @@ const sidebars = {
"customization/overview",
"customization/context-providers",
"customization/slash-commands",
"customization/other-configuration",
],
},
{
@ -47,10 +46,10 @@ const sidebars = {
collapsible: true,
collapsed: true,
items: [
"walkthroughs/codellama",
// "walkthroughs/codellama",
"walkthroughs/running-continue-without-internet",
"walkthroughs/codebase-embeddings",
"walkthroughs/config-file-migration",
// "walkthroughs/config-file-migration",
],
},
"development-data",

Binary file not shown.

Before

Width:  |  Height:  |  Size: 131 KiB

After

Width:  |  Height:  |  Size: 60 KiB

BIN
docs/static/img/jetbrains-quickstart.png vendored Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 371 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 762 KiB

BIN
docs/static/img/slash-commands.png vendored Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 93 KiB

1289
docs/static/schemas/config.json vendored Normal file

File diff suppressed because it is too large Load diff

View file

@ -8,6 +8,4 @@ src/client
gui
exe
sync.node
bin

View file

@ -1,5 +1,5 @@
{
"title": "SerializedContinueConfig",
"title": "config.json",
"$ref": "#/definitions/continuedev__core__config__serialized_config__SerializedContinueConfig",
"definitions": {
"BaseCompletionOptions": {
@ -31,6 +31,11 @@
"description": "The frequency penalty of the completion.",
"type": "number"
},
"mirostat": {
"title": "Mirostat",
"description": "Enable Mirostat sampling, controlling perplexity during text generation (default: 0, 0 = disabled, 1 = Mirostat, 2 = Mirostat 2.0). Only available for Ollama, LM Studio, and llama.cpp providers",
"type": "number"
},
"stop": {
"title": "Stop",
"description": "The stop tokens of the completion.",
@ -950,22 +955,24 @@
"open",
"google",
"search",
"url",
"http",
"codebase",
"problems",
"folder"
"folder",
"issue"
],
"markdownEnumDescriptions": [
"Reference the contents of the current changes as given by `git diff`",
"Reference the contents of the terminal",
"Reference the contents of all open files.",
"Reference the contents of all open or pinned files.",
"Enter a search phrase and include the Google search results as context",
"Enter a URL and use the contents of the webpage as context",
"Reference the results of a ripgrep search in your codebase",
"Write a custom context provider at your own HTTP endpoint. Set 'url' in the params object for the endpoint you have setup.",
"Use embeddings to automatically find relevant files from throughout the codebase",
"Reference all linting errors and warnings in the currently open file",
"Include important files from a folder in the prompt, as determined by similarity search"
"Include important files from a folder in the prompt, as determined by similarity search",
"Reference GitHub issues from a repository",
"Retrieve important pages from a documentation website, as determined by similarity search"
],
"type": "string"
},
@ -1002,6 +1009,97 @@
"required": ["params"]
}
},
{
"if": {
"properties": {
"name": {
"enum": ["open"]
}
}
},
"then": {
"properties": {
"params": {
"properties": {
"onlyPinned": {
"type": "boolean",
"description": "If set to true, only 'pinned' files will be included.",
"default": false
}
}
}
}
}
},
{
"if": {
"properties": {
"name": {
"enum": ["issue"]
}
}
},
"then": {
"properties": {
"params": {
"properties": {
"githubToken": {
"type": "string",
"description": "Your GitHub token to access the GitHub API. Required for private repositories."
},
"repos": {
"type": "array",
"description": "A list of repositories to search for issues",
"items": {
"type": "object",
"properties": {
"owner": {
"type": "string",
"description": "The owner of the repository"
},
"repo": {
"type": "string",
"description": "The name of the repository"
},
"type": {
"type": "string",
"description": "The type of issues to search for",
"enum": ["open", "closed", "all"]
}
},
"required": ["owner", "repo"]
}
}
},
"required": ["repos"]
}
},
"required": ["params"]
}
},
{
"if": {
"properties": {
"name": {
"enum": ["http"]
}
}
},
"then": {
"properties": {
"params": {
"properties": {
"url": {
"type": "string",
"description": "The HTTP endpoint of your context provider server."
}
},
"required": ["url"]
}
},
"required": ["params"]
}
},
{
"if": {
"properties": {
@ -1041,7 +1139,7 @@
"required": ["name"]
},
"continuedev__core__config__serialized_config__SerializedContinueConfig": {
"title": "SerializedContinueConfig",
"title": "config.json",
"type": "object",
"properties": {
"allowAnonymousTelemetry": {

View file

@ -1,12 +1,12 @@
{
"name": "continue",
"version": "0.9.20",
"version": "0.9.29",
"lockfileVersion": 3,
"requires": true,
"packages": {
"": {
"name": "continue",
"version": "0.9.20",
"version": "0.9.29",
"license": "Apache-2.0",
"dependencies": {
"@electron/rebuild": "^3.2.10",
@ -78,11 +78,14 @@
"version": "1.0.0",
"license": "Apache-2.0",
"dependencies": {
"@octokit/rest": "^20.0.2",
"@xenova/transformers": "^2.14.0",
"cheerio": "^1.0.0-rc.12",
"dotenv": "^16.3.1",
"fastest-levenshtein": "^1.0.16",
"handlebars": "^4.7.8",
"js-tiktoken": "^1.0.8",
"node-html-markdown": "^1.3.0",
"openai": "^4.20.1",
"replicate": "^0.23.0",
"socket.io-client": "^4.7.3",
@ -96,8 +99,10 @@
"devDependencies": {
"@types/handlebars": "^4.1.0",
"@types/jest": "^29.5.11",
"@types/jquery": "^3.5.29",
"@types/mustache": "^4.2.5",
"@types/uuid": "^9.0.7",
"esbuild": "^0.19.11",
"jest": "^29.7.0",
"ts-jest": "^29.1.1"
}

View file

@ -1,7 +1,7 @@
{
"name": "continue",
"icon": "media/icon.png",
"version": "0.9.20",
"version": "0.9.29",
"repository": {
"type": "git",
"url": "https://github.com/continuedev/continue"
@ -124,7 +124,7 @@
{
"command": "continue.newSession",
"category": "Continue",
"title": "New Session (⌘ M)",
"title": "New Session",
"icon": "$(add)"
},
{
@ -152,6 +152,11 @@
"command": "continue.optimizeCode",
"category": "Continue",
"title": "Optimize this Code"
},
{
"command": "continue.fixGrammar",
"category": "Continue",
"title": "Fix Grammar / Spelling"
}
],
"keybindings": [
@ -241,6 +246,11 @@
"command": "continue.optimizeCode",
"group": "Continue",
"when": "editorHasSelection"
},
{
"command": "continue.fixGrammar",
"group": "Continue",
"when": "editorHasSelection && editorLangId == 'markdown'"
}
],
"explorer/context": [

Some files were not shown because too many files have changed in this diff Show more