# AI Prompt Guard

The `ai-prompt-guard` plugin safeguards your LLM endpoints by inspecting and validating incoming prompt messages. It checks the content of requests against user-defined allowed and denied patterns to ensure that only approved inputs are forwarded to upstream LLM. The plugin can examine either the final message or the entire conversation history. It can also check prompts from all roles or only from end users.

When both `allow_patterns` and `deny_patterns` are configured, the plugin first ensures that at least one `allow_patterns` is matched. If none match, the request is rejected. If an allowed pattern is matched, it then checks for any occurrences of denied patterns.

<!-- -->

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

The following API7 Enterprise Dashboard demo follows the [allow and deny patterns example](#implement-allow-and-deny-patterns). It shows how to validate prompts with both pattern types and how an allow match takes precedence.

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

The plugin checks 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.

By default, the plugin selects the final message and then checks it only if its role is `user`. It does not search backward for the latest user message when the final message has another role. Use `match_all_roles` to include other roles and `match_all_conversation_history` to include earlier messages.

| Request format           | Content checked                                                                                                                                                                                                                             |
| ------------------------ | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| Bedrock Converse         | Content in `system` and `messages`, subject to the role and conversation-history settings.                                                                                                                                                  |
| Anthropic Messages       | Content in the top-level `system` prompt and `messages`, subject to the role and conversation-history settings.                                                                                                                             |
| Responses API            | User content in `input`. With `match_all_roles` enabled, it also checks `instructions` and content assigned other roles in `input`. The conversation-history setting does not apply because `instructions` and `input` are parallel fields. |
| Chat Completions         | Content in `messages`, subject to the role and conversation-history settings.                                                                                                                                                               |
| Embeddings               | A string in `input`. APISIX 3.20.0 also selects all string items in an `input` array. API7 Enterprise 3.9.23 and 3.10.10 do not inspect string arrays.                                                                                      |
| Other JSON (passthrough) | Not inspected as a supported AI request format.                                                                                                                                                                                             |

Embeddings inputs have neither roles nor conversation history, so `match_all_roles` and `match_all_conversation_history` do not change which items are selected. In APISIX 3.20.0, allow and deny patterns run against the space-joined batch, and a deny match rejects the whole request.

The plugin does not decode numeric token arrays into text. An Embeddings request containing only token IDs continues upstream without prompt inspection.

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

The following examples will be using OpenAI as the upstream service provider. Before proceeding, create an [OpenAI account](https://openai.com) and an [API key](https://openai.com/blog/openai-api). You can optionally save the key to an environment variable as such:

```
export OPENAI_API_KEY=YOUR_LLM_API_KEY   # replace with your API key
```

If you are working with other LLM providers, please refer to the provider's documentation to obtain an API key.

### Implement Allow and Deny Patterns[​](#implement-allow-and-deny-patterns "Direct link to Implement Allow and Deny Patterns")

The following example demonstrates how to use the `ai-prompt-guard` plugin to validate user prompts by defining both allow and deny patterns and understand how the allow pattern takes precedence.

Define the allow and deny patterns. You can optionally save them to environment variables for easier escape:

```
# allow US dollar amount

export ALLOW_PATTERN_1='\\$?\\(?\\d{1,3}(,\\d{3})*(\\.\\d{1,2})?\\)?'

# deny phone number in US number format

export DENY_PATTERN_1='(\\([0-9]{3}\\)|[0-9]{3}-)[0-9]{3}-[0-9]{4}'
```

* Admin API
* ADC
* Ingress Controller

Create a route that uses `ai-proxy` to proxy to OpenAI and `ai-prompt-guard` to inspect input prompts:

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

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

  --data-binary @- <<EOF

  {

    "id": "ai-prompt-guard-route",

    "uri": "/anything",

    "methods": ["POST"],

    "plugins": {

      "ai-proxy": {

        "provider": "openai",

        "auth": {

          "header": {

            "Authorization": "Bearer $OPENAI_API_KEY"

          }

        },

        "options":{

          "model": "gpt-4"

        }

      },

      "ai-prompt-guard": {

        "allow_patterns": [

          "$ALLOW_PATTERN_1"

        ],

        "deny_patterns": [

          "$DENY_PATTERN_1"

        ]

      }

    }

  }

EOF
```

❶ Specify the provider to be `openai`.

❷ Attach the OpenAI API key in the `Authorization` header as a Bearer token.

❸ Specify the name of the model.

❹ Allow message pattern that matches any dollar amounts.

❺ Deny message patterns that include any US phone number format.

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

adc.yaml

```
services:

  - name: prompt-guard-service

    routes:

      - name: prompt-guard-route

        uris:

          - /anything

        methods:

          - POST

        plugins:

          ai-proxy:

            provider: openai

            auth:

              header:

                Authorization: Bearer ${OPENAI_API_KEY}

            options:

              model: gpt-4

          ai-prompt-guard:

            allow_patterns:

              - \$?\(?\d{1,3}(,\d{3})*(\.\d{1,2})?\)?

            deny_patterns:

              - (\([0-9]{3}\)|[0-9]{3}-)[0-9]{3}-[0-9]{4}

    upstream:

      type: roundrobin

      nodes:

        - host: httpbin.org

          port: 80

          weight: 1
```

Preview the changes and confirm that they only affect resources for this guide:

```
adc diff -f adc.yaml \

  --include-resource-type service \

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

Synchronize the configuration to the gateway:

```
adc sync -f adc.yaml \

  --include-resource-type service \

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

❶ Specify the provider to be `openai`.

❷ Attach the OpenAI API key in the `Authorization` header as a Bearer token.

❸ Specify the name of the model.

❹ Allow message pattern that matches any dollar amounts.

❺ Deny message patterns that include any US phone number format.

* Gateway API
* APISIX CRD

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

ai-prompt-guard-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-prompt-guard-plugin-config

spec:

  plugins:

    - name: ai-prompt-guard

      config:

        allow_patterns:

          - \$?\(?\d{1,3}(,\d{3})*(\.\d{1,2})?\)?

        deny_patterns:

          - (\([0-9]{3}\)|[0-9]{3}-)[0-9]{3}-[0-9]{4}

    - name: ai-proxy

      config:

        provider: openai

        auth:

          header:

            Authorization: Bearer YOUR_LLM_API_KEY

        options:

          model: gpt-4

---

apiVersion: gateway.networking.k8s.io/v1

kind: HTTPRoute

metadata:

  namespace: aic

  name: prompt-guard-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-prompt-guard-plugin-config

      backendRefs:

        - name: httpbin-external-domain

          port: 80
```

Apply the configuration to your cluster:

```
kubectl apply -f ai-prompt-guard-ic.yaml
```

❶ Allow message pattern that matches any dollar amounts.

❷ Deny message patterns that include any US phone number format.

❸ Attach OpenAI API key in the `Authorization` header.

❹ Specify the name of the model.

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

ai-prompt-guard-ic.yaml

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

kind: ApisixRoute

metadata:

  namespace: aic

  name: prompt-guard-route

spec:

  ingressClassName: apisix

  http:

    - name: prompt-guard-route

      match:

        paths:

          - /anything

        methods:

          - POST

      plugins:

        - name: ai-prompt-guard

          enable: true

          config:

            allow_patterns:

              - '\$?\(?\d{1,3}(,\d{3})*(\.\d{1,2})?\)?'

            deny_patterns:

              - '(\([0-9]{3}\)|[0-9]{3}-)[0-9]{3}-[0-9]{4}'

        - name: ai-proxy

          enable: true

          config:

            provider: openai

            auth:

              header:

                Authorization: "Bearer YOUR_LLM_API_KEY"

            options:

              model: gpt-4
```

Apply the configuration to your cluster:

```
kubectl apply -f ai-prompt-guard-ic.yaml
```

❶ Allow message pattern that matches any dollar amounts.

❷ Deny message patterns that include any US phone number format.

❸ Attach OpenAI API key in the `Authorization` header.

❹ Specify the name of the model.

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 request to the route to rate the fairness of a purchase:

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

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

  -d '{

    "messages": [

      { "role": "system", "content": "Rate if the purchase is at a decent price in USD." },

      { "role": "user", "content": "John paid $12.5 for a hot brewed coffee in El Paso." }

    ]

  }'
```

You should receive an `HTTP/1.1 200 OK` response similar to the following:

```
{

  ...

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

  "choices": [

    {

      "index": 0,

      "message": {

        "role": "assistant",

        "content": "The purchase is not at a decent price. Typically, a hot brewed coffee costs anywhere from $1 to $3 in most places in the US, so $12.5 is quite expensive.",

        "refusal": null

      },

      "logprobs": null,

      "finish_reason": "stop"

    }

  ],

  ...

}
```

Send another request to the route without any price in the message:

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

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

  -d '{

    "messages": [

      { "role": "system", "content": "Rate if the purchase is at a decent price in USD." },

      { "role": "user", "content": "John paid a bit for a hot brewed coffee in El Paso." }

    ]

  }'
```

You should receive an `HTTP/1.1 400 Bad Request` response and see the following message:

```
{"message":"Request doesn't match allow patterns"}
```

Send a third request to the route with a phone number in the message:

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

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

  -d '{

    "messages": [

      { "role": "system", "content": "Rate if the purchase is at a decent price in USD." },

      { "role": "user", "content": "John (647-200-9393) paid $12.5 for a hot brewed coffee in El Paso." }

    ]

  }'
```

You should receive an `HTTP/1.1 400 Bad Request` response and see the following message:

```
{"message":"Request contains prohibited content"}
```

By default, the plugin only inspects the final message when its role is `user`. For instance, if you send a request including the prohibited content in the `system` prompt:

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

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

  -d '{

    "messages": [

      { "role": "system", "content": "Rate if the purchase from 647-200-9393 is at a decent price in USD." },

      { "role": "user", "content": "John paid $12.5 for a hot brewed coffee in El Paso." }

    ]

  }'
```

You will receive an `HTTP/1.1 200 OK` response.

If you send a request including the prohibited content in the second last message:

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

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

  -d '{

    "messages": [

      { "role": "system", "content": "Rate if the purchase is at a decent price in USD." },

      { "role": "user", "content": "Customer John contact: 647-200-9393" },

      { "role": "user", "content": "John paid $12.5 for a hot brewed coffee in El Paso." }

    ]

  }'
```

You will also receive an `HTTP/1.1 200 OK` response.

See the [next example](#validate-messages-from-all-roles-and-conversation-history) to see how to inspect messages from all roles and all messages.

### Validate Messages From All Roles and Conversation History[​](#validate-messages-from-all-roles-and-conversation-history "Direct link to Validate Messages From All Roles and Conversation History")

The following example demonstrates how to use the `ai-prompt-guard` plugin to validate prompts from all roles, such as `system` and `user`, and validate the entire conversation history instead of only the final message.

Define the allow and deny patterns. You can optionally save them to environment variables for easier escape:

```
export ALLOW_PATTERN_1='\\$?\\(?\\d{1,3}(,\\d{3})*(\\.\\d{1,2})?\\)?'

export DENY_PATTERN_1='(\\([0-9]{3}\\)|[0-9]{3}-)[0-9]{3}-[0-9]{4}'
```

* Admin API
* ADC
* Ingress Controller

Create a route that uses `ai-proxy` to proxy to OpenAI and `ai-prompt-guard` to inspect input prompts:

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

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

  --data-binary @- <<EOF

  {

    "id": "ai-prompt-guard-route",

    "uri": "/anything",

    "methods": ["POST"],

    "plugins": {

      "ai-proxy": {

        "provider": "openai",

        "auth": {

          "header": {

            "Authorization": "Bearer $OPENAI_API_KEY"

          }

        },

        "options":{

          "model": "gpt-4"

        }

      },

      "ai-prompt-guard": {

        "match_all_roles": true,

        "match_all_conversation_history": true,

        "allow_patterns": [

          "$ALLOW_PATTERN_1"

        ],

        "deny_patterns": [

          "$DENY_PATTERN_1"

        ]

      }

    }

  }

EOF
```

❶ Validate messages from all roles.

❷ Validate messages of the entire conversation.

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

adc.yaml

```
services:

  - name: prompt-guard-service

    routes:

      - name: prompt-guard-route

        uris:

          - /anything

        methods:

          - POST

        plugins:

          ai-proxy:

            provider: openai

            auth:

              header:

                Authorization: Bearer ${OPENAI_API_KEY}

            options:

              model: gpt-4

          ai-prompt-guard:

            match_all_roles: true

            match_all_conversation_history: true

            allow_patterns:

              - \$?\(?\d{1,3}(,\d{3})*(\.\d{1,2})?\)?

            deny_patterns:

              - (\([0-9]{3}\)|[0-9]{3}-)[0-9]{3}-[0-9]{4}

    upstream:

      type: roundrobin

      nodes:

        - host: httpbin.org

          port: 80

          weight: 1
```

Preview the changes and confirm that they only affect resources for this guide:

```
adc diff -f adc.yaml \

  --include-resource-type service \

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

Synchronize the configuration to the gateway:

```
adc sync -f adc.yaml \

  --include-resource-type service \

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

❶ Validate messages from all roles.

❷ Validate messages of the entire conversation.

* Gateway API
* APISIX CRD

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

ai-prompt-guard-history-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-prompt-guard-plugin-config

spec:

  plugins:

    - name: ai-prompt-guard

      config:

        match_all_roles: true

        match_all_conversation_history: true

        allow_patterns:

          - \$?\(?\d{1,3}(,\d{3})*(\.\d{1,2})?\)?

        deny_patterns:

          - (\([0-9]{3}\)|[0-9]{3}-)[0-9]{3}-[0-9]{4}

    - name: ai-proxy

      config:

        provider: openai

        auth:

          header:

            Authorization: Bearer YOUR_LLM_API_KEY

        options:

          model: gpt-4

---

apiVersion: gateway.networking.k8s.io/v1

kind: HTTPRoute

metadata:

  namespace: aic

  name: prompt-guard-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-prompt-guard-plugin-config

      backendRefs:

        - name: httpbin-external-domain

          port: 80
```

Apply the configuration to your cluster:

```
kubectl apply -f ai-prompt-guard-history-ic.yaml
```

❶ Validate messages from all roles.

❷ Validate messages of the entire conversation.

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

ai-prompt-guard-history-ic.yaml

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

kind: ApisixRoute

metadata:

  namespace: aic

  name: prompt-guard-route

spec:

  ingressClassName: apisix

  http:

    - name: prompt-guard-route

      match:

        paths:

          - /anything

        methods:

          - POST

      plugins:

        - name: ai-prompt-guard

          enable: true

          config:

            match_all_roles: true

            match_all_conversation_history: true

            allow_patterns:

              - '\$?\(?\d{1,3}(,\d{3})*(\.\d{1,2})?\)?'

            deny_patterns:

              - '(\([0-9]{3}\)|[0-9]{3}-)[0-9]{3}-[0-9]{4}'

        - name: ai-proxy

          enable: true

          config:

            provider: openai

            auth:

              header:

                Authorization: "Bearer YOUR_LLM_API_KEY"

            options:

              model: gpt-4
```

Apply the configuration to your cluster:

```
kubectl apply -f ai-prompt-guard-history-ic.yaml
```

❶ Validate messages from all roles.

❷ Validate messages of the entire conversation.

Send a request including with prohibited content in the `system` prompt:

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

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

  -d '{

    "messages": [

      { "role": "system", "content": "Rate if the purchase from 647-200-9393 is at a decent price in USD." },

      { "role": "user", "content": "John paid $12.5 for a hot brewed coffee in El Paso." }

    ]

  }'
```

You should receive an `HTTP/1.1 400 Bad Request` response and see the following message:

```
{"message":"Request contains prohibited content"}
```

Send a request with multiple messages from the same role with prohibited content:

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

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

  -d '{

    "messages": [

      { "role": "system", "content": "Rate if the purchase is at a decent price in USD." },

      { "role": "user", "content": "Customer John contact: 647-200-9393" },

      { "role": "user", "content": "John paid $12.5 for a hot brewed coffee in El Paso." }

    ]

  }'
```

You should receive an `HTTP/1.1 400 Bad Request` response and see the following message:

```
{"message":"Request contains prohibited content"}
```

Send a request that conforms to the patterns:

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

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

  -d '{

    "messages": [

      { "role": "system", "content": "Rate if the purchase is at a decent price in USD." },

      { "role": "system", "content": "The purchase is made in El Paso." },

      { "role": "user", "content": "Customer John contact: xxx-xxx-xxxx" },

      { "role": "user", "content": "John paid $12.5 for a hot brewed coffee." }

    ]

  }'
```

You should receive an `HTTP/1.1 200 OK` response similar to the following:

```
{

  ...,

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

  "choices": [

    {

      "index": 0,

      "message": {

        "role": "assistant",

        "content": "$12.5 is generally considered quite expensive for a cup of brew coffee.",

        "refusal": null

      },

      "logprobs": null,

      "finish_reason": "stop"

    }

  ],

  ...

}
```
