Extract–Explain Split
Let deterministic code read and validate the facts, let the model only explain them, and rebuild the final answer from the extraction so the model cannot change a number or add an item.
cd examples && pytest security_and_trust/test_extract_explain_split.pyWhat It Is
A split between two jobs that are often given to one model call. Extraction reads the facts out of a document: test names, values, units, amounts, dates. Explanation turns those facts into language a person understands. In this pattern, extraction is ordinary code (parsers, OCR, lookup tables) followed by a deterministic validator. The model gets only the validated facts and writes the explanation. Afterwards, code rebuilds the answer's factual parts from the extraction and keeps the model's text only where it agrees with them.
The name is ours. The principle underneath is the familiar one of not letting a probabilistic component be the source of truth for facts that matter.
The Problem It Solves
Ask a model to "read this lab report and explain the results" and it does both in one step, which hides a nasty failure. It can misread 10.8 as 11, swap a value with its reference range, or produce a test that isn't on the page, and then write a fluent, confident explanation of the wrong number. Because reading and explaining happened together, there's no checkpoint where anyone, or anything, could have caught it.
Telling the model "only explain, don't change values" helps, but it's a request. Without a check in code, a model that changes a value or files a low result under "normal" goes straight to the user, with nothing to flag it.
How It Works
flowchart LR
D["Document"] --> E["Deterministic extractor
(parser, OCR, synonym table)"]
E --> V{"Validator
unit class · hard limits ·
cross-field consistency"}
V -->|"rejected"| R["Shown to the user as
'found but couldn't be validated'"]
V -->|"valid facts"| M["Model: explain these facts
(never sees raw text)"]
M --> C["Reconcile in code:
facts from extraction,
text only where model agrees"]
V --> C
C --> A["Answer"]
- Extract with code. Parse the document into a typed intermediate record: canonical ID, raw text, value, unit, source line. Map synonyms ("Glycated Haemoglobin" means
hba1c) through a table, not the model. - Validate with code. Reject values in the wrong unit class and values outside what's physically possible (a hard limit set wide enough that anything beyond it is an extraction error). Flag combinations that contradict each other. Never use a model to validate a model.
- Show what was rejected. "A potassium value of 22 was found but failed validation; check the original" is honest, and far better than silently dropping it or explaining it.
- Explain from the record only. The prompt contains the validated facts as structured data and says not to change or add values. The model never sees the raw document, so it has nothing to re-extract from.
- Reconcile after the model answers. Build the final list of values and statuses from the extraction. Attach the model's explanation to a fact only when its ID matches and the model agreed on the status. Drop and log anything else. This step is what turns "only explain" from a request into a guarantee.
When to Use It
- The answer contains facts where a wrong value causes harm or costs money: lab results, invoices, contract terms, account balances, dosages.
- The facts have a structure that code can read, even if reading it takes several tiers (digital text, table OCR, a vision model as a last resort).
- People need plain-language help understanding facts, not just a table of them.
When NOT to Use It
- There are no extractable facts. Summaries of opinions, brainstorming and drafting have nothing for the split to protect.
- You can't build an extractor that beats the model. For messy, unstructured inputs the model may simply be the best extractor available. Then validate its output deterministically and let a person confirm it (Suggest–Edit–Commit) instead.
- The explanation must reason about values the extractor can't produce. If the model needs to infer missing facts, the split forces those to be explicit gaps, which may be the right answer but changes the product.
Trade-offs
- The extractor is real engineering. Parsers, synonym tables, unit conversion and limits per field take time, and each new document format needs work. That is the price of a checkable source of truth.
- Explanations get narrower. The model can't mention what extraction didn't capture. Users sometimes notice "it ignored the doctor's note". Decide which fields to extract on purpose.
- Validation limits need owners. Hard limits set too tight reject real values (unit-conversion bugs are a classic cause). Too loose and they catch nothing. Test them with real documents.
Failure Modes
Trusting the model's copy of the facts. The architecture says "the model only explains", but the final values are read back from the model's JSON. The model rounds 10.8 to 11 and files a borderline value as normal, and nothing compares it with the extraction. Rebuild every fact from the extraction after the model answers.
Validating before normalizing. Limits written in one unit reject correct values reported in another (mmol/L against mg/dL limits). Convert to canonical units first, then validate.
The model still sees raw text. It's passed "for context", and the model helpfully re-extracts and contradicts the validated record. Send only the record.
Rejected values disappear. A value fails validation and is dropped silently, and the user never learns their report had a reading the system couldn't trust. List rejected values in the answer.
Implementation Example
A small catalog (synonyms, unit classes, hard limits, normal ranges), a deterministic extractor and validator, an explanation call that sees only validated facts, and a reconciler. The tests include a report with an impossible potassium value (rejected and never sent to the model) and a model reply that flips a status and invents a test. Both are dropped, and the extracted values come through untouched.
cd examples && pytest security_and_trust/test_extract_explain_split.py"""Extract–Explain Split.
When an answer contains facts that matter (numbers, names, statuses), don't
let the model produce them. A deterministic extractor reads the facts, a
deterministic validator rejects impossible ones, and the model receives only
the validated facts and writes the explanation. Then code rebuilds the final
answer from the extraction, so the model cannot change a value, flip a
status or add an item, even if it tries.
The example reads lab results from report text. The same shape fits invoices,
contracts, logs: anywhere a wrong fact is worse than a plain explanation.
"""
from __future__ import annotations
import json
import re
from collections.abc import Callable
from dataclasses import dataclass, field
@dataclass(frozen=True)
class Test:
id: str
names: tuple[str, ...] # synonyms as they appear in documents, lowercase
units: frozenset[str] # accepted unit class
hard_limits: tuple[float, float] # outside this, the value is an extraction error
normal: tuple[float, float]
CATALOG = [
Test("glucose_fasting", ("fasting glucose", "fbs", "glucose fasting"), frozenset({"mg/dl"}), (10, 800), (70, 100)),
Test("hba1c", ("hba1c", "glycated haemoglobin", "glycated hemoglobin"), frozenset({"%"}), (2, 20), (4.0, 5.6)),
Test("potassium", ("potassium", "k+"), frozenset({"meq/l", "mmol/l"}), (1.5, 9.0), (3.5, 5.1)),
]
LINE = re.compile(r"^\s*(?P<name>[A-Za-z][A-Za-z0-9+ ]*?)\s*[:\-]?\s*(?P<value>\d+(?:\.\d+)?)\s*(?P<unit>[A-Za-z%/]+)", re.M)
@dataclass
class Fact:
test_id: str
value: float
unit: str
status: str # "low" | "normal" | "high"
source_line: str
@dataclass
class Report:
facts: list[Fact] = field(default_factory=list)
rejected: list[str] = field(default_factory=list) # shown to the user, never sent to the model
explanations: dict[str, str] = field(default_factory=dict)
dropped_from_model: list[str] = field(default_factory=list) # model output that didn't match a fact
def extract(text: str, catalog: list[Test] = CATALOG) -> Report:
by_name = {n: t for t in catalog for n in t.names}
report = Report()
for m in LINE.finditer(text):
test = by_name.get(m["name"].strip().lower())
if test is None:
continue
value, unit, line = float(m["value"]), m["unit"].lower(), m.group(0).strip()
if unit not in test.units:
report.rejected.append(f"{line}: unit {unit!r} is not valid for {test.id}")
elif not test.hard_limits[0] <= value <= test.hard_limits[1]:
report.rejected.append(f"{line}: {value} is outside what is physically possible; check the original")
else:
lo, hi = test.normal
status = "low" if value < lo else "high" if value > hi else "normal"
report.facts.append(Fact(test.id, value, unit, status, line))
return report
PROMPT = """You explain results that were already extracted and validated by another system.
Do not re-extract, change or add values. For each test_id below, explain in plain language
what the result means. Reply as JSON: {{"<test_id>": {{"status": "<status as given>", "explanation": "..."}}}}.
{facts}"""
def explain(report: Report, llm: Callable[[str], str]) -> Report:
if not report.facts:
return report
payload = json.dumps([{"test_id": f.test_id, "value": f.value, "unit": f.unit, "status": f.status}
for f in report.facts], indent=1)
try:
reply = json.loads(llm(PROMPT.format(facts=payload)))
except json.JSONDecodeError:
reply = {}
# Reconcile: the extraction is the source of truth. "Only explain" in the prompt is a
# request; this is the guarantee.
facts = {f.test_id: f for f in report.facts}
for test_id, item in (reply if isinstance(reply, dict) else {}).items():
fact = facts.get(test_id)
if fact is None:
report.dropped_from_model.append(f"{test_id}: not in the extraction (invented)")
elif not isinstance(item, dict) or item.get("status") != fact.status:
report.dropped_from_model.append(f"{test_id}: model disagreed with status {fact.status!r}")
else:
report.explanations[test_id] = str(item.get("explanation", ""))
return reportTool Landscape
| Tool | Notes |
|---|---|
| Document parsers and table OCR (pdfplumber, PaddleOCR PP-Structure, Tesseract) | The deterministic first tiers of extraction |
| Domain ontologies (LOINC, UCUM units, ISO 4217) | Canonical IDs and units the validator can rely on |
| Pydantic, JSON Schema | The typed intermediate record between the two halves |
| Structured outputs | Keep the explanation reply parseable; still reconcile it |
Related Patterns
- Grounding Verifier checks a model's claims against sources after the fact. This pattern keeps the model from producing the facts at all.
- Closed-Vocabulary Output validates what the model returns. Here the model's facts are replaced outright.
- Intent-Only Retrieval applies the same principle to search: the model reads the question, and your data supplies the answer.
- Suggest–Edit–Commit is the fallback when extraction must come from a model: the person confirms the facts.
Further Reading
- Survey of Hallucination in Natural Language Generation, Ji et al., 2022
- Emerging Patterns in Building GenAI Products, Bharani Subramaniam and Martin Fowler
- LOINC. An example of the canonical vocabulary an extractor maps to.
Spotted something wrong or have a production story? Edit this page on GitHub.