> For the complete documentation index, see [llms.txt](https://docs.meganova.ai/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://docs.meganova.ai/libra-os/use-cases/content-moderation.md).

# Content Moderation

Flag and risk-score user-generated content against your own policy taxonomy using a Libra OS moderation classifier persona.

> **Note:** Libra OS ships with a built-in **AI Firewall** that moderates every interaction with the model automatically — blocking jailbreaks, PII leaks, and toxic outputs when risk exceeds the configured threshold. That is a *safety* gate for model interactions, not a general-purpose policy classifier. This guide covers the separate problem: classifying **your users' content** (posts, comments, messages) against your own policy categories and risk levels.

> **Runnable version:** a self-contained implementation (SDK client + labelled UGC set + verdict eval) lives in the cookbook: [`nova-os-cookbook/content-moderation`](https://github.com/libraos/cookbook/tree/main/content-moderation).

***

## When to use an LLM for content moderation

An LLM-based classifier fits well when:

* **Cost-effective at scale** — a single fast model call replaces hand-written rules that require constant maintenance.
* **Semantic understanding** — catches meaning-level violations (sarcasm, coded language, dogwhistles) that keyword filters miss.
* **Consistent policy application** — the same system prompt and schema produce reproducible decisions across languages and formats.
* **Policy evolves** — add or rename a category in the system prompt without retraining a custom model.
* **Interpretable reasoning** — the classifier returns an `explanation` field alongside the verdict, which is auditable by your trust-and-safety team.
* **Multilingual** — no language-specific pipelines; the model handles translation implicitly.
* **Multimodal** — the same pattern extends to image or audio descriptions passed as text.

***

## Two layers of moderation in Libra OS

### Layer 1 — Built-in AI Firewall (automatic)

Every request through Libra OS passes the AI Firewall before reaching the model. It scores requests across jailbreak, PII, and toxic-output signals. When the score reaches the block threshold (`LIBRA_OS_FIREWALL_THRESHOLD`, default `0.4`), the request is rejected and a safe refusal is returned.

You can tune the threshold in your environment:

```bash
LIBRA_OS_FIREWALL_THRESHOLD=0.3   # stricter: block more
LIBRA_OS_FIREWALL_THRESHOLD=0.6   # looser: allow more, catch less
```

The Firewall is **always on** at the model-interaction layer. You cannot (and should not) use it as a general taxonomy classifier — it does not know your product categories, your jurisdiction, or your risk tiers.

### Layer 2 — Custom policy classifier (this guide)

For your own categories and risk levels, you build a **moderation classifier persona** with `output_type`. The classifier is a persona with `brain: false` (single-shot, no planner) and a JSON Schema verdict as its output contract. The rest of this guide explains how to build and operate it.

***

## Define your unsafe categories

Start by mapping out what your policy actually prohibits. A typical platform taxonomy:

| Category                    | Description                                                          |
| --------------------------- | -------------------------------------------------------------------- |
| Hate speech                 | Content attacking people based on protected characteristics          |
| Harassment / threats        | Targeting individuals with hostility or credible threats             |
| Self-harm                   | Content promoting or glorifying self-harm or suicide                 |
| Sexual content              | Explicit or adult content not permitted on the platform              |
| Violence                    | Graphic depictions or incitement of real-world violence              |
| Spam / scam                 | Unsolicited bulk content, phishing, or fraud                         |
| Conspiracy / misinformation | Demonstrably false claims presented as fact                          |
| Privacy / PII               | Sharing personal information about real individuals without consent  |
| Specialized advice          | Unlicensed medical, legal, or financial advice that could cause harm |

Add platform-specific categories as needed — for example, `Underage posting` for an age-restricted service, or `Off-topic` for a focused community.

***

## Choose the model

Content moderation is a high-volume, latency-sensitive workload. Use the **skill tier**: a fast, cheap model such as `gemini/gemini-2.5-flash` or a comparable Flash/Haiku-class model. This maps to `LIBRA_OS_SKILL_MODEL` in your environment.

Reserve a larger model only if you are classifying long-form documents or need deeper reasoning on edge cases.

***

## Build a moderation classifier persona

Register the persona with `output_type` using a JSON Schema that locks the response shape. The `on_violation: "repair"` setting asks the model to self-correct if it produces invalid JSON.

```bash
curl -X POST https://demo.meganova.app/v1/agents \
  -H "Authorization: Bearer $TOKEN" \
  -H "anthropic-beta: managed-agents-2026-04-01" \
  -H "Content-Type: application/json" \
  -d '{
    "name": "content-moderator",
    "agent_type": "persona",
    "brain": false,
    "model": "gemini/gemini-2.5-flash",
    "system": "You are a content-moderation system for a social platform. Given a user message, decide whether it violates any of the following unsafe categories:\n\n- Hate speech\n- Harassment / threats\n- Self-harm\n- Sexual content\n- Violence\n- Spam / scam\n- Conspiracy / misinformation\n- Privacy / PII\n- Specialized advice\n\nReturn only the JSON object specified. If the content is clearly safe, set violation to false and categories to an empty array. Provide a brief explanation of your reasoning.",
    "output_type": {
      "schema_inline": {
        "type": "object",
        "properties": {
          "violation": {
            "type": "boolean"
          },
          "categories": {
            "type": "array",
            "items": { "type": "string" }
          },
          "explanation": {
            "type": "string"
          }
        },
        "required": ["violation", "categories", "explanation"]
      },
      "on_violation": "repair"
    }
  }'
```

> **Note:** Every `array` property in the schema must include an `items` field. Some gateway-routed models reject an array schema that omits `items` and return a 400 error.

***

## Run the classifier

Submit user content to the moderator persona through the chat endpoint. Replace `{api_key}` with the agent's API key (from `POST /api/agents/content-moderator/keys`).

**Allowed content:**

```bash
curl -X POST https://demo.meganova.app/agents/v1/{api_key}/chat \
  -H "Authorization: Bearer $TOKEN" \
  -H "Content-Type: application/json" \
  -d '{
    "messages": [
      {"role": "user", "content": "Just got back from a hike — the trail conditions were perfect today!"}
    ]
  }'
```

```json
{
  "violation": false,
  "categories": [],
  "explanation": "The message describes a recreational activity with no policy-violating content."
}
```

**Flagged content:**

```bash
curl -X POST https://demo.meganova.app/agents/v1/{api_key}/chat \
  -H "Authorization: Bearer $TOKEN" \
  -H "Content-Type: application/json" \
  -d '{
    "messages": [
      {"role": "user", "content": "I know where you live and I will make you regret this."}
    ]
  }'
```

```json
{
  "violation": true,
  "categories": ["Harassment / threats"],
  "explanation": "The message contains a direct threat that implies knowledge of the target's location and intent to cause harm."
}
```

***

## Risk levels instead of binary

A boolean verdict is the simplest starting point, but most platforms need graduated responses: auto-block the worst content, route borderline cases to human review, and pass low-risk content automatically.

Replace `violation` with a `risk_level` integer (0 = safe, 1 = low, 2 = medium, 3 = high):

```bash
curl -X POST https://demo.meganova.app/v1/agents \
  -H "Authorization: Bearer $TOKEN" \
  -H "anthropic-beta: managed-agents-2026-04-01" \
  -H "Content-Type: application/json" \
  -d '{
    "name": "content-moderator-tiered",
    "agent_type": "persona",
    "brain": false,
    "model": "gemini/gemini-2.5-flash",
    "system": "You are a content-moderation system. Score content on a 0–3 risk scale:\n0 = clearly safe\n1 = low risk (watch but allow)\n2 = medium risk (route to human review)\n3 = high risk (block immediately)\n\nUnsafe categories: Hate speech, Harassment / threats, Self-harm, Sexual content, Violence, Spam / scam, Conspiracy / misinformation, Privacy / PII, Specialized advice.\n\nReturn only the JSON object specified.",
    "output_type": {
      "schema_inline": {
        "type": "object",
        "properties": {
          "risk_level": {
            "type": "integer",
            "minimum": 0,
            "maximum": 3
          },
          "categories": {
            "type": "array",
            "items": { "type": "string" }
          },
          "explanation": {
            "type": "string"
          }
        },
        "required": ["risk_level", "categories", "explanation"]
      },
      "on_violation": "repair"
    }
  }'
```

In your application layer, branch on `risk_level`:

| Risk level | Action                           |
| ---------- | -------------------------------- |
| 0          | Publish immediately              |
| 1          | Publish; add to monitoring queue |
| 2          | Hold; route to human reviewer    |
| 3          | Block; notify user and log       |

***

## Improve performance

### Add category definitions

Ambiguous categories (what exactly counts as "harassment" on your platform?) produce inconsistent decisions. Expand the system prompt with precise definitions and examples:

```
Harassment / threats: Direct messages that target a specific person with hostile, intimidating, or threatening language. Includes doxxing and credible threats of physical harm. Does NOT include general criticism of public figures or strongly-worded debate.
```

Tighter definitions reduce false positives on borderline content and reduce false negatives on evasive phrasing.

### Batch multiple messages

For feed-level moderation you often have dozens of messages to score at once. Send them in a single call with a schema that returns a list, cutting API calls — and cost — proportionally.

```bash
curl -X POST https://demo.meganova.app/agents/v1/{api_key}/chat \
  -H "Authorization: Bearer $TOKEN" \
  -H "Content-Type: application/json" \
  -d '{
    "messages": [
      {
        "role": "user",
        "content": "Moderate the following messages and return a verdict for each:\n\n[{\"id\":\"m1\",\"text\":\"Great post, thanks for sharing!\"},{\"id\":\"m2\",\"text\":\"You should be ashamed of yourself, I know your address.\"},{\"id\":\"m3\",\"text\":\"Buy cheap followers here: spam-site.example.com\"}]"
      }
    ]
  }'
```

Register the batch moderator with a schema that wraps verdicts in an array:

```json
{
  "type": "object",
  "properties": {
    "violations": {
      "type": "array",
      "items": {
        "type": "object",
        "properties": {
          "id":          { "type": "string" },
          "risk_level":  { "type": "integer", "minimum": 0, "maximum": 3 },
          "categories":  { "type": "array", "items": { "type": "string" } },
          "explanation": { "type": "string" }
        },
        "required": ["id", "risk_level", "categories", "explanation"]
      }
    }
  },
  "required": ["violations"]
}
```

### Tune the Firewall threshold

The built-in Firewall handles safety signals independently of your custom classifier. If you find the Firewall is blocking valid user content on your platform (high false-positive rate), raise `LIBRA_OS_FIREWALL_THRESHOLD`. If you are seeing borderline safety violations slip through, lower it. Keep the two layers — Firewall safety threshold and custom classifier risk tier — tuned separately; they solve different problems.

***

## Deploy

**Surface the explanation to your team, not your users.** The `explanation` field is for your trust-and-safety reviewers, not for end-user error messages. Show users a friendly, policy-referencing message instead: *"This post was removed because it appears to violate our community guidelines on \[category]."*

**Log every flagged decision.** Persist the full verdict (content hash or id, categories, risk level, timestamp) for trend analysis. Rising frequency in a category signals either a coordinated campaign or a policy gap that needs tightening.

**Measure precision and recall continuously.** Sample flagged content and a random slice of allowed content weekly. Calculate false-positive rate (legitimate content blocked) and false-negative rate (violations that passed). Use these numbers to refine category definitions or adjust risk-level thresholds — not to swap models.

**Version your system prompt.** Store the system prompt text alongside your model choice and schema version in source control. When you update the policy, diff the prompt and re-run your evaluation set before deploying to production.

***

## Next steps

* [Customer Support Agent](https://docs.meganova.ai/libra-os/use-cases/customer-support-agent.md)
* [Ticket Routing](https://docs.meganova.ai/libra-os/use-cases/ticket-routing.md)
* [Capabilities](https://docs.meganova.ai/libra-os/capabilities.md)
