Merge pull request #2194 from continuedev/nate/better-diff-algo

Improved diff algo and testing
This commit is contained in:
Nate Sesti 2024-09-05 19:44:20 -07:00 • committed by GitHub
commit b5b0b3f32e
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
14 changed files with 598 additions and 122 deletions

View file

@ -1,44 +0,0 @@
on:
defaults:
run:
working-directory: ./server
jobs:
lint:
runs-on: ubuntu-latest
name: ${{ matrix.name }}
strategy:
fail-fast: false
matrix:
include:
- name: ruff
command: ruff check --output-format=github .
deps: --only lint-ruff
- name: mypy
command: mypy
deps: --with lint-typing
steps:
- uses: actions/checkout@v4
- name: Install Python
uses: actions/setup-python@v4
with:
python-version: "3.11"
- uses: snok/install-poetry@v1
- name: Install dependencies
run: poetry install ${{ matrix.deps }}
- run: poetry run ${{ matrix.command }}
# test:
# runs-on: ubuntu-latest
# steps:
# - uses: actions/checkout@v4
# - name: Install Python
# uses: actions/setup-python@v4
# with:
# python-version: "3.12"
# - uses: snok/install-poetry@v1
# - run: poetry run python -m pip install --upgrade pip setuptools
# - name: Install dependencies
# run: poetry install
# - run: poetry run pytest

View file

@ -1,65 +0,0 @@
on:
name: Rust Continuous integration
defaults:
run:
working-directory: ./server
jobs:
# test:
# name: test
# runs-on: ${{ matrix.os }}
# strategy:
# matrix:
# os: [ubuntu-latest, macos-latest, windows-latest]
# toolchain: [stable]
# include:
# - os: ubuntu-latest
# toolchain: nightly
# steps:
# - uses: actions/checkout@v4
# - uses: dtolnay/rust-toolchain@master
# with:
# toolchain: ${{ matrix.toolchain }}
# - run: cargo test --all-features
fmt:
name: format
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- uses: dtolnay/rust-toolchain@nightly
with:
components: rustfmt
- run: cargo fmt --all --check
clippy:
name: lint
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- uses: dtolnay/rust-toolchain@master
with:
toolchain: nightly-2023-12-10
components: clippy
- uses: actions-rs-plus/clippy-check@v2
with:
working-directory: server/
args: --all-features --all-targets
docs:
name: docs
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- uses: dtolnay/rust-toolchain@stable
- run: cargo doc --no-deps
cargo-deny:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- uses: EmbarkStudios/cargo-deny-action@v1
with:
arguments: --manifest-path server/Cargo.toml

View file

@ -1,11 +1,19 @@
import fs from "node:fs";
import { streamDiff } from "../diff/streamDiff.js";
import { DiffLine, DiffLineType } from "../index.js";
// @ts-ignore no typings available
import { changed, diff as myersDiff } from "myers-diff";
import path from "node:path";
// "modification" is an extra type used to represent an "old" + "new" diff line
type MyersDiffTypes = Extract<DiffLineType, "new" | "old"> | "modification";
const UNIFIED_DIFF_SYMBOLS = {
same: "",
new: "+",
old: "-",
};
async function* generateLines(lines: string[]): AsyncGenerator<string> {
for (const line of lines) {
yield line;
@ -43,6 +51,43 @@ function getMyersDiffType(diff: any): MyersDiffTypes | undefined {
return undefined;
}
function displayDiff(diff: DiffLine[]) {
return diff
.map(({ type, line }) => `${UNIFIED_DIFF_SYMBOLS[type]} ${line}`)
.join("\n");
}
async function expectDiff(file: string) {
const testFilePath = path.join(
__dirname,
"diff",
"test-examples",
file + ".diff",
);
const testFileContents = fs.readFileSync(testFilePath, "utf-8");
const [oldText, newText, expectedDiff] = testFileContents
.split("\n---\n")
.map((s) => s.replace(/^\n+/, "").trimEnd());
const oldLines = oldText.split("\n");
const newLines = newText.split("\n");
const { streamDiffs, myersDiffs } = await collectDiffs(oldLines, newLines);
const displayedDiff = displayDiff(streamDiffs);
if (!expectedDiff || expectedDiff.trim() === "") {
console.log(
"Expected diff was empty. Writing computed diff to the test file",
);
fs.writeFileSync(
testFilePath,
`${oldText}\n\n---\n\n${newText}\n\n---\n\n${displayedDiff}`,
);
throw new Error("Expected diff is empty");
}
expect(displayedDiff).toEqual(expectedDiff);
}
// We use a longer `)` string here to not get
// caught by the fuzzy matcher
describe("streamDiff(", () => {
@ -177,4 +222,20 @@ describe("streamDiff(", () => {
expect(myersDiffs[0].lhs.del).toEqual(2);
expect(getMyersDiffType(myersDiffs[0])).toBe("old");
});
test("tabs vs. spaces differences are ignored", async () => {
await expectDiff("fastapi-tabs-vs-spaces");
});
test("FastAPI example", async () => {
await expectDiff("fastapi");
});
test("FastAPI comments", async () => {
await expectDiff("add-comments");
});
test("Mock LLM example", async () => {
await expectDiff("mock-llm");
});
});

View file

@ -0,0 +1,23 @@
# Diff algorithm tests
Tests are specified as
```
<CODE BEFORE>
---
<CODE AFTER>
---
<EXPECTED DIFF>
```
`---` is the delimeter, and surrounding whitespace will be trimmed.
The expected diff can be generated with the `displayDiff` function.
We make this explicit instead of comparing to the output of `myersDiff` in case the output from that is either unattainable or not exactly what we want.
In order to generate the expected diff, you can first leave it empty and then run the test. The test will catch this and write the _computed_ diff to the test file. It is up to you to correct this to the expected diff.

View file

@ -0,0 +1,53 @@
from fastapi import FastAPI
app = FastAPI()
@app.get("/")
def read_root():
return {"Hello": "World"}
@app.get("/landing")
def read_landing_page():
return {"message": "Welcome to the landing page"}
---
# Import the FastAPI class from the fastapi module
from fastapi import FastAPI
# Create an instance of the FastAPI application
app = FastAPI()
# Define a route for the root endpoint ("/")
@app.get("/")
def read_root():
# Return a simple JSON response
return {"Hello": "World"} // This is an example comment
# Define a route for the landing page endpoint ("/landing")
@app.get("/landing")
def read_landing_page():
# Return a JSON response with a welcome message
return {"message": "Welcome to the landing page"}
---
+ # Import the FastAPI class from the fastapi module
from fastapi import FastAPI
+ # Create an instance of the FastAPI application
app = FastAPI()
+ # Define a route for the root endpoint ("/")
@app.get("/")
def read_root():
+ # Return a simple JSON response
+ return {"Hello": "World"} // This is an example comment
+
+ # Define a route for the landing page endpoint ("/landing")
- return {"Hello": "World"}
-
@app.get("/landing")
def read_landing_page():
+ # Return a JSON response with a welcome message
return {"message": "Welcome to the landing page"}

View file

@ -0,0 +1,42 @@
from fastapi import FastAPI
app = FastAPI()
@app.get("/")
def read_root():
\treturn {"Hello": "World"}
@app.get("/landing")
def read_landing_page():
\treturn {"message": "Welcome to the landing page"}
---
from fastapi import FastAPI, HTTPException
app = FastAPI()
@app.get("/")
def read_root():
return {"Hello": "World"}
@app.get("/landing")
def read_landing_page():
raise HTTPException(status_code=404, detail="Page not found")
---
- from fastapi import FastAPI
+ from fastapi import FastAPI, HTTPException
app = FastAPI()
@app.get("/")
def read_root():
- \treturn {"Hello": "World"}
+ return {"Hello": "World"}
@app.get("/landing")
def read_landing_page():
+ raise HTTPException(status_code=404, detail="Page not found")
- \treturn {"message": "Welcome to the landing page"}

View file

@ -0,0 +1,41 @@
from fastapi import FastAPI
app = FastAPI()
@app.get("/")
def read_root():
return {"Hello": "World"}
@app.get("/landing")
def read_landing_page():
return {"message": "Welcome to the landing page"}
---
from fastapi import FastAPI, HTTPException
app = FastAPI()
@app.get("/")
def read_root():
return {"Hello": "World"}
@app.get("/landing")
def read_landing_page():
raise HTTPException(status_code=404, detail="Page not found")
---
- from fastapi import FastAPI
+ from fastapi import FastAPI, HTTPException
app = FastAPI()
@app.get("/")
def read_root():
return {"Hello": "World"}
@app.get("/landing")
def read_landing_page():
+ raise HTTPException(status_code=404, detail="Page not found")
- return {"message": "Welcome to the landing page"}

View file

@ -0,0 +1,103 @@
import { ChatMessage, CompletionOptions, ModelProvider } from "../../index.js";
import { BaseLLM } from "../index.js";
class Mock extends BaseLLM {
static Completion = "Test Completion";
static providerName: ModelProvider = "mock";
protected async *_streamComplete(
prompt: string,
options: CompletionOptions,
): AsyncGenerator<string> {
yield Mock.Completion;
}
protected async *_streamChat(
messages: ChatMessage[],
options: CompletionOptions,
): AsyncGenerator<ChatMessage> {
yield {
role: "assistant",
content: Mock.Completion,
};
}
}
export default Mock;
---
import { ChatMessage, CompletionOptions, ModelProvider } from "../../index.js";
import { BaseLLM } from "../index.js";
class Mock extends BaseLLM {
private static _completion: string = "Test Completion";
static providerName: ModelProvider = "mock";
static get completion(): string {
return Mock._completion;
}
static set completion(value: string) {
Mock._completion = value;
}
protected async *_streamComplete(
prompt: string,
options: CompletionOptions,
): AsyncGenerator<string> {
yield Mock.completion;
}
protected async *_streamChat(
messages: ChatMessage[],
options: CompletionOptions,
): AsyncGenerator<ChatMessage> {
yield {
role: "assistant",
content: Mock.completion,
};
}
}
export default Mock;
---
import { ChatMessage, CompletionOptions, ModelProvider } from "../../index.js";
import { BaseLLM } from "../index.js";
class Mock extends BaseLLM {
- static Completion = "Test Completion";
+ private static _completion: string = "Test Completion";
static providerName: ModelProvider = "mock";
+ static get completion(): string {
+ return Mock._completion;
+ }
+
+ static set completion(value: string) {
+ Mock._completion = value;
+ }
+
protected async *_streamComplete(
prompt: string,
options: CompletionOptions,
): AsyncGenerator<string> {
- yield Mock.Completion;
+ yield Mock.completion;
}
protected async *_streamChat(
messages: ChatMessage[],
options: CompletionOptions,
): AsyncGenerator<ChatMessage> {
yield {
role: "assistant",
- content: Mock.Completion,
+ content: Mock.completion,
};
}
}
export default Mock;

View file

@ -31,7 +31,8 @@ function linesMatch(lineA: string, lineB: string, linesBetween = 0): boolean {
return (
// Should be more unlikely for lines to fuzzy match if they are further away
(d / Math.max(lineA.length, lineB.length) < 0.5 - linesBetween * 0.05 ||
(d / Math.max(lineA.length, lineB.length) <=
Math.max(0, 0.48 - linesBetween * 0.06) ||
lineA.trim() === lineB.trim()) &&
lineA.trim() !== ""
);

138
core/util/dedent.test.ts Normal file
View file

@ -0,0 +1,138 @@
import { dedent } from "./index";
describe("dedent function", () => {
it("should remove common leading whitespace from all lines", () => {
const result = dedent`
Hello
World
!
`;
expect(result).toBe("Hello\n World\n !");
});
it("should handle strings with no indentation", () => {
const result = dedent`Hello
World
!`;
expect(result).toBe("Hello\nWorld\n!");
});
it("should handle strings with mixed indentation", () => {
const result = dedent`
Hello
World
!
`;
expect(result).toBe(" Hello\nWorld\n !");
});
it("should remove leading and trailing empty lines", () => {
const result = dedent`
Hello
World
`;
expect(result).toBe("Hello\nWorld");
});
it("should handle empty strings", () => {
const result = dedent``;
expect(result).toBe("");
});
it("should handle strings with only whitespace", () => {
const result = dedent`
`;
expect(result).toBe("");
});
it.skip("should handle strings with tabs", () => {
const result = dedent`
\tHello
\t\tWorld
\t\t\t!
`;
expect(result).toBe("\tHello\n\t\tWorld\n\t\t\t!");
});
it("should handle interpolated values", () => {
const world = "World";
const result = dedent`
Hello ${world}
How are you?
`;
expect(result).toBe("Hello World\n How are you?");
});
it("should handle multiple interpolated values", () => {
const greeting = "Hello";
const name = "Alice";
const question = "How are you?";
const result = dedent`
${greeting} ${name}
${question}
`;
expect(result).toBe("Hello Alice\n How are you?");
});
it("should handle interpolated values with different indentation", () => {
const value1 = "foo";
const value2 = "bar";
const result = dedent`
${value1}
${value2}
`;
expect(result).toBe("foo\n bar");
});
it("should handle a single line with indentation", () => {
const result = dedent` Hello World!`;
expect(result).toBe("Hello World!");
});
it("should handle a string with only one non-empty line", () => {
const result = dedent`
Hello World!
`;
expect(result).toBe("Hello World!");
});
it("should handle a string with Unicode characters", () => {
const result = dedent`
こんにちは
世界
`;
expect(result).toBe("こんにちは\n 世界");
});
it("should handle a string with emoji", () => {
const result = dedent`
🌍
🌎
🌏
`;
expect(result).toBe("🌍\n 🌎\n 🌏");
});
it.skip("should handle a string with CRLF line endings", () => {
const result = dedent`
Hello\r
World\r
`;
expect(result).toBe("Hello\r\n World");
});
it("should not count empty lines in the minimum indentation", () => {
const result = dedent`
Hello
World
`;
expect(result).toBe("Hello\n\nWorld");
});
});

View file

@ -2,19 +2,19 @@ export function removeQuotesAndEscapes(output: string): string {
output = output.trim();
// Replace smart quotes
output = output.replace("“", "\"");
output = output.replace("”", "\"");
output = output.replace("“", '"');
output = output.replace("”", '"');
output = output.replace("‘", "'");
output = output.replace("’", "'");
// Remove escapes
output = output.replace("\\\"", "\"");
output = output.replace('\\"', '"');
output = output.replace("\\'", "'");
output = output.replace("\\n", "\n");
output = output.replace("\\t", "\t");
output = output.replace("\\\\", "\\");
while (
(output.startsWith("\"") && output.endsWith("\"")) ||
(output.startsWith('"') && output.endsWith('"')) ||
(output.startsWith("'") && output.endsWith("'"))
) {
output = output.slice(1, -1);
@ -120,7 +120,9 @@ export function getUniqueFilePath(
}
export function shortestRelativePaths(paths: string[]): string[] {
if (paths.length === 0) {return [];}
if (paths.length === 0) {
return [];
}
const partsLengths = paths.map((x) => x.split(SEP_REGEX).length);
const currentRelativePaths = paths.map(getBasename);
@ -135,7 +137,9 @@ export function shortestRelativePaths(paths: string[]): string[] {
const firstDuplicatedPath = currentRelativePaths.find(
(x, i) => isDuplicated[i],
);
if (!firstDuplicatedPath) {break;}
if (!firstDuplicatedPath) {
break;
}
currentRelativePaths.forEach((x, i) => {
if (x === firstDuplicatedPath) {
@ -270,3 +274,33 @@ export function deduplicateArray<T>(
}
export type TODO = any;
export function dedent(strings: TemplateStringsArray, ...values: any[]) {
let result = strings.reduce(
(acc, str, i) => acc + str + (values[i] || ""),
"",
);
result = result.replace(/^\n/, "").replace(/\n\s*$/, "");
let lines = result.split("\n");
// Remove leading white-space-only lines
while (lines.length > 0 && lines[0].trim() === "") {
lines.shift();
}
// Remove trailing white-space-only lines
while (lines.length > 0 && lines[lines.length - 1].trim() === "") {
lines.pop();
}
const minIndent = lines.reduce((min, line) => {
if (line.trim() === "") {
// Don't consider empty lines when calculating indentation
return min;
}
const match = line.match(/^\s*/);
return Math.min(min, match ? match[0].length : Infinity);
}, Infinity);
return lines.map((line) => line.slice(minIndent)).join("\n");
}

View file

@ -81,6 +81,9 @@ export async function* streamDiffLines(
oldLines = [];
}
// Trim end of oldLines, otherwise we have trailing \r on every line for CRLF files
oldLines = oldLines.map((line) => line.trimEnd());
const prompt = constructPrompt(
prefix,
highlighted,

View file

@ -200,8 +200,8 @@
"### Free Trial\nNew users can try out Continue for free using a proxy server that securely makes calls to OpenAI using our API key. If you are ready to use your own API key or have used all 250 free uses, you can enter your API key in config.json where it says `apiKey=\"\"` or select another model provider.\n> [Reference](https://docs.continue.dev/reference/Model%20Providers/freetrial)",
"### Anthropic\nTo get started with Anthropic models, you first need to sign up for the open beta [here](https://claude.ai/login) to obtain an API key.\n> [Reference](https://docs.continue.dev/reference/Model%20Providers/anthropicllm)",
"### Cohere\nTo use Cohere, visit the [Cohere dashboard](https://dashboard.cohere.com/api-keys) to create an API key.\n\n> [Reference](https://docs.continue.dev/reference/Model%20Providers/cohere)",
"### Bedrock\nTo get started with Bedrock you need to sign up on AWS [here](https://aws.amazon.com/bedrock/claude/)",
"### Bedrock Imported Models\nTo get started with Bedrock you need to sign up on AWS [here](https://aws.amazon.com/bedrock/claude/)",
"### Bedrock\nTo get started with Bedrock you need to sign up on AWS [here](https://aws.amazon.com/bedrock)",
"### Bedrock Imported Models\nTo get started with Bedrock you need to sign up on AWS [here](https://aws.amazon.com/bedrock)",
"### Sagemaker\nSagemaker is AWS' machine learning platform.",
"### Together\nTogether is a hosted service that provides extremely fast streaming of open-source language models. To get started with Together:\n1. Obtain an API key from [here](https://together.ai)\n2. Paste below\n3. Select a model preset\n> [Reference](https://docs.continue.dev/reference/Model%20Providers/togetherllm)",
"### Ollama\nTo get started with Ollama, follow these steps:\n1. Download from [ollama.ai](https://ollama.ai/) and open the application\n2. Open a terminal and run `ollama run <MODEL_NAME>`. Example model names are `codellama:7b-instruct` or `llama2:7b-text`. You can find the full list [here](https://ollama.ai/library).\n3. Make sure that the model name used in step 2 is the same as the one in config.json (e.g. `model=\"codellama:7b-instruct\"`)\n4. Once the model has finished downloading, you can start asking questions through Continue.\n> [Reference](https://docs.continue.dev/reference/Model%20Providers/ollama)",
@ -242,6 +242,21 @@
"description": "The base URL of the LLM API.",
"type": "string"
},
"region": {
"title": "Region",
"description": "The region where the model is hosted",
"type": "string"
},
"profile": {
"title": "Profile",
"description": "The AWS security profile to use",
"type": "string"
},
"modelArn": {
"title": "Profile",
"description": "The AWS arn for the imported model",
"type": "string"
},
"contextLength": {
"title": "Context Length",
"description": "The maximum context length of the LLM in tokens, as counted by countTokens.",
@ -393,6 +408,21 @@
"required": ["apiKey"]
}
},
{
"if": {
"properties": {
"provider": {
"enum": [
"bedrockimport"
]
}
},
"required": ["provider"]
},
"then": {
"required": ["modelArn"]
}
},
{
"if": {
"properties": {
@ -2030,7 +2060,8 @@
"cohere",
"free-trial",
"gemini",
"voyage"
"voyage",
"bedrock"
]
},
"model": {
@ -2053,6 +2084,16 @@
"type": "integer",
"minimum": 128,
"exclusiveMaximum": 2147483647
},
"region": {
"title": "Region",
"description": "The region where the model is hosted",
"type": "string"
},
"profile": {
"title": "Profile",
"description": "The AWS security profile to use",
"type": "string"
}
},
"required": ["provider"],

View file

@ -203,8 +203,8 @@
"### Free Trial\nNew users can try out Continue for free using a proxy server that securely makes calls to OpenAI using our API key. If you are ready to use your own API key or have used all 250 free uses, you can enter your API key in config.json where it says `apiKey=\"\"` or select another model provider.\n> [Reference](https://docs.continue.dev/reference/Model%20Providers/freetrial)",
"### Anthropic\nTo get started with Anthropic models, you first need to sign up for the open beta [here](https://claude.ai/login) to obtain an API key.\n> [Reference](https://docs.continue.dev/reference/Model%20Providers/anthropicllm)",
"### Cohere\nTo use Cohere, visit the [Cohere dashboard](https://dashboard.cohere.com/api-keys) to create an API key.\n\n> [Reference](https://docs.continue.dev/reference/Model%20Providers/cohere)",
"### Bedrock\nTo get started with Bedrock you need to sign up on AWS [here](https://aws.amazon.com/bedrock/claude/)",
"### Bedrock Imported Models\nTo get started with Bedrock you need to sign up on AWS [here](https://aws.amazon.com/bedrock/claude/)",
"### Bedrock\nTo get started with Bedrock you need to sign up on AWS [here](https://aws.amazon.com/bedrock)",
"### Bedrock Imported Models\nTo get started with Bedrock you need to sign up on AWS [here](https://aws.amazon.com/bedrock)",
"### Sagemaker\nSagemaker is AWS' machine learning platform.",
"### Together\nTogether is a hosted service that provides extremely fast streaming of open-source language models. To get started with Together:\n1. Obtain an API key from [here](https://together.ai)\n2. Paste below\n3. Select a model preset\n> [Reference](https://docs.continue.dev/reference/Model%20Providers/togetherllm)",
"### Ollama\nTo get started with Ollama, follow these steps:\n1. Download from [ollama.ai](https://ollama.ai/) and open the application\n2. Open a terminal and run `ollama run <MODEL_NAME>`. Example model names are `codellama:7b-instruct` or `llama2:7b-text`. You can find the full list [here](https://ollama.ai/library).\n3. Make sure that the model name used in step 2 is the same as the one in config.json (e.g. `model=\"codellama:7b-instruct\"`)\n4. Once the model has finished downloading, you can start asking questions through Continue.\n> [Reference](https://docs.continue.dev/reference/Model%20Providers/ollama)",
@ -245,6 +245,21 @@
"description": "The base URL of the LLM API.",
"type": "string"
},
"region": {
"title": "Region",
"description": "The region where the model is hosted",
"type": "string"
},
"profile": {
"title": "Profile",
"description": "The AWS security profile to use",
"type": "string"
},
"modelArn": {
"title": "Profile",
"description": "The AWS arn for the imported model",
"type": "string"
},
"contextLength": {
"title": "Context Length",
"description": "The maximum context length of the LLM in tokens, as counted by countTokens.",
@ -409,6 +424,25 @@
]
}
},
{
"if": {
"properties": {
"provider": {
"enum": [
"bedrockimport"
]
}
},
"required": [
"provider"
]
},
"then": {
"required": [
"modelArn"
]
}
},
{
"if": {
"properties": {
@ -2257,7 +2291,8 @@
"cohere",
"free-trial",
"gemini",
"voyage"
"voyage",
"bedrock"
]
},
"model": {
@ -2280,6 +2315,16 @@
"type": "integer",
"minimum": 128,
"exclusiveMaximum": 2147483647
},
"region": {
"title": "Region",
"description": "The region where the model is hosted",
"type": "string"
},
"profile": {
"title": "Profile",
"description": "The AWS security profile to use",
"type": "string"
}
},
"required": [