AI / LangChain4j interview questions
What is the @SystemMessage and @UserMessage annotation in LangChain4j AI Services?
@SystemMessage and @UserMessage are the two prompt-definition annotations at the core of LangChain4j's AI Services pattern. Together they define what gets sent to the LLM for each method invocation, replacing all manual prompt string assembly.
@SystemMessage defines the system prompt — the persona, context, constraints, and behavioral instructions that frame the entire conversation. It is sent as the role: system message in the API request. It can be a plain string literal, or point to a classpath resource file for longer prompts.
@UserMessage defines the user turn — what gets sent as the role: user message. Method parameters are injected into the template via {{paramName}} placeholders or can be injected automatically when there is only one String parameter. If @UserMessage is omitted, the first String parameter is used as the user message verbatim.
interface Translator { @SystemMessage("You are a professional translator. Translate precisely without adding commentary.") @UserMessage("Translate the following text to {{targetLanguage}}: {{text}}") String translate(String text, @V("targetLanguage") String lang); } // Or loading from a classpath template file: interface LegalReviewer { @SystemMessage(fromResource = "prompts/legal-reviewer-system.txt") @UserMessage("Review this contract clause: {{clause}}") ReviewResult review(String clause); }
The @V annotation explicitly names a variable for injection when the parameter name differs or when there are multiple parameters. Without @V, LangChain4j uses the Java parameter name (requires compilation with -parameters flag, or the @Param annotation).
More Related questions...