use lazy edit in apply

This commit is contained in:
Nate 2024-09-11 10:08:20 -07:00
parent 7d7207dcc2
commit 64e50ec1fa
8 changed files with 364 additions and 35 deletions

View file

@ -1,6 +1,6 @@
import { distance } from "fastest-levenshtein";
import { LineStream } from "../diff/util";
import { DiffLine } from "../";
import { LineStream } from "../diff/util";
export type LineFilter = (args: {
lines: LineStream;
@ -238,9 +238,10 @@ export async function* stopAtSimilarLine(
export async function* stopAtLines(
stream: LineStream,
fullStop: () => void,
linesToStopAt: string[] = LINES_TO_STOP_AT,
): LineStream {
for await (const line of stream) {
if (LINES_TO_STOP_AT.some((stopAt) => line.trim().includes(stopAt))) {
if (linesToStopAt.some((stopAt) => line.trim().includes(stopAt))) {
fullStop();
break;
}
@ -382,6 +383,17 @@ export async function* filterEnglishLinesAtEnd(lines: LineStream) {
}
}
export async function* filterLeadingNewline(lines: LineStream): LineStream {
let firstLine = true;
for await (const line of lines) {
if (firstLine && line.trim() === "") {
firstLine = false;
continue;
}
yield line;
}
}
/**
* Removes leading indentation from the first line of a CodeLlama output.
* @param {LineStream} lines - The input stream of lines.

View file

@ -14,6 +14,7 @@ import { recentlyEditedFilesCache } from "./context/retrieval/recentlyEditedFile
import { ContinueServerClient } from "./continueServer/stubs/client";
import { getAuthUrlForTokenPage } from "./control-plane/auth/index";
import { ControlPlaneClient } from "./control-plane/client";
import { streamDiffLines } from "./edit/streamDiffLines";
import { CodebaseIndexer, PauseToken } from "./indexing/CodebaseIndexer";
import DocsService from "./indexing/docs/DocsService";
import Ollama from "./llm/llms/Ollama";
@ -27,7 +28,6 @@ import type { IMessenger, Message } from "./util/messenger";
import { editConfigJson } from "./util/paths";
import { Telemetry } from "./util/posthog";
import { TTS } from "./util/tts";
import { streamDiffLines } from "./util/verticalEdit";
export class Core {
// implements IMessenger<ToCoreProtocol, FromCoreProtocol>

View file

@ -93,19 +93,31 @@ export function matchLine(
*/
export async function* streamLines(
streamCompletion: AsyncGenerator<string | ChatMessage>,
log: boolean = false,
): LineStream {
let allLines = [];
let buffer = "";
for await (const update of streamCompletion) {
const chunk =
typeof update === "string" ? update : stripImages(update.content);
buffer += chunk;
const lines = buffer.split("\n");
buffer = lines.pop() ?? "";
for (const line of lines) {
yield line;
try {
for await (const update of streamCompletion) {
const chunk =
typeof update === "string" ? update : stripImages(update.content);
buffer += chunk;
const lines = buffer.split("\n");
buffer = lines.pop() ?? "";
for (const line of lines) {
yield line;
allLines.push(line);
}
}
if (buffer.length > 0) {
yield buffer;
allLines.push(buffer);
}
} finally {
if (log) {
console.log("Streamed lines: ", allLines.join("\n"));
}
}
if (buffer.length > 0) {
yield buffer;
}
}

51
core/edit/lazy/prompts.ts Normal file
View file

@ -0,0 +1,51 @@
import { ChatMessage, ModelProvider } from "../..";
import { dedent } from "../../util";
export const UNCHANGED_CODE = "UNCHANGED CODE";
type LazyApplyPrompt = (
oldCode: string,
filename: string,
newCode: string,
) => ChatMessage[];
function claude35SonnetLazyApplyPrompt(
...args: Parameters<LazyApplyPrompt>
): ReturnType<LazyApplyPrompt> {
const userContent = dedent`
ORIGINAL CODE:
\`\`\`${args[1]}
${args[0]}
\`\`\`
NEW CODE:
\`\`\`
${args[2]}
\`\`\`
Above is a code block containing the original version of a file (ORIGINAL CODE) and below it is a code snippet (NEW CODE) that was suggested as modification to the original file.
Your task is to apply the NEW CODE to the ORIGINAL CODE and show what the entire file would look like after it is applied. Your response should be a code block containing a new version of the entire file. Whenever any part of the code is the same as before, you may simply indicate this with a comment that says "${UNCHANGED_CODE}" instead of rewriting. You may do this for imports as well if needed. Do not explain your changes either before or after the code block.
`;
const assistantContent = dedent`
Sure! Here's the modified version of the file after applying the new code:
\`\`\`${args[1]}
`;
return [
{ role: "user", content: userContent },
{ role: "assistant", content: assistantContent },
];
}
export function lazyApplyPromptForModel(
model: string,
provider: ModelProvider,
): LazyApplyPrompt | undefined {
if (model.includes("sonnet")) {
return claude35SonnetLazyApplyPrompt;
}
return undefined;
}

View file

@ -0,0 +1,184 @@
import {
filterLeadingAndTrailingNewLineInsertion,
filterLeadingNewline,
stopAtLines,
} from "../../autocomplete/lineStream.js";
import { streamDiff } from "../../diff/streamDiff.js";
import { LineStream, streamLines } from "../../diff/util.js";
import { DiffLine, ILLM } from "../../index.js";
import { lazyApplyPromptForModel, UNCHANGED_CODE } from "./prompts.js";
export async function* streamLazyApply(
oldCode: string,
filename: string,
newCode: string,
llm: ILLM,
): AsyncGenerator<DiffLine> {
const promptFactory = lazyApplyPromptForModel(llm.model, llm.providerName);
if (!promptFactory) {
throw new Error(`Lazy apply not supported for model ${llm.model}`);
}
const promptMessages = promptFactory(oldCode, filename, newCode);
const lazyCompletion = llm.streamChat(promptMessages);
// Do find and replace over the lazy edit response
async function replacementFunction(
oldCode: string,
linesBefore: string[],
linesAfter: string[],
): Promise<string> {
let r = getReplacementByMatching(oldCode, linesBefore, linesAfter);
if (r) {
return r;
}
r = await getReplacementWithLlm(oldCode, linesBefore, linesAfter, llm);
if (r) {
return r;
}
return "// NO REPLACEMENT FOUND";
}
let lazyCompletionLines = streamLines(lazyCompletion, true);
// Process line output
// lazyCompletionLines = filterEnglishLinesAtStart(lazyCompletionLines);
lazyCompletionLines = stopAtLines(lazyCompletionLines, () => {}, ["```"]);
lazyCompletionLines = filterLeadingNewline(lazyCompletionLines);
// Fill in unchanged code
let lines = streamFillUnchangedCode(
lazyCompletionLines,
oldCode,
replacementFunction,
);
// Convert output to diff
const oldLines = oldCode.split(/\r?\n/);
let diffLines = streamDiff(oldLines, lines);
diffLines = filterLeadingAndTrailingNewLineInsertion(diffLines);
for await (const diffLine of diffLines) {
yield diffLine;
}
}
const BUFFER_LINES_BELOW = 2;
async function* streamFillUnchangedCode(
lines: LineStream,
oldCode: string,
replacementFunction: (
oldCode: string,
linesBefore: string[],
linesAfter: string[],
) => Promise<string>,
): LineStream {
const newLines = [];
let buffer = [];
let waitingForBuffer = false;
for await (const line of lines) {
if (waitingForBuffer) {
buffer.push(line);
if (buffer.length >= BUFFER_LINES_BELOW) {
// Find the replacement and continue streaming once we have it
const replacement = await replacementFunction(
oldCode,
newLines,
buffer,
);
for (const replacementLine of replacement.split("\n")) {
yield replacementLine;
newLines.push(replacementLine);
}
console.log("FOUND REPLACEMENT:\n", replacement);
// Yield the buffered lines
for (const bufferedLine of buffer) {
yield bufferedLine;
newLines.push(bufferedLine);
}
waitingForBuffer = false;
buffer = [];
} else {
continue;
}
}
if (line.includes(UNCHANGED_CODE)) {
// Buffer so we can give the context of BUFFER_LINES_BELOW lines below
waitingForBuffer = true;
// TODO: If the UNCHANGED CODE is at the very top of the file we need to handle a bit differently
} else {
yield line;
newLines.push(line);
}
}
if (waitingForBuffer) {
// If we're still waiting for a buffer, we've reached the end of the stream
// and we should just look for the replacement with what we have
const replacement = await replacementFunction(oldCode, newLines, buffer);
for (const replacementLine of replacement.split("\n")) {
yield replacementLine;
newLines.push(replacementLine);
}
// Yield the buffered lines
for (const bufferedLine of buffer) {
yield bufferedLine;
newLines.push(bufferedLine);
}
}
}
const MATCH_LINES_ABOVE = 1;
function getReplacementByMatching(
oldCode: string,
linesBefore: string[],
linesAfter: string[],
): string | undefined {
const oldLines = oldCode.split("\n");
const linesToMatchAbove = MATCH_LINES_ABOVE;
const linesToMatchBelow = Math.min(BUFFER_LINES_BELOW, linesAfter.length);
// Get surrounding lines around the gap
const beforeContext = linesBefore.slice(-linesToMatchAbove).join("\n");
const afterContext = linesAfter.slice(0, linesToMatchBelow).join("\n");
// Find the start index in the old code
const startIndex = oldLines.findIndex((line, index) => {
const chunk = oldLines.slice(index, index + linesToMatchAbove).join("\n");
return chunk === beforeContext;
});
if (startIndex === -1) {
return undefined; // Couldn't find matching start
}
// Find the end index in the old code
const endIndex = oldLines.findIndex((line, index) => {
if (index <= startIndex + linesToMatchBelow) return false;
const chunk = oldLines.slice(index, index + linesToMatchBelow).join("\n");
return chunk === afterContext;
});
if (endIndex === -1) {
return undefined; // Couldn't find matching end
}
// Extract the replacement code
const replacement = oldLines
.slice(startIndex + linesToMatchAbove, endIndex)
.join("\n");
return replacement;
}
async function getReplacementWithLlm(
oldCode: string,
linesBefore: string[],
linesAfter: string[],
llm: ILLM,
): Promise<string> {
return "// TODO";
}

View file

@ -15,7 +15,7 @@ import {
LLMFullCompletionOptions,
} from "../index.js";
import { gptEditPrompt } from "../llm/templates/edit.js";
import { Telemetry } from "./posthog.js";
import { Telemetry } from "../util/posthog.js";
function constructPrompt(
prefix: string,

View file

@ -1,7 +1,9 @@
import { ConfigHandler } from "core/config/ConfigHandler";
import { pruneLinesFromBottom, pruneLinesFromTop } from "core/llm/countTokens";
import { getMarkdownLanguageTagForFile } from "core/util";
import { streamDiffLines } from "core/util/verticalEdit";
import { DiffLine } from "core";
import { streamDiffLines } from "core/edit/streamDiffLines";
import * as vscode from "vscode";
import { VerticalPerLineDiffHandler } from "./handler";
@ -29,7 +31,7 @@ export class VerticalPerLineDiffManager {
filepath: string,
startLine: number,
endLine: number,
input: string,
input?: string,
) {
if (this.filepathToHandler.has(filepath)) {
this.filepathToHandler.get(filepath)?.clear(false);
@ -172,6 +174,71 @@ export class VerticalPerLineDiffManager {
}
}
async streamDiffLines(diffStream: AsyncGenerator<DiffLine>) {
vscode.commands.executeCommand("setContext", "continue.diffVisible", true);
// Get the current editor filepath/range
let editor = vscode.window.activeTextEditor;
if (!editor) {
return;
}
const filepath = editor.document.uri.fsPath;
const startLine = 0;
const endLine = editor.document.lineCount - 1;
// Check for existing handlers in the same file the new one will be created in
const existingHandler = this.getHandlerForFile(filepath);
if (existingHandler) {
existingHandler.clear(false);
}
await new Promise((resolve) => {
setTimeout(resolve, 200);
});
// Create new handler with determined start/end
const diffHandler = this.createVerticalPerLineDiffHandler(
filepath,
startLine,
endLine,
);
if (!diffHandler) {
console.warn("Issue occured while creating new vertical diff handler");
return;
}
if (editor.selection) {
// Unselect the range
editor.selection = new vscode.Selection(
editor.selection.active,
editor.selection.active,
);
}
vscode.commands.executeCommand(
"setContext",
"continue.streamingDiff",
true,
);
try {
await diffHandler.run(diffStream);
// enable a listener for user edits to file while diff is open
this.enableDocumentChangeListener();
} catch (e) {
this.disableDocumentChangeListener();
vscode.window.showErrorMessage(`Error streaming diff: ${e}`);
} finally {
vscode.commands.executeCommand(
"setContext",
"continue.streamingDiff",
false,
);
}
}
/**
* Streams an edit to the current document based on user input and model output.
*

View file

@ -1,4 +1,5 @@
import { ConfigHandler } from "core/config/ConfigHandler";
import { streamLazyApply } from "core/edit/lazy/streamLazyApply";
import {
FromCoreProtocol,
FromWebviewProtocol,
@ -11,18 +12,19 @@ import {
CORE_TO_WEBVIEW_PASS_THROUGH,
WEBVIEW_TO_CORE_PASS_THROUGH,
} from "core/protocol/passThrough";
import { getBasename } from "core/util";
import { InProcessMessenger, Message } from "core/util/messenger";
import { getConfigJsonPath } from "core/util/paths";
import * as fs from "node:fs";
import * as path from "node:path";
import * as vscode from "vscode";
import { VerticalPerLineDiffManager } from "../diff/verticalPerLine/manager";
import { VsCodeIde } from "../VsCodeIde";
import {
getControlPlaneSessionInfo,
WorkOsAuthProvider,
} from "../stubs/WorkOsAuthProvider";
import { getExtensionUri } from "../util/vscode";
import { VsCodeIde } from "../VsCodeIde";
import { VsCodeWebviewProtocol } from "../webviewProtocol";
/**
@ -124,35 +126,36 @@ export class VsCodeMessenger {
});
this.onWebview("applyToCurrentFile", async (msg) => {
// Select the entire current file
// Get active text editor
const editor = vscode.window.activeTextEditor;
if (!editor) {
vscode.window.showErrorMessage("No active editor to apply edits to");
return;
}
if (editor.selection.isEmpty) {
const document = editor.document;
const start = new vscode.Position(0, 0);
const end = new vscode.Position(
document.lineCount - 1,
document.lineAt(document.lineCount - 1).text.length,
);
editor.selection = new vscode.Selection(start, end);
}
const verticalDiffManager = await this.verticalDiffManagerPromise;
const prompt = `The following code was suggested as an edit:\n\`\`\`\n${msg.data.text}\n\`\`\`\nPlease apply it to the previous code.`;
// Get LLM from config
const configHandler = await configHandlerPromise;
const config = await configHandler.loadConfig();
const modelTitle =
config.experimental?.modelRoles?.applyCodeBlock ??
(await this.webviewProtocol.request("getDefaultModelTitle", undefined));
const llm = config.models.find((model) => model.title === modelTitle);
if (!llm) {
vscode.window.showErrorMessage(
`Model ${modelTitle} not found in config.`,
);
return;
}
verticalDiffManager.streamEdit(prompt, modelTitle);
// Generate the diff and pass through diff manager
const diffLines = streamLazyApply(
editor.document.getText(),
getBasename(editor.document.fileName),
msg.data.text,
llm,
);
const verticalDiffManager = await this.verticalDiffManagerPromise;
verticalDiffManager.streamDiffLines(diffLines);
});
this.onWebview("showTutorial", async (msg) => {