Moderation and Safety Best Practices

Ma Mahalakshmi V Updated 16 Sep 2026
6 min read ·Lesson 60 of 224

What the Moderation Endpoint Checks

Unit 11, Lesson 5 introduced guardrails as a way to enforce application-specific rules — refund amounts, prompt injection phrases specific to a support desk. The moderation endpoint addresses a different, narrower, and more general concern: whether a piece of text (something a user submitted, or something the model generated) contains content in categories like hate speech, harassment, self-harm, or violence, independent of any application-specific business logic at all.

from openai import OpenAI

client = OpenAI()

moderation_result = client.moderations.create(input="I want to build a birdhouse this weekend.")

result = moderation_result.results[0]
print(f"Flagged: {result.flagged}")
print(f"Categories flagged: {[cat for cat, flagged in result.categories.__dict__.items() if flagged]}")

Note: The exact set of moderation categories, the specific structure of the categories and category_scores objects, and the moderation model used can all change over time as the platform's safety systems are updated. Confirm the current category list and response structure against the current official documentation before building logic that depends on a specific category name.

result.flagged is a single boolean summarizing whether any category was triggered, while result.categories gives the specific breakdown — checking the specific categories, rather than only the overall flagged boolean, matters when different categories warrant different application responses (a violence-related flag and a self-harm-related flag are both serious, but they call for different follow-up actions, as the next section covers).

Checking Both User Input and Model Output

A moderation check applied only to what a user submits misses an entire category of risk: the model's own generated output, which is not guaranteed to avoid these categories on its own, especially under an adversarial or unusual input.

def is_content_safe(client, text: str) -> bool:
    result = client.moderations.create(input=text).results[0]
    return not result.flagged

def generate_moderated_response(client, user_message: str) -> str:
    if not is_content_safe(client, user_message):
        return "I'm not able to help with that request."

    response = client.responses.create(model="gpt-5.6-terra", input=user_message)
    output_text = response.output_text

    if not is_content_safe(client, output_text):
        return "I generated a response that didn't meet content guidelines, so I've withheld it."

    return output_text

This two-sided check reflects a distinction worth making deliberately: moderating only the input protects against a user submitting harmful content, but does nothing about a model response that turns out to be problematic despite an entirely innocuous input — checking the output as well closes that gap, at the cost of an additional moderation call per request.

Moderation and Guardrails Solve Different Problems

Unit 11, Lesson 5 distinguished application-specific guardrails from platform-wide moderation in the context of a single agent; the same distinction applies across this entire course, and it's worth being explicit about which one to reach for.

AspectPlatform ModerationApplication Guardrails (Unit 11)
ScopeGeneral categories (hate, harassment, self-harm, violence)Whatever your specific application defines
Defined byThe platformYou, in your own code
ExampleDetecting hate speech in a user messageBlocking a refund over $500 without approval
Applies toAny text, independent of any specific applicationOnly the specific agent or workflow it's attached to

Neither one is a substitute for the other in a production system — a support desk (Unit 11's capstone project) benefits from both: platform moderation catching genuinely harmful content in either direction, and application guardrails enforcing business rules specific to that support desk that platform moderation was never designed to know about at all.

Handling Flagged Content Thoughtfully

Not every flagged category deserves an identical response — a blanket "reject everything flagged" policy is simpler to write but often not the most appropriate response for every situation a real application will encounter.

def handle_moderation_result(result) -> dict:
    if not result.flagged:
        return {"action": "proceed"}

    flagged_categories = [cat for cat, is_flagged in result.categories.__dict__.items() if is_flagged]

    self_harm_categories = [cat for cat in flagged_categories if "self-harm" in cat or "self_harm" in cat]
    if self_harm_categories:
        return {"action": "provide_support_resources", "categories": self_harm_categories}

    return {"action": "reject", "categories": flagged_categories}

Note: The exact category names available (and therefore the specific substring matching shown here) can vary across moderation model versions. Confirm current category names against the current official documentation rather than assuming these specific strings.

Content flagged for self-harm-related categories, in particular, deserves a materially different response than content flagged for something like harassment — a blanket rejection is a poor response to someone expressing distress, whereas providing supportive resources (without the application attempting to serve as a substitute for real professional support) is more appropriate; this kind of category-aware handling is exactly why checking specific categories, not just the overall flagged boolean, matters in practice.

Logging Safety Events Without Over-Retaining Sensitive Content

Tracking how often moderation flags trigger, and for which categories, is valuable for understanding an application's actual risk profile over time — but what gets logged, and for how long, deserves the same deliberate care Unit 11, Lesson 6 raised about tracing potentially sensitive tool arguments.

import time

def log_moderation_event(result, request_id: str) -> None:
    if not result.flagged:
        return

    flagged_categories = [cat for cat, is_flagged in result.categories.__dict__.items() if is_flagged]
    # Log which categories triggered and when, without necessarily retaining
    # the full flagged text itself, depending on your organization's data
    # handling and retention requirements.
    print(f"[{time.time()}] request {request_id} flagged: {flagged_categories}")

Logging that a request was flagged, which categories triggered, and when, supports monitoring and trend analysis without necessarily requiring the full flagged content to be retained indefinitely — whether to retain the actual flagged text, and for how long, is a decision that should follow your organization's own data handling and retention requirements rather than a default assumption either way.

Common Mistakes

Moderating only user input and never the model's own generated output, missing the case where a response turns out to be problematic despite a perfectly innocuous input.

Treating every flagged category identically with a blanket rejection, rather than responding differently to categories — such as self-harm-related content — that call for a materially different, more supportive response.

Relying on platform moderation alone as a substitute for application-specific guardrails, when the two address different concerns and a production system generally needs both, as Unit 11, Lesson 5 established.

Logging and retaining full flagged content indefinitely without considering data handling requirements, applying less care to safety-event logs than the application applies elsewhere to sensitive data.

Best Practices

Check moderation on both user input and model-generated output, not input alone, to catch problems in either direction.

Respond differently to different flagged categories, particularly treating self-harm-related flags as calling for supportive handling rather than a blanket rejection.

Combine platform moderation with your own application-specific guardrails, since each addresses a different category of risk that the other was never designed to catch.

Apply the same data handling discipline to safety-event logging as to any other sensitive data, deciding deliberately what to retain and for how long rather than defaulting to indefinite full-content logging.

0 Comments

Reviewed before they appear

No comments yet.

OpenAI SDK
Introduction to the OpenAI SDK Setting Up Python Creating an API Key Your First Call — client.responses.create() and response.output_text Understanding Billing, Credits, and What a Request Costs Why Responses Replaced Chat Completions Anatomy of a Request: model, input, and instructions Anatomy of a Response: The Typed output Array, Not Just Text Roles: User, Assistant, and Developer/System Choosing a Model, and Reading the Models Page Instead of Memorizing Names Instructions vs. Input Writing Prompts That Get Consistent Results Few-Shot Examples Reasoning Models and the reasoning Parameter Debugging a Prompt That Misbehaves Why Streaming Matters for User Experience stream=True and Iterating Over Events Handling the Event Types You Actually Care About Background Mode for Long-Running Jobs Project — Add Live Streaming to Your Chatbot The Problem With Parsing Free Text JSON Schema and Strict Mode Pydantic Models With the SDK's Parse Helpers Handling Refusals and Validation Failures Project — A Resume-to-JSON Extractor Working With input_image input_file, PDFs, and the Files API Image Generation Speech-to-Text and Text-to-Speech Project: A PDF Question-Answering Script What Function Calling Is Defining a Tool Schema The Full Loop Multiple Tools Errors, Timeouts, and Untrusted Arguments Project: A Weather Assistant Web Search File Search and Vector Stores Code Interpreter Remote MCP Servers and Connectors Project: A Research Assistant What an Embedding Is, Without the Maths Generating and Storing Embeddings Similarity Search From Scratch Hosted Vector Stores vs. Rolling Your Own A Small RAG App Over a Folder of Notes Agents vs. a Single API Call — When You Need One pip install openai Giving Agents Tools Handoffs and Multi-Agent Triage Guardrails and Approvals Tracing and Observing What Your Agent Did A Multi-Agent Support Desk Error Codes and What Each One Means Retries, Timeouts, and Backoff Rate Limits and Spend Limits Prompt Caching and Cost Optimisation The Batch API for Bulk Work Async Clients and Concurrency Moderation and Safety Best Practices Designing the App Backend With FastAPI Streaming to a Simple Frontend Deploying and a Cost/Safety Checklist Why Web Search Is Useful for Current Information Using the Web Search Tool with the Responses API Configuring Search Behavior for Application Use Cases Understanding Citations and Source Attribution Where to Go Next Building a Research Assistant with Web Search Combining Web Search with Structured Outputs Handling Conflicting or Low-Quality Web Sources Reducing Unsupported Claims with Grounded Generation Testing Freshness-Sensitive AI Answers Production Considerations for Web-Grounded Applications Understanding File Search and Retrieval-Augmented Generation Creating and Organizing Vector Stores Uploading Documents for Retrieval Connecting Vector Stores to Responses API Requests Designing Document Metadata and Filtering Strategies Building a PDF Question-Answering Application Improving Retrieval Quality With Better Document Preparation Handling Missing Evidence and Retrieval Failures Combining File Search With Web Search Building a Production Knowledge-Base Assistant What the Code Interpreter Tool Is Designed For Running Python-Based Analysis Through the OpenAI SDK Uploading Datasets for Analysis Analyzing CSV and Spreadsheet Data Generating Charts and Data Summaries Handling Generated Files and Downloadable Artifacts Building a Data-Analysis Assistant Combining Code Execution with Structured Outputs Validating Generated Calculations and Results Security and Sandbox Considerations for Code Execution Understanding Multimodal Input with the OpenAI SDK Sending Images to a Model Image Analysis from URLs and Uploaded Files Extracting Text and Information from Screenshots Building an Image-Question-Answering Application Combining Image Input with Structured Output Analyzing Multiple Images in One Request Handling Image Quality and Input Limitations Designing Multimodal Prompts for Reliable Results Building a Practical Vision-Powered Python Application Understanding Speech-to-Text and Text-to-Speech Workflows Transcribing Audio with the OpenAI SDK Working with Uploaded Audio Files Handling Timestamps and Transcription Metadata Building a Meeting Transcription Workflow Generating Spoken Responses from Text Handling Long Audio and Processing Failures Combining Audio with Text and Tool Calling Building an End-to-End Python Voice Application What Embeddings Are and When to Use Them Generating Embeddings With the OpenAI API Preparing Text for Embedding Comparing Vectors With Cosine Similarity Building a Simple Semantic Search Engine in Python Storing Embeddings in a Database Metadata Filtering for Semantic Search Chunking Strategies for Better Retrieval Evaluating Semantic Search Quality Building a Document Similarity Application When Batch Processing Makes Sense Designing Large-Volume AI Processing Pipelines Using Asynchronous Python with the OpenAI SDK Running Concurrent Requests Safely Controlling Concurrency and Avoiding Rate Limits Tracking Batch Job Progress Handling Partial Failures in Bulk Workloads Retrying Failed Items Without Duplicating Successful Work Designing Resumable AI Processing Jobs Building a Production Batch-Processing Pipeline Batch Processing Makes Sense Large-Scale AI Processing Pipelines Async Python with OpenAI SDK Safe Concurrent Requests Concurrency & Rate Limits Batch Progress Tracking Partial Failure Handling Safe Retry Handling Resumable AI Jobs Production Batch Pipeline System–User Data Separation Reusable App Instructions Prompt Templates & Variables Extraction & Classification Prompts Summarization & Transformation Prompts Explicit Output Requirements Prompt Version Management Prompt Testing & Evaluation Reusable Python Prompt Library API Key Security Secure API Key Storage Secure Secret Management Prompt Injection Prevention Trusted vs. Untrusted Content Tool Argument Validation Sensitive Data Handling Secure Logging AI Action Authorization Production AI Security Checklist Why AI Applications Need Evaluation Beyond Unit Tests Unit Testing OpenAI SDK Integration Code Mocking API Responses in Python Tests Testing Structured Outputs Against Schemas Testing Tool-Calling Workflows Building a Small Evaluation Dataset Measuring Accuracy, Consistency, and Failure Rates Regression Testing Prompts and Model Changes Human Evaluation Versus Automated Evaluation Creating a Repeatable Evaluation Pipeline AI Request Monitoring Token Cost Management Usage Metrics Design Reducing Model Calls Prompt & Context Optimization Model Selection & Optimization AI Caching Strategies Interactive Latency Optimization Usage Dashboards & Budget Alerts Performance & Cost Checklist Every API Call Starts Fresh Fixing API Statelessness Server-Side Conversation Memory Limits of Response Chaining What We're Building Conversation Memory Challenges Preparing an OpenAI SDK Application for Deployment Environment-Specific Configuration for Development and Production Deploying a Python AI Service with Docker Container Health Checks and Startup Configuration Managing Secrets in Cloud Deployments Background Workers for Long-Running AI Tasks Queues and Asynchronous Job Architectures Scaling AI Workloads Horizontally Monitoring Production Incidents and Failures Production Deployment Checklist for OpenAI SDK Applications Reusable OpenAI Service Classes AI Client Dependency Injection Typed AI Responses Python Configuration Management AI Request Decorators Centralized AI Error Handling Clean SDK Abstractions Reusable OpenAI Utilities Internal AI Python Libraries SDK Integration Maintenance Production AI Chatbot Document Q&A System Web Research Assistant Customer Support Agent AI Data Analysis Assistant Image Analysis App Meeting Transcription & Summary Semantic Document Search Multi-Tool AI Agent Production OpenAI SDK App Why "It Looked Fine When I Tested It" Isn't Enough Timing Note Status Note Pre-Decision Status Note Current Availability Note
Ask about this post
AI Ask about this post

Ask questions about Moderation and Safety Best Practices and get answers drawn from it.

Signed-in readers only.