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.
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...
