Merge branch 'main' into patch-3

This commit is contained in:
kongkong 2024-11-29 10:44:49 +08:00 • committed by GitHub
commit 3e8a14c54a
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
11 changed files with 233 additions and 289 deletions

View file

@ -9,7 +9,6 @@ export interface AutocompleteLanguageInfo {
topLevelKeywords: string[];
singleLineComment?: string;
endOfLine: string[];
stopWords?: string[];
lineFilters?: LineFilter[];
charFilters?: CharacterFilter[];
useMultiline?: (args: { prefix: string; suffix: string }) => boolean;

View file

@ -1,46 +0,0 @@
import { IDE, Location } from "../..";
import { LANGUAGES } from "../constants/AutocompleteLanguageInfo";
import { getSymbolsForSnippet } from "./ranking";
interface FileInfo {
filepath: string;
}
export class NearbyDefinitionsService {
static N = 10;
constructor(private readonly ide: IDE) {}
async getDefinitionsForLine(filepath: string, line: number) {
const lineContent = await this.ide.readRangeInFile(filepath, {
start: {
line,
character: 0,
},
end: {
line: line + 1,
character: 0,
},
});
// Remove keywords
const lang = LANGUAGES[filepath.split(".").slice(-1)[0]];
const symbols = Array.from(getSymbolsForSnippet(lineContent))
.filter((s) => s.length > 0)
.filter((s) => !(lang && lang?.stopWords?.includes(s)));
return Promise.all(
symbols.map((s) => {
const character = lineContent.indexOf(s);
const pos: Location = {
filepath,
position: {
line,
character,
},
};
}),
);
}
}

View file

@ -6,7 +6,7 @@ import { stopAtStartOf, stopAtStopTokens } from "./charStream";
import {
avoidEmptyComments,
avoidPathLine,
noDoubleNewlineAfterClosingBracket,
noDoubleNewLine,
showWhateverWeHaveAtXMs,
skipPrefixes,
stopAtLines,
@ -49,7 +49,7 @@ export class StreamTransformPipeline {
);
lineGenerator = avoidPathLine(lineGenerator, helper.lang.singleLineComment);
lineGenerator = skipPrefixes(lineGenerator);
lineGenerator = noDoubleNewlineAfterClosingBracket(lineGenerator);
lineGenerator = noDoubleNewLine(lineGenerator);
for (const lineFilter of helper.lang.lineFilters ?? []) {
lineGenerator = lineFilter({ lines: lineGenerator, fullStop });

View file

@ -171,46 +171,45 @@ describe("stopAtStartOf", () => {
controlPlaneEnv.CONTROL_PLANE_URL,
),
`;
/* Some LLMs, such as Codestral, repeat the suffix of the query. To test our filtering, we cut the sample code at random positions, remove a part of the input
and construct a response, containing the removed part and the suffix. The goal of the stopAtStartOf() method is to detect the start of the suffix in the response */
it("should stop if the start of the suffix is reached", async () => {
const removeLength = 10;
for (let i = 0; i < sampleCode.length - removeLength - 20; i++) {
const removed = sampleCode.slice(i, i + removeLength);
const suffix = sampleCode.slice(i + removeLength);
const response = removed + suffix;
const suffix = `
const data = await response.json();
return data.items;
}`;
const mockStream = createMockStream(sampleCode.split(/(?! )/g));
const result = stopAtStartOf(mockStream, suffix);
// split the response but keep spaces
const mockStream = createMockStream(response.split(/(?! )/g));
const result = stopAtStartOf(mockStream, suffix);
const resultStr = await streamToString(result);
if (resultStr !== removed) {
throw new Error(
`i=${i} result:\n${resultStr}\n\nremoved:\n${removed}\n\nsuffix:\n${suffix}`,
);
}
}
const resultStr = await streamToString(result);
expect(resultStr).toBe(` {
method: "GET",
headers: {
"Content-Type": "application/json",
Authorization: \`Bearer \${this.workOsAccessToken}\`,
},
},
);
`);
});
it("should stop if the start of the suffix is reached, even if the suffix has a prefix", async () => {
const removeLength = 10;
for (let i = 0; i < sampleCode.length - removeLength - 20; i++) {
const removed = sampleCode.slice(i, i + removeLength);
let suffix = sampleCode.slice(i + removeLength);
const response = removed + suffix;
// add a prefix to the suffix
suffix = "strange words;\n which start the suffix#" + suffix;
const suffix = `
xxxconst data = await response.json();
return data.items;
}`;
const mockStream = createMockStream(sampleCode.split(/(?! )/g));
const result = stopAtStartOf(mockStream, suffix);
// split the response but keep spaces
const mockStream = createMockStream(response.split(/(?! )/g));
const result = stopAtStartOf(mockStream, suffix);
const resultStr = await streamToString(result);
if (resultStr !== removed) {
throw new Error(
`i=${i} result:\n${resultStr}\n\nremoved:\n${removed}\n\nsuffix:\n${suffix}`,
);
}
}
const resultStr = await streamToString(result);
expect(resultStr).toBe(` {
method: "GET",
headers: {
"Content-Type": "application/json",
Authorization: \`Bearer \${this.workOsAccessToken}\`,
},
},
);
`);
});
});

View file

@ -119,8 +119,9 @@ export async function* stopAtStopTokens(
}
/**
* Asynchronously yields characters from the input stream, stopping if a sequence contained in the beginning of the suffix is encountered.
* */
* Asynchronously yields characters from the input stream.
* Stops if the beginning of the suffix is detected in the stream.
*/
export async function* stopAtStartOf(
stream: AsyncGenerator<string>,
suffix: string,
@ -132,42 +133,31 @@ export async function* stopAtStartOf(
}
return;
}
// We use sequenceLength * 1.5 as a heuristic to make sure we don't miss the sequence if the
// stream is not perfectly aligned with the sequence (small whitespace differences etc).
const targetPart = suffix
.trimStart()
.slice(0, Math.floor(sequenceLength * 1.5));
const n = Math.min(suffix.length, 3 * sequenceLength);
let prev = new Array(n + 1).fill(0);
let res = 0;
let buffer = "";
for await (const chunk of stream) {
const s1 = chunk;
const m = chunk.length;
for (let i = 1; i <= m; i++) {
// Create a temporary array to store the current row
let curr = new Array(n + 1).fill(0);
for (let j = 1; j <= n; j++) {
if (s1[i - 1] === suffix[j - 1]) {
curr[j] = prev[j - 1] + 1;
res = Math.max(res, curr[j]);
} else {
curr[j] = 0;
}
}
buffer += chunk;
// Move the current row's data to the previous row
prev = curr;
// Check if the targetPart contains contains the buffer at any point
if (buffer.length >= sequenceLength && targetPart.includes(buffer)) {
return; // Stop processing when the sequence is found
}
if (res > sequenceLength) {
return;
}
buffer += s1[i - 1];
while (buffer.length > sequenceLength) {
yield buffer[0];
buffer = buffer.slice(1);
}
// Yield chunk by chunk, ensuring not to exceed sequenceLength in the buffer
while (buffer.length > sequenceLength) {
yield buffer[0];
buffer = buffer.slice(1);
}
}
yield buffer;
// Yield the remaining buffer if it is not contained in the `targetPart`
if (buffer.length > 0) {
yield buffer;
}
}

View file

@ -537,53 +537,32 @@ export async function* showWhateverWeHaveAtXMs(
ms: number,
): LineStream {
const startTime = Date.now();
let firstNonWhitespaceLineYielded = false;
for await (const line of lines) {
// Always get at least one line
yield line;
// But after that, soft break at X ms
if (Date.now() - startTime > ms) {
if (!firstNonWhitespaceLineYielded && line.trim() !== "") {
firstNonWhitespaceLineYielded = true;
}
const isTakingTooLong = Date.now() - startTime > ms;
if (isTakingTooLong && firstNonWhitespaceLineYielded) {
break;
}
}
}
export async function* noDoubleNewlineAfterClosingBracket(
lines: LineStream,
): LineStream {
const bracketTypeCounts = new Map<string, number>();
export async function* noDoubleNewLine(lines: LineStream): LineStream {
let isFirstLine = true;
for await (const line of lines) {
if (line.trim() === "") {
// Double newline detected
// Check if any bracket counts are negative
let hasNegativeCount = false;
for (const count of bracketTypeCounts.values()) {
if (count < 0) {
hasNegativeCount = true;
break;
}
}
if (hasNegativeCount) {
// Stop the generator if we've closed brackets we didn't open
return;
}
if (line.trim() === "" && !isFirstLine) {
return;
}
isFirstLine = false;
yield line;
// Update bracket counts
for (const char of line) {
if (BRACKETS[char]) {
// It's an opening bracket
const count = bracketTypeCounts.get(char) || 0;
bracketTypeCounts.set(char, count + 1);
} else if (BRACKETS_REVERSE[char]) {
// It's a closing bracket
const openingBracket = BRACKETS_REVERSE[char];
const count = bracketTypeCounts.get(openingBracket) || 0;
bracketTypeCounts.set(openingBracket, count - 1);
}
}
}
}

View file

@ -110,6 +110,7 @@ Here is a list of features:
- Feature 2`,
},
{
// options: { only: true },
description: "Should autocomplete a Java method within a class",
filename: "Calculator.java",
input: `
@ -150,37 +151,7 @@ public class Calculator {
POSTGRES_DB: mydb
`,
expectedCompletion: `
POSTGRES_DB: mydb
`,
},
{
description:
"Should filter out suffix generated by LLM (sample from Codestral)",
filename: "test.js",
input: `
add(number) {
this.result += number;
return this;
}
// Add the subtract method
subtract(number) {<|fim|>
subtract(number) {
this.result -= number;
return this;
}
multiply(number) {
this.result *= number;
return this;
}`,
llmOutput: ` this.result -= number;
return this;
}
// Add the multiply method
multiply(number) {
`,
expectedCompletion: undefined,
POSTGRES_DB: mydb`,
},
{
description: "Should enforce bracket matching in JSON files",
@ -283,8 +254,7 @@ async getContextForPath(
): Promise<AutocompleteCodeSnippet[]> {
const snippets: AutocompleteCodeSnippet[] = [];
`,
expectedCompletion: `console.log('TEST');
`,
expectedCompletion: `console.log('TEST');`,
},
{
description: "Should autocomplete React effect hook",
@ -333,6 +303,82 @@ export const Timer = () => {
llmOutput: ` this;`,
expectedCompletion: `this;`,
},
{
description: "Should complete YAML list item and preserve structure",
filename: "test.yaml",
input: `
services:
- name: web
image: nginx
- name: app<|fim|>
volumes:
- volume1
- volume2
`,
llmOutput: `
image: node
`,
expectedCompletion: `
image: node`,
},
{
description:
"Should complete YAML key-value pair inside a nested structure",
filename: "test.yaml",
input: `
version: '3'
services:
db:
image: postgres
environment:
POSTGRES_USER: user
POSTGRES_PASSWORD: pass
POSTGRES_DB: mydb<|fim|>
`,
llmOutput: `
PGDATA: /var/lib/postgresql/data/pgdata
`,
expectedCompletion: `
PGDATA: /var/lib/postgresql/data/pgdata`,
},
{
description: "Should complete YAML block within an existing block",
filename: "test.yaml",
input: `
pipelines:
branches:
master:
- step:
name: Build and Test
script:
- npm install
- npm run test
- step:
name: Deploy<|fim|>
`,
llmOutput: `
script:
- npm run deploy
`,
expectedCompletion: `
script:
- npm run deploy`,
},
{
description:
"Should autocomplete SQL query with subquery and alias in SELECT clause",
filename: "complex_query.sql",
input: `SELECT u.id,
u.name,
(SELECT COUNT(*) FROM orders o WHERE o.user_id = u.id) AS order_count
FROM users u
WHERE u.active = 1
<|fim|>`,
llmOutput:
" AND EXISTS (SELECT 1 FROM transactions t WHERE t.user_id = u.id AND t.amount > 100)",
expectedCompletion:
"AND EXISTS (SELECT 1 FROM transactions t WHERE t.user_id = u.id AND t.amount > 100)",
},
];
export const TEST_CASES_WITHOUT_DIFF: AutocompleteFileringTestInput[] = [
@ -832,21 +878,6 @@ func main() {
llmOutput: " DEFAULT",
expectedCompletion: " DEFAULT",
},
{
description:
"Should autocomplete SQL query with subquery and alias in SELECT clause",
filename: "complex_query.sql",
input: `SELECT u.id,
u.name,
(SELECT COUNT(*) FROM orders o WHERE o.user_id = u.id) AS order_count
FROM users u
WHERE u.active = 1
<|fim|>`,
llmOutput:
" AND EXISTS (SELECT 1 FROM transactions t WHERE t.user_id = u.id AND t.amount > 100)",
expectedCompletion:
" AND EXISTS (SELECT 1 FROM transactions t WHERE t.user_id = u.id AND t.amount > 100)",
},
{
description:
"Should autocomplete multi-line SQL query with CASE statements",
@ -1030,70 +1061,6 @@ Smart<|fim|>`,
llmOutput: "ob, 2023-02-10",
expectedCompletion: "ob, 2023-02-10",
},
{
description: "Should complete YAML list item and preserve structure",
filename: "test.yaml",
input: `
services:
- name: web
image: nginx
- name: app<|fim|>
volumes:
- volume1
- volume2
`,
llmOutput: `
image: node
`,
expectedCompletion: `
image: node
`,
},
{
description:
"Should complete YAML key-value pair inside a nested structure",
filename: "test.yaml",
input: `
version: '3'
services:
db:
image: postgres
environment:
POSTGRES_USER: user
POSTGRES_PASSWORD: pass
POSTGRES_DB: mydb<|fim|>
`,
llmOutput: `
PGDATA: /var/lib/postgresql/data/pgdata
`,
expectedCompletion: `
PGDATA: /var/lib/postgresql/data/pgdata
`,
},
{
description: "Should complete YAML block within an existing block",
filename: "test.yaml",
input: `
pipelines:
branches:
master:
- step:
name: Build and Test
script:
- npm install
- npm run test
- step:
name: Deploy<|fim|>
`,
llmOutput: `
script:
- npm run deploy
`,
expectedCompletion: `
script:
- npm run deploy
`,
},
{
description:
"Should autocomplete a Rust function implementation inside a struct",
@ -2168,4 +2135,70 @@ export default {
llmOutput: "}",
expectedCompletion: "}",
},
{
description:
"Should handle autocomplete in two similar TypeScript functions",
filename: "List.svelte",
input: `
import { createClient, RedisClientType } from "redis";
import { IKeyValueStore } from "./index.js";
export class RedisKeyValueStore implements IKeyValueStore {
private client: RedisClientType;
constructor(redisUrl: string) {
this.client = createClient({
url: redisUrl
.replace("https://", "redis://")
.replace("http://", "redis://"),
});
this.client.on("connect", () => console.log("Redis Connected"));
this.client.on("error", (err) => console.log("Redis Client Error", err));
this.client.connect();
}
public async has(tableName: string, key: string): Promise<boolean> {
return (await this.client.exists(this._getKey(tableName, key))) > 0;
}
public async keys(tableName: string): Promise<string[]> {
const keys = await this.client.keys(this._getTableKey(tableName));
return keys.map((key) => key.split("::")[1]);
}
public async put(
tableName: string,
key: string,
value: string,
): Promise<void> {
await this.client.set(this._getKey(tableName, key), value);
}
public async get(
tableName: string,
key: string,
): Promise<string | undefined> {
const value = await this.client.get(this._getKey(tableName, key));
return value ?? undefined;
}
public async deleteAll(tableName: string): Promise<void> {
await this.client.del(this._getTableKey(tableName));
}
<|fim|>
public async remove(tableName: string, key: string): Promise<boolean> {
const result = await this.client.del(this._getKey(tableName, key));
return result > 0;
}
}
`,
llmOutput: ` public async delete(tableName: string, key: string): Promise<void> {
await this.client.del(this._getKey(tableName, key));
}`,
expectedCompletion: ` public async delete(tableName: string, key: string): Promise<void> {
await this.client.del(this._getKey(tableName, key));
}`,
},
];

View file

@ -43,11 +43,15 @@ function isExtremeRepetition(completion: string): boolean {
}
return false;
}
export function isOnlyWhitespace(completion: string): boolean {
function isOnlyWhitespace(completion: string): boolean {
const whitespaceRegex = /^[\s]+$/;
return whitespaceRegex.test(completion);
}
function isBlank(completion: string): boolean {
return completion.trim().length === 0;
}
export function postprocessCompletion({
completion,
llm,
@ -60,6 +64,11 @@ export function postprocessCompletion({
suffix: string;
}): string | undefined {
// Don't return empty
if (isBlank(completion)) {
return undefined;
}
// Don't return whitespace
if (isOnlyWhitespace(completion)) {
return undefined;
}
@ -112,11 +121,8 @@ export function postprocessCompletion({
// }
// If prefix ends with space and so does completion, then remove the space from completion
if (
prefix.split("\n").pop()?.trim() !== "" &&
prefix.endsWith(" ") &&
completion.startsWith(" ")
) {
if (prefix.endsWith(" ") && completion.startsWith(" ")) {
completion = completion.slice(1);
}

View file

@ -13,12 +13,14 @@ const getCommentMark = (helper: HelperVars) => {
};
const addCommentMarks = (text: string, helper: HelperVars) => {
const commentMark = getCommentMark(helper);
const lines = [
...text
.trim()
.split("\n")
.map((line) => `${getCommentMark(helper)} ${line}`),
.map((line) => `${commentMark} ${line}`),
];
return lines.join("\n");
};
@ -61,11 +63,6 @@ const commentifySnippet = (
};
};
const SNIPPET_TYPES_TO_COMMENT = [
AutocompleteSnippetType.Code,
AutocompleteSnippetType.Clipboard,
];
export const formatSnippets = (
helper: HelperVars,
snippets: AutocompleteSnippet[],
@ -88,19 +85,7 @@ export const formatSnippets = (
}
})
.map((item) => {
if (SNIPPET_TYPES_TO_COMMENT.includes(item.type)) {
return commentifySnippet(helper, item);
}
return item;
})
.map((item) => {
if (SNIPPET_TYPES_TO_COMMENT.includes(item.type)) {
const commentMark = getCommentMark(helper);
return item.content + `\n${commentMark}\n${commentMark}`;
}
return item.content;
return commentifySnippet(helper, item).content;
})
.join("\n") + `\n${currentFilepathComment}`
);

View file

@ -10,7 +10,7 @@ const STARCODER2_T_ARTIFACTS = ["t.", "\nt", "<file_sep>"];
const PYTHON_ENCODING = "#- coding: utf-8";
const CODE_BLOCK_END = "```";
const multilineStops: string[] = [DOUBLE_NEWLINE, WINDOWS_DOUBLE_NEWLINE];
// const multilineStops: string[] = [DOUBLE_NEWLINE, WINDOWS_DOUBLE_NEWLINE];
const commonStops = [SRC_DIRECTORY, PYTHON_ENCODING, CODE_BLOCK_END];
export function getStopTokens(
@ -25,7 +25,6 @@ export function getStopTokens(
...(model.toLowerCase().includes("starcoder2")
? STARCODER2_T_ARTIFACTS
: []),
...(lang.stopWords ?? []),
// ...lang.topLevelKeywords.map((word) => `\n${word}`),
];

View file

@ -17,7 +17,7 @@ Each model has specific configuration options tailored to its provider and funct
- `title` (**required**): The title to assign to your model, shown in dropdowns, etc.
- `provider` (**required**): The provider of the model, which determines the type and interaction method. Options inclued `openai`, `ollama`, etc., see intelliJ suggestions.
- `model` (**required**): The name of the model, used for prompt template auto-detection.
- `model` (**required**): The name of the model, used for prompt template auto-detection. Use `AUTODETECT` special name to get all available models.
- `apiKey`: API key required by providers like OpenAI, Anthropic, and Cohere.
- `apiBase`: The base URL of the LLM API.
- `contextLength`: Maximum context length of the model, typically in tokens (default: 2048).