Improve Filtering

This commit is contained in:
Ruedi Steinmann 2024-11-25 20:32:15 +01:00
parent c359b296fa
commit bd2bf657a0
5 changed files with 176 additions and 69 deletions

View file

@ -2,7 +2,7 @@ import { streamLines } from "../../../diff/util";
import { DEFAULT_AUTOCOMPLETE_OPTS } from "../../../util/parameters";
import { HelperVars } from "../../util/HelperVars";
import { stopAtStopTokens } from "./charStream";
import { stopAtStartOf, stopAtStopTokens } from "./charStream";
import {
avoidEmptyComments,
avoidPathLine,
@ -27,6 +27,7 @@ export class StreamTransformPipeline {
let charGenerator = generator;
charGenerator = stopAtStopTokens(generator, stopTokens);
charGenerator = stopAtStartOf(charGenerator, suffix);
for (const charFilter of helper.lang.charFilters ?? []) {
charGenerator = charFilter({
chars: charGenerator,

View file

@ -1,12 +1,20 @@
import { stopAtStopTokens } from "./charStream";
import { stopAtStartOf, stopAtStopTokens } from "./charStream";
async function* createMockStream(chunks: string[]): AsyncGenerator<string> {
for (const chunk of chunks) {
yield chunk;
}
}
async function streamToString(stream: AsyncGenerator<string>): Promise<string> {
let result = "";
for await (const chunk of stream) {
result += chunk;
}
return result;
}
describe("stopAtStopTokens", () => {
async function* createMockStream(chunks: string[]): AsyncGenerator<string> {
for (const chunk of chunks) {
yield chunk;
}
}
it("should yield characters until a stop token is encountered", async () => {
const mockStream = createMockStream(["Hello", " world", "! Stop", "here"]);
const stopTokens = ["Stop"];
@ -30,12 +38,7 @@ describe("stopAtStopTokens", () => {
const stopTokens = ["END", "STOP", "HALT"];
const result = stopAtStopTokens(mockStream, stopTokens);
const output = [];
for await (const char of result) {
output.push(char);
}
expect(output.join("")).toBe("This is a test. ");
expect(await streamToString(result)).toBe("This is a test. ");
});
it("should handle stop tokens split across chunks", async () => {
@ -67,12 +70,7 @@ describe("stopAtStopTokens", () => {
const stopTokens = ["END"];
const result = stopAtStopTokens(mockStream, stopTokens);
const output = [];
for await (const char of result) {
output.push(char);
}
expect(output.join("")).toBe("This is a complete stream");
expect(await streamToString(result)).toBe("This is a complete stream");
});
it("should handle empty chunks", async () => {
@ -80,12 +78,7 @@ describe("stopAtStopTokens", () => {
const stopTokens = ["STOP"];
const result = stopAtStopTokens(mockStream, stopTokens);
const output = [];
for await (const char of result) {
output.push(char);
}
expect(output.join("")).toBe("Hello world! ");
expect(await streamToString(result)).toBe("Hello world! ");
});
it("should handle stop token at the beginning of the stream", async () => {
@ -106,12 +99,7 @@ describe("stopAtStopTokens", () => {
const stopTokens = ["STOP"];
const result = stopAtStopTokens(mockStream, stopTokens);
const output = [];
for await (const char of result) {
output.push(char);
}
expect(output.join("")).toBe("Hello world");
expect(await streamToString(result)).toBe("Hello world");
});
it("should handle multiple stop tokens of different lengths", async () => {
@ -124,12 +112,7 @@ describe("stopAtStopTokens", () => {
const stopTokens = ["STOP", "END", "HALT"];
const result = stopAtStopTokens(mockStream, stopTokens);
const output = [];
for await (const char of result) {
output.push(char);
}
expect(output.join("")).toBe("This is a test with multiple ");
expect(await streamToString(result)).toBe("This is a test with multiple ");
});
it("should handle an empty stream", async () => {
@ -137,12 +120,7 @@ describe("stopAtStopTokens", () => {
const stopTokens = ["STOP"];
const result = stopAtStopTokens(mockStream, stopTokens);
const output = [];
for await (const char of result) {
output.push(char);
}
expect(output.join("")).toBe("");
expect(await streamToString(result)).toBe("");
});
it("should handle an empty stop tokens array", async () => {
@ -166,11 +144,73 @@ describe("stopAtStopTokens", () => {
];
const result = stopAtStopTokens(mockStream, stopTokens);
const output = [];
for await (const char of result) {
output.push(char);
}
expect(output.join("")).toBe("Hello world!");
expect(await streamToString(result)).toBe("Hello world!");
});
});
describe("stopAtStartOf", () => {
const sampleCode = ` {
method: "GET",
headers: {
"Content-Type": "application/json",
Authorization: \`Bearer \${this.workOsAccessToken}\`,
},
},
);
const data = await response.json();
return data.items;
}
async getContextItems(
query: string,
extras: ContextProviderExtras,
): Promise<ContextItem[]> {
const response = await extras.fetch(
new URL(
\`/proxy/context/\${this.options.id}/retrieve\`,
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;
// 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}`,
);
}
}
});
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;
// 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}`,
);
}
}
});
});

View file

@ -117,3 +117,57 @@ export async function* stopAtStopTokens(
yield char;
}
}
/**
* Asynchronously yields characters from the input stream, stopping if a sequence contained in the beginning of the suffix is encountered.
* */
export async function* stopAtStartOf(
stream: AsyncGenerator<string>,
suffix: string,
sequenceLength: number = 20,
): AsyncGenerator<string> {
if (suffix.length < sequenceLength) {
for await (const chunk of stream) {
yield chunk;
}
return;
}
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;
}
}
// Move the current row's data to the previous row
prev = curr;
if (res > sequenceLength) {
return;
}
buffer += s1[i - 1];
while (buffer.length > sequenceLength) {
yield buffer[0];
buffer = buffer.slice(1);
}
}
}
yield buffer;
}

View file

@ -157,23 +157,35 @@ public class Calculator {
POSTGRES_DB: mydb
`,
},
// TODO
// {
// description: "Should autocomplete a Markdown list with nested items",
// filename: "test.md",
// input: `
// - Item 1
// - Item 2
// - Subitem 1
// <|fim|>
// - Item 3
// `,
// llmOutput: ` - Subitem 2
// - Subitem 3
// `,
// expectedCompletion: ` - Subitem 2
// - Subitem 3`,
// },
{
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: null,
},
{
description: "Should enforce bracket matching in JSON files",
filename: "test.json",
@ -559,7 +571,7 @@ export const Timer = () => {
);
};`,
llmOutput: "return () => clearInterval(interval);",
expectedCompletion: "return () => clearInterval(interval);",
expectedCompletion: null,
filename: "Timer.tsx",
},

View file

@ -72,5 +72,5 @@ export async function testAutocompleteFiltering(
);
// Ensure that we return the text that is wanted to be displayed
expect(result?.completion).toEqual(test.expectedCompletion);
expect(result?.completion ?? null).toEqual(test.expectedCompletion);
}