Annotation Based Prompt Template

Annotation provides a simple way to define prompt templates with variables using annotations. This library has two main parts:

  1. @Prompt annotation: Used to define a prompt template with variables, examples, and an optional name for the prompt.

  2. PromptProcessor class: Responsible for processing the @Prompt and @Prompts annotations on a class and creating a PromptTemplate based on the annotations and the fields of the annotated class.

Usage:

Example

Here's an example of using the @Prompt annotation:

@Prompt(
    template = "Hello, {{$name}}! Your age is {{$age}}.",
    variables = {"name", "age"})
class HelloAgePrompt {
  public String name = "Jane";
  public String age = "30";
}

HelloAgePrompt helloAgePrompt = new HelloAgePrompt();
PromptTemplate helloAgePromptTemplate =
    PromptProcessor.createPromptTemplate(HelloAgePrompt.class, helloAgePrompt);
String result = helloAgePromptTemplate.format();
System.out.println(result); // Output: "Hello, Jane! Your age is 30."

Using multiple prompts

When you have multiple prompt templates in a single class, use the @Prompts annotation as a container for multiple @Prompt annotations. In this case, provide a unique name for each prompt:

@Prompt(
    template = "My favourite subject in school is {{$subject}}.",
    variables = {"subject"},
    name = "favoriteSubjectPrompt")
@Prompt(
    template = "I really love {{$subject}} because {{$reason}}.",
    name = "reasonPrompt",
    variables = {"reason", "subject"})
private static class SubjectRelatedPrompt {
  public String subject = "Math";
  public String reason = "I love numbers";
}

SubjectRelatedPrompt subjectRelatedPrompt = new SubjectRelatedPrompt();
PromptTemplate textPromptTemplate =
    PromptProcessor.createPromptTemplate(
        SubjectRelatedPrompt.class, subjectRelatedPrompt, "favoriteSubjectPrompt");
String result = textPromptTemplate.format();
System.out.println(result); // Output: "My favourite subject in school is Math."

Last updated