✨ render mustache template in system message

This commit is contained in:
Nate Sesti 2024-01-08 11:39:42 -08:00
parent 97e54cf8e4
commit e0bd1fe89d
7 changed files with 120 additions and 27 deletions

View file

@ -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<string>
): Promise<ContinueConfig> {
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);
}

View file

@ -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

View file

@ -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<string>
): Promise<string> {
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<string>,
completionOptions?: BaseCompletionOptions,
systemMessage?: string
): Promise<BaseLLM | undefined> {
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);

View file

@ -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<string> {
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 {

View file

@ -293,7 +293,12 @@ async function loadFullConfigNode(ide: IDE): Promise<ContinueConfig> {
console.log("Error loading config.ts: ", e);
}
}
const finalConfig = intermediateToFinalConfig(intermediate);
const finalConfig = await intermediateToFinalConfig(
intermediate,
async (filepath) => {
return ideProtocolClient.readFile(filepath);
}
);
return finalConfig;
}

View file

@ -20,9 +20,7 @@ function useSetup(dispatch: Dispatch<any>) {
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<any>) {
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) {

View file

@ -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",