🐛 streaming fixes

This commit is contained in:
Nate Sesti 2023-12-17 14:10:19 -05:00
parent 0e8352cdae
commit 258f6471c2
12 changed files with 4927 additions and 8848 deletions

View file

@ -471,6 +471,7 @@ const EditSlashCommand: SlashCommand = {
generator = llm.streamComplete(rendered as string, {
maxTokens: Math.min(maxTokens, Math.floor(llm.contextLength / 2), 4096),
raw: true,
});
} else {
async function* gen() {

View file

@ -92,7 +92,7 @@ export async function* ideStreamRequest(
staleTimeout = setTimeout(() => {
console.warn("Stream request timed out.");
done = true;
}, 5000);
}, 20_000);
}
};
window.addEventListener("message", handler);
@ -104,4 +104,6 @@ export async function* ideStreamRequest(
}
await new Promise((resolve) => setTimeout(resolve, 50));
}
clearTimeout(staleTimeout);
}

View file

@ -318,6 +318,18 @@ export abstract class BaseLLM implements ILLM {
prompt: string,
options: LLMFullCompletionOptions = {}
) {
if (!this._shouldRequestDirectly()) {
for await (const content of ideStreamRequest("llmStreamComplete", {
prompt,
provider: this.providerName,
llmOptions: this._llmOptions,
completionOptions: options,
})) {
yield content;
}
return;
}
const { completionOptions, log, raw } =
this._parseCompletionOptions(options);
@ -342,10 +354,7 @@ export abstract class BaseLLM implements ILLM {
}
let completion = "";
for await (const chunk of this._ideOrDirectStreamComplete(
prompt,
completionOptions
)) {
for await (const chunk of this._streamComplete(prompt, completionOptions)) {
completion += chunk;
yield chunk;
}
@ -354,6 +363,17 @@ export abstract class BaseLLM implements ILLM {
}
async complete(prompt: string, options: LLMFullCompletionOptions = {}) {
if (!this._shouldRequestDirectly()) {
return (
await ideRequest("llmComplete", {
prompt,
provider: this.providerName,
llmOptions: this._llmOptions,
completionOptions: options,
})
).content;
}
const { completionOptions, log, raw } =
this._parseCompletionOptions(options);
@ -377,10 +397,7 @@ export abstract class BaseLLM implements ILLM {
}
}
const completion = await this._ideOrDirectComplete(
prompt,
completionOptions
);
const completion = await this._complete(prompt, completionOptions);
this._logTokensGenerated(completionOptions.model, completion);
return completion;
@ -398,6 +415,17 @@ export abstract class BaseLLM implements ILLM {
messages: ChatMessage[],
options: LLMFullCompletionOptions = {}
): AsyncGenerator<ChatMessage> {
if (!this._shouldRequestDirectly()) {
for await (const content of ideStreamRequest("llmStreamChat", {
messages,
provider: this.providerName,
llmOptions: this._llmOptions,
completionOptions: options,
})) {
yield { role: "user", content };
}
}
const { completionOptions, log, raw } =
this._parseCompletionOptions(options);
@ -419,7 +447,7 @@ export abstract class BaseLLM implements ILLM {
try {
if (this.templateMessages) {
for await (const chunk of this._ideOrDirectStreamComplete(
for await (const chunk of this._streamComplete(
prompt,
completionOptions
)) {
@ -427,7 +455,7 @@ export abstract class BaseLLM implements ILLM {
yield { role: "assistant", content: chunk };
}
} else {
for await (const chunk of this._ideOrDirectStreamChat(
for await (const chunk of this._streamChat(
messages,
completionOptions
)) {
@ -494,60 +522,4 @@ export abstract class BaseLLM implements ILLM {
}
return (window as any)?.ide !== "vscode";
}
private async *_ideOrDirectStreamComplete(
prompt: string,
options: CompletionOptions
): AsyncGenerator<string> {
if (this._shouldRequestDirectly()) {
for await (const content of this._streamComplete(prompt, options)) {
yield content;
}
} else {
for await (const content of ideStreamRequest("llmStreamComplete", {
prompt,
provider: this.providerName,
llmOptions: this._llmOptions,
completionOptions: options,
})) {
yield content;
}
}
}
private async *_ideOrDirectStreamChat(
messages: ChatMessage[],
options: CompletionOptions
): AsyncGenerator<ChatMessage> {
if (this._shouldRequestDirectly()) {
for await (const content of this._streamChat(messages, options)) {
yield content;
}
} else {
for await (const content of ideStreamRequest("llmStreamChat", {
messages,
provider: this.providerName,
llmOptions: this._llmOptions,
completionOptions: options,
})) {
yield { role: "user", content };
}
}
}
private async _ideOrDirectComplete(
prompt: string,
options: CompletionOptions
): Promise<string> {
if (this._shouldRequestDirectly()) {
return await this._complete(prompt, options);
} else {
return (
await ideRequest("llmComplete", {
prompt,
provider: this.providerName,
llmOptions: this._llmOptions,
completionOptions: options,
})
).content;
}
}
}

View file

@ -1,118 +1,120 @@
// import * as dotenv from "dotenv";
// import { ContinueSDK } from "../../commands";
// import EditSlashCommand, {
// contextItemToRangeInFileWithContents,
// getPromptParts,
// } from "../../commands/slash/edit";
// import FileSystemIde from "../../ide/filesystem";
// import { dedentAndGetCommonWhitespace } from "../../util";
// import FreeTrial from "../llms/FreeTrial";
import * as dotenv from "dotenv";
import { ContinueSDK } from "../..";
import EditSlashCommand, {
contextItemToRangeInFileWithContents,
getPromptParts,
} from "../../commands/slash/edit";
import FileSystemIde from "../../ide/filesystem";
import { dedentAndGetCommonWhitespace } from "../../util";
import FreeTrial from "../llms/FreeTrial";
import Ollama from "../llms/Ollama";
// jest.setTimeout(100_000);
jest.setTimeout(100_000);
// dotenv.config();
dotenv.config();
// const TEST_CONTEXT_ITEM = {
// name: "editme.py (1-2)",
// description: "/Users/natesesti/Desktop/continue/core/llm/test/editme.py",
// content: "def average(nums: list) -> float:\n pass\n",
// id: {
// providerTitle: "code",
// itemId: "/Users/natesesti/Desktop/continue/core/llm/test/editme.py",
// },
// editing: true,
// };
const TEST_CONTEXT_ITEM = {
name: "editme.py (1-2)",
description: "/Users/natesesti/Desktop/continue/core/llm/test/editme.py",
content: "def average(nums: list) -> float:\n pass\n",
id: {
providerTitle: "code",
itemId: "/Users/natesesti/Desktop/continue/core/llm/test/editme.py",
},
editing: true,
};
// const f1 = `\
// def maximum(nums: list) -> float:
// return max(nums)
// `;
const f1 = `\
def maximum(nums: list) -> float:
return max(nums)
`;
// const f2 = `\
// def total(nums: list) -> float:
// s = sum(nums)
// return s
// `;
const f2 = `\
def total(nums: list) -> float:
s = sum(nums)
return s
`;
// const f3 = `\
// def average(nums: list) -> float:
// return sum(nums) / len(nums)
// `;
const f3 = `\
def average(nums: list) -> float:
return sum(nums) / len(nums)
`;
// const fullFile = `${f1}\n${f2}\n${f3}\n`;
const fullFile = `${f1}\n${f2}\n${f3}\n`;
// const TEST_CONTEXT_ITEM2 = {
// name: "editme2.py (4-7)",
// description: "/Users/natesesti/Desktop/continue/core/llm/test/editme2.py",
// content: f2,
// id: {
// providerTitle: "code",
// itemId: "/Users/natesesti/Desktop/continue/core/llm/test/editme2.py",
// },
// editing: true,
// };
const TEST_CONTEXT_ITEM2 = {
name: "editme2.py (4-7)",
description: "/Users/natesesti/Desktop/continue/core/llm/test/editme2.py",
content: f2,
id: {
providerTitle: "code",
itemId: "/Users/natesesti/Desktop/continue/core/llm/test/editme2.py",
},
editing: true,
};
// describe("/edit slash command", () => {
// test("doesn't break", async () => {
// const command = EditSlashCommand;
// const sdk: ContinueSDK = {
// ide: new FileSystemIde(),
// llm: new FreeTrial({ model: "gpt-3.5-turbo" }),
// addContextItem: (item: any) => {},
// history: [],
// input: "implement this function",
// contextItems: [TEST_CONTEXT_ITEM],
// options: {},
// };
describe("/edit slash command", () => {
test.only("doesn't break", async () => {
const command = EditSlashCommand;
const sdk: ContinueSDK = {
ide: new FileSystemIde(),
// llm: new FreeTrial({ model: "gpt-3.5-turbo" }),
llm: new Ollama({ model: "codellama-7b" }),
addContextItem: (item: any) => {},
history: [],
input: "implement this function",
contextItems: [TEST_CONTEXT_ITEM],
};
// let total = "";
// for await (const update of command.run(sdk)) {
// total += update;
// }
// console.log(total);
// });
let total = "";
for await (const update of command.run(sdk)) {
if (update === undefined) continue;
total += update;
}
console.log(total);
});
// test.skip("dedentAndGetCommonWhitespace", () => {
// // TODO
// let [dedented, whitespace] = dedentAndGetCommonWhitespace(
// `\
// ...
// ...
// ...
// ..
// . .`
// );
test.skip("dedentAndGetCommonWhitespace", () => {
// TODO
let [dedented, whitespace] = dedentAndGetCommonWhitespace(
`\
...
...
...
..
. .`
);
// expect(dedented).toEqual(`\
// ...
// ...
// ...
// ..
// . .`);
// expect(whitespace).toEqual(" ");
expect(dedented).toEqual(`\
...
...
...
..
. .`);
expect(whitespace).toEqual(" ");
// let [dedented2, whitespace2] = dedentAndGetCommonWhitespace("");
// expect(dedented2).toEqual("");
// expect(whitespace2).toEqual("");
let [dedented2, whitespace2] = dedentAndGetCommonWhitespace("");
expect(dedented2).toEqual("");
expect(whitespace2).toEqual("");
// let [dedented3, whitespace3] = dedentAndGetCommonWhitespace(" \n\n ");
// expect(dedented3).toEqual(" \n\n ");
// expect(whitespace3).toEqual("");
// });
let [dedented3, whitespace3] = dedentAndGetCommonWhitespace(" \n\n ");
expect(dedented3).toEqual(" \n\n ");
expect(whitespace3).toEqual("");
});
// test.skip("getPromptParts", async () => {
// // TODO
// const { filePrefix, fileSuffix, contents, maxTokens } =
// await getPromptParts(
// contextItemToRangeInFileWithContents(TEST_CONTEXT_ITEM2),
// fullFile,
// new FreeTrial({ model: "gpt-3.5-turbo" }),
// "implement this function"
// );
test.skip("getPromptParts", async () => {
// TODO
const { filePrefix, fileSuffix, contents, maxTokens } =
await getPromptParts(
contextItemToRangeInFileWithContents(TEST_CONTEXT_ITEM2),
fullFile,
new FreeTrial({ model: "gpt-3.5-turbo" }),
"implement this function"
);
// expect(filePrefix).toEqual(`${f1}`);
// expect(`${fileSuffix}\n`).toEqual(`\n${f3}`);
// expect(contents).toEqual(f2);
// expect(maxTokens).toEqual(2048);
// });
// });
expect(filePrefix).toEqual(`${f1}`);
expect(`${fileSuffix}\n`).toEqual(`\n${f3}`);
expect(contents).toEqual(f2);
expect(maxTokens).toEqual(2048);
});
});

View file

@ -1,110 +1,109 @@
// import * as dotenv from "dotenv";
import * as dotenv from "dotenv";
// import { BaseLLM } from "..";
// import { CompletionOptions } from "../..";
// import Mistral from "../llms/Mistral";
import { BaseLLM } from "..";
import { CompletionOptions } from "../..";
// jest.setTimeout(100_000);
jest.setTimeout(100_000);
// dotenv.config();
dotenv.config();
// const COMPLETION_OPTIONS: Partial<CompletionOptions> = {
// temperature: 0.5,
// topP: 1,
// topK: 40,
// presencePenalty: 0,
// frequencyPenalty: 0,
// // stop: ["\n"],
// // maxTokens: 5,
// };
const COMPLETION_OPTIONS: Partial<CompletionOptions> = {
temperature: 0.5,
topP: 1,
topK: 40,
presencePenalty: 0,
frequencyPenalty: 0,
// stop: ["\n"],
// maxTokens: 5,
};
// function testLLM(llm: BaseLLM) {
// beforeAll(() => {
// llm.completionOptions = { ...llm.completionOptions, ...COMPLETION_OPTIONS };
// });
function testLLM(llm: BaseLLM) {
beforeAll(() => {
llm.completionOptions = { ...llm.completionOptions, ...COMPLETION_OPTIONS };
});
// describe(llm.providerName, () => {
// test("Stream Chat works", async () => {
// let total = "";
// for await (const chunk of llm.streamChat([
// { role: "user", content: "Tell a story" },
// ])) {
// total += chunk.content;
// }
describe(llm.providerName, () => {
test("Stream Chat works", async () => {
let total = "";
for await (const chunk of llm.streamChat([
{ role: "user", content: "Tell a story" },
])) {
total += chunk.content;
}
// expect(total.length).toBeGreaterThan(0);
// console.log(total);
// return;
// });
expect(total.length).toBeGreaterThan(0);
console.log(total);
return;
});
// // test("Stream Complete works", async () => {
// // let total = "";
// // for await (const chunk of llm.streamComplete("Hello")) {
// // total += chunk;
// // }
// test("Stream Complete works", async () => {
// let total = "";
// for await (const chunk of llm.streamComplete("Hello")) {
// total += chunk;
// }
// // expect(total.length).toBeGreaterThan(0);
// // console.log(total);
// // return;
// // });
// expect(total.length).toBeGreaterThan(0);
// console.log(total);
// return;
// });
// // test("Complete works", async () => {
// // const completion = await llm.complete("Hello");
// test("Complete works", async () => {
// const completion = await llm.complete("Hello");
// // expect(completion.length).toBeGreaterThan(0);
// // console.log(completion);
// // return;
// // });
// });
// }
// expect(completion.length).toBeGreaterThan(0);
// console.log(completion);
// return;
// });
});
}
// describe("LLM", () => {
// // // testLLM(
// // // new FreeTrial({
// // // model: "gpt-3.5-turbo",
// // // })
// // // );
// // // testLLM(
// // // new Anthropic({
// // // model: "claude-2",
// // // apiKey: process.env.ANTHROPIC_API_KEY,
// // // })
// // // );
// // // testLLM(
// // // new OpenAI({ apiKey: process.env.OPENAI_API_KEY, model: "gpt-3.5-turbo" })
// // // );
// // // TODO: Fix Replicate
// // // testLLM(
// // // new Replicate({
// // // apiKey: process.env.REPLICATE_API_KEY,
// // // model: "codellama-7b",
// // // })
// // // );
// // // testLLM(new LMStudio({ model: "codellama-7b" }));
// // // testLLM(new Ollama({ model: "codellama-7b" }));
// // testLLM(
// // new Together({
// // apiKey: process.env.TOGETHER_API_KEY,
// // model: "codellama-7b",
// // })
// // );
// // // testLLM(new LlamaCpp({ model: "deepseek-7b" }));
// // // testLLM(new Llamafile({ model: "mistral-7b" }));
// // // TODO: Test these
// // // testLLM(new TextGenWebUI({ model: "codellama-7b" }));
// // // testLLM(new HuggingFaceTGI({ model: "codellama-7b" }));
// // // testLLM(new HuggingFaceInferenceAPI({ model: "codellama-7b" }));
// // testLLM(
// // new GooglePalm({
// // model: "gemini-pro",
// // // model: "chat-bison-001",
// // apiKey: process.env.GOOGLE_PALM_API_KEY,
// // })
// // );
// // testLLM(
// // new Gemini({ model: "gemini-pro", apiKey: process.env.GOOGLE_PALM_API_KEY })
// // );
// testLLM(
// new Mistral({ apiKey: process.env.MISTRAL_API_KEY, model: "mistral-small" })
// );
// });
describe("LLM", () => {
// // testLLM(
// // new FreeTrial({
// // model: "gpt-3.5-turbo",
// // })
// // );
// // testLLM(
// // new Anthropic({
// // model: "claude-2",
// // apiKey: process.env.ANTHROPIC_API_KEY,
// // })
// // );
// // testLLM(
// // new OpenAI({ apiKey: process.env.OPENAI_API_KEY, model: "gpt-3.5-turbo" })
// // );
// // TODO: Fix Replicate
// // testLLM(
// // new Replicate({
// // apiKey: process.env.REPLICATE_API_KEY,
// // model: "codellama-7b",
// // })
// // );
// // testLLM(new LMStudio({ model: "codellama-7b" }));
// // testLLM(new Ollama({ model: "codellama-7b" }));
// testLLM(
// new Together({
// apiKey: process.env.TOGETHER_API_KEY,
// model: "codellama-7b",
// })
// );
// // testLLM(new LlamaCpp({ model: "deepseek-7b" }));
// // testLLM(new Llamafile({ model: "mistral-7b" }));
// // TODO: Test these
// // testLLM(new TextGenWebUI({ model: "codellama-7b" }));
// // testLLM(new HuggingFaceTGI({ model: "codellama-7b" }));
// // testLLM(new HuggingFaceInferenceAPI({ model: "codellama-7b" }));
// testLLM(
// new GooglePalm({
// model: "gemini-pro",
// // model: "chat-bison-001",
// apiKey: process.env.GOOGLE_PALM_API_KEY,
// })
// );
// testLLM(
// new Gemini({ model: "gemini-pro", apiKey: process.env.GOOGLE_PALM_API_KEY })
// );
// testLLM(
// new Mistral({ apiKey: process.env.MISTRAL_API_KEY, model: "mistral-small" })
// );
});

File diff suppressed because it is too large Load diff

View file

@ -325,7 +325,6 @@
"@types/cors": "^2.8.17",
"@types/express": "^4.17.21",
"@types/glob": "^8.0.0",
"@types/mocha": "^10.0.1",
"@types/node": "16.x",
"@types/node-fetch": "^2.6.2",
"@types/react-dom": "^18.2.4",
@ -340,7 +339,6 @@
"eslint": "^8.28.0",
"glob": "^8.0.3",
"json-schema-to-typescript": "^12.0.0",
"mocha": "^10.1.0",
"ovsx": "^0.8.3",
"typescript": "^4.9.3",
"vite": "^4.3.9",
@ -349,6 +347,7 @@
"dependencies": {
"@electron/rebuild": "^3.2.10",
"@reduxjs/toolkit": "^1.9.3",
"@types/jest": "^29.5.11",
"axios": "^1.2.5",
"core": "file:../../core",
"cors": "^2.8.5",
@ -359,6 +358,7 @@
"highlightable": "^1.3.0-beta.0",
"http-proxy": "^1.18.1",
"http-proxy-middleware": "^2.0.6",
"jest": "^29.7.0",
"ncp": "^2.0.0",
"node-machine-id": "^1.1.12",
"posthog-node": "^3.1.2",
@ -368,7 +368,6 @@
"socket.io-client": "^4.7.2",
"strip-ansi": "^7.1.0",
"tailwindcss": "^3.3.2",
"ts-node": "^10.9.1",
"uuidv4": "^6.2.13",
"vscode-languageclient": "^8.0.2",
"ws": "^8.13.0"

View file

@ -1,39 +0,0 @@
import * as path from "path";
import Mocha from "mocha";
import * as glob from "glob";
export function run() {
// Avoid timing out when stopping on breakpoints during debugging in VSCode
const timeoutOption = process.env.MOCHA_TIMEOUT ? parseInt(process.env.MOCHA_TIMEOUT) : undefined;
// Create the mocha test
const mocha = new Mocha({
ui: "tdd",
color: true,
timeout: timeoutOption,
});
// See esbuild.test.mjs for more details
// Assumes this file is in out/test-runner/mochaRunner.js
const compiledTestSuitesDirectory = path.resolve(__dirname, "../test-suites");
glob.sync("**/**.test.js", { cwd: compiledTestSuitesDirectory }).forEach((file) => {
mocha.addFile(path.resolve(compiledTestSuitesDirectory, file));
});
return new Promise<void>((c, e) => {
try {
// Run the mocha test
mocha.run((failures) => {
if (failures > 0) {
e(new Error(`${failures} tests failed.`));
} else {
c();
}
});
} catch (err) {
console.error(err);
e(err);
}
});
}

View file

@ -1,16 +0,0 @@
import { test, describe } from "mocha";
import * as assert from "assert";
// You can import and use all API from the 'vscode' module
// as well as import your extension to test it
import * as vscode from "vscode";
// import * as myExtension from '../../extension';
describe("Extension Test Suite", () => {
vscode.window.showInformationMessage("Start all tests.");
test("Sample test", () => {
assert.strictEqual(-1, [1, 2, 3].indexOf(5));
assert.strictEqual(-1, [1, 2, 3].indexOf(0));
});
});

View file

@ -1,18 +0,0 @@
import { test, describe } from "mocha";
import assert from "assert";
import { convertSingleToDoubleQuoteJSON } from "../util/util";
describe("utils.ts", () => {
test("convertSingleToDoubleQuoteJson", () => {
let pairs = [
[`{'a': 'b'}`, `{"a": "b"}`],
[`{'a': "b", "c": 'd'}`, `{"a": "b", "c": "d"}`],
[`{'a': '\\'"'}`, `{"a": "'\\""}`],
];
for (let pair of pairs) {
let result = convertSingleToDoubleQuoteJSON(pair[0]);
assert(result === pair[1]);
JSON.parse(result);
}
});
});

File diff suppressed because it is too large Load diff

View file

@ -42,8 +42,7 @@ function useHistory(dispatch: Dispatch) {
const sessionInfo: PersistedSessionInfo = {
history: stateCopy.history,
title,
// truncateText(stateCopy.history[0].message.content, 50)
title: title || truncateText(stateCopy.history[0].message.content, 50),
sessionId: stateCopy.sessionId,
workspaceDirectory: (window as any).workspacePaths?.[0] || "",
};