From e0bd1fe89d9a2a587780d5f236f6c7628174bb28 Mon Sep 17 00:00:00 2001 From: Nate Sesti Date: Mon, 8 Jan 2024 11:39:42 -0800 Subject: [PATCH] =?UTF-8?q?=E2=9C=A8=20render=20mustache=20template=20in?= =?UTF-8?q?=20system=20message?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- core/config/load.ts | 12 ++++- core/llm/countTokens.ts | 8 +-- core/llm/llms/index.ts | 62 ++++++++++++++++++++-- extensions/vscode/src/continueIdeClient.ts | 16 ++++-- extensions/vscode/src/ideProtocol.ts | 7 ++- gui/src/hooks/useSetup.ts | 9 ++-- gui/src/redux/slices/stateSlice.ts | 33 +++++++++--- 7 files changed, 120 insertions(+), 27 deletions(-) diff --git a/core/config/load.ts b/core/config/load.ts index ecf2205de..75b3490d1 100644 --- a/core/config/load.ts +++ b/core/config/load.ts @@ -56,12 +56,20 @@ function isContextProviderWithParams( } /** Only difference between intermediate and final configs is the `models` array */ -function intermediateToFinalConfig(config: Config): ContinueConfig { +async function intermediateToFinalConfig( + config: Config, + readFile: (filepath: string) => Promise +): Promise { const models: BaseLLM[] = []; for (const desc of config.models) { let llm: BaseLLM | undefined; if (isModelDescription(desc)) { - llm = llmFromDescription(desc, config.completionOptions); + llm = await llmFromDescription( + desc, + readFile, + config.completionOptions, + config.systemMessage + ); } else { llm = new CustomLLMClass(desc); } diff --git a/core/llm/countTokens.ts b/core/llm/countTokens.ts index 4f2f24eb9..964ba627d 100644 --- a/core/llm/countTokens.ts +++ b/core/llm/countTokens.ts @@ -6,11 +6,6 @@ import { import { ChatMessage } from ".."; import { TOKEN_BUFFER_FOR_SAFETY } from "./constants"; -function renderTemplatedString(template: string): string { - // TODO - return template; -} - function encodingForModel(modelName: string): Tiktoken { let encoding: Tiktoken; try { @@ -216,10 +211,9 @@ function compileChatMessages( } if (systemMessage && systemMessage.trim() !== "") { - const renderedSystemMessage = renderTemplatedString(systemMessage); const systemChatMsg: ChatMessage = { role: "system", - content: renderedSystemMessage, + content: systemMessage, }; // Insert as second to last // Later moved to top, but want second-priority to last user message diff --git a/core/llm/llms/index.ts b/core/llm/llms/index.ts index 1cbb95ffa..6721eb75d 100644 --- a/core/llm/llms/index.ts +++ b/core/llm/llms/index.ts @@ -1,3 +1,4 @@ +import Handlebars from "handlebars"; import { BaseLLM } from ".."; import { BaseCompletionOptions, @@ -23,6 +24,53 @@ import Replicate from "./Replicate"; import TextGenWebUI from "./TextGenWebUI"; import Together from "./Together"; +function convertToLetter(num: number): string { + let result = ""; + while (num > 0) { + const remainder = (num - 1) % 26; + result = String.fromCharCode(97 + remainder) + result; + num = Math.floor((num - 1) / 26); + } + return result; +} + +const getHandlebarsVars = ( + value: string +): [string, { [key: string]: string }] => { + const ast = Handlebars.parse(value); + + let keysToFilepath: { [key: string]: string } = {}; + let keyIndex = 1; + for (let i in ast.body) { + if (ast.body[i].type === "MustacheStatement") { + const letter = convertToLetter(keyIndex); + keysToFilepath[letter] = (ast.body[i] as any).path.original; + value = value.replace( + new RegExp("{{\\s*" + (ast.body[i] as any).path.original + "\\s*}}"), + `{{${letter}}}` + ); + keyIndex++; + } + } + return [value, keysToFilepath]; +}; + +async function renderTemplatedString( + template: string, + readFile: (filepath: string) => Promise +): Promise { + const [newTemplate, vars] = getHandlebarsVars(template); + template = newTemplate; + let data: any = {}; + for (let key in vars) { + let fileContents = await readFile(vars[key]); + data[key] = fileContents || vars[key]; + } + const templateFn = Handlebars.compile(template); + let final = templateFn(data); + return final; +} + const LLMs = [ Anthropic, FreeTrial, @@ -43,10 +91,12 @@ const LLMs = [ DeepInfra, ]; -export function llmFromDescription( +export async function llmFromDescription( desc: ModelDescription, - completionOptions?: BaseCompletionOptions -): BaseLLM | undefined { + readFile: (filepath: string) => Promise, + completionOptions?: BaseCompletionOptions, + systemMessage?: string +): Promise { const cls = LLMs.find((llm) => llm.providerName === desc.provider); if (!cls) { @@ -58,6 +108,11 @@ export function llmFromDescription( ...desc.completionOptions, }; + systemMessage = desc.systemMessage || systemMessage; + if (systemMessage !== undefined) { + systemMessage = await renderTemplatedString(systemMessage, readFile); + } + const options: LLMOptions = { ...desc, completionOptions: { @@ -68,6 +123,7 @@ export function llmFromDescription( cls.defaultOptions?.completionOptions?.maxTokens || 1024, }, + systemMessage, }; return new cls(options); diff --git a/extensions/vscode/src/continueIdeClient.ts b/extensions/vscode/src/continueIdeClient.ts index 39cdecb1c..411677497 100644 --- a/extensions/vscode/src/continueIdeClient.ts +++ b/extensions/vscode/src/continueIdeClient.ts @@ -1,6 +1,7 @@ import { FileEdit, RangeInFile } from "core"; import { getConfigJsonPath } from "core/util/paths"; import { readFileSync } from "fs"; +import * as path from "path"; import * as vscode from "vscode"; import { debugPanelWebview, getSidebarContent } from "./debugPanel"; import { diffManager } from "./diff/horizontal"; @@ -17,8 +18,6 @@ import { openEditorAndRevealRange, uriFromFilePath, } from "./util/vscode"; -const os = require("os"); -const path = require("path"); const continueVirtualDocumentScheme = "continue"; @@ -353,8 +352,19 @@ class IdeProtocolClient { return absolutePaths; } + getAbsolutePath(filepath: string): string { + const workspaceDirectories = this.getWorkspaceDirectories(); + if (!path.isAbsolute(filepath) && workspaceDirectories.length === 1) { + return path.join(workspaceDirectories[0], filepath); + } else { + return filepath; + } + } + async readFile(filepath: string): Promise { - const MAX_BYTES = 100000; // 0.1MB - socket.io has a 1MB limit, but seems to die a around 0.5MB + filepath = this.getAbsolutePath(filepath); + + const MAX_BYTES = 100000; let contents: string | undefined; if (typeof contents === "undefined") { try { diff --git a/extensions/vscode/src/ideProtocol.ts b/extensions/vscode/src/ideProtocol.ts index 933948e6a..ff453a850 100644 --- a/extensions/vscode/src/ideProtocol.ts +++ b/extensions/vscode/src/ideProtocol.ts @@ -293,7 +293,12 @@ async function loadFullConfigNode(ide: IDE): Promise { console.log("Error loading config.ts: ", e); } } - const finalConfig = intermediateToFinalConfig(intermediate); + const finalConfig = await intermediateToFinalConfig( + intermediate, + async (filepath) => { + return ideProtocolClient.readFile(filepath); + } + ); return finalConfig; } diff --git a/gui/src/hooks/useSetup.ts b/gui/src/hooks/useSetup.ts index 255a43c7d..6fc898a8d 100644 --- a/gui/src/hooks/useSetup.ts +++ b/gui/src/hooks/useSetup.ts @@ -20,9 +20,7 @@ function useSetup(dispatch: Dispatch) { try { const ide = new ExtensionIde(); let serialized = await ide.getSerializedConfig(); - console.log("serialized: ", serialized); let intermediate = serializedToIntermediateConfig(serialized); - console.log("i1", intermediate); const configJsUrl = await ide.getConfigJsUrl(); if (configJsUrl) { @@ -40,7 +38,12 @@ function useSetup(dispatch: Dispatch) { errorPopup(e.message); } } - const finalConfig = intermediateToFinalConfig(intermediate); + const finalConfig = await intermediateToFinalConfig( + intermediate, + async (filepath) => { + return new ExtensionIde().readFile(filepath); + } + ); // Fall back to config.json dispatch(setConfig(finalConfig)); } catch (e) { diff --git a/gui/src/redux/slices/stateSlice.ts b/gui/src/redux/slices/stateSlice.ts index 27b0aad89..7fd2ca02d 100644 --- a/gui/src/redux/slices/stateSlice.ts +++ b/gui/src/redux/slices/stateSlice.ts @@ -8,11 +8,14 @@ import { ContinueConfig, PersistedSessionInfo, } from "core"; -import defaultConfig from "core/config/default"; -import { - intermediateToFinalConfig, - serializedToIntermediateConfig, -} from "core/config/load"; +import GenerateTerminalCommand from "core/commands/slash/cmd"; +import CommentSlashCommand from "core/commands/slash/comment"; +import EditSlashCommand from "core/commands/slash/edit"; +import ShareSlashCommand from "core/commands/slash/share"; +import DiffContextProvider from "core/context/providers/DiffContextProvider"; +import OpenFilesContextProvider from "core/context/providers/OpenFilesContextProvider"; +import TerminalContextProvider from "core/context/providers/TerminalContextProvider"; +import FreeTrial from "core/llm/llms/FreeTrial"; import { v4 } from "uuid"; import { RootStore } from "../store"; @@ -90,9 +93,23 @@ const initialState: RootStore["state"] = { history: [], contextItems: [], active: false, - config: intermediateToFinalConfig( - serializedToIntermediateConfig(defaultConfig) - ), + config: { + models: [ + new FreeTrial({ model: "gpt-4", title: "GPT-4" }), + new FreeTrial({ model: "gpt-3.5-turbo", title: "GPT-3.5-Turbo" }), + ], + slashCommands: [ + EditSlashCommand, + CommentSlashCommand, + ShareSlashCommand, + GenerateTerminalCommand, + ], + contextProviders: [ + new DiffContextProvider({}), + new OpenFilesContextProvider({}), + new TerminalContextProvider({}), + ], + }, title: "New Session", sessionId: v4(), defaultModelTitle: "GPT-4",