Spaces:
Runtime error
Runtime error
Download chatbot.py from cuiconnect/backend: direct link, hf CLI and curl.
- Browser
- Download file 28.5 kB
-
https://huggingface.co/spaces/cuiconnect/backend/resolve/main/chatbot.py
- Command line
-
hf download hf://spaces/cuiconnect/backend/chatbot.py
-
curl -L -o chatbot.py https://huggingface.co/spaces/cuiconnect/backend/resolve/main/chatbot.py
28.5 kB
| 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() | |
| 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)" | |
| 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 | |