Automated content moderation is a classification problem wearing a trust-and-safety costume. The hard part is rarely the model call itself. It is deciding what your policy actually says, keeping latency low enough to sit inside a request path, and making sure that when the classifier is wrong the blast radius is a queued review item rather than a wrongful ban. This guide builds that pipeline with the DeepSeek API for automated content moderation, using code you can run today.
Two properties of DeepSeek models make them a good fit here. Chat completions are cheap enough to run on every comment rather than a sample of them, and the API is OpenAI-compatible, so existing SDK code drops in with two changed lines. The models also follow long policy instructions in the system prompt without drifting, which matters because your rulebook is the actual product.
Define the Policy Before You Write a Prompt
A moderation prompt is only as good as the taxonomy behind it. Vague categories such as harmful content push the model into guessing, and guessing produces the two failure modes that hurt most: false positives that silence legitimate users, and false negatives that let genuinely dangerous material through.
Write the policy as a short dictionary of categories, each with a one-line operational definition. Describe what the content does, not how it makes you feel about it.
Zero-tolerance categories, such as sexual content involving minors, should be binary and never probabilistic.
Context-dependent categories such as harassment and violence need an evidence requirement, so the model must quote the span it is acting on.
Spam and scam categories should mention evasion patterns: leetspeak, homoglyphs, split links, and obfuscated contact details.
Always include a benign bucket and an explicit review action so the model has a legitimate way to say not sure instead of forcing a label.
A Runnable Moderator with Structured Output
The snippet below keeps the policy in the system prompt and forces a JSON verdict. It uses deepseek-v4-flash, the right default for a first pass over high-volume text. Note the fallback in the except block: a parse failure should degrade to human review, never to a crash and never to an automatic allow.
import json
import os
from openai import OpenAI
client = OpenAI(
api_key=os.environ['AICREDITS_API_KEY'],
base_url='https://api.aicreditsapi.com/v1',
)
POLICY = {
'harassment': 'Targeted abuse, slurs, or sustained attacks on a person or group.',
'self_harm': 'Encouraging, instructing, or celebrating self-injury or suicide.',
'sexual_minors': 'Any sexualized content involving minors. Zero tolerance.',
'violence': 'Threats of violence or instructions for causing physical harm.',
'spam': 'Deceptive promotion, scam links, bulk repetition, engagement farming.',
'benign': 'Everything that does not clearly match a category above.',
}
SYSTEM_PROMPT = f'''You are a content moderation classifier. Evaluate the text supplied by the user against this policy:
{json.dumps(POLICY, indent=2)}
Return ONLY a JSON object, with no prose and no markdown fences.
Schema: label (one of the policy categories), confidence (float between 0.0 and 1.0), evidence (a short verbatim span from the text, or an empty string), action (one of: allow, review, block).
Rules:
- confidence is your calibrated certainty in the label.
- If the text is ambiguous, or you cannot quote evidence, return label benign with action review.
- Do not moralize, apologize, or explain outside the JSON.'''
def moderate(text):
resp = client.chat.completions.create(
model='deepseek-v4-flash',
messages=[
{'role': 'system', 'content': SYSTEM_PROMPT},
{'role': 'user', 'content': text},
],
temperature=0,
response_format={'type': 'json_object'},
)
raw = resp.choices[0].message.content
try:
return json.loads(raw)
except json.JSONDecodeError:
return {'label': 'benign', 'confidence': 0.0, 'evidence': '', 'action': 'review'}
if __name__ == '__main__':
samples = [
'Thanks for sharing the dataset, this is useful.',
'You are a worthless idiot and everyone here hates you.',
]
for s in samples:
print(s[:40], '->', moderate(s))
Two design choices matter more than prompt wording. First, temperature 0 removes sampling randomness, which makes audit logs far easier to reason about, though you should treat outputs as repeatable in practice rather than bit-exact. Second, the system prompt is byte-identical on every call, which lets the provider serve it from prompt cache and keeps the effective cost weighted toward your short user text instead of the long policy block.
Route the Hard Cases Up, Not Everything
Sending every comment to the stronger model is wasteful, and sending every comment to the fast model alone will eventually embarrass you. The middle path is confidence-based routing. Let deepseek-v4-flash clear the obvious cases and hand low-confidence verdicts to deepseek-v4-pro, which reasons more carefully about nuance and contested categories. Because pro costs more than flash, the expensive calls stay proportional to genuine ambiguity rather than to total traffic.
def escalate(text):
resp = client.chat.completions.create(
model='deepseek-v4-pro',
messages=[
{'role': 'system', 'content': SYSTEM_PROMPT},
{'role': 'user', 'content': text},
],
temperature=0,
response_format={'type': 'json_object'},
)
verdict = json.loads(resp.choices[0].message.content)
verdict['escalated'] = True
return verdict
def route(text):
verdict = moderate(text)
if verdict['action'] == 'allow' or verdict['confidence'] >= 0.8:
return verdict
return escalate(text)
Set that confidence threshold empirically rather than by instinct. Label a few hundred verdicts by hand, then move the threshold until the false-positive rate on the auto-allow path sits where you want it. A threshold that feels right in a demo is usually too aggressive in production.
Batch, Cache, and Watch the Tail
Two operational wins are almost free. Cache by content hash, because spam campaigns and reposted abuse reuse the same strings and a cache hit costs nothing. Then moderate in a thread pool rather than serially when you process a backlog, with exponential backoff so a rate-limit response degrades into a retry instead of a dropped item.
import hashlib
import time
from concurrent.futures import ThreadPoolExecutor
_cache = {}
def cache_key(text):
return hashlib.sha256(text.strip().encode('utf-8')).hexdigest()
def route_cached(text):
key = cache_key(text)
if key in _cache:
return _cache[key]
for attempt in range(4):
try:
verdict = route(text)
break
except Exception:
if attempt == 3:
raise
time.sleep(2 ** attempt) # 1s, 2s, 4s backoff
_cache[key] = verdict
return verdict
def moderate_batch(texts, workers=8):
with ThreadPoolExecutor(max_workers=workers) as pool:
return list(pool.map(route_cached, texts))
Keep the original text and the raw model response. You will need both when a user appeals.
Never auto-ban on a single model verdict. Auto-allow and auto-review are safe defaults; permanent account actions deserve a human.
Track false positives per category, not just overall. One noisy category can hollow out trust in the entire system.
Do not strip links or obfuscation before classification. Pre-processing can delete the exact evidence the model needs to catch a scam.
Model Selection at a Glance
| Workload | Model | Why |
|---|---|---|
| First pass over every comment, post, or DM | deepseek-v4-flash | Fast and inexpensive enough to run on all traffic; handles clear-cut cases confidently |
| Low-confidence or contested verdicts | deepseek-v4-pro | Stronger reasoning on sarcasm, reclaimed language, and policy edge cases |
| Appeal review support | deepseek-v4-pro | Summarizes the thread and the original verdict for a human reviewer |
| Re-scoring an existing archive | deepseek-v4-flash | Volume work where caching and off-peak scheduling reduce the total |
The pattern generalizes: flash for volume, pro for judgment, and a human for consequences.
Where AiCredits Fits
If you are building this outside China, the practical blocker is usually billing rather than engineering. AiCredits serves DeepSeek API credits to international developers with payment by card or PayPal and no Chinese phone number or bank account required, so you can wire the endpoint above into your pipeline and stop thinking about procurement.
AiCredits also ships code linting tools that catch the small mistakes behind most moderation incidents: unhandled JSON parse failures, missing retry logic around network calls, and hard-coded thresholds that never get revisited. Point your client at https://api.aicreditsapi.com/v1, check current rates at aicreditsapi.com/pricing, and keep in mind that off-peak usage and cache hits both cost less than peak, uncached traffic.
Moderation is a product decision expressed as code. The model executes that decision; it should never be the one making it.
Frequently Asked Questions
Yes. The models handle multilingual input well. A reliable pattern is to instruct them to classify in English but return evidence quoted verbatim in the original language, so reviewers see the exact span that triggered the verdict.
Not guaranteed across provider-side updates. Treat it as removing sampling noise, log every verdict, and avoid assuming two identical calls will always produce identical output.
Use deepseek-v4-flash for the first pass, keep the policy prompt stable so it caches, cap the amount of user text you send, and run calls concurrently when processing batches.
Not through AiCredits. You can buy credits with a card or PayPal from anywhere and use the same OpenAI-compatible endpoint shown in the examples above.