The AI Gateway described in this topic is the AI Gateway sub-product of Alibaba Cloud API Gateway. As an enterprise-grade AI traffic hub, AI Gateway provides unified multi-model proxying and efficient management of MCP and Agents, making LLM calls more controllable, secure, and cost-effective. Integrating AI Guardrails with AI Gateway automatically performs content security detection and risk interception on AI requests and responses passing through the gateway, without modifying your business architecture. This topic describes the complete process from creating a guardrail configuration to associating it with a gateway instance.
Prerequisites
-
Activate AI Gateway: Click Activate AI Gateway.
-
Activate AI Guardrails: Click Activate AI Guardrails.
-
Complete SLR authorization: You need to complete the authorization for AI Gateway to call AI Guardrails in the AI Gateway console. This can be done in Step 2 below.
Integration process overview
The overall process consists of two steps: first create a protection configuration in the AI Guardrails console, then associate the configuration with the target instance in the AI Gateway console.
|
Step |
Operation location |
Description |
|
Step 1 |
Create a protection configuration |
Configure detection rules and protection disposition policies in the AI Guardrails console. Simply saving a new configuration does not make it take effect; the configuration takes effect only after it is successfully associated in AI Gateway. |
|
Step 2 |
Associate the configuration |
Associate the guardrail configuration with the gateway instance in the AI Gateway console. It takes effect immediately. |
Differences from the previous version: In the previous version, all configuration was completed in the AI Gateway console. The new version consolidates detection configuration and protection disposition in the AI Guardrails console and fixes some known issues of the previous version.
Step 1: Create a configuration in the AI Guardrails console
1.1 Go to the configuration page
-
Log on to the AI Guardrails console.
-
On the Provisioning page, switch to AI Gateway at the top of the page, and click Add Configuration.
1.2 Select the model protocol
In the "Protocol Configuration" section, select the required model protocol:
|
Option |
Description |
|
OpenAI |
Models compatible with the OpenAI Chat Completions protocol. |
|
Anthropic |
Models compatible with the Anthropic Messages protocol. |
|
Vertex AI |
The Google Vertex AI protocol. |
1.3 Configure request detection (input)
After you turn on the Detection Request switch, configure the detection parameters on the input side:
|
Parameter |
Description |
Default value |
|
Modality |
The content modality to detect, such as Text. |
Text |
|
Mapped Service |
The corresponding detection service. |
|
|
Submission Method |
The text slicing method, such as Slice by character. |
Slice by character |
|
Maximum character length |
The maximum number of characters allowed per request. |
100000. The excess is discarded. Note
Queuing overly long text for moderation significantly affects latency. The discard-on-excess design lets you decide the balance between performance and effectiveness. |
|
Slice size |
The number of characters per detection slice. |
2000, maximum 2000 Note
Smaller slices result in more moderation calls and higher moderation fees. The input scenario is non-streaming, so a slice size of 2000 is generally recommended; there is no need to make it smaller. |
|
Maximum concurrency |
The concurrency of slice moderation submissions. |
2, maximum 5 |
To detect multiple modalities (such as text and images), click + Add Modality to add a row.
1.4 Configure output detection (response)
After you turn on the Detection Output switch, first select the Review Mode:
|
Review mode |
Description |
Available response hit actions |
Applicable scenario |
|
Synchronous moderation |
The output content first undergoes security moderation and is returned to the gateway only after it passes. Content that fails moderation is handled according to the policy configured below. In streaming scenarios, the system first accumulates content up to the configured slice size, then performs security moderation on the slice. |
Block / Observe / Mask |
Extremely high security requirements where no non-compliant content may be exposed, and a certain amount of detection latency is tolerable. |
|
Asynchronous moderation |
The output content is returned to the gateway immediately while security moderation runs asynchronously in the background. If moderation fails, subsequent output is blocked and the already-returned content is handled according to the policy configured below (if Recall is configured, the business frontend must handle the recall event for it to take effect). In streaming scenarios, this method does not affect the user's streaming output experience. The system asynchronously accumulates content up to the configured slice size in the background and then performs security moderation. The last slice is forced to undergo synchronous moderation to ensure that all slices are detected. |
Recall / Observe |
Pursues low latency and a streaming output experience, allowing brief display of non-compliant content before recall. |
Default values for output detection parameters:
|
Parameter |
Description |
Default value |
|
Modality |
The content modality to detect, such as Text. |
Text |
|
Mapped Service |
The corresponding detection service. |
|
|
Submission Method |
The text slicing method, such as Slice by character. |
Slice by character |
|
Maximum character length |
The maximum number of characters allowed per request. |
100000. The excess is discarded. Note
Queuing overly long text for moderation significantly affects latency. The discard-on-excess design lets you decide the balance between performance and effectiveness |
|
Slice size |
The number of characters per detection slice. |
300, maximum 2000 Note
The output scenario is generally streaming. The slice size affects user experience and the time risky content is exposed. A slice size between 200 and 500 is generally recommended to balance semantics and user experience. |
|
Maximum concurrency |
The concurrency of slice moderation submissions. |
Under synchronous moderation: default 2, maximum 5 Under asynchronous moderation: default 1, maximum 1 |
1.5 Configure protection disposition
Click + Add Rule to create a protection disposition rule.
Protection dimensions (multiple selection):
|
Protection dimension |
Description |
|
Content compliance |
Non-compliant content such as political, pornographic, and violent or terrorist content. |
|
Sensitive data |
Sensitive information such as personal privacy and trade secrets. |
|
Custom Data Masking |
Sensitive data masking 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. |
|
Customize Detection Agent |
Detection based on a custom large model. |
|
IP Detection Agent |
Detection related to well-known IPs. |
-
Detection policy configuration: On the AI Guardrails console -> Protection Config page, you can adjust the protection rules and thresholds for the corresponding service.
-
Protection disposition configuration: This page configures the disposition for specific protection dimensions. If a protection dimension is enabled in the detection policy but not configured on the protection disposition page, no disposition is applied by default, that is, the content is allowed.
Risk levels and actions:
|
Parameter |
Available values |
Description |
|
Risk level |
High risk / Medium risk / Low risk |
The disposition is executed when this risk level is triggered. |
|
Request hit action |
Block / Observe / Mask |
When a risk is detected in the request, the request is blocked and not sent to the model. |
|
Response hit action |
Block / Recall / Observe / Mask |
The handling method when a risk is detected in the response. Available values differ by submission method. |
|
Block message |
Custom text |
The replacement text returned to the user when blocked. |
Difference between Recall and Block: Block directly blocks the response and does not return it to the user. Recall first returns the response, then asynchronously notifies the client to recall it, and subsequent output is not returned to the user. Recall mode requires the client to handle the recall event. For details, see Asynchronous moderation details below.
In general, we recommend synchronous moderation for non-streaming output scenarios and asynchronous moderation for streaming output scenarios.
After the configuration is complete, click Save.
Step 2: Associate the configuration in the AI Gateway console
-
Log on to the AI Gateway console, open the Instance page, select the region of the target instance in the top menu bar, and click the target Instance ID.
Important-
AI Gateway automatically selects the nearest corresponding AI Guardrails region based on its own region. The mapping logic is shown in the following table. In addition, the US (Virginia) region of AI Guardrails does not support AI Gateway integration, so when an AI Gateway node is located in the US, it is routed to the Germany (Frankfurt) region of AI Guardrails.
Gateway console region
Guardrails console region
Asia Pacific - China
China (Shanghai)
Asia Pacific - Other
Singapore
China (Hong Kong)
China (Hong Kong)
Europe and Americas
Germany (Frankfurt)
Other regions
China (Shanghai)
-
-
Find the instance to configure and confirm that the engine version is 2.1.26 or later. If the version is earlier than this requirement, manually upgrade it on the instance page first.
-
In the left-side navigation pane, click Model API, then click the target API Name to go to the API Details page.
-
On the API details page, click the AI Guardrails edit area to expand the configuration. If SLR authorization is not completed, follow the on-screen instructions to complete the authorization, allowing AI Gateway to access the AI Guardrails service.
-
Select the configuration created in the AI Guardrails console in the previous step and associate it with the current gateway instance. If you are switching from an old configuration, you need to manually switch to the new version.
-
It takes effect immediately after saving, without restarting or redeploying.
-
The engine version of the AI Gateway instance must be 2.1.26 or later; otherwise, the guardrail configuration cannot be associated.
-
If an old configuration already exists before the engine version upgrade, you need to manually switch to the new version. If you do not need to switch, the old configuration still takes effect and is not affected.
-
AI Gateway supports configuring AI Guardrails protection policies by consumer. You can match consumers according to the following rules and select different AI Guardrails configuration IDs from the drop-down list.
-
Any consumer: Takes effect for all consumers.
-
Exact match: Takes effect for the specified consumer.
-
Regex match: Takes effect for consumers that match the regular expression.
-
Prefix match: Takes effect for consumers that start with the specified prefix.
-
Asynchronous moderation details
How it works
In Asynchronous moderation mode, the response content generated by the model is immediately streamed back to the user while being asynchronously submitted to AI Guardrails for detection. If non-compliant content is detected, AI Guardrails returns a recall event. After receiving it, the client performs the recall action and replaces the displayed non-compliant content with the block message.
Recall event format
When a response hits 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 non-compliant and the response has been recalled."},"finish_reason":"content_filter","x_guardrail":{"action":"recall","scope":"all","replace_text":"The content is non-compliant and the response has been recalled."}}]}
data: [DONE]
Description of key fields:
|
Field |
Description |
|
|
The value is |
|
|
The value is |
|
|
The value is |
|
|
The text displayed as a replacement after recall. |
Client handling logic
When parsing the SSE stream, the client needs to add handling for recall events:
-
Check whether
choices[].finish_reasoniscontent_filter. -
If it is
content_filterandx_guardrail.actionisrecall, clear the displayed streaming content. -
Display the content of
x_guardrail.replace_textto the user.
Frontend pseudocode reference:
// In the SSE streaming loop
for await (const chunk of stream) {
const choice = chunk.choices?.[0];
// Detect the 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;
}
// Normal streaming display
appendText(choice?.delta?.content);
}
AI Guardrails moderation latency comparison: asynchronous vs. synchronous
Assume the slice configuration is: input slice 2000, concurrency 2, output slice 300.
Asynchronous moderation (Recall mode):
|
Metric |
Input 1000 characters Output 1000 characters |
Input 5000 characters Output 5000 characters |
Input 10000 characters Output 10000 characters |
|
TTFT increase |
Latency of 1 moderation call |
Latency of 1 moderation call |
Latency of 1 moderation call |
|
Response latency increase |
Latency of 1 moderation call |
Latency of 1 moderation call |
Latency of 1 moderation call |
Synchronous moderation (Block mode):
|
Metric |
Input 1000 characters Output 1000 characters |
Input 5000 characters Output 5000 characters |
Input 10000 characters Output 10000 characters |
|
TTFT increase |
Latency of 2 moderation calls |
Latency of 3 moderation calls |
Latency of 4 moderation calls |
|
Response latency increase |
Latency of 4 moderation calls |
Latency of 17 moderation calls |
Latency of 34 moderation calls |
Conclusion: Asynchronous moderation has significant advantages in both TTFT and large model response latency, especially in long-text scenarios where the gap is larger. If your business allows brief display of non-compliant content before recall, we recommend prioritizing asynchronous moderation.
Notes
-
Configuration scope: One guardrail configuration can be associated with multiple gateway instances. After you modify the guardrail configuration, all associated instances take effect synchronously.
-
Review mode switching: Simply modify the review mode (switch between synchronous and asynchronous moderation) in the AI Guardrails console. No changes are needed on the gateway side.
-
Customize Detection Agent latency: After you enable Customize Detection Agent, the detection latency increases from about 200 ms to between 200 ms and 2 s (depending on the selected model). Choose appropriately based on your business latency requirements.
-
Recall events depend on the client: In asynchronous moderation mode, the recall action requires the client to handle it. If the client does not implement recall logic, non-compliant content remains in the user interface.
-
AI Gateway engine version requirement: The engine version of the AI Gateway instance must be 2.1.26 or later; otherwise, the guardrail configuration cannot be associated.
-
Switching from an old version: If you are using an engine version earlier than 2.1.26 with guardrails enabled, you need to manually upgrade the engine version first, then perform the two steps above to complete the configuration, and manually switch to the new version on the guardrail configuration page of AI Gateway. Version switching cannot be rolled back, so proceed with caution. We also recommend adding a new instance and completing configuration verification before switching traffic.