← Blog

Claude API Content Moderation Pipeline Tutorial

2026-11-18 · 5 min read · SubToAPI Team

If you're searching for a Claude API content moderation pipeline tutorial, you're probably trying to decide between Anthropic's own moderation guidance, a dedicated moderation model, or building something custom on top of Claude's general reasoning. This article walks through a practical, production-ready pipeline: how to structure the moderation prompt, how to parse structured output reliably, how to handle edge cases like borderline content, and how to wire it into a queue so it scales without blowing your latency budget.

The short answer: you don't need a separate moderation model. Claude is capable of structured content classification out of the box if you give it a tight prompt, a fixed taxonomy, and force JSON output. The harder part is the surrounding pipeline — retries, confidence thresholds, human review escalation, and logging — which is what most tutorials skip.

Why build moderation on Claude instead of a dedicated API

Dedicated moderation endpoints are fast and cheap but rigid — fixed categories, no context awareness, no ability to explain a decision. Claude gives you:

The tradeoff is latency and cost per call, which is why the pipeline design matters more than the prompt itself.

Step 1: Define a fixed taxonomy and output schema

Don't let the model free-text its verdict. Force a schema so downstream code never has to parse prose.

{
  "flagged": true,
  "categories": ["harassment", "spam"],
  "severity": "medium",
  "confidence": 0.82,
  "reason": "Short explanation for logging/appeals"
}

Lock the category list in the prompt itself — don't let the model invent new ones.

Step 2: Write the moderation prompt

Keep the system prompt deterministic and narrow. Give explicit category definitions, not just names.

const SYSTEM_PROMPT = `You are a content moderation classifier. Analyze the user-submitted text and return ONLY valid JSON matching this schema:

{
  "flagged": boolean,
  "categories": string[],   // subset of: harassment, hate_speech, self_harm, sexual_content, spam, pii, violence
  "severity": "low" | "medium" | "high",
  "confidence": number,     // 0 to 1
  "reason": string
}

Rules:
- "flagged" is true if ANY category applies with medium or high severity.
- Low severity, ambiguous content should still be returned with flagged: false but categories listed if relevant.
- Never include categories outside the fixed list.
- Do not add commentary outside the JSON object.`;

Step 3: Call the API and parse defensively

Even with a strict schema, treat the response as untrusted input. Validate it before using it.

async function moderateText(text) {
  const response = 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 response.json();
  const raw = data.content[0].text;

  let parsed;
  try {
    parsed = JSON.parse(raw);
  } catch {
    // Fall back to manual review if the model didn't return clean JSON
    return { flagged: true, categories: ["unparseable"], severity: "high", confidence: 0, reason: "parse_error" };
  }

  return parsed;
}

Using a hosted endpoint like this means you get a single sub_live_ key, built-in streaming and usage metadata without managing separate credentials per environment — see the quickstart for setup.

Step 4: Build the escalation logic

The classifier output alone isn't a decision — it's an input to your business rules. A typical escalation ladder:

function decide(moderation) {
  if (!moderation.flagged) return "allow";

  if (moderation.severity === "high" && moderation.confidence > 0.8) {
    return "block";
  }

  if (moderation.severity === "medium" || moderation.confidence < 0.6) {
    return "queue_for_human_review";
  }

  return "allow_with_warning";
}

This separation matters: the model's job is classification, not policy. Keep severity thresholds in code so you can tune them without touching the prompt or re-deploying.

Step 5: Handle scale without blowing your latency budget

Moderation often runs inline (before publishing a comment) or async (batch-reviewing uploaded content). For inline use:

For async/batch pipelines, queue submissions and process in parallel batches with retry/backoff:

async function moderateBatch(items, concurrency = 5) {
  const results = [];
  for (let i = 0; i < items.length; i += concurrency) {
    const chunk = items.slice(i, i + concurrency);
    const chunkResults = await Promise.all(chunk.map(item => moderateText(item.text)));
    results.push(...chunkResults);
  }
  return results;
}

If you're running this across multiple services or client apps, routing calls through SubToAPI gives you per-app API keys and usage metadata so you can see exactly which service is generating moderation traffic and at what volume — useful when a single "comments" feature turns into five internal tools all calling the same classifier. Pricing starts at €9/month on the Solo plan, with Team and Scale tiers for shared seats.

Step 6: Log everything for appeals and tuning

Store the raw model output, the final decision, and the input hash (not necessarily the raw text, depending on your data retention policy) for every moderation call. This is what lets you:

For teams building this on top of a hosted gateway, check the messages docs for request/response shapes and streaming docs if you want partial moderation feedback on long-form content as it's generated.

Putting it together

A minimal but solid pipeline looks like: inbound text → fast first-pass classification → rule-based decision → either allow, block, or queue for human review → log the full trace. Start simple, measure your flagged rate and false-positive rate on real traffic, and only add complexity (multi-model escalation, caching, batch processing) once you know where the bottleneck actually is.

questions

Does Claude have a built-in moderation endpoint like OpenAI's moderation API? No. Claude doesn't ship a dedicated moderation endpoint — you build classification using the standard messages API with a structured prompt, as shown above.

Should moderation run before or after content is published? For high-risk categories (harassment, self-harm, hate speech), moderate before publishing (inline). For lower-risk content like general spam detection, async post-publish review is usually fast enough and cheaper.

How do I avoid the model inventing new categories? Explicitly list the fixed taxonomy in the system prompt and validate the returned JSON against that list in code — reject or flag for review any response containing categories outside it.

Turn your Claude access into an HTTPS API

SubToAPI gives you application API keys, streaming, tool use and usage insights on top of your existing Claude access — set up in minutes.

Start free  Read the quickstart →