Enable AI Guardrails in AI Gateway

Updated at:

The AI Gateway described in this topic is the AI Gateway sub-product of Alibaba Cloud API Gateway. As an enterprise-level AI traffic hub, AI Gateway provides unified proxy for multiple models and efficiently manages MCP and agents, making LLM calls more controllable, secure, and cost-effective. After you integrate AI Guardrails with AI Gateway, the AI requests and responses that pass through the gateway are automatically checked for content security risks and blocked when necessary, without changing your application architecture. This topic describes the complete workflow from creating a guardrail configuration to associating it with a gateway instance.

Prerequisites

  1. Activate AI Gateway: Click Activate AI Gateway.

  2. Activate AI Guardrails: Click Activate AI Guardrails.

  3. Complete SLR authorization: You must complete the authorization for AI Gateway to access AI Guardrails in the AI Gateway console. For more information, see Step 2.

Workflow overview

The workflow consists of two steps: create a protection configuration in the AI Guardrails console, and then associate the configuration with the target instance in the AI Gateway console.

Step

Location

Description

Step 1

Create a protection configuration

In the AI Guardrails console, configure detection rules and protection actions. Configurations only take effect after they are successfully associated in AI Gateway.

Step 2

Associate the configuration

In the AI Gateway console, associate the guardrail configuration with the gateway instance. The configuration takes effect immediately.

Note

Differences from earlier versions: In earlier versions, all configurations were completed in the AI Gateway console. The new version moves detection and protection action configurations to the AI Guardrails console and fixes some known issues in earlier versions.

Step 1: Create a configuration in the AI Guardrails console

1.1 Go to the configuration page

  1. Log on to the AI Guardrails console.

  2. On the Overview page, find the AI Gateway icon. In the dialog box that appears when you hover over the icon, choose Access Management > Create Configuration.

1.2 Select the model protocol

In the Protocol Configuration section, select the required model protocol:

Option

Description

OpenAI

Models that are compatible with the OpenAI Chat Completions protocol.

Anthropic

Models that are compatible with the Anthropic Messages protocol.

Vertex AI

Google Vertex AI protocol.

1.3 Configure request checks (input)

After you turn on Check Request, configure the input-side check parameters:

Parameter

Description

Default value

Modality

The modality of the content to check, for example, Text.

Text

Mapped service

The corresponding check service.

query_security_check_pro, selectable from the drop-down list

Submission method

The text chunking method, for example, Chunk by character.

Chunk by character

Maximum character length

The maximum number of characters allowed in a single request.

100000; excess content is dropped.

Note

Queueing long texts for checks significantly affects latency. The excess-drop design lets you decide the balance between performance and effectiveness.

Chunk size

The number of characters in each check chunk.

2000; maximum 2000

Note

The chunk size affects the number of checks and is indirectly related to review costs, so proceed with caution. For typical input scenarios, a chunk size of 2000 is recommended.

Maximum concurrency

The concurrency for submitting chunks for checks.

2; maximum 5

If you need to check multiple modalities, such as text and images, click + Add Modality to add a row.

1.4 Configure response checks (output)

After you turn on Check Response, first select a Review Mode:

Review mode

Description

Available actions on response match

Use case

Review before delivery

Each output chunk is checked before it is returned to the user.

Block / Observe / Mask

For scenarios that require strict security and do not allow any non-compliant content to be displayed.

Review after delivery

Output chunks are returned to the user first and checked asynchronously. If a violation is detected, subsequent output is interrupted and a recall event is returned. Your business must handle the recall event.

Recall / Observe

For scenarios that require low latency and can tolerate brief display of non-compliant content before a recall.

Default response check parameters:

Parameter

Description

Default value

Modality

The modality of the content to check, for example, Text.

Text

Mapped service

The corresponding check service.

response_security_check_pro, selectable from the drop-down list

Submission method

The text chunking method, for example, Chunk by character.

Chunk by character

Maximum character length

The maximum number of characters allowed in a single request.

100000; excess content is dropped.

Note

Queueing long texts for checks significantly affects latency. The excess-drop design lets you decide the balance between performance and effectiveness.

Chunk size

The number of characters in each check chunk.

300; maximum 2000

Note

Output scenarios are generally streaming. The chunk size affects user experience and risk exposure time. A chunk size of 200 to 500 is recommended to balance semantics and user experience.

Maximum concurrency

The concurrency for submitting chunks for checks.

Review before delivery: default 2, maximum 5

Review after delivery: default 1, maximum 1

1.5 Configure protection actions

Click + Add Rule to create a protection action rule.

Protection dimensions (multiple selections allowed):

Protection dimension

Description

Content compliance

Non-compliant content such as political, pornographic, or violent content.

Sensitive data

Sensitive information such as personal privacy data and business secrets.

Custom masking

Masking of sensitive data based on custom rules.

Prompt attack

Detection of attacks such as prompt injection.

Malicious URL

Detection of malicious links and phishing websites.

Model hallucination

Detection of false information generated by the model.

Custom detection agent

Detection based on a custom large language model.

IP detection agent

Detection related to well-known IP addresses.

Important
  • Detection strategy configuration: In the AI Guardrails console, go to the Protection Configuration page to adjust the protection rules and thresholds for the corresponding service.

  • Protection action configuration: This page configures actions for specific protection dimensions. If a protection dimension is enabled in the detection strategy but not configured on this page, the default action is no action (allow).

Risk levels and actions:

Parameter

Available values

Description

Risk level

High risk / Medium risk / Low risk

The action is executed when a risk at this level is triggered.

Action on request match

Block / Observe / Mask

If a risk is detected in a request, the request is blocked and is not sent to the model.

Action on response match

Block / Recall / Observe / Mask

The action to take when a risk is detected in a response. Available values vary by submission method.

Blocking message

Custom text

The replacement text returned to the user when a response is blocked.

Note

Difference between recall and block: Block directly blocks a response and does not return it to the user. Recall returns the response first and then asynchronously notifies the client to recall it, and subsequent output is not returned to the user. In recall mode, the client must handle recall events. For more information, see Review after delivery details below.

In general, for non-streaming output, use review before delivery. For streaming output, use review after delivery.

After the configuration is complete, click Save.

Step 2: Associate the configuration in the AI Gateway console

  1. Log on to the AI Gateway console, go to the Instances page, select the region where the target instance is located from the top menu bar, and click the target instance.

    Important
    • AI Gateway automatically selects the nearest AI Guardrails region based on its own region. The mapping is shown in the following table. AI Guardrails in US (Virginia) does not support AI Gateway integration, so AI Gateway nodes in the United States are routed to Germany (Frankfurt).

      Gateway console region

      Guardrails console region

      Asia Pacific - China

      China (Shanghai)

      Asia Pacific - Others

      Singapore

      China (Hong Kong)

      China (Hong Kong)

      Europe and Americas

      Germany (Frankfurt)

      Other regions

      China (Shanghai)

  2. Find the instance that you want to configure and make sure that its engine version is 2.1.26 or later. If the version is earlier than 2.1.26, manually upgrade the instance on the instance page first.

  3. In the left-side navigation pane, click Model API, and then click the target API name to go to the API details page.

  4. Go to the API Details page and click the AI Guardrails section to edit it. If SLR authorization is not complete, follow the page prompts to complete the authorization and allow AI Gateway to access AI Guardrails.

  5. Select the configuration that you created in the AI Guardrails console in the previous step and associate it with the current gateway instance. If you are switching from an earlier configuration, manually switch to the new version.

  6. The configuration takes effect immediately after you save it. No restart or redeployment is required.

Important
  • The engine version of the AI Gateway instance must be 2.1.26 or later. Otherwise, you cannot associate a guardrail configuration.

  • If an earlier configuration exists before the engine version is upgraded, you must manually switch to the new version. If you do not need to switch, the earlier configuration still takes effect and is not affected.

  • AI Gateway supports configuring AI Guardrails protection policies per consumer. You can match consumers by the following rules and select different AI Guardrails configuration IDs from the drop-down list:

    • Any consumer: Applies to all consumers.

    • Exact match: Applies to the specified consumer.

    • Regex match: Applies to consumers that match the regular expression.

    • Prefix match: Applies to consumers that start with the specified prefix.

Review after delivery details

How it works

In review after delivery mode, the model response is immediately streamed back to the user while it is asynchronously sent to AI Guardrails for checking. If non-compliant content is detected, AI Guardrails returns a recall event. After the client receives the event, it performs the recall action and replaces the displayed non-compliant content with the blocking message.

Recall event format

If a response matches a protection rule, AI Guardrails appends the following event to the SSE stream:

data: {"id":"chatcmpl-xxxx","object":"chat.completion.chunk","created":1793104383,"model":"qwen-max","choices":[{"index":0,"delta":{"content":"The content is not compliant. The response has been recalled."},"finish_reason":"content_filter","x_guardrail":{"action":"recall","scope":"all","replace_text":"The content is not compliant. The response has been recalled."}}]}

data: [DONE]
          

Key fields:

Field

Description

finish_reason

The value content_filter indicates that the content was filtered for security.

x_guardrail.action

The value recall indicates that the client must perform a recall.

x_guardrail.scope

The value all indicates that all output that has been displayed must be recalled.

x_guardrail.replace_text

The text to display after the recall.

Client-side handling

When the client parses the SSE stream, it must handle recall events:

  1. Check whether choices[].finish_reason is content_filter.

  2. If the value is content_filter and x_guardrail.action is recall, clear the streamed content that has been displayed.

  3. Display the content of x_guardrail.replace_text to the user.

Frontend pseudocode:

// In the SSE streaming loop
for await (const chunk of stream) {
  const choice = chunk.choices?.[0];

  // Check for a recall event
  if (choice?.finish_reason === 'content_filter'
      && choice?.delta?.x_guardrail?.action === 'recall') {
    // Clear the displayed content
    clearDisplayedContent();
    // Display the replacement text
    displayText(choice.delta.x_guardrail.replace_text);
    break;
  }

  // Display the streamed content normally
  appendText(choice?.delta?.content);
}
          

AI Guardrails check latency comparison: review after delivery vs. review before delivery

The following data assumes the same chunk configuration: input chunk size 2000, concurrency 2, and output chunk size 300.

Review after delivery (recall mode):

Metric

Input 1000 characters

Output 1000 characters

Input 5000 characters

Output 5000 characters

Input 10000 characters

Output 10000 characters

TTFT increase

1 check

1 check

1 check

Response time increase

1 check

1 check

1 check

Review before delivery (block mode): The chunk configuration is input chunk size 2000, concurrency 20, and output chunk size 300.

Metric

Input 1000 characters

Output 1000 characters

Input 5000 characters

Output 5000 characters

Input 10000 characters

Output 10000 characters

TTFT increase

2 checks

4 checks

6 checks

Response time increase

4 checks

17 checks

34 checks

Note

Conclusion: Review after delivery has a significant advantage in both TTFT and response time, especially for long text. If your business can tolerate brief display of non-compliant content before a recall, we recommend that you use review after delivery.

Cautions

  • Configuration scope: One guardrail configuration can be associated with multiple gateway instances. After you modify the guardrail configuration, the changes take effect on all associated instances.

  • Switching the review mode: To switch between review before delivery and review after delivery, change the review mode in the AI Guardrails console. No change is required on the gateway side.

  • Custom detection agent latency: After you enable a custom detection agent, the check latency increases from about 200 ms to 200 ms to 2 s, depending on the model that you select. Choose the agent based on your latency requirements.

  • Recall events require client support: In review after delivery mode, recall actions require client-side handling. If the client does not implement recall logic, non-compliant content remains on the user interface.

  • AI Gateway engine version requirement: The engine version of the AI Gateway instance must be 2.1.26 or later. Otherwise, you cannot associate a guardrail configuration.

  • Migrating from an earlier version: If you are using an engine version earlier than 2.1.26 with guardrails enabled, manually upgrade the engine version first, and then perform the preceding two steps to complete the configuration. You must also manually switch to the new version on the guardrail configuration page in AI Gateway. Version switching cannot be reverted, so proceed with caution. We recommend that you add an instance, complete and verify the configuration, and then switch traffic.