Sub topic 12
Grounding values in the source text
This chapter assumes you can call an LLM, parse its JSON reply, and validate it with a Pydantic model as in the previous chapters. It also assumes you can run basic Python string and regular-expression code.
Why validation is not enough
A Pydantic model checks shape. It confirms that total is a number and that vendor is a string. It cannot tell whether "Acme Corporation" appears in the document or the model made it up. A hallucinated value that has the right type passes validation without any error.
Grounding adds a second check. For each extracted value, you confirm that the document supports it. The check is cheap, needs no extra model call, and catches invented vendors, invoice numbers copied from the prompt's examples, and values "completed" from the model's memory.
What a grounding check can and cannot prove
| Check | Catches | Misses |
|---|---|---|
| Substring match | Invented names and IDs | A real value from the wrong place |
| Amount match | Invented or mis-typed numbers | The subtotal returned as the total |
| Fuzzy match | OCR noise in the source | Near-miss values such as `INV-2041` vs `INV-2047` |
| Evidence quote | Values with no stated support | A quote that is real but irrelevant |
Normalizing before you compare
Raw in checks fail for harmless reasons. PDF text has line breaks in the middle of names, doubled spaces, non-breaking spaces, and soft hyphens. Normalize both sides the same way before comparing.
import re
import unicodedata
from decimal import Decimal
def normalize(text):
text = unicodedata.normalize("NFKC", str(text)) # folds non-breaking spaces, ligatures
text = text.replace("\u00ad", "") # drop soft hyphens
return " ".join(text.split()).casefold()
def is_grounded(value, source_text):
if value is None:
return True # null means "not present", so there is nothing to verify
return normalize(value) in normalize(source_text)
source = "INVOICE\nAcme Corp.\nInvoice No: INV-2041\nTotal due: 1,234.50 EUR"
print(is_grounded("Acme Corp.", source)) # True
print(is_grounded("Acme Corporation", source)) # Falsecasefold() is a stronger form of lower() that handles characters such as the German ß. Do not strip punctuation by default. INV-2041 and INV2041 may be different identifiers.
Checking numbers and dates
The model returns 1234.5 as a number, but the document says 1,234.50 or 1.234,50. A substring check on the number always fails. Instead, generate the ways the value might be written and look for any of them.
def amount_variants(value):
d = Decimal(str(value)).quantize(Decimal("0.01"))
us = f"{d:,.2f}" # 1,234.50
eu = us.replace(",", "X").replace(".", ",").replace("X", ".") # 1.234,50
plain = f"{d:.2f}" # 1234.50
variants = {us, eu, plain, plain.replace(".", ","), us.replace(",", " ")}
if d == d.to_integral_value():
variants.add(f"{d:,.0f}") # 1,500
variants.add(f"{d:.0f}") # 1500
return variants
def is_amount_grounded(value, source_text):
if value is None:
return True
haystack = normalize(source_text)
for variant in amount_variants(value):
# The boundaries stop "234.50" from matching inside "1,234.50".
pattern = r"(?<![\d.,])" + re.escape(variant) + r"(?!\d|[.,]\d)"
if re.search(pattern, haystack):
return True
return False
print(is_amount_grounded(1234.5, source)) # True
print(is_amount_grounded(234.5, source)) # False
print(is_amount_grounded(999.0, source)) # FalseDates follow the same idea. The schema asks for YYYY-MM-DD, but the document may say 3 March 2025 or 03/03/25. Build a few renderings with datetime.strftime, or check that the day, month and year each appear. Be careful with 03/04/25, which is ambiguous between day-first and month-first. Treat ambiguous dates as review candidates even when they are grounded.
Tolerating OCR noise
On scanned pages, OCR may read Acme Corp as Acme C0rp. An exact check then flags a correct value. A fuzzy check slides a window the length of the value across the source and keeps the best similarity score.
from difflib import SequenceMatcher
def best_match_ratio(value, source_text):
needle = normalize(value)
haystack = normalize(source_text)
if needle in haystack:
return 1.0
best = 0.0
for i in range(max(1, len(haystack) - len(needle) + 1)):
window = haystack[i:i + len(needle)]
best = max(best, SequenceMatcher(None, needle, window).ratio())
return best
print(round(best_match_ratio("Acme Corp", "Acme C0rp, Berlin"), 2)) # about 0.89Choose the threshold from data. A low threshold such as 0.7 accepts INV-2047 for INV-2041. For identifiers and amounts, require exact matches and use fuzzy matching only for names and free text. The window scan is quadratic, so run it on one page or chunk at a time, not on a 300-page document.
Asking the model for evidence quotes
A stronger design asks the model to return, for each value, the exact text it read it from. You then verify two things. The quote must appear in the source, and the value must appear in the quote. The model must commit to a location, and your code checks that location.
def check_evidence(extraction, source_text):
haystack = normalize(source_text)
problems = []
for name, item in extraction.items():
value, quote = item["value"], item.get("quote")
if value is None:
continue
if not quote or normalize(quote) not in haystack:
problems.append((name, "quote not found in source"))
continue
if isinstance(value, (int, float)):
supported = is_amount_grounded(value, quote)
else:
supported = normalize(value) in normalize(quote)
if not supported:
problems.append((name, "value not supported by quote"))
return problems
extraction = {
"vendor": {"value": "Acme Corp", "quote": "Acme Corp."},
"invoice_number": {"value": "INV-2041", "quote": "Invoice No: INV-2041"},
"total": {"value": 1234.5, "quote": "Total due: 1,234.50 EUR"},
"currency": {"value": "USD", "quote": None},
}
print(check_evidence(extraction, source))
# [('currency', 'quote not found in source')]In the prompt, add a rule such as: "For every non-null value, also return quote, a short exact copy of the text you used. Do not paraphrase." Quotes cost extra output tokens. Reserve them for the fields where a wrong value is expensive.
Deciding what to do with failures
Choose a policy per field, not one policy for the whole record.
- Identifiers and amounts: an ungrounded value is suspect. Do not accept it automatically.
- Descriptive text: the model may legitimately normalize wording, so use fuzzy matching or skip the check.
- Inferred fields: a
currencyderived from a€symbol will not appear asEUR. Either allow a lookup table of symbols, or make the field explicitly "inferred" in the schema.
Collect the failures in a list such as suspect_fields. A later chapter routes records with suspect fields to human review, and the pipeline chapter wires that list into the full flow.
Common errors
- Comparing before normalizing. Line breaks and non-breaking spaces cause false alarms.
- Substring matches inside longer tokens.
34.50matches inside1,234.50unless you add boundaries. - Treating null as a failure. A null value has nothing to verify, and flagging it hides the real signal.
- Grounding against the wrong text. Check against the same text the model saw. If you chunked the document, check each field against its own chunk, or against the full text if the field came from merging.
- Trusting the score for everything. A passing check shows only that the value exists in the document.
Exercise
A model extracts total = 450.0 from an invoice that contains the lines "Subtotal: 450.00" and "Total due: 535.50". Does is_amount_grounded(450.0, source) return True? What does this show about grounding, and what other check would help?
Show answer
It returns True, because "450.00" appears in the subtotal line. Grounding confirms that a value exists in the document, not that it belongs to the right field. An evidence quote check would help, because the quote "Subtotal: 450.00" shows the model read the wrong line. Field-level accuracy against labeled examples would also reveal the pattern.
Exercise
Why does is_amount_grounded use the lookbehind (?<![\d.,]) and the lookahead (?!\d|[.,]\d) around each variant?
Show answer
They make sure the variant is a whole number in the source and not part of a longer one. Without them, 234.50 would match inside 1,234.50, and 1,234.5 would match the start of 1,234.56. The grounding check would then accept wrong amounts.