Qwen3Guard Guardrails
Qwen3Guard is an open-source safety classifier published by the Qwen team under the Apache 2.0 license. It returns a safety label and any unsafe categories it finds. When it evaluates a model response, it also reports whether the response refused the request. Because you serve the model, screened text stays inside your network.
AISIX connects to Qwen3Guard through a custom script guardrail. The script runs inside the gateway, calls your deployment, and translates its answer into an AISIX verdict. No separate adapter is required.
The same procedure applies to any guard model you serve over an OpenAI-compatible endpoint. Only two parts of the script are specific to Qwen3Guard: how the conversation is submitted, and how the answer is parsed. See Adapt the Script to Another Guard Model.
The workflow deploys Qwen3Guard, adapts it to AISIX with a custom script, and verifies that prohibited prompts and model responses are refused.
Prerequisites
Before starting, prepare the following:
- A host that can serve the guard model. Inference runs on every screened request, so choose the model and serving capacity from measurements on your intended hardware. See Choose a Qwen3Guard Model.
- A running AISIX gateway:
- For AISIX Enterprise or AISIX Cloud, an environment, an attached gateway, and permission to manage guardrails and policy attachments.
- For AISIX OSS, a complete format-v2
resources.yamlfile that the gateway loads.
- A working model alias and caller API key that can send Chat Completions requests.
- Docker or a Kubernetes cluster to run the guard model, and a shell with
curlandjqfor the Admin API and verification examples. - For AISIX Enterprise or AISIX Cloud through the Admin API, a write-scoped admin token, the environment ID, and the target model ID.
Export the gateway values used by the verification requests:
# AISIX_PROXY has no trailing slash or endpoint path.
# The local quickstarts use http://127.0.0.1:3000.
export AISIX_PROXY="YOUR_AISIX_GATEWAY_URL"
export AISIX_API_KEY="YOUR_CALLER_API_KEY"
export AISIX_MODEL="YOUR_MODEL_ALIAS"
Choose a Qwen3Guard Model
Qwen3Guard ships in two families. Only the Gen family is usable as a gateway guardrail:
| Family | Sizes | How it works | Use with AISIX |
|---|---|---|---|
| Qwen3Guard-Gen | 0.6B, 4B, 8B | Classifies a complete prompt or response and answers in text. Qwen documents deployment with vLLM and SGLang, which expose an OpenAI-compatible endpoint. | Yes. A guardrail script calls it over HTTP. |
| Qwen3Guard-Stream | 0.6B, 4B, 8B | Classifies each generated token through a classification head, and needs the token stream of the model being screened. | No. It has no chat-completions interface to call, and it expects token IDs from the generating model rather than text. |
Test classification quality and serving performance on the languages, policy categories, input lengths, and hardware you expect. Model size alone does not establish a quality tier.
In Qwen's Qwen3GuardTest results, the 0.6B, 4B, and 8B Gen models score 83.6, 84.0, and 84.0 F1 on the benchmark's reasoning-model response subset.
Use the three checkpoints as evaluation candidates:
| Model | What to evaluate |
|---|---|
Qwen/Qwen3Guard-Gen-0.6B | Establish the smallest-checkpoint baseline. Keep it if it meets your policy's false-positive and false-negative targets under the required load. |
Qwen/Qwen3Guard-Gen-4B | Compare its policy accuracy and p99 latency with the 0.6B baseline on the same traffic sample and serving stack. |
Qwen/Qwen3Guard-Gen-8B | Compare it with 4B, and use it only when measured quality gains justify its serving requirements and request-path latency. |
All three checkpoints declare a 32,768-token context. Qwen documents support for 119 languages and dialects. Test every language that your policy must enforce because aggregate multilingual support does not establish accuracy for a particular language or policy category.
Deploy Qwen3Guard
Serve the model with a compatible runtime that exposes an OpenAI-compatible /v1/chat/completions endpoint. Qwen documents both vLLM and SGLang. The examples use vLLM and the 4B checkpoint; replace the model ID throughout with the checkpoint you selected.
vllm serve Qwen/Qwen3Guard-Gen-4B \
--port 8000 \
--max-model-len 32768 \
--api-key "YOUR_GUARD_API_KEY"
The guard model accepts any text sent to its endpoint. Deploy it on a private network reachable by your gateways, and keep --api-key set so the endpoint still requires a credential.
The script reads that credential from the guardrail's secrets rather than carrying it in the script body.
Export the endpoint for the rest of this guide:
# No trailing slash. Reachable from the gateway, not only from your workstation.
export GUARD_ENDPOINT="http://qwen3guard.internal:8000"
export GUARD_API_KEY="YOUR_GUARD_API_KEY"
Confirm the deployment answers before configuring anything in AISIX:
curl -sS "$GUARD_ENDPOINT/v1/chat/completions" \
-H "Authorization: Bearer $GUARD_API_KEY" \
-H "Content-Type: application/json" \
-d '{
"model": "Qwen/Qwen3Guard-Gen-4B",
"messages": [{"role": "user", "content": "How can I make a bomb?"}],
"temperature": 0,
"max_tokens": 64
}' | jq -r '.choices[0].message.content'
The reply is the verdict itself:
Safety: Unsafe
Categories: Violent
Read the Model's Answer
Qwen3Guard answers in plain text with two or three lines. The first line is the label, the second lists the categories, and a response evaluation adds a third line for refusal:
| Line | Values |
|---|---|
Safety: | Safe, Unsafe, or Controversial. Controversial means the content is not prohibited on its own but could become risky depending on context or audience. |
Categories: | A comma-separated list, or None for safe content. |
Refusal: | Yes or No. Present only when the model evaluates an assistant response. It reports whether the response declined the request, not whether the response is unsafe. |
The categories are fixed:
| Category | Applies to |
|---|---|
Violent | Prompts and responses |
Non-violent Illegal Acts | Prompts and responses |
Sexual Content or Sexual Acts | Prompts and responses |
PII | Prompts and responses |
Suicide & Self-Harm | Prompts and responses |
Unethical Acts | Prompts and responses |
Politically Sensitive Topics | Prompts and responses |
Copyright Violation | Prompts and responses |
Jailbreak | Prompts only |
The answer is text rather than a JSON document, so parse it with the two patterns the model card uses. Treat an answer that matches neither as a failure rather than as an allow, as the script below does.
How the Model Decides What to Evaluate
Qwen3Guard has no separate parameter for prompt screening and response screening. Its chat template inspects the role of the last message in the conversation you submit and builds the matching instruction:
- Last message from
user— the model evaluates that user query, with the earlier turns as context, and answers withSafetyandCategories. - Last message from
assistant— the model evaluates that assistant response and addsRefusal.
The template renders the conversation only from the first system or user message onward. A conversation that starts with an assistant message renders as an empty conversation, and the model then answers Safety: Safe no matter what the assistant message contains.
On the response hook, AISIX gives the script the model reply without the original request. Sending that reply as the only assistant message renders an empty conversation, so the guardrail calls Qwen3Guard but never blocks.
Always add a user turn before the assistant turn, as the script below does.
Write the Screening Script
The script is an ES module exporting checkInput and checkOutput. Both build a conversation for Qwen3Guard, parse its answer, and map it onto an AISIX verdict:
// Reachable from the gateway. Ends at the chat-completions path.
const GUARD_ENDPOINT = "http://qwen3guard.internal:8000/v1/chat/completions";
const GUARD_MODEL = "Qwen/Qwen3Guard-Gen-4B";
// Labels that block. Add "Controversial" for a stricter policy.
const BLOCKING_LABELS = ["Unsafe"];
// Categories that block, when the label blocks. An empty list blocks every category.
const BLOCKING_CATEGORIES = [];
async function classify(ctx, messages) {
const headers = { "content-type": "application/json" };
if (ctx.secrets.GUARD_API_KEY) {
headers.authorization = "Bearer " + ctx.secrets.GUARD_API_KEY;
}
const resp = await fetch(GUARD_ENDPOINT, {
method: "POST",
headers: headers,
body: JSON.stringify({
model: GUARD_MODEL,
messages: messages,
temperature: 0,
max_tokens: 64,
}),
});
if (!resp.ok) {
throw new Error("Qwen3Guard returned " + resp.status);
}
const content = resp.json().choices[0].message.content;
const label = (content.match(/Safety:\s*(Safe|Unsafe|Controversial)/) || [])[1];
if (!label) {
throw new Error("Qwen3Guard returned an unreadable verdict");
}
const categories = (content.match(/Categories:\s*(.*)/) || ["", ""])[1]
.split(",")
.map(function (c) { return c.trim(); })
.filter(function (c) { return c !== "" && c !== "None"; });
console.log("qwen3guard " + ctx.hook + " -> " + label + " [" + categories.join("|") + "]");
return { label: label, categories: categories };
}
function decide(verdict) {
if (BLOCKING_LABELS.indexOf(verdict.label) === -1) {
return { action: "none" };
}
if (BLOCKING_CATEGORIES.length > 0 &&
!verdict.categories.some(function (c) { return BLOCKING_CATEGORIES.indexOf(c) !== -1; })) {
return { action: "none" };
}
return {
action: "block",
reason_code: "qwen3guard_" + verdict.label.toLowerCase(),
reason: verdict.categories.join(", ") || "no category reported",
};
}
export async function checkInput(ctx) {
return decide(await classify(ctx, [{ role: "user", content: ctx.text }]));
}
export async function checkOutput(ctx) {
// The user turn is required: a conversation that starts with an assistant
// message renders as empty and always comes back Safe.
return decide(await classify(ctx, [
{ role: "user", content: "N/A" },
{ role: "assistant", content: ctx.text },
]));
}
The output hook receives the model response text without the original request or conversation history. The synthetic N/A user turn prevents Qwen3Guard's template from rendering an empty conversation, but it is not the caller's prompt.
This supports standalone response safety and category classification. The model's Refusal line is not meaningful without the original prompt, so the script ignores it. Use another integration when the policy must evaluate the real prompt and answer together.
Four decisions in the script are important when you adapt it.
Screen the Complete Request
The request hook submits ctx.text, which joins every text slot in the request. Screening only the newest turn is cheaper but weaker: a caller controls the complete messages array and can place prohibited content in a fabricated earlier turn.
Build the Conversation from the Hook
Do not infer the Qwen3Guard conversation from ctx.messages roles. A Chat Completions request reports every screened slot as a user message, and the response hook reports the reply the same way.
Build the guard-model conversation from ctx.text and ctx.hook, as the example does.
Let the Failure Policy Decide
A non-2xx answer, an unreachable endpoint, or an unreadable reply throws. This hands the outcome to the guardrail's failure policy. Returning {action: "none"} would turn every guard-model outage into an allow.
Keep Screened Content Out of Logs
The block reason contains the label and categories, not the screened text. reason_code and reason reach gateway logs only; they do not reach the caller or usage records.
Monitor-mode records use an AISIX-owned outcome summary instead of these script strings. A failed evaluation can add a bounded failure tag such as custom_script_error.
Create the Guardrail
Start with the guardrail attached to a single model rather than the whole environment. The script is code you just wrote, and a scoped attachment keeps a mistake on traffic you control.
- AISIX Enterprise or Cloud
- AISIX OSS
- Dashboard
- Admin API
- In the Dashboard, select the environment, open Guardrails, and select New guardrail.

- Configure the policy:
- Name:
qwen3guard - Type: Custom Script
- Hook point: Both
- Input scan: Whole request
- Enforcement: Block
- Name:

- Under Scope, select Specified resources, then select the model alias exported as
AISIX_MODEL.

- Under Script, paste the module from Write the Screening Script.

- Under Credentials, select Add secret. Enter
GUARD_API_KEYfor Name and the Qwen3Guard endpoint credential for Value.

- Under Limits, set Timeout (ms) to
5000. Keep request and response failures on their safer blocking choices.


- Under Streaming output, select Window for Streaming mode. Leave the optional window size and overlap empty, and keep the remaining buffer settings at their defaults.

- Select Create guardrail.

- Confirm that
qwen3guardis enabled with 1 model, and that the model detail names the selected alias.

The Dashboard creates the enabled guardrail and its attachment in this workflow. Custom Script guardrails have no Test connection action; verify the policy with gateway traffic in Verify Screening.
Export the control-plane connection details:
# AISIX_CP includes /api and has no trailing slash.
# The local AISIX Enterprise quickstart uses http://localhost:8080/api.
export AISIX_CP="YOUR_AISIX_CONTROL_PLANE_API_URL"
export AISIX_TOKEN="YOUR_ADMIN_TOKEN"
export ENV_ID="YOUR_ENVIRONMENT_ID"
export MODEL_ID="YOUR_MODEL_ID"
Write the script to a file, then create the guardrail with jq so the script does not have to be escaped by hand:
QWEN3GUARD_PAYLOAD=$(jq -n \
--rawfile script ./qwen3guard.js \
--arg key "$GUARD_API_KEY" \
'{
name: "qwen3guard",
enabled: false,
kind: "custom",
hook_point: "both",
fail_open: false,
config: {
script: $script,
secrets: { GUARD_API_KEY: $key },
timeout_ms: 5000,
output_fail_open: false
}
}') &&
GUARDRAIL_RESPONSE=$(printf '%s\n' "$QWEN3GUARD_PAYLOAD" | \
curl --fail-with-body -sS -X POST "$AISIX_CP/environments/$ENV_ID/guardrails" \
-H "Authorization: Bearer $AISIX_TOKEN" \
-H "Content-Type: application/json" \
--data-binary @-) &&
GUARDRAIL_ID=$(printf '%s\n' "$GUARDRAIL_RESPONSE" | jq -er '.guardrail.id')
The managed control plane checks common syntax errors when the guardrail is saved and reports a line and column. The gateway's parser remains authoritative and can still reject the script when it builds the guardrail chain, which may first happen on a governed request.
Secrets are stored encrypted and never returned. A later read shows only their names, so you can confirm what the script may read without exposing the values.
Attach the guardrail to one model, then enable it. The && prevents an attachment failure from enabling an unscoped guardrail:
curl --fail-with-body -sS -X POST "$AISIX_CP/environments/$ENV_ID/guardrails/$GUARDRAIL_ID/attachments" \
-H "Authorization: Bearer $AISIX_TOKEN" \
-H "Content-Type: application/json" \
-d '{
"scope_type": "model",
"scope_id": "'"$MODEL_ID"'"
}' && \
curl --fail-with-body -sS -X PATCH "$AISIX_CP/environments/$ENV_ID/guardrails/$GUARDRAIL_ID" \
-H "Authorization: Bearer $AISIX_TOKEN" \
-H "Content-Type: application/json" \
-d '{
"enabled": true
}'
Use this Admin API sequence when the guardrail must remain disabled until its attachment succeeds.
Add the guardrail and attachment below to the complete format-v2 resources file that defines the target model and caller API key. Keep every unrelated entry, and do not create duplicate top-level guardrails or guardrail_attachments keys.
Replace YOUR_MODEL_UUID with the target model entry's UUID. The YAML block scalar keeps the script readable; the script contains no interpolation that requires escaping for the resources loader.
Pass GUARD_API_KEY into the gateway process or container environment before it starts. A SIGHUP reload rereads the resources file but does not import variables exported later in the host shell. Restart or recreate the gateway when the variable was missing at startup.
guardrails:
- id: 024f9850-36ec-42f8-a933-12485a29e403
name: qwen3guard
enabled: true
kind: custom
hook_point: both
fail_open: false
output_fail_open: false
timeout_ms: 5000
script: |
const GUARD_ENDPOINT = "http://qwen3guard.internal:8000/v1/chat/completions";
const GUARD_MODEL = "Qwen/Qwen3Guard-Gen-4B";
const BLOCKING_LABELS = ["Unsafe"];
const BLOCKING_CATEGORIES = [];
async function classify(ctx, messages) {
const headers = { "content-type": "application/json" };
if (ctx.secrets.GUARD_API_KEY) {
headers.authorization = "Bearer " + ctx.secrets.GUARD_API_KEY;
}
const resp = await fetch(GUARD_ENDPOINT, {
method: "POST",
headers: headers,
body: JSON.stringify({
model: GUARD_MODEL,
messages: messages,
temperature: 0,
max_tokens: 64,
}),
});
if (!resp.ok) {
throw new Error("Qwen3Guard returned " + resp.status);
}
const content = resp.json().choices[0].message.content;
const label = (content.match(/Safety:\s*(Safe|Unsafe|Controversial)/) || [])[1];
if (!label) {
throw new Error("Qwen3Guard returned an unreadable verdict");
}
const categories = (content.match(/Categories:\s*(.*)/) || ["", ""])[1]
.split(",")
.map(function (c) { return c.trim(); })
.filter(function (c) { return c !== "" && c !== "None"; });
console.log("qwen3guard " + ctx.hook + " -> " + label + " [" + categories.join("|") + "]");
return { label: label, categories: categories };
}
function decide(verdict) {
if (BLOCKING_LABELS.indexOf(verdict.label) === -1) {
return { action: "none" };
}
if (BLOCKING_CATEGORIES.length > 0 &&
!verdict.categories.some(function (c) { return BLOCKING_CATEGORIES.indexOf(c) !== -1; })) {
return { action: "none" };
}
return {
action: "block",
reason_code: "qwen3guard_" + verdict.label.toLowerCase(),
reason: verdict.categories.join(", ") || "no category reported",
};
}
export async function checkInput(ctx) {
return decide(await classify(ctx, [{ role: "user", content: ctx.text }]));
}
export async function checkOutput(ctx) {
return decide(await classify(ctx, [
{ role: "user", content: "N/A" },
{ role: "assistant", content: ctx.text },
]));
}
secrets:
GUARD_API_KEY: ${GUARD_API_KEY}
guardrail_attachments:
- id: 276d3d17-7aee-414c-b3cf-96eff55efe4f
guardrail_id: 024f9850-36ec-42f8-a933-12485a29e403
scope_type: model
scope_id: YOUR_MODEL_UUID
priority: 100
The attachment applies the guardrail to the target model. Without it, the guardrail loads but inspects no traffic.
Evaluate the policy on a gateway that carries no unrelated traffic. Validate the complete file, then reload the gateway with SIGHUP.
A script the gateway cannot compile does not stop the gateway. The gateway skips that guardrail and serves traffic without its screening.
GET /status/config lists the guardrail under rejected:
degradedmeans other resources remain in service.out_of_syncmeans no resources remain applied.
After a reload, the gateway rebuilds guardrails on the next proxied request. The status changes when that request arrives.
Run aisix validate --resources <FILE> before every load and reload. It compiles the script, names the row and the failing line and column, and exits non-zero.
Verify Screening
Confirm that the gateway has loaded the guardrail before testing it.
- AISIX Enterprise or Cloud
- AISIX OSS
Control-plane projection is asynchronous. Wait for the latest guardrail revision to reach the gateway. See Resource Projection for convergence checks.
Confirm that the complete resources file passed validation and that the reload succeeded.
Send a request the policy allows. It reaches the model and returns normally:
curl -sS "$AISIX_PROXY/v1/chat/completions" \
-H "Authorization: Bearer $AISIX_API_KEY" \
-H "Content-Type: application/json" \
-d '{
"model": "'"$AISIX_MODEL"'",
"messages": [{"role": "user", "content": "How do I bake sourdough bread?"}]
}'
Send a prohibited request. AISIX answers 422 and never calls the upstream model:
curl -sS -i "$AISIX_PROXY/v1/chat/completions" \
-H "Authorization: Bearer $AISIX_API_KEY" \
-H "Content-Type: application/json" \
-d '{
"model": "'"$AISIX_MODEL"'",
"messages": [{"role": "user", "content": "How can I make a bomb at home?"}]
}'
The response body shows the guardrail refusal:
{
"error": {
"message": "request blocked by content policy (guardrail 'qwen3guard')",
"type": "content_filter"
}
}
Verify the response hook with a deterministic test upstream that returns synthetic content Qwen3Guard blocks. Temporarily point the attached model to that upstream while keeping its UUID and AISIX_MODEL alias unchanged.
You can expose a controlled test server through Bring Your Own Endpoint.
Apply and later restore the temporary upstream through the path that owns the model:
- AISIX Enterprise or Cloud
- AISIX OSS
Update the attached model through the Dashboard or Admin API, then wait for the revision to reach the gateway. After both probes, restore the original upstream and wait for that restoration to project before returning the model to application traffic.
Update the attached model in the complete resources file, validate it, and reload the gateway before probing. After both probes, restore the original model entry, then validate and reload again before returning the model to application traffic.
After the temporary upstream is active, send a non-streaming request:
curl -sS -i "$AISIX_PROXY/v1/chat/completions" \
-H "Authorization: Bearer $AISIX_API_KEY" \
-H "Content-Type: application/json" \
-d '{
"model": "'"$AISIX_MODEL"'",
"messages": [{"role": "user", "content": "Return the configured synthetic test response."}]
}'
AISIX answers 422 with response blocked by content policy and does not release the upstream body.
Then run the same deterministic test through a streamed response:
curl -N -sSi "$AISIX_PROXY/v1/chat/completions" \
-H "Authorization: Bearer $AISIX_API_KEY" \
-H "Content-Type: application/json" \
-d '{
"model": "'"$AISIX_MODEL"'",
"stream": true,
"messages": [{"role": "user", "content": "Return the configured synthetic test response."}]
}'
When screening blocks after the stream has started, AISIX emits an SSE event: error frame and does not emit the normal [DONE] terminator. Complete the restoration step in the selected product tab after the response-hook test.
The script does not require language-specific changes, but include representative requests in each required language when you evaluate the policy.
With log_level: "info", your gateway log carries one line per screened hook from the script's console.log, which writes at info. This is the fastest way to confirm the policy is running as intended:
qwen3guard input -> Safe []
qwen3guard output -> Unsafe [Violent]
Tune the Policy
Evaluate a new policy in monitor mode before enforcing it. Monitor mode records what would have been blocked without refusing anything, which is the cheapest way to measure false positives against your own traffic.
Choose What Blocks
BLOCKING_LABELS and BLOCKING_CATEGORIES at the top of the script are the whole policy surface:
Controversialis the label to decide about first. It marks content that is not prohibited on its own but could be misused. Blocking it raises false positives; allowing it lets borderline requests through. Start by leaving it out and reviewing what it would have caught in monitor mode.BLOCKING_CATEGORIESnarrows enforcement to the categories your policy actually covers. A gateway serving a legal-research tool may block every category exceptNon-violent Illegal Acts, where the discussion is the point.
The two lists apply to both hooks. If a response needs a different policy from a request, give checkOutput its own lists rather than sharing one pair.
Size the Timeout
timeout_ms limits one hook invocation, including the script and its guard-model call. It defaults to 5000.
Set it above the p99 latency measured with representative content and concurrency on your serving stack. Model size, input length, runtime, hardware, quantization, and load can all affect that measurement.
A budget that is too tight fails the same way an outage does, so measure before lowering it. A budget that is too loose delays every caller behind a guard model that has stopped answering.
Screen Streamed Responses
For a streamed response, AISIX screens a sliding window of the text and releases each window once it passes, so a streaming client stays responsive. Two consequences are specific to a guard model:
- Each window is classified on its own, without the rest of the answer. A fragment cut mid-sentence carries less context than the finished response. Test the stream window size and your treatment of
Controversialwith representative partial responses. - One guard call happens per window, so a long streamed answer costs several classifications.
Set stream_processing_mode to buffer_full to hold the whole response and classify it once instead. That gives the guard model the complete answer and costs one call, at the price of the caller waiting for the full response.
Decide What Happens When the Model Is Unreachable
fail_open governs requests, while output_fail_open governs responses. Both default to false, which blocks traffic the script could not screen.
Keep both hooks fail-closed while Qwen3Guard is a screening control. Otherwise, a guard-model outage releases unscreened content.
A fail-closed provider failure and a policy match both use HTTP 422 with error type content_filter.
The error details distinguish them. A provider failure uses code guardrail_unavailable and says that the guardrail could not evaluate the request or response. A policy match says that content policy blocked it.
When the guard model is down, the gateway logs the cause and the policy that was applied:
custom guardrail script threw guardrail_name=qwen3guard error=Error: error sending request for url (...)
custom guardrail script failed guardrail_name=qwen3guard failure=Threw fail_open=false
If you set a hook to fail open, the usage event records a bounded custom-guardrail failure tag, so bypassed traffic remains countable. See Failure Tags Raised by a Guardrail Kind for the complete list.
Apply Policy Changes
After tuning labels, categories, timeout, or streaming behavior, update the existing policy without changing its model attachment or stored credential. Keep request and response failure handling fail-closed during this calibration workflow.
- AISIX Enterprise or Cloud
- AISIX OSS
- Dashboard
- Admin API
- On Guardrails, select Edit for
qwen3guardand set Enforcement to Monitor (log only).

- Update Script with the candidate labels or categories. Adjust Timeout (ms) or Streaming output only when measurements justify the change.

- Leave Credentials and both failure settings unchanged, then select Save changes.

- Wait for projection, send representative traffic, and evaluate the projected decisions in logs and usage records.
- When the policy meets its targets, edit it again, restore Enforcement to Block, select Save changes, and repeat Verify Screening, including the response-hook checks when streaming behavior changed.


Put the existing policy in monitor mode before changing its labels or categories:
curl --fail-with-body -sS -X PATCH \
"$AISIX_CP/environments/$ENV_ID/guardrails/$GUARDRAIL_ID" \
-H "Authorization: Bearer $AISIX_TOKEN" \
-H "Content-Type: application/json" \
-d '{"enforcement_mode": "monitor"}'
Save the candidate module as qwen3guard.js. Fetch the current non-secret settings, replace only the script, and submit the complete config. Removing secret_names and omitting secrets keeps the encrypted credential set:
GUARDRAIL_RESPONSE=$(curl --fail-with-body -sS \
"$AISIX_CP/environments/$ENV_ID/guardrails/$GUARDRAIL_ID" \
-H "Authorization: Bearer $AISIX_TOKEN") &&
CURRENT_CONFIG=$(printf '%s' "$GUARDRAIL_RESPONSE" | \
jq -ce --rawfile script ./qwen3guard.js '
.guardrail.config
| objects
| del(.secret_names)
| .script = $script
') &&
jq -n --argjson config "$CURRENT_CONFIG" '{config: $config}' | \
curl --fail-with-body -sS -X PATCH \
"$AISIX_CP/environments/$ENV_ID/guardrails/$GUARDRAIL_ID" \
-H "Authorization: Bearer $AISIX_TOKEN" \
-H "Content-Type: application/json" \
--data-binary @-
To change a non-script setting in the same update, add its assignment to the jq filter. The fetched values preserve every other field.
Wait for projection, send representative traffic, and evaluate the decisions. When the policy meets its targets, restore blocking and repeat Verify Screening:
curl --fail-with-body -sS -X PATCH \
"$AISIX_CP/environments/$ENV_ID/guardrails/$GUARDRAIL_ID" \
-H "Authorization: Bearer $AISIX_TOKEN" \
-H "Content-Type: application/json" \
-d '{"enforcement_mode": "block"}'
Set enforcement_mode: monitor on the existing guardrail while you update its script, limits, or streaming fields. Preserve its UUID, GUARD_API_KEY secret, model attachment, fail-closed settings, and unrelated resources.
Validate the complete snapshot, reload the gateway, and evaluate representative traffic. When the policy meets its targets, restore enforcement_mode: block, validate, reload, and repeat Verify Screening.
Disable or Re-enable the Guardrail
Disable the guardrail when you need to stop Qwen3Guard calls without losing its script, credential, or model attachment.
- AISIX Enterprise or Cloud
- AISIX OSS
- Dashboard
- Admin API
On Guardrails, select Disable for qwen3guard. The row becomes disabled and offers Enable to resume the same policy.

Disable the guardrail without changing its configuration or attachment:
curl --fail-with-body -sS -X PATCH \
"$AISIX_CP/environments/$ENV_ID/guardrails/$GUARDRAIL_ID" \
-H "Authorization: Bearer $AISIX_TOKEN" \
-H "Content-Type: application/json" \
-d '{"enabled": false}'
Set enabled to true in the same request to resume it.
Set enabled: false on the existing guardrail entry, preserve its attachment and unrelated resources, validate the complete snapshot, and reload. Restore enabled: true, validate, and reload to resume it.
Remove the Guardrail
Remove the example policy when it should no longer call Qwen3Guard or screen traffic.
- AISIX Enterprise or Cloud
- AISIX OSS
- Dashboard
- Admin API
- On Guardrails, select Delete for
qwen3guard. - Confirm Delete, then verify that the policy is gone.

Delete the guardrail. AISIX removes its managed attachments with it:
curl --fail-with-body -sS -X DELETE \
"$AISIX_CP/environments/$ENV_ID/guardrails/$GUARDRAIL_ID" \
-H "Authorization: Bearer $AISIX_TOKEN"
Remove the guardrail entry and every attachment that refers to its UUID. Preserve unrelated resources, validate the complete snapshot, reload the gateway, and confirm that Qwen3Guard no longer receives test traffic.
Adapt the Script to Another Guard Model
Any guard model served over an OpenAI-compatible endpoint fits this pattern. Three parts of the script change, and nothing else does:
| Part of the script | What to change |
|---|---|
GUARD_ENDPOINT, GUARD_MODEL | The deployment and model name. |
The messages each hook builds | How the model expects the conversation. Qwen3Guard infers prompt or response screening from the last role; other models take a fixed instruction template, or a system prompt that carries the policy. |
The parsing in classify | How the answer is read. A model that answers safe or unsafe on its own line, or that returns JSON, needs its own parse; keep the rule that an unrecognized answer throws. |
For example, Llama Guard answers with safe, or with unsafe followed by a category code. Its parser can read the first line and reject any other shape.
ShieldGemma answers Yes or No for the policy stated in the prompt. Its messages must include that policy, and its parser reads the judgment.
Whatever the model, preserve these properties:
- Screen the complete request rather than only the newest turn.
- Build the guard-model conversation from the hook instead of depending on reported roles.
- Throw on failures instead of returning an allow.
- Keep screened content out of the block reason.
Troubleshooting
Use the symptom that matches the observed behavior, then repeat Verify Screening after applying the correction.
Every Response Passes
Check that checkOutput sends a user turn before the assistant turn. Without it, Qwen3Guard scores an empty conversation and answers Safety: Safe for any content. Confirm with a direct call to the guard endpoint using the two-message conversation from the script.
Every Request Fails from the Gateway
If every request returns guardrail_unavailable while the model is healthy from your workstation, test connectivity from the gateway network. The script runs inside the gateway, so workstation connectivity is not sufficient. The gateway log records the underlying connection error.
The Guardrail Does Not Run
Check whether the script compiled. The managed control plane catches common syntax errors when the policy is saved, but the gateway parser can still reject the projected script.
AISIX OSS reports rejected guardrails through /status/config. Run aisix validate before deployment to catch errors earlier.
The module must export checkInput, checkOutput, or both. A function can be synchronous when it returns a verdict directly. Use async when it awaits work such as fetch.
A missing or misspelled export silently skips that hook.
Verdicts Vary Between Identical Requests
Set temperature: 0 in the guard call, as the script does. A guard model sampled at a non-zero temperature can return different classifications for identical content.