Sub topic 8
Classifier and Moderation Models
Rule-based checks are fast and predictable, but they only catch what you wrote a rule for. This chapter covers the next step up: small models trained to label text. It assumes you have read the earlier chapters on guardrail placement and deterministic checks. You should be comfortable with Python and with calling a model through an API.
What a classifier guardrail is
A classifier is a model that reads text and returns a label, usually with a confidence score. A moderation model is a classifier trained on harm categories such as hate, harassment, self-harm, sexual content and violence. Both run as a separate step in your pipeline. They are not the main model that writes the answer.
Compared with a regex, a classifier can recognise meaning. A regex for "ignore previous instructions" misses "disregard everything you were told earlier". A classifier trained on injection examples often catches both. The cost is that its decisions are probabilistic and harder to explain.
| Property | Rule-based check | Classifier model | LLM judge |
|---|---|---|---|
| Handles paraphrase | Poorly | Well | Very well |
| Latency | Microseconds | Milliseconds to tens of ms | Hundreds of ms to seconds |
| Cost per call | Near zero | Low | Highest |
| Predictable | Fully | Mostly | Least |
| Needs training data | No | Yes, or use a hosted one | No, needs a prompt |
Where classifiers fit
You can run a classifier at either checkpoint. On the input side it screens user messages for toxicity, injection attempts or off-topic requests. On the output side it screens the model's reply for harmful content before the user sees it.
Running cheap rules first is deliberate. If a length limit or a PII pattern already rejects the request, you never pay for the classifier call.
Types of classifiers you will meet
- Moderation endpoints. Hosted APIs return per-category flags and scores for a piece of text. You send text and receive a result. You do not manage the model.
- Open-source safety models. You run them yourself. Examples include toxicity classifiers and safety-tuned models that take a conversation and return "safe" or "unsafe" with a category code. Self-hosting keeps data in your environment and avoids per-call fees.
- Custom classifiers. You train a small model on your own labelled examples. This fits domain-specific rules such as "is this message a billing question?" or "does this reply give legal advice?".
- Managed guardrail services. Cloud providers offer configurable filters for content categories, denied topics and PII, applied around a model call. They reduce setup work but limit how much you can tune.
Scores, thresholds and categories
Most classifiers return a score between 0 and 1 for each category, not just a yes or no. You choose the threshold that turns a score into a decision. The threshold is the most important setting you control.
- A low threshold blocks more content. You catch more harmful text (fewer false negatives) but block more legitimate text (more false positives).
- A high threshold blocks less. Users are interrupted less often, but more harmful text gets through.
Scores from different models are not comparable. A score of 0.7 from one model may mean something quite different from 0.7 from another, because models are calibrated differently. Always pick a threshold by measuring on your own data, as a later chapter on evaluation describes.
Use per-category thresholds when the risks differ. A children's education app might block "violence" at 0.3, while a crime-fiction writing tool might allow it up to 0.9 but keep "self-harm" strict.
A runnable example
The code below wraps any classifier behind a small interface. It uses a stand-in classifier so the example runs without a network call. In production you would replace keyword_classifier with a call to a moderation API or a local model.
from dataclasses import dataclass
@dataclass
class Verdict:
allowed: bool
category: str = ""
score: float = 0.0
# Per-category thresholds: a score at or above the value blocks the text.
THRESHOLDS = {"harassment": 0.5, "self_harm": 0.3, "violence": 0.7}
def keyword_classifier(text: str) -> dict:
"""Stand-in for a real model. Returns a score per category."""
lowered = text.lower()
return {
"harassment": 0.9 if "idiot" in lowered else 0.05,
"self_harm": 0.8 if "hurt myself" in lowered else 0.02,
"violence": 0.85 if "attack" in lowered else 0.03,
}
def moderate(text: str, classify=keyword_classifier) -> Verdict:
scores = classify(text)
worst = max(scores, key=scores.get)
for category, score in scores.items():
if score >= THRESHOLDS[category]:
return Verdict(False, category, score)
return Verdict(True, worst, scores[worst])
for message in ["How do I reset my password?", "You are an idiot"]:
print(message, "->", moderate(message))The first message is allowed. The second is blocked in the harassment category with a score of 0.9. Passing classify as a parameter lets you swap in a real model or a test double without changing the decision logic.
Choosing a classifier
Work through these questions in order.
- Is the risk well defined by patterns? If yes, use a rule. A US Social Security number format does not need a model.
- Is it a common, well-studied category? Toxicity, hate and sexual content are covered by existing moderation models. Start with a hosted or open-source one before training your own.
- Is it specific to your product? Train or fine-tune a small classifier, or write a clear prompt for an LLM judge, which the next chapter covers.
- What is the latency budget? A chat interface that streams tokens may only tolerate a few tens of milliseconds for an input check. A batch pipeline can afford more.
- Can the text leave your environment? If not, self-host.
Common errors
Treating the score as a probability of harm. A score of 0.8 does not mean an 80% chance the text is harmful. It is a model-specific number. Measure real error rates at your chosen threshold.
Ignoring language and context. Many moderation models perform best on English. They can miss harm in other languages, in slang, or when words are deliberately misspelled. Test on the languages your users write in.
Classifying only the last message. In a conversation, a single message may look harmless while the whole exchange is not. Pass enough context for the classifier to judge, within its input limit.
Over-blocking sensitive but legitimate content. A medical assistant must discuss self-harm risk factors. A moderation model may flag those messages. Use per-category thresholds, and consider routing flagged messages to a specialised response rather than a flat refusal.
Forgetting that classifiers can be attacked. Adversarial input, such as unusual Unicode, spacing tricks or text in an encoded form, can lower a classifier's score. Normalise text first (for example, Unicode normalisation and removing zero-width characters) before classifying.
Truncated input. Classifiers have a maximum input length. If a long message is cut off, harmful text after the cut is never seen. Either split long text into chunks and classify each, or reject text over the limit with a rule-based check.
import unicodedata
ZERO_WIDTH = dict.fromkeys(map(ord, "\u200b\u200c\u200d\u2060\ufeff"))
def normalise(text: str) -> str:
text = unicodedata.normalize("NFKC", text)
return text.translate(ZERO_WIDTH)
def chunks(text: str, size: int = 1000):
for start in range(0, len(text), size):
yield text[start:start + size]
def moderate_long(text: str, classify) -> bool:
"""Return True if every chunk passes. classify takes a string and returns a bool: True means safe."""
clean = normalise(text)
return all(classify(part) for part in chunks(clean))
print(moderate_long("hello\u200b world", lambda t: "idiot" not in t))Fixed-size chunks can split a harmful phrase across a boundary. Overlapping chunks reduce that risk at the price of more calls.
Handling the result
A blocked classification does not always mean a hard refusal. Match the action to the category and score:
- A very high score on a severe category: block and log.
- A borderline score: allow but flag for review, or ask the model to answer more cautiously.
- A custom topic classifier that says "off-topic": redirect the user to what the assistant can help with.
The next chapters cover failure handling in more detail. For now, record the category, score and threshold with every decision. You will need that record to tune thresholds later.
Limits
A classifier is a trained model, so it makes mistakes in both directions. It reflects the data it was trained on, and it can degrade when user behaviour shifts. It also adds a dependency: if the moderation service is down, you must decide whether to fail open (allow traffic) or fail closed (block it). Low-risk apps may fail open. Apps with serious harm potential should fail closed.
Exercise
Your moderation model returns a "violence" score of 0.6 for a message in a crime-fiction writing tool. The global threshold is 0.5, and many legitimate users are being blocked. Name two changes you could make, and say what risk each one introduces.
Show answer
First, raise the threshold for the "violence" category only, for example to 0.85, since this product expects violent themes. The risk is that genuinely threatening content scoring between 0.5 and 0.85 now passes, so keep stricter thresholds on other categories such as self-harm. Second, route scores in the borderline range to review or to a more careful response instead of blocking outright. The risk is added latency, cost or reviewer workload. In both cases, measure the false positive and false negative rates on labelled examples from your own users before and after the change.
Exercise
A user pastes a 20,000-character message into a classifier with a 2,000-character input limit, and the classifier only sees the first part. What failure does this create, and how do you prevent it?
Show answer
Harmful text after the cutoff is never classified, so it passes as if it were safe (a false negative). Prevent it by rejecting over-long input with a length rule, or by splitting the text into chunks, ideally overlapping, and classifying every chunk. Allow the message only if all chunks pass.