File size: 28,479 Bytes
c5cf697
9129ffb
c5cf697
 
 
 
 
9129ffb
 
 
 
c5cf697
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
9129ffb
 
c5cf697
 
 
 
 
 
 
 
 
 
 
9129ffb
 
 
c5cf697
 
 
 
 
9129ffb
 
 
 
c5cf697
 
9129ffb
 
 
 
 
c5cf697
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
9129ffb
 
 
 
 
 
 
 
 
 
 
c5cf697
 
 
 
 
 
 
 
 
 
9129ffb
 
 
 
 
 
c5cf697
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
9129ffb
 
 
 
 
 
 
c5cf697
 
 
 
 
 
 
 
9129ffb
 
c5cf697
 
 
9129ffb
 
 
c5cf697
9129ffb
 
c5cf697
 
 
 
9129ffb
 
c5cf697
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
9129ffb
c5cf697
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
9129ffb
c5cf697
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
9129ffb
 
 
c5cf697
9129ffb
 
c5cf697
 
 
9129ffb
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
a03551b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
9129ffb
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
c5cf697
 
 
 
 
2b32e9d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
9129ffb
2b32e9d
 
9129ffb
c5cf697
 
a03551b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
c5cf697
9129ffb
c5cf697
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
9129ffb
 
 
 
 
 
c5cf697
9129ffb
c5cf697
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
9129ffb
c5cf697
 
 
 
 
 
 
 
 
 
9129ffb
 
c5cf697
9129ffb
 
 
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
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
import json
import os
import threading
import time
import uuid
from datetime import datetime, timezone

from groq import Groq
from langchain.memory import ConversationTokenBufferMemory
from langchain_community.document_loaders.csv_loader import CSVLoader
from langchain_community.vectorstores import FAISS
from langdetect import detect
from deep_translator import GoogleTranslator
from pydantic import BaseModel, Field, ValidationError
from typing import Annotated

# Groq structured outputs: https://console.groq.com/docs/structured-outputs
FOLLOWUP_JSON_SCHEMA = {
    "type": "object",
    "properties": {
        "suggested_questions": {
            "type": "array",
            "description": (
                "Natural follow-up questions the student might ask next about COMSATS "
                "or clarifying the last answer (1 to 4 questions)."
            ),
            "items": {"type": "string"},
            "minItems": 1,
            "maxItems": 4,
        }
    },
    "required": ["suggested_questions"],
    "additionalProperties": False,
}


class FollowUpQuestionsPayload(BaseModel):
    """Validated shape returned by generate_followup_questions."""

    suggested_questions: Annotated[list[str], Field(min_length=1, max_length=4)]


class Comsatsbot:
    def __init__(
        self,
        hf,
        llm,
        api_keys,
        chats_collection,
        paths,
        gemini_api_keys,
        index_path='faiss_kb',
        kb_upload_dir='kb_uploads',
    ):
        self.llm = llm
        self.api_keys = api_keys
        self.client = None
        self.models = ["llama-3.3-70b-versatile", "llama-3.1-8b-instant", "openai/gpt-oss-20b", "meta-llama/llama-4-scout-17b-16e-instruct", "meta-llama/llama-prompt-guard-2-22m", "qwen/qwen3-32b"]
        self.groq_json_models = ["meta-llama/llama-4-scout-17b-16e-instruct", "openai/gpt-oss-20b", "openai/gpt-oss-safeguard-20b", "openai/gpt-oss-120b"]
        self.gemini_api_keys = gemini_api_keys
        self.gemini_client = None
        self.gemini_models = ["gemini-2.5-flash-lite", "gemini-3.1-flash-lite-preview", "gemini-3.1-flash-live-preview", "gemini-2.5-flash"]
        # Initialize memory buffer and MongoDB connection
        self.memory = ConversationTokenBufferMemory(llm=self.llm, max_token_limit=3000)
        self.chats_collection = chats_collection
        self.index_path = index_path
        self.kb_upload_dir = kb_upload_dir
        self._faiss_lock = threading.Lock()
        self.hf = hf
        self.faiss_index = None
        self.faiss_retriever = None
        self.paths = paths
        self.initialize_faiss_index()
        

    @staticmethod
    def _followup_history_snippet(chat_history: list, max_turns: int = 4) -> str:
        if not chat_history:
            return "(no prior turns in this conversation)"
        tail = chat_history[-max_turns:]
        lines = []
        for h in tail:
            q = (h.get("question") or "").strip()
            a = (h.get("answer") or "").strip()
            if q:
                lines.append(f"Earlier Q: {q[:320]}")
            if a:
                lines.append(f"Earlier A: {a[:400]}")
        return "\n".join(lines) if lines else "(no prior turns)"

    @staticmethod
    def _build_followup_user_prompt(
        question: str,
        answer: str,
        history_snippet: str,
        language_label: str,
    ) -> str:
        return f"""You generate suggested follow-up questions for a COMSATS University Attock campus chatbot.

Context:
- Latest student question: {question}
- Latest assistant answer: {answer}
- Recent conversation (may be truncated):
{history_snippet}

Requirements:
1. Produce exactly ONE JSON object with a single key "suggested_questions" whose value is an array of strings.
2. The array MUST contain between 1 and 4 questions inclusive (prefer 3–4 when the topic allows; use only 1–2 if the answer was very narrow or unknown).
3. Each question must be short (aim under 120 characters), clear, and something the same student might reasonably ask next.
4. Questions must stay relevant to COMSATS (programs, admissions, campus, fees, departments, links already mentioned) or logically deepen/clarify the last answer.
5. Write every suggested question in **{language_label}** (same language family as the student's latest question).
6. Do not repeat the student's latest question verbatim; do not add numbering prefixes like "1." inside the strings.
7. Do not include markdown, explanations, or keys other than "suggested_questions".

Return only valid JSON."""

    def _parse_followup_json(self, content: str | None) -> list[str] | None:
        if not content or not content.strip():
            return None
        try:
            data = json.loads(content)
        except json.JSONDecodeError:
            return None
        if not isinstance(data, dict):
            return None
        raw = data.get("suggested_questions")
        if not isinstance(raw, list):
            return None
        cleaned = [
            str(x).strip()
            for x in raw
            if isinstance(x, (str, int, float)) and str(x).strip()
        ]
        if not cleaned:
            return None
        cleaned = cleaned[:4]
        try:
            validated = FollowUpQuestionsPayload.model_validate(
                {"suggested_questions": cleaned}
            )
            return validated.suggested_questions
        except ValidationError:
            if len(cleaned) >= 1:
                return cleaned[:4]
            return None

    def generate_followup_questions(
        self,
        question: str,
        answer: str,
        history_snippet: str,
        language_label: str,
    ) -> list[str] | None:
        system_schema = (
            "You output only JSON matching the schema: an object with "
            '"suggested_questions": string array (1–4 items). No prose.'
        )
        user_prompt = self._build_followup_user_prompt(
            question, answer, history_snippet, language_label
        )

        # Use only self.groq_json_models for suggestions β€” never self.models (RAG answer pool).
        for api_key in self.api_keys:
            client = Groq(api_key=api_key)
            for model_id in self.groq_json_models:
                try:
                    resp = client.chat.completions.create(
                        model=model_id,
                        messages=[
                            {"role": "system", "content": system_schema},
                            {"role": "user", "content": user_prompt},
                        ],
                        temperature=0.2,
                        response_format={
                            "type": "json_schema",
                            "json_schema": {
                                "name": "follow_up_questions",
                                "strict": True,
                                "schema": FOLLOWUP_JSON_SCHEMA,
                            },
                        },
                    )
                    content = resp.choices[0].message.content
                    parsed = self._parse_followup_json(content)
                    if parsed:
                        return parsed
                except Exception:
                    time.sleep(0.4)
                    continue
        return None

    def load_data(self, paths):
        documents = []
        for path in paths:
            loader = CSVLoader(file_path=path)
            data = loader.load()
            documents.extend(data)
        return documents

    def initialize_faiss_index(self):
        if os.path.exists(self.index_path):
            try:
                self.faiss_index = FAISS.load_local(
                    self.index_path, self.hf, allow_dangerous_deserialization=True
                )
                self.faiss_retriever = self.faiss_index.as_retriever(search_kwargs={"k": 5})
            except Exception:
                documents = self.load_data(self.paths)
                self.faiss_index = FAISS.from_documents(documents, self.hf)
                self.faiss_index.save_local(self.index_path)
                self.faiss_retriever = self.faiss_index.as_retriever(search_kwargs={"k": 5})
        else:
            documents = self.load_data(self.paths)
            self.faiss_index = FAISS.from_documents(documents, self.hf)
            self.faiss_index.save_local(self.index_path)
            self.faiss_retriever = self.faiss_index.as_retriever(search_kwargs={"k": 5})

    def update_faiss_index(self, path: str) -> dict:
        """Embed CSV rows and merge into the live FAISS index; persist and refresh retriever."""
        if not os.path.isfile(path):
            raise ValueError(f"CSV not found: {path}")
        with self._faiss_lock:
            if self.faiss_index is None:
                raise RuntimeError(
                    "FAISS index is not loaded. Fix faiss_kb or bundled CSVs and restart."
                )
            documents = self.load_data([path])
            if not documents:
                raise ValueError("CSV contained no rows.")
            rows = len(documents)
            new_vs = FAISS.from_documents(documents, self.hf)
            self.faiss_index.merge_from(new_vs)
            self.faiss_index.save_local(self.index_path)
            self.faiss_retriever = self.faiss_index.as_retriever(search_kwargs={"k": 5})
            return {"rows_merged": rows, "mode": "merge"}

    def merge_kb_csv_bytes(self, original_filename: str, data: bytes) -> dict:
        """Save uploaded CSV under kb_upload_dir and merge into FAISS via update_faiss_index."""
        if not data or not data.strip():
            raise ValueError("Empty file.")
        os.makedirs(self.kb_upload_dir, exist_ok=True)
        safe = os.path.basename(original_filename or "upload.csv").strip() or "upload.csv"
        safe = safe.replace('..', '').replace('/', '_').replace('\\', '_')
        if not safe.lower().endswith('.csv'):
            safe = f'{safe}.csv'
        dest_name = f'{uuid.uuid4().hex}_{safe}'
        dest_path = os.path.join(os.path.abspath(self.kb_upload_dir), dest_name)
        with open(dest_path, 'wb') as f:
            f.write(data)
        stats = self.update_faiss_index(dest_path)
        stats['saved_as'] = dest_name
        return stats

    def list_kb_upload_filenames(self) -> list[str]:
        root = os.path.abspath(self.kb_upload_dir)
        if not os.path.isdir(root):
            return []
        return sorted(
            n
            for n in os.listdir(root)
            if n.lower().endswith('.csv') and os.path.isfile(os.path.join(root, n))
        )

    def retrieve_answer(self, query):
        if self.faiss_retriever:
            return self.faiss_retriever.invoke(query)
        else:
            print("FAISS retriever is not initialized. Please create or load an index.")
            return None

    def _assert_chat_owned(self, chat_record, user_id):
        if not chat_record:
            raise KeyError("Chat ID not found.")
        if chat_record.get("user_id") != user_id:
            raise KeyError("Chat ID not found.")

    def create_chat_record(self, chat_id, user_id):
        now = datetime.now(timezone.utc)
        self.chats_collection.insert_one({
            "_id": chat_id,
            "user_id": user_id,
            "history": [],
            "updated_at": now,
        })

    def update_chat(self, chat_id, question, answer):
        now = datetime.now(timezone.utc)
        self.chats_collection.update_one(
            {"_id": chat_id},
            {
                "$push": {"history": {"question": question, "answer": answer}},
                "$set": {"updated_at": now},
            },
        )

    def list_chats(self, user_id, skip: int = 0, limit: int = 30):
        cursor = self.chats_collection.find({"user_id": user_id})
        items = []
        for doc in cursor:
            history = doc.get("history") or []
            if history:
                preview = (history[-1].get("question") or "")[:100]
            else:
                preview = "New conversation"
            ua = doc.get("updated_at")
            items.append({
                "chat_id": doc["_id"],
                "preview": preview.strip() or "New conversation",
                "updated_at": ua.isoformat() if hasattr(ua, "isoformat") else None,
                "message_count": len(history),
            })

        def sort_key(entry):
            ts = entry["updated_at"] or ""
            return ts

        items.sort(key=sort_key, reverse=True)
        total = len(items)
        slice_items = items[skip : skip + limit]
        return {
            "chats": slice_items,
            "total": total,
            "skip": skip,
            "limit": limit,
            "has_more": skip + len(slice_items) < total,
        }

    def load_chat(self, chat_id, user_id):
        chat_record = self.chats_collection.find_one({"_id": chat_id})
        self._assert_chat_owned(chat_record, user_id)
        return chat_record.get("history", [])

    def load_chat_history_page(
        self,
        chat_id,
        user_id,
        before_index: int | None,
        limit: int,
    ):
        chat_record = self.chats_collection.find_one({"_id": chat_id})
        self._assert_chat_owned(chat_record, user_id)
        full = chat_record.get("history") or []
        n = len(full)
        limit = max(1, min(limit, 100))

        if before_index is not None and before_index <= 0:
            return {
                "history": [],
                "total_pairs": n,
                "has_older": False,
                "next_before_index": 0,
                "range_start": 0,
                "range_end_exclusive": 0,
            }

        if before_index is None:
            start = max(0, n - limit)
            slice_ = full[start:n]
            has_older = start > 0
            next_before = start
        else:
            end = before_index
            start = max(0, end - limit)
            slice_ = full[start:end]
            has_older = start > 0
            next_before = start

        return {
            "history": slice_,
            "total_pairs": n,
            "has_older": has_older,
            "next_before_index": next_before,
            "range_start": start,
            "range_end_exclusive": start + len(slice_),
        }

    def new_chat(self, chat_id, user_id):
        if self.chats_collection.find_one({"_id": chat_id}):
            raise KeyError(f"Chat ID {chat_id} exist already.")

        self.create_chat_record(chat_id, user_id)
        return "success"

    def delete_chat(self, chat_id, user_id):
        chat_record = self.chats_collection.find_one({"_id": chat_id})
        self._assert_chat_owned(chat_record, user_id)
        self.chats_collection.delete_one({"_id": chat_id})
        return "success"

    def generate_response(self, question, history, context, detected_language):

        if detected_language == 'ur':
            language = 'Urdu'
        else:
            language = 'English'
        while True:
            for api_key in self.api_keys:
                self.client = Groq(api_key=api_key)

                for model in self.models:
                    try:
                        chat_completion = self.client.chat.completions.create(
                        messages=[
                            {
                                "role": "user",
                                "content": f'''
                 Kindly use the proper emojis where we need to use in some response (angry, happy, sad etc)        
                You are an comsats assistant to help the user related to comsats university, conversation, studies related query. 
                Answer the following Question: {question}
                Kindly use the proper emojis where we need to use in some response (angry, happy, sad etc)
                Dont need to mention that (according to provided context/Based on the provided chat history) in response and just generate the response just like human without mention this according to context and chat history.
                You are a conversational and helpfull agent to help the comsats university attock campus students, and your task is to provide concise and direct answers to the questions asked in {language} Language. kindly answer in correct way and to the point in {language} language. 
                Your task is to provide concise, direct answers to questions asked in {language}. Kindly respond correctly and to the point in {language}. Avoid irrelevant explanations and ensure proper use of {language} in your answers. 
                Your task is to use the emoji when there is happy, sad, surprise, angry expression required in response. Kindly analyze the question and if expression is required in response then use the emoji otherwise dont use the emoji and remember that you dont need to use the emoji in simple studies and comstas related question.
                For example user ask same question again and again, user is not understanding anything, user asking wrong things etc then your task is to use the emoji in such response and be choosy in using emoji in response in happy sad angry response according to user question.
                If there is any need to provide the url and then kindly generate the url according to following structure. Kindly provide the link clickable. Your provided should be generated according to following structure 
                [Click here to visit "website name"](website url "https://comsats.edu.pk" write the same url as it is provided in context below)
                Dont need to explain and repeat the prompt in response. Answer in {language} language.
                1. If the question is in {language}, answer in {language}.
                2. Dont need to explain irrelevant explanation and use the proper emojis in answer if required in response (anger, sad, surprise ect).
                3. Always respond in a human-like tone and keep your answers concise, to the point and friendly.
                4. If the question is conversational (like greetings, need any converstaion, help related studies, knowledge base question etc), respond in a warm, conversational tone.
                5. Always consider the provided context and chat history to formulate your response.
                6. If you don’t know the answer to the provided question or you did not find the answer from the context and chat history, kindly respond with "I don't know the answer to this.emooji" without adding irrelevant text explanations.
                7. Kindly generate a perfect and to the point  and short answer. Dont use any irrelevant text explanation and i want full concise and to the point answer.
                8. Kindly answer in {language} and dont need to generate a response in other language and i want answer in this language {language}.
                 Kindly use the proper emojis where we need to use in some response (angry, happy, sad etc)
                Question: {question}
                Use the following context to answer and dont mention that you are answer from this tcontext in response:
                Comsats Attock Campus Provide BSomputerScience, BSSoftwareEngineer BSArtificialIntelligence BSEnglish BSmath BSElectricalEngineering BSComputerEngineering BSBBA 
                Has three departments CS(CS, AI, SE), Math(math, BBA, english) and EE(EE, CE).
                It has cricket ground and football ground and two canteens. First near math and ee department and second near cs department. There is also mosque near cs department. CS department has threater liker rooms lt and total 9 theaters called lt and math has classroom cr and ee has labs.
                They accept the nts test for admission and provide the cgpa for 4 on 85 percent and 3.66 between 79 to 84 and many more. 
                admssion detail: (http://admissions.comsats.edu.pk/Home/EligibilityCriteria?pt=BS)
                ms sites:
https://cuiatk.edu.pk/new/rt-program/master-of-science-in-computer-science/
https://cuiatk.edu.pk/new/rt-program/master-of-science-in-electrical-engineering/
https://cuiatk.edu.pk/new/rt-program/master-of-science-in-computer-engineering/
https://cuiatk.edu.pk/new/rt-program/master-in-business-administration/
https://cuiatk.edu.pk/new/rt-program/master-of-science-in-mathematics/


PHD sites:
https://cuiatk.edu.pk/new/rt-program/phd-in-computer-science/
https://cuiatk.edu.pk/new/rt-program/phd-in-electrical-engineering/
https://cuiatk.edu.pk/new/rt-program/phd-in-computer-engineering/
https://cuiatk.edu.pk/new/rt-program/phd-in-management-science/
https://cuiatk.edu.pk/new/rt-program/phd-in-mathematics/


explores other content and pages on this site sto answer user query in concise related to comsats university and attock campus.
https://cuiatk.edu.pk/
                
                {context}
                Context is ending 
                Now here is chat history that you have to consider and identify
                **Consider the following chat history for additional context to answer the question:** 
                {history}
                Answer the following Question: {question}
                '''
                            }
                        ],
                        model=model,
                    )

                        response_content = chat_completion.choices[0].message.content
                        return response_content
                    except Exception as e:
                        time.sleep(2)

                        continue

            return "Sorry, unable to provide an answer at this time."
    
    def generate_web_response(self, question, history, detected_language):
        from google import genai
        from google.genai import types

        # Mirror query language: Urdu / English explicitly; other codes β†’ same language as question.
        lang_display = {"ur": "Urdu", "en": "English"}.get(detected_language)
        if lang_display:
            lang_rule = (
                f"You MUST answer entirely in {lang_display}. Do not switch languages."
            )
        else:
            lang_rule = (
                "You MUST answer entirely in the same language as the Question above "
                "(if the user wrote in Urdu, use Urdu; if English, use English; "
                "otherwise mirror their language). Do not switch languages."
            )

        prompt = f"""You are the COMSATS University (Attock campus) assistant. Google Search is available β€” use it only for COMSATS-related facts.

ALLOWED TOPICS β€” Only COMSATS University (including Attock): admissions, programs, departments, BS/MS/MPhil/PhD and other degrees, fees, eligibility, deadlines, campus, academics, exams, student services, official policies, and similar university matters.

POSTGRADUATE (MS / MPhil / PhD) β€” Whenever the user asks about MS, MPhil, PhD, postgraduate admissions, graduate programs, thesis, or eligibility for masters/doctoral study at COMSATS, you MUST prioritize facts found via search on the official admissions portal: http://admissions.comsats.edu.pk (use search queries that surface this domain). Prefer information consistent with that site; mention key facts briefly (e.g. program names, eligibility, links) without copying long pages verbatim.

REFUSE OFF-TOPIC β€” Do NOT answer: hobbies, entertainment unrelated to COMSATS, drugs or substances, illegal topics, unrelated trivia, creative tasks, or personal advice unrelated to the university. Reply with ONE short polite refusal only β€” you only help with COMSATS-related questions. No partial off-topic content.

CONCISE OUTPUT (strict) β€”
β€’ Answer in the fewest sentences needed; default to 2–6 short sentences unless the user explicitly asks for a list.
β€’ No filler: do not start with "As an AI", "Based on my search", or restate the whole question. Jump straight to the answer.
β€’ No irrelevant side topics, no long introductions or conclusions, no duplicate points.
β€’ Prefer one clear fact per sentence; use short bullets only when they improve clarity (e.g. eligibility steps).
β€’ If uncertain after search, say briefly that verified details were not found; do not invent policies or dates.

CORRECTNESS β€” State facts accurately from search results; do not guess fees, dates, or rules. If multiple campuses exist, clarify when it matters for the user.

LANGUAGE β€” {lang_rule}

Question:
{question}

Prior conversation (may be truncated):
{history}

ms sites:
https://cuiatk.edu.pk/new/rt-program/master-of-science-in-computer-science/
https://cuiatk.edu.pk/new/rt-program/master-of-science-in-electrical-engineering/
https://cuiatk.edu.pk/new/rt-program/master-of-science-in-computer-engineering/
https://cuiatk.edu.pk/new/rt-program/master-in-business-administration/
https://cuiatk.edu.pk/new/rt-program/master-of-science-in-mathematics/


PHD sites:
https://cuiatk.edu.pk/new/rt-program/phd-in-computer-science/
https://cuiatk.edu.pk/new/rt-program/phd-in-electrical-engineering/
https://cuiatk.edu.pk/new/rt-program/phd-in-computer-engineering/
https://cuiatk.edu.pk/new/rt-program/phd-in-management-science/
https://cuiatk.edu.pk/new/rt-program/phd-in-mathematics/


explores other content and pages on this site sto answer user query in concise related to comsats university and attock campus.
https://cuiatk.edu.pk/
"""

        grounding_tool = types.Tool(google_search=types.GoogleSearch())
        config = types.GenerateContentConfig(tools=[grounding_tool])

        for api_key in self.gemini_api_keys:
            try:
                self.gemini_client = genai.Client(api_key=api_key)
            except Exception:
                time.sleep(0.3)
                continue
            for model_name in self.gemini_models:
                try:
                    response = self.gemini_client.models.generate_content(
                        model=model_name,
                        contents=prompt,
                        config=config,
                    )
                    text = getattr(response, "text", None) or ""
                    if text.strip():
                        return text
                except Exception:
                    time.sleep(0.3)
                    continue
        return "Sorry, web search is unavailable right now."

    def response(self, question, chat_id, user_id, allow_augmentation: bool = False, use_web_search: bool = False):
        chat_history = self.load_chat(chat_id, user_id)

        # Load the previous conversation into memory
        for entry in chat_history:
            self.memory.save_context({"input": entry["question"]}, {"output": entry["answer"]})

        language = detect(question)
        history_str = self.memory.load_memory_variables({})["history"]

        if use_web_search:
            answer = self.generate_web_response(question, history_str, language)
        else:
            if not self.faiss_retriever:
                answer = (
                    "Knowledge base search is unavailable right now. "
                    "Please try again later or use web search if enabled."
                )
            elif language == 'ur':
                question_translation = GoogleTranslator(source='ur', target='en').translate(question)
                context = self.faiss_retriever.invoke(question_translation)
                all_content = ''
                for document in context:
                    all_content += document.page_content + '\n'
                answer = self.generate_response(question, history_str, all_content, language)
            else:
                context = self.faiss_retriever.invoke(question)
                all_content = ''
                for document in context:
                    all_content += document.page_content + '\n'
                answer = self.generate_response(question, history_str, all_content, language)

        suggested_questions: list[str] | None = None
        if allow_augmentation:
            lang_label = "Urdu" if language == 'ur' else "English"
            snippet = self._followup_history_snippet(chat_history)
            suggested_questions = self.generate_followup_questions(
                question,
                answer,
                snippet,
                lang_label,
            )

        self.update_chat(chat_id, question, answer)
        return answer, suggested_questions