EvidenceGuard-AI / src /evidence_verifier.py
leeshal's picture
Upload 55 files
a805048 verified
Raw History Blame Contribute Delete
19.2 kB
"""Evidence verification layer of EvidenceGuard AI.
1. Evidence sufficiency - is the question actually covered by the retrieved passages?
2. Contradiction detection - do relevant passages from different documents disagree?
3. Citation validation - is every answer sentence supported by the passage it cites?
Two interchangeable judges are provided:
* NLIJudge : cross-encoder/nli-deberta-v3-xsmall (Apache-2.0), probabilities for
contradiction / entailment / neutral.
* no NLI : rule-based checks only (numeric value mismatch, polarity/negation flip,
lexical & numeric support). Always active - NLI models are known to be weak
at comparing numbers, which dominate policy documents, so the numeric rule
is kept even when NLI is available (union of both signals).
"""
from __future__ import annotations
import logging
import re
from dataclasses import asdict, dataclass, field
import numpy as np
import config
from src.text_utils import (DOMAIN_STOPWORDS, content_tokens, extract_facts, fact_occurrences,
fact_values, split_sentences, tokenize)
log = logging.getLogger(__name__)
_NEG = re.compile(r"\b(not|cannot|no|never|without)\b")
_UPDATE_CUE = re.compile(r"\b(supersedes?|revised to|extended to|with effect from|amendment|is revised)\b", re.I)
_BOILERPLATE = re.compile(r"Document No\.|Issued by:|Effective from", re.I)
def stem(t: str) -> str:
"""Tiny suffix stripper (plural / -ed / -ing); enough to match 'electives' with 'elective'."""
if len(t) <= 3 or not t.isalpha() and "-" not in t:
return t
if t.endswith("ies") and len(t) > 4:
return t[:-3] + "y"
if t.endswith(("sses", "xes", "ches", "shes")):
return t[:-2]
if t.endswith("s") and not t.endswith(("ss", "us", "is")):
t = t[:-1]
for suf in ("ing", "ed"):
if len(t) > 5 and t.endswith(suf):
return t[: -len(suf)]
return t
def stems(text: str, drop_domain: bool = False) -> set[str]:
return {stem(t) for t in content_tokens(text, drop_domain=drop_domain)}
def topic_tokens(text: str) -> set[str]:
"""Content stems without numbers - what a sentence is *about*."""
return {stem(t) for t in content_tokens(text, drop_domain=True)
if not re.match(r"^\d", t) and t not in {"inr", "per", "up", "least"}}
def is_negated(text: str) -> bool:
return bool(_NEG.search(text.lower()))
def negated_predicates(text: str) -> set[str]:
"""Stems of the words a negation applies to: 'will not be accepted' -> {'accept'}."""
out = set()
for m in re.finditer(r"\b(?:not|cannot|never)\s+(?:be\s+|been\s+)?([a-z]+)", text.lower()):
w = stem(m.group(1))
out.add(w[:-2] if w.endswith("ed") else w)
return out
# ====================================================================== NLI
class NLIJudge:
def __init__(self, model_name: str = config.NLI_MODEL):
from sentence_transformers import CrossEncoder
self.model = CrossEncoder(model_name, device="cpu")
cfg = getattr(self.model, "config", None) or self.model.model.config
self.labels = {int(k): v.lower() for k, v in cfg.id2label.items()}
self.name = f"NLI cross-encoder ({model_name})"
def probs(self, pairs: list[tuple[str, str]]) -> list[dict]:
if not pairs:
return []
logits = np.asarray(self.model.predict(pairs, show_progress_bar=False), dtype="float64")
if logits.ndim == 1:
logits = logits[None, :]
e = np.exp(logits - logits.max(axis=1, keepdims=True))
p = e / e.sum(axis=1, keepdims=True)
return [{self.labels[j]: float(row[j]) for j in range(row.shape[0])} for row in p]
def load_nli(backend: str = config.EG_BACKEND):
if backend in ("full", "auto"):
try:
return NLIJudge()
except Exception as e:
if backend == "full":
raise
log.warning("NLI model unavailable (%s); using rule-based verification only", e)
return None
# ====================================================================== results
@dataclass
class Sufficiency:
status: str # sufficient | partial | insufficient
max_relevance: float
coverage: float # combined coverage score
coverage_single: float
coverage_union: float
missing_terms: list = field(default_factory=list)
@dataclass
class Conflict:
doc_a: str
title_a: str
page_a: int
issued_a: str
sentence_a: str
doc_b: str
title_b: str
page_b: int
issued_b: str
sentence_b: str
kind: str # numeric | polarity | nli
detail: str
newer: str # title of the more recent document ("" if unknown)
explicit_update: bool
passage_a: int = 0 # 1-based index in the context list
passage_b: int = 0
@dataclass
class CitationCheck:
sentence: str
cited: list
supported: bool
score: float
reason: str
# ====================================================================== verifier
class EvidenceVerifier:
def __init__(self, kb, nli: NLIJudge | None = None, thresholds: dict | None = None):
self.kb = kb
self.nli = nli
self.th = thresholds or config.load_thresholds()
@property
def name(self):
return (self.nli.name + " + numeric/polarity rules") if self.nli else \
"Rule-based verifier (numeric mismatch, polarity flip, lexical support) - offline fallback"
# ------------------------------------------------------------------ 1. sufficiency
def query_terms(self, question: str) -> list[str]:
q = list(dict.fromkeys(stem(t) for t in content_tokens(question, drop_domain=True)))
return q or list(dict.fromkeys(stem(t) for t in content_tokens(question)))
def _weight(self, term: str) -> float:
# IDF is stored for raw tokens; try stem and common surface forms.
for cand in (term, term + "s", term + "es", term + "ed", term + "ing"):
if self.kb.in_vocab(cand):
return self.kb.term_idf(cand)
return self.kb.max_idf + 1.0
def sufficiency(self, question: str, items) -> Sufficiency:
terms = self.query_terms(question)
if not items or not terms:
return Sufficiency("insufficient", 0.0, 0.0, 0.0, 0.0, terms)
w = {t: self._weight(t) for t in terms}
total = sum(w.values())
top = items[:3]
pst = [stems(f"{r.chunk.title}. {r.chunk.text}") for r in top]
single = max(sum(w[t] for t in terms if t in s) / total for s in pst)
union_set = set().union(*pst)
union = sum(w[t] for t in terms if t in union_set) / total
cov = 0.5 * single + 0.5 * union
surface = {stem(t): t for t in content_tokens(question)} # stem -> word as typed
missing = [t for t in terms if t not in union_set]
# Content words that never occur anywhere in the collection (e.g. "revaluation",
# "convocation") mean the topic itself is absent: never offer a partial answer then.
oov = [t for t in missing if not re.match(r"^\d", t) and not any(
self.kb.in_vocab(c) for c in (t, t + "s", t + "es", t + "ed", t + "ing"))]
rel = max(r.relevance for r in items)
if rel >= self.th["min_relevance"] and cov >= self.th["min_coverage"]:
status = "sufficient"
elif rel >= self.th["min_relevance"] * 0.8 and cov >= self.th["partial_coverage"] and not oov:
status = "partial"
else:
status = "insufficient"
return Sufficiency(status, float(rel), float(cov), float(single), float(union),
[surface.get(t, t) for t in missing])
def sentence_coverage(self, question: str, sentence: str) -> float:
terms = self.query_terms(question)
if not terms:
return 0.0
w = {t: self._weight(t) for t in terms}
st = stems(sentence)
return sum(w[t] for t in terms if t in st) / sum(w.values())
# ------------------------------------------------------------------ 2. contradiction detection
def expand_for_conflicts(self, question: str, items, retriever, k: int = 4):
"""Conflict-search retrieval.
Competing versions of a rule are often *not* in the top-k for the question (an amendment
circular is short and phrased differently). Each of the best evidence sentences is used as
a new query; passages from OTHER documents that come back are added as conflict candidates.
"""
from src.retrieval import Retrieved
if retriever is None:
return []
have = {r.chunk.chunk_id for r in items}
docs = {r.chunk.doc_id for r in items}
anchors = [a for a in sorted(self._relevant_sentences(question, items), key=lambda x: -x[3])
if a[3] >= self.th["conflict_sentence_coverage"] and (extract_facts(a[2]) or is_negated(a[2]))][:3]
extra = []
for _, r, s, _ in anchors:
for cand in retriever.retrieve(s, k):
c = cand.chunk
if c.chunk_id in have or c.doc_id == r.chunk.doc_id:
continue
sim = max((self._topic_sim(s, x) for x in split_sentences(c.text)), default=0.0)
if sim >= self.th["conflict_topic_sim"]:
have.add(c.chunk_id)
extra.append(Retrieved(c, cand.score, dense=cand.dense, sparse=cand.sparse,
rerank=r.relevance * 0.99, source="conflict-search"))
del docs
return extra
def _relevant_sentences(self, question: str, items):
"""Sentences that are themselves about the question (not merely in a relevant chunk)."""
out = []
for idx, r in enumerate(items, 1):
expansion = getattr(r, "source", "") == "conflict-search"
if r.relevance < self.th["conflict_min_relevance"] and not expansion:
continue
for s in split_sentences(r.chunk.text):
if _BOILERPLATE.search(s) or len(s.split()) < 5:
continue
cov = self.sentence_coverage(question, s)
if cov >= self.th["conflict_sentence_coverage"] * 0.5:
out.append((idx, r, s, cov))
return out
@staticmethod
def _topic_sim(a: str, b: str) -> float:
"""Overlap coefficient of the (number-free) content stems of two sentences."""
ta, tb = topic_tokens(a), topic_tokens(b)
if not ta or not tb:
return 0.0
return len(ta & tb) / min(len(ta), len(tb))
def _numeric_clash(self, question: str, a: str, b: str, min_shared: int = 2):
"""Same kind of value, different number, described by overlapping words around it.
Two extra guards against false alarms:
* the value must be of the type the question asks about ("how many marks" -> marks);
* the question words that sit next to the value must agree in both sentences
(8 books for *research scholars* is not a conflict with 6 books for *PG students*).
"""
from src.llm_generator import expected_answer_type
want = expected_answer_type(question)
qt = set(self.query_terms(question))
best = None
sa_st, sb_st = stems(a), stems(b)
for ua, va, ca in fact_occurrences(a, before=75, after=40):
if want and ua not in want:
continue
wa = topic_tokens(ca)
for ub, vb, cb in fact_occurrences(b, before=75, after=40):
if ua != ub or va == vb:
continue
if ua not in ("date", "time"):
x, y = float(va), float(vb)
if min(x, y) > 0 and max(x, y) / min(x, y) > 5: # different quantities, not versions
continue
wb = topic_tokens(cb)
shared = wa & wb
# question words describing either value must also occur in the other sentence
near_q = (wa | wb) & qt
if near_q:
missing = {t for t in near_q if not (t in sa_st and t in sb_st)}
if sum(self._weight(t) for t in missing) / sum(self._weight(t) for t in near_q) > \
self.th["conflict_subject_mismatch"]:
continue
if (len(shared) >= min_shared or shared & qt) and (best is None or len(shared) > best[0]):
best = (len(shared), f"{ua}: {va} vs {vb} (context: {', '.join(sorted(shared)[:4])})")
return best[1] if best else None
def detect_conflicts(self, question: str, items) -> list[Conflict]:
sents = self._relevant_sentences(question, items)
best_cov = max((x[3] for x in sents), default=0.0)
pairs = []
for i in range(len(sents)):
for j in range(i + 1, len(sents)):
(ia, ra, sa, ca_), (ib, rb, sb, cb_) = sents[i], sents[j]
if ra.chunk.doc_id == rb.chunk.doc_id:
continue
# one side must be (close to) the best-matching evidence sentence
if max(ca_, cb_) < max(self.th["conflict_sentence_coverage"], 0.8 * best_cov):
continue
pairs.append((self._topic_sim(sa, sb), ia, ra, sa, ib, rb, sb, sents[i][3] + sents[j][3]))
# Most query-relevant pairs first, so the reported conflict is the one the user asked about.
pairs.sort(key=lambda p: -p[7])
pairs = [p[:7] for p in pairs]
nli_probs = []
if self.nli and pairs:
nli_probs = self.nli.probs([(p[3], p[6]) for p in pairs])
found, seen = [], set()
for k, (sim, ia, ra, sa, ib, rb, sb) in enumerate(pairs):
kind, detail = None, ""
clash = self._numeric_clash(question, sa, sb, int(self.th["conflict_min_shared"]))
if clash:
kind, detail = "numeric", clash
elif is_negated(sa) != is_negated(sb) and sim >= self.th["conflict_topic_sim"] and \
any(p in {x[:len(p)] for x in stems(sb if is_negated(sa) else sa)}
for p in negated_predicates(sa if is_negated(sa) else sb)):
kind, detail = "polarity", "one passage permits what the other rules out"
elif nli_probs and nli_probs[k].get("contradiction", 0) >= self.th["nli_contradiction"] \
and sim >= self.th["conflict_topic_sim"]:
kind, detail = "nli", f"NLI contradiction p={nli_probs[k]['contradiction']:.2f}"
if not kind:
continue
key = tuple(sorted([ra.chunk.doc_id, rb.chunk.doc_id]))
if key in seen:
continue
seen.add(key)
ca, cb = ra.chunk, rb.chunk
newer = ""
if ca.issued and cb.issued and ca.issued != cb.issued:
newer = ca.title if ca.issued > cb.issued else cb.title
explicit = bool(_UPDATE_CUE.search(sa) or _UPDATE_CUE.search(sb) or
_UPDATE_CUE.search(ca.text) and ca.issued >= cb.issued or
_UPDATE_CUE.search(cb.text) and cb.issued >= ca.issued)
found.append(Conflict(ca.doc_id, ca.title, ca.page, ca.issued, sa,
cb.doc_id, cb.title, cb.page, cb.issued, sb,
kind, detail, newer, explicit, ia, ib))
return found[:3]
# ------------------------------------------------------------------ 3. citation validation
def _lexical_support(self, sentence: str, passage: str) -> tuple[float, str]:
s_vals, p_vals = fact_values(sentence), fact_values(passage)
missing_vals = s_vals - p_vals
st = stems(re.sub(r"\[\d+\]", "", sentence))
pt = stems(passage)
overlap = len(st & pt) / max(1, len(st))
if missing_vals:
return min(overlap, 0.2), f"values {sorted(missing_vals)} not found in cited passage"
return overlap, f"token overlap {overlap:.2f}"
def validate_citations(self, claims, items) -> list[CitationCheck]:
checks = []
texts = [f"{r.chunk.title}. {r.chunk.text}" for r in items]
nli_inputs = []
for sent, cited in claims:
cited_ok = [c for c in cited if 1 <= c <= len(items)]
pool = cited_ok or list(range(1, len(items) + 1))
best, reason, best_c = -1.0, "no passage", []
for c in pool:
sc, why = self._lexical_support(sent, texts[c - 1])
if sc > best:
best, reason, best_c = sc, why, [c]
checks.append(CitationCheck(sent, cited_ok, best >= self.th["citation_overlap"], float(best),
reason if cited_ok else "uncited sentence; " + reason))
nli_inputs.append((texts[best_c[0] - 1] if best_c else "", sent))
if self.nli and checks:
probs = self.nli.probs([(p, re.sub(r"\[\d+\]", "", h)) for p, h in nli_inputs])
for chk, pr in zip(checks, probs):
ent = pr.get("entailment", 0.0)
if not chk.supported and ent >= self.th["nli_entailment"] and "not found" not in chk.reason:
chk.supported, chk.reason = True, chk.reason + f"; NLI entailment {ent:.2f}"
else:
chk.reason += f"; NLI entailment {ent:.2f}"
return checks
# ------------------------------------------------------------------ premise check
@staticmethod
def premise_issues(question: str, evidence_sentences: list[str]) -> list[str]:
"""Values asserted in the question that the evidence states differently.
For every value in the question (e.g. "50 marks" in "Given that internal assessment
carries 50 marks ...") find the evidence value of the same unit whose surrounding words
best match the question's words around it; report it if the numbers differ.
"""
issues = []
for uq, vq, cq in fact_occurrences(question, before=45, after=30):
wq = topic_tokens(cq)
best = None
for s in evidence_sentences:
for ue, ve, ce in fact_occurrences(s, before=45, after=30):
if ue != uq:
continue
shared = len(wq & topic_tokens(ce))
if shared >= 1 and (best is None or shared > best[0]):
best = (shared, ve)
if best and best[1] != vq:
unit = "" if uq == "%" else f" {uq}"
issues.append(f"the question assumes {vq}{unit}, but the documents state {best[1]}{unit}")
return issues
def to_dict(obj):
return asdict(obj) if hasattr(obj, "__dataclass_fields__") else obj
__all__ = ["EvidenceVerifier", "load_nli", "Sufficiency", "Conflict", "CitationCheck", "to_dict",
"DOMAIN_STOPWORDS", "tokenize"]