Spaces:
Running on Zero
Running on Zero
Download src/llm_generator.py from leeshal/EvidenceGuard-AI: direct link, hf CLI and curl.
- Browser
- Download file 11.5 kB
-
https://huggingface.co/spaces/leeshal/EvidenceGuard-AI/resolve/main/src/llm_generator.py
- Command line
-
hf download hf://spaces/leeshal/EvidenceGuard-AI/src/llm_generator.py
-
curl -L -o llm_generator.py https://huggingface.co/spaces/leeshal/EvidenceGuard-AI/resolve/main/src/llm_generator.py
11.5 kB
| """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." | |
| ) | |
| 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) | |
| 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) | |