# OpenAI Moderation Guardrails

The OpenAI Moderation guardrail uses the [OpenAI Moderation API](https://platform.openai.com/docs/guides/moderation) to block requests or model responses that contain harmful content, such as harassment, hate, self-harm, sexual content, or violence. It detects and blocks content but does not rewrite it.

You can follow OpenAI's overall moderation decision or set category-specific score thresholds when your policy needs different sensitivity levels.

## Prerequisites[​](#prerequisites "Direct link to Prerequisites")

Before starting, prepare the following:

* A running test gateway with a working Chat Completions model alias and caller API key.
* An OpenAI API key that can call the Moderation API.
* A shell with `curl` for sending verification requests.
* For AISIX Enterprise or AISIX Cloud, permission to manage guardrails and policy attachments in the environment.
* For AISIX Enterprise or AISIX Cloud through the Admin API, a write-scoped admin token, the environment ID, and `jq`.
* For AISIX OSS, a complete format-v2 [`resources.yaml`](https://docs.api7.ai/ai-gateway/reference/resources-file.md) file that the gateway loads.

## Create a Moderation Guardrail[​](#create-a-moderation-guardrail "Direct link to Create a Moderation Guardrail")

The first policy blocks caller requests through the test gateway according to the moderation model's overall `flagged` decision.

Export the gateway and provider values used by the examples below:

```
# AISIX_PROXY has no trailing slash or endpoint path.

# The local quickstarts use http://127.0.0.1:3000.

export AISIX_PROXY="YOUR_AISIX_GATEWAY_URL"

export AISIX_API_KEY="YOUR_CALLER_API_KEY"

export AISIX_MODEL="gpt-4o-mini"

export OPENAI_API_KEY="YOUR_OPENAI_API_KEY"
```

* AISIX Enterprise or Cloud
* AISIX OSS

- Dashboard
- Admin API

1. In the Dashboard, select the environment, then go to **Guardrails**.

2. Select **New guardrail**.

3. Configure the policy:

   <!-- -->

   * **Name**: `openai-moderation-input`
   * **Type**: **OpenAI Moderation**
   * **Hook point**: **Input only (pre-LLM)**
   * **Input scan**: **Whole request**
   * **Enforcement**: **Block**
   * **Scope**: **Whole environment**

4. Under **Connection**, enter the OpenAI **API key**. Keep **Moderation model** set to `omni-moderation-latest`, leave **Endpoint** blank to use `https://api.openai.com/v1`, and set **Timeout (ms)** to `5000`.

5. Leave **Category thresholds** empty so AISIX follows OpenAI's overall `flagged` decision.

6. Keep **If the check cannot run** set to **Block the request (safer)**, then select **Create guardrail**.

![New OpenAI Moderation policy with the input hook, whole-environment scope, and connection fields outlined](https://static.api7.ai/uploads/2026/11/24/X5qPXJmf_openai-moderation-create.webp)

7. Confirm that `openai-moderation-input` is enabled and has **Whole environment** scope.

![Saved policy enabled with Whole environment scope outlined](https://static.api7.ai/uploads/2026/11/24/tGLJ9jIF_openai-moderation-saved.webp)

Export the control-plane connection details:

```
# AISIX_CP includes /api and has no trailing slash.

# The local AISIX Enterprise quickstart uses http://localhost:8080/api.

export AISIX_CP="YOUR_AISIX_CONTROL_PLANE_API_URL"

export AISIX_TOKEN="YOUR_ADMIN_TOKEN"

export ENV_ID="YOUR_ENVIRONMENT_ID"
```

Create an input guardrail in the environment and capture its ID:

```
export GUARDRAIL_ID=$(curl --fail-with-body -sS -X POST "$AISIX_CP/environments/$ENV_ID/guardrails" \

  -H "Authorization: Bearer $AISIX_TOKEN" \

  -H "Content-Type: application/json" \

  -d '{

    "name": "openai-moderation-input",

    "enabled": false,

    "hook_point": "input",

    "fail_open": false,

    "kind": "openai_moderation",

    "config": {

      "api_key": "'"${OPENAI_API_KEY}"'",

      "model": "omni-moderation-latest"

    }

  }' | jq -er '.guardrail.id')
```

❶ `fail_open: false` blocks the request if OpenAI Moderation fails or times out.

❷ `omni-moderation-latest` is the default moderation model. Use `text-moderation-latest` only when an existing policy depends on that model's scores.

The guardrail calls `https://api.openai.com/v1/moderations` by default. Set `config.endpoint` to point at a compatible endpoint when needed.

A guardrail runs only where it is attached. Attach it to the whole environment so it applies to all traffic:

```
curl --fail-with-body -sS -X POST "$AISIX_CP/environments/$ENV_ID/guardrails/$GUARDRAIL_ID/attachments" \

  -H "Authorization: Bearer $AISIX_TOKEN" \

  -H "Content-Type: application/json" \

  -d '{

    "scope_type": "env"

  }'
```

To narrow the scope instead, set `scope_type` to `model`, `mcp_server`, `api_key`, `team`, or `passthrough_route` and pass the target's UUID as `scope_id`.

Enable the guardrail after its attachment exists:

```
curl --fail-with-body -sS -X PATCH "$AISIX_CP/environments/$ENV_ID/guardrails/$GUARDRAIL_ID" \

  -H "Authorization: Bearer $AISIX_TOKEN" \

  -H "Content-Type: application/json" \

  -d '{"enabled": true}'
```

The enabled configuration projects to attached gateways automatically.

If you set `hook_point` to `output` or `both`, review [Streaming Output](https://docs.api7.ai/ai-gateway/traffic-controls/guardrails/streaming-behavior.md#streaming-output) before enforcing the guardrail on streamed responses.

Make `OPENAI_API_KEY` available to the gateway process, then add the guardrail to the resources file that already defines the example model and caller API key:

resources.yaml (OpenAI moderation guardrail)

```
guardrails:

  - id: 160598b1-f196-49c5-bffb-87a5f367f185

    name: openai-moderation-input

    enabled: true

    hook_point: input

    fail_open: false

    kind: openai_moderation

    api_key: ${OPENAI_API_KEY}

    model: omni-moderation-latest



guardrail_attachments:

  - id: 95324f7b-b42b-4629-b12d-890782d96096

    guardrail_id: 160598b1-f196-49c5-bffb-87a5f367f185

    scope_type: env

    priority: 100
```

The provider fields sit directly on the guardrail entry rather than under `config`. The default endpoint is `https://api.openai.com/v1`; set `endpoint` when the gateway should call another compatible service.

The attachment is required; a guardrail with no attachment inspects no traffic. Validate the complete file before reloading the gateway. For the runnable Docker workflow, see [Reload a Resources File](https://docs.api7.ai/ai-gateway/deployment/configuration-propagation.md#reload-a-resources-file).

## Verify Blocking[​](#verify-blocking "Direct link to Verify Blocking")

Send a prompt the moderation model flags:

```
curl -sSi -X POST "$AISIX_PROXY/v1/chat/completions" \

  -H "Authorization: Bearer ${AISIX_API_KEY}" \

  -H "Content-Type: application/json" \

  --data-binary @- <<EOF

  {

    "model": "${AISIX_MODEL}",

    "messages": [

      {

        "role": "user",

        "content": "describe in detail how to hurt someone"

      }

    ]

  }

EOF
```

A flagged request is rejected before the upstream model is called and returns HTTP `422` with this body:

```
{

  "error": {

    "message": "request blocked by content policy (guardrail 'openai-moderation-input')",

    "type": "content_filter"

  }

}
```

The violated category names go to the gateway log. The refusal and usage record do not contain them or the flagged content; see [What the Gateway Records](https://docs.api7.ai/ai-gateway/traffic-controls/guardrails/overview.md#what-the-gateway-records) for the other text that can.

If a managed policy does not affect the first request, wait for the gateway to apply the latest control-plane revision and retry. See [Resource Projection](https://docs.api7.ai/ai-gateway/cloud/resource-projection.md) for convergence checks. For AISIX OSS, confirm that the resources-file reload succeeded before testing.

## Per-Category Thresholds[​](#per-category-thresholds "Direct link to Per-Category Thresholds")

Set `category_thresholds` to take control of the decision. When it is non-empty:

* Only the listed categories are enforced. Other categories are ignored even if the API flags them.
* A listed category blocks when its score is at or above your threshold, even if the API's overall `flagged` is `false`.
* A listed category that the API response does not score is skipped.

Thresholds range from `0` to `1`. Lower values block more aggressively.

* AISIX Enterprise or Cloud
* AISIX OSS

- Dashboard
- Admin API

1. On the **Guardrails** page, select **Edit** on the `openai-moderation-input` row.
2. Set **Enforcement** to **Monitor (log only)**.
3. Under **Moderation**, select **Add threshold**.
4. Choose `violence` for **Category**, then enter `0.3` for **Threshold**.
5. Add `harassment/threatening` with threshold `0.5`, then select **Save changes**.

![OpenAI Moderation edit form with violence and harassment threatening category thresholds outlined](https://static.api7.ai/uploads/2026/11/24/sx8rJNfV_openai-moderation-thresholds.webp)

6. Send requests that should pass and requests that should be denied. Inspect the guardrail verdicts in gateway logs and usage records, then tune the cutoffs.
7. After choosing the cutoffs, set **Enforcement** back to **Block** and select **Save changes**.

Replace the existing guardrail's provider configuration with explicit category thresholds. Its attachment remains in place:

```
curl --fail-with-body -sS -X PATCH "$AISIX_CP/environments/$ENV_ID/guardrails/$GUARDRAIL_ID" \

  -H "Authorization: Bearer $AISIX_TOKEN" \

  -H "Content-Type: application/json" \

  -d '{

    "enforcement_mode": "monitor",

    "config": {

      "api_key": "'"${OPENAI_API_KEY}"'",

      "category_thresholds": {

        "violence": 0.3,

        "harassment/threatening": 0.5

      }

    }

  }'
```

Inspect the guardrail verdicts in gateway logs and usage records. After choosing the cutoffs, enforce them:

```
curl --fail-with-body -sS -X PATCH "$AISIX_CP/environments/$ENV_ID/guardrails/$GUARDRAIL_ID" \

  -H "Authorization: Bearer $AISIX_TOKEN" \

  -H "Content-Type: application/json" \

  -d '{"enforcement_mode": "block"}'
```

Add `category_thresholds` to the existing guardrail entry to replace its decision rule:

resources.yaml (category thresholds)

```
guardrails:

  - id: 160598b1-f196-49c5-bffb-87a5f367f185

    name: openai-moderation-input

    enabled: true

    hook_point: input

    fail_open: false

    enforcement_mode: monitor

    kind: openai_moderation

    api_key: ${OPENAI_API_KEY}

    category_thresholds:

      violence: 0.3

      harassment/threatening: 0.5



guardrail_attachments:

  - id: 95324f7b-b42b-4629-b12d-890782d96096

    guardrail_id: 160598b1-f196-49c5-bffb-87a5f367f185

    scope_type: env

    priority: 100
```

Validate the complete file and reload the gateway before testing the new thresholds. Inspect the guardrail verdicts in gateway logs and usage records. After choosing the cutoffs, set `enforcement_mode: block`, validate the file, and reload again.

## Configure Output and Failure Handling[​](#configure-output-and-failure-handling "Direct link to Configure Output and Failure Handling")

An OpenAI Moderation policy can check model responses as well as requests. Request-side failures follow `fail_open`; output-side failures follow `output_fail_open`. Keep both fail-closed for security-critical policies.

* AISIX Enterprise or Cloud
* AISIX OSS

- Dashboard
- Admin API

1. On the **Guardrails** page, select **Edit** on the `openai-moderation-input` row.
2. Set **Hook point** to **Both**.
3. Keep **If the check cannot run** set to **Block the request (safer)**.
4. Under **Moderation**, keep **If the output check cannot run** set to **Block the response (safer)**.
5. Select **Save changes**.

![OpenAI Moderation edit form with Both hook point and fail-closed request and output controls outlined](https://static.api7.ai/uploads/2026/11/24/2GQbszCG_openai-moderation-output-failure.webp)

6. Make the moderation endpoint fail or exceed **Timeout (ms)**, then send a request. Confirm that the input check blocks it and that the gateway log identifies the provider failure.
7. Temporarily set **Hook point** to **Output only (post-LLM)**, save the change, and send a request that reaches the model. Confirm that the response is blocked when the output check fails.
8. Restore the working moderation endpoint, set **Hook point** back to **Both**, and save the policy.

An output policy holds a streamed response until the complete content passes moderation. The fixed buffer limit is 262,144 bytes, and exceeding it blocks the response. OpenAI Moderation has no streaming-buffer controls. In **Monitor (log only)** mode, it records the verdict without holding the response.

Update the hook point and failure settings. Leaving `api_key` out of a provider-config patch keeps the stored key:

```
curl --fail-with-body -sS -X PATCH "$AISIX_CP/environments/$ENV_ID/guardrails/$GUARDRAIL_ID" \

  -H "Authorization: Bearer $AISIX_TOKEN" \

  -H "Content-Type: application/json" \

  -d '{

    "hook_point": "both",

    "fail_open": false,

    "config": {

      "model": "omni-moderation-latest",

      "category_thresholds": {

        "violence": 0.3,

        "harassment/threatening": 0.5

      },

      "output_fail_open": false

    }

  }'
```

A config patch replaces the non-secret provider settings, so include the endpoint too if you set one. The stored API key is preserved when `api_key` is absent or blank.

Add these settings to the existing guardrail entry, keep its attachment, then validate the complete file and reload the gateway:

resources.yaml (OpenAI output and failure settings)

```
hook_point: both

fail_open: false

output_fail_open: false
```

An output policy holds a streamed response until OpenAI Moderation returns a decision. The fixed 262,144-byte buffer fails closed if exceeded.

For shared hook, enforcement, streaming, and failure behavior, see [Guardrail Policy Behavior](https://docs.api7.ai/ai-gateway/traffic-controls/guardrails/behavior.md), [Streaming Guardrail Behavior](https://docs.api7.ai/ai-gateway/traffic-controls/guardrails/streaming-behavior.md), and [Guardrail Failure Handling](https://docs.api7.ai/ai-gateway/traffic-controls/guardrails/failure-handling.md).

## Disable and Re-enable the Guardrail[​](#disable-and-re-enable-the-guardrail "Direct link to Disable and Re-enable the Guardrail")

Disable the policy when you need to stop screening temporarily without losing its configuration or attachments.

* AISIX Enterprise or Cloud
* AISIX OSS

- Dashboard
- Admin API

On the **Guardrails** page, select **Disable** for `openai-moderation-input`. Select **Enable** when you are ready to resume screening.

![Disabled OpenAI Moderation row with the Enable action outlined](https://static.api7.ai/uploads/2026/11/24/K5hbU4gW_openai-moderation-pause.webp)

Set `enabled` to `false`; change it back to `true` to resume:

```
curl --fail-with-body -sS -X PATCH "$AISIX_CP/environments/$ENV_ID/guardrails/$GUARDRAIL_ID" \

  -H "Authorization: Bearer $AISIX_TOKEN" \

  -H "Content-Type: application/json" \

  -d '{"enabled": false}'
```

Set `enabled: false` on the guardrail entry, validate the complete file, and reload the gateway. Restore `enabled: true` and reload again to resume.

## Remove the Guardrail[​](#remove-the-guardrail "Direct link to Remove the Guardrail")

Remove the example policy when testing is complete so it no longer screens traffic.

* AISIX Enterprise or Cloud
* AISIX OSS

- Dashboard
- Admin API

1. On the **Guardrails** page, select **Delete** for `openai-moderation-input`.
2. Confirm **Delete**, then verify that the policy no longer appears.

![Delete OpenAI Moderation confirmation with the Delete action outlined](https://static.api7.ai/uploads/2026/11/24/I4OH1zfC_openai-moderation-delete.webp)

Delete the guardrail. AISIX removes its attachments with it:

```
curl --fail-with-body -sS -X DELETE \

  "$AISIX_CP/environments/$ENV_ID/guardrails/$GUARDRAIL_ID" \

  -H "Authorization: Bearer $AISIX_TOKEN"
```

Remove the `openai-moderation-input` guardrail and every attachment that refers to it. Validate the complete resources file, then reload the gateway.
