Content Moderation
Build scalable content moderation pipelines using cloud APIs, open-source models, and custom classifiers to ensure LLM outputs meet your safety standards.
Moderation API Comparison
| Service | Categories | Latency | Cost |
|---|---|---|---|
| OpenAI Moderation | Violence, sexual, hate, self-harm, harassment | ~100ms | Free with API |
| Perspective API | Toxicity, insult, profanity, identity attack, threat | ~200ms | Free tier available |
| Azure Content Safety | Hate, sexual, violence, self-harm (severity levels) | ~150ms | Pay per request |
| AWS Comprehend | Sentiment, PII, toxicity, targeted sentiment | ~300ms | Pay per character |
Using the OpenAI Moderation API
from openai import OpenAI client = OpenAI() def moderate_output(text: str) -> dict: """Check LLM output against OpenAI moderation.""" response = client.moderations.create(input=text) result = response.results[0] if result.flagged: # Identify which categories were flagged flagged_categories = [ cat for cat, flagged in result.categories.model_dump().items() if flagged ] return { "safe": False, "categories": flagged_categories, "scores": result.category_scores.model_dump() } return {"safe": True}
Custom Toxicity Classifiers
When commercial APIs do not cover your specific needs, build custom classifiers:
from transformers import pipeline class CustomModerator: def __init__(self): self.toxicity = pipeline( "text-classification", model="unitary/toxic-bert" ) self.threshold = 0.7 def check(self, text: str) -> dict: # Split long text into chunks for classification chunks = [text[i:i+512] for i in range(0, len(text), 512)] max_score = 0 for chunk in chunks: result = self.toxicity(chunk)[0] if result["label"] == "toxic": max_score = max(max_score, result["score"]) return { "toxic": max_score > self.threshold, "score": max_score }
Building a Moderation Pipeline
Layer 1: Fast Filters
Regex PII detection and keyword blocklists run first. Under 5ms. Catches obvious violations without external API calls.
Layer 2: Local ML Models
On-device toxicity and topic classifiers. 10-50ms. No external dependency. Good for basic content safety.
Layer 3: Cloud APIs
OpenAI Moderation, Perspective API for comprehensive coverage. 100-300ms. Use for outputs that pass local checks but need deeper analysis.
Layer 4: Human Review
Escalate edge cases and high-risk content to human moderators. Minutes to hours. Reserve for ambiguous cases and policy development.
Ready to Go Deeper?
Live instructor-led courses from our partners. Affiliate disclosure.
AI & ML Courses - 30% Off
Live instructor-led AI, machine learning, data science, and cloud courses for working professionals. Use code Limited30 at checkout.
EdurekaDataCamp - AI & Data Science
Hands-on Python, machine learning, and AI courses with interactive exercises and real projects.
DataCampedX - Top AI Courses
University-level AI courses from MIT, Harvard, Stanford. Earn certificates that employers recognize.
edX