π Prompt Template
Language models process textual data, which is commonly known as a prompt. This text is usually not a fixed string but a blend of templates, examples, and user inputs.
PromptTemplate Class
PromptTemplate
is a class representing a template with variables where variables are defined using double curly braces, e.g., {{$variable}}
. The class provides methods to replace variables with values and validate the template.
Creating a PromptTemplate instance:
Use the builder() method to create a new PromptTemplate.Builder object. Set the template, examples, example header, and variables as needed, then call build() to create the PromptTemplate.
Example:
String template = "Hello {{$name}}!";
PromptTemplate promptTemplate =
PromptTemplate.builder()
.setTemplate(template)
.addVariableValuePair("name", "Langtorch")
.build();
System.out.println(promptTemplate.format()); // Hello Langtorch!
Working with LLM provider:
Straightforward way:
String template = "What is the synonym of Happy?"
// Prerequisite: Set OPENAI_API_KEY inside the .env file under the Resource folder.
OpenAI openAI = new OpenAI();
String result = "Result: " + openAI.run("What is the synonym of Happy?");
// Result: Joyful, cheerful, delighted, pleased, content, satisfied, thrilled, elated, overjoyed.
Now, we can make it more generic: to make a synonym function that returns the synonym of the input.
public String getSynonym(String word) {
String template = "What is the synonym of {{$adj}}?";
PromptTemplate promptTemplate = PromptTemplate.builder()
.setTemplate(template)
.addVariableValuePair("adj", word)
.build();
OpenAI openAI = new OpenAI();
return openAI.run(promptTemplate.format());
}
String result = getSynonym("sad") // Depressed
Here we introduce PromptTemplate to help you conveniently format the prompt.
Define the string template where you can define variables by making it a special pattern:
{{$variable}}
where the variable must be one or more word characters (letters, digits, or underscores).set variable value with
.setVariables(new HashMap<>(Map.of("variable", "some value"))).
Formatted prompt looks like this: What is the synonym of sad?
Last updated