⚡️ Rewrite LLM class without bugs

This commit is contained in:
Nate Sesti 2023-12-06 08:06:31 -08:00
parent 9157ad0d05
commit 552b4e3586
7 changed files with 863 additions and 0 deletions

47
core/README.md Normal file
View file

@ -0,0 +1,47 @@
# Continue Core
The Continue Core contains functionality that can be shared across web, VS Code, or Node.js server. It is written in TypeScript and contains much of the functionality that was previously inside of the legacy Continue Python Server.
- LLM class
- Token counting and pruning
- Prompt templates
- Prompts
- Loading config file
Since it's written in Typescript, it can be placed directly in the React app without needing to communicate with a server.
Reasons to avoid Python
- Circular imports
- No real type checking
- Fake async
- snake_case
- Doesn't run in browser
---
TODO:
Imports
- tiktoken
- posthog
- chevron
Repetitive
- LLM subclasses
- Slash commands
- Context providers
The important thing is to build backward. Your goal should be to add functionality, not to rebuild what you previously had.
1. Get text streaming from an LLM. One LLM class. FreeTrial.
- After: complete rest of LLM classes
2. /test slash command is a good one to start with
- Then the others. but don't need all of them. keep it simple
3. Diff context provider
- Subgoal: set up IDEProtocol to work over message passing
4. File context provider
- Need to figure out how to do search
5. History and other storage of state. Do it through the IDE protocol probably? Still want local files.

26
core/llm/constants.ts Normal file
View file

@ -0,0 +1,26 @@
const DEFAULT_MAX_TOKENS = 1000;
const DEFAULT_ARGS = {
max_tokens: DEFAULT_MAX_TOKENS,
temperature: 0.5,
};
const CONTEXT_LENGTH_FOR_MODEL = {
"gpt-3.5-turbo": 4096,
"gpt-3.5-turbo-0613": 4096,
"gpt-3.5-turbo-16k": 16_384,
"gpt-4": 8192,
"gpt-35-turbo-16k": 16_384,
"gpt-35-turbo-0613": 4096,
"gpt-35-turbo": 4096,
"gpt-4-32k": 32_768,
"gpt-4-1106-preview": 128_000,
};
const TOKEN_BUFFER_FOR_SAFETY = 350;
export {
DEFAULT_MAX_TOKENS,
DEFAULT_ARGS,
CONTEXT_LENGTH_FOR_MODEL,
TOKEN_BUFFER_FOR_SAFETY,
};

237
core/llm/countTokens.ts Normal file
View file

@ -0,0 +1,237 @@
import { TOKEN_BUFFER_FOR_SAFETY } from "./constants";
import { ChatMessage } from "./types";
// TODO: tiktoken and chevron and posthog
function renderTemplatedString(template: string): string {
// TODO
return template;
}
function countTokens(content: string, modelName: string): number {
// TODO
return 0;
}
function flattenMessages(msgs: ChatMessage[]): ChatMessage[] {
const flattened: ChatMessage[] = [];
for (let i = 0; i < msgs.length; i++) {
const msg = msgs[i];
if (
flattened.length > 0 &&
flattened[flattened.length - 1].role === msg.role
) {
flattened[flattened.length - 1].content += "\n\n" + (msg.content || "");
} else {
flattened.push(msg);
}
}
return flattened;
}
function countChatMessageTokens(
modelName: string,
chatMessage: ChatMessage
): number {
// Doing simpler, safer version of what is here:
// https://github.com/openai/openai-cookbook/blob/main/examples/How_to_count_tokens_with_tiktoken.ipynb
// every message follows <|im_start|>{role/name}\n{content}<|end|>\n
const TOKENS_PER_MESSAGE: number = 4;
return countTokens(chatMessage.content, modelName) + TOKENS_PER_MESSAGE;
}
function pruneStringFromTop(
modelName: string,
maxTokens: number,
prompt: string
): string {
// TODO: Tiktoken
// const encoding = encodingForModel(modelName);
// if (encoding === null) {
const desiredLengthInChars = maxTokens * 2;
return prompt.slice(-desiredLengthInChars);
// }
// const tokens = encoding.encode(prompt, { disallowedSpecial: [] });
// if (tokens.length <= maxTokens) {
// return prompt;
// }
// return encoding.decode(tokens.slice(-maxTokens));
}
function pruneRawPromptFromTop(
modelName: string,
contextLength: number,
prompt: string,
tokensForCompletion: number
): string {
const maxTokens =
contextLength - tokensForCompletion - TOKEN_BUFFER_FOR_SAFETY;
return pruneStringFromTop(modelName, maxTokens, prompt);
}
function pruneChatHistory(
modelName: string,
chatHistory: ChatMessage[],
contextLength: number,
tokensForCompletion: number
): ChatMessage[] {
let totalTokens =
tokensForCompletion +
chatHistory.reduce((acc, message) => {
return acc + countChatMessageTokens(modelName, message);
}, 0);
// 0. Prune any messages that take up more than 1/3 of the context length
const longestMessages = chatHistory.sort(
(a, b) => b.content.length - a.content.length
);
const longerThanOneThird = longestMessages.filter(
(message) => countTokens(message.content, modelName) > contextLength / 3
);
const distanceFromThird = longerThanOneThird.map(
(message) => countTokens(message.content, modelName) - contextLength / 3
);
for (let i = 0; i < longerThanOneThird.length; i++) {
// Prune line-by-line
const message = longerThanOneThird[i];
let lines = message.content.split("\n");
let tokensRemoved = 0;
while (
tokensRemoved < distanceFromThird[i] &&
totalTokens > contextLength &&
lines.length > 0
) {
const delta = countTokens("\n" + lines.pop()!, modelName);
tokensRemoved += delta;
totalTokens -= delta;
}
message.content = lines.join("\n");
}
// 1. Replace beyond last 5 messages with summary
let i = 0;
while (totalTokens > contextLength && i < chatHistory.length - 5) {
const message = chatHistory[0];
totalTokens -= countTokens(message.content, modelName);
totalTokens += countTokens(message.summary, modelName);
message.content = message.summary;
i++;
}
// 2. Remove entire messages until the last 5
while (
chatHistory.length > 5 &&
totalTokens > contextLength &&
chatHistory.length > 0
) {
const message = chatHistory.shift()!;
totalTokens -= countTokens(message.content, modelName);
}
// 3. Truncate message in the last 5, except last 1
i = 0;
while (
totalTokens > contextLength &&
chatHistory.length > 0 &&
i < chatHistory.length - 1
) {
const message = chatHistory[i];
totalTokens -= countTokens(message.content, modelName);
totalTokens += countTokens(message.summary, modelName);
message.content = message.summary;
i++;
}
// 4. Remove entire messages in the last 5, except last 1
while (totalTokens > contextLength && chatHistory.length > 1) {
const message = chatHistory.shift()!;
totalTokens -= countTokens(message.content, modelName);
}
// 5. Truncate last message
if (totalTokens > contextLength && chatHistory.length > 0) {
const message = chatHistory[0];
message.content = pruneRawPromptFromTop(
modelName,
contextLength,
message.content,
tokensForCompletion
);
totalTokens = contextLength;
}
return chatHistory;
}
function compileChatMessages(
modelName: string,
msgs: ChatMessage[] | undefined = undefined,
contextLength: number,
maxTokens: number,
prompt: string | undefined = undefined,
functions: any[] | undefined = undefined,
systemMessage: string | undefined = undefined
): ChatMessage[] {
const msgsCopy = msgs ? msgs.map((msg) => ({ ...msg })) : [];
if (prompt) {
const promptMsg: ChatMessage = {
role: "user",
content: prompt,
summary: prompt,
};
msgsCopy.push(promptMsg);
}
if (systemMessage && systemMessage.trim() !== "") {
const renderedSystemMessage = renderTemplatedString(systemMessage);
const systemChatMsg: ChatMessage = {
role: "system",
content: renderedSystemMessage,
summary: renderedSystemMessage,
};
// Insert as second to last
// Later moved to top, but want second-priority to last user message
msgsCopy.splice(-1, 0, systemChatMsg);
}
let functionTokens = 0;
if (functions) {
for (const func of functions) {
functionTokens += countTokens(JSON.stringify(func), modelName);
}
}
if (maxTokens + functionTokens + TOKEN_BUFFER_FOR_SAFETY >= contextLength) {
throw new Error(
`max_tokens (${maxTokens}) is too close to context_length (${contextLength}), which doesn't leave room for chat. This would cause incoherent responses. Try increasing the context_length parameter of the model in your config file.`
);
}
const history = pruneChatHistory(
modelName,
msgsCopy,
contextLength,
functionTokens + maxTokens + TOKEN_BUFFER_FOR_SAFETY
);
if (
systemMessage &&
history.length >= 2 &&
history[history.length - 2].role === "system"
) {
const movedSystemMessage = history.splice(-2, 1)[0];
history.unshift(movedSystemMessage);
}
const flattenedHistory = flattenMessages(history);
return flattenedHistory;
}
export { compileChatMessages, pruneRawPromptFromTop, countTokens };

299
core/llm/index.ts Normal file
View file

@ -0,0 +1,299 @@
import { CONTEXT_LENGTH_FOR_MODEL } from "./constants";
import {
compileChatMessages,
countTokens,
pruneRawPromptFromTop,
} from "./countTokens";
import { CompletionOptions, RequestOptions, ChatMessage } from "./types";
interface ILLM {
title?: string;
uniqueId?: string;
model: string;
systemMessage?: string;
contextLength: number;
completionOptions: CompletionOptions;
requestOptions: RequestOptions;
promptTemplates?: Record<string, string>;
templateMessages?: (messages: ChatMessage[]) => string;
writeLog?: (str: string) => Promise<void>;
llmRequestHook?: (model: string, prompt: string) => any;
apiKey?: string;
apiBase?: string;
}
interface LLMFullCompletionOptions {
raw?: boolean;
log?: boolean;
model?: string;
temperature?: number;
topP?: number;
topK?: number;
presencePenalty?: number;
frequencyPenalty?: number;
stop?: string[];
maxTokens?: number;
}
abstract class AbstractLLM implements ILLM {
title?: string;
uniqueId?: string;
model: string;
systemMessage?: string;
contextLength: number;
completionOptions: CompletionOptions;
requestOptions: RequestOptions;
promptTemplates?: Record<string, string>;
templateMessages?: (messages: ChatMessage[]) => string;
writeLog?: (str: string) => Promise<void>;
llmRequestHook?: (model: string, prompt: string) => any;
apiKey?: string;
apiBase?: string;
constructor(options: ILLM) {
this.title = options.title;
this.uniqueId = options.uniqueId;
this.model = options.model;
this.systemMessage = options.systemMessage;
this.contextLength = options.contextLength;
this.completionOptions = options.completionOptions;
this.requestOptions = options.requestOptions;
this.promptTemplates = options.promptTemplates;
this.templateMessages = options.templateMessages;
this.writeLog = options.writeLog;
this.llmRequestHook = options.llmRequestHook;
this.apiKey = options.apiKey;
this.apiBase = options.apiBase;
}
private _compileChatMessages(
options: CompletionOptions,
messages: ChatMessage[],
functions?: any[]
) {
let contextLength = this.contextLength;
if (
options.model !== this.model &&
options.model in CONTEXT_LENGTH_FOR_MODEL
) {
contextLength = CONTEXT_LENGTH_FOR_MODEL[options.model];
}
return compileChatMessages(
options.model,
messages,
contextLength,
options.maxTokens,
undefined,
functions,
this.systemMessage
);
}
private _getSystemMessage(): string | undefined {
// TODO: Merge with config system message
return this.systemMessage;
}
private _templatePromptLikeMessages(prompt: string): string {
if (!this.templateMessages) {
return prompt;
}
const msgs: ChatMessage[] = [
{ role: "user", content: prompt, summary: prompt },
];
const systemMessage = this._getSystemMessage();
if (systemMessage) {
msgs.unshift({ role: "system", content: systemMessage, summary: "" });
}
return this.templateMessages(msgs);
}
private _compileLogMessage(
prompt: string,
completionOptions: CompletionOptions
): string {
const dict = { contextLength: this.contextLength, ...completionOptions };
const settings = Object.entries(dict)
.map(([key, value]) => `${key}: ${value}`)
.join("\n");
return `Settings:
${settings}
############################################
${prompt}`;
}
private _logTokensGenerated(model: string, completion: string) {
// TODO: PostHog
}
private _parseCompletionOptions(options: LLMFullCompletionOptions) {
const log = options.log ?? true;
const raw = options.raw ?? false;
delete options.log;
delete options.raw;
const completionOptions: CompletionOptions = {
...this.completionOptions,
...options,
};
return { completionOptions, log, raw };
}
private _formatChatMessages(messages: ChatMessage[]): string {
let formatted = "";
for (let msg of messages) {
formatted += `<${msg.role}>\n${msg.content || ""}\n\n`;
}
return formatted;
}
async *streamComplete(
prompt: string,
options: LLMFullCompletionOptions = {}
) {
const { completionOptions, log, raw } =
this._parseCompletionOptions(options);
prompt = pruneRawPromptFromTop(
completionOptions.model,
this.contextLength,
prompt,
completionOptions.maxTokens
);
if (!raw) {
prompt = this._templatePromptLikeMessages(prompt);
}
if (log) {
if (this.writeLog) {
await this.writeLog(this._compileLogMessage(prompt, completionOptions));
}
if (this.llmRequestHook) {
this.llmRequestHook(completionOptions.model, prompt);
}
}
let completion = "";
for await (const chunk of this._streamComplete(prompt, completionOptions)) {
completion += chunk;
yield chunk;
}
this._logTokensGenerated(completionOptions.model, completion);
}
async complete(prompt: string, options: LLMFullCompletionOptions = {}) {
const { completionOptions, log, raw } =
this._parseCompletionOptions(options);
prompt = pruneRawPromptFromTop(
completionOptions.model,
this.contextLength,
prompt,
completionOptions.maxTokens
);
if (!raw) {
prompt = this._templatePromptLikeMessages(prompt);
}
if (log) {
if (this.writeLog) {
await this.writeLog(this._compileLogMessage(prompt, completionOptions));
}
if (this.llmRequestHook) {
this.llmRequestHook(completionOptions.model, prompt);
}
}
const completion = await this._complete(prompt, completionOptions);
this._logTokensGenerated(completionOptions.model, completion);
return completion;
}
async *streamChat(
messages: ChatMessage[],
options: LLMFullCompletionOptions = {}
): AsyncGenerator<ChatMessage> {
const { completionOptions, log, raw } =
this._parseCompletionOptions(options);
messages = this._compileChatMessages(completionOptions, messages);
const prompt = this.templateMessages
? this.templateMessages(messages)
: this._formatChatMessages(messages);
if (log) {
if (this.writeLog) {
await this.writeLog(this._compileLogMessage(prompt, completionOptions));
}
if (this.llmRequestHook) {
this.llmRequestHook(completionOptions.model, prompt);
}
}
let completion = "";
if (this.templateMessages) {
for await (const chunk of this._streamComplete(
prompt,
completionOptions
)) {
completion += chunk;
yield chunk;
}
} else {
for await (const chunk of this._streamChat(messages, completionOptions)) {
completion += chunk.content;
yield chunk;
}
}
this._logTokensGenerated(completionOptions.model, completion);
}
private async *_streamComplete(prompt: string, options: CompletionOptions) {
throw new Error("Not implemented");
}
private async *_streamChat(
messages: ChatMessage[],
options: CompletionOptions
): AsyncGenerator<ChatMessage> {
if (!this.templateMessages) {
throw new Error(
"You must either implement template_messages or _stream_chat"
);
}
for await (const chunk of this._streamComplete(
this.templateMessages(messages),
options
)) {
yield { role: "assistant", content: chunk, summary: chunk };
}
}
private async _complete(prompt: string, options: CompletionOptions) {
let completion = "";
for await (const chunk of this._streamComplete(prompt, options)) {
completion += chunk;
}
return completion;
}
countTokens(text: string): number {
return countTokens(text, this.model);
}
}

124
core/llm/templates/chat.ts Normal file
View file

@ -0,0 +1,124 @@
import { ChatMessage } from "../types";
function anthropicTemplateMessages(messages: ChatMessage[]): string {
const HUMAN_PROMPT = "\n\nHuman:";
const AI_PROMPT = "\n\nAssistant:";
let prompt = "";
// Anthropic prompt must start with a Human turn
if (
messages.length > 0 &&
messages[0].role !== "user" &&
messages[0].role !== "system"
) {
prompt += `${HUMAN_PROMPT} Hello.`;
}
for (const msg of messages) {
prompt += `${
msg.role === "user" || msg.role === "system" ? HUMAN_PROMPT : AI_PROMPT
} ${msg.content} `;
}
prompt += AI_PROMPT;
return prompt;
}
function zephyrTemplateMessages(msgs: ChatMessage[]): string {
let prompt = "";
if (msgs[0].role === "system") {
prompt += `<|system|>${msgs[0].content}</s>\n`;
msgs.shift();
} else {
prompt += "<|system|> </s>\n";
}
for (const msg of msgs) {
prompt += msg.role === "user" ? "<|user|>\n" : "<|assistant|>\n";
prompt += `${msg.content}</s>\n`;
}
prompt += "<|assistant|>\n";
return prompt;
}
function chatmlTemplateMessages(messages: ChatMessage[]): string {
let prompt = "";
for (const msg of messages) {
prompt += `<|im_start|>${msg.role}\n${msg.content}<|im_end|>\n`;
}
prompt += "<|im_start|>assistant\n";
return prompt;
}
function templateAlpacaMessages(msgs: ChatMessage[]): string {
let prompt = "";
if (msgs[0].role === "system") {
prompt += `${msgs[0].content}\n\n`;
msgs.shift();
}
for (const msg of msgs) {
prompt += msg.role === "user" ? "### Instruction:\n" : "### Response:\n";
prompt += `${msg.content}\n\n`;
}
prompt += "### Response:\n";
return prompt;
}
function deepseekTemplateMessages(msgs: ChatMessage[]): string {
let prompt = "";
let system: string | null = null;
prompt +=
"You are an AI programming assistant, utilizing the DeepSeek Coder model, developed by DeepSeek Company, and you only answer questions related to computer science. For politically sensitive questions, security and privacy issues, and other non-computer science questions, you will refuse to answer.\n";
if (msgs[0].role === "system") {
system = msgs.shift()!.content;
}
for (let i = 0; i < msgs.length; i++) {
const msg = msgs[i];
prompt += msg.role === "user" ? "### Instruction:\n" : "### Response:\n";
if (system && msg.role === "user" && i === msgs.length - 1) {
prompt += system + "\n";
}
prompt += `${msg.content}`;
prompt += msg.role === "user" ? "\n" : "<|EOT|>\n";
}
return prompt + "### Response:\n";
}
function phindTemplateMessages(msgs: ChatMessage[]): string {
let prompt = "";
if (msgs[0].role === "system") {
prompt += `### System Prompt\n${msgs[0].content}\n\n`;
msgs.shift();
}
for (const msg of msgs) {
prompt += msg.role === "user" ? "### User Message\n" : "### Assistant\n";
prompt += `${msg.content}\n`;
}
prompt += "### Assistant\n";
return prompt;
}
export {
anthropicTemplateMessages,
zephyrTemplateMessages,
chatmlTemplateMessages,
templateAlpacaMessages,
deepseekTemplateMessages,
phindTemplateMessages,
};

100
core/llm/templates/edit.ts Normal file
View file

@ -0,0 +1,100 @@
const simplifiedEditPrompt = `Consider the following code:
\`\`\`
{{{codeToEdit}}}
\`\`\`
Edit the code to perfectly satisfy the following user request:
{{{userInput}}}
Output nothing except for the code. No code block, no English explanation, no start/end tags.`;
const simplestEditPrompt = `Here is the code before editing:
\`\`\`
{{{codeToEdit}}}
\`\`\`
Here is the edit requested:
"{{{userInput}}}"
Here is the code after editing:`;
const codellamaInfillEditPrompt = "{{filePrefix}}<FILL>{{fileSuffix}}";
const codellamaEditPrompt = `[CODE]
{{{codeToEdit}}}
[/CODE]
[INST]
You are an expert programmer and personal assistant, here is your task: "Rewrite the above code in order to {{{userInput}}}"
Your answer should start with a [CODE] tag and end with a [/CODE] tag.
[/INST] Sure! Here's the code you requested:
[CODE]`;
const alpacaEditPrompt = `Below is an instruction that describes a task, paired with an input that provides further context. Write a response that appropriately completes the request.
### Instruction: Rewrite the code to satisfy this request: "{{{userInput}}}"
### Input:
\`\`\`
{{{codeToEdit}}}
\`\`\`
### Response:
Sure! Here's the code you requested:
\`\`\`
`;
const phindEditPrompt = `### System Prompt
You are an expert programmer and write code on the first attempt without any errors or fillers.
### User Message:
Rewrite the code to satisfy this request: "{{{userInput}}}"
\`\`\`
{{{codeToEdit}}}
\`\`\`
### Assistant:
Sure! Here's the code you requested:
\`\`\`
`;
const deepseekEditPrompt = `### System Prompt
You are an AI programming assistant, utilizing the DeepSeek Coder model, developed by DeepSeek Company, and you only answer questions related to computer science. For politically sensitive questions, security and privacy issues, and other non-computer science questions, you will refuse to answer.
### Instruction:
Rewrite the code to satisfy this request: "{{{userInput}}}"
\`\`\`
{{{codeToEdit}}}
\`\`\`<|EOT|>
### Response:
Sure! Here's the code you requested:
\`\`\`
`;
const zephyrEditPrompt = `<|system|>
You are an expert programmer and write code on the first attempt without any errors or fillers.</s>
<|user|>
Rewrite the code to satisfy this request: "{{{userInput}}}"
\`\`\`
{{{codeToEdit}}}
\`\`\`</s>
<|assistant|>
Sure! Here's the code you requested:
\`\`\`
`;
export {
simplifiedEditPrompt,
simplestEditPrompt,
codellamaInfillEditPrompt,
codellamaEditPrompt,
alpacaEditPrompt,
phindEditPrompt,
deepseekEditPrompt,
zephyrEditPrompt,
};

30
core/llm/types.d.ts vendored Normal file
View file

@ -0,0 +1,30 @@
interface CompletionOptions {
model: string;
temperature?: number;
topP?: number;
topK?: number;
presencePenalty?: number;
frequencyPenalty?: number;
stop?: string[];
maxTokens: number;
}
interface RequestOptions {
timeout?: number;
verifySsl?: boolean;
caBundlePath: string;
proxy?: string;
headers?: Record<string, string>;
}
type ChatMessageRole = "user" | "assistant" | "system";
interface ChatMessage {
role: ChatMessageRole;
content: string;
name?: string;
summary: string;
}
export { CompletionOptions, RequestOptions, ChatMessage, ChatMessageRole };