Sub topic 8
Classifier and moderation models
This chapter assumes you can write basic Python, call an LLM through an SDK, and read JSON. It also assumes you know the deterministic checks from the earlier chapters: length limits, regular expressions and allowlists.
When rules are not enough
A regular expression can find an email address. It cannot tell whether a message is hateful, whether a user is trying to get around your system prompt, or whether a reply gives self-harm instructions. These risks depend on meaning, and the same idea can be written in many different ways.
A classifier is a small model that reads text and returns a label with a score. A moderation model is a classifier trained on harm categories such as hate, violence, sexual content and self-harm. Both are cheaper and faster than a full LLM call, and they give the same score for the same text on every run.
How a classifier check works
The classifier sits at the same checkpoints as your rules. It can read the user's input before the model call, or the model's output after it. It returns a score per category. Your code then compares each score with a threshold and decides what to do.
A minimal example
The function below wraps any classifier that takes a string and returns a dictionary of category scores. In practice that could be a hosted moderation endpoint or a model you run yourself. The stub at the bottom lets you run the code without one.
THRESHOLDS = {"hate": 0.7, "violence": 0.7, "self_harm": 0.3}
def moderate(text: str, classify) -> tuple[bool, str]:
scores = classify(text)
for category, limit in THRESHOLDS.items():
if scores.get(category, 0.0) >= limit:
return False, category
return True, ""
def fake_classify(text: str) -> dict:
# Stand-in for a real model, for demonstration only.
if "hurt myself" in text.lower():
return {"self_harm": 0.92}
return {"hate": 0.01, "violence": 0.02, "self_harm": 0.01}
print(moderate("What is the weather today?", fake_classify))
print(moderate("I want to hurt myself", fake_classify))
# (True, '')
# (False, 'self_harm')Each category has its own threshold. Here self-harm uses a low threshold of 0.3, so the check catches more cases at the cost of more false alarms. Choose thresholds by how bad a miss is for that category, not by one global number.
Choosing a classifier
| Option | Strength | Weakness |
|---|---|---|
| Hosted moderation API | No setup, maintained by the provider | Fixed categories, data leaves your system |
| Open-source classifier | Runs in your environment, can be fine-tuned | You host, update and monitor it |
| Custom classifier | Matches your own policy | Needs labeled examples |
Use a hosted API when your risks match its standard categories. Train or fine-tune your own when your policy is specific, for example "no medical dosage advice".
Common errors
- One threshold for everything. Categories differ in risk and in how noisy their scores are. Tune each one.
- Checking only the input. A safe prompt can still produce an unsafe reply, so check the output too.
- Trusting scores as probabilities. A score of 0.9 does not mean a 90% chance of harm. Calibrate against labeled examples from your own traffic.
- Ignoring language and context. Many classifiers work best on English and can miss slang, other languages, or text hidden in encodings.
- No handling for classifier failure. If the classifier times out, decide in advance whether to fail open or fail closed.
Exercise
Your app flags 30% of harmless messages as violent with a single threshold of 0.4. Missing real threats is costly, but the false alarms are driving users away. What do you check and change first?
Show answer
Measure the false positive and false negative rates on labeled samples of your own traffic at several thresholds for the violence category. Raise the threshold until false positives fall to an acceptable level while misses stay tolerable. Where a miss is costly, send borderline scores (for example 0.4 to 0.7) to human review or a second check instead of blocking outright.