Intermediate

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

ServiceCategoriesLatencyCost
OpenAI ModerationViolence, sexual, hate, self-harm, harassment~100msFree with API
Perspective APIToxicity, insult, profanity, identity attack, threat~200msFree tier available
Azure Content SafetyHate, sexual, violence, self-harm (severity levels)~150msPay per request
AWS ComprehendSentiment, PII, toxicity, targeted sentiment~300msPay per character

Using the OpenAI Moderation API

Python - OpenAI Moderation
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:

Python - Custom Toxicity Classifier
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.

Performance optimization: Run layers in sequence and short-circuit early. If Layer 1 blocks the output, skip Layers 2-4. This keeps average latency low while maintaining comprehensive coverage for edge cases.

Ready to Go Deeper?

Live instructor-led courses from our partners. Affiliate disclosure.