Spaces:
Sleeping
Sleeping
Download backend/rag.py from Abdullah0327/Docent-AI-ChatBot: direct link, hf CLI and curl.
- Browser
- Download file 16.1 kB
-
https://huggingface.co/spaces/Abdullah0327/Docent-AI-ChatBot/resolve/main/backend/rag.py
- Command line
-
hf download hf://spaces/Abdullah0327/Docent-AI-ChatBot/backend/rag.py
-
curl -L -o rag.py https://huggingface.co/spaces/Abdullah0327/Docent-AI-ChatBot/resolve/main/backend/rag.py
16.1 kB
| import os | |
| import json | |
| import re | |
| import time | |
| from concurrent.futures import ThreadPoolExecutor, TimeoutError as _FutureTimeout | |
| from pathlib import Path | |
| from dotenv import load_dotenv | |
| from langchain_nvidia_ai_endpoints import ChatNVIDIA | |
| from langchain_core.prompts import ChatPromptTemplate, MessagesPlaceholder | |
| from langchain_core.messages import HumanMessage, AIMessage | |
| from langchain_core.output_parsers import StrOutputParser | |
| from langchain_community.vectorstores import FAISS | |
| try: | |
| from langchain_nvidia_ai_endpoints import NVIDIARerank | |
| except ImportError: | |
| NVIDIARerank = None | |
| try: | |
| from rank_bm25 import BM25Okapi | |
| except ImportError: | |
| BM25Okapi = None | |
| load_dotenv(Path(__file__).parent.parent / ".env") | |
| # Nemotron Super 49B: NVIDIA's distillation of Llama 3.3 70B β comparable | |
| # answer quality, but its NIM endpoint is far less congested than the raw 70B | |
| # (which regularly queues for minutes and 504s on the free tier). | |
| CHAT_MODEL = os.environ.get("CHAT_MODEL", "nvidia/llama-3.3-nemotron-super-49b-v1.5") | |
| # Question condensing is a trivial rewrite task β a small model does it just as | |
| # well and much faster than the 70B answer model. | |
| CONDENSE_MODEL = os.environ.get("CONDENSE_MODEL", "meta/llama-3.1-8b-instruct") | |
| # Reranker: free on NVIDIA NIM; re-scores the candidate chunks against the | |
| # question far more accurately than raw embedding distance. Set USE_RERANKER=0 | |
| # to disable. | |
| RERANK_MODEL = os.environ.get("RERANK_MODEL", "nvidia/llama-nemotron-rerank-1b-v2") | |
| USE_RERANKER = os.environ.get("USE_RERANKER", "1").lower() not in ("0", "false", "no") | |
| # If the primary model streams nothing for this long, give up and answer with | |
| # the fallback model instead of waiting for NVIDIA's 300s gateway timeout. | |
| FIRST_TOKEN_TIMEOUT = float(os.environ.get("FIRST_TOKEN_TIMEOUT", "25")) | |
| RETRIEVE_K = 5 # chunks that reach the prompt | |
| CANDIDATE_K = 20 # candidates gathered before fusion/reranking | |
| RRF_C = 60 # standard reciprocal-rank-fusion constant | |
| HISTORY_TURNS = 6 # how many prior messages to feed back as conversation memory | |
| # Words that suggest the question leans on the conversation ("it", "that | |
| # policy", "what about them"...). Only such questions need the condense step. | |
| _REFERENTIAL = re.compile( | |
| r"\b(it|its|that|this|these|those|they|them|their|he|she|him|her|his|hers" | |
| r"|one|ones|same|above|previous|earlier|before|again|also|too|more|another" | |
| r"|other|why|and)\b", | |
| re.IGNORECASE, | |
| ) | |
| SYSTEM_PROMPT = """You are a strict policy assistant. Your ONLY job is to answer questions \ | |
| using the document excerpts provided below as context. | |
| Rules you must NEVER break: | |
| 1. Answer ONLY using information found in the context below. | |
| 2. Do NOT use any outside knowledge, assumptions, or information not present in the context. | |
| 3. Do NOT make up, infer, or guess any information that is not explicitly stated in the context. | |
| 4. If the answer is not present in the context, respond with exactly: | |
| "I don't have information about that in the provided documents." | |
| 5. When answering, be concise and quote or closely paraphrase the relevant policy text. | |
| 6. Do not greet the user or add filler phrases. | |
| 7. The conversation history is provided only to resolve references (e.g. "it", "that policy"). | |
| You must STILL answer the latest question solely from the context excerpts below. | |
| Context from documents: | |
| {context} | |
| """ | |
| # Used to turn a follow-up question into a standalone one for retrieval. | |
| CONDENSE_PROMPT = """Given the conversation history and a follow-up question, rewrite the \ | |
| follow-up as a single standalone question that can be understood without the history. | |
| Only output the rewritten question β no preamble, no explanation. | |
| If the question is already standalone, return it unchanged.""" | |
| def _display_page(page) -> int | str: | |
| """PyPDFLoader stores 0-based page numbers; convert to the 1-based number | |
| a human (and any PDF viewer) uses.""" | |
| return page + 1 if isinstance(page, int) else "?" | |
| def format_docs(docs: list) -> str: | |
| parts = [] | |
| for i, doc in enumerate(docs, 1): | |
| source = doc.metadata.get("source", "unknown") | |
| page = _display_page(doc.metadata.get("page")) | |
| parts.append(f"[Excerpt {i} | File: {source} | Page: {page}]\n{doc.page_content}") | |
| return "\n\n---\n\n".join(parts) | |
| def _to_lc_messages(history: list[dict]) -> list: | |
| """Convert stored {role, content} dicts into LangChain message objects.""" | |
| msgs = [] | |
| for h in history[-HISTORY_TURNS:]: | |
| if h.get("role") == "user": | |
| msgs.append(HumanMessage(content=h.get("content", ""))) | |
| elif h.get("role") == "assistant": | |
| msgs.append(AIMessage(content=h.get("content", ""))) | |
| return msgs | |
| def _sources_from_docs(docs: list) -> list[dict]: | |
| by_key: dict = {} | |
| sources = [] | |
| for doc in docs: | |
| source = doc.metadata.get("source", "unknown") | |
| page = _display_page(doc.metadata.get("page")) | |
| snippet = (doc.page_content or "").strip() | |
| key = (source, page) | |
| if key in by_key: | |
| # Same file+page retrieved more than once β keep every snippet so | |
| # the PDF preview can highlight all matched passages. | |
| if snippet: | |
| by_key[key]["snippets"].append(snippet) | |
| continue | |
| raw_imgs = doc.metadata.get("images", "[]") | |
| try: | |
| images = json.loads(raw_imgs) if isinstance(raw_imgs, str) else raw_imgs | |
| except Exception: | |
| images = [] | |
| entry = { | |
| "file": source, | |
| "page": page, | |
| "images": images, | |
| "snippets": [snippet] if snippet else [], | |
| } | |
| by_key[key] = entry | |
| sources.append(entry) | |
| return sources | |
| # Crude suffix stripping so "plagiarizing" and "plagiarism" both become | |
| # "plagiar" β enough for BM25 recall without a full stemmer dependency. | |
| _STEM_SUFFIXES = ( | |
| "izations", "ization", "isation", "izing", "ising", "ments", "ment", | |
| "ations", "ation", "ness", "isms", "ism", "izes", "ize", "ise", | |
| "ying", "ing", "ies", "ied", "ers", "er", "est", "es", "ed", "ly", "s", "y", | |
| ) | |
| def _stem(word: str) -> str: | |
| for suffix in _STEM_SUFFIXES: | |
| if len(word) > len(suffix) + 3 and word.endswith(suffix): | |
| return word[: -len(suffix)] | |
| return word | |
| def _bm25_tokenize(text: str) -> list[str]: | |
| return [_stem(w) for w in re.findall(r"[a-z0-9]+", text.lower())] | |
| def _doc_key(doc) -> tuple: | |
| return (doc.metadata.get("source"), doc.metadata.get("page"), hash(doc.page_content)) | |
| # Sentinel marking a stream that ended without producing any token | |
| _STREAM_END = object() | |
| def _first_visible_token(gen): | |
| """Advance the stream to the first NON-EMPTY token. Reasoning models emit | |
| empty-content chunks while 'thinking' β those must not satisfy the | |
| first-token watchdog, or a silently-thinking model looks like a hung UI.""" | |
| for token in gen: | |
| if token: | |
| return token | |
| return _STREAM_END | |
| def _answer_system_prompt(model_name: str) -> str: | |
| """Nemotron reasoning models stream hidden 'thinking' tokens by default β | |
| the UI sees nothing for 20-40s and the token budget gets eaten. /no_think | |
| at the top of the system prompt disables that.""" | |
| if "nemotron" in model_name.lower(): | |
| return "/no_think\n" + SYSTEM_PROMPT | |
| return SYSTEM_PROMPT | |
| def _needs_condensing(question: str, history_msgs: list) -> bool: | |
| """Skip the condense LLM call when the question stands on its own. | |
| Very short questions or ones with referential words need the history.""" | |
| if not history_msgs: | |
| return False | |
| q = question.strip() | |
| return len(q.split()) <= 4 or bool(_REFERENTIAL.search(q)) | |
| class RagEngine: | |
| """Holds the retriever + LLM and answers questions with optional memory.""" | |
| def __init__(self, vector_store: FAISS): | |
| self.vector_store = vector_store | |
| # Keyword (BM25) index over every chunk β catches exact tokens like | |
| # policy codes ("A011") and acronyms that embeddings often miss. | |
| self._all_docs = list(getattr(vector_store.docstore, "_dict", {}).values()) | |
| self._bm25 = None | |
| if BM25Okapi is not None and self._all_docs: | |
| # Index the source filename with each chunk β policy titles like | |
| # "Plagiarism-Policy" are a strong keyword signal the chunk text | |
| # itself often lacks. | |
| self._bm25 = BM25Okapi([ | |
| _bm25_tokenize(f"{d.metadata.get('source', '')} {d.page_content}") | |
| for d in self._all_docs | |
| ]) | |
| self.reranker = None | |
| self._rerank_failures = 0 | |
| if NVIDIARerank is not None and USE_RERANKER: | |
| try: | |
| self.reranker = NVIDIARerank( | |
| model=RERANK_MODEL, | |
| api_key=os.environ["NVIDIA_API_KEY"], | |
| top_n=RETRIEVE_K, | |
| ) | |
| except Exception as e: | |
| print(f"[rag] reranker unavailable: {e}", flush=True) | |
| self.llm = ChatNVIDIA( | |
| model=CHAT_MODEL, | |
| api_key=os.environ["NVIDIA_API_KEY"], | |
| temperature=0.0, | |
| max_tokens=1024, | |
| ) | |
| self.condense_llm = ChatNVIDIA( | |
| model=CONDENSE_MODEL, | |
| api_key=os.environ["NVIDIA_API_KEY"], | |
| temperature=0.0, | |
| max_tokens=120, | |
| ) | |
| # Backup answer model: NVIDIA's free 70B endpoint sometimes 504s under | |
| # load; the 8B model is far less congested and still grounded by the | |
| # strict context-only prompt. | |
| self.fallback_llm = ChatNVIDIA( | |
| model=CONDENSE_MODEL, | |
| api_key=os.environ["NVIDIA_API_KEY"], | |
| temperature=0.0, | |
| max_tokens=1024, | |
| ) | |
| self.answer_prompt = ChatPromptTemplate.from_messages([ | |
| ("system", _answer_system_prompt(CHAT_MODEL)), | |
| MessagesPlaceholder("history"), | |
| ("human", "{question}"), | |
| ]) | |
| self.fallback_prompt = ChatPromptTemplate.from_messages([ | |
| ("system", _answer_system_prompt(CONDENSE_MODEL)), | |
| MessagesPlaceholder("history"), | |
| ("human", "{question}"), | |
| ]) | |
| self.condense_prompt = ChatPromptTemplate.from_messages([ | |
| ("system", CONDENSE_PROMPT), | |
| MessagesPlaceholder("history"), | |
| ("human", "{question}"), | |
| ]) | |
| self.condense_chain = self.condense_prompt | self.condense_llm | StrOutputParser() | |
| def _standalone_question(self, question: str, history_msgs: list) -> str: | |
| if not history_msgs: | |
| return question | |
| try: | |
| rewritten = self.condense_chain.invoke({"history": history_msgs, "question": question}) | |
| return rewritten.strip() or question | |
| except Exception: | |
| return question | |
| def _retrieve(self, query: str) -> list: | |
| """Hybrid retrieval: vector + BM25 merged with reciprocal-rank fusion, | |
| then (optionally) reranked by a cross-encoder for final precision.""" | |
| rrf: dict[tuple, float] = {} | |
| by_key: dict[tuple, object] = {} | |
| for rank, doc in enumerate(self.vector_store.similarity_search(query, k=CANDIDATE_K)): | |
| key = _doc_key(doc) | |
| by_key[key] = doc | |
| rrf[key] = rrf.get(key, 0.0) + 1.0 / (RRF_C + rank) | |
| if self._bm25 is not None: | |
| scores = self._bm25.get_scores(_bm25_tokenize(query)) | |
| top_idx = sorted(range(len(scores)), key=lambda i: -scores[i])[:CANDIDATE_K] | |
| for rank, i in enumerate(top_idx): | |
| if scores[i] <= 0: | |
| break | |
| doc = self._all_docs[i] | |
| key = _doc_key(doc) | |
| by_key.setdefault(key, doc) | |
| rrf[key] = rrf.get(key, 0.0) + 1.0 / (RRF_C + rank) | |
| # RRF gives the fallback ordering; the reranker sees the FULL union of | |
| # both retrievers' candidates (~2ΓCANDIDATE_K) β it judges relevance | |
| # far better than rank fusion, so don't pre-cut its input. | |
| candidates = [by_key[k] for k in sorted(rrf, key=lambda k: -rrf[k])] | |
| if not candidates: | |
| return [] | |
| if self.reranker is not None: | |
| try: | |
| result = list(self.reranker.compress_documents(documents=candidates, query=query)) | |
| self._rerank_failures = 0 | |
| return result | |
| except Exception as e: | |
| # Tolerate transient blips; only give up after repeated failures | |
| self._rerank_failures += 1 | |
| if self._rerank_failures >= 3: | |
| print(f"[rag] reranker failed {self._rerank_failures}x ({e.__class__.__name__}) β disabled", flush=True) | |
| self.reranker = None | |
| else: | |
| print(f"[rag] reranker error ({e.__class__.__name__}) β using fusion ranking this time", flush=True) | |
| return candidates[:RETRIEVE_K] | |
| def _prepare(self, question: str, history: list[dict] | None): | |
| """Shared retrieval pipeline: returns (chain_inputs, sources).""" | |
| history_msgs = _to_lc_messages(history or []) | |
| t0 = time.perf_counter() | |
| if _needs_condensing(question, history_msgs): | |
| search_query = self._standalone_question(question, history_msgs) | |
| else: | |
| search_query = question | |
| t1 = time.perf_counter() | |
| docs = self._retrieve(search_query) | |
| t2 = time.perf_counter() | |
| print( | |
| f"[rag] condense {t1 - t0:.2f}s | retrieve {t2 - t1:.2f}s " | |
| f"| {len(docs)} chunks | query: {search_query[:80]!r}", | |
| flush=True, | |
| ) | |
| inputs = { | |
| "context": format_docs(docs), | |
| "history": history_msgs, | |
| "question": question, | |
| } | |
| return inputs, _sources_from_docs(docs) | |
| def _stream_with_fallback(self, inputs: dict): | |
| """Stream from the main model; if it errors OR produces no output | |
| within FIRST_TOKEN_TIMEOUT (a congested free endpoint can hang for | |
| 300s before 504ing), answer with the smaller fallback model instead.""" | |
| primary = (self.answer_prompt | self.llm | StrOutputParser()).stream(inputs) | |
| executor = ThreadPoolExecutor(max_workers=1) | |
| future = executor.submit(_first_visible_token, primary) | |
| try: | |
| first = future.result(timeout=FIRST_TOKEN_TIMEOUT) | |
| except _FutureTimeout: | |
| print( | |
| f"[rag] {CHAT_MODEL} gave no output within {FIRST_TOKEN_TIMEOUT:.0f}s β " | |
| f"answering with {CONDENSE_MODEL}", | |
| flush=True, | |
| ) | |
| executor.shutdown(wait=False) | |
| yield from (self.fallback_prompt | self.fallback_llm | StrOutputParser()).stream(inputs) | |
| return | |
| except Exception as e: | |
| print( | |
| f"[rag] {CHAT_MODEL} failed ({e.__class__.__name__}) β " | |
| f"retrying with {CONDENSE_MODEL}", | |
| flush=True, | |
| ) | |
| executor.shutdown(wait=False) | |
| yield from (self.fallback_prompt | self.fallback_llm | StrOutputParser()).stream(inputs) | |
| return | |
| executor.shutdown(wait=False) | |
| if first is _STREAM_END: | |
| return | |
| yield first | |
| yield from primary | |
| def answer(self, question: str, history: list[dict] | None = None) -> tuple[str, list[dict]]: | |
| """Return (answer_text, sources). History is a list of {role, content}.""" | |
| inputs, sources = self._prepare(question, history) | |
| return "".join(self._stream_with_fallback(inputs)), sources | |
| def answer_stream(self, question: str, history: list[dict] | None = None): | |
| """Return (sources, token_generator) so the caller can stream the answer.""" | |
| inputs, sources = self._prepare(question, history) | |
| return sources, self._stream_with_fallback(inputs) | |
| def build_engine(vector_store: FAISS) -> RagEngine: | |
| return RagEngine(vector_store) | |