OpenAI Moderation Guardrail Usage
OpenAI Moderation Guardrail Usage
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:
validisFalsewhen OpenAI flags the content or when the maximum per-category score exceeds thethreshold(default0.5).scoreis the maximum category score.categoriesis the full per-category breakdown, each with ascoreand atriggeredflag:
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