AI / LangChain4j interview questions
What is the PromptTemplate in LangChain4j and how does it differ from @UserMessage?
PromptTemplate is the lower-level prompt construction API in LangChain4j, used when you are working directly with ChatLanguageModel or building custom chains without the AI Services abstraction. It lets you define a reusable template string with {{variable}} placeholders and fill them in programmatically at runtime.
PromptTemplate template = PromptTemplate.from( "You are translating from English to {{language}}. Translate: {{text}}" ); Prompt prompt = template.apply(Map.of( "language", "French", "text", "The quick brown fox jumps over the lazy dog" )); // Generates a Prompt object containing the filled-in text String result = chatModel.generate(prompt.toUserMessage()) .content().text();
The key difference from @UserMessage is the level of abstraction and who drives the execution:
| Aspect | PromptTemplate | @UserMessage |
|---|---|---|
| Usage context | Direct ChatLanguageModel calls, custom chains | AI Services interface methods only |
| Variable injection | Manual Map.of(...) call | Automatic from method parameters |
| Code required | Template creation, apply(), generate() | Just annotation — no code |
| Best for | Dynamic, programmatically constructed prompts | Declarative, fixed-structure interactions |
Use PromptTemplate when you need to dynamically compose different prompt templates at runtime, when you are building low-level chains, or when the fixed annotation approach of AI Services is too rigid for a particular use case.
More Related questions...