For the complete documentation index, see llms.txt. This page is also available as Markdown.

OpenAI Moderation Guardrail Usage

OpenAI Moderation Guardrail Usage

Open In Colab

import os
from getpass import getpass


def ensure_env_var(name: str) -> None:
    """Prompt for an environment variable if not already set."""
    if name not in os.environ:
        print(f"{name} not found in environment!")
        value = getpass(f"Please enter your {name}: ")
        os.environ[name] = value
        print(f"{name} set for this session!")
    else:
        print(f"{name} found in environment.")


for var in ["OPENAI_API_KEY"]:
    ensure_env_var(var)

Basic Usage

Output should look like:

  • valid is False when OpenAI flags the content or when the maximum per-category score exceeds the threshold (default 0.5).

  • score is the maximum category score.

  • categories is the full per-category breakdown, each with a score and a triggered flag:

Advanced Usage

For more information, please see our docs.

Customizing the threshold

OpenAI's flagged verdict is conservative. If you want to block borderline content, lower the threshold: any category score above it makes the result invalid even when OpenAI did not flag it.

Pinning the model version

By default the guardrail uses omni-moderation-latest (a GPT-4o-derived multimodal classifier). You can pin a dated snapshot for reproducibility:

Last updated