From 033c5e7f0bbc59ecb15f2d01a3ee5b80a9f0ffd9 Mon Sep 17 00:00:00 2001 From: Ferris Lucas Date: Fri, 6 Oct 2023 18:19:03 -0500 Subject: [PATCH] Support liquidjs templating in user prompts --- src/services/TemplateLoader.js | 24 ++++++++++++++++++------ test/templateLoader.test.js | 5 +++++ 2 files changed, 23 insertions(+), 6 deletions(-) diff --git a/src/services/TemplateLoader.js b/src/services/TemplateLoader.js index d88aee9..17c9cd0 100644 --- a/src/services/TemplateLoader.js +++ b/src/services/TemplateLoader.js @@ -10,12 +10,24 @@ class TemplateLoader { await this.loadTemplateFromUrl(template) : await this.loadTemplateFromPath(template) } + const expandedPrompt = await this.parseTemplate(prompt, context) const engine = new Liquid() engine.registerFilter("jsonToObject", (json) => JSON.parse(json)) - const tpl = engine.parse(templateText) + const tpl = engine.parse(templateText) const content = await engine.render(tpl, { context: context, - prompt: prompt + prompt: expandedPrompt + }) + return content + } + + static async parseTemplate(text, context) { + const engine = new Liquid() + engine.registerFilter("jsonToObject", (json) => JSON.parse(json)) + const tpl = engine.parse(text) + const content = await engine.render(tpl, { + context: context, + prompt: text }) return content } @@ -38,7 +50,7 @@ class TemplateLoader { static getTemplateText(template) { if (template === 'refactor') { - return `The user's request is: {{prompt}} + return `{{prompt}} {% if context.files.size > 0 %} ### The following are file paths and content related to this request. @@ -54,9 +66,9 @@ File: {{ item.filename }} """ if (template === 'empty') { return `{% if context.files.size > 0 %}You will be provided the contents of some files. The contents of each file begin with "--BEGIN-FILE:" followed by the file path. -The contents of each file end with "--END-FILE--".{% endif %} - -Your instructions are: {{prompt}} +The contents of each file end with "--END-FILE--". +{% endif %} +{{prompt}} {% if context.files.size > 0 %}The file contents are below:{% endif %} {% for item in context.files %} --BEGIN-FILE: {{ item.filename }} diff --git a/test/templateLoader.test.js b/test/templateLoader.test.js index ad140d8..d14b651 100644 --- a/test/templateLoader.test.js +++ b/test/templateLoader.test.js @@ -24,6 +24,11 @@ describe('TemplateLoader', () => { loadTemplateFromPathStub.restore(); }); + + it('should expand liduidjs templating tags in the prompt', async () => { + const result = await TemplateLoader.loadTemplate('prompt: {{context.test}}', { test: 42 }, 'empty') + assert.strictEqual(result.trim(), 'prompt: 42') + }) }); describe('loadTemplateFromUrl', () => {