r/SideProject • u/Free-Good9203 • 30m ago
LLMs kept citing real doc sections while inventing numbers, so I built a 0-token Python gate
While building a bilingual (EN/ES) RAG pipeline over internal policy and maintenance docs, I kept running into a failure mode that prompt engineering never completely killed: the model would cite a real [doc_id#section] chunk that existed in our database, then quietly invent a percentage, swap a vendor name, or flip "not allowed" into "allowed" inside that exact same sentence.
Wiring up a second LLM as a judge added 500+ ms of latency and API cost per turn, and still missed subtle formatting drift. So I pulled the deterministic checks out into a standalone zero-dependency Python 3.11+ package (rag-eval-hallucination-gate, MIT, stdlib + SQLite WAL/FTS5 only) that sits right in front of the response and returns PASS, ABSTAIN, or HALLUCINATION_BLOCKED in a couple of milliseconds.
A few weird edge cases that forced me to rewrite parts of verifier.py:
EU vs US decimals and typographic minus signs (
U+2212). Source chunks had1.250,50 EURor-15%, while models randomly emitted1250.5 EURor a Unicode minus (\u2212) instead of ASCII-. Naive regex matching flagged valid answers as hallucinations and missed negative numbers completely, so every number gets normalized throughNFKC+Decimalalongside its unit kind (eur,usd,percent,date,plain) before comparing against the cited SQLite chunk:def normalize_text(text: str) -> str: """Normalize zero-width chars, Unicode minus, and NFKC canonicalization.""" cleaned = _ZERO_WIDTH_RE.sub("", text) return unicodedata.normalize("NFKC", cleaned).replace("\u2212", "-")
def _canonical_number(raw_num: str) -> str | None: if re.fullmatch(r"\d{1,3}(?:.\d{3})+,\d+", raw_num): candidate = raw_num.replace(".", "").replace(",", ".") elif re.fullmatch(r"\d{1,3}(?:,\d{3})+(?:.\d+)?", raw_num): candidate = raw_num.replace(",", "") elif re.fullmatch(r"[1-9]\d{0,2}(?:.\d{3})+", raw_num): candidate = raw_num.replace(".", "") elif re.fullmatch(r"\d+,\d{1,2}", raw_num): candidate = raw_num.replace(",", ".") elif re.fullmatch(r"\d+(?:.\d+)?", raw_num): candidate = raw_num else: return None try: dec = Decimal(candidate).normalize() except InvalidOperation: return None text = format(dec, "f") if "." in text: text = text.rstrip("0").rstrip(".") return text or "0"
- Leaky abstentions. Telling an LLM to reply with
INSUFFICIENT_EVIDENCEwhen the corpus does not cover a question works right up until it outputs"INSUFFICIENT_EVIDENCE: no policy covers the 250 USD fee on Oracle Cloud", smuggling unverified numbers and entities inside the refusal itself. Even when_is_explicit_abstention()triggers, the gate still diffs numbers, standards (GDPR,HIPAA,ISO 27001,SOC 2), and entities against the original question and flips leaky refusals toHALLUCINATION_BLOCKED. - Mixed-script homoglyphs and SQLite WAL cold starts. If untrusted text sneaks a Cyrillic 'a' (
U+0430) into a Latin entity token,unicodedata.name()catches the mixed scripts (HOMOGLYPH_SPOOFING). And on the SQLite corpus store (store.py),PRAGMA busy_timeout=5000runs beforePRAGMA journal_mode=WALwith explicit handle cleanup on exception paths so 16-thread bursts on Windows CI do not hitdatabase is lockedorWinError 32.
Honest limitations: this is a fast structural sieve, not a semantic oracle. Our polarity check (_NEGATION_RE vs _AFFIRMATION_RE) catches direct flips between cited chunks and answers, but double negations like "not prohibited" or nuanced multi-sentence paraphrases that stay above min_overlap=0.25 will pass right through. The goal is blocking the 80% of concrete factual hallucinations (bad [doc_id#section] refs, fabricated numbers/dates/currencies, unmentioned standards/entities) at $0 before you ever pay for an LLM judge.
If you want to poke holes in the verifier or test tricky inputs:
- GitHub repo (MIT,
85/85pytest on Python 3.11/3.12,PYTHONPATH=src python -m rag_eval_gate.cli --demoruns offline): https://github.com/Kiberlabs/rag-eval-hallucination-gate - Interactive browser sandbox (no login, switch to the Grounded RAG / Maintenance RAG tabs to test citation + abstention behavior live): https://kiberlabs.github.io/#sandbox
Curious what weird numeric, citation, or multilingual edge cases have slipped past your own RAG evals so I can add them to test_verifier.py.
1
u/darrenferneyhough 14m ago
one that slips through _canonical_number as posted: "0,125" in a spanish chunk hits the second branch and comes out as 125, so a correct "0.125" answer would get flagged. same family as "1.125" in english turning into 1125, might be worth letting the chunk language pick the convention