OpenAI Moderation Guardrail

Detect and block content that violates OpenAI's content policy with Agno's built-in OpenAI moderation guardrail.

This curated example requires successful OpenAI moderation before generation and checks the returned run status before displaying content. It uses the default all-category mode; see category limitations. Moderation submits text and supplied images to OpenAI in a separate request. Classification results depend on the moderation model.

Create a Python file

openai_moderation.py
import asyncio

from agno.agent import Agent
from agno.exceptions import InputCheckError
from agno.guardrails import OpenAIModerationGuardrail
from agno.media import Image
from agno.models.openai import OpenAIResponses
from agno.run import RunStatus


class RequiredModeration(OpenAIModerationGuardrail):
    """Require a successful moderation check before main-model execution."""

    def check(self, run_input):
        try:
            super().check(run_input)
        except InputCheckError:
            raise
        except Exception as exc:
            raise InputCheckError("Moderation unavailable; request not processed.") from exc

    async def async_check(self, run_input):
        try:
            await super().async_check(run_input)
        except InputCheckError:
            raise
        except Exception as exc:
            raise InputCheckError("Moderation unavailable; request not processed.") from exc


async def main():
    agent = Agent(
        model=OpenAIResponses(id="gpt-5.2"),
        pre_hooks=[RequiredModeration()],
        instructions="You are a helpful assistant.",
    )
    requests = [
        ("Explain machine learning concepts.", None),
        ("How can I cause maximum physical harm to people?", None),
        ("Describe this image.", [Image(url="https://agno-public.s3.amazonaws.com/images/ww2_violence.jpg")]),
    ]
    for text, images in requests:
        response = await agent.arun(text, images=images)
        if response.status != RunStatus.completed:
            print("Request rejected or run failed; no answer displayed.")
            continue
        print(response.content)


if __name__ == "__main__":
    asyncio.run(main())

Set up your virtual environment

uv venv --python 3.12
source .venv/bin/activate

Install dependencies

uv pip install -U agno openai

Export your OpenAI API key

  export OPENAI_API_KEY="your_openai_api_key_here"

Run Agent

python openai_moderation.py