# AI Aliyun Content Moderation

The `ai-aliyun-content-moderation` plugin uses [Aliyun Machine-Assisted Moderation Plus](https://help.aliyun.com/document_detail/2671445.html) to evaluate selected request roles and LLM responses for risks such as profanity, hate speech, harassment, and violence. It rejects content whose evaluated risk reaches the configured threshold and can annotate or interrupt streaming responses according to `stream_check_mode`.

Introduced in API7 Enterprise 3.8.0 and APISIX 3.14.0.

Please ensure that the `access_key_secret` is correctly configured in the plugin. If it is incorrectly configured, all requests will bypass the plugin to be directly forwarded to the LLM upstream, and you will see a `Specified signature is not matched with our calculation` in the gateway's error log from the plugin.

The `ai-aliyun-content-moderation` plugin should be used with either [`ai-proxy`](https://docs.api7.ai/hub/ai-proxy.md) or [`ai-proxy-multi`](https://docs.api7.ai/hub/ai-proxy-multi.md) plugin for proxying LLM requests.

<!-- -->

## Demo[​](#demo "Direct link to Demo")

The following demo demonstrates the [moderate request content toxicity example](#moderate-request-content-toxicity) in API7 Enterprise using the Dashboard, where you can moderate request content for toxicity and customize the rejection code and message.

## Behavior by Request Format[​](#behavior-by-request-format "Direct link to Behavior by Request Format")

The plugin moderates Chat Completions, Responses API, Embeddings, Anthropic Messages, and Bedrock Converse requests using each protocol's native content structure.

The gateway identifies each request by checking URI-specific rules before body-only rules:

* Bedrock Converse requires a URI ending in `/converse` and a `messages` array.
* Anthropic Messages requires a URI ending in `/v1/messages`.
* Responses API requires a URI ending in `/v1/responses` and an `input` field.
* Chat Completions uses a `messages` array.
* Embeddings uses `input` after the earlier rules do not match.
* Other non-empty JSON objects use passthrough after none of the earlier rules match.

| Request format           | Content available for moderation              |
| ------------------------ | --------------------------------------------- |
| Bedrock Converse         | Text from `system` and `messages`.            |
| Anthropic Messages       | Text from `messages`.                         |
| Responses API            | Text from `instructions` and `input`.         |
| Chat Completions         | Text from `messages`.                         |
| Embeddings               | A string or an array of strings in `input`.   |
| Other JSON (passthrough) | No request-format-specific text is extracted. |

The plugin moderates the latest user turn by default. Use `request_check_mode` to select the latest turn or all matching turns. Use `request_check_roles` to select user, tool, or system content.

Availability differs by release:

* `request_check_mode`: API7 Enterprise 3.9.16 and 3.10.2; APISIX 3.18.0.
* Role selection: API7 Enterprise 3.9.16 and 3.10.3; APISIX 3.18.0.
* API7 Enterprise 3.10.2 supports only user messages.

With role-aware selection, the Anthropic top-level `system` prompt is available when the system role is selected. Tool-result moderation applies when the request format represents tool output as a distinct tool role or item. Anthropic Messages and Bedrock Converse nest tool results in user messages, so they are not extracted when only the tool role is selected.

To moderate the broadest supported request content, configure all available roles and all turns in the plugin configuration:

```
{

  "request_check_roles": ["user", "tool", "system"],

  "request_check_mode": "all"

}
```

This configuration scans all text that the detected protocol exposes for those roles. It does not reproduce raw-body moderation: nested Anthropic and Bedrock tool results remain part of user content rather than distinct `tool` messages, and unsupported non-AI structures follow `fail_mode`.

If Responses content is rejected, the plugin returns the configured message in Responses API format. Streaming requests receive typed server-sent events ending with `response.completed`.

Embeddings has no conversation roles or turns. With role-aware selection, its `input` is selected by the user role. Rejected requests receive an OpenAI-style error response.

If an Aliyun moderation request fails, the plugin logs the error and allows the content without a moderation verdict. The `fail_mode` setting governs unsupported or non-AI request formats; it does not make Aliyun service failures fail closed. Monitor moderation errors and Aliyun availability when this plugin is an enforcement control.

In API7 Enterprise 3.9.21 and 3.10.8, and in APISIX 3.19.0, `final_packet` mode can emit a moderation result for supported SSE streams even when no usage event is present. It does not add a result to aborted streams. The same supported releases also suppress the result after a protocol failure event. Because the content has already streamed to the client, use `realtime` mode when you need to interrupt content during delivery.

## Response Moderation and Limits[​](#response-moderation-and-limits "Direct link to Response Moderation and Limits")

Set `check_response` to `true` to enable response moderation. Choose the response mode according to how the client consumes the answer:

| Response mode             | When text is checked                                                                                                                                             | Result when the threshold is reached                                                                                 |
| ------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------------------------------------- |
| Non-streaming             | The complete extracted response text is checked before it is returned, splitting it into service-sized requests when needed. `stream_check_mode` does not apply. | The response is replaced with a refusal using `deny_code` and `deny_message`.                                        |
| Streaming, `realtime`     | Text is checked in batches as chunks arrive. A check runs at the byte threshold, after the time threshold, or at stream completion.                              | The remaining stream is replaced with a refusal. Previously delivered content and the HTTP status cannot be changed. |
| Streaming, `final_packet` | The complete extracted text is checked after generation.                                                                                                         | The final moderation data reports the risk. It does not prevent or undo delivery.                                    |

`realtime` does not hold the entire answer until it passes moderation. Its default `stream_check_cache_size` of `128` counts UTF-8 bytes, so text with characters encoded as multiple bytes reaches the threshold with fewer than 128 characters. The threshold triggers a check after a chunk arrives and can be exceeded by that chunk. The default `stream_check_interval` of `3` seconds is checked when chunks arrive, not by an independent timer. Batch boundaries can change the context Aliyun evaluates, so streaming and non-streaming checks can produce different results for the same answer.

The plugin has the following limits:

* Only extracted text is moderated. Images and image URLs in multimodal content are not sent for image moderation. Empty text does not trigger a moderation request.
* Upstream responses with an HTTP status of `400` or higher are not moderated. A response from which no supported text can be extracted does not receive a text moderation verdict.
* Aliyun's default service limits are 2,000 characters for `llm_query_moderation` and 5,000 for `llm_response_moderation`. Keep `request_check_length_limit` and `response_check_length_limit` within the selected [Aliyun service limits](https://help.aliyun.com/en/document_detail/2671445.html). These character limits differ from the byte threshold used by `stream_check_cache_size`; increasing a plugin limit does not increase the service limit.
* Aliyun authentication errors, timeouts, throttling, and other moderation failures are logged and allow the content to continue. `risk_level_bar: none` still depends on a successful moderation result; it does not change this failure policy.

For diagnosis, record `$request_type` and `$llm_content_risk_level` in the access log, and check the error log for `failed to check content`. A missing risk level is not proof that content passed moderation. With multiple batches, the risk variable records the latest returned result, not an aggregate score for the entire request.

## Examples[​](#examples "Direct link to Examples")

The following examples use OpenAI as the upstream service provider.

Before proceeding, create an [OpenAI account](https://openai.com) and obtain an [API key](https://openai.com/blog/openai-api). If you are working with other LLM providers, please refer to the provider's documentation to obtain an API key.

Additionally, create an [Aliyun account](https://help.aliyun.com/en/account/step-1-register-an-alibaba-cloud-account), enable Machine-Assisted Moderation Plus, and obtain the endpoint, region ID, access key ID, and access key secret.

Export the credentials and endpoint details before using the Admin API or ADC examples:

```
export OPENAI_API_KEY="<your-openai-api-key>"

export ALIYUN_ENDPOINT=https://green-cip.cn-shanghai.aliyuncs.com

export ALIYUN_REGION_ID=cn-shanghai

export ALIYUN_ACCESS_KEY_ID="<your-aliyun-access-key-id>"

export ALIYUN_ACCESS_KEY_SECRET="<your-aliyun-access-key-secret>"
```

For the Ingress Controller examples, replace the angle-bracketed credential placeholders in the manifest before applying it.

### Moderate Request Content Toxicity[​](#moderate-request-content-toxicity "Direct link to Moderate Request Content Toxicity")

The following example demonstrates how you can use the plugin to moderate content toxicity in requests and customize rejection code and message.

* Admin API
* ADC
* Ingress Controller

Create a route to the LLM chat completion endpoint using the [`ai-proxy`](https://docs.api7.ai/hub/ai-proxy.md) plugin and configure the integration details as well as the deny code and message in the `ai-aliyun-content-moderation` plugin:

```
curl "http://127.0.0.1:9180/apisix/admin/routes" -X PUT \

  -H "X-API-KEY: ${ADMIN_API_KEY}" \

  --data-binary @- <<EOF

  {

    "id": "ai-aliyun-content-moderation-route",

    "uri": "/anything",

    "plugins": {

      "ai-aliyun-content-moderation": {

        "endpoint": "$ALIYUN_ENDPOINT",

        "region_id": "$ALIYUN_REGION_ID",

        "access_key_id": "$ALIYUN_ACCESS_KEY_ID",

        "access_key_secret": "$ALIYUN_ACCESS_KEY_SECRET",

        "deny_code": 400,

        "deny_message": "Request contains forbidden content, such as hate speech or violence."

      },

      "ai-proxy": {

        "provider": "openai",

        "auth": {

          "header": {

            "Authorization": "Bearer $OPENAI_API_KEY"

          }

        }

      }

    }

  }

EOF
```

❶ Configure the rejection HTTP status code.

❷ Configure the rejection message.

Create a route with the `ai-aliyun-content-moderation` and [`ai-proxy`](https://docs.api7.ai/hub/ai-proxy.md) plugins configured as such:

adc.yaml

```
services:

  - name: aliyun-moderation-service

    labels:

      docs-example: ai-aliyun-content-moderation

    routes:

      - name: aliyun-moderation-route

        uris:

          - /anything

        methods:

          - POST

        plugins:

          ai-aliyun-content-moderation:

            endpoint: ${ALIYUN_ENDPOINT}

            region_id: ${ALIYUN_REGION_ID}

            access_key_id: ${ALIYUN_ACCESS_KEY_ID}

            access_key_secret: ${ALIYUN_ACCESS_KEY_SECRET}

            deny_code: 400

            deny_message: Request contains forbidden content, such as hate speech or violence.

          ai-proxy:

            provider: openai

            auth:

              header:

                Authorization: Bearer ${OPENAI_API_KEY}

    upstream:

      type: roundrobin

      nodes:

        - host: httpbin.org

          port: 80

          weight: 1
```

Preview the changes for this example and confirm that the diff contains no unintended updates or deletions:

```
adc diff -f adc.yaml \

  --include-resource-type service \

  --label-selector docs-example=ai-aliyun-content-moderation
```

Synchronize the reviewed service configuration:

```
adc sync -f adc.yaml \

  --include-resource-type service \

  --label-selector docs-example=ai-aliyun-content-moderation
```

❶ Configure the rejection HTTP status code.

❷ Configure the rejection message.

* Gateway API
* APISIX CRD

Create a route with the `ai-aliyun-content-moderation` and [`ai-proxy`](https://docs.api7.ai/hub/ai-proxy.md) plugins configured as such:

ai-aliyun-moderation-ic.yaml

```
apiVersion: v1

kind: Service

metadata:

  name: httpbin-external-domain

  namespace: aic

spec:

  type: ExternalName

  externalName: httpbin.org

  ports:

    - name: http

      port: 80

      protocol: TCP

---

apiVersion: apisix.apache.org/v1alpha1

kind: PluginConfig

metadata:

  namespace: aic

  name: ai-aliyun-moderation-plugin-config

spec:

  plugins:

    - name: ai-aliyun-content-moderation

      config:

        endpoint: https://green-cip.cn-shanghai.aliyuncs.com

        region_id: cn-shanghai

        access_key_id: <aliyun-access-key-id>

        access_key_secret: <aliyun-access-key-secret>

        deny_code: 400

        deny_message: Request contains forbidden content, such as hate speech or violence.

    - name: ai-proxy

      config:

        provider: openai

        auth:

          header:

            Authorization: Bearer <openai-api-key>

---

apiVersion: gateway.networking.k8s.io/v1

kind: HTTPRoute

metadata:

  namespace: aic

  name: aliyun-moderation-route

spec:

  parentRefs:

    - name: apisix

  rules:

    - matches:

        - path:

            type: Exact

            value: /anything

          method: POST

      filters:

        - type: ExtensionRef

          extensionRef:

            group: apisix.apache.org

            kind: PluginConfig

            name: ai-aliyun-moderation-plugin-config

      backendRefs:

        - name: httpbin-external-domain

          port: 80
```

Apply the configuration to your cluster:

```
kubectl apply -f ai-aliyun-moderation-ic.yaml
```

❶ Configure the rejection HTTP status code.

❷ Configure the rejection message.

Create a route with the `ai-aliyun-content-moderation` and [`ai-proxy`](https://docs.api7.ai/hub/ai-proxy.md) plugins configured as such:

ai-aliyun-moderation-ic.yaml

```
apiVersion: apisix.apache.org/v2

kind: ApisixRoute

metadata:

  namespace: aic

  name: aliyun-moderation-route

spec:

  ingressClassName: apisix

  http:

    - name: aliyun-moderation-route

      match:

        paths:

          - /anything

        methods:

          - POST

      plugins:

        - name: ai-aliyun-content-moderation

          enable: true

          config:

            endpoint: "https://green-cip.cn-shanghai.aliyuncs.com"

            region_id: "cn-shanghai"

            access_key_id: <aliyun-access-key-id>

            access_key_secret: <aliyun-access-key-secret>

            deny_code: 400

            deny_message: "Request contains forbidden content, such as hate speech or violence."

        - name: ai-proxy

          enable: true

          config:

            provider: openai

            auth:

              header:

                Authorization: "Bearer <openai-api-key>"
```

Apply the configuration to your cluster:

```
kubectl apply -f ai-aliyun-moderation-ic.yaml
```

❶ Configure the rejection HTTP status code.

❷ Configure the rejection message.

The ADC and Gateway API tabs include a conventional backend. When the plugin handles the request itself, the backend is not contacted. Verify the plugin-specific result below; a backend response alone does not confirm that the plugin ran.

Send a POST request to the route with a system prompt and a user question with a profane word in the request body:

```
curl -i "http://127.0.0.1:9080/anything" -X POST \

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

  -d '{

    "model": "gpt-4",

    "messages": [

      { "role": "system", "content": "You are a mathematician" },

      { "role": "user", "content": "Stupid, what is 1+1?" }

    ]

  }'
```

If Aliyun classifies the prompt at or above the configured threshold, you receive an `HTTP/1.1 400 Bad Request` response like the following. The usage values are zero because request moderation rejected the prompt before it reached the LLM:

```
{

  "object": "chat.completion",

  "usage": {

    "completion_tokens": 0,

    "prompt_tokens": 0,

    "total_tokens": 0

  },

  "choices": [

    {

      "message": {

        "role": "assistant",

        "content": "Request contains forbidden content, such as hate speech or violence."

      },

      "finish_reason": "stop",

      "index": 0

    }

  ],

  "model": "gpt-4",

  "id": "c9466bbf-e010-469d-949a-a10f25525964"

}
```

Send another request to the route with a typical question in the request body:

```
curl -i "http://127.0.0.1:9080/anything" -X POST \

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

  -d '{

    "messages": [

      { "role": "system", "content": "You are a mathematician" },

      { "role": "user", "content": "What is 1+1?" }

    ]

  }'
```

You should receive an `HTTP/1.1 200 OK` response with the model output:

```
{

  ...,

  "model": "gpt-4-0613",

  "choices": [

    {

      "index": 0,

      "message": {

        "role": "assistant",

        "content": "1+1 equals 2.",

        "refusal": null

      },

      "logprobs": null,

      "finish_reason": "stop"

    }

  ],

  ...

}
```

### Adjust Risk Level Threshold[​](#adjust-risk-level-threshold "Direct link to Adjust Risk Level Threshold")

The following example demonstrates how you can adjust the threshold of risk level, which regulates whether a request/response should be allowed through.

* Admin API
* ADC
* Ingress Controller

Create a route to the LLM chat completion endpoint using the [`ai-proxy`](https://docs.api7.ai/hub/ai-proxy.md) plugin and configure the `risk_level_bar` in `ai-aliyun-content-moderation` to be `high`:

```
curl "http://127.0.0.1:9180/apisix/admin/routes" -X PUT \

  -H "X-API-KEY: ${ADMIN_API_KEY}" \

  --data-binary @- <<EOF

  {

    "id": "ai-aliyun-content-moderation-route",

    "uri": "/anything",

    "plugins": {

      "ai-aliyun-content-moderation": {

        "endpoint": "$ALIYUN_ENDPOINT",

        "region_id": "$ALIYUN_REGION_ID",

        "access_key_id": "$ALIYUN_ACCESS_KEY_ID",

        "access_key_secret": "$ALIYUN_ACCESS_KEY_SECRET",

        "deny_code": 400,

        "deny_message": "Request contains forbidden content, such as hate speech or violence.",

        "risk_level_bar": "high"

      },

      "ai-proxy": {

        "provider": "openai",

        "auth": {

          "header": {

            "Authorization": "Bearer $OPENAI_API_KEY"

          }

        },

        "model": "gpt-4"

      }

    }

  }

EOF
```

Create a route with the `ai-aliyun-content-moderation` and [`ai-proxy`](https://docs.api7.ai/hub/ai-proxy.md) plugins configured as such:

adc.yaml

```
services:

  - name: aliyun-moderation-service

    labels:

      docs-example: ai-aliyun-content-moderation

    routes:

      - name: aliyun-moderation-route

        uris:

          - /anything

        methods:

          - POST

        plugins:

          ai-aliyun-content-moderation:

            endpoint: ${ALIYUN_ENDPOINT}

            region_id: ${ALIYUN_REGION_ID}

            access_key_id: ${ALIYUN_ACCESS_KEY_ID}

            access_key_secret: ${ALIYUN_ACCESS_KEY_SECRET}

            deny_code: 400

            deny_message: Request contains forbidden content, such as hate speech or violence.

            risk_level_bar: high

          ai-proxy:

            provider: openai

            auth:

              header:

                Authorization: Bearer ${OPENAI_API_KEY}

            options:

              model: gpt-4

    upstream:

      type: roundrobin

      nodes:

        - host: httpbin.org

          port: 80

          weight: 1
```

Preview the changes for this example and confirm that the diff contains no unintended updates or deletions:

```
adc diff -f adc.yaml \

  --include-resource-type service \

  --label-selector docs-example=ai-aliyun-content-moderation
```

Synchronize the reviewed service configuration:

```
adc sync -f adc.yaml \

  --include-resource-type service \

  --label-selector docs-example=ai-aliyun-content-moderation
```

* Gateway API
* APISIX CRD

Create a route with the `ai-aliyun-content-moderation` and [`ai-proxy`](https://docs.api7.ai/hub/ai-proxy.md) plugins configured as such:

ai-aliyun-moderation-threshold-ic.yaml

```
apiVersion: v1

kind: Service

metadata:

  name: httpbin-external-domain

  namespace: aic

spec:

  type: ExternalName

  externalName: httpbin.org

  ports:

    - name: http

      port: 80

      protocol: TCP

---

apiVersion: apisix.apache.org/v1alpha1

kind: PluginConfig

metadata:

  namespace: aic

  name: ai-aliyun-moderation-plugin-config

spec:

  plugins:

    - name: ai-aliyun-content-moderation

      config:

        endpoint: https://green-cip.cn-shanghai.aliyuncs.com

        region_id: cn-shanghai

        access_key_id: <aliyun-access-key-id>

        access_key_secret: <aliyun-access-key-secret>

        deny_code: 400

        deny_message: Request contains forbidden content, such as hate speech or violence.

        risk_level_bar: high

    - name: ai-proxy

      config:

        provider: openai

        auth:

          header:

            Authorization: Bearer <openai-api-key>

        options:

          model: gpt-4

---

apiVersion: gateway.networking.k8s.io/v1

kind: HTTPRoute

metadata:

  namespace: aic

  name: aliyun-moderation-route

spec:

  parentRefs:

    - name: apisix

  rules:

    - matches:

        - path:

            type: Exact

            value: /anything

          method: POST

      filters:

        - type: ExtensionRef

          extensionRef:

            group: apisix.apache.org

            kind: PluginConfig

            name: ai-aliyun-moderation-plugin-config

      backendRefs:

        - name: httpbin-external-domain

          port: 80
```

Apply the configuration to your cluster:

```
kubectl apply -f ai-aliyun-moderation-threshold-ic.yaml
```

Create a route with the `ai-aliyun-content-moderation` and [`ai-proxy`](https://docs.api7.ai/hub/ai-proxy.md) plugins configured as such:

ai-aliyun-moderation-threshold-ic.yaml

```
apiVersion: apisix.apache.org/v2

kind: ApisixRoute

metadata:

  namespace: aic

  name: aliyun-moderation-route

spec:

  ingressClassName: apisix

  http:

    - name: aliyun-moderation-route

      match:

        paths:

          - /anything

        methods:

          - POST

      plugins:

        - name: ai-aliyun-content-moderation

          enable: true

          config:

            endpoint: "https://green-cip.cn-shanghai.aliyuncs.com"

            region_id: "cn-shanghai"

            access_key_id: <aliyun-access-key-id>

            access_key_secret: <aliyun-access-key-secret>

            deny_code: 400

            deny_message: "Request contains forbidden content, such as hate speech or violence."

            risk_level_bar: high

        - name: ai-proxy

          enable: true

          config:

            provider: openai

            auth:

              header:

                Authorization: "Bearer <openai-api-key>"

            options:

              model: gpt-4
```

Apply the configuration to your cluster:

```
kubectl apply -f ai-aliyun-moderation-threshold-ic.yaml
```

Send a POST request to the route with a system prompt and a user question with a profane word in the request body:

```
curl -i "http://127.0.0.1:9080/anything" -X POST \

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

  -d '{

    "model": "gpt-4",

    "messages": [

      { "role": "system", "content": "You are a mathematician" },

      { "role": "user", "content": "Stupid, what is 1+1?" }

    ]

  }'
```

If Aliyun classifies the prompt at or above the configured threshold, you receive an `HTTP/1.1 400 Bad Request` response like the following. The usage values are zero because request moderation rejected the prompt before it reached the LLM:

```
{

  "object": "chat.completion",

  "usage": {

    "completion_tokens": 0,

    "prompt_tokens": 0,

    "total_tokens": 0

  },

  "choices": [

    {

      "message": {

        "role": "assistant",

        "content": "Request contains forbidden content, such as hate speech or violence."

      },

      "finish_reason": "stop",

      "index": 0

    }

  ],

  "model": "gpt-4",

  "id": "c9466bbf-e010-469d-949a-a10f25525964"

}
```

Update the `risk_level_bar` in the plugin to `max`:

```
curl "http://127.0.0.1:9180/apisix/admin/routes/ai-aliyun-content-moderation-route" -X PATCH \

  -H "X-API-KEY: ${ADMIN_API_KEY}" \

  -d '{

    "plugins": {

      "ai-aliyun-content-moderation": {

        "risk_level_bar": "max"

      }

    }

  }'
```

Send the same request to the route:

```
curl -i "http://127.0.0.1:9080/anything" -X POST \

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

  -d '{

    "messages": [

      { "role": "system", "content": "You are a mathematician" },

      { "role": "user", "content": "Stupid, what is 1+1?" }

    ]

  }'
```

You should receive an `HTTP/1.1 200 OK` response with the model output:

```
{

  ...,

  "model": "gpt-4-0613",

  "choices": [

    {

      "index": 0,

      "message": {

        "role": "assistant",

        "content": "1+1 equals 2.",

        "refusal": null

      },

      "logprobs": null,

      "finish_reason": "stop"

    }

  ],

  ...

}
```

The request is forwarded because the word "stupid" has a risk level of `high`, which is below the configured threshold of `max`.

The plugin no longer emits the raw moderation request or successful moderation response as debug logs. Use the client-visible rejection status and your Aliyun monitoring data to investigate moderation outcomes without exposing prompt content in gateway logs.

### Moderate Response Content[​](#moderate-response-content "Direct link to Moderate Response Content")

After creating the route in [Moderate Request Content Toxicity](#moderate-request-content-toxicity) with the Admin API, enable response moderation and select `realtime` for streaming clients:

```
curl "http://127.0.0.1:9180/apisix/admin/routes/ai-aliyun-content-moderation-route" -X PATCH \

  -H "X-API-KEY: ${ADMIN_API_KEY}" \

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

  -d '{

    "plugins": {

      "ai-aliyun-content-moderation": {

        "check_response": true,

        "stream_check_mode": "realtime",

        "stream_check_cache_size": 128,

        "stream_check_interval": 3

      }

    }

  }'
```

This patch preserves the route's existing credentials and request moderation. For ADC or Ingress Controller, add these four settings to the plugin configuration in the existing manifest and apply it through the same workflow.

Send a non-streaming request:

```
curl -i "http://127.0.0.1:9080/anything" -X POST \

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

  -d '{

    "model": "gpt-4",

    "stream": false,

    "messages": [

      { "role": "user", "content": "Explain how a rainbow forms." }

    ]

  }'
```

When both moderation checks succeed below the threshold, the original answer is returned. If the response reaches the threshold, the gateway returns the configured refusal. Unlike a request-side refusal, a response-side refusal retains the token usage already reported by the LLM.

Repeat the request with `"stream": true` and `curl -N` to test incremental checks. A successful stream can deliver content before a later batch is refused. To collect a final moderation result without interrupting delivery, change `stream_check_mode` to `final_packet` and inspect the final SSE moderation data. Use Aliyun's test cases and logs to verify a refusal; a benign answer alone does not prove that the moderation service was called.
