AI / LangChain4j interview questions
What is the ModerationModel interface in LangChain4j and how can you implement a custom one?
The ModerationModel interface in LangChain4j defines the contract for content moderation checks. It takes a String input and returns a Response<Moderation> — where Moderation contains a boolean flagged() result and optionally category-level scores. LangChain4j's @Moderate AI Services annotation uses whichever ModerationModel you register on the builder.
The built-in implementation is OpenAiModerationModel, which calls OpenAI's text-moderation-latest API. But for custom moderation logic — rule-based keyword filtering, an internal ML model, or a different provider's moderation API — you implement the interface directly:
public class KeywordModerationModel implements ModerationModel { private static final Set<String> BLOCKED = Set.of( "badword1", "badword2", "competitor-brand" ); @Override public Response<Moderation> moderate(String text) { boolean flagged = BLOCKED.stream() .anyMatch(word -> text.toLowerCase().contains(word)); return Response.from( flagged ? Moderation.flagged(text) : Moderation.notFlagged() ); } } // Plug in as the moderation model SafeAssistant assistant = AiServices.builder(SafeAssistant.class) .chatLanguageModel(chatModel) .moderationModel(new KeywordModerationModel()) .build();
Custom implementations are particularly useful for on-premise deployments that cannot use external APIs, for organizations with specific terminology blocklists, or for domain-specific moderation where generic toxicity models produce too many false positives. The interface is small and straightforward — moderate(String) is the only method you must implement.
More Related questions...