Skip to content
,

OpenAI Moderation API Tutorial in Python: Models, Categories, Thresholds

12–17 minutes
Woman in a brick-walled loft holding a tablet with a MODERATION API card, hook free 13 safety categories

The OpenAI Moderation API checks text and images for harmful content and gives you a score for each category. It is free, it takes one short API call, and it is the easiest safety layer you can add to a chatbot, comment box or AI app.

In this guide I walk through the current model id, every category, Python code for text and images, how to pick thresholds, and how to screen both user input and model output.

TLDR

  • Model: omni-moderation-latest (snapshot omni-moderation-2024-09-26). It reads text and images, not audio.
  • Cost: the moderation endpoint is free. Default limits start at 250 requests per minute on the Free tier.
  • Output: a flagged true/false, 13 category flags and 13 scores from 0 to 1.
  • New in 2026: you can now ask the Responses and Chat Completions APIs to return moderation scores with each reply (added 4 June 2026).
  • Old models gone: the text-moderation-* models were shut down on 27 October 2025.

What the Moderation API Is and When to Use It

The Moderation API is a classifier. You send it content, and it tells you whether that content may break common safety policies. It does not write anything or change the content.

OpenAI says to use the results to enforce your own policy. That can mean blocking a message, sending it to a human for review, or taking action on an account that keeps posting flagged content.

Good places to use it:

  • Chatbots: check what users type before you send it to a model.
  • AI output: check what the model writes before you show it.
  • User uploads: screen profile photos, forum images and comments.
  • Bulk cleanup: scan old posts or datasets, even through the Batch API.
Quick answer: call client.moderations.create(model="omni-moderation-latest", input=...), read results[0].flagged and results[0].category_scores, and act on them. It costs nothing.

Current Moderation Model IDs

As of 3 December 2026, the model page lists one main moderation model. The changelog and deprecations page fill in the history.

Model id Inputs Status Notes
omni-moderation-latest Text, image Current, default Alias. Built on GPT-4o (launched 26 Sep 2024).
omni-moderation-2024-09-26 Text, image Current Pinned snapshot behind the alias.
omni-moderation-csam-latest One image Approved orgs only Child-safety image classifier, free for approved organizations (16 Nov 2026).
text-moderation-latest / -stable / -007 Text Shut down Retired 27 Oct 2025. Replacement: omni-moderation.
OpenAI omni-moderation model page showing snapshot omni-moderation-2024-09-26, text and image input, and a note that moderation models are free
Official OpenAI omni-moderation model page: text and image input, free to use (checked 3 Dec 2026).

Note: the API reference still lists the old text-moderation-* names in its model enum. They were shut down in 2025, so always use the omni model. If you leave model out, the API defaults to omni-moderation-latest.

Setup: Get Ready in 5 Steps

You need Python 3.10 or newer and an OpenAI API key. I checked the code below against the official docs and the openai Python SDK 3.63.0 (released 3 Dec 2026).

  1. Create an API key. Sign in to the OpenAI platform and make a project key. My guide on how to get an OpenAI API key shows each screen.
  2. Save it as an environment variable. On macOS or Linux run export OPENAI_API_KEY="sk-...". On Windows PowerShell run $env:OPENAI_API_KEY="sk-...".
  3. Make a virtual environment. Run python3 -m venv .venv, then activate it.
  4. Install the SDK. Run pip install -U openai. Check it with pip show openai.
  5. Run a test call. Paste Example 1 below into moderate.py and run python moderate.py.

New to the SDK? My OpenAI API Python tutorial covers clients, errors and streaming in more depth.

Example 1: Moderate Text in Python

This is the smallest useful call. The client reads OPENAI_API_KEY from your environment, so the key never sits in your code.

from openai import OpenAI

client = OpenAI()  # reads OPENAI_API_KEY

response = client.moderations.create(
    model="omni-moderation-latest",
    input="I will find you and hurt you.",
)

result = response.results[0]
print("Flagged:", result.flagged)

# Show only the categories that were flagged
for name, hit in result.categories.model_dump(by_alias=True).items():
    if hit:
        print("Category hit:", name)

# Top 3 scores
scores = result.category_scores.model_dump(by_alias=True)
for name, score in sorted(scores.items(), key=lambda x: -x[1])[:3]:
    print(f"{name}: {score:.4f}")

The by_alias=True part matters. It gives you the real API names such as harassment/threatening instead of Python-safe names like harassment_threatening.

Moderate many texts in one call

The input field also accepts a list of strings. You get one result per string, in the same order.

texts = ["Have a great day!", "Second comment here", "Third one"]
response = client.moderations.create(model="omni-moderation-latest", input=texts)

for text, res in zip(texts, response.results):
    print(res.flagged, "-", text[:40])

Example 2: Moderate Images and Text Together

For images, pass a list of objects. Each one has a type of text or image_url. The image URL can be a normal web link or a Base64 data URL, and files can be up to 20 MB.

import base64
from openai import OpenAI

client = OpenAI()

# Option A: a public image URL
image_part = {"type": "image_url", "image_url": {"url": "https://example.com/photo.png"}}

# Option B: a local file as a Base64 data URL
with open("upload.jpg", "rb") as f:
    b64 = base64.b64encode(f.read()).decode("utf-8")
image_part = {"type": "image_url", "image_url": {"url": f"data:image/jpeg;base64,{b64}"}}

response = client.moderations.create(
    model="omni-moderation-latest",
    input=[
        {"type": "text", "text": "Caption the user wrote for this photo"},
        image_part,
    ],
)

result = response.results[0]
print("Flagged:", result.flagged)
print(result.category_applied_input_types.model_dump(by_alias=True))

The category_applied_input_types field tells you which input each score came from. For example, "violence": ["image"] means the violence score was based on the image.

Warning: OpenAI says never to submit known child sexual abuse material, and not to send suspected material to omni-moderation-latest. Approved organizations should use the separate CSAM classifier and follow their legal reporting duties.

Categories and Scores Explained

Each result has three main parts:

  • flagged: OpenAI’s first-pass true/false decision.
  • categories: a true/false flag for each category.
  • category_scores: a confidence score from 0 to 1 for each category.

Here are the 13 categories in plain, neutral terms. Some read images too; the rest are text only.

Category What it covers (summary) Inputs
harassment Content that harasses or bullies a person or group Text
harassment/threatening Harassment that also includes a threat of harm Text
hate Content attacking people based on a protected trait Text
hate/threatening Hateful content that also threatens harm Text
illicit Advice or instructions for wrongdoing Text
illicit/violent Wrongdoing advice that involves violence or weapons Text
self-harm Content that depicts or encourages self-harm Text, image
self-harm/intent A person saying they intend to harm themselves Text, image
self-harm/instructions Content that gives instructions for self-harm Text, image
sexual Sexually explicit content Text, image
sexual/minors Any sexual content involving a minor Text
violence Content that depicts violence Text, image
violence/graphic Violence shown in graphic detail Text, image

If you send only an image, the text-only categories return a score of 0. That is expected, not a bug.

Tip: the scores were calibrated with the omni model to better match the chance of a real violation. OpenAI also warns that calibration can change when the model is upgraded, so pin omni-moderation-2024-09-26 if you need stable numbers.

How to Choose Thresholds

OpenAI does not publish per-category threshold numbers. The flagged field is its own default line. Your app may need a stricter or looser line, and that is where scores help.

A simple three-zone plan

  • Allow: score below your low line. Let it through.
  • Review: score between the lines. Hold it or send it to a human queue.
  • Block: score above your high line, or flagged is true for a zero-tolerance category.

How to tune the lines

  1. Start with flagged. Use OpenAI’s default for a week and log every score.
  2. Collect real samples. Pull 100 to 200 items from your own traffic, including edge cases.
  3. Label them. Mark what your policy says should happen to each one.
  4. Pick lines per category. Find the score where wrong blocks and missed items balance for your audience.
  5. Re-check after upgrades. Run your labeled set again whenever the model snapshot changes.

Different apps want different lines. A kids’ learning app should be much stricter than a medical forum, where talk about injuries is normal. A crime-fiction writing tool may allow more violence but keep sexual/minors at zero tolerance.

Note: the docs warn that a model’s refusal can still be flagged if it talks about a harmful topic. Do not treat every flagged output as a failure; look at the text.

Example 3: Screen User Input and Model Output

This is the pattern most apps need. Check the user’s message first. If it passes, generate a reply, then check the reply before you show it.

from openai import OpenAI

client = OpenAI()

# Your own policy lines (example values, tune with your data)
BLOCK_LINES = {
    "sexual/minors": 0.01,
    "self-harm/intent": 0.30,
    "harassment/threatening": 0.50,
    "violence/graphic": 0.60,
}

def check(text: str) -> tuple[bool, list[str]]:
    res = client.moderations.create(
        model="omni-moderation-latest", input=text
    ).results[0]
    scores = res.category_scores.model_dump(by_alias=True)
    hits = [c for c, line in BLOCK_LINES.items() if scores.get(c, 0) >= line]
    if res.flagged:
        hits += [c for c, v in res.categories.model_dump(by_alias=True).items() if v]
    return (len(hits) == 0, sorted(set(hits)))

def safe_chat(user_text: str) -> str:
    ok, hits = check(user_text)
    if not ok:
        print("Blocked input:", hits)  # log for your team, not the user
        return "Sorry, I can't help with that request."

    reply = client.responses.create(
        model="gpt-6.2-sol",
        input=user_text,
    ).output_text

    ok, hits = check(reply)
    if not ok:
        return "Sorry, I couldn't produce a safe answer to that."
    return reply

print(safe_chat("Give me three tips for a calm morning routine."))

A few practical points for production:

  • Do not show raw category names to users. Log them for your team and show a friendly message instead.
  • Show support for self-harm hits. For self-harm/intent, many apps show local helpline details instead of a plain block.
  • Fail safe. Decide what happens if the moderation call fails. Most public apps hold the message and retry.
  • Run checks in parallel. You can start moderation and generation together, then drop the reply if the input is flagged.

Example 4: Inline Moderation in the Responses API

Since 4 June 2026, the Responses and Chat Completions APIs accept a moderation object. The reply then carries input and output scores, so you skip the extra calls.

from openai import OpenAI

client = OpenAI()

response = client.responses.create(
    model="gpt-6.2-sol",
    input="Write a short, friendly welcome message for new forum members.",
    moderation={"model": "omni-moderation-latest"},
)

input_mod = response.moderation.input
output_mod = response.moderation.output

for label, mod in (("input", input_mod), ("output", output_mod)):
    if mod.type == "error":
        print(label, "moderation failed:", mod.message)
    else:
        print(label, "flagged:", mod.flagged)

print(response.output_text)

Know the limits of this mode before you rely on it:

  • It scores, it does not block. An OpenAI staff reply on the developer forum says the model still generates normally. Use the standalone endpoint to stop bad input before generation.
  • Streaming waits for the end. Streamed responses only include scores after the full output is ready.
  • Tool calls: it covers tool-call arguments and tool outputs, but not tool names, descriptions or schemas.
  • Check for errors. A moderation step can fail on its own, so test type == "error" before reading scores.

For more on the Responses API itself, see my Responses API tutorial.

curl Example

Here is the same text check from the command line. It is handy for quick tests and for languages without an official SDK.

curl https://api.openai.com/v1/moderations \
  -H "Content-Type: application/json" \
  -H "Authorization: Bearer $OPENAI_API_KEY" \
  -d '{
    "model": "omni-moderation-latest",
    "input": "Text from a user comment goes here."
  }'

The JSON reply has id, model and a results array. Each result has flagged, categories, category_scores and category_applied_input_types.

Cost, Rate Limits and Languages

Is the Moderation API free?

Yes. OpenAI’s moderation guide says the endpoint is free to use, and the model page calls moderation models free. You still need an API key, and requests count against your rate limits.

For inline moderation, the docs do not list a separate moderation charge. You still pay the normal token price for the model that writes the reply.

What you call Moderation cost Worked example (10,000 chat turns)
Standalone /v1/moderations $0 20,000 checks (input + output) = $0
Reply from gpt-6.2-sol Not moderation; $2 in / $10 out per 1M tokens 200 in + 300 out tokens each = 2M in ($4) + 3M out ($30) = $34
Total About $34, and moderation adds nothing to it

See OpenAI API pricing for every model’s token price.

Default rate limits for omni-moderation-latest

Usage tier Requests per minute Requests per day Tokens per minute
Free 250 5,000 10,000
Build 500 No limit listed 20,000
Launch 2,000 No limit listed 250,000
Grow 5,000 No limit listed 500,000
OpenAI omni-moderation rate limits table: Free 250 RPM, 5,000 RPD, 10,000 TPM; Build 500 RPM; Launch 2,000 RPM
Rate limits on the official OpenAI omni-moderation model page (checked 3 Dec 2026).

Your tier rises automatically as you use the API and spend more. My guide to LLM API rate limits and tiers explains how the tiers work across providers.

Tip: the model also works with the Batch API (v1/batch). That is the easy way to scan a large backlog of old posts without hitting per-minute limits. See my Batch API tutorial.

Which languages does it support?

OpenAI’s launch post says the omni model was tested in 40 languages. It scored 42% better than the old model on that test and improved in 98% of the languages.

  • Biggest gains: Telugu (6.4x), Bengali (5.6x) and Marathi (4.6x).
  • Low-resource languages: Khmer and Swati improved by about 70%.
  • No fixed list: the docs do not publish an official list of supported languages, so test with your own users’ languages.

Input size

The docs do not state a maximum text length, and the image limit is 20 MB per file. For very long documents, a safe habit is to split the text into chunks of a few paragraphs and moderate each one. That also tells you which part triggered a flag.

Troubleshooting: Common Problems and Fixes

These are the real errors from OpenAI’s error-code guide that you are most likely to hit with moderation. My OpenAI API errors guide covers the full list.

Error or symptom Python exception Likely cause Fix
401 “Incorrect API key provided” AuthenticationError Typo, revoked key or old cached key Check OPENAI_API_KEY, or make a new key.
401 “IP not authorized” AuthenticationError Your server’s IP is not on the project allowlist Add the IP in project settings.
403 “Country, region, or territory not supported” PermissionDeniedError Calling from an unsupported location Check OpenAI’s supported countries page.
429 “Rate limit reached for requests” RateLimitError Too many calls per minute or day Honor Retry-After, add backoff, batch strings in one call.
400 bad request BadRequestError Wrong input shape, broken Base64, image over 20 MB, or an old model name Use type/image_url objects and omni-moderation-latest.
500 or 503 “Model temporarily overloaded” InternalServerError A problem on OpenAI’s side Wait and retry, then check the status page.
Text-only categories score 0 None You sent only an image Expected. Add the caption as a text part.
Inline moderation field has type: "error" None The moderation step failed but the reply still came back Read message, then call the standalone endpoint.
Scores shift after an upgrade None You use the -latest alias Pin the dated snapshot and re-test your thresholds.

A simple retry wrapper handles most 429 and 5xx cases:

import time
from openai import OpenAI, RateLimitError, InternalServerError

client = OpenAI(max_retries=3)  # the SDK already retries some errors

def moderate_with_retry(text, tries=4):
    for attempt in range(tries):
        try:
            return client.moderations.create(model="omni-moderation-latest", input=text)
        except (RateLimitError, InternalServerError):
            time.sleep(2 ** attempt)
    raise RuntimeError("Moderation unavailable, hold the message for review")

Frequently Asked Questions

Is the OpenAI Moderation API really free?

Yes. OpenAI’s docs say the moderation endpoint is free to use. Your calls only count against your rate limits, which start at 250 requests per minute on the Free tier.

What is the current OpenAI moderation model?

It is omni-moderation-latest, which points to the snapshot omni-moderation-2024-09-26. The old text-moderation-* models were shut down on 27 October 2025.

Can the Moderation API check images?

Yes. Send image parts with type: "image_url" using a web URL or a Base64 data URL, up to 20 MB each. Six categories, such as violence and sexual, score images; the rest are text only.

Can it check audio or video?

No. The docs say the omni model does not classify audio. For audio, transcribe it first and moderate the text; for video, moderate sampled frames as images.

Do I have to use OpenAI models to use the Moderation API?

No. The endpoint only needs content and an API key. You can use it to screen text from any model or from your own users.

What threshold should I use?

OpenAI does not publish fixed numbers. Start with the flagged field, log the scores, then set your own per-category lines using labeled samples from your app.

Does inline moderation in the Responses API block bad prompts?

No. It returns scores with the reply, but the model still generates. Call the standalone moderation endpoint first if you need to stop a prompt before generation.

Sources

Free weekly email

Get new AI guides every week

One short weekly email with our newest local AI, ComfyUI and AI tool guides. No spam, no pop-ups, just the good stuff.

Free. Unsubscribe anytime in one click. We only use your email to send this newsletter. See our privacy policy.

Woman in a brick-walled loft holding a tablet with a MODERATION API card, hook free 13 safety categories