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.
Invest now in Acorns!!! 🚀
Join Acorns and get your $5 bonus!
Acorns is a micro-investing app that automatically invests your "spare change" from daily purchases into diversified, expert-built portfolios of ETFs. It is designed for beginners, allowing you to start investing with as little as $5. The service automates saving and investing. Disclosure: I may receive a referral bonus.
Invest now!!! Get Free equity stock (US, UK only)!
Use Robinhood app to invest in stocks. It is safe and secure. Use the Referral link to claim your free stock when you sign up!.
The Robinhood app makes it easy to trade stocks, crypto and more.
Webull! Receive free stock by signing up using the link: Webull signup.
More Related questions...
