Statistical Guardrails

Reject on the numbers: cosine-distance drift and token-entropy confidence.

Quantitative, model-agnostic checks sit between a non-deterministic agent and the user and reject outputs on statistical signals rather than schema or rules. Two complementary checks: semantic-drift detection embeds each response and measures its cosine distance from a set of "safe" baseline examples, flagging outliers by z-score (off-topic drift, persona shifts, likely hallucination or toxicity); and confidence gating computes the Shannon entropy of the generated tokens' probabilities — high entropy means the model was guessing among many low-probability tokens, a proxy for low-confidence or fabricated answers.

In practiceA medical-information agent runs every generated answer through a cosine-distance drift detector; responses that stray semantically from the safe-answer baseline are flagged and routed to a human reviewer before delivery.

Without itWithout statistical guardrails, an answer that is schema-valid but semantically drifted reaches the user unflagged, because structural validators see nothing wrong and the drift only shows up once a complaint surfaces it.

Level
04 · Production
Subdomain
Governance & Safety
Also known as
Semantic Guardrails, Quantitative Guardrails, Confidence Gating, Semantic Drift Detection
Trade-off
A cheap, model-agnostic safety net is gained against threshold-tuning effort and false positives — a legitimately novel but correct answer can read as drift, and a confidently-wrong answer can pass the entropy gate.
The mechanism

How it works.

Two numbers are computed for every free-text answer: how far it lies from known good answers, and how unsure the model was while writing it. An answer outside the limits is held back.

1 · Calibrate

  1. Collect safe answersA baseline set
  2. Embed themThe usual distance and its spread
  3. Set the limitsA z-score and an entropy threshold

2 · On every answer

  1. Embed the answerMeasure its distance to the baseline
  2. Compute the z-scoreHow unusual is that distance?
  3. Compute the entropyFrom the token probabilities
  4. Deliver or holdOutside a limit: to a reviewer
Baseline
A set of answers known to be acceptable. Everything else is measured against it.
z-score
How many standard deviations a value lies from the average. A distance with a z-score of 3 is very unusual for this baseline.
Shannon entropy
A measure of how spread out the token probabilities were. High means the model was choosing among many unlikely tokens.
Walk it through

A real run, step by step.

TaskA medical-information agent. Every answer is held when its z-score is above 2.5 or its entropy is above 3.0:
Illustrative values.
Answerz-scoreEntropyOutcome
The dosage of a common painkiller0.41.1Delivered
Side effects, in unusual wording1.91.6Delivered
An investment tip in the middle of the answer3.81.4Held: drift away from the topic
A drug name that does not exist, with invented details1.23.7Held: low confidence
What this shows: the two checks catch different failures. The third answer was written with confidence and lies far from the baseline. The fourth stays on topic and was guessed. Neither check reads a rule or a schema, so both work on free text. The price is tuning: a correct answer that is merely unusual is held, and a wrong answer written with confidence passes the entropy check.
In code

The pattern in code.

NumPypython
import numpy as np

def calibrate(safe_answers):
    vectors = np.array([embed(answer) for answer in safe_answers])
    centroid = vectors.mean(axis=0)
    distances = [cosine_distance(vector, centroid) for vector in vectors]
    return centroid, np.mean(distances), np.std(distances)

def check(answer, token_probabilities, baseline, max_z=2.5, max_entropy=3.0):
    centroid, mean, std = baseline
    # semantic drift
    z = (cosine_distance(embed(answer), centroid) - mean) / std
    # per token, in bits
    entropy = np.mean([-sum(p * np.log2(p) for p in dist if p > 0)
                       for dist in token_probabilities])
    if z > max_z:
        return "hold: drift"
    if entropy > max_entropy:
        return "hold: low confidence"
    return "deliver"
Fit

Use it, or not.

When to reach for it

  • Outputs are free-form, so schema validation does not apply.
  • A numeric reject/allow boundary is needed.
  • Topical drift or low-confidence fabrication must be caught before a response reaches a user.

When it backfires

  • Outputs are already structurally validated and that suffices.
  • Token log-probabilities or a trustworthy baseline corpus are unavailable.
  • The latency of an extra embedding / scoring pass is unacceptable.
Pitfalls

Two ways this pattern will hurt you.

Thresholds tuned on a stale baseline

The z-score baseline was built from last quarter's safe answers. The product's scope expanded, legitimate new topics now read as drift, and the guardrail rejects correct outputs.

Countermeasure

Refresh the baseline corpus as scope changes, and alert on rejection-rate spikes so a drifting threshold is caught before it blocks real traffic.

The entropy gate waves through a confident fabrication

Low token entropy reads as high confidence, but a fluent hallucination is exactly that — confident and wrong. The statistical gate passes it because confidence is not correctness.

Countermeasure

Never treat low entropy as a truth signal. Pair confidence gating with a grounding or verification check (retrieval, a fact-check tool, or LLM-as-judge) before trusting the output.

EU law

Regulation

Duties from EU law that this pattern helps meet, or that land on it. A reading aid, not legal advice.

  • EU AI Act Art. 15An appropriate level of accuracy, robustness and cybersecurity, held consistently over the lifecycle.Providers of high-risk systems · from 2 Dec 2027 (Annex III) or 2 Aug 2028 (Annex I products)

An engineer's reading aid, not legal advice. The legal texts and their interpretation are authoritative.

Framework support

Where Statistical Guardrails is native.

NeMo GuardrailsLibraryComposes as a custom rail.Adaptable
Guardrails AILibraryComposes as a custom validator.Adaptable

Search

Search patterns, frameworks, and pages.