content-moderation-patterns
Installation
Review the source and dependencies with a prompt. A package is available to download.
Install with an AI assistant
Copy the prompt so your assistant can review the pinned revision and dependencies first.
View promptHide prompt
Check whether SkillPI Skill Finder is installed for your current agent. If it is missing, install and enable it using the official instructions at https://github.com/Findskills/skillpi. Then use Skill Finder to locate and install "content-moderation-patterns" from this exact SkillPI detail page: https://skillpi.com/skills/deepskill-ed8e0a9cf7d3c68ba1de3c9d1fab48e1c06f2d22519dec12a73b586487f3fb06. Verify the upstream source and version against https://github.com/softspark/ai-toolkit before installing. If they do not match, stop and report the mismatch. Report the installed path and source version.
Source and setup
github.com
Setup guidance pending
See the original source for supported tools, dependencies, and permissions.
Installation test pending
Patterns for content moderation using Claude: contrasts pre-filtering versus LLM classification and covers category definitions, threshold settings, and human-in-the-loop (HITL) processes. Triggered by moderation requests, safety filtering, policy enforcement, or invocation of a content classifier.
Introduction source: third_party · softspark · 0.0.1 Reference
SkillPi interpretation
- Tasks
- Content moderation with Claude: pre-filter vs LLM-classify, categories, thresholds, HITL. Triggers: moderation, safety filter, policy enforcement, content classifier.
- Testing
- Not tested
Browse files
Frontmatter
name: content-moderation-patterns
description: "Content moderation with Claude: pre-filter vs LLM-classify, categories, thresholds, HITL. Triggers: moderation, safety filter, policy enforcement, content classifier."
effort: medium
user-invocable: false
allowed-tools: ReadContent Moderation Patterns
Two-stage pattern that balances cost, latency, and quality: cheap deterministic filters first, then LLM classification only on survivors.
Architecture
[ input ]
│
▼
[ pre-filter ] ── (regex, allow/block lists, length check) ──► reject early
│
▼
[ LLM classifier ] ── (Haiku, structured output) ──► categories + confidence
│
▼
[ decision router ]
├── high confidence + policy violation → reject
├── high confidence + clean → pass
└── low confidence or edge categories → human review queue
Pre-filter Stage (cheap)
Catch the obvious cases before paying an LLM call:
BANNED_PATTERNS = [
re.compile(r"\b(banned_term_1|banned_term_2)\b", re.I),
re.compile(r"\bhttps?://(?!allowed-domain\.com)", re.I), # external links
]
def pre_filter(text: str) -> tuple[bool, str]:
if len(text) > 10_000:
return False, "too_long"
for pat in BANNED_PATTERNS:
if pat.search(text):
return False, f"banned_pattern:{pat.pattern}"
return True, "pass"
Roughly 40-70% of spammy input should die here. Log counts by rule so you can tune.
LLM Classifier Stage (Haiku)
Use the smallest capable model. Haiku is usually right for moderation.
CATEGORIES = ["harassment", "self_harm", "spam", "off_topic", "pii", "clean"]
def classify(text: str) -> dict:
response = client.messages.create(
model="claude-haiku-4-5",
max_tokens=256,
tools=[{
"name": "moderate",
"description": "Classify content against policy",
"input_schema": {
"type": "object",
"properties": {
"categories": {
"type": "array",
"items": {"type": "string", "enum": CATEGORIES}
},
"confidence": {"type": "number", "minimum": 0, "maximum": 1},
"reasoning": {"type": "string", "maxLength": 200}
},
"required": ["categories", "confidence", "reasoning"]
}
}],
tool_choice={"type": "tool", "name": "moderate"},
system=POLICY_DESCRIPTION, # cached — stable across requests
messages=[{"role": "user", "content": text}]
)
return extract_tool_result(response)
Cache the policy description — it's the same on every call. See prompt-caching-patterns.
Category Design
- Start with 5-8 categories, not 50. Fewer = higher per-category accuracy.
- One
cleancategory — easier than trying to define "not bad" - No overlapping categories —
harassmentandhate_speechshould be merged or clearly separated by specific criteria in the policy doc unclear/needs_reviewcategory — gives the model a graceful escape hatch instead of forcing a wrong label
Threshold Router
def route(classification: dict) -> str:
conf = classification["confidence"]
cats = set(classification["categories"])
if "clean" in cats and conf > 0.8:
return "pass"
if cats & BLOCK_CATEGORIES and conf > 0.85:
return "reject"
if cats & BLOCK_CATEGORIES:
return "human_review"
return "human_review" # default to review on ambiguity
Thresholds belong in config, not code — they change as you learn.
Human-in-the-Loop
- All
human_reviewcases go to a queue with the model's reasoning - Human decisions flow back into a dataset used to evaluate new model versions
- Track disagreement rate between human and model — rising disagreement signals policy drift
Evaluation Loop
Build a golden set of ~500 examples per category with ground truth. Track:
- Precision per category (of what we flagged, how much was truly bad)
- Recall per category (of truly bad, how much we caught)
- False-positive cost per category — harassment FP is cheap, "clean FP" (wrongly blocking good content) is expensive
Anti-patterns
| Anti-pattern | Why it bites | Fix |
|---|---|---|
| One huge prompt asking "is this okay?" | Unstable answers, no tracking | Structured categories + confidence |
| Using Opus for moderation | 10x cost, no accuracy gain for this task | Haiku is fine |
| Hiding policy in user message | Policy gets mixed with input | Policy in system prompt, cached |
| Binary block/allow only | No signal for edge cases | Add review queue |
| No audit trail | Can't improve | Log every decision with full classification |
Related
security-patterns— input validation at system boundariesprompt-caching-patterns— cache the policy docmodel-routing-patterns— when to escalate from Haiku to Sonnet- Anthropic docs: https://docs.claude.com/en/docs/about-claude/use-case-guides/content-moderation
Rules
- MUST pre-filter the obvious cases (regex, deny-lists, length caps) before sending to an LLM — LLM moderation on a 500MB comment is unusable
- MUST return a structured JSON classification (category, confidence, reason), not a prose verdict — prose breaks audit trails
- NEVER ship a moderation pipeline without a human-in-the-loop escalation path for ambiguous cases
- NEVER hide the policy in the user message; the policy belongs in the cached system prompt so it is versioned and auditable
- CRITICAL: log every decision (input, category, confidence, model, policy version, timestamp) — moderation without an audit trail cannot be improved or appealed
- MANDATORY: calibrate confidence thresholds per category; harassment FP is cheap, clean-content FP is expensive
Gotchas
- False positives on clean content are much more expensive than false negatives on borderline content, in user-trust terms. Optimize for recall on hard-fail categories (CSAM, doxing) but precision on soft-fail categories (spam, rudeness).
- Haiku is sufficient for most moderation classification; using Opus inflates cost 10× with no measurable accuracy gain on this task. Reach for Opus only for edge cases that Haiku consistently misclassifies.
- Prompt caching on the policy doc only hits when the cache window is still warm (5 minutes). Bursty traffic with long quiet periods loses the cache every window — amortize by keeping a heartbeat call.
- Structured JSON output via tool-use is more reliable than free-form JSON in the response — parse errors happen ~1-3% of the time with free-form, near zero with tool-use schemas.
- The golden test set drifts. Policy changes, new attack patterns, and new product surfaces all invalidate old examples. Refresh quarterly or after any policy update.
When NOT to Load
- For structured JSON output design in general — use
/json-mode-patterns - For security input validation (SQLi, XSS) — use
/security-patterns - For caching the policy doc mechanics — use
/prompt-caching-patterns - For picking the model tier (Haiku vs Sonnet vs Opus) — use
/model-routing-patterns - For moderation of voice/audio content — this skill covers text; audio adds a transcription failure mode not covered here
Version history
-
v6.2.0
GitHub ↗
Original release notes
**Full Changelog**: https://github.com/softspark/ai-toolkit/compare/v6.1.0...v6.2.0
-
v6.1.0
GitHub ↗
Original release notes
**Full Changelog**: https://github.com/softspark/ai-toolkit/compare/v6.0.0...v6.1.0
-
v6.0.0
GitHub ↗
Original release notes
## What's Changed * chore: bump softprops/action-gh-release from 3.0.3 to 3.0.4 by @dependabot[bot] in https://github.com/softspark/ai-toolkit/pull/45 * fix: handle Windows status output and clarify Antigravity workflow support by @softspark in https://github.com/softspark/ai-toolkit/pull/46 **Full Changelog**: https://github.com/softspark/ai-toolkit/compare/v5.5.0...v6.0.0
-
v5.5.0
GitHub ↗
Original release notes
### Ecosystem - **OpenCode V2 and V1 compatibility:** `scripts/generate_opencode_plugin.py` emits the documented `id/setup/server` contract for V2 and V1 **1.18.29+**. Upgrade older V1 clients before using this plugin, then run `ai-toolkit update` to regenerate managed copies. `doctor` warns about obsolete V1-only exports. Scoped global/project IDs avoid native collisions; advisory work has one owner per location, while safety guards execute in every registered layer. The current V2 package is `@opencode/cli`; `opencode-ai` still publishes V1. - **Claude guard failure policy:** destructive-command, home-path and configuration guards use `onFailure: block` on Claude Code **2.1.295+**. Legacy entries migrate without duplication; hooks owned by other plugins survive. Older clients do not have this infrastructure-failure guarantee. - **Codex, Gemini and Devin:** Codex refresh accepts the two diagnostic model-request events. Gemini advisory hooks return native JSON and save native completion responses; Devin prompt/edit hooks emit event-labelled context. - **All 13 integrations reviewed:** refresh release metadata and the ecosystem snapshot, distinguish stable/preview channels, and pin Auggie's stable v0 references. User model, effort and approval selections remain unchanged. ### Fixed - **One Claude Stop checker:** remove the duplicate advisory handler from the global and app manifests. `quality-gate.sh` keeps PHPStan advisory through `quality-check.sh --php-only`, preserving checker precedence and Makefile settings. PHPStan now runs synchronously on Stop and TaskCompleted (#43). - **OpenCode guard execution:** replace the unsupported Bun stdin path with real subprocess execution in both APIs. Denial, missing guards, crashes and timeouts block tools. Transactional generation refuses user-owned collisions and symlinked destinations; lifecycle cleanup releases advisory ownership. - **Isolated release smoke:** `scripts/release.sh` installs the packed artifact in a disposable, network-disabled container with no mounts and the OS user's default home. Host settings are not used as a smoke sandbox. ### Changed - Hook entries: 29 to 28 across the same 14 Claude events. Skills remain 116 and agents remain 44. Bats coverage grows from 2012 to 2037 tests. - Refresh compatibility documentation and remove stale inventory counts from the backward-compatibility policy. All protected public surfaces remain. - Skill body budget is unchanged: the largest body remains `design-engineering` at 17,197 bytes, less than 2,000 bytes below the 18,000-byte warning threshold, so the release ratchet does not apply. **Included pull request:** [#43: run the project checker once on Claude Code Stop](https://github.com/softspark/ai-toolkit/pull/43), contributed by @jacekprzybyl. **Full changelog:** https://github.com/softspark/ai-toolkit/compare/v5.4.2...v5.5.0
-
v5.4.2
GitHub ↗
Original release notes
## What's Changed * fix(install): read state.json on native Windows by @jacekprzybyl in https://github.com/softspark/ai-toolkit/pull/39 * test: isolate USERPROFILE together with HOME on Windows by @jacekprzybyl in https://github.com/softspark/ai-toolkit/pull/41 **Full Changelog**: https://github.com/softspark/ai-toolkit/compare/v5.4.1...v5.4.2
Only the five most recent versions are shown. View full version history at the source ↗
Current listing version
0.0.1
Quality assessment
Out of 100 · Assessment report from SkillPi LAB.
Highlights
- 提供完整的两阶段内容审核架构,平衡成本、延迟和质量
- 包含具体实现代码和最佳实践,可直接用于生产环境
- 覆盖预过滤、LLM分类、阈值路由、人在回路等关键环节
Highlights
- 触发词精准完整,覆盖审核、安全过滤、策略执行、内容分类器等多种场景
- description 清晰明确,边界清晰,不易与其他 Skill 重叠
Highlights
- Phase/步骤清晰,有出口条件,含端到端示例
- frontmatter完整,单文件≤500行,结构规范
- 包含架构图、代码示例、规则、反模式等完整内容
Highlights
- 工具来源明确,参数正确,覆盖主要异常
- 不可逆操作有确认机制,包含人工审核队列
- 提供完整的日志记录和审计追踪机制
The arithmetic mean of the first four original scores, rounded to a whole number.
Static text checks
100 / 100 · skillpi-20261123-no-r3-v1
No current rules matched the text.
This score reflects rule matches in the text and is provided for reference before use. It excludes attachments and runtime behavior.
Permissions and checks before use
Automatically summarized from this main document. Matches may be examples or defensive advice; they are not actual permission declarations. Attachments, external dependencies and runtime behavior are not covered.
These common operations were not identified in the main document. This does not mean no permissions or risks exist.
Domains or addresses referenced in the document
These addresses may be documentation links or examples, not an approved network allowlist. Verify actual destinations and outgoing data before use.
- docs.claude.com
Security rating and access scope
safe · Static evidence review; not a runtime safety guarantee.
Before use, confirm and authorize actual file access, external services and network destinations in your host. This review grants no runtime permissions.
User discussion
No verified reviews yet.