campusdesk-ai / src /generation /answer_generator.py
Estarcode's picture
Upload folder using huggingface_hub
2ab2b76 verified
Raw History Blame Contribute Delete
8.65 kB
"""Small Hugging Face instruction-tuned generator producing cited English/Pidgin JSON answers."""
import json
import os
import re
import time
from typing import Dict, List, Optional
import torch
from transformers import AutoModelForCausalLM, AutoTokenizer
from src.config import GENERATOR_COLAB_MODEL_ID, GENERATOR_STRONG_MODEL_ID
from src.schemas import GroundedAnswer, ReplyLanguage, RetrievedPassage
def select_default_generator_model() -> str:
env_override = os.getenv("CAMPUSDESK_GEN_MODEL")
if env_override:
return env_override
if torch.cuda.is_available():
return GENERATOR_COLAB_MODEL_ID
return GENERATOR_STRONG_MODEL_ID
def extract_json_block(raw_text: str) -> Optional[dict]:
"""Parse JSON object from model output, tolerating markdown code fences."""
cleaned = raw_text.strip()
cleaned = re.sub(r"^```(?:json)?\s*", "", cleaned, flags=re.IGNORECASE)
cleaned = re.sub(r"\s*```$", "", cleaned)
try:
return json.loads(cleaned)
except json.JSONDecodeError:
match = re.search(r"\{.*\}", cleaned, flags=re.DOTALL)
if match:
try:
return json.loads(match.group(0))
except json.JSONDecodeError:
return None
return None
SYSTEM_PROMPT = """You are CampusDesk AI, the official bilingual helpdesk assistant for the Zaria Institute of Technology (ZIT) Student Bursary & Welfare Office.
STRICT GROUNDING RULES:
1. Answer ONLY using the 3 retrieved Evidence Passages and any Dated Amendment Notes provided. Never use outside knowledge or guess missing rules.
2. Cite EVERY material claim inline with the exact passage ID in square brackets, e.g. [N02-P01], [N01-P02], [N09-R03]. Every answer that uses facts from the passages MUST include at least one valid [PASSAGE_ID] in both "answer" and "cited_passage_ids".
3. Check Amendment Notes FIRST: apply the latest dated rule ONLY to the exact rule it changes, and keep unamended rules intact.
4. Check prohibitions, eligibility rules, and date comparisons strictly before answering Yes or No (e.g., if parent/guardian accounts are rejected, answer NO; if 12 June 2026 is after 10 June 2026, answer NO; if a CGPA meets the amended threshold, answer YES). State conditions strictly from evidence without inventing exceptions.
5. Preserve all dates (e.g., 10 June 2026), CGPA numbers (e.g., 2.20, 2.50), levels, and Naira figures (e.g., NGN 150,000, NGN 3,000) verbatim.
6. UNKNOWN / SILENT RULES: Set "missing_information" to "None" if the evidence directly answers the full question. If the passages answer ONLY PART of the question, answer the supported part completely with [PASSAGE_ID] citations and state what is missing in "answer" and "missing_information" (never invent an answer for the unmentioned part). If the passages do NOT cover the topic at all, state that the ZIT bursary notices do not cover this topic, keep "next_steps" as [], and explain the gap in "missing_information".
7. Reply strictly in the requested language inside the "answer" string:
- "English": clear, polite, direct student guidance answering the question first (Yes/No or exact fact).
- "Nigerian Pidgin": natural, respectful Nigerian Pidgin directly answering the question (e.g., "No. Application don close on 10 June 2026 [N02-P01]. For di documents, notice talk say make you attach your valid ZIT Student ID card, 2025/2026 Tuition Fee Receipt, and signed HOD Attestation Letter [N01-P02]."). Keep dates and Naira amounts exact.
8. Never output plain-text "Next Steps:" or markdown outside JSON. Only include "next_steps" (1 to 3 short action bullets in the requested language) when evidence supports actionable steps.
Return ONE valid JSON object ONLY starting with { and ending with }:
{
"answer": "Direct grounded reply in the requested language with inline [PASSAGE_ID] citations.",
"next_steps": ["Step 1..."],
"missing_information": "Exact gap not covered by the notices, or 'None' if fully answered.",
"cited_passage_ids": ["N02-P01", "N01-P02"]
}"""
class GroundedGenerator:
"""Hugging Face causal LM generator for grounded bilingual RAG replies."""
def __init__(self, model_id: Optional[str] = None):
self.model_id = model_id or select_default_generator_model()
self.device = "cuda" if torch.cuda.is_available() else "cpu"
dtype = torch.float16 if self.device == "cuda" else torch.bfloat16
self.tokenizer = AutoTokenizer.from_pretrained(self.model_id)
self.model = AutoModelForCausalLM.from_pretrained(
self.model_id,
dtype=dtype,
low_cpu_mem_usage=True,
device_map="auto" if self.device == "cuda" else None,
)
if self.device == "cpu":
self.model = self.model.to("cpu")
self.model.eval()
@staticmethod
def build_evidence_block(
top_passages: List[RetrievedPassage],
amendment_notes: List[str],
) -> str:
ordered = sorted(top_passages, key=lambda rp: (rp.passage.date, rp.rank))
blocks = []
if amendment_notes:
blocks.append(
"AMENDMENT RESOLUTION NOTES (READ FIRST):\n"
+ "\n".join(f"- {n}" for n in amendment_notes)
)
for rp in ordered:
p = rp.passage
amend_tag = f" | Amends: {p.amends_doc_id}" if p.amends_doc_id else ""
blocks.append(
f"[{p.passage_id}] (Rank #{rp.rank} | Doc: {p.doc_id} | Date: {p.date} | "
f"Version: {p.version} | {p.section_or_row}{amend_tag})\n{p.text}"
)
return "\n\n".join(blocks)
@torch.inference_mode()
def generate(
self,
query: str,
reply_language: ReplyLanguage,
top_passages: List[RetrievedPassage],
amendment_notes: List[str],
max_new_tokens: int = 320,
) -> GroundedAnswer:
start = time.perf_counter()
evidence_block = self.build_evidence_block(top_passages, amendment_notes)
valid_ids = {rp.passage.passage_id for rp in top_passages}
user_prompt = (
f"Requested Reply Language: {reply_language}\n"
f"Student Question: {query}\n\n"
f"EVIDENCE PASSAGES:\n{evidence_block}\n\n"
f"Produce the JSON response in {reply_language}:"
)
messages = [
{"role": "system", "content": SYSTEM_PROMPT},
{"role": "user", "content": user_prompt},
]
prompt_text = self.tokenizer.apply_chat_template(
messages,
tokenize=False,
add_generation_prompt=True,
)
inputs = self.tokenizer([prompt_text], return_tensors="pt").to(self.model.device)
output_ids = self.model.generate(
**inputs,
max_new_tokens=max_new_tokens,
do_sample=False,
temperature=None,
top_p=None,
pad_token_id=self.tokenizer.eos_token_id,
)
generated_ids = output_ids[0][inputs["input_ids"].shape[1] :]
raw_output = self.tokenizer.decode(generated_ids, skip_special_tokens=True).strip()
parsed = extract_json_block(raw_output)
if parsed and isinstance(parsed, dict) and "answer" in parsed:
answer_text = str(parsed.get("answer", "")).strip()
raw_steps = parsed.get("next_steps") or []
if isinstance(raw_steps, str):
raw_steps = [raw_steps] if raw_steps.strip() else []
next_steps = [str(s).strip() for s in raw_steps if str(s).strip()][:4]
missing_info = str(parsed.get("missing_information") or "None").strip()
raw_cited = parsed.get("cited_passage_ids") or []
cited = [c for c in raw_cited if c in valid_ids]
else:
answer_text = raw_output
next_steps = []
missing_info = "None"
cited = []
elapsed = (time.perf_counter() - start) * 1000.0
return GroundedAnswer(
answer=answer_text,
next_steps=next_steps,
missing_information=missing_info,
cited_passage_ids=cited,
reply_language=reply_language,
raw_model_output=raw_output,
latency_ms=round(elapsed, 2),
)
_GENERATOR_CACHE: Dict[str, GroundedGenerator] = {}
def get_generator(model_id: Optional[str] = None) -> GroundedGenerator:
target = model_id or select_default_generator_model()
if target not in _GENERATOR_CACHE:
_GENERATOR_CACHE[target] = GroundedGenerator(model_id=target)
return _GENERATOR_CACHE[target]