Spaces:
Running on Zero
Running on Zero
File size: 11,456 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 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 | """Answer generation.
Backends
HFInferenceGenerator - Hugging Face Inference Providers (huggingface_hub.InferenceClient),
token read from the HF_TOKEN environment variable / Space secret.
LocalLLMGenerator - small instruction-tuned model (default Qwen/Qwen2.5-0.5B-Instruct,
Apache-2.0) run on CPU with transformers, greedy decoding.
ExtractiveGenerator - no LLM: composes the answer from the retrieved sentences that best
cover the question (offline fallback; cannot hallucinate new text,
but can still pick an irrelevant sentence - which is exactly the
failure EvidenceGuard's verification layer is designed to catch).
Every backend returns GenOutput with a list of (sentence, [cited passage numbers]) claims,
so citation validation works the same way for all of them.
"""
from __future__ import annotations
import logging
import re
import time
from dataclasses import dataclass, field
import config
from src.text_utils import content_tokens, extract_facts, split_sentences
log = logging.getLogger(__name__)
def expected_answer_type(question: str) -> set[str]:
"""Light answer-type detection (classic QA technique): which kind of value is asked for."""
q = question.lower()
m = re.search(r"\bhow many (working days|contact hours|days|books|marks|credits|minutes|semesters|years|"
r"members|weeks|months|hours)\b", q)
if m:
unit = m.group(1)
return {"days", "working days"} if unit in ("days", "working days") else {unit}
if re.search(r"\bhow many [a-z-]+", q) and not re.search(r"\bhow many (times|of)\b", q):
return {"count"} # e.g. "how many open electives": a count, not a unit value
if re.search(r"\b(timings?|what time|at what time)\b", q):
return {"time"}
if re.search(r"\b(when|what date|which date|on what date|last date|deadline|by when)\b", q):
return {"date"}
if re.search(r"\b(fee|fine|cost|amount|charged)\b", q):
return {"inr"}
if re.search(r"\b(percentage|percent)\b", q):
return {"%"}
if re.search(r"\bhow long\b", q):
return {"days", "working days", "minutes", "semesters", "years", "weeks", "months"}
if re.search(r"\bhow (many|much)\b", q):
return {"days", "working days", "books", "marks", "credits", "minutes", "semesters", "years",
"members", "%", "inr", "mb", "contact hours", "weeks", "months"}
return set()
INSUFFICIENT = "INSUFFICIENT_EVIDENCE"
BASELINE_SYSTEM = ("You are a helpful university assistant. Answer the user's question using the "
"context passages. Cite the passages you use like [1].")
GROUNDED_SYSTEM = (
"You are EvidenceGuard, a careful university policy assistant.\n"
"Rules:\n"
"1. Use ONLY the numbered context passages. Never use outside knowledge.\n"
"2. End every sentence with the passage number(s) that support it, e.g. [2].\n"
f"3. If the passages do not contain the answer, reply with exactly: {INSUFFICIENT}\n"
"4. If the passages disagree, state each version with its citation and say which document is more recent.\n"
"5. If the question contains a false assumption, correct it.\n"
"6. Answer in at most 4 short sentences."
)
@dataclass
class GenOutput:
text: str
claims: list = field(default_factory=list) # [(sentence, [passage numbers])]
backend: str = ""
seconds: float = 0.0
declined: bool = False # model itself said evidence is insufficient
def format_context(items) -> str:
lines = []
for i, r in enumerate(items, 1):
c = r.chunk
lines.append(f"[{i}] ({c.title}, page {c.page}, issued {c.issued or 'unknown'}) {c.text}")
return "\n".join(lines)
def build_messages(question: str, items, mode: str, conflicts=None, premise_notes=None):
system = GROUNDED_SYSTEM if mode == "grounded" else BASELINE_SYSTEM
user = f"Context passages:\n{format_context(items)}\n\nQuestion: {question}"
if mode == "grounded" and conflicts:
user += "\n\nVerifier note: these passages conflict: " + "; ".join(
f"[{c.passage_a}] vs [{c.passage_b}] ({c.detail}); newer document: {c.newer or 'unknown'}"
for c in conflicts)
if mode == "grounded" and premise_notes:
user += "\n\nVerifier note: " + "; ".join(premise_notes)
return [{"role": "system", "content": system}, {"role": "user", "content": user}]
def parse_claims(text: str) -> list[tuple[str, list[int]]]:
claims = []
for s in split_sentences(text.replace("\n", " ")):
cites = [int(x) for x in re.findall(r"\[(\d+)\]", s)]
clean = re.sub(r"\s*\[\d+\](?:\s*\[\d+\])*", "", s).strip()
if clean:
claims.append((clean, cites))
return claims
# ====================================================================== LLM backends
class HFInferenceGenerator:
def __init__(self, model: str = config.HF_API_MODEL, token: str | None = config.HF_TOKEN):
if not token:
raise RuntimeError("HF_TOKEN is not set")
from huggingface_hub import InferenceClient
self.client = InferenceClient(model=model, token=token, timeout=60)
self.name = f"HF Inference API ({model})"
def complete(self, messages) -> str:
r = self.client.chat_completion(messages=messages, max_tokens=config.MAX_NEW_TOKENS,
temperature=max(0.01, config.TEMPERATURE))
return r.choices[0].message.content or ""
class LocalLLMGenerator:
def __init__(self, model: str = config.LOCAL_LLM_MODEL):
import torch
from transformers import AutoModelForCausalLM, AutoTokenizer
self.torch = torch
self.tok = AutoTokenizer.from_pretrained(model)
self.model = AutoModelForCausalLM.from_pretrained(model, dtype=torch.float32)
self.model.eval()
self.name = f"Local transformers ({model}, CPU)"
def complete(self, messages) -> str:
prompt = self.tok.apply_chat_template(messages, tokenize=False, add_generation_prompt=True)
ids = self.tok(prompt, return_tensors="pt")
with self.torch.no_grad():
out = self.model.generate(**ids, max_new_tokens=config.MAX_NEW_TOKENS, do_sample=False,
pad_token_id=self.tok.eos_token_id)
return self.tok.decode(out[0][ids["input_ids"].shape[1]:], skip_special_tokens=True).strip()
# ====================================================================== extractive backend
class ExtractiveGenerator:
name = "Extractive composer (no LLM) - offline fallback"
def __init__(self, kb):
self.kb = kb
def select(self, question: str, items, max_sents: int = 3):
from src.evidence_verifier import stem, stems
q = list(dict.fromkeys(stem(t) for t in content_tokens(question, drop_domain=True)))
q = q or list(dict.fromkeys(stem(t) for t in content_tokens(question)))
if not items:
return []
w = {t: (self.kb.term_idf(t) if self.kb.in_vocab(t) else self.kb.max_idf) * (0.4 if t[:1].isdigit() else 1.0)
for t in q}
total = sum(w.values()) or 1.0
want = expected_answer_type(question)
cands = []
for i, r in enumerate(items, 1):
for s in split_sentences(r.chunk.text):
if re.search(r"Document No\.|Issued by:|^Aranya Valley University", s) or len(s.split()) < 6:
continue
units = {f.split(":", 1)[0] for f in extract_facts(s)}
bonus = 0.15 if want and (want & units) else 0.0
cands.append((i, r, s, stems(s), bonus))
if not cands:
return []
chosen, covered = [], set()
for _ in range(max_sents):
best, best_gain = None, 0.0
for i, r, s, st, bonus in cands:
if any(s == c[0] for c in chosen):
continue
gain = sum(w[t] for t in q if t in st and t not in covered) / total
score = gain + 0.15 * r.relevance - 0.02 * (i - 1) + (bonus if not chosen else 0.0)
if best is None or score > best[0]:
best, best_gain = (score, i, s, st), gain
if best is None or (chosen and best_gain < 0.12):
break
chosen.append((best[2], [best[1]]))
covered |= {t for t in q if t in best[3]}
return chosen
# ====================================================================== facade
class AnswerGenerator:
"""Chooses an LLM backend once and exposes generate(question, items, mode, ...)."""
def __init__(self, kb, backend: str = config.LLM_BACKEND):
self.extractive = ExtractiveGenerator(kb)
self.llm = None
self.requested = backend
self.error = ""
if backend in ("auto", "hf_api") and config.HF_TOKEN:
try:
self.llm = HFInferenceGenerator()
except Exception as e:
self.error = f"HF API unavailable: {e}"
if self.llm is None and backend in ("auto", "local"):
try:
self.llm = LocalLLMGenerator()
except Exception as e:
self.error = (self.error + "; " if self.error else "") + f"local LLM unavailable: {e}"
if self.llm is None and backend not in ("extractive", "auto"):
log.warning("Requested LLM backend %s unavailable (%s); using extractive", backend, self.error)
@property
def name(self):
return self.llm.name if self.llm else self.extractive.name
def generate(self, question: str, items, mode: str = "baseline", conflicts=None,
premise_notes=None) -> GenOutput:
t0 = time.perf_counter()
if self.llm is not None:
try:
text = self.llm.complete(build_messages(question, items, mode, conflicts, premise_notes))
declined = INSUFFICIENT in text
claims = [] if declined else parse_claims(text)
return GenOutput(text, claims, self.llm.name, time.perf_counter() - t0, declined)
except Exception as e: # network / quota errors -> graceful fallback
log.warning("LLM call failed (%s); falling back to extractive", e)
return self._extractive(question, items, mode, conflicts, premise_notes, t0)
def _extractive(self, question, items, mode, conflicts, premise_notes, t0) -> GenOutput:
if mode == "grounded" and conflicts:
claims = []
for c in conflicts[:2]:
claims.append((c.sentence_a, [c.passage_a]))
claims.append((c.sentence_b, [c.passage_b]))
# add the best directly relevant sentence(s) too, so the answer stays on the question
claims += self.extractive.select(question, items, max_sents=2)
seen, uniq = set(), []
for s, ci in claims:
if s not in seen:
uniq.append((s, ci))
seen.add(s)
claims = uniq
else:
claims = self.extractive.select(question, items)
text = " ".join(f"{s} [{','.join(map(str, c))}]" for s, c in claims)
return GenOutput(text, claims, self.extractive.name, time.perf_counter() - t0)
|