Skip to content

Commit

Permalink
core[patch]: Account for escaped variables in mustache templates (#5775)
Browse files Browse the repository at this point in the history
  • Loading branch information
bracesproul authored Jun 15, 2024
1 parent a2ded31 commit d09f63a
Show file tree
Hide file tree
Showing 2 changed files with 25 additions and 1 deletion.
4 changes: 3 additions & 1 deletion langchain-core/src/prompts/template.ts
Original file line number Diff line number Diff line change
Expand Up @@ -85,7 +85,9 @@ const mustacheTemplateToNodes = (
if (temp[0] === "name") {
const name = temp[1].includes(".") ? temp[1].split(".")[0] : temp[1];
return { type: "variable", name };
} else if (temp[0] === "#") {
} else if (["#", "&"].includes(temp[0])) {
// # represents a section, "&" represents an unescaped variable.
// These should both be considered variables.
return { type: "variable", name: temp[1] };
} else {
return { type: "literal", text: temp[1] };
Expand Down
22 changes: 22 additions & 0 deletions langchain-core/src/prompts/tests/prompt.mustache.test.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
import { test, expect } from "@jest/globals";
import { PromptTemplate } from "../prompt.js";
import { parseTemplate } from "../template.js";

test("Single input variable.", async () => {
const template = "This is a {{foo}} test.";
Expand Down Expand Up @@ -91,3 +92,24 @@ hello
is a test.`);
expect(promptWithRepeats.inputVariables).toEqual(["foo"]);
});

test("Escaped variables", async () => {
const template = `test: {{{text}}}`;
const parsed = parseTemplate(template, "mustache");
expect(parsed[0]).toStrictEqual({
type: "literal",
text: "test: ",
});
expect(parsed[1]).toStrictEqual({
type: "variable",
name: "text",
});

const promptTemplate = PromptTemplate.fromTemplate(template, {
templateFormat: "mustache",
});
const result = await promptTemplate.invoke({
text: `hello i have a "quote`,
});
expect(result.value).toBe(`test: hello i have a "quote`);
});

0 comments on commit d09f63a

Please sign in to comment.