A model can return perfect JSON that says something false, and true text that breaks the application receiving it. That is why validating the output is not a single check: there are at least four, each with a kind of error that the others do not see. In this article you build them one at a time with a fake, deterministic model: the shape of the answer (the schema), the place where the answer ends up (HTML, database), the grounding in the sources (numbers and words, then inference) and the final decision with three states. No model was run or called.
The two entries of the OWASP 2025 list behind this series of checks are LLM05, Improper Output Handling and LLM09, Misinformation. The first is a classic security problem: the model's output is an input for the rest of the system, and must be treated as such. The second is a content problem: the model says false things with the same confidence with which it says true ones. They are different failures, and that is why the first check (the shape) is not enough for the second.
What you are looking for: errors of shape, destination and content
On content, the literature distinguishes two families. The survey by Ji et al. on hallucination in text generation separates intrinsic hallucinations (the output contradicts the content of the source) from extrinsic ones (the output cannot be verified from the source); the NIST AI 600-1 profile gathers them under the heading "confabulation", defined as the production of content stated with confidence but erroneous or false. To choose the control, though, a more operational classification is better, which is mine and unofficial:
- Contradiction with the source: the answer says the opposite of the retrieved document.
- Ungrounded addition: the answer asserts something that no source contains.
- Self-contradiction: two sentences of the same answer deny each other.
- Unjustified certainty: a confident tone about something the source leaves open.
- Invented reference: it cites a document or a source that does not exist.
Five errors, but only three families of control. Invented references are caught by a deterministic check (is the cited source among the retrieved ones?), contradictions and additions by a comparison with the sources (lexical or by inference), and unjustified certainty only by a judge, which has the limits already seen in article 1. None of these things is free, and I give you no timings or percentages: they depend on the model and on the corpus, and they are measured.
The shape: a closed schema and a loop that says what to fix
The first check verifies that the output is JSON and respects a schema. The listing (formato.py) uses Pydantic 2.14.3, run in a test environment, and has two settings that matter. extra="forbid" rejects unexpected fields: the Pydantic documentation specifies that the default behavior is to ignore them, which means an extra field would pass silently. The validator fuori_ambito_senza_fonti expresses a rule across fields that the JSON schema alone cannot state.
The genera_validata loop does three things that set it apart from a simple try. It collects Pydantic's errors into readable lines and sends them back to the model so that it knows what to fix. It has a limit on attempts. And, once the limit is exhausted, it returns None instead of raising an exception: the decision on how to degrade belongs to the caller, who can answer with a controlled message. The fake model in the listing follows a script: the first attempt has an out-of-range value and an extra field, the second a violated rule, the third is valid.
import json
from typing import Literal
from pydantic import BaseModel, ConfigDict, Field, ValidationError, model_validator
class Risposta(BaseModel):
model_config = ConfigDict(extra="forbid")
text: str = Field(min_length=1, max_length=400)
confidence: float = Field(ge=0.0, le=1.0)
category: Literal["direct", "clarification", "out_of_scope"]
sources: list[str] = Field(default_factory=list)
@model_validator(mode="after")
def fuori_ambito_senza_fonti(self):
if self.category == "out_of_scope" and self.sources:
raise ValueError("category 'out_of_scope' but sources are cited")
return self
def errori_leggibili(e: ValidationError) -> list[str]:
return [f"{'.'.join(map(str, d['loc'])) or 'answer'}: {d['msg']}" for d in e.errors()]
def genera_validata(chiama, domanda, max_tentativi=3):
messaggi = [domanda]
for tentativo in range(1, max_tentativi + 1):
grezzo = chiama(messaggi)
try:
return Risposta.model_validate(json.loads(grezzo)), tentativo, messaggi[1:]
except json.JSONDecodeError as e:
problemi = [f"invalid JSON at position {e.pos}"]
except ValidationError as e:
problemi = errori_leggibili(e)
messaggi.append("ERRORS: " + "; ".join(problemi)) # the model sees what to fix
return None, max_tentativi, messaggi[1:] # a controlled outcome, not an exception
def modello_finto(copione):
it = iter(copione)
return lambda messaggi: next(it)
if __name__ == "__main__":
print("JSON schema keys:", sorted(Risposta.model_json_schema()["properties"]))
copione = [
'{"text": "The Base plan costs 9 euros.", "confidence": 1.4, "category": "direct", "note": "x"}',
'{"text": "The Base plan costs 9 euros.", "confidence": 0.8, "category": "out_of_scope", "sources": ["doc-1"]}',
'{"text": "The Base plan costs 9 euros.", "confidence": 0.8, "category": "direct", "sources": ["doc-1"]}',
]
r, n, feedback = genera_validata(modello_finto(copione), "How much does the Base plan cost?")
print(f"validated at attempt {n}:", r.category, r.sources)
for riga in feedback:
print(" to the model:", riga)
r, n, _ = genera_validata(modello_finto(["Sure! Here is the answer:"] * 3), "How much does the Base plan cost?")
print(f"after {n} attempts the answer is {r}: the caller decides how to degrade")
# Output:
# JSON schema keys: ['category', 'confidence', 'sources', 'text']
# validated at attempt 3: direct ['doc-1']
# to the model: ERRORS: confidence: Input should be less than or equal to 1; note: Extra inputs are not permitted
# to the model: ERRORS: answer: Value error, category 'out_of_scope' but sources are cited
# after 3 attempts the answer is None: the caller decides how to degrade
The output shows the complete loop: the answer is accepted at the third attempt, and the two "to the model" lines are exactly what was sent back to it, with the field names (confidence, note) and the type of error. In the last case the model keeps answering with non-JSON text three times and the result is None. In a real system the number of attempts rises with latency and cost, and a high retry rate is a signal that schema and prompt are not aligned with the model's capabilities: but which rate counts as "high" you establish by measuring your own system.
There is also the way of constraining the generation instead of validating afterwards: the Ollama documentation on structured outputs describes a format field that accepts a JSON schema, and suggests deriving it from a Pydantic model with model_json_schema(). Constraining the shape guarantees the syntax, not the truth: perfect JSON can assert something false. That is why validation after generation remains necessary even when the runtime constrains the shape.
The destination: encode the output for the context where it ends up
OWASP's page on LLM05 says to treat the model like any other user, with a zero-trust approach, to validate responses before passing them to backend functions and to encode the output according to context (for example HTML encoding for the web, parameterized queries for the database). The reason is simple: the model's text can contain characters that, in a certain context, are syntax. No attack is needed for the failure to happen.
The listing uscita_sicura.py uses as "model output" a harmless string that contains a tag, an apostrophe and an ampersand. The first part encodes it for HTML with html.escape. The second saves it in a SQLite database in two ways: with a parameter and, to show the failure, by concatenating it into the statement. The second path fails at the first apostrophe, and this is the benign case: with a text chosen by an adversary the same error is a vulnerability.
import html
import sqlite3
# Text "produced by the model": no attack, only characters that have a meaning in certain contexts
USCITA_MODELLO = "Title: <b>Guide</b> by O'Brien & sons"
def per_html(testo: str) -> str:
return html.escape(testo, quote=True) # the context is a web page
def salva(conn, testo: str, parametrizzato: bool) -> None:
if parametrizzato:
conn.execute("INSERT INTO note(titolo) VALUES (?)", (testo,))
else:
conn.execute(f"INSERT INTO note(titolo) VALUES ('{testo}')") # the apostrophe breaks the statement
if __name__ == "__main__":
print("raw HTML :", USCITA_MODELLO)
print("encoded HTML :", per_html(USCITA_MODELLO))
conn = sqlite3.connect(":memory:")
conn.execute("CREATE TABLE note(titolo TEXT)")
salva(conn, USCITA_MODELLO, parametrizzato=True)
print("SQL with params:", conn.execute("SELECT titolo FROM note").fetchone()[0])
try:
salva(conn, USCITA_MODELLO, parametrizzato=False)
except sqlite3.OperationalError as e:
print("SQL concatenated:", type(e).__name__, "-", e)
# Output:
# raw HTML : Title: <b>Guide</b> by O'Brien & sons
# encoded HTML : Title: <b>Guide</b> by O'Brien & sons
# SQL with params: Title: <b>Guide</b> by O'Brien & sons
# SQL concatenated: OperationalError - near "Brien": syntax error
The four lines of the output are the rule as an example. The raw text is what the model produced; the encoded text no longer has the characters that the browser interprets as markup (<, &); the parameterized version keeps the original text in the database without altering it; the concatenation fails with OperationalError. The rule that follows is that there is no "cleaning" valid for every destination: you encode at the point where the data enters a context, with the tool of that context.
Grounding in the sources: numbers first, then meaning
The cheapest level of comparison with the sources uses no model. The listing grounding.py splits the answer into sentences and performs two deterministic checks. First, every number that appears in the sentence must appear in at least one source: a "30 days" where the source says "14 days" is an error caught with a set subtraction. Second, the significant words of the sentence must overlap enough with those of a source, with a threshold (here 0.6) that is a parameter to calibrate.
import re
FONTI = {
"doc-1": "The Base plan costs 9 euros per month. The Base plan has no phone support.",
"doc-2": "Refunds are possible within 14 days of purchase.",
}
PAROLE_VUOTE = {"the", "a", "an", "of", "to", "in", "for", "is", "are", "and", "that", "per"}
def numeri(testo: str) -> set[str]:
return set(re.findall(r"\d+(?:[.,]\d+)?", testo))
def parole(testo: str) -> set[str]:
return {p for p in re.findall(r"\w+", testo.lower()) if p not in PAROLE_VUOTE}
def frasi(testo: str) -> list[str]:
return [f.strip() for f in re.split(r"(?<=[.!?])\s+", testo) if f.strip()]
def controlla_ancoraggio(risposta: str, fonti: dict[str, str], soglia_sovrapposizione=0.6):
corpus_numeri = set().union(*(numeri(t) for t in fonti.values()))
esiti = []
for frase in frasi(risposta):
mancanti = sorted(numeri(frase) - corpus_numeri)
migliore = max((len(parole(frase) & parole(t)) / max(len(parole(frase)), 1) for t in fonti.values()), default=0.0)
if mancanti:
verdetto = f"numbers not in the sources {mancanti}"
elif migliore < soglia_sovrapposizione:
verdetto = f"poorly grounded (overlap {migliore:.2f})"
else:
verdetto = "grounded (lexically)"
esiti.append((frase, verdetto))
return esiti
if __name__ == "__main__":
risposte = [
"The Base plan costs 9 euros per month. Refunds are possible within 30 days.",
"The Base plan costs 9 euros per month. It also has a training course.",
"The Base plan has phone support.",
]
for r in risposte:
for frase, verdetto in controlla_ancoraggio(r, FONTI):
print(f"{verdetto:42} | {frase}")
print()
# Output:
# grounded (lexically) | The Base plan costs 9 euros per month.
# numbers not in the sources ['30'] | Refunds are possible within 30 days.
#
# grounded (lexically) | The Base plan costs 9 euros per month.
# poorly grounded (overlap 0.20) | It also has a training course.
#
# grounded (lexically) | The Base plan has phone support.
Read the three answers as three lessons. In the first, the sentence with the price is grounded and the one with "30 days" is stopped by the check on numbers, because the source says 14. In the second, the addition "It also has a training course" has an overlap of 0.20 with the sources and is flagged as poorly grounded. In the third, "The Base plan has phone support" passes as grounded, and it is the opposite of what the source says ("has no phone support"): all its words are in the document, so the lexical comparison is satisfied. It is the structural limit of this level, and the reason why a second level that understands meaning is needed.
Comparison by inference
The second level is called natural language inference (NLI): a model receives a pair of sentences, the premise and the hypothesis, and says whether the premise entails the hypothesis, contradicts it or is neutral. Applied to answers, the source is the premise and each sentence of the answer is the hypothesis. The model card of cross-encoder/nli-deberta-v3-small says it is trained on the SNLI and MultiNLI datasets, that it returns three scores in the order contradiction, entailment, neutral and that it reaches 91.65% accuracy on the SNLI test set and 87.55% on MNLI mismatched. These are the card's values, obtained on English: on Italian and on texts from your own domain the behavior must be measured.
The listing below is the schema to adapt, taken from the usage described in the card. I did not run it, because it requires PyTorch and the model download, which this work excludes. I point out two details: the order of the pairs (premise, hypothesis) and the reading of the label with the order declared by the card, because reversing it would swap contradiction and entailment. A very common variant instead uses the zero-shot classification pipeline with the labels "entailment, neutral, contradiction" and the source inside the hypothesis template: it answers a different question ("which label does this text resemble?") and not the one you need ("is this sentence entailed by this source?").
# schema to adapt, NOT run: it requires sentence-transformers, PyTorch and the model download
from sentence_transformers import CrossEncoder
modello = CrossEncoder("cross-encoder/nli-deberta-v3-small")
ETICHETTE = ["contradiction", "entailment", "neutral"] # order stated in the model card
def frasi_in_contraddizione(frasi: list[str], fonte: str) -> list[str]:
coppie = [(fonte, frase) for frase in frasi] # (premise, hypothesis)
punteggi = modello.predict(coppie) # one row of three scores per pair
return [f for f, riga in zip(frasi, punteggi) if ETICHETTE[riga.argmax()] == "contradiction"]
The result is not a verdict of truth. "Contradiction" means that the sentence contradicts the text you passed, and "neutral" means that this text is not enough to decide: a correct sentence that is not in the corpus is neutral, not false. That is the reason why in the final listing a contradiction blocks while the absence of support only warns. Retrieving the right sources for each sentence (a RAG step) remains upstream and determines the quality of the whole comparison.
The decision: three states and an explicit assumption about errors
The concluding level combines the results. The listing decisione.py takes the results of the previous checks and returns allow, warn or block, with the reasons. The rules are those of the discussion: a broken format and a cited source that does not exist (compared against the allowed sources) block immediately; a contradiction with the source blocks; an ungrounded sentence or an NLI check that does not respond produce a warning, unless you choose the strict behavior with su_errore_nli="block".
from dataclasses import dataclass
@dataclass(frozen=True)
class Controlli:
formato_ok: bool
fonti_citate: frozenset
fonti_ammesse: frozenset
frasi_non_ancorate: int
contraddizioni_nli: int | None # None = the NLI check did not respond
def decidi(c: Controlli, su_errore_nli: str = "warn") -> tuple[str, list[str]]:
motivi = []
if not c.formato_ok:
return "block", ["format"]
inventate = c.fonti_citate - c.fonti_ammesse
if inventate:
return "block", [f"invented sources {sorted(inventate)}"]
if c.contraddizioni_nli is None:
if su_errore_nli == "block":
return "block", ["NLI check unavailable"]
motivi.append("NLI check unavailable")
elif c.contraddizioni_nli > 0:
return "block", [f"contradictions with the sources: {c.contraddizioni_nli}"]
if c.frasi_non_ancorate:
motivi.append(f"ungrounded sentences: {c.frasi_non_ancorate}")
return ("warn", motivi) if motivi else ("allow", [])
if __name__ == "__main__":
AMMESSE = frozenset({"doc-1", "doc-2"})
casi = {
"all in order": Controlli(True, frozenset({"doc-1"}), AMMESSE, 0, 0),
"one ungrounded sentence": Controlli(True, frozenset({"doc-1"}), AMMESSE, 1, 0),
"source does not exist": Controlli(True, frozenset({"doc-9"}), AMMESSE, 0, 0),
"contradicts the source": Controlli(True, frozenset({"doc-1"}), AMMESSE, 0, 1),
"NLI not responding": Controlli(True, frozenset({"doc-1"}), AMMESSE, 0, None),
"broken format": Controlli(False, frozenset(), AMMESSE, 0, 0),
}
for nome, c in casi.items():
azione, motivi = decidi(c)
print(f"{nome:24} -> {azione:9} {motivi}")
azione, motivi = decidi(casi["NLI not responding"], su_errore_nli="block")
print(f"{'NLI not responding (strict)':24} -> {azione:9} {motivi}")
# Output:
# all in order -> allow []
# one ungrounded sentence -> warn ['ungrounded sentences: 1']
# source does not exist -> block ["invented sources ['doc-9']"]
# contradicts the source -> block ['contradictions with the sources: 1']
# NLI not responding -> warn ['NLI check unavailable']
# broken format -> block ['format']
# NLI not responding (strict) -> block ['NLI check unavailable']
The interesting case is "NLI not responding", which gives warn in the default setting and block in the strict one. It is the same dilemma as the judge in article 1: stop the user because the check is broken, or let them through with a note? It depends on how much an error costs in your context, and it is worth deciding in writing. The intermediate state has a precise value: it lets you send the answer with a warning, which reduces useless blocks on cases that are unverifiable but not wrong.
What you can do now
You can distinguish the checks of shape, destination and content, and you know which error each one answers. You can build a loop that sends validation errors back to the model and, once the limit is exhausted, degrades in a controlled way. You can encode the output for the context where it ends up, write a comparison with the sources that does not require a model and say where it stops, and place the comparison by inference with its limits. For the consequences of all this on the decision log and on alerts, the next step is guardrail observability; to measure the defenses on a set of cases, how to test a guardrail. If you arrive here from prompt injection, the fourth article explains why the output text must be considered untrusted.
The same series also includes guardrails with NeMo Guardrails and Colang.
Frequently asked questions
What is the difference between validating the shape and validating the content?
The shape concerns the structure: valid JSON, fields, types, ranges. The content concerns what the answer asserts. An answer can have a perfect shape and say something false, which is why both checks are needed.
Why encode the model's output if the answer is only text?
Because the text ends up in contexts where certain characters are syntax: HTML, SQL, commands. OWASP recommends treating the model like any user and encoding the output according to the context, with tools such as parameterized queries.
Is the check on numbers enough to find hallucinations?
No. It finds the numbers that the sources do not contain, but it does not see a sentence that uses only words present in the source to say the opposite. For that case you need a comparison by inference, which in turn has limits and must be measured on your language and your domain.
What does it mean for a sentence to be "neutral" for an NLI model?
That the source you passed to it is not enough to establish whether the sentence is true or false. It is not a verdict of falsehood: a correct sentence that is absent from the corpus comes out neutral, and that is why it is better to treat it with a warning and not a block.
Is it worth constraining generation to a JSON schema?
It is, where the runtime offers it, because it reduces syntax errors. But it guarantees the shape, not the truth, so validation after generation and the comparison with the sources remain necessary.
Sources
- OWASP GenAI: LLM05:2025 Improper Output Handling - the mitigation strategies (zero trust, validation of responses, encoding according to context, parameterized queries), consulted on 2026-11-12
- OWASP GenAI: LLM09:2025 Misinformation - the mitigation strategies (RAG, automatic validation, human oversight), consulted on 2026-11-12
- NIST AI 600-1: Generative AI Profile - the definition of confabulation among the twelve risks, consulted on 2026-11-12
- Ji et al., Survey of Hallucination in Natural Language Generation (arXiv:2202.03629) - the distinction between intrinsic and extrinsic hallucinations, read from the PDF, consulted on 2026-11-12
- Hugging Face: cross-encoder/nli-deberta-v3-small - the training data (SNLI, MultiNLI), the order of the three labels, the reported accuracies and the usage example, consulted on 2026-11-12
- Ollama: Structured Outputs - the format field that accepts a JSON schema and the suggestion to use Pydantic's model_json_schema(), consulted on 2026-11-12
- Pydantic: Configuration API - the default behavior of extra: ignore, and forbid, consulted on 2026-11-12
The listings were run twice with identical output (Python 3.14 for uscita_sicura.py, grounding.py and decisione.py; Python 3.10 with Pydantic 2.14.3 for formato.py). The model is a fake script and no model was run. The listing nli_schema.py was not run (schema to adapt).

Commenti
Caricamento commenti...
Sign in to comment