Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Support Liquidjs templating in user prompts #53

Merged
merged 1 commit into from
Oct 6, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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
Loading