Skip to main content
In this hands-on guide, you’ll learn how to use the OpenAI Moderation API to automatically inspect text inputs for policy violations and prevent unsafe or disallowed content from reaching your generation pipeline. By embedding a quick moderation check before calling the generation endpoint, you can maintain safe, compliant, and high-quality interactions with large language models.

Table of Contents

  1. Installation & Setup
  2. Basic Moderation Check
  3. Understanding the Moderation Response
  4. Handling Policy Violations
  5. Example: Self-Harm Prompt
  6. Best Practices & Summary

1. Installation & Setup

Before you start, ensure you have Python 3.7+ installed.
Set your API key in an environment variable to keep it secure:
Then import and configure the client:

2. Basic Moderation Check

Start with a harmless prompt (e.g., a travel itinerary). This step ensures you only proceed with clean inputs.
Expected output:

3. Understanding the Moderation Response

The Moderation API returns a JSON object with three key parts: Example response structure:
If flagged is false, you can skip deep inspection and call the generation API directly.

4. Handling Policy Violations

When the API flags a prompt (flagged: true), you should:
  1. Identify the highest-scoring category from category_scores.
  2. Inform or sanitize user input.
  3. Log or audit the incident for compliance.

5. Example: Self-Harm Prompt

Let’s test a harmful input:
Expected output:
Detailed output snippet:
Always stop the generation pipeline when flagged: true to prevent unsafe content.
Example handling:

6. Best Practices & Summary

  • Pre-filter all user inputs with the Moderation API before any generation call.
  • Log flagged prompts along with category scores for audit and tuning.
  • Gracefully inform users when their request is disallowed.
  • Keep your API key secure using environment variables or a secrets manager.
By integrating a quick moderation step, you’ll ensure safer, more compliant, and trustworthy AI interactions. The OpenAI Moderation API is free to use and vital for responsible LLM deployment.

Watch Video

Practice Lab