# Guardrail Policy Behavior

Every AISIX guardrail follows the same policy model. A hook point decides when it runs, and attachments decide which traffic it covers. Enforcement mode determines whether a match affects the request or response. Provider-specific settings determine how the selected content is evaluated.

Route and field coverage can narrow what a policy sees after these shared controls apply. See [Guardrail Content Coverage](https://docs.api7.ai/ai-gateway/traffic-controls/guardrails/content-coverage.md) for those boundaries, [Streaming Guardrail Behavior](https://docs.api7.ai/ai-gateway/traffic-controls/guardrails/streaming-behavior.md) for output hold-back, and [Guardrail Failure Handling](https://docs.api7.ai/ai-gateway/traffic-controls/guardrails/failure-handling.md) for unavailable checks.

## Guardrail Hook Point[​](#guardrail-hook-point "Direct link to Guardrail Hook Point")

Every guardrail runs at one of three hook points. The selected hook determines which side of the exchange AISIX evaluates and where a blocking verdict takes effect:

| Hook Point | What AISIX Checks                      | Effect of a Blocking Match                                 |
| ---------- | -------------------------------------- | ---------------------------------------------------------- |
| `input`    | The caller request before dispatch.    | AISIX rejects the request without contacting the upstream. |
| `output`   | The upstream response before delivery. | AISIX withholds the matching response from the caller.     |
| `both`     | Both request and response content.     | AISIX applies the same guardrail on both supported sides.  |

Not every route supports both hooks, and some fields are intentionally outside coverage. See [Guardrail Content Coverage](https://docs.api7.ai/ai-gateway/traffic-controls/guardrails/content-coverage.md) for the route and field matrix.

## Choose the Input Message Window[​](#choose-the-input-message-window "Direct link to Choose the Input Message Window")

Input guardrails can inspect the complete request history or only the active turn. The `input_messages` setting selects that window without changing the request AISIX sends to the model.

| Value         | Messages Available to the Input Check                                                                                                                                   |
| ------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `all`         | The complete request, including system, developer, user, assistant, and tool messages. This is the default.                                                             |
| `latest_turn` | Messages after the last assistant message. System and developer messages are excluded. The remaining window contains current-turn user messages and their tool results. |

Use `latest_turn` for IDE and agent clients that resend the complete conversation on every request. It avoids screening history the model has already answered. Keep `all` when the policy must inspect or mask the complete conversation.

The window is selected before any guardrail-kind-specific role filter. For example, semantic screening can apply `text_source` after `input_messages` has selected the conversation window.

### Current-Turn Boundaries[​](#current-turn-boundaries "Direct link to Current-Turn Boundaries")

When `latest_turn` is selected, AISIX finds the turn boundary from the assistant and tool structures used by each protocol:

| Protocol           | Assistant Turns                                                                | Current-Turn Tool Results                                  |
| ------------------ | ------------------------------------------------------------------------------ | ---------------------------------------------------------- |
| Chat Completions   | Assistant messages                                                             | `tool` messages                                            |
| Anthropic Messages | Assistant messages                                                             | `tool_result` blocks                                       |
| Responses          | Assistant messages, `function_call`, `custom_tool_call`, and `reasoning` items | `function_call_output` and `custom_tool_call_output` items |

A trailing assistant message is a prefill supplied for the model to continue, so AISIX keeps it in the current-turn window. A request with no assistant message keeps every non-system and non-developer message.

If a client resends a blocked message without an assistant reply between attempts, the message remains in the latest turn and can match again.

A Guardrail Rewrites Only Its Window

A masking guardrail can rewrite only content available inside its message window. Under `latest_turn`, earlier history is forwarded unchanged. Use `all` when historical PII or secrets must be masked before dispatch.

### Configure the Window[​](#configure-the-window "Direct link to Configure the Window")

The message window can be configured through each management interface. Output-only guardrails do not expose this setting because output checks always inspect the complete response.

In the Dashboard, choose **Whole request** or **Latest turn only** under **Input scan**. The setting appears for `input` and `both` hook points.

Through the Admin API, set `input_messages` on the guardrail. In a format-v2 resources file, set it on the guardrail entry:

resources.yaml (guardrail entry)

```
guardrails:

  - id: a9174a5c-c7b3-424a-a327-ee3d6b0848cf

    name: block-secrets

    kind: keyword

    hook_point: input

    input_messages: latest_turn

    patterns:

      - kind: literal

        value: internal-project-codename
```

## Guardrail Matching[​](#guardrail-matching "Direct link to Guardrail Matching")

Attachments place a guardrail in the request path. They determine which environment, resource, or caller context the guardrail can inspect.

| Product                         | How to Set Scope                                                                                                                                                                    |
| ------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| AISIX Enterprise or AISIX Cloud | Create attachments for the environment, model alias, MCP server, passthrough route, caller API key, or team. One definition can have several attachments with different priorities. |
| AISIX OSS                       | Declare the guardrail and its entries in `guardrail_attachments` in the format-v2 resources file.                                                                                   |

A guardrail with no attachments is valid but inspects no traffic. The Dashboard labels it **Not attached**, and the gateway logs one warning that names it.

Attach Before Enabling

Deleting the last attachment disables the guardrail's effect without widening its scope. Creating a guardrail through the Admin API does not create an attachment automatically; create the attachment before enabling the guardrail. The Dashboard performs both operations when you choose a scope during creation.

### Scope Compatibility[​](#scope-compatibility "Direct link to Scope Compatibility")

Attachment scopes can overlap. One request can match the environment, caller API key, team, and one destination attachment:

* A model request can match a model attachment but never an MCP-server attachment.
* An MCP tool call can match an MCP-server attachment but resolves no model.
* A passthrough request can match its route attachment but resolves neither a model nor an MCP server.
* An A2A call resolves no model, MCP server, or passthrough route. Only environment, caller API key, and team attachments cover it.

To cover several destination types, attach the guardrail to the environment or add one attachment for each resource.

### Attachment Priority and Duplicate Matches[​](#attachment-priority-and-duplicate-matches "Direct link to Attachment Priority and Duplicate Matches")

When a request matches several guardrails, AISIX evaluates them as one chain. A blocking verdict from any guardrail blocks the request or response.

When the same guardrail matches through several control-plane attachments, AISIX keeps one copy. The highest numerical attachment priority wins. At equal priority, the more specific scope wins in this order:

1. Caller API key
2. Team
3. Model alias, MCP server, or passthrough route
4. Environment

Model aliases, MCP servers, and passthrough routes have equal specificity because one request cannot resolve more than one of them.

### Guardrail Scope Follows the Addressed Model[​](#guardrail-scope-follows-the-addressed-model "Direct link to Guardrail Scope Follows the Addressed Model")

Model-scoped policies follow the alias the caller addressed, not the target selected later by a routing or ensemble model.

For a routing, semantic-routing, or ensemble request, attach the guardrail to the group itself. A guardrail attached only to a member model runs when the caller addresses that member directly, but not when the group dispatches traffic to it.

A wildcard model is also the addressed model. A guardrail attached to `openai/*` covers requests served by that wildcard until an exact alias takes precedence. After an exact `openai/gpt-4o` alias is created, requests for that name use only attachments on the exact alias.

## Enforcement Modes[​](#enforcement-modes "Direct link to Enforcement Modes")

Enforcement mode determines whether a verdict changes traffic or is recorded only for evaluation. Start in monitor mode when the policy still needs production validation:

| Mode      | Match Behavior                                                                                  | Recommended Use                                         |
| --------- | ----------------------------------------------------------------------------------------------- | ------------------------------------------------------- |
| `block`   | Blocks matching input or output. A supported mask action rewrites content. This is the default. | Enforce a validated policy.                             |
| `monitor` | Allows content unchanged and records what enforcement would have done.                          | Measure matches and false positives before enforcement. |

Monitor mode records the guardrail name, hook, and expected action on the usage event:

* `would_block` for a blocking verdict
* `would_mask` with safe detector counts for supported masking
* `would_mask_unsupported` when the surface cannot apply a mask

When evaluation fails, `would_block` also includes a bounded failure tag such as `custom_timeout`. It does not include screened content or a script-provided reason. Custom scripts use the fixed count name `custom` and the number of text segments that would change.

With gateway `log_level: "info"`, a would-block observation also writes:

```
guardrail in monitor mode observed a violation; not blocking (enforcement_mode=monitor)
```

After evaluating representative traffic, change the policy to `block`. See [Guardrail Failure Handling](https://docs.api7.ai/ai-gateway/traffic-controls/guardrails/failure-handling.md#how-monitor-mode-handles-failures) for how monitor mode interacts with unavailable checks.

## Observe Policy Outcomes[​](#observe-policy-outcomes "Direct link to Observe Policy Outcomes")

After evaluation, usage events record which guardrails applied, whether a guardrail blocked the request, monitor-mode observations, and the first fail-open bypass reason. AISIX records these fields whether the request succeeds, fails upstream, or is refused by policy.

Guardrail-specific fields contain policy names, actions, bounded failure tags, and safe detector counts. They do not copy matched content or script-provided reasons. See [What the Gateway Records](https://docs.api7.ai/ai-gateway/traffic-controls/guardrails/overview.md#what-the-gateway-records) for surrounding request data that other logging or export settings can retain.

See [Caller Responses](https://docs.api7.ai/ai-gateway/traffic-controls/guardrails/failure-handling.md#caller-responses) for protocol-specific refusal shapes and [Interpret Bypass Reasons](https://docs.api7.ai/ai-gateway/traffic-controls/guardrails/failure-handling.md#interpret-bypass-reasons) for fail-open evidence.

## Guardrail Metrics[​](#guardrail-metrics "Direct link to Guardrail Metrics")

Guardrail metrics complement the outcome stored on each usage event. `aisix_guardrail_latency_seconds` records timed executions and labels them by guardrail name, kind, phase, result, and bounded failure type.

Use the histogram to compare local and remote guardrail latency and to monitor blocked, bypassed, and monitor-mode outcomes. Windowed streaming can record several executions for one response; synchronous per-field keyword and PII masking is not timed.

A fail-closed evaluation keeps `result="blocked"`; its `error_type` distinguishes an unavailable check from an ordinary policy match. Ordinary matches use `error_type="none"`.

The bypass counter and latency histogram cover different populations. See [Interpret Bypass Reasons](https://docs.api7.ai/ai-gateway/traffic-controls/guardrails/failure-handling.md#interpret-bypass-reasons) for the distinction and [Metrics Reference](https://docs.api7.ai/ai-gateway/reference/metrics.md#measure-guardrail-latency-and-outcomes) for labels and PromQL examples.

To measure first-frame delay introduced by output guardrails, compare the downstream and upstream series of `aisix_request_ttft_seconds`. See [Separate Gateway Wait from Upstream TTFT](https://docs.api7.ai/ai-gateway/reference/metrics.md#separate-gateway-wait-from-upstream-ttft).

## Validate the Complete Policy[​](#validate-the-complete-policy "Direct link to Validate the Complete Policy")

Shared policy controls are only the first part of an enforceable guardrail. Before enabling block mode, confirm that the target route and fields are supported in [Guardrail Content Coverage](https://docs.api7.ai/ai-gateway/traffic-controls/guardrails/content-coverage.md).

For output policies, account for [streaming hold-back](https://docs.api7.ai/ai-gateway/traffic-controls/guardrails/streaming-behavior.md) and decide whether [unavailable checks](https://docs.api7.ai/ai-gateway/traffic-controls/guardrails/failure-handling.md) should stop or bypass traffic. Together, these decisions determine how the policy behaves in production.
