✨ allow templating for custom commands

This commit is contained in:
Nate Sesti 2024-04-14 16:00:30 -07:00
parent 332c69fc1e
commit 6ff78fd8f3
7 changed files with 146 additions and 131 deletions

View file

@ -1,43 +1,58 @@
import { CustomCommand, SlashCommand, SlashCommandDescription } from "..";
import { stripImages } from "../llm/countTokens";
import { renderTemplatedString } from "../llm/llms";
import SlashCommands from "./slash";
export function slashFromCustomCommand(
customCommand: CustomCommand,
customCommand: CustomCommand,
): SlashCommand {
return {
name: customCommand.name,
description: customCommand.description,
run: async function* ({ input, llm, history }) {
const promptUserInput = `Task: ${customCommand.prompt}. Additional info: ${input}`;
const messages = [...history];
// Find the last chat message with this slash command and replace it with the user input
for (let i = messages.length - 1; i >= 0; i--) {
if (
messages[i].role === "user" &&
stripImages(messages[i].content).startsWith(`/${customCommand.name}`)
) {
messages[i] = { ...messages[i], content: promptUserInput };
break;
}
}
return {
name: customCommand.name,
description: customCommand.description,
run: async function* ({ input, llm, history, ide }) {
// Remove slash command prefix from input
let userInput = input;
if (userInput.startsWith(`/${customCommand.name}`)) {
userInput = userInput
.slice(customCommand.name.length + 1, userInput.length)
.trimStart();
}
for await (const chunk of llm.streamChat(messages)) {
yield stripImages(chunk.content);
}
},
};
// Render prompt template
const promptUserInput = await renderTemplatedString(
customCommand.prompt,
ide.readFile.bind(ide),
{ input: userInput },
);
const messages = [...history];
// Find the last chat message with this slash command and replace it with the user input
for (let i = messages.length - 1; i >= 0; i--) {
if (
messages[i].role === "user" &&
stripImages(messages[i].content).startsWith(`/${customCommand.name}`)
) {
messages[i] = { ...messages[i], content: promptUserInput };
break;
}
}
for await (const chunk of llm.streamChat(messages)) {
yield stripImages(chunk.content);
}
},
};
}
export function slashCommandFromDescription(
desc: SlashCommandDescription,
desc: SlashCommandDescription,
): SlashCommand | undefined {
const cmd = SlashCommands.find((cmd) => cmd.name === desc.name);
if (!cmd) {
return undefined;
}
return {
...cmd,
params: desc.params,
};
const cmd = SlashCommands.find((cmd) => cmd.name === desc.name);
if (!cmd) {
return undefined;
}
return {
...cmd,
params: desc.params,
};
}

View file

@ -1,10 +1,10 @@
import Handlebars from "handlebars";
import { BaseLLM } from "..";
import {
BaseCompletionOptions,
ILLM,
LLMOptions,
ModelDescription,
BaseCompletionOptions,
ILLM,
LLMOptions,
ModelDescription,
} from "../..";
import { DEFAULT_MAX_TOKENS } from "../constants";
import Anthropic from "./Anthropic";
@ -28,121 +28,121 @@ 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;
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,
value: string,
): [string, { [key: string]: string }] => {
const ast = Handlebars.parse(value);
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];
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>,
export async function renderTemplatedString(
template: string,
readFile: (filepath: string) => Promise<string>,
inputData: any,
): 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 [newTemplate, vars] = getHandlebarsVars(template);
const data: any = { ...inputData };
for (const key in vars) {
const fileContents = await readFile(vars[key]);
data[key] = fileContents || (inputData[vars[key]] ?? vars[key]);
}
const templateFn = Handlebars.compile(newTemplate);
const final = templateFn(data);
return final;
}
const LLMs = [
Anthropic,
FreeTrial,
Gemini,
Llamafile,
Ollama,
Replicate,
TextGenWebUI,
Together,
HuggingFaceTGI,
HuggingFaceInferenceAPI,
LlamaCpp,
OpenAI,
LMStudio,
Mistral,
Bedrock,
DeepInfra,
OpenAIFreeTrial,
Flowise,
Groq,
Anthropic,
FreeTrial,
Gemini,
Llamafile,
Ollama,
Replicate,
TextGenWebUI,
Together,
HuggingFaceTGI,
HuggingFaceInferenceAPI,
LlamaCpp,
OpenAI,
LMStudio,
Mistral,
Bedrock,
DeepInfra,
OpenAIFreeTrial,
Flowise,
Groq,
];
export async function llmFromDescription(
desc: ModelDescription,
readFile: (filepath: string) => Promise<string>,
completionOptions?: BaseCompletionOptions,
systemMessage?: string,
desc: ModelDescription,
readFile: (filepath: string) => Promise<string>,
completionOptions?: BaseCompletionOptions,
systemMessage?: string,
): Promise<BaseLLM | undefined> {
const cls = LLMs.find((llm) => llm.providerName === desc.provider);
const cls = LLMs.find((llm) => llm.providerName === desc.provider);
if (!cls) {
return undefined;
}
if (!cls) {
return undefined;
}
const finalCompletionOptions = {
...completionOptions,
...desc.completionOptions,
};
const finalCompletionOptions = {
...completionOptions,
...desc.completionOptions,
};
systemMessage = desc.systemMessage ?? systemMessage;
if (systemMessage !== undefined) {
systemMessage = await renderTemplatedString(systemMessage, readFile);
}
systemMessage = desc.systemMessage ?? systemMessage;
if (systemMessage !== undefined) {
systemMessage = await renderTemplatedString(systemMessage, readFile, {});
}
const options: LLMOptions = {
...desc,
completionOptions: {
...finalCompletionOptions,
model: (desc.model || cls.defaultOptions?.model) ?? "codellama-7b",
maxTokens:
finalCompletionOptions.maxTokens ??
cls.defaultOptions?.completionOptions?.maxTokens ??
DEFAULT_MAX_TOKENS,
},
systemMessage,
};
const options: LLMOptions = {
...desc,
completionOptions: {
...finalCompletionOptions,
model: (desc.model || cls.defaultOptions?.model) ?? "codellama-7b",
maxTokens:
finalCompletionOptions.maxTokens ??
cls.defaultOptions?.completionOptions?.maxTokens ??
DEFAULT_MAX_TOKENS,
},
systemMessage,
};
return new cls(options);
return new cls(options);
}
export function llmFromProviderAndOptions(
providerName: string,
llmOptions: LLMOptions,
providerName: string,
llmOptions: LLMOptions,
): ILLM {
const cls = LLMs.find((llm) => llm.providerName === providerName);
const cls = LLMs.find((llm) => llm.providerName === providerName);
if (!cls) {
throw new Error(`Unknown LLM provider type "${providerName}"`);
}
if (!cls) {
throw new Error(`Unknown LLM provider type "${providerName}"`);
}
return new cls(llmOptions);
return new cls(llmOptions);
}

View file

@ -1590,7 +1590,7 @@
{
"name": "test",
"prompt": "Write a comprehensive set of unit tests for the selected code. It should setup, run tests that check for correctness including important edge cases, and teardown. Ensure that the tests are complete and sophisticated. Give the tests just as chat output, don't edit any file.",
"description": "This is an example custom command. Use /config to edit it and create more"
"description": "This is an example custom command. Open config.json to edit it and create more"
}
],
"type": "array",

View file

@ -1590,7 +1590,7 @@
{
"name": "test",
"prompt": "Write a comprehensive set of unit tests for the selected code. It should setup, run tests that check for correctness including important edge cases, and teardown. Ensure that the tests are complete and sophisticated. Give the tests just as chat output, don't edit any file.",
"description": "This is an example custom command. Use /config to edit it and create more"
"description": "This is an example custom command. Open config.json to edit it and create more"
}
],
"type": "array",

View file

@ -1590,7 +1590,7 @@
{
"name": "test",
"prompt": "Write a comprehensive set of unit tests for the selected code. It should setup, run tests that check for correctness including important edge cases, and teardown. Ensure that the tests are complete and sophisticated. Give the tests just as chat output, don't edit any file.",
"description": "This is an example custom command. Use /config to edit it and create more"
"description": "This is an example custom command. Open config.json to edit it and create more"
}
],
"type": "array",

View file

@ -1780,7 +1780,7 @@
{
"name": "test",
"prompt": "Write a comprehensive set of unit tests for the selected code. It should setup, run tests that check for correctness including important edge cases, and teardown. Ensure that the tests are complete and sophisticated. Give the tests just as chat output, don't edit any file.",
"description": "This is an example custom command. Use /config to edit it and create more"
"description": "This is an example custom command. Open config.json to edit it and create more"
}
],
"type": "array",

View file

@ -15,5 +15,5 @@
"resolveJsonModule": true /* Enable importing .json files */
},
"include": ["src/**/*", "../../core/**/*.ts"],
"exclude": ["../../core/dist/**/*"]
"exclude": ["../../core/dist/**/*", "../../core/test/**/*"]
}