Skip to content
Snippets Groups Projects
Unverified Commit 6d22fa2a authored by Marcus Schiesser's avatar Marcus Schiesser Committed by GitHub
Browse files

feat: Get PromptTemplate template variables at run-time (#1502)

parent 16f00681
No related branches found
No related tags found
No related merge requests found
---
"@llamaindex/core": patch
---
Get PromptTemplate template variables at run-time
...@@ -32,6 +32,10 @@ export abstract class BasePromptTemplate< ...@@ -32,6 +32,10 @@ export abstract class BasePromptTemplate<
const Vars extends readonly string[] = string[], const Vars extends readonly string[] = string[],
> { > {
metadata: Metadata = {}; 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(); templateVars: Set<string> = new Set();
options: Partial<Record<TemplatesVar[number] | (string & {}), string>> = {}; options: Partial<Record<TemplatesVar[number] | (string & {}), string>> = {};
outputParser: BaseOutputParser | undefined; outputParser: BaseOutputParser | undefined;
...@@ -223,4 +227,13 @@ export class PromptTemplate< ...@@ -223,4 +227,13 @@ export class PromptTemplate<
get template(): Template { get template(): Template {
return this.#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)))];
}
} }
...@@ -158,4 +158,15 @@ describe("PromptTemplate", () => { ...@@ -158,4 +158,15 @@ describe("PromptTemplate", () => {
const formatted = prompt.format({ text: "world", foo: "bar" }); const formatted = prompt.format({ text: "world", foo: "bar" });
expect(formatted).toBe("hello world bar\noutput_instruction"); 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");
});
}); });
0% Loading or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment