Skip to main content
Version: 1.13.0

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.yaml file 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 curl and jq for 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:

FamilySizesHow it worksUse with AISIX
Qwen3Guard-Gen0.6B, 4B, 8BClassifies 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-Stream0.6B, 4B, 8BClassifies 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:

ModelWhat to evaluate
Qwen/Qwen3Guard-Gen-0.6BEstablish 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-4BCompare its policy accuracy and p99 latency with the 0.6B baseline on the same traffic sample and serving stack.
Qwen/Qwen3Guard-Gen-8BCompare 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:

LineValues
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:

CategoryApplies to
ViolentPrompts and responses
Non-violent Illegal ActsPrompts and responses
Sexual Content or Sexual ActsPrompts and responses
PIIPrompts and responses
Suicide & Self-HarmPrompts and responses
Unethical ActsPrompts and responses
Politically Sensitive TopicsPrompts and responses
Copyright ViolationPrompts and responses
JailbreakPrompts 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 with Safety and Categories.
  • Last message from assistant — the model evaluates that assistant response and adds Refusal.
caution

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.

  1. In the Dashboard, select the environment, open Guardrails, and select New guardrail.
Guardrails page with New guardrail outlined
  1. Configure the policy:
    • Name: qwen3guard
    • Type: Custom Script
    • Hook point: Both
    • Input scan: Whole request
    • Enforcement: Block
Qwen3Guard Custom Script policy with both hooks, whole-request input, and blocking enforcement outlined
  1. Under Scope, select Specified resources, then select the model alias exported as AISIX_MODEL.
Guardrail scope with Specified resources selected and the docs-research-model checkbox outlined
  1. Under Script, paste the module from Write the Screening Script.
Script panel with the Qwen3Guard screening module outlined
  1. Under Credentials, select Add secret. Enter GUARD_API_KEY for Name and the Qwen3Guard endpoint credential for Value.
Credentials panel with the GUARD_API_KEY name and masked synthetic value outlined
  1. Under Limits, set Timeout (ms) to 5000. Keep request and response failures on their safer blocking choices.
Custom Script timeout, optional memory limit, and fail-closed response setting outlined
Fail-closed request setting outlined
  1. 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.
Window streaming mode and optional window and buffer fields outlined
  1. Select Create guardrail.
Create guardrail action outlined
  1. Confirm that qwen3guard is enabled with 1 model, and that the model detail names the selected alias.
Saved Qwen3Guard policy showing enabled status, one-model scope, one credential, and the selected model detail

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.

Verify Screening​

Confirm that the gateway has loaded the guardrail before testing it.

Control-plane projection is asynchronous. Wait for the latest guardrail revision to reach the gateway. See Resource Projection for convergence checks.

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:

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.

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:

  • Controversial is 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_CATEGORIES narrows enforcement to the categories your policy actually covers. A gateway serving a legal-research tool may block every category except Non-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 Controversial with 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.

  1. On Guardrails, select Edit for qwen3guard and set Enforcement to Monitor (log only).
Qwen3Guard enforcement set to Monitor log only and outlined
  1. Update Script with the candidate labels or categories. Adjust Timeout (ms) or Streaming output only when measurements justify the change.
Qwen3Guard script editor showing Controversial in the blocking labels
  1. Leave Credentials and both failure settings unchanged, then select Save changes.
Save changes action outlined
  1. Wait for projection, send representative traffic, and evaluate the projected decisions in logs and usage records.
  2. 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.
Qwen3Guard enforcement restored to Block and outlined
Save changes action outlined

Disable or Re-enable the Guardrail​

Disable the guardrail when you need to stop Qwen3Guard calls without losing its script, credential, or model attachment.

On Guardrails, select Disable for qwen3guard. The row becomes disabled and offers Enable to resume the same policy.

Disabled Qwen3Guard policy with one-model scope and Enable outlined

Remove the Guardrail​

Remove the example policy when it should no longer call Qwen3Guard or screen traffic.

  1. On Guardrails, select Delete for qwen3guard.
  2. Confirm Delete, then verify that the policy is gone.
Delete confirmation naming qwen3guard with Delete outlined

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 scriptWhat to change
GUARD_ENDPOINT, GUARD_MODELThe deployment and model name.
The messages each hook buildsHow 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 classifyHow 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.