AI / LangChain4j interview questions
What is the @Moderate annotation in LangChain4j and how does content moderation work?
The @Moderate annotation integrates content moderation directly into the AI Services pipeline. When placed on an AI Services method, LangChain4j automatically runs the user message through OpenAI's Moderation API before passing it to the language model. If the content is flagged as violating content policies, a ModerationException is thrown before the LLM is ever called — protecting you from sending inappropriate content upstream and from generating harmful responses.
interface SafeAssistant { @Moderate // automatic moderation check on every call @SystemMessage("You are a helpful customer service assistant.") String chat(String userMessage); } // Build with a moderation model configured SafeAssistant assistant = AiServices.builder(SafeAssistant.class) .chatLanguageModel(chatModel) .moderationModel(OpenAiModerationModel.builder() .apiKey(apiKey) .build()) .build(); // Usage try { String response = assistant.chat(userInput); } catch (ModerationException e) { // Input was flagged â respond with a rejection message return "I cannot process that request."; }
The moderation check happens before the main LLM call, which means: no tokens wasted on the primary model, no risk of the LLM processing harmful prompts, and your system gets an automatic first line of defense. The moderation model (currently only OpenAI's text-moderation-latest is supported natively) returns categories and confidence scores for hate, harassment, self-harm, violence, and sexual content.
For applications where OpenAI's moderation is not suitable (on-premise deployments, or different moderation criteria), you can implement the ModerationModel interface with custom logic and plug it in identically.
More Related questions...