Improved code linking (#1500)

* allow setting apiBase for bedrock provider

* ⚡️ better linking

* ✨ new prompt file action

* ⚡️ strip <COMPLETION> from GPT-4 completion
This commit is contained in:
Nate Sesti 2024-06-16 19:54:32 -07:00 • committed by GitHub
parent 53aab1e6fd
commit 4f8e907d05
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
13 changed files with 192 additions and 32 deletions

View file

@ -38,6 +38,7 @@ import { AutocompleteLanguageInfo } from "./languages.js";
import {
avoidPathLine,
noTopLevelKeywordsMidline,
skipPrefixes,
stopAtLines,
stopAtRepeatingLines,
stopAtSimilarLine,
@ -407,6 +408,7 @@ export async function getTabCompletion(
lineGenerator = stopAtLines(lineGenerator, fullStop);
lineGenerator = stopAtRepeatingLines(lineGenerator, fullStop);
lineGenerator = avoidPathLine(lineGenerator, lang.singleLineComment);
lineGenerator = skipPrefixes(lineGenerator);
lineGenerator = noTopLevelKeywordsMidline(
lineGenerator,
lang.topLevelKeywords,

View file

@ -121,6 +121,22 @@ export async function* stopAtLines(
}
}
const PREFIXES_TO_SKIP = ["<COMPLETION>"];
export async function* skipPrefixes(lines: LineStream): LineStream {
let isFirstLine = true;
for await (const line of lines) {
if (isFirstLine) {
const match = PREFIXES_TO_SKIP.find((prefix) => line.startsWith(prefix));
if (match) {
yield line.slice(match.length);
continue;
}
isFirstLine = false;
}
yield line;
}
}
const LINES_TO_SKIP = ["</START EDITING HERE>"];
export async function* skipLines(stream: LineStream): LineStream {

View file

@ -54,7 +54,11 @@ import {
defaultSlashCommandsJetBrains,
defaultSlashCommandsVscode,
} from "./default.js";
import { getPromptFiles, slashCommandFromPromptFile } from "./promptFile.js";
import {
DEFAULT_PROMPTS_FOLDER,
getPromptFiles,
slashCommandFromPromptFile,
} from "./promptFile.js";
const { execSync } = require("child_process");
function resolveSerializedConfig(filepath: string): SerializedContinueConfig {
@ -171,7 +175,10 @@ async function serializedToIntermediateConfig(
promptFiles = (
await Promise.all(
workspaceDirs.map((dir) =>
getPromptFiles(ide, path.join(dir, promptFolder ?? ".prompts")),
getPromptFiles(
ide,
path.join(dir, promptFolder ?? DEFAULT_PROMPTS_FOLDER),
),
),
)
)

View file

@ -1,9 +1,12 @@
import path from "path";
import * as YAML from "yaml";
import type { IDE, SlashCommand } from "..";
import { stripImages } from "../llm/countTokens.js";
import { renderTemplatedString } from "../llm/llms/index.js";
import { getBasename } from "../util/index.js";
export const DEFAULT_PROMPTS_FOLDER = ".prompts";
export async function getPromptFiles(
ide: IDE,
dir: string,
@ -21,6 +24,60 @@ export async function getPromptFiles(
}
}
const DEFAULT_PROMPT_FILE = `# This is an example ".prompt" file
# It is used to define and reuse prompts within Continue
# Continue will automatically create a slash command for each prompt in the .prompts folder
# To learn more, see the full .prompt file reference: https://docs.continue.dev/walkthroughs/prompt-files
temperature: 0.0
---
{{{ diff }}}
Give me feedback on the above changes. For each file, you should output a markdown section including the following:
- If you found any problems, an h3 like "❌ <filename>"
- If you didn't find any problems, an h3 like "✅ <filename>"
- If you found any problems, add below a bullet point description of what you found, including a minimal code snippet explaining how to fix it
- If you didn't find any problems, you don't need to add anything else
Here is an example. The example is surrounded in backticks, but your response should not be:
\`\`\`
### ✅ <Filename1>
### ❌ <Filename2>
<Description>
\`\`\`
You should look primarily for the following types of issues, and only mention other problems if they are highly pressing.
- console.logs that have been left after debugging
- repeated code
- algorithmic errors that could fail under edge cases
- something that could be refactored
Make sure to review ALL files that were changed, do not skip any.
`;
export async function createNewPromptFile(
ide: IDE,
promptPath: string | undefined,
): Promise<void> {
const workspaceDirs = await ide.getWorkspaceDirs();
if (workspaceDirs.length === 0) {
throw new Error(
"No workspace directories found. Make sure you've opened a folder in your IDE.",
);
}
const promptFilePath = path.join(
workspaceDirs[0],
promptPath ?? DEFAULT_PROMPTS_FOLDER,
"new-prompt-file.prompt",
);
await ide.writeFile(promptFilePath, DEFAULT_PROMPT_FILE);
await ide.openFile(promptFilePath);
}
export function slashCommandFromPromptFile(
path: string,
content: string,

View file

@ -14,6 +14,7 @@ import {
setupLocalMode,
setupOptimizedExistingUserMode,
} from "./config/onboarding.js";
import { createNewPromptFile } from "./config/promptFile";
import { addModel, addOpenAIKey, deleteModel } from "./config/util.js";
import { ContinueServerClient } from "./continueServer/stubs/client.js";
import { indexDocs } from "./indexing/docs/index.js";
@ -190,6 +191,12 @@ export class Core {
deleteModel(msg.data.title);
this.configHandler.reloadConfig();
});
on("config/newPromptFile", async (msg) => {
createNewPromptFile(
this.ide,
(await this.config()).experimental?.promptPath,
);
});
on("config/reload", (msg) => {
this.configHandler.reloadConfig();
return this.configHandler.getSerializedConfig();

View file

@ -24,7 +24,9 @@ class Bedrock extends BaseLLM {
constructor(options: LLMOptions) {
super(options);
this.apiBase = `https://bedrock-runtime.${options.region}.amazonaws.com`;
if (!options.apiBase) {
this.apiBase = `https://bedrock-runtime.${options.region}.amazonaws.com`;
}
}
protected async *_streamComplete(

View file

@ -45,6 +45,7 @@ export type ToCoreFromIdeOrWebviewProtocol = {
{ model: SerializedContinueConfig["models"][number] },
void,
];
"config/newPromptFile": [undefined, void];
"config/ideSettingsUpdate": [IdeSettings, void];
"config/getBrowserSerialized": [undefined, BrowserSerializedContinueConfig];
"config/deleteModel": [{ title: string }, void];

View file

@ -16,6 +16,7 @@ export const WEBVIEW_TO_CORE_PASS_THROUGH: (keyof ToCoreFromWebviewProtocol)[] =
"devdata/log",
"config/addOpenAiKey",
"config/addModel",
"config/newPromptFile",
"config/ideSettingsUpdate",
"config/getBrowserSerialized",
"config/deleteModel",

View file

@ -48,6 +48,7 @@ class ContinueBrowser(val project: Project, url: String, useOsr: Boolean = false
"config/ideSettingsUpdate",
"config/getBrowserSerialized",
"config/deleteModel",
"config/newPromptFile",
"config/reload",
"context/getContextItems",
"context/loadSubmenuItems",

View file

@ -365,15 +365,12 @@ class VsCodeIde implements IDE {
new vscode.Position(startLine, 0),
new vscode.Position(endLine, 0),
);
openEditorAndRevealRange(filepath, range).then(() => {
// TODO: Highlight lines
// this.ideUtils.highlightCode(
// {
// filepath,
// range,
// },
// "#fff1"
// );
openEditorAndRevealRange(filepath, range).then((editor) => {
// Select the lines
editor.selection = new vscode.Selection(
new vscode.Position(startLine, 0),
new vscode.Position(endLine, 0),
);
});
}

View file

@ -374,6 +374,7 @@ function TipTapEditor(props: TipTapEditorProps) {
availableSlashCommandsRef,
onClose,
onOpen,
ideMessenger,
),
renderText: (props) => {
return props.node.attrs.label;

View file

@ -161,10 +161,26 @@ export function getCommandSuggestion(
availableSlashCommandsRef: MutableRefObject<ComboBoxItem[]>,
onClose: () => void,
onOpen: () => void,
ideMessenger: IIdeMessenger,
) {
const items = async ({ query }) => {
const options = [
...availableSlashCommandsRef.current,
{
title: "Build a custom prompt",
description: "Build a custom prompt",
type: "action",
id: "createPromptFile",
label: "Create Prompt File",
action: () => {
console.log("I", ideMessenger.request);
ideMessenger.request("config/newPromptFile", undefined);
},
name: "Create Prompt File",
},
];
return (
availableSlashCommandsRef.current?.filter((slashCommand) => {
options.filter((slashCommand) => {
const sc = slashCommand.title.substring(1).toLowerCase();
const iv = query.toLowerCase();
return sc.startsWith(iv);
@ -175,7 +191,8 @@ export function getCommandSuggestion(
id: provider.title,
title: provider.title,
label: provider.title,
type: "slashCommand" as ComboBoxItemType,
type: (provider.type ?? "slashCommand") as ComboBoxItemType,
action: provider.action,
}));
};
return getSuggestion(items, undefined, onClose, onOpen);

View file

@ -1,3 +1,4 @@
import { RangeInFile } from "core";
import { useContext, useEffect, useState } from "react";
import { useSelector } from "react-redux";
import styled from "styled-components";
@ -24,14 +25,13 @@ function LinkableCode(props: any) {
const [linkingDone, setLinkingDone] = useState(false);
const [isLink, setIsLink] = useState(false);
const [filepath, setFilepath] = useState("");
const [line, setLine] = useState(0);
const [rif, setRif] = useState<undefined | RangeInFile>(undefined);
useEffect(() => {
if (linkingDone) return;
setLinkingDone(true);
// Get filename from props.children
// Get content of the code tag
let content: string | undefined = undefined;
if (typeof props.children === "string") {
content = props.children;
@ -44,7 +44,7 @@ function LinkableCode(props: any) {
}
if (!content) return;
// Check if this is a real file
// Match filepath with context items
const contextItemFileMatch = contextItems.find(
(item) =>
["file", "codebase", "folder"].includes(item.id.providerTitle) &&
@ -58,38 +58,89 @@ function LinkableCode(props: any) {
.split(" (")[1]
.split(")")[0]
.split("-");
setFilepath(contextItemFileMatch.description.split(" (")[0]);
setLine(parseInt(startLine));
const filepath = contextItemFileMatch.description.split(" (")[0];
setRif({
filepath,
range: {
start: {
line: 0,
character: 0,
},
end: {
line: 0,
character: 0,
},
},
});
return;
} else {
setFilepath(contextItemFileMatch.description.split(" (")[0]);
setLine(0);
// If no line number, just open the file
setRif({
filepath: contextItemFileMatch.description.split(" (")[0],
range: {
start: {
line: 0,
character: 0,
},
end: {
line: 0,
character: 0,
},
},
});
return;
}
}
if (content.length > 6) {
// Try to match the content with a line in a file
if (content.length > 8) {
const contextItemContentMatch = contextItems.find(
(item) =>
["file", "codebase", "folder"].includes(item.id.providerTitle) &&
item.content.includes(content),
);
if (contextItemContentMatch) {
const line = contextItemContentMatch.content
.split("\n")
.slice(1) // code block fence
.findIndex((line) => line.includes(content));
const [filepath, rest] =
contextItemContentMatch.description.split(" (");
const [startLine, endLine] = rest.split(")")[0]?.split("-") || [
"0",
"0",
];
const start = parseInt(startLine);
const end = parseInt(endLine);
setIsLink(true);
setFilepath(contextItemContentMatch.description.split(" (")[0]);
setLine(
contextItemContentMatch.content
.split("\n")
.findIndex((line) => line.includes(content)) + 1,
);
setRif({
filepath,
range: {
start: {
line: start + line,
character: 0,
},
end: {
line: start + line + 1,
character: 0,
},
},
});
console.log("MATCH: ", content, contextItemContentMatch, line);
}
}
}, [linkingDone, contextItems]);
const onClick = () => {
if (!isLink) return;
if (!rif) return;
ideMessenger.post("showLines", {
filepath,
startLine: line,
endLine: line + 1,
filepath: rif.filepath,
startLine: rif.range.start.line,
endLine: rif.range.end.line,
});
};