LangChain4j's PromptTemplate allows you to create dynamic prompts with placeholders. Instead of hardcoding prompt strings, you can define templates with variables that get replaced at runtime with actual values.
This approach provides several benefits:
- Reusability of prompt structures across different contexts
- Clean separation of prompt logic from data
- Consistent prompt formatting
- Easy maintenance and updates to prompt templates
PromptTemplate Usage
Prompt templates use a simple syntax with {{variableName}} placeholders. When you apply the template, these placeholders are replaced with actual values, creating a complete prompt ready for the AI model.
Creating PromptTemplate
Following methods are used to create PromptTemplate instance:
public static PromptTemplate from(String template)
This method is the most basic version, used when you only need to process a raw string.
public static PromptTemplate from(String template,
String name)
This method allows a raw string along with a unique name to the template, which is particularly useful for logging, debugging, or tracking prompt performance in complex applications.
public static PromptTemplate from(String template,
Clock clock)
Other than string template and a name, this method accepts an instance of Clock which enables the automatic injection of temporal variables:
- {{current_date}}
- {{current_time}}
- {{current_date_time}}
In fact the above first two methods also implicity support this variables, if clock is not provided or it is null then internally Clock.systemDefaultZone() is used to create the Clock instance.
Applying template variables
Following are the method of which replaces the placeholders with their values.
Prompt apply(Object value)
Above method applies a value to a template containing a single variable. The single variable should have the name {{it}}
Prompt apply(Map<String, Object> variables)
Above method applies multiple values to a template containing multiple variables.
Understanding Prompt class
Prompt class has various useful methods to create messages.
Definition of PromptVersion: 1.10.0 package dev.langchain4j.model.input;
public class Prompt {
/**
* Create a new Prompt.
* @param text the text of the prompt.
*/
public Prompt(String text) {
}
public String text(); 1
public SystemMessage toSystemMessage(); 2
public UserMessage toUserMessage(String userName); 3
public UserMessage toUserMessage(); 4
public AiMessage toAiMessage(); 5
public boolean equals(Object o);
public int hashCode();
public String toString();
public static Prompt from(String text); 6
}
Examples
The following example demonstrates how to create a restaurant review analyzer using PromptTemplate. We'll define a template that takes customer feedback and analyzes it in a structured way.
package com.logicbig.example;
import dev.langchain4j.data.message.UserMessage;
import dev.langchain4j.model.chat.ChatModel;
import dev.langchain4j.model.chat.response.ChatResponse;
import dev.langchain4j.model.input.Prompt;
import dev.langchain4j.model.input.PromptTemplate;
import dev.langchain4j.model.ollama.OllamaChatModel;
public class RestaurantReviewAnalyzer {
public static void main(String[] args) {
// Create Ollama model with Phi3
ChatModel model = OllamaChatModel.builder()
.baseUrl("http://localhost:11434")
.modelName("phi3:mini-128k")
.numCtx(4096)
.temperature(0.7)
.build();
// Define prompt template for review analysis
String template = "The time is {{current_date_time}}.\n"
+ "Analyze the following restaurant review and provide:\n" +
"1. Sentiment (positive/negative/neutral)\n" +
"2. Key points mentioned\n" +
"3. Suggestions for improvement\n\n" +
"Review: {{it}}";
PromptTemplate promptTemplate = PromptTemplate.from(template);
Prompt prompt = promptTemplate.apply(
"The food was excellent but "
+ "the service was very slow. " +
"We waited 45 minutes for our main course. " +
"The dessert, however, was amazing.");
// Generate response
UserMessage userMessage = prompt.toUserMessage();
ChatResponse response = model.chat(userMessage);
System.out.println("=== Restaurant Review Analysis ===");
System.out.println("Prompt:\n" + prompt.text());
System.out.println("\nAnalysis:\n" + response.aiMessage().text());
}
}
Output=== Restaurant Review Analysis === Prompt: The time is 2026-01-18T18:44:35.249431700. Analyze the following restaurant review and provide: 1. Sentiment (positive/negative/neutral) 2. Key points mentioned 3. Suggestions for improvement
Review: The food was excellent but the service was very slow. We waited 45 minutes for our main course. The dessert, however, was amazing.
Analysis: 1. Sentiment - Mixed (positive and negative) 2. Key points mentioned: - Positive sentiment towards their food quality with comments like "The food was excellent" and the praise of the "dessert [being] amazing." These indicate satisfaction in what they ate, particularly noticing good taste from different dishes on offer. - Negative sentiment regarding service speed as indicated by phrases such as "the service was very slow," along with quantifiable information about wait time ("45 minutes for our main course"). This implies dissatisfaction due to the delay and suggests a negative impact on overall experience if timely service is valued. 3. Suggestions for improvement: - The restaurant could benefit from staff training or process evaluation aimed at reducing waiting times, with specific focus areas being meal preparation efficiency and possibly table management strategies to expedite serving without compromising food quality. Regular performance reviews might help identify bottlenecks in the service delivery chain that need addressing. Additionally, implementing a system for managing peak hours or ensuring more staff during busy times could mitigate wait issues while maintaining high standards of customer experience and satisfaction.
Template with Multiple Variables
PromptTemplate can handle multiple variables and complex structures. Let's see another example that generates personalized product recommendations based on user preferences.
package com.logicbig.example;
import dev.langchain4j.model.chat.ChatModel;
import dev.langchain4j.model.chat.response.ChatResponse;
import dev.langchain4j.model.input.Prompt;
import dev.langchain4j.model.input.PromptTemplate;
import dev.langchain4j.model.ollama.OllamaChatModel;
import java.util.Map;
public class ProductRecommendationGenerator {
public static void main(String[] args) {
// Create Ollama model
ChatModel model = OllamaChatModel.builder()
.baseUrl("http://localhost:11434")
.modelName("phi3:mini-128k")
.numCtx(4096)
.temperature(0.7)
.build();
// Define template with multiple variables
String template = "Recommend {{number}} {{category}} products " +
"within a budget of {{budget}}. " +
"The user prefers: {{preferences}}.";
Prompt prompt = PromptTemplate.from(template)
.apply(Map.of("number", "3",
"category", "smartphone",
"budget", "$500-$700",
"preferences", "good camera, "
+ "long battery life, and "
+ "5G support"));
// Generate response
ChatResponse response = model.chat(prompt.toUserMessage());
System.out.println("=== Product Recommendations ===");
System.out.println("Template: " + template);
System.out.println("\nGenerated Prompt: " + prompt.text());
System.out.println("\nRecommendations:\n" + response.aiMessage().text());
}
}
Output=== Product Recommendations === Template: Recommend {{number}} {{category}} products within a budget of {{budget}}. The user prefers: {{preferences}}.
Generated Prompt: Recommend 3 smartphone products within a budget of $500-$700. The user prefers: good camera, long battery life, and 5G support.
Recommendations: 1. Samsung Galaxy M42 - This is an excellent choice for its great all-around performance including the A6 processor along with a triple rear cameras setup which are capable of taking high quality pictures even in low light conditions. The phone has up to 30 hours talk time and supports 5G connectivity, ensuring you get fast internet speeds wherever available within your budget range. 2. Google Pixel 6a - With its top-notch camera system that performs well both daylight and low light photos taken with the rear triple cameras setup; coupled with a long battery life of up to about 45 hours talk time, this phone provides excellent value for money within your budget range. It also comes equipped with T-Mobile'in exclusive Google Mobile Hotspot feature which allows multiple devices connected simultaneously and offers impressive speeds when using the same carrier as well supporting 5G connectivity in select areas. 3. Motorola Moto G Play - This mid-range smartphone provides a great balance of features, including an excellent camera with dual rear cameras setup that can deliver decent quality photos even for social media sharing or casual photography needs on the go; it also offers impressive battery life lasting up to 36 hours talk time. Not only does this phone support T-Mobile's exclusive Google Mobile Hotspot feature, but Motorola�s dedication towards providing a robust and reliable network experience ensures stable internet connectivity when in an area with good signal coverage as well offering impressive speeds at times within your budget range while also supporting 5G. In summary, all three of these recommended smartphones offer great camera performance combined with long battery life along with the support for T-Mobile's exclusive Google Mobile Hotspot feature and in select areas they can provide you fast internet connectivity through their built-in LTE modem or 5G where available. All come within your budget range, making them perfect choices to fulfill all of your requirements without breaking much on price.
Template with Clock
This example demonstrates automatic date and time injection within input messages.
The following variables are automatically injected when a Clock instance is provided (if no instance is specified, the system default clock is used):
- {{current_date}}
- {{current_time}}
- {{current_date_time}}
package com.logicbig.example;
import dev.langchain4j.model.chat.ChatModel;
import dev.langchain4j.model.input.Prompt;
import dev.langchain4j.model.input.PromptTemplate;
import dev.langchain4j.model.ollama.OllamaChatModel;
import java.time.Clock;
import java.time.Instant;
import java.time.ZoneId;
import java.util.Map;
public class NamedClockTemplateExample {
public static void main(String[] args) {
// 1. Setup Ollama with Phi-3
ChatModel model = OllamaChatModel.builder()
.baseUrl("http://localhost:11434")
.modelName("phi3:mini-128k")
.numCtx(4096)
.temperature(0.7)
.build();
// 2. Define a template that uses automatic date variables
// The name "daily-task-assistant" helps you identify this template in logs
String template = "Current Date: {{current_date}}. \n" +
"Task: Write a short to-do list for a {{user_role}}.";
String templateName = "daily-task-assistant";
// 3. Use the specific method: from(template, name, clock)
// We'll use a fixed clock here to demonstrate how to control 'current_date'
Clock fixedClock = Clock.fixed(Instant.parse("2026-01-18T10:00:00Z"), ZoneId.of("UTC"));
PromptTemplate promptTemplate =
PromptTemplate.from(template, templateName, fixedClock);
// 4. Apply the template
// Notice we only provide 'user_role'. 'current_date' is handled by the Clock.
Prompt prompt = promptTemplate.apply(Map.of("user_role",
"Software Engineer"));
// 5. Execute with Phi-3
String response = model.chat(prompt.text());
System.out.println("-- Prompt (Named: " + templateName + ") --");
System.out.println(prompt.text());
System.out.println("\n-- Phi-3 Response --");
System.out.println(response);
}
}
Output-- Prompt (Named: daily-task-assistant) -- Current Date: 2026-01-18. Task: Write a short to-do list for a Software Engineer.
-- Phi-3 Response -- Software Engineering To-Do List - January 18, 2026
1. Review the current project status and update progress report by EOD today. 2. Attend daily standup meeting with team at 9:30 AM tomorrow morning to discuss tasks for next day. 3. Code review of latest pull request on Tuesday, provide feedback before end-of-the-day deadline (by midnight). 4. Research and propose new software architecture improvements by Wednesday afternoon meeting with the team leader. 5. Schedule client meetings for presenting project updates next week - allocate 30 minutes per day over three days starting Thursday morning at 10:0in AM. 6. Check in-house test suites and ensure they are up to date by Friday before beginning testing activities; run all tests on the latest codebase after fixing identified bugs. 7. Organize a short coding workshop for junior engineers this weekend with relevant mentors - discuss best practices, design patterns, etc., from 2 PM-4PM at office conference room Saturday afternoon. 8. Plan and prioritize tasks list based on the client's feedback received yesterday; update project roadmap accordingly by Monday morning before team meeting (at 10 AM). 9. Spend an hour after work for personal development - read latest industry articles, watch relevant webinars or tutorials to stay updated with technology trends and skills enhancement during lunchtime at home tomorrow afternoon. 10. Complete all assigned tasks by the end of next week; submit a comprehensive progress report on Friday morning before leaving office for long-weekend break starting Saturday noon until Monday evening (without fail).
Conclusion
The output from our examples demonstrates how PromptTemplate effectively replaces placeholders with actual values to create meaningful prompts. This confirms that PromptTemplate successfully separates prompt structure from content, allowing for reusable and maintainable AI interactions.
Example ProjectDependencies and Technologies Used: - langchain4j 1.10.0 (Build LLM-powered applications in Java: chatbots, agents, RAG, and much more)
- langchain4j-ollama 1.10.0 (LangChain4j :: Integration :: Ollama)
- JDK 17
- Maven 3.9.11
|