Build a Content Moderation Pipeline with the Claude API
What this guide covers
If you're searching for how to build a content moderation pipeline on the Claude API, you're probably trying to classify user-generated text (comments, chat messages, listings, reviews) for policy violations — and you want a system that's accurate, fast, and doesn't require training a custom model. Claude handles this well because it can reason about context and nuance (sarcasm, implied threats, coded language) that keyword filters and small classifiers miss.
The short answer: send each piece of content to Claude with a structured classification prompt, force a JSON response with categories and severity, then route the result through rule-based logic (auto-allow, auto-block, or human review). Below is a full working setup, including how to handle scale, cost, and edge cases.
Pipeline architecture
A production moderation pipeline has four stages:
- Pre-filter — cheap regex/keyword checks to catch obvious spam or blocked terms before spending an API call.
- Classification — Claude scores the content against your policy categories.
- Decision logic — deterministic rules map Claude's output to an action.
- Audit trail — log every decision with the model's reasoning for appeals and policy tuning.
Only stage 2 needs the LLM. Keep stages 1, 3, and 4 in your own backend — don't ask Claude to "decide" anything outside of classification; let your code own the business logic.
Writing the classification prompt
The key to a reliable moderation pipeline is forcing structured output. Don't ask Claude to "flag anything bad" in free text — give it explicit categories and require JSON.
const SYSTEM_PROMPT = `You are a content moderation classifier. Analyze the user content and return ONLY valid JSON matching this schema:
{
"categories": {
"harassment": boolean,
"hate_speech": boolean,
"sexual_content": boolean,
"violence": boolean,
"spam": boolean,
"self_harm": boolean
},
"severity": "none" | "low" | "medium" | "high",
"confidence": number,
"reasoning": string
}
Rules:
- "severity" reflects the worst violated category.
- "confidence" is 0-1, your certainty in this classification.
- "reasoning" is one short sentence, no more.
- Do not include markdown, backticks, or any text outside the JSON object.`;
async function classifyContent(text) {
const res = await fetch("https://api.subtoapi.app/v1/messages", {
method: "POST",
headers: {
"Authorization": `Bearer ${process.env.SUBTOAPI_KEY}`,
"Content-Type": "application/json",
},
body: JSON.stringify({
model: "claude-sonnet-4",
max_tokens: 300,
system: SYSTEM_PROMPT,
messages: [{ role: "user", content: text }],
}),
});
const data = await res.json();
return JSON.parse(data.content[0].text);
}
This runs through SubToAPI's Messages endpoint, which gives you the same request/response shape as the native Claude API, so if you're already prototyping against Anthropic's SDK, swapping the base URL and key is the only change needed.
Decision logic: don't let the model make the final call
Treat Claude's output as a signal, not a verdict. Your backend should apply deterministic thresholds:
function decide(classification) {
const { severity, confidence, categories } = classification;
if (severity === "high" && confidence > 0.7) {
return "auto_block";
}
if (severity === "medium" || (severity === "high" && confidence <= 0.7)) {
return "human_review";
}
if (categories.self_harm) {
// always escalate regardless of severity score
return "human_review_priority";
}
return "allow";
}
This separation matters for two reasons: it keeps your moderation policy auditable (you can change thresholds without changing prompts), and it protects you from a single bad model response taking an irreversible action on borderline content.
Handling scale without burning budget
Running every message through a full LLM call is expensive at volume. A few practical optimizations:
- Batch low-risk content. Group multiple short items (comments, usernames) into one request with clear delimiters and ask for an array of classifications back. This cuts request overhead significantly.
- Cache repeated content. User bios, product descriptions, and other reused text don't need re-classification on every view — hash the content and cache the decision.
- Use a cheaper model for the first pass. Run Haiku-tier classification first; only escalate ambiguous or high-severity results to Sonnet for a second opinion.
- Stream for long documents. If you're moderating long-form content (articles, long reviews), use streaming so you can start processing partial results instead of waiting for the full generation on large inputs.
curl https://api.subtoapi.app/v1/messages \
-H "Authorization: Bearer $SUBTOAPI_KEY" \
-H "Content-Type: application/json" \
-d '{
"model": "claude-haiku-4",
"max_tokens": 200,
"system": "Classify for policy violations. Return JSON only.",
"messages": [{"role": "user", "content": "Batch: [1] comment text... [2] comment text..."}]
}'
Why route moderation traffic through an API layer
Moderation pipelines generate high request volume with tight latency requirements, so visibility into usage matters more than in a typical integration. SubToAPI gives every application its own sub_live_ key, so you can isolate your moderation service from other Claude-powered features in your product, see per-service token usage and spend in one dashboard, and add team seats on the Team or Scale plans without sharing a single raw credential across engineers. Start with the free trial at /signup, check /pricing for the plan that matches your request volume, and follow the quickstart to get your first classification call running in minutes.
Logging and appeals
Store the full classification JSON — not just the final action — alongside a content hash, timestamp, and model version. When a user appeals a block, you need the original reasoning to decide whether the call was correct, and you'll want this data later to tune your severity thresholds or system prompt. Treat prompt changes like code changes: version them, and re-run a labeled test set before shipping updates to the classifier.
Testing before production
Build a labeled dataset of 100-200 examples covering your actual policy edge cases (not generic toxicity examples) before launch. Run it through the pipeline, compare against your expected labels, and tune the system prompt and thresholds until false-positive and false-negative rates are acceptable for your risk tolerance. Re-run this test set whenever you change the model version or prompt — moderation accuracy can shift between model updates in ways that aren't obvious from spot-checking.
Questions
Can Claude replace a dedicated moderation API entirely? For most text use cases, yes — it handles nuance better than keyword filters. For image/video moderation or extremely high-volume low-latency use (ad-bidding-level speed), pair it with a specialized classifier as a pre-filter.
How do I stop users from bypassing moderation with prompt injection? Never let user content modify your system prompt. Keep the classification instructions in system and the user content strictly in the messages array — Claude won't follow instructions embedded inside content it's classifying.
What happens if the model returns malformed JSON? Wrap the parse in a try/catch and default to human_review on failure rather than allow. Malformed output should fail safe, not open.