Skip to content

Commit

Permalink
Merge pull request #53 from ferrislucas/use-liquid-in-prompts
Browse files Browse the repository at this point in the history
Support Liquidjs templating in user prompts
  • Loading branch information
ferrislucas authored Oct 6, 2023
2 parents 554587e + 033c5e7 commit c427633
Show file tree
Hide file tree
Showing 2 changed files with 23 additions and 6 deletions.
24 changes: 18 additions & 6 deletions src/services/TemplateLoader.js
Original file line number Diff line number Diff line change
Expand Up @@ -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
}
Expand All @@ -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.
Expand All @@ -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 }}
Expand Down
5 changes: 5 additions & 0 deletions test/templateLoader.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -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', () => {
Expand Down

0 comments on commit c427633

Please sign in to comment.