# 实施 AI 安全护栏并保护 PII

本指南介绍如何在同一条路由上使用 [`ai-prompt-guard`](https://docs.apiseven.com/hub/ai-prompt-guard.md)、[`ai-aws-content-moderation`](https://docs.apiseven.com/hub/ai-aws-content-moderation.md) 和 [`ai-request-rewrite`](https://docs.apiseven.com/hub/ai-request-rewrite.md)，在请求到达主模型前集中执行提示词过滤、内容审核和请求侧 PII 遮蔽。

启用 `ai-request-rewrite` 时，网关会先将原始请求体发送给配置的重写模型，然后 `ai-prompt-guard` 才会检查改写后的请求体。请求侧遮蔽可以减少主模型接触 PII 的机会，但重写模型服务提供方仍会收到原始内容。如果原始内容不能离开你的环境，请使用可信或自托管的重写模型服务。

## 概览[​](#概览 "概览的直接链接")

在网关层实施安全护栏最为有效，因为策略可以集中管理并跨应用一致执行。实用的纵深防御模型包含三层：

1. **提示词过滤**：在调用主模型前阻止提示词注入和禁止的指令。
2. **内容审核**：检测有害内容类别并拒绝高风险请求。
3. **PII 遮蔽**：在请求发往主模型服务提供方前转换敏感数据，同时考虑对重写模型的单独调用。

## 前置条件[​](#前置条件 "前置条件的直接链接")

* 安装 [Docker](https://docs.docker.com/get-docker/)。

* 安装 [cURL](https://curl.se/)，用于发送请求并验证服务。

* 拥有一个正在运行的 API7 网关实例。

* [从控制台获取 Token](https://docs.apiseven.com/api7-gateway/reference/obtain-dashboard-token.md)，并保存到环境变量：

  ```
  export API_KEY=your-dashboard-token   # 请替换为你的控制台 Token
  ```

* 将 `{gateway_group_id}` 替换为网关组 ID。如果正在按照快速入门操作，请使用 `default`。

* 如果使用 Admin API 示例，请创建或复用一个服务。如果尚无服务，请按照[创建或复用服务](https://docs.apiseven.com/api7-gateway/ai-gateway/get-started.md#create-or-reuse-a-service)操作，然后将其 ID 保存到环境变量：

  ```
  export SERVICE_ID=your-service-id         # 请替换为你的服务 ID
  ```

## 提示词保护[​](#提示词保护 "提示词保护的直接链接")

使用 [`ai-prompt-guard`](https://docs.apiseven.com/hub/ai-prompt-guard.md) 应用基于 PCRE 的允许和拒绝模式。此示例仅检查用户消息（`match_all_roles: false`）和最新消息（`match_all_conversation_history: false`）。匹配拒绝模式时，以 HTTP 400 拒绝请求。

* Admin API
* ADC

```
allow_pattern='(?i)^(what|how|why|explain|summarize|translate)\\b'

deny_pattern='(?i)(ignore\\s+all\\s+previous\\s+instructions|reveal\\s+system\\s+prompt|bypass\\s+guardrails)'



curl -k "https://localhost:7443/apisix/admin/routes/ai-guardrails-prompt-protection?gateway_group_id={gateway_group_id}" -X PUT \

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

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

  --data-binary @- <<EOF

  {

    "name": "ai-guardrails-prompt-protection",

    "service_id": "$SERVICE_ID",

    "paths": ["/ai/prompt-protection"],

    "plugins": {

      "ai-prompt-guard": {

        "allow_patterns": ["$allow_pattern"],

        "deny_patterns": ["$deny_pattern"],

        "match_all_roles": false,

        "match_all_conversation_history": false

      },

      "ai-proxy": {

        "provider": "openai",

        "auth": { "header": { "Authorization": "Bearer $OPENAI_API_KEY" } },

        "options": { "model": "gpt-4o" }

      }

    }

  }

EOF
```

❶ `allow_patterns` 使用 PCRE 语法定义允许的提示词形式。

❷ `deny_patterns` 阻止已知注入和绕过策略的短语。

❸ `match_all_roles: false` 和 `match_all_conversation_history: false` 将匹配范围限定为最新的 `user` 消息。

adc.yaml

```
services:

  - name: AI Prompt Protection

    routes:

      - uris:

          - /ai/prompt-protection

        name: ai-guardrails-prompt-protection

        plugins:

          ai-prompt-guard:

            allow_patterns:

              - (?i)^(what|how|why|explain|summarize|translate)\b

            deny_patterns:

              - (?i)(ignore\s+all\s+previous\s+instructions|reveal\s+system\s+prompt|bypass\s+guardrails)

            match_all_roles: false

            match_all_conversation_history: false

          ai-proxy:

            provider: openai

            auth:

              header:

                Authorization: "Bearer ${OPENAI_API_KEY}"

            options:

              model: gpt-4o

    labels:

      docs-example: ai-prompt-protection
```

❶ `allow_patterns` 使用 PCRE 语法定义允许的提示词形式。

❷ `deny_patterns` 阻止已知注入和绕过策略的短语。

❸ `match_all_roles: false` 和 `match_all_conversation_history: false` 将匹配范围限定为最新的 `user` 消息。

预览本示例管理的资源变更，确认没有非预期的更新或删除：

```
adc diff -f adc.yaml \

  --include-resource-type service \

  --label-selector docs-example=ai-prompt-protection
```

审查变更后同步配置：

```
adc sync -f adc.yaml \

  --include-resource-type service \

  --label-selector docs-example=ai-prompt-protection
```

完整配置说明请参阅 [`ai-prompt-guard`](https://docs.apiseven.com/hub/ai-prompt-guard.md)。

## 内容审核[​](#内容审核 "内容审核的直接链接")

内容审核为有害或滥用性文本增加第二层过滤。

### AWS Comprehend 集成[​](#aws-comprehend-集成 "AWS Comprehend 集成的直接链接")

使用 [`ai-aws-content-moderation`](https://docs.apiseven.com/hub/ai-aws-content-moderation.md) 按 0–1 阈值对六个审核类别评分。可在 `moderation_categories` 中设置分类阈值，并通过 `moderation_threshold` 设置总体有害性阈值。超过任一阈值的请求可使用自定义状态码和消息阻止。

* Admin API
* ADC

```
curl -k "https://localhost:7443/apisix/admin/routes/ai-guardrails-content-moderation?gateway_group_id={gateway_group_id}" -X PUT \

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

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

  --data-binary @- <<EOF

  {

    "name": "ai-guardrails-content-moderation",

    "service_id": "$SERVICE_ID",

    "paths": ["/ai/content-moderation"],

    "plugins": {

      "ai-aws-content-moderation": {

        "comprehend": {

          "access_key_id": "$AWS_ACCESS_KEY_ID",

          "secret_access_key": "$AWS_SECRET_ACCESS_KEY",

          "region": "us-east-1"

        },

        "moderation_categories": {

          "PROFANITY": 0.5,

          "HATE_SPEECH": 0.5,

          "INSULT": 0.5,

          "HARASSMENT_OR_ABUSE": 0.5,

          "SEXUAL": 0.5,

          "VIOLENCE_OR_THREAT": 0.5

        },

        "moderation_threshold": 0.5

      },

      "ai-proxy": {

        "provider": "openai",

        "auth": { "header": { "Authorization": "Bearer $OPENAI_API_KEY" } },

        "options": { "model": "gpt-4o" }

      }

    }

  }

EOF
```

❶ `comprehend` 提供调用 Comprehend API 的 AWS 凭证，必须配置 `access_key_id`、`secret_access_key` 和 `region`。

❷ 为 `PROFANITY`、`HATE_SPEECH`、`INSULT`、`HARASSMENT_OR_ABUSE`、`SEXUAL` 和 `VIOLENCE_OR_THREAT` 配置分类阈值。

❸ `moderation_threshold` 定义总体有害性阈值；使用 `moderation_categories` 在全局阈值之外实施特定类别阈值。

adc.yaml

```
services:

  - name: AI Content Moderation

    routes:

      - uris:

          - /ai/content-moderation

        name: ai-guardrails-content-moderation

        plugins:

          ai-aws-content-moderation:

            comprehend:

              access_key_id: ${AWS_ACCESS_KEY_ID}

              secret_access_key: ${AWS_SECRET_ACCESS_KEY}

              region: us-east-1

            moderation_categories:

              PROFANITY: 0.5

              HATE_SPEECH: 0.5

              INSULT: 0.5

              HARASSMENT_OR_ABUSE: 0.5

              SEXUAL: 0.5

              VIOLENCE_OR_THREAT: 0.5

            moderation_threshold: 0.5

          ai-proxy:

            provider: openai

            auth:

              header:

                Authorization: "Bearer ${OPENAI_API_KEY}"

            options:

              model: gpt-4o

    labels:

      docs-example: ai-content-moderation
```

❶ `comprehend` 提供调用 Comprehend API 的 AWS 凭证，必须配置 `access_key_id`、`secret_access_key` 和 `region`。

❷ 为 `PROFANITY`、`HATE_SPEECH`、`INSULT`、`HARASSMENT_OR_ABUSE`、`SEXUAL` 和 `VIOLENCE_OR_THREAT` 配置分类阈值。

❸ `moderation_threshold` 定义总体有害性阈值；使用 `moderation_categories` 在全局阈值之外实施特定类别阈值。

预览本示例管理的资源变更，确认没有非预期的更新或删除：

```
adc diff -f adc.yaml \

  --include-resource-type service \

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

审查变更后同步配置：

```
adc sync -f adc.yaml \

  --include-resource-type service \

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

完整配置说明请参阅 [`ai-aws-content-moderation`](https://docs.apiseven.com/hub/ai-aws-content-moderation.md)。

### 自定义审核服务[​](#自定义审核服务 "自定义审核服务的直接链接")

可以通过 [`ai-request-rewrite`](https://docs.apiseven.com/hub/ai-request-rewrite.md) 调用专用模型，在转发到主大语言模型路由前对请求内容进行分类或转换。该插件会用模型输出替换请求体，但不会自行解释评分或根据自定义审核结果拒绝请求。其他已配置的安全护栏仍可拒绝改写后的请求；若要实施自定义分类策略，请使用能明确返回阻止决定的组件。

## PII 遮蔽[​](#pii-遮蔽 "PII 遮蔽的直接链接")

PII 遮蔽可以减少姓名、电话号码、账户标识符等敏感字段意外暴露给主模型服务提供方的机会。原始请求仍会发送给重写模型服务提供方，而且单靠遮蔽并不能证明符合某项合规标准。

### 请求侧 PII 遮蔽[​](#请求侧-pii-遮蔽 "请求侧 PII 遮蔽的直接链接")

使用 [`ai-request-rewrite`](https://docs.apiseven.com/hub/ai-request-rewrite.md) 把传入提示词发送给独立模型，在请求到达主大语言模型前检测并遮蔽 PII。

警告

重写模型会在脱敏前收到原始请求。请使用已获准处理未脱敏内容的服务提供方，或将重写模型部署在要求的信任边界内。

* Admin API
* ADC

```
curl -k "https://localhost:7443/apisix/admin/routes/ai-guardrails-pii-request?gateway_group_id={gateway_group_id}" -X PUT \

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

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

  --data-binary @- <<EOF

  {

    "name": "ai-guardrails-pii-request",

    "service_id": "$SERVICE_ID",

    "paths": ["/ai/pii-request"],

    "plugins": {

      "ai-request-rewrite": {

        "provider": "openai",

        "auth": {

          "header": {

            "Authorization": "Bearer $OPENAI_API_KEY"

          }

        },

        "options": {

          "model": "gpt-4o"

        },

        "prompt": "Return the complete incoming OpenAI-compatible request as valid JSON. Preserve every field and structure. In textual message content only, replace emails with [REDACTED_EMAIL], phone numbers with [REDACTED_PHONE], payment card numbers with [REDACTED_CARD], and government identifiers with [REDACTED_ID]. Return JSON only."

      },

      "ai-proxy": {

        "provider": "openai",

        "auth": { "header": { "Authorization": "Bearer $OPENAI_API_KEY" } },

        "options": { "model": "gpt-4o" }

      }

    }

  }

EOF
```

❶ `provider` 设置用于重写决策的模型后端。

❷ `auth` 配置调用重写模型的凭证。

❸ `options.model` 选择重写模型。重写输出会替换完整请求体，因此 `prompt` 必须要求返回有效且完整的 AI 请求，而不能只返回脱敏后的文本。

adc.yaml

```
services:

  - name: AI Request-Side PII Masking

    routes:

      - uris:

          - /ai/pii-request

        name: ai-guardrails-pii-request

        plugins:

          ai-request-rewrite:

            provider: openai

            auth:

              header:

                Authorization: "Bearer ${OPENAI_API_KEY}"

            options:

              model: gpt-4o

            prompt: >-

              Return the complete incoming OpenAI-compatible request as valid JSON.

              Preserve every field and structure. In textual message content only,

              replace emails with [REDACTED_EMAIL], phone numbers with

              [REDACTED_PHONE], payment card numbers with [REDACTED_CARD], and

              government identifiers with [REDACTED_ID]. Return JSON only.

          ai-proxy:

            provider: openai

            auth:

              header:

                Authorization: "Bearer ${OPENAI_API_KEY}"

            options:

              model: gpt-4o

    labels:

      docs-example: ai-request-side-pii-masking
```

❶ `provider` 设置用于重写决策的模型后端。

❷ `auth` 配置调用重写模型的凭证。

❸ `options.model` 选择重写模型。重写输出会替换完整请求体，因此 `prompt` 必须要求返回有效且完整的 AI 请求，而不能只返回脱敏后的文本。

预览本示例管理的资源变更，确认没有非预期的更新或删除：

```
adc diff -f adc.yaml \

  --include-resource-type service \

  --label-selector docs-example=ai-request-side-pii-masking
```

审查变更后同步配置：

```
adc sync -f adc.yaml \

  --include-resource-type service \

  --label-selector docs-example=ai-request-side-pii-masking
```

### 响应侧 PII 过滤[​](#响应侧-pii-过滤 "响应侧 PII 过滤的直接链接")

`ai-request-rewrite` 只处理客户端请求，不会检查或修改模型响应。请在上游应用或其他明确支持响应处理的组件中实施响应侧 PII 控制。

完整配置说明请参阅 [`ai-request-rewrite`](https://docs.apiseven.com/hub/ai-request-rewrite.md)。

## 组合安全护栏[​](#组合安全护栏 "组合安全护栏的直接链接")

大多数部署会在同一路由上组合这些控制。可观察到的请求流程如下：

1. `ai-request-rewrite` 调用配置的重写模型，并替换完整请求体。
2. `ai-prompt-guard` 检查重写后的请求，并拒绝提示词匹配相应模式的请求。
3. `ai-proxy` 识别请求协议并选择服务提供方配置；随后 `ai-aws-content-moderation` 在 access 阶段审核内容。
4. access 阶段完成后，`ai-proxy` 构建并发送获准的服务提供方请求。

备注

插件执行顺序由阶段和优先级决定，而不是配置中的排列顺序。特别是 `ai-request-rewrite` 在 `ai-prompt-guard` 之前执行，因此提示词防护规则不会保护对外部重写模型的调用。

* Admin API
* ADC

```
allow_pattern='(?i)^.{1,4000}$'

deny_pattern='(?i)(ignore\\s+all\\s+previous\\s+instructions|reveal\\s+system\\s+prompt|developer\\s+mode)'



curl -k "https://localhost:7443/apisix/admin/routes/ai-guardrails-combined?gateway_group_id={gateway_group_id}" -X PUT \

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

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

  --data-binary @- <<EOF

  {

    "name": "ai-guardrails-combined",

    "service_id": "$SERVICE_ID",

    "paths": ["/ai/combined"],

    "plugins": {

      "ai-prompt-guard": {

        "allow_patterns": ["$allow_pattern"],

        "deny_patterns": ["$deny_pattern"],

        "match_all_roles": false,

        "match_all_conversation_history": false

      },

      "ai-request-rewrite": {

        "provider": "openai",

        "auth": {

          "header": {

            "Authorization": "Bearer $OPENAI_API_KEY"

          }

        },

        "options": {

          "model": "gpt-4o"

        },

        "prompt": "Return the complete incoming OpenAI-compatible request as valid JSON. Preserve every field and structure. Redact PII only in textual message content. Return JSON only."

      },

      "ai-aws-content-moderation": {

        "comprehend": {

          "access_key_id": "$AWS_ACCESS_KEY_ID",

          "secret_access_key": "$AWS_SECRET_ACCESS_KEY",

          "region": "us-east-1"

        },

        "moderation_categories": {

          "PROFANITY": 0.5,

          "HATE_SPEECH": 0.5,

          "INSULT": 0.5,

          "HARASSMENT_OR_ABUSE": 0.5,

          "SEXUAL": 0.5,

          "VIOLENCE_OR_THREAT": 0.5

        },

        "moderation_threshold": 0.5

      },

      "ai-proxy": {

        "provider": "openai",

        "auth": { "header": { "Authorization": "Bearer $OPENAI_API_KEY" } },

        "options": { "model": "gpt-4o" }

      }

    }

  }

EOF
```

❶ `ai-prompt-guard` 检查改写后的请求，并以 HTTP 400 拒绝匹配拒绝模式的请求。

❷ `ai-request-rewrite` 首先运行，将原始请求发送给配置的模型，再用返回的完整 JSON 请求替换整个请求体。

❸ `ai-aws-content-moderation` 在 `comprehend` 块提供 AWS Comprehend 凭证，并在转发流量前实施有害性和滥用阈值。

adc.yaml

```
services:

  - name: AI Combined Guardrails

    routes:

      - uris:

          - /ai/combined

        name: ai-guardrails-combined

        plugins:

          ai-prompt-guard:

            allow_patterns:

              - (?i)^.{1,4000}$

            deny_patterns:

              - (?i)(ignore\s+all\s+previous\s+instructions|reveal\s+system\s+prompt|developer\s+mode)

            match_all_roles: false

            match_all_conversation_history: false

          ai-request-rewrite:

            provider: openai

            auth:

              header:

                Authorization: "Bearer ${OPENAI_API_KEY}"

            options:

              model: gpt-4o

            prompt: >-

              Return the complete incoming OpenAI-compatible request as valid JSON.

              Preserve every field and structure. Redact PII only in textual

              message content. Return JSON only.

          ai-aws-content-moderation:

            comprehend:

              access_key_id: ${AWS_ACCESS_KEY_ID}

              secret_access_key: ${AWS_SECRET_ACCESS_KEY}

              region: us-east-1

            moderation_categories:

              PROFANITY: 0.5

              HATE_SPEECH: 0.5

              INSULT: 0.5

              HARASSMENT_OR_ABUSE: 0.5

              SEXUAL: 0.5

              VIOLENCE_OR_THREAT: 0.5

            moderation_threshold: 0.5

          ai-proxy:

            provider: openai

            auth:

              header:

                Authorization: "Bearer ${OPENAI_API_KEY}"

            options:

              model: gpt-4o

    labels:

      docs-example: ai-combined-guardrails
```

❶ `ai-prompt-guard` 检查改写后的请求，并以 HTTP 400 拒绝匹配拒绝模式的请求。

❷ `ai-request-rewrite` 首先运行，将原始请求发送给配置的模型，再用返回的完整 JSON 请求替换整个请求体。

❸ `ai-aws-content-moderation` 在 `comprehend` 块提供 AWS Comprehend 凭证，并在转发流量前实施有害性和滥用阈值。

预览本示例管理的资源变更，确认没有非预期的更新或删除：

```
adc diff -f adc.yaml \

  --include-resource-type service \

  --label-selector docs-example=ai-combined-guardrails
```

审查变更后同步配置：

```
adc sync -f adc.yaml \

  --include-resource-type service \

  --label-selector docs-example=ai-combined-guardrails
```

## 后续步骤[​](#后续步骤 "后续步骤的直接链接")

* [提示词工程和模板](https://docs.apiseven.com/api7-gateway/ai-gateway/use-cases/prompt-engineering-and-templating.md) — 在安全检查前规范提示词。
* [基于 Token 的限流和配额管理](https://docs.apiseven.com/api7-gateway/ai-gateway/use-cases/token-rate-limiting-and-quota-management.md) — 为受保护路由添加预算控制。
* [AI 可观测性和成本跟踪](https://docs.apiseven.com/api7-gateway/ai-gateway/use-cases/ai-observability-and-cost-tracking.md) — 监控审核结果、Token 用量和延迟。
