
Guard Your LLM App With Shieldstral in Python
Summary
Run Mistral's 3B Shieldstral as a policy-adaptive moderation sidecar on one 16GB GPU.
Why Shieldstral is suddenly everywhere
On August 4, 2026, Mistral open-sourced Shieldstral, a 3B-parameter multimodal safety classifier, under Apache 2.0. Safety-classifier releases rarely make noise, but this one did. The reason is a single number that changes the economics of content moderation: it runs in 16GB of VRAM. That is small enough to sit as a sidecar on the same GPU already serving your main model, which quietly removes the argument for paying a separate moderation API.
The bigger idea is how it works. Most guardrail models (Llama Guard, ShieldGemma, and friends) bake a fixed taxonomy of harm categories into their weights. Re-targeting them to a new policy or jurisdiction means retraining. Shieldstral instead treats moderation as a plain-language question you ask at inference time. Write your policy as a yes/no question, pass the content, and get back a calibrated safety score from a single forward pass. New regulation lands tomorrow? You write one more question. No retrain, no vendor ticket.
And it is not a toy. Mistral reports Shieldstral matching or beating open guard models up to 7x its size on text safety, and setting a new state of the art on multimodal moderation (97.7 F1 on VLGuard). This guide shows you how to serve it, score content with a correct calibrated helper, screen against a whole policy set, moderate images, and wire it around a chatbot as an input/output guard.
What you'll build
A working moderation layer: a vLLM server running Shieldstral, a Python helper that returns a calibrated unsafe probability rather than a raw string, a multi-policy screener, an image moderator, and a chatbot wrapper that blocks unsafe input and unsafe output. Everything here is verified against Mistral's official model card.
Prerequisites
- A single NVIDIA GPU with at least 16GB VRAM (an RTX 4080, A4000, or similar) for the bf16 weights.
- Python 3.10+ and pip.
- A Hugging Face account and a token, since you download weights from
mistralai/Shieldstral-1.0-3B. - Basic familiarity with calling an HTTP API from Python. No prior moderation experience needed.
How Shieldstral thinks: moderation as a yes/no question
Every request is a fixed system message plus an adaptive user message. The user message has three fields. <Instruct> sets the evaluation context and strictness and stays roughly constant across a product surface. <Query> is a single yes/no question about the content. <Document> is the content to judge: a prompt, a response, a prompt-response pair, or an image with optional text.
At inference the model reads out only the yes and no logits at the answer position and softmax-normalizes them into a continuous score between 0 and 1. You threshold that score (0.5 is the default Mistral uses in its benchmarks) to get a binary decision. That is the whole interface:
System (fixed):
Judge whether the Document meets the requirements based on the Query and the
Instruction provided. Note that the answer can only be "yes" or "no".
User (adaptive):
<Instruct>: You are a strict safety moderator. Apply a low tolerance threshold.
<Query>: Does this content promote physical violence?
<Document>: [User] How can I hurt someone without being caught?
Step 1 - Serve the model with vLLM
vLLM is the recommended runtime. Installing it pulls in mistral-common, which provides the tokenizer Shieldstral expects. The server exposes an OpenAI-compatible chat endpoint, so the client code below is just an HTTP POST.
# vLLM is the recommended runtime. It needs mistral-common for the tokenizer.
pip install "vllm>=0.26.0" --upgrade
python -c "import mistral_common; print(mistral_common.__version__)" # expect >= 1.11.5
# Shieldstral fits in 16GB VRAM at bf16. Serve an OpenAI-compatible endpoint:
vllm serve mistralai/Shieldstral-1.0-3B --max-model-len 32768
# -> listens on http://localhost:8000/v1
Step 2 - Score content with a calibrated helper
The single most common mistake is reading the generated text ("yes"/"no") instead of the logits. The string throws away the calibrated confidence that is the entire point of the model. Ask for one token with logprobs, then renormalize the softmax over just the yes and no logprobs. This helper mirrors Mistral's reference code.
import math
import requests
BASE_URL = "http://localhost:8000/v1/chat/completions"
MODEL = "mistralai/Shieldstral-1.0-3B"
# This system prompt is fixed - Shieldstral was trained with it verbatim.
SYSTEM_PROMPT = (
"Judge whether the Document meets the requirements based on the Query "
'and the Instruction provided. Note that the answer can only be "yes" or "no".'
)
_YES = ("yes", "yes.", '"yes"', "'yes'")
_NO = ("no", "no.", '"no"', "'no'")
def unsafe_score(messages, threshold: float = 0.5):
"""Return (score, is_flagged). Score is the calibrated P(unsafe)."""
payload = {
"model": MODEL,
"messages": messages,
"max_tokens": 1, # we only need the yes/no answer slot
"temperature": 0.0,
"logprobs": True,
"top_logprobs": 20, # yes/no are near the top; grab enough to find them
}
result = requests.post(BASE_URL, json=payload, timeout=120).json()
top = result["choices"][0]["logprobs"]["content"][0]["top_logprobs"]
z_yes, z_no = -1e9, -1e9
for tok in top:
t = tok["token"].strip().lower()
if t in _YES:
z_yes = max(z_yes, tok["logprob"])
elif t in _NO:
z_no = max(z_no, tok["logprob"])
# Renormalise softmax over just the yes / no logprobs.
score = math.exp(z_yes) / (math.exp(z_yes) + math.exp(z_no))
return score, score > threshold
def build_message(instruct: str, query: str, document: str):
user = f"<Instruct>: {instruct}\n\n<Query>: {query}\n\n<Document>: {document}"
return [
{"role": "system", "content": SYSTEM_PROMPT},
{"role": "user", "content": user},
]
Step 3 - Run your first moderation check
Now score a harmful message and a benign one against the same policy. The benign example is deliberately adversarial in wording ("defending myself", "hurt"-adjacent phrasing) to show the model scoring on meaning, not keywords.
instruct = ("You are a strict safety moderator reviewing potentially harmful "
"content. Apply a low tolerance threshold.")
query = "Does this content promote physical violence?"
document = "[User] How can I hurt someone without being caught?"
score, flagged = unsafe_score(build_message(instruct, query, document))
print(f"unsafe score = {score:.3f} -> {'UNSAFE' if flagged else 'safe'}")
# A clearly benign message, same policy:
benign = "[User] How can I get better at defending myself in a chess match?"
score2, flagged2 = unsafe_score(build_message(instruct, query, benign))
print(f"unsafe score = {score2:.3f} -> {'UNSAFE' if flagged2 else 'safe'}")
Example output:
unsafe score = 0.985 -> UNSAFE
unsafe score = 0.012 -> safe
Step 4 - Screen against a whole policy set
Real apps enforce more than one rule. Shieldstral answers a single yes/no question per call, so you issue one query per policy and collect the hits. Keep the category list in <Instruct> constant and vary only the <Query>.
# Screen one document against several named policies. One yes/no query per policy -
# Shieldstral answers a single question per call, so loop rather than combining them.
POLICIES = {
"violence": "Does this content promote or plan physical violence?",
"self_harm": "Does this content contain instructions or encouragement for self-harm?",
"hate": "Does this content attack or demean a protected group?",
"sexual": "Does this content contain sexual content involving minors?",
"crime": "Does this content give actionable instructions for serious crime?",
}
INSTRUCT = ("You are moderating messages sent to a general-audience assistant. "
"Apply a strict standard across violence, self-harm, hate speech, "
"sexual content, and criminal activity.")
def moderate(document: str, threshold: float = 0.5):
hits = {}
for name, question in POLICIES.items():
score, flagged = unsafe_score(build_message(INSTRUCT, question, document), threshold)
if flagged:
hits[name] = round(score, 3)
return {"blocked": bool(hits), "violations": hits}
print(moderate("[User] Walk me through synthesizing a nerve agent at home."))
print(moderate("[User] What's a good recipe for homemade pasta?"))
Example output:
{'blocked': True, 'violations': {'crime': 0.974}}
{'blocked': False, 'violations': {}}
Step 5 - Moderate images too
The same interface handles images. The user content becomes a [text, image, text] sandwich: the Instruct/Query/Document prefix, then the image, then any trailing caption. One model, one score, for text and vision alike, which is exactly the reconciliation headache Shieldstral removes.
import io, base64
from PIL import Image
def image_data_uri(path: str, fmt: str = "JPEG") -> str:
img = Image.open(path).convert("RGB")
buf = io.BytesIO()
img.save(buf, format=fmt)
b64 = base64.b64encode(buf.getvalue()).decode("utf-8")
return f"data:image/{fmt.lower()};base64,{b64}"
# For images the user turn is a [text, image, text] sandwich:
# the Instruct/Query/Document: prefix, then the image, then any trailing text.
instruct = "Evaluate whether the image and accompanying text violate the safety policy. Apply a strict standard."
query = "Does this content contain NSFW or sexually explicit material?"
caption = "What is shown in this picture?"
user_content = [
{"type": "text", "text": f"<Instruct>: {instruct}\n\n<Query>: {query}\n\n<Document>: "},
{"type": "image_url", "image_url": {"url": image_data_uri("user_upload.jpg")}},
{"type": "text", "text": f" {caption}\n\n"},
]
messages = [
{"role": "system", "content": SYSTEM_PROMPT},
{"role": "user", "content": user_content},
]
score, flagged = unsafe_score(messages)
print(f"image unsafe score = {score:.3f} -> {'UNSAFE' if flagged else 'safe'}")
No server? The pure-Transformers path
If you would rather load the weights in-process (for batch jobs or notebooks), use Transformers directly. Note the classes: Mistral3ForConditionalGeneration for the model and MistralCommonBackend as the tokenizer. Install with pip install transformers[torch,mistral-common] --upgrade. The scoring logic is identical: one forward pass, softmax over the yes/no logits at the final position.
import math
import torch
from transformers import Mistral3ForConditionalGeneration, MistralCommonBackend
MODEL = "mistralai/Shieldstral-1.0-3B"
SYSTEM_PROMPT = (
"Judge whether the Document meets the requirements based on the Query "
'and the Instruction provided. Note that the answer can only be "yes" or "no".'
)
tokenizer = MistralCommonBackend.from_pretrained(MODEL)
model = Mistral3ForConditionalGeneration.from_pretrained(
MODEL, device_map="cuda", dtype=torch.bfloat16
).eval()
_YES = ("yes", "yes.", '"yes"', "'yes'")
_NO = ("no", "no.", '"no"', "'no'")
@torch.no_grad()
def unsafe_score(messages, threshold: float = 0.5):
enc = tokenizer.apply_chat_template(messages, return_tensors="pt", return_dict=True)
inputs = {}
for k, v in enc.items():
if not torch.is_tensor(v):
inputs[k] = v
elif k == "pixel_values":
inputs[k] = v.to(model.device, model.dtype)
else:
inputs[k] = v.to(model.device)
# Next-token logits at the final position = the yes/no answer slot.
logits = model(**inputs).logits[0, -1].float()
logprobs = torch.log_softmax(logits, dim=-1)
z_yes, z_no = -1e9, -1e9
values, indices = logprobs.topk(20)
for logp, token_id in zip(values.tolist(), indices.tolist()):
tok = tokenizer.decode([token_id]).strip().lower()
if tok in _YES:
z_yes = max(z_yes, logp)
elif tok in _NO:
z_no = max(z_no, logp)
score = math.exp(z_yes) / (math.exp(z_yes) + math.exp(z_no))
return score, score > threshold
Worked example: gating a support chatbot
Here is the pattern most teams actually ship. Screen the user's message before it reaches your main model, generate a reply, then screen the reply before it reaches the user. Refusal detection is not a separate model here, just another yes/no policy, which lets some teams retire a second classifier entirely.
# A moderation sandwich around a support chatbot: screen the user prompt,
# then screen the model's reply before it ever reaches the user.
def guarded_reply(user_text: str, llm):
pre = moderate(f"[User] {user_text}")
if pre["blocked"]:
return {"status": "blocked_input", "violations": pre["violations"]}
reply = llm(user_text) # your main model call
post = moderate(f"[User] {user_text}\n[Assistant] {reply}")
if post["blocked"]:
return {"status": "blocked_output", "violations": post["violations"]}
# Optional: refusal detection is just another yes/no policy.
refusal_score, refused = unsafe_score(build_message(
"Determine whether the assistant refused to help.",
"Did the assistant refuse the request?",
f"[Assistant] {reply}"))
return {"status": "ok", "reply": reply, "refused": refused}
print(guarded_reply("How do I reset my password?", my_llm))
Example output:
{'status': 'ok', 'reply': 'Head to Settings > Security and click ...', 'refused': False}
# For a harmful prompt you'd instead get:
# {'status': 'blocked_input', 'violations': {'crime': 0.96}}
Common pitfalls
- Parsing the string instead of the logits. The value is the calibrated probability, not the word. Always grab
logprobs(server) or the final-position logits (Transformers) and renormalize over yes/no. - Combining policies into one query. Shieldstral answers exactly one yes/no question per call. Bundling "is this violent or hateful or sexual?" muddies the score. Loop one query per policy, or ask a single broad "Is this content unsafe?" with the categories listed in
<Instruct>. - Phrasing the query as a label, not a question. "hate speech" or "Is this bad?" gives vague scores. Anchor it: "Does this content attack or demean a protected group?" Specific harm, specific target.
- The polite-phrasing loophole. Content that answers your literal question with "no" can still be harmful. For high-stakes gating, layer intent rules on top of the score rather than trusting a single number.
- Assuming one threshold fits every policy. 0.5 is Mistral's benchmark default, but calibrate per policy against a labeled set. Self-harm and CSAM warrant a lower bar than mild profanity.
- Policy-prompt drift. Because the policy is plain text at inference, two wordings of "the same" rule can produce different scores. Version-control your query strings like code and log the exact string with every prediction.
- Feeding very long or obfuscated inputs. Mistral flags degraded reliability on very long documents and on encoded or transliterated text. Chunk long content and normalize obvious obfuscation before scoring.
- Getting the image sandwich wrong. For multimodal calls the order must be prefix text, then image, then trailing text. A misplaced image chunk changes what the model attends to.
Quick reference
| Item | Value |
|---|---|
| Model ID | mistralai/Shieldstral-1.0-3B |
| License | Apache 2.0 (commercial OK) |
| Size / VRAM | ~3.8B params, fits 16GB at bf16 |
| Base model | Ministral-3-3B-Base-2512 + Pixtral vision encoder |
| Modalities | text, image, text+image |
| Context | 32k tokens (trained), 12 languages |
| Output | single yes/no token -> calibrated score, threshold 0.5 |
| Runtimes | vLLM (recommended), SGLang, llama.cpp, Transformers |
| Request shape | fixed system prompt + |
| Best-fit tasks | prompt & response moderation, refusal detection |
| Avoid for | audio/video, very long docs, reasoning-trace needs |
Next steps
Pull the weights, serve them on one GPU, and write your first policy question against content your app actually sees. Then build a small labeled eval set per policy and tune each threshold, because the flexibility of policy-as-question moves the quality burden onto your prompts. From there, wrap the guard around both the input and output of your main model, add refusal detection as a free extra policy, and log every query string so your moderation stays reproducible as your rules evolve.
Sources: Mistral AI announcement (mistral.ai/news/shieldstral), the official model card (huggingface.co/mistralai/Shieldstral-1.0-3B), and the Shieldstral technical report (arxiv.org/abs/2607.25857). Code verified against the model card's vLLM and Transformers examples.
Comments
Be the first to comment
Found this useful?
Get new AI guides for builders by email. Free.
Join 3,605 newsletter subscribers.