File size: 8,649 Bytes
2ab2b76
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""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]