> For the complete documentation index, see [llms.txt](https://knowly-ai.gitbook.io/langtorch/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://knowly-ai.gitbook.io/langtorch/prompt-template.md).

# 📝 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., <mark style="color:red;">`{{$variable}}`</mark>. 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:**

```java
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:**

```java
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.

<pre class="language-java"><code class="lang-java"><strong>public String getSynonym(String word) {
</strong>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());
<strong>}
</strong>
String result = getSynonym("sad") // Depressed            
</code></pre>

Here we introduce **PromptTemplate** to help you conveniently format the prompt.

1. 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**).
2. set variable value with `.setVariables(new HashMap<>(Map.of("variable", "some value"))).`

Formatted prompt looks like this: `What is the synonym of sad?`
