Qwen3Guard-Stream is a specialized model designed for real-time, token-level safety classification. It allows you to evaluate the safety of a conversation as tokens are being generated.
Workflow:
- Prompt-Level Check: Perform an initial safety assessment of the user's prompt.
- Token-Level Moderation: As the assistant generates tokens, feed them incrementally to the model to detect risks dynamically.
Important Integration Note:
Streaming detection requires streaming token IDs as input. This is best suited for models that share the Qwen3 tokenizer. If using a different tokenizer, you must re-tokenize the input text into the Qwen3 vocabulary and feed tokens incrementally.
Key Methods:
model.stream_moderate_from_ids(token_ids, role, stream_state): Processes token IDs and returns a result dictionary and an updated stream_state.model.close_stream(stream_state): Cleans up the stream state.
Result Dictionary Keys:
result['risk_level']: Returns the safety status (e.g., Safe).result['category']: Returns the specific safety category if a risk is detected.
import torch
from transformers import AutoModel, AutoTokenizer
model_path="Qwen/Qwen3Guard-Stream-4B"
# trust_remote_code=True is required for this architecture
tok = AutoTokenizer.from_pretrained(model_path, trust_remote_code=True)
model = AutoModel.from_pretrained(
model_path,
device_map="auto",
torch_dtype=torch.bfloat16,
trust_remote_code=True
).eval()
# Example: Simulating streaming moderation
# (Assuming token_ids and user_end_index are prepared from a conversation)
stream_state = None
# 1. Initial prompt moderation
result, stream_state = model.stream_moderate_from_ids(token_ids[:user_end_index+1], role="user", stream_state=None)
# 2. Token-by-token assistant moderation
for i in range(user_end_index + 1, len(token_ids)):
current_token = token_ids[i]
result, stream_state = model.stream_moderate_from_ids(current_token, role="assistant", stream_state=stream_state)
print(f"Token: {tok.decode([current_token])} -> Risk: {result['risk_level'][-1]}")
model.close_stream(stream_state)