Spaces:
Running on Zero
Running on Zero
File size: 9,547 Bytes
a805048 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 | """SYSTEM B - EvidenceGuard RAG.
hybrid retrieval -> cross-encoder reranking -> evidence sufficiency -> contradiction detection
-> context-grounded generation -> citation validation -> confidence-based abstention -> explanation
Each stage can be switched off for the ablation study.
"""
from __future__ import annotations
import re
import time
from dataclasses import asdict
import config
from src.baseline_rag import passage_dicts
from src.retrieval import DenseRetriever, HybridRetriever
from src.reranker import rerank
from src.text_utils import split_sentences
ABSTAIN_TEXT = ("I could not find sufficient evidence in the uploaded documents to answer this question. "
"Please check with the relevant university office.")
_PRESUPPOSITION = re.compile(r"^\s*(since|given that|as|because|assuming)\b", re.I)
class EvidenceGuardRAG:
def __init__(self, kb, generator, reranker, verifier, use_hybrid=True, use_rerank=True,
use_verification=True, top_k: int = config.TOP_K, name: str = "EvidenceGuard RAG"):
self.kb, self.gen, self.reranker, self.verifier = kb, generator, reranker, verifier
self.retriever = HybridRetriever(kb) if use_hybrid else DenseRetriever(kb)
self.use_rerank, self.use_verification = use_rerank, use_verification
self.top_k, self.name = top_k, name
# ------------------------------------------------------------------
def answer(self, question: str) -> dict:
T = {}
t0 = time.perf_counter()
n = config.CANDIDATES if self.use_rerank else self.top_k
items = self.retriever.retrieve(question, n)
T["retrieval"] = time.perf_counter() - t0
t = time.perf_counter()
if self.use_rerank:
items = rerank(self.reranker, question, items, self.top_k)
elif self.use_verification and items:
# Verification needs calibrated relevance scores. Score passages for gating only;
# retrieval order and the passage set stay exactly as the dense retriever returned them.
for r, s in zip(items, self.reranker.score(question, [f"{r.chunk.title}. {r.chunk.text}" for r in items])):
r.rerank = float(s)
T["rerank"] = time.perf_counter() - t
if not self.use_verification:
gen = self.gen.generate(question, items, mode="grounded")
T["verification"], T["generation"] = 0.0, gen.seconds
T["total"] = time.perf_counter() - t0
return self._package(question, items, gen.claims, "answered", None, [], [], None,
"Verification disabled for this configuration.", T, gen.backend, [])
# ---------------- 1. sufficiency
t = time.perf_counter()
ordered = sorted(items, key=lambda r: -r.relevance)
suff = self.verifier.sufficiency(question, ordered)
if suff.status == "insufficient":
T["verification"] = time.perf_counter() - t
T["generation"] = 0.0
T["total"] = time.perf_counter() - t0
why = (f"Abstained: evidence is insufficient (best passage relevance {suff.max_relevance:.2f}, "
f"query coverage {suff.coverage:.2f}; thresholds {self.verifier.th['min_relevance']:.2f} / "
f"{self.verifier.th['min_coverage']:.2f}).")
if suff.missing_terms:
why += f" Question terms not found in the retrieved passages: {', '.join(suff.missing_terms[:8])}."
return self._package(question, items, [], "abstained", suff, [], [], 0.0, why, T, "", [])
# ---------------- 2. conflict-search retrieval + contradiction detection + premise check
items = items + self.verifier.expand_for_conflicts(question, items, self.retriever)
conflicts = self.verifier.detect_conflicts(question, items)
premise = []
if _PRESUPPOSITION.search(question):
ev = [s for r in ordered[:3] for s in split_sentences(r.chunk.text)]
premise = self.verifier.premise_issues(question, ev)
T["verification"] = time.perf_counter() - t
# ---------------- 3. grounded generation
gen = self.gen.generate(question, items, mode="grounded", conflicts=conflicts, premise_notes=premise)
T["generation"] = gen.seconds
if gen.declined:
T["total"] = time.perf_counter() - t0
return self._package(question, items, [], "abstained", suff, conflicts, [], 0.0,
"Abstained: the language model reported that the passages do not contain the answer.",
T, gen.backend, premise)
# ---------------- 4. citation validation
t = time.perf_counter()
checks = self.verifier.validate_citations(gen.claims, items)
T["verification"] += time.perf_counter() - t
supported = [(c.sentence, c.cited or [self._best_cite(c)]) for c in checks if c.supported]
ratio = len(supported) / max(1, len(checks))
# ---------------- 5. confidence & decision
conf = 0.4 * min(1.0, suff.max_relevance) + 0.4 * min(1.0, suff.coverage) + 0.2 * ratio
if not supported:
decision, why = "abstained", "Abstained: none of the generated sentences could be verified against the cited passages."
elif conf < self.verifier.th["min_confidence"]:
decision, why = "abstained", f"Abstained: confidence {conf:.2f} is below the threshold {self.verifier.th['min_confidence']:.2f}."
elif conflicts:
decision = "conflict"
why = ("Answered with a conflict warning: " + "; ".join(
f"'{c.title_a}' and '{c.title_b}' disagree ({c.detail})" for c in conflicts) + ".")
elif suff.status == "partial" or ratio < 1:
decision = "partial"
why = f"Partially answered: query coverage {suff.coverage:.2f}"
if suff.missing_terms:
why += f"; not covered: {', '.join(suff.missing_terms[:6])}"
if ratio < 1:
why += f"; {len(checks) - len(supported)} unsupported sentence(s) removed"
why += "."
else:
decision = "answered"
why = (f"Answered: relevance {suff.max_relevance:.2f}, coverage {suff.coverage:.2f}, "
f"{len(supported)}/{len(checks)} sentences verified against their citations.")
T["total"] = time.perf_counter() - t0
return self._package(question, items, supported if decision != "abstained" else [], decision, suff,
conflicts, checks, conf, why, T, gen.backend, premise)
@staticmethod
def _best_cite(check):
m = re.search(r"\[(\d+)\]", check.sentence)
return int(m.group(1)) if m else 1
# ------------------------------------------------------------------
def _render(self, claims, decision, conflicts, items, premise):
if decision == "abstained":
return ABSTAIN_TEXT
parts = []
if conflicts:
parts.append("⚠️ **Conflicting evidence found.** The documents disagree:")
shown = set()
for c in conflicts[:2]:
for title, issued, sent, n in ((c.title_a, c.issued_a, c.sentence_a, c.passage_a),
(c.title_b, c.issued_b, c.sentence_b, c.passage_b)):
if sent in shown:
continue
shown.add(sent)
parts.append(f"- *{title}* (issued {issued or 'unknown'}): {sent} [{n}]")
newest = conflicts[0].newer
if newest:
parts.append(f"The more recent document is *{newest}*"
+ (", which explicitly revises the earlier rule." if conflicts[0].explicit_update else ".")
+ " Please confirm with the issuing office before relying on either version.")
extra = [(s, c) for s, c in claims if s not in shown]
if extra:
parts.append("**Most relevant evidence:** " + " ".join(f"{s} [{', '.join(map(str, c))}]" for s, c in extra))
return "\n".join(parts)
for p in premise:
parts.append(f"**Note:** {p[0].upper() + p[1:]}.")
parts.append(" ".join(f"{s} [{', '.join(map(str, c))}]" for s, c in claims))
return "\n\n".join(parts)
def _package(self, question, items, claims, decision, suff, conflicts, checks, conf, why, T, backend, premise):
cited = sorted({c for _, cs in claims for c in cs if 1 <= c <= len(items)})
if decision == "conflict":
cited = sorted(set(cited) | {n for cf in conflicts for n in (cf.passage_a, cf.passage_b)})
return {
"system": self.name, "question": question,
"answer": self._render(claims, decision, conflicts, items, premise),
"decision": decision, "claims": claims,
"citations": [{"n": c, "doc_name": items[c - 1].chunk.doc_name, "title": items[c - 1].chunk.title,
"page": items[c - 1].chunk.page} for c in cited],
"passages": passage_dicts(items),
"sufficiency": asdict(suff) if suff else None,
"conflicts": [asdict(c) for c in conflicts],
"citation_checks": [asdict(c) for c in checks],
"premise_notes": premise,
"confidence": None if conf is None else round(conf, 3),
"explanation": why, "timings": T, "generator": backend,
}
|