Inferensys

Prompt

Toxicity Detection Guardrail Prompt for User Inputs

A practical prompt playbook for using Toxicity Detection Guardrail Prompt for User Inputs in production AI workflows.
Developer doing prompt engineering on laptop, prompt variations visible on screen, casual coding session.
PROMPT PLAYBOOK

When to Use This Prompt

Defines the specific job, ideal user, and operational constraints for deploying a toxicity detection guardrail on user inputs.

This prompt is a production-grade guardrail for platform safety teams who need to classify user-submitted text before it reaches any downstream AI model, database, or human agent. The job-to-be-done is not just to detect profanity, but to produce a structured, actionable toxicity assessment—including severity, category labels, and a recommended action (BLOCK, FLAG, or ALLOW)—that can be consumed by application logic. The ideal user is a trust and safety engineer or an AI product manager integrating this into a content pipeline where a single missed toxic input can create brand risk or user harm.

You should use this prompt when you need a pre-processing gate that operates on raw, unverified user strings. It is designed for high-volume, low-latency classification where the cost of a false negative (allowing a threat or slur through) is significantly higher than the cost of a false positive (flagging a benign message for review). The prompt is calibrated to handle adversarial inputs, including slang, intentional misspellings ('leetspeak'), and obfuscation, but it is not a replacement for a full human review queue for borderline cases. It is most effective when wired into a synchronous API call that blocks or routes the user's message before any generative AI step consumes it.

Do not use this prompt as a post-generation output filter for an LLM. It is optimized for short, unstructured user inputs, not for evaluating long-form AI-generated text for subtle bias or toxicity. Do not use it as the sole defense in regulated environments where a single toxic exposure is a compliance violation; always pair it with a human-in-the-loop (HITL) review step for messages scored near the decision threshold. Finally, avoid using this prompt on inputs that have already been sanitized or redacted, as the removal of key terms can mask the true intent and cause the classifier to miss adversarial content.

PRACTICAL GUARDRAILS

Use Case Fit

Where the Toxicity Detection Guardrail Prompt delivers reliable classification and where it introduces operational risk. Use these cards to decide if this prompt fits your input pipeline before integrating it into production.

01

Good Fit: Pre-Processing User-Generated Text

Use when: you need to classify free-text user inputs (chat messages, comments, forum posts) before they enter your main AI pipeline or are stored. Guardrail: run this prompt as a synchronous pre-check with a strict latency budget; cache results to avoid re-scanning the same text.

02

Bad Fit: Real-Time Voice or Streaming Audio

Avoid when: latency must be under 50ms or the input is raw audio. This prompt requires transcribed text and adds model inference time. Guardrail: use a lightweight keyword blocklist for real-time audio and reserve this prompt for async transcript review.

03

Required Inputs: Normalized Text with Metadata

What to watch: the prompt expects clean, decoded text. Passing HTML entities, base64 blobs, or unnormalized Unicode produces unreliable scores. Guardrail: apply text normalization, HTML decoding, and Unicode sanitization before calling the prompt. Attach a message_id for traceability.

04

Operational Risk: Adversarial Misspellings and Leetspeak

What to watch: users bypass filters with character substitutions (sh1t), zero-width characters, or homoglyphs. The model may miss these without explicit calibration. Guardrail: include adversarial examples in your few-shot calibration set and run periodic red-team tests against the deployed prompt.

05

Operational Risk: Over-Blocking Legitimate Content

What to watch: medical discussions, identity terms, or reclaimed slurs can trigger false positives that silently drop valid user messages. Guardrail: always log the toxicity score and category alongside the final action. Implement a human-review queue for edge cases near your threshold.

06

Not a Replacement for Human Moderation in High-Stakes Contexts

What to watch: in child safety, threats of violence, or regulated platforms, an automated score is insufficient as the sole decision point. Guardrail: use this prompt as a first-pass filter that escalates high-severity items to trained human moderators with full context preserved.

PROMPT PLAYBOOK

Copy-Ready Prompt Template

A reusable prompt template for classifying user input toxicity with severity, category, and recommended action.

This template is the core instruction set for a toxicity detection guardrail. It is designed to be placed in the system prompt of a stateless classifier model, or as a pre-processing step before user input reaches your main application logic. The prompt instructs the model to act as a content safety classifier, analyzing the raw user text for a range of harmful categories. It uses square-bracket placeholders for the dynamic parts you must supply: the user's text, your specific policy definitions, the required JSON output schema, and any few-shot examples to calibrate behavior for edge cases like slang or adversarial misspellings.

text
You are a content safety classifier. Your sole task is to analyze the provided user input for toxicity, harassment, hate speech, self-harm, violence, and sexual content. Do not engage with the content as a conversation. Do not generate a response to the user. Only produce the classification output.

## Safety Policy
[POLICY_DEFINITIONS]

## Input
User Input: "[USER_INPUT]"

## Classification Task
1. Analyze the user input against each category defined in the Safety Policy.
2. Determine a severity level for any detected violation: `low`, `medium`, `high`, or `critical`.
3. Recommend a single action: `allow`, `flag_for_review`, `block`, or `escalate`.
4. If the input is safe across all categories, the severity must be `none` and the action must be `allow`.

## Output Format
You must respond with a single, valid JSON object conforming to this exact schema. Do not include any text outside the JSON object.
[OUTPUT_SCHEMA]

## Calibration Examples
[FEW_SHOT_EXAMPLES]

## Constraints
- Do not explain your reasoning in the output.
- Do not modify the user input.
- Adversarial misspellings and obfuscated terms (e.g., 'sh00t', 'h8') must be treated as their intended harmful words.

To adapt this template, start by replacing [POLICY_DEFINITIONS] with your organization's specific content policy, defining each category with clear, actionable descriptions. The [OUTPUT_SCHEMA] placeholder should be replaced with a strict JSON schema, for example: { "toxicity_score": <float 0-1>, "categories": [<string>], "severity": <string>, "action": <string> }. The [FEW_SHOT_EXAMPLES] are critical for handling edge cases; provide at least 3-5 examples that demonstrate the boundary between allow and flag_for_review, and show how to handle reclaimed slurs or coded language. For high-stakes production environments, the escalate action should trigger an immediate human review queue, and the raw prompt input and output must be logged immutably for audit trails. Avoid the temptation to make the policy too broad, as over-classification will break the user experience and create a backlog of false positives for your review team.

IMPLEMENTATION TABLE

Prompt Variables

Required and optional inputs for the toxicity detection guardrail prompt. Each variable must be validated before injection to prevent prompt injection, schema corruption, or policy bypass.

PlaceholderPurposeExampleValidation Notes

[USER_INPUT]

The raw user message to classify for toxicity

You're so stupid nobody likes you

Required string. Must be non-empty. Sanitize for null bytes and encoding attacks before injection. Max 4096 chars unless truncated upstream.

[TOXICITY_CATEGORIES]

Comma-separated list of toxicity categories to detect

hate_speech, harassment, sexual_content, violence, self_harm

Required string. Must match predefined enum values. Reject unknown categories. Default to standard taxonomy if empty.

[SEVERITY_THRESHOLD]

Minimum severity score that triggers a block or flag action

0.7

Required float between 0.0 and 1.0. Validate range. Values below 0.3 produce excessive false positives; above 0.9 risks false negatives.

[OUTPUT_SCHEMA]

JSON schema the model must conform to in its response

{"type": "object", "properties": {"toxicity_score": {"type": "number"}, "category": {"type": "string"}, "severity": {"type": "string"}, "action": {"type": "string"}, "explanation": {"type": "string"}}, "required": ["toxicity_score", "category", "severity", "action"]}

Required valid JSON schema string. Parse and validate before injection. Reject schemas with unbounded fields or missing required properties.

[ACTION_MAP]

Mapping of severity levels to recommended enforcement actions

{"low": "allow", "medium": "flag_for_review", "high": "block", "critical": "block_and_escalate"}

Required valid JSON object. Must contain keys for all severity levels used. Validate action values against allowed set: allow, flag_for_review, block, block_and_escalate.

[CONTEXT_WINDOW]

Number of previous messages to include for conversation context

3

Optional integer. Default 0 for stateless classification. Max 10 to prevent prompt bloat. Validate range 0-10.

[LANGUAGE_CODE]

ISO 639-1 language code for the input text

en

Optional string. Default en. Validate against ISO 639-1 list. Affects slang and adversarial misspelling calibration. Reject unsupported codes.

[CALIBRATION_EXAMPLES]

Few-shot examples for edge cases, slang, and adversarial inputs

[{"input": "u r so dum", "expected": {"toxicity_score": 0.85, "category": "harassment"}}]

Optional JSON array. Max 5 examples. Validate each example has input and expected fields. Strip examples containing prompt injection patterns before injection.

PROMPT PLAYBOOK

Implementation Harness Notes

How to wire the toxicity detection guardrail into a production application with validation, retries, and observability.

The toxicity detection prompt is not a standalone chatbot; it is a synchronous classification step in a larger application pipeline. Wire it as a pre-processing guard before any user input reaches your primary model, retrieval system, or agent loop. The harness should call the prompt, parse the JSON output, and branch based on the recommended_action field. A typical flow: receive user input → call toxicity detection prompt → if action: block, return a canned safety response and log the incident; if action: flag, route to a human review queue; if action: pass, continue to the main workflow. Do not pass the raw toxicity output to the user. The prompt's output is internal metadata for routing and audit, not a user-facing message.

Validation and retry logic is critical because the prompt returns structured JSON. Implement a JSON schema validator that checks for required fields (toxicity_score, categories, severity, recommended_action, rationale) and correct types. If parsing fails, retry once with the same input and a stricter format instruction appended to the prompt. If the retry also fails, treat the input as action: flag and escalate to human review rather than silently passing potentially toxic content. Log the raw model response and parse error for debugging. For high-throughput systems, set a latency budget: if the toxicity check exceeds 500ms, fall back to a simpler keyword-based filter or pass the input with a warning flag, depending on your risk tolerance. Never block the user indefinitely on a guardrail timeout.

Model choice matters for both accuracy and cost. Use a fast, instruction-tuned model (e.g., GPT-4o-mini, Claude 3.5 Haiku, or a fine-tuned small classifier) rather than a large reasoning model. The task is classification, not generation, and latency is the enemy of guardrails. If you observe false negatives on adversarial misspellings or slang, augment the prompt with a few-shot example bank of known bypass attempts, or pair the prompt with a separate pattern-matching layer that catches obvious keyword obfuscation before the LLM call. Logging and observability are non-negotiable: log every toxicity check with the input hash, model response, parsed score, action taken, and latency. This audit trail is essential for tuning thresholds, defending moderation decisions, and detecting prompt drift when you change models or system instructions. Wire these logs into your existing trust and safety dashboard, not a separate silo.

Human review integration should be designed for the flag action path. When the prompt returns action: flag, place the input and the full toxicity response into a review queue with context about the user session. Do not show the reviewer only the score; show the rationale field so they can make an informed decision quickly. Track reviewer decisions (override to block, override to pass) and use that data to calibrate your severity thresholds over time. If your flag rate exceeds 5% of total traffic, revisit your threshold definitions or add a second-pass classifier to reduce reviewer burden. Finally, never use the toxicity prompt's output to train a public model or share with third parties without scrubbing user-input text and reviewing data-sharing agreements. The prompt processes raw user content, which may contain PII or sensitive material even if classified as toxic.

IMPLEMENTATION TABLE

Expected Output Contract

Defines the structure, types, and validation rules for the JSON output produced by the Toxicity Detection Guardrail Prompt. Use this contract to build a parser and validation layer in your application harness before the output is used for downstream routing or blocking decisions.

Field or ElementType or FormatRequiredValidation Rule

classification.primary_label

string (enum)

Must be one of: 'toxic', 'severe_toxic', 'identity_attack', 'insult', 'threat', 'sexual_explicit', 'benign'. No other values allowed.

classification.secondary_labels

array of strings

If present, each element must be a valid primary_label enum value. Array must not contain duplicates. Must not include the primary_label value.

severity.score

number (float)

Must be a float between 0.0 and 1.0 inclusive. Precision limited to 2 decimal places. A score of 0.0 is only valid when primary_label is 'benign'.

severity.rationale

string

Must be a non-empty string between 20 and 300 characters. Must reference specific tokens or phrases from [USER_INPUT] that justify the score. No markdown.

recommended_action

string (enum)

Must be one of: 'allow', 'flag_for_review', 'block'. 'block' is only valid when severity.score >= 0.8. 'allow' is only valid when primary_label is 'benign'.

flagged_tokens

array of objects

If present, each object must contain 'token' (string, exact substring from [USER_INPUT]), 'start_index' (integer, 0-based character offset), and 'end_index' (integer). Indices must match the input string.

calibration_confidence

number (float)

Must be a float between 0.0 and 1.0 inclusive representing the model's confidence in its own classification. Values below 0.6 should trigger a retry or human review in the harness.

model_version

string

Must match the regex pattern ^\d+.\d+.\d+$ for semantic versioning. Used for audit trail and regression tracking. Reject output if this field is missing or malformed.

PRACTICAL GUARDRAILS

Common Failure Modes

Toxicity detection prompts fail in predictable ways under production pressure. These cards cover the most common failure modes, why they happen, and the guardrails that prevent them from reaching users.

01

Adversarial Misspelling Bypass

What to watch: Users replace characters with lookalikes (e.g., 'sh1t' for 'shit'), insert spaces, or use leetspeak to evade keyword-based filters. The prompt classifies the obfuscated input as clean because the surface form doesn't match known patterns. Guardrail: Include explicit instructions to normalize text and flag character-substitution patterns before classification. Add few-shot examples of obfuscated terms mapped to their toxic interpretations.

02

Context-Dependent Toxicity Misclassification

What to watch: Terms that are toxic in one context are benign in another (e.g., reclaimed slurs within in-group discussion, clinical terminology, quoted text). The prompt over-flags or under-flags based on surface tokens alone. Guardrail: Require the prompt to assess surrounding context, speaker identity signals, and quotation boundaries before assigning severity. Include calibration examples where identical words carry different toxicity labels based on context.

03

Severity Inflation on Ambiguous Inputs

What to watch: When the prompt is uncertain, it defaults to high-severity classifications to 'play it safe,' causing false positives that block legitimate content. This erodes user trust and creates review queue overload. Guardrail: Add a confidence score requirement and a separate 'ambiguous' category. Instruct the prompt to assign high severity only when multiple toxicity signals converge, not on single ambiguous terms.

04

Multilingual and Code-Switched Input Blind Spots

What to watch: Toxicity expressed in non-English languages, mixed-language code-switching, or language-specific slurs passes through undetected because the prompt's examples and instructions are English-centric. Guardrail: Include multilingual few-shot examples covering the deployment's expected languages. Add a pre-classification language detection step and explicit instruction that toxicity rules apply across all languages present in the input.

05

Category Confusion Between Toxicity and Disagreement

What to watch: Strong opinions, criticism, or heated-but-legitimate disagreement are classified as toxic, especially when they contain emphatic language or negative sentiment. This silences valid user expression. Guardrail: Define clear boundaries between toxicity (attacks on people/groups) and strong opinion (attacks on ideas). Include counterexamples where passionate disagreement is labeled as non-toxic. Add a secondary 'civility' dimension separate from toxicity.

06

Prompt Drift Under High-Volume Load

What to watch: As input volume increases, the model begins to shortcut its reasoning, skipping the structured output format, dropping severity justifications, or defaulting to a single category. Classification quality degrades silently. Guardrail: Enforce strict output schema validation on every response. Reject and retry any classification missing required fields. Monitor category distribution and severity score variance in production to detect drift early.

IMPLEMENTATION TABLE

Evaluation Rubric

Criteria for testing the toxicity detection guardrail prompt before production deployment. Use this rubric to calibrate thresholds, catch over-blocking, and verify that edge cases are handled correctly.

CriterionPass StandardFailure SignalTest Method

Clear Toxicity Detection

Flags explicit slurs, threats, and hate speech with severity >= 0.9 and category label

Misses unambiguous toxic terms or labels them as benign

Run 50 known toxic inputs; measure recall at severity >= 0.9

Benign Input Pass-Through

Returns severity <= 0.2 and action 'allow' for neutral, polite, or constructive messages

Flags neutral text as toxic or recommends 'block' for safe content

Run 100 benign inputs; measure false positive rate

Adversarial Misspelling Resistance

Detects leetspeak, character substitutions, and intentional misspellings of toxic terms

Fails to flag 'h8', 'k1ll', or zero-width obfuscated slurs

Run 30 obfuscated toxic inputs; require >= 85% detection rate

Slang and Coded Language Handling

Flags known dog whistles, coded hate symbols, and emerging toxic slang

Treats coded language as benign due to literal reading

Curate 20 coded-language examples; measure detection rate

Severity Calibration Consistency

Assigns severity scores that increase with toxicity intensity across a graded test set

Scores mild insults higher than direct threats or shows random scoring

Use a 5-level severity ladder; check Spearman correlation >= 0.85

Action Recommendation Accuracy

Recommends 'block' for severity >= 0.7, 'review' for 0.4-0.7, 'allow' for < 0.4

Recommends 'allow' on high-severity content or 'block' on borderline cases

Validate action thresholds against 200 labeled examples

Multi-Turn Context Stability

Maintains consistent toxicity judgments when the same input appears in different conversation contexts

Changes severity by more than 0.3 based on preceding benign turns

Embed 20 toxic inputs in 5-turn conversations; check score variance

Output Schema Compliance

Returns valid JSON matching [OUTPUT_SCHEMA] with all required fields populated

Missing fields, wrong types, or unparseable JSON in response

Schema validation on 100 outputs; require 100% parse rate

ADAPTATION OPTIONS

Adapt This Prompt

How to adapt

Start with the base prompt and a simple JSON schema. Use a lightweight eval set of 20-30 messages covering clear toxic, clear safe, and ambiguous cases. Skip severity calibration and focus on binary classification first.

code
Analyze this message for toxicity. Return JSON with:
- "is_toxic": boolean
- "category": string or null
- "explanation": short string

Message: [USER_INPUT]

Watch for

  • Slang and coded language slipping through
  • Over-flagging sarcasm as toxic
  • No confidence scoring, so borderline cases get hard labels
Prasad Kumkar

About the author

Prasad Kumkar

CEO & MD, Inference Systems

Prasad Kumkar is the CEO & MD of Inference Systems and writes about AI systems architecture, LLM infrastructure, model serving, evaluation, and production deployment. Over 5+ years, he has worked across computer vision models, L5 autonomous vehicle systems, and LLM research, with a focus on taking complex AI ideas into real-world engineering systems.

His work and writing cover AI systems, large language models, AI agents, multimodal systems, autonomous systems, inference optimization, RAG, evaluation, and production AI engineering.