diff --git a/.changeset/rotten-fans-mix.md b/.changeset/rotten-fans-mix.md new file mode 100644 index 0000000000000000000000000000000000000000..58e4f519c1f1b387c7abe913cde58bfd3287714c --- /dev/null +++ b/.changeset/rotten-fans-mix.md @@ -0,0 +1,5 @@ +--- +"@llamaindex/core": patch +--- + +Get PromptTemplate template variables at run-time diff --git a/packages/core/src/prompts/base.ts b/packages/core/src/prompts/base.ts index 2aacdf34046b4c7cfb813d99d738a6dfcd2b1513..b17b11316cd79c974fed963710ec30135b488b59 100644 --- a/packages/core/src/prompts/base.ts +++ b/packages/core/src/prompts/base.ts @@ -32,6 +32,10 @@ export abstract class BasePromptTemplate< const Vars extends readonly string[] = string[], > { metadata: Metadata = {}; + /** + * Set of template variables used in the prompt template. Used for type hints only. + * To get the list of template variables used in the prompt at run-time, use the `vars` method. + */ templateVars: Set<string> = new Set(); options: Partial<Record<TemplatesVar[number] | (string & {}), string>> = {}; outputParser: BaseOutputParser | undefined; @@ -223,4 +227,13 @@ export class PromptTemplate< get template(): Template { return this.#template; } + + /** + * Returns all the template variables used in the prompt template. + */ + vars(): string[] { + const template = this.template; + const matches = template.match(/\{([^}]+)\}/g) || []; + return [...new Set(matches.map((match) => match.slice(1, -1)))]; + } } diff --git a/packages/core/tests/prompts.test.ts b/packages/core/tests/prompts.test.ts index d0a839f3a45014ba76e8282c4c49d1319fa0d063..48b9bac02928ce7e6ce5b3c1c378343cafe3f7c9 100644 --- a/packages/core/tests/prompts.test.ts +++ b/packages/core/tests/prompts.test.ts @@ -158,4 +158,15 @@ describe("PromptTemplate", () => { const formatted = prompt.format({ text: "world", foo: "bar" }); expect(formatted).toBe("hello world bar\noutput_instruction"); }); + + test("should return all unique template vars of a prompt", () => { + const prompt = new PromptTemplate({ + template: "Hello {name}! Your age is {age}. Nice to meet you {name}!", + }); + + const vars = prompt.vars(); + expect(vars).toHaveLength(2); + expect(vars).toContain("name"); + expect(vars).toContain("age"); + }); });