Table of Contents
- Adding LLM Guardrails to a Multimodal Chatbot with Qwen3Guard
- Qwen3Guard Model Details
- Building a Gradio Multimodal Chatbot with Response Moderation
- Step 1: Installing Required Dependencies
- Step 2: Importing Libraries and Utilities
- Step 3: Loading Qwen3-VL and Qwen3Guard-Gen with Transformers
- Step 4: Testing AI Content Moderation on Chatbot Responses
- Step 5: Adding Qwen3Guard Response Filtering to the Gradio Interface
- Step 6: Launching the Safe Gradio Chatbot
- Example: How the Chatbot Blocks a Flagged Response
- Summary
Adding LLM Guardrails to a Multimodal Chatbot with Qwen3Guard
As artificial intelligence (AI) systems become increasingly powerful and widely deployed, ensuring their safety has emerged as one of the most critical challenges in the field. While the chatbots we have built in the previous lessons demonstrate impressive capabilities in understanding text and images, they lack a crucial component: the ability to detect and filter harmful content. Without proper safeguards, AI systems can be manipulated to generate dangerous instructions, spread misinformation, or produce content that violates ethical guidelines and societal norms. This is where Qwen3Guard enters the picture, providing state-of-the-art safety moderation capabilities that protect both users and service providers from harmful AI interactions.
Qwen3Guard represents a comprehensive safety solution that addresses 2 fundamental limitations of existing guard models. First, most guard models implement rigid, one-size-fits-all safety policies that fail to account for the diverse deployment scenarios where context matters. Qwen3Guard introduces a 3-tiered severity classification system (Safe, Controversial, and Unsafe) that enables fine-grained control over safety thresholds.
Content labeled as Controversial might be acceptable in some applications but blocked in others, allowing developers to tailor safety policies to their specific use cases.
Second, many guard models require a complete response before they can assess it, which prevents them from moderating individual tokens as they are generated.
- Generative Qwen3Guard (Qwen3Guard-Gen): Safety classification of complete user prompts and model responses
- Stream Qwen3Guard (Qwen3Guard-Stream): Token-level monitoring of model responses during generation
In this lesson, we extend our multimodal chatbot from Lessons 1 and 2 by integrating Qwen3Guard’s safety moderation capabilities. We will evaluate assistant responses before displaying them to users.
Through practical implementation, we will learn how to detect multiple categories of harmful content including violence, illegal activities, sexual content, personally identifiable information (PII), self-harm content, unethical acts, politically sensitive topics, copyright violations, and jailbreak attempts. The Generative variant will provide detailed classification results with specific risk categories, while the safety checks will run transparently in the background, blocking the display of responses flagged as Unsafe or Controversial.
By the end of this lesson, we will have a multimodal chatbot that checks assistant responses for harmful content before displaying them.
This lesson is the 3rd in a 4-part series on Building with Qwen3 Models:
- Building an Intelligent Chatbot with Qwen3 Instruct and Thinking Models
- Building a Multimodal Chatbot with Qwen3-VL Instruct and Thinking Models
- Adding LLM Guardrails to a Multimodal Chatbot with Qwen3Guard (this tutorial)
- Lesson 4
To learn about Qwen3 and build intelligent applications from scratch, just keep reading.
Qwen3Guard Model Details
Qwen3Guard-Gen vs. Qwen3Guard-Stream
Qwen3Guard comprises 2 specialized variants designed to address different aspects of safety moderation: Qwen3Guard-Gen and Qwen3Guard-Stream. Both variants build upon Qwen3 foundation models and are available with 0.6 billion, 4 billion, or 8 billion parameters to accommodate various deployment scenarios and resource constraints. The architectural innovations in each variant reflect their distinct use cases: comprehensive classification for the Generative model and real-time streaming detection for the Stream model.
Qwen3Guard-Gen reformulates safety classification as an instruction-following task, leveraging the natural language understanding and generation capabilities of the base LLM. Rather than adding classification heads or specialized layers, Qwen3Guard-Gen processes safety queries as natural language instructions and generates structured responses in text format.
Given a prompt or response to evaluate, the model receives instructions that include the task definition (classify input as safe, controversial, or unsafe), the safety policy defining each category, the specific safety categories to check, and output formatting requirements (Figure 1).

The model then generates a structured response containing the safety assessment (Safe/Unsafe/Controversial), the relevant safety categories for Unsafe or Controversial content (Violent, Illegal Acts, Sexual Content, PII, Self-Harm, Unethical Acts, Politically Sensitive, Copyright Violation, or Jailbreak), and, for response classification, whether the assistant refused to answer the query.
This generative approach offers several advantages. First, it enables flexible, customizable safety policies without retraining. Developers can modify instructions to emphasize certain categories or adjust severity thresholds. Second, the model can provide explanations for its classifications, improving interpretability and trust. Third, it naturally extends to multilingual scenarios since the base model already supports 119 languages. The generative paradigm means Qwen3Guard-Gen behaves like a sophisticated conversation partner that understands nuanced safety requirements and can adapt its assessments based on contextual information provided in the prompt.
Qwen3Guard-Stream (Figure 2) employs a fundamentally different architecture optimized for real-time token-level classification during streaming generation. Built on the same Qwen3 base models, Qwen3Guard-Stream adds 2 specialized classification heads to the final transformer layer: a Prompt Moderator head that evaluates incoming user queries and a Response Moderator head that assesses each generated token in real time.

The architecture extracts the last hidden state from the backbone model and processes it through 2 parallel pathways, one for analyzing responses and one for queries. Each pathway includes a pre-processing layer with layer normalization, followed by 2 classification layers: one predicting the risk level (Safe, Controversial, or Unsafe) and another predicting the specific safety category.
The mathematical formulation captures this dual-head design elegantly. For each token, the model computes:
and
and
and
where is the last hidden state from the backbone,
matrices are learnable weights, and
tensors are probability distributions over risk levels and safety categories for responses (
) and queries (
), respectively.
The key innovation enabling Qwen3Guard-Stream’s real-time capabilities is its token-level operation. Unlike Qwen3Guard-Gen, which must wait for complete text, Qwen3Guard-Stream evaluates each token as it is generated, computing safety classifications in parallel with model generation.
If the model begins generating unsafe content, Qwen3Guard-Stream can detect it within 1 or 2 tokens, allowing the application to halt generation. A debouncing mechanism ensures stability: content is flagged as unsafe starting from token only if both token
and its predecessor
are classified as
Unsafe or Controversial, preventing spurious false positives from single-token anomalies.
Both variants support the 3-tiered severity classification (Safe, Controversial, Unsafe) and the 9 safety categories defined in Qwen3Guard’s comprehensive policy. The choice between the Gen and Stream variants depends on application requirements: Qwen3Guard-Gen provides more detailed, explainable classifications suitable for batch processing, content moderation reviews, and scenarios where complete context is available.
Qwen3Guard-Stream enables real-time protection during live interactions, making it ideal for chatbots, streaming assistants, and applications where low latency is critical. In practice, both can be used together: Qwen3Guard-Gen for comprehensive prompt analysis before generation begins, and Qwen3Guard-Stream for real-time monitoring during response generation.
Training Data and Safety Labels
Training Qwen3Guard required developing a massive, high-quality dataset covering diverse languages, safety categories, and severity levels. The dataset comprises over 1.19 million samples including both human-annotated and synthetically generated data.
The data distribution spans 14 major languages plus many others, with Chinese (26.64%) and English (21.9%) as the largest segments, followed by Korean (9.91%), Indonesian (5.38%), Russian (5.36%), Japanese (4.82%), Arabic (4.71%), and others. The data is roughly balanced between prompt classification (41.2%) and response classification (58.8%), ensuring the model learns to evaluate both user inputs and assistant outputs effectively.
To ensure comprehensive coverage of all safety categories, Qwen3Guard employs sophisticated data synthesis strategies. For prompt synthesis, the team adopted the Self-Instruct framework, first decomposing the safety policy into a fine-grained taxonomy and collecting seed prompts for each category. Large language models then generated additional examples based on these seeds.
The team used 2 complementary strategies to enhance data quality: keyword-guided synthesis where generation was conditioned on category-specific keywords (e.g., “bomb,” “TNT,” “C4” for explosives), and paired positive-negative examples that share surface structure but differ in safety (“How to make a bomb” vs “How to make a cake”). This pairing prevents the model from learning spurious correlations between innocent words and safety labels.
For response collection, the data includes both human-authored content and model-generated responses from various sources. Special emphasis was placed on 2 challenging categories: unsafe responses generated using base models (rather than safety-aligned instruct models) to ensure the guard learns to detect harmful content that might occasionally slip through alignment training, and responses with reasoning content from models such as QwQ (Qwen with Questions) and Qwen3-Thinking, preparing the guard to moderate the explicit thinking processes that these models generate. This is particularly important as reasoning models become more prevalent, requiring guards that can evaluate not just final answers but also intermediate reasoning steps that might reveal problematic logic or biases.
Multilingual coverage was achieved through 2 mechanisms: direct collection of safety data in multiple languages, particularly Chinese and English, and translation of existing data to 15 additional languages using Qwen-MT (machine translation). Translation quality was validated through language mixing detection, LLM judges evaluating naturalness and safety label preservation, and random sampling with manual review. This multilingual approach ensures Qwen3Guard can protect users across linguistic boundaries, a critical requirement for globally deployed AI systems.
A major challenge in training Qwen3Guard-Stream was converting coarse sample-level labels into fine-grained token-level annotations. The team developed an automated annotation method combining rollout-based safety assessment and LLM-as-judge verification. For each unsafe sample, the method iterates through tokens to find where unsafe content begins. For token , it constructs prefix
containing all tokens up to
and generates multiple rollout continuations.
If at least 85% of rollouts are classified as Unsafe by Qwen3Guard-Gen, token is flagged. However, rollouts can overestimate risk. Even safe tokens might lead to unsafe continuations due to model behavior. Therefore, an LLM judge (Qwen3-235B-A22B) verifies each flagged token, assessing whether prefix
itself is unsafe rather than predicting future content. Only when both rollout assessment and judge verification agree is token
marked as the unsafe boundary, with all subsequent tokens inheriting the sample-level label.
Training follows specialized objectives for each variant. Qwen3Guard-Gen uses standard supervised fine-tuning (SFT) loss, optimizing the model to generate correctly formatted classification responses. The instruction-following nature means it learns from the full context of each safety evaluation task, including policy definitions and output format requirements. Qwen3Guard-Stream employs a more complex joint training strategy with separate losses for query and response classification. Query loss is computed only at the final token (the end-of-query marker), while response loss is computed at every token and averaged, enabling token-by-token predictions. A conditional mechanism applies category loss only when the ground-truth risk level is Unsafe or Controversial, ensuring the model focuses category predictions where safety concerns actually exist.
An innovative aspect of Qwen3Guard-Gen’s training is the building of controversial labels through a multi-stage process (Figure 3). The training data is split into 2 parts, and for each part, 2 models are trained with reweighted samples to yield “Loose” and “Strict” predictions. Each model then annotates the other part, and final labels are assigned through voting. Where predictions conflict, samples are marked as Controversial. This produces a 3-tiered classification that captures the inherent ambiguity in safety judgments, recognizing that some content’s harm depends on context, cultural norms, or application-specific policies. Label distillation then refines the dataset by retraining on synthetic data and using the improved model to re-annotate samples, iteratively improving data quality.

Benchmarks for Prompt and Response Moderation
Qwen3Guard achieves state-of-the-art performance across comprehensive safety benchmarks, demonstrating its effectiveness at both prompt and response classification. Evaluation spans English, Chinese, and multilingual datasets covering diverse safety categories, with results consistently showing Qwen3Guard outperforming existing open-source alternatives and competing with proprietary systems. The 3-tiered severity classification (with Strict and Loose modes) provides flexibility for different deployment scenarios while maintaining high accuracy.
On English prompt classification benchmarks (Figure 4), Qwen3Guard-Gen models show exceptional performance. Qwen3Guard-Gen-8B achieves an average F1 score of 90.0%, with particularly strong results on specialized datasets: 91.4% on Aegis, 99.5% on SimpleSafety, 100% on HarmBench, and 88.9% on WildGuard.

The Strict mode (treating Controversial as Unsafe) excels on datasets emphasizing caution, while Loose mode (treating Controversial as Safe) performs better on datasets preferring permissiveness. This dual-mode capability allows developers to tune sensitivity based on application requirements: stricter for child-facing applications, looser for professional or research contexts. Even the smallest 0.6B variant achieves 88.1% average F1, demonstrating strong performance despite minimal parameter count.
On English response benchmarks, Qwen3Guard-Gen shows strong performance (Figure 4), effectively identifying when model responses contain harmful instructions, inappropriate content, or policy violations. The application can interrupt generation when Qwen3Guard-Stream detects unsafe content.
Multilingual performance demonstrates Qwen3Guard’s global applicability. On Chinese safety benchmarks, the models achieve F1 scores comparable to English performance, validating the effectiveness of multilingual training data and translation strategies. Performance remains strong across lower-resource languages, though with slightly reduced accuracy reflecting the inherent challenge of limited training data. The model’s ability to handle code-switching (mixing multiple languages in a single input) further enhances practical utility for globally deployed systems.
Building a Gradio Multimodal Chatbot with Response Moderation
Now let us extend our multimodal chatbot from Lesson 2 by integrating Qwen3Guard for comprehensive safety moderation. We will check assistant responses for harmful content before displaying them.
Step 1: Installing Required Dependencies
We will use the same dependencies as Lesson 2, with no additional packages needed for Qwen3Guard since it uses the standard Transformers pipeline() function.
!pip install torch transformers accelerate gradio "gradio>=5,<6"
!pip install qwen-vl-utils pillow
print("\nβ
Dependencies installed successfully!")
On Lines 1 and 2, we install all the dependencies from our previous lessons: PyTorch for deep learning, Transformers for model loading, Accelerate for optimization, Gradio for the web interface, Flash Attention for faster inference, and qwen-vl-utils with Pillow for image processing. Qwen3Guard uses the same pipeline infrastructure as our other models, so no additional packages are required.
Step 2: Importing Libraries and Utilities
We extend our imports to include regular expression support for parsing Guard outputs.
import torch
from transformers import pipeline
import gradio as gr
from typing import List, Tuple, Optional
from PIL import Image
import requests
from io import BytesIO
from qwen_vl_utils import process_vision_info
from IPython.display import display, Markdown
import re
print(f"PyTorch version: {torch.__version__}")
print(f"CUDA available: {torch.cuda.is_available()}")
if torch.cuda.is_available():
print(f"CUDA device: {torch.cuda.get_device_name(0)}")
On Lines 1-10, we import all necessary modules from Lessons 1 and 2, plus the re module for regular expressions. On Line 10, the re module will help us parse Qwen3Guard’s structured text output to extract safety labels and categories. On Lines 12-15, we perform environment checks to verify PyTorch installation and graphics processing unit (GPU) availability.
Step 3: Loading Qwen3-VL and Qwen3Guard-Gen with Transformers
Now we initialize 3 model pipelines: the Qwen3-VL models from Lesson 2 and the new Guard model.
print("=" * 60)
print("Initializing Qwen3-VL-2B-Instruct and Qwen3-VL-2B-Thinking Pipelines")
print("=" * 60)
qwen3vl_instruct = pipeline("image-text-to-text", model="Qwen/Qwen3-VL-2B-Instruct")
qwen3vl_thinking = pipeline("image-text-to-text", model="Qwen/Qwen3-VL-2B-Thinking")
print("=" * 60)
print("Initializing Qwen3-Guard Text Generation Pipeline")
print("=" * 60)
def extract_label_categories_refusal(content):
safe_pattern = r"Safety: (Safe|Unsafe|Controversial)"
category_pattern = r"(Violent|Non-violent Illegal Acts|Sexual Content or Sexual Acts|PII|Suicide & Self-Harm|Unethical Acts|Politically Sensitive Topics|Copyright Violation|JailBreak|None)"
safe_label_match = re.search(safe_pattern, content)
label = safe_label_match.group(1) if safe_label_match else None
categories = re.findall(category_pattern, content)
return label, categories
# Use Qwen3Guard-Gen-0.6B so all three pipelines fit comfortably in a 15 GB T4 GPU.
# If you need slightly more precise detection on a larger GPU (e.g., L4/A100), swap to "Qwen/Qwen3Guard-Gen-4B".
qwen3guard = pipeline("text-generation", model="Qwen/Qwen3Guard-Gen-0.6B", dtype=torch.float16)
print("\nβ
Pipelines initialized successfully!")
On Lines 1-6, we initialize the same Qwen3-VL models from Lesson 2 for multimodal understanding with both Instruct and Thinking variants. On Lines 8-10, we print messages indicating we are loading the Guard model.
On Lines 12-18, we define a utility function to parse Guard model outputs. Qwen3Guard-Gen produces structured text responses with a Safety: field containing 1 of 3 values (Safe, Unsafe, or Controversial) and category names. On Lines 13 and 14, we define regex patterns to match the safety label and category names. On Lines 15-17, we use re.search to extract the safety label and re.findall to extract all mentioned categories (there may be multiple). On Line 18, we return both the label and the list of categories for easy processing.
On Line 22, we initialize the Qwen3Guard-Gen-0.6B model using a standard text-generation pipeline. Qwen3Guard-Gen accepts text inputs and generates text outputs following its trained instruction-following format. On Line 24, we confirm successful initialization of all 3 model types.
Step 4: Testing AI Content Moderation on Chatbot Responses
Before building the full interface, let us test the Guard model to see how it evaluates responses to potentially unsafe prompts.
# Initialize conversation history
conversation = []
# First message with image
img1 = Image.open(BytesIO(requests.get("https://img.freepik.com/premium-photo/portrait-black-people_963476-3426.jpg", timeout=10).content))
user_msg_1 = "Make a dark joke on the person in the image."
conversation.append({"role": "user", "content": [{"type": "text", "text": user_msg_1}, {"type": "image", "image": img1}]})
display(Markdown(f"**User**: {user_msg_1}"))
display(img1)
On Line 2, we initialize an empty conversation history. On Lines 5 and 6, we load a test image and create an intentionally unsafe user message requesting content that could be unethical (making jokes about someone’s appearance or race). On Lines 7-9, we append this to the conversation and display both the message and image for visibility. This test case helps us verify that the Guard model can flag potentially inappropriate responses.
Now let us see how the Guard evaluates this:
# Generate response with thinking model
response = qwen3vl_thinking(conversation, do_sample=False, max_new_tokens=1024, return_full_text=False)
trace = response[0]['generated_text'].split('</think>')[0]
response_text = response[0]['generated_text'].split('</think>')[1]
# Safety check the response
guard_response = qwen3guard(
[{"role": "user", "content": response_text}],
do_sample=False,
max_new_tokens=256,
return_full_text=False
)
print(guard_response)
label, categories = extract_label_categories_refusal(guard_response[0]['generated_text'])
display(Markdown(f"\n**Guard Assessment**: Label: {label}, Categories: {categories}"))
On Lines 2-4, we generate a response using the Thinking model and parse out the thinking trace and final response. On Lines 7-12, we pass the assistant’s response to the Guard model for safety evaluation. The Guard receives the response text as a user message (following its training format where it evaluates content by treating it as a query). We use deterministic generation (do_sample=False) and limit output to 256 tokens.
On Lines 14-16, we print the raw Guard output and extract the safety label and categories using our parsing function, then display the assessment. In Figure 5, the Guard labels the response as Controversial and assigns it to the Unethical Acts category.

Step 5: Adding Qwen3Guard Response Filtering to the Gradio Interface
Now we will build the complete interface with integrated safety checks.
import base64
from io import BytesIO
def create_chatbot_interface(chatbot, thinking_chatbot, guard_model):
"""
Gradio interface for chatbot interaction with safety checks
"""
def pil_to_base64(img):
buf = BytesIO()
img.resize((256, 256)).save(buf, format="PNG")
return "data:image/png;base64," + base64.b64encode(buf.getvalue()).decode()
def add_user_message(message: str, image, conversation, history):
if not message.strip() and image is None:
return history, "", None
if history is None:
history = []
user_content = []
if message.strip():
user_content.append({"type": "text", "text": message})
if image is not None:
user_content.append({"type": "image", "image": image})
conversation.append({"role": "user", "content": user_content})
display_text = message or ""
if image is not None:
img_str = pil_to_base64(image)
display_text += f"\n\n"
history.append([display_text, None])
return history, "", None # show user message immediately
On Lines 1-7, we import base64 and BytesIO, then define our interface creation function that now accepts 3 models: the Qwen3-VL chatbot, thinking chatbot, and guard model. On Lines 9-12, we define the image encoding helper function from Lesson 2. On Lines 14-32, we define the user message handler that now accepts both text and optional images, building a flexible content list and displaying the combined input in the chat history.
def chat_function(message: str, conversation, history, model_choice: str):
try:
# --- Generate assistant response ---
if model_choice == "Thinking":
response = thinking_chatbot(conversation, do_sample=False, max_new_tokens=1024, return_full_text=False)
trace = response[0]['generated_text'].split('</think>')[0]
response = response[0]['generated_text'].split('</think>')[1]
assistant_text = (
"<details><summary>Show thinking trace</summary>\n\n"
"```text\n" + (trace or "").strip() + "\n```\n"
"</details>\n\n"
+ (response or "")
)
else:
response = chatbot(conversation, do_sample=False, max_new_tokens=1024, return_full_text=False)
assistant_text = response[0]['generated_text']
# --- Safety check for assistant response ---
guard_assistant = guard_model(
[{"role": "user", "content": assistant_text}],
do_sample=False,
max_new_tokens=256,
return_full_text=False
)
label_a, categories_a = extract_label_categories_refusal(
guard_assistant[0]['generated_text']
)
if label_a == "Unsafe" or label_a == "Controversial":
assistant_text = "β οΈ I apologize, but I cannot provide a response to this query that meets our safety standards."
# --- Append safe or refused response ---
conversation.append({"role": "assistant", "content": [{"type": "text", "text": assistant_text}]})
history[-1][1] = assistant_text
return history, "", None
except Exception as e:
history[-1][1] = f"Exception: {e}"
return history, "", None
On Lines 4-16, we generate the assistant response using either Thinking or Instruct mode, exactly as in Lesson 2. On Lines 19-27, we implement the crucial safety check. We pass the generated response to the Guard model and extract the safety label and categories. On Lines 28 and 29, if the label is Unsafe or Controversial (indicating potential harm), we replace the assistant’s response with a safety refusal message. When the Guard flags a response, the chatbot displays the refusal message. On Lines 32-38, we append the final response (either the original or the safety refusal) to the conversation history and handle any exceptions.
This implementation demonstrates a critical pattern for responsible AI: always check outputs before displaying them to users. The safety check happens transparently in the background, and users experience seamless protection without needing to understand the technical details.
with gr.Blocks() as interface:
gr.Markdown("## π€ Qwen3 Multimodal Chatbot with Safety Moderation")
with gr.Row():
chatbot_ui = gr.Chatbot(scale=4)
with gr.Row():
msg = gr.Textbox(placeholder="Type your message here...", scale=8)
image_input = gr.Image(label="Upload Image (optional)", type="pil", scale=1)
send_btn = gr.Button("π€ Send", scale=1)
stop_btn = gr.Button("βΉοΈ Stop", scale=1)
model_selector = gr.Dropdown(
choices=["Instruct", "Thinking"],
value="Instruct",
label="Model selection",
scale=2
)
history_state = gr.State([])
conversation_state = gr.State([])
# Step 1: Show user message immediately
send_btn.click(
add_user_message,
inputs=[msg, image_input, conversation_state, history_state],
outputs=[chatbot_ui, msg, image_input],
)
# Step 2: Then process with chatbot + safety checks
send_event = send_btn.click(
chat_function,
inputs=[msg, conversation_state, history_state, model_selector],
outputs=[chatbot_ui, msg, image_input],
)
stop_btn.click(None, None, None, cancels=[send_event])
return interface
On Lines 1-38, we build the Gradio interface using the same structure as Lesson 2, with an updated title mentioning safety moderation. The interface layout includes the chatbot display, text and image inputs, send and stop buttons, and model selection dropdown. We register 2 handlers for the Send button, one to display the userβs message and one to generate and check the assistantβs response. The difference from Lesson 2 is that our chat_function now includes Guard checks, but this happens transparently without any user interface (UI) changes.
Step 6: Launching the Safe Gradio Chatbot
Finally, we create and launch our safety-enhanced chatbot.
# Create the interface
interface = create_chatbot_interface(qwen3vl_instruct, qwen3vl_thinking, qwen3guard)
print("β
Gradio interface created!")
print("Launching Gradio interface...")
print("Access the chatbot at: http://localhost:7860")
print("Press the 'Stop' button in the output to stop the server\n")
interface.launch()
On Lines 2 and 3, we instantiate the interface by passing all 3 model pipelines: the Qwen3-VL Instruct model, Qwen3-VL Thinking model, and Guard model. On Lines 5-7, we print access information. On Line 9, we launch the application. Before displaying an assistant response, the chatbot checks it with the Guard model. It displays a refusal message if the Guard returns Unsafe or Controversial.
Example: How the Chatbot Blocks a Flagged Response
In Figure 6, the user uploads a photo of a large group of people in traditional attire and asks: βMake a joke on this image.β
Here, the chatbot activates its safety guardrails and responds with:
β οΈ I apologize, but I cannot provide a response to this query that meets our safety standards.
This is a powerful demonstration of Qwen3Guard in action. The chatbot displays the refusal after Qwen3Guard flags the generated response.
What's next? We recommend PyImageSearch University.
120+ total classes β’ 115+ hours of on-demand code walkthrough videos β’ Last updated: November 2026
β β β β β 4.84 (128 Ratings) β’ 16,000+ Students Enrolled
I strongly believe that if you had the right teacher you could master computer vision and deep learning.
Do you think learning computer vision and deep learning has to be time-consuming, overwhelming, and complicated? Or has to involve complex mathematics and equations? Or requires a degree in computer science?
Thatβs not the case.
All you need to master computer vision and deep learning is for someone to explain things to you in simple, intuitive terms. And thatβs exactly what I do. My mission is to change education and how complex Artificial Intelligence topics are taught.
If you're serious about learning computer vision, your next stop should be PyImageSearch University, the most comprehensive computer vision, deep learning, and OpenCV course online today. Here youβll learn how to successfully and confidently apply computer vision to your work, research, and projects. Join me in computer vision mastery.
Inside PyImageSearch University you'll find:
- ✓ 120+ courses on essential computer vision, deep learning, and OpenCV topics
- ✓ 94+ Certificates of Completion
- ✓ 115+ hours of on-demand video
- ✓ Brand new courses released regularly, ensuring you can keep up with state-of-the-art techniques
- ✓ Pre-configured Jupyter Notebooks in Google Colab
- ✓ Run all code examples in your web browser β works on Windows, macOS, and Linux (no dev environment configuration required!)
- ✓ Access to centralized code repos for all 540+ tutorials on PyImageSearch
- ✓ Easy one-click downloads for code, datasets, pre-trained models, etc.
- ✓ Access on mobile, laptop, desktop, etc.
Summary
Throughout this lesson, we have explored Qwen3Guard and its critical role in building responsible, safe AI systems. We began by understanding the architecture of 2 specialized variants: Qwen3Guard-Gen, which reformulates safety classification as an instruction-following task and provides detailed, explainable assessments with 3-tiered severity levels (Safe, Controversial, Unsafe), and Qwen3Guard-Stream, which adds dual classification heads for real-time token-level moderation during streaming generation.
We learned about the comprehensive 9-category safety policy covering violence, illegal activities, sexual content, PII, self-harm, unethical acts, politically sensitive topics, copyright violations, and jailbreak attempts. The sophisticated training methodology (including keyword-guided synthesis, paired positive-negative examples, multilingual translation, and automated token-level annotation through rollout assessment and LLM-judge verification) ensures robust safety detection across diverse scenarios and languages.
We then translated this theoretical foundation into practical implementation by extending our multimodal chatbot with comprehensive safety moderation. Through hands-on coding, we learned critical patterns for responsible AI development: initializing Guard pipelines using standard text-generation infrastructure, parsing structured safety outputs with regular expressions to extract labels and categories, implementing transparent background safety checks that intercept problematic content before display, blocking the display of responses labeled as Unsafe or Controversial, and maintaining user experience while enforcing strict safety policies.
Safety checks should be built into the chatbot. By integrating Guard checks directly into our generation pipeline, we ensure that safety is enforced consistently without requiring users to understand or manage it manually.
This lesson represents a crucial milestone in our journey toward a production-ready AI assistant. We have progressed from basic text understanding (Lesson 1) to multimodal capabilities (Lesson 2) and now to safety-aware operation that protects users from harmful content. The combination of powerful language and vision models with robust safety guardrails creates a system that is both capable and responsible.
In the final lesson (Lesson 4), we will complete our assistant by integrating Qwen3 Embedding to enable retrieval-augmented generation (RAG). This will allow the chatbot to search through knowledge bases, ground its responses in retrieved documents, and provide citations for its claims. By the end of the series, we will have built a comprehensive, safe, multimodal, knowledge-grounded AI assistant that demonstrates best practices for model capabilities, safety, and factual grounding.
Citation Information
Mangla, P. βAdding LLM Guardrails to a Multimodal Chatbot with Qwen3Guard,β PyImageSearch, S. Huot, A. Sharma, and P. Thakur, eds., 2026, https://pyimg.co/qwb0l
@incollection{Mangla_2026_adding-llm-guardrails-to-multimodal-chatbot-qwen3guard,
author = {Puneet Mangla},
title = {{Adding LLM Guardrails to a Multimodal Chatbot with Qwen3Guard}},
booktitle = {PyImageSearch},
editor = {Susan Huot and Aditya Sharma and Piyush Thakur},
year = {2026},
url = {https://pyimg.co/qwb0l},
}
To download the source code to this post (and be notified when future tutorials are published here on PyImageSearch), simply enter your email address in the form below!

Download the Source Code and FREE 17-page Resource Guide
Enter your email address below to get a .zip of the code and a FREE 17-page Resource Guide on Computer Vision, OpenCV, and Deep Learning. Inside you'll find my hand-picked tutorials, books, courses, and libraries to help you master CV and DL!



Comment section
Hey, Adrian Rosebrock here, author and creator of PyImageSearch. While I love hearing from readers, a couple years ago I made the tough decision to no longer offer 1:1 help over blog post comments.
At the time I was receiving 200+ emails per day and another 100+ blog post comments. I simply did not have the time to moderate and respond to them all, and the sheer volume of requests was taking a toll on me.
Instead, my goal is to do the most good for the computer vision, deep learning, and OpenCV community at large by focusing my time on authoring high-quality blog posts, tutorials, and books/courses.
If you need help learning computer vision and deep learning, I suggest you refer to my full catalog of books and courses β they have helped tens of thousands of developers, students, and researchers just like yourself learn Computer Vision, Deep Learning, and OpenCV.
Click here to browse my full catalog.