Spaces:
Sleeping
Sleeping
Download rag_chain.py from StudyOcean/Study-Ocean-AI-Mentor: direct link, hf CLI and curl.
- Browser
- Download file 7.29 kB
-
https://huggingface.co/spaces/StudyOcean/Study-Ocean-AI-Mentor/resolve/main/rag_chain.py
- Command line
-
hf download hf://spaces/StudyOcean/Study-Ocean-AI-Mentor/rag_chain.py
-
curl -L -o rag_chain.py https://huggingface.co/spaces/StudyOcean/Study-Ocean-AI-Mentor/resolve/main/rag_chain.py
7.29 kB
| """ | |
| RAG Chain module for Study Ocean Student Mentor. | |
| Reverted to stable RetrievalQA for compatibility with LangChain 0.2.x. | |
| """ | |
| from langchain_community.vectorstores import FAISS | |
| from langchain_huggingface import HuggingFaceEmbeddings | |
| from langchain_google_genai import ChatGoogleGenerativeAI | |
| from langchain.chains import RetrievalQA | |
| from langchain.prompts import PromptTemplate | |
| import config | |
| # βββ System Prompt for Student Mentor ββββββββββββββββββββββββ | |
| STUDENT_MENTOR_PROMPT = PromptTemplate( | |
| input_variables=["context", "question"], | |
| template="""You are **Study Ocean AI Mentor** β a friendly, patient, and knowledgeable tutor who helps students understand their study material deeply. | |
| Your role: | |
| - You solve student doubts with clear, step-by-step explanations | |
| - You use simple language that students can easily understand | |
| - You provide examples and analogies when helpful | |
| - You reference the study material when answering | |
| - If the answer is in the provided context, use it; if not, say so honestly | |
| - You encourage students and make learning enjoyable | |
| **Important Guidelines:** | |
| 1. Start with a brief, direct answer, then explain in detail | |
| 2. Use bullet points, numbered steps, or tables for clarity | |
| 3. If it's a math/science problem, show the solution step by step | |
| 4. If it's a theory question, break it into key points | |
| 5. Mention which topic/chapter the information relates to when possible | |
| 6. If the user is just saying "hi", "how are you", or making casual conversation, respond warmly and naturally without mentioning study materials. | |
| 7. If it's a genuine study question not covered in the context, say: "This isn't explicitly in your study materials, but here is the answer..." | |
| 8. π Use relevant emojis generously in every response to make learning fun and visually appealing for Gen-Z students! | |
| --- | |
| π **Relevant Study Material:** | |
| {context} | |
| --- | |
| π **Student's Question:** | |
| {question} | |
| --- | |
| π **Mentor's Response:** | |
| """ | |
| ) | |
| def load_vector_store() -> FAISS: | |
| """Load the pre-built FAISS vector store from disk. Fallback to ingestion if it fails.""" | |
| embeddings = HuggingFaceEmbeddings( | |
| model_name=config.EMBEDDING_MODEL, | |
| model_kwargs={"device": "cpu"}, | |
| encode_kwargs={"normalize_embeddings": True}, | |
| ) | |
| try: | |
| print("π Loading vector store...") | |
| vector_store = FAISS.load_local( | |
| config.VECTOR_STORE_PATH, | |
| embeddings, | |
| allow_dangerous_deserialization=True, | |
| ) | |
| print(" β Vector store loaded!") | |
| except Exception as e: | |
| print(f" β Failed to load vector store: {e}") | |
| print(" π Automatically rebuilding index from PDFs... (This may take a minute)") | |
| from ingest import run_ingestion | |
| run_ingestion() | |
| # Try loading again after ingestion | |
| vector_store = FAISS.load_local( | |
| config.VECTOR_STORE_PATH, | |
| embeddings, | |
| allow_dangerous_deserialization=True, | |
| ) | |
| print(" β Vector store rebuilt and loaded!") | |
| return vector_store | |
| def build_rag_chain(vector_store: FAISS) -> RetrievalQA: | |
| """Build the RAG chain with retriever + LLM.""" | |
| # Configure retriever | |
| retriever = vector_store.as_retriever( | |
| search_type="similarity", | |
| search_kwargs={"k": config.TOP_K_RESULTS}, | |
| ) | |
| # Initialize Groq LLM (Super Fast) | |
| from langchain_groq import ChatGroq | |
| # Aggressive cleaning of the Groq key | |
| import re | |
| raw_key = str(config.GROQ_API_KEY) | |
| api_key = re.sub(r'[^a-zA-Z0-9_\-]', '', raw_key) | |
| print(f" β‘ Groq Engine active. Key length: {len(api_key)}") | |
| llm = ChatGroq( | |
| model_name=config.LLM_MODEL, | |
| groq_api_key=api_key, | |
| temperature=config.TEMPERATURE, | |
| max_tokens=config.MAX_OUTPUT_TOKENS, | |
| ) | |
| # Build the RAG chain | |
| chain = RetrievalQA.from_chain_type( | |
| llm=llm, | |
| chain_type="stuff", | |
| retriever=retriever, | |
| return_source_documents=True, | |
| chain_type_kwargs={ | |
| "prompt": STUDENT_MENTOR_PROMPT, | |
| }, | |
| ) | |
| return chain | |
| def ask_question(chain: RetrievalQA, question: str) -> dict: | |
| """ | |
| Ask a question and get the mentor's response along with source references. | |
| """ | |
| result = chain.invoke({"query": question}) | |
| # Extract source info | |
| sources = [] | |
| seen = set() | |
| for doc in result.get("source_documents", []): | |
| source_name = doc.metadata.get("source", "Unknown") | |
| subject = doc.metadata.get("subject", "General") | |
| key = f"{subject}/{source_name}" | |
| if key not in seen: | |
| seen.add(key) | |
| sources.append({ | |
| "file": source_name, | |
| "subject": subject, | |
| "preview": doc.page_content[:150] + "..." if len(doc.page_content) > 150 else doc.page_content, | |
| }) | |
| return { | |
| "answer": result["result"], | |
| "sources": sources, | |
| } | |
| def stream_question(chain: RetrievalQA, question: str): | |
| """ | |
| Generator that streams the response word-by-word with maximum compatibility. | |
| """ | |
| try: | |
| print(f"π‘ Received streaming request for: '{question[:50]}...'") | |
| # 1. Access components safely | |
| # RetrievalQA has a 'retriever' attribute | |
| docs = chain.retriever.get_relevant_documents(question) | |
| context = "\n\n".join([doc.page_content for doc in docs]) | |
| print(f" π Found {len(docs)} relevant chunks.") | |
| # 2. Extract sources | |
| sources = [] | |
| seen = set() | |
| for doc in docs: | |
| source_name = doc.metadata.get("source", "Unknown") | |
| subject = doc.metadata.get("subject", "General") | |
| key = f"{subject}/{source_name}" | |
| if key not in seen: | |
| seen.add(key) | |
| sources.append({"file": source_name, "subject": subject}) | |
| # 3. Stream from the LLM (which is inside the combine_documents_chain) | |
| # In RetrievalQA, the LLM is available via chain.combine_documents_chain.llm_chain.llm | |
| llm = chain.combine_documents_chain.llm_chain.llm | |
| prompt = STUDENT_MENTOR_PROMPT.format(context=context, question=question) | |
| import json | |
| yield f"DATA:{json.dumps({'sources': sources})}\n\n" | |
| print(" π§ Starting LLM stream...") | |
| token_count = 0 | |
| for chunk in llm.stream(prompt): | |
| token_count += 1 | |
| yield chunk.content | |
| print(f" β Stream complete. Sent {token_count} chunks.") | |
| except Exception as e: | |
| print(f" β Streaming Error: {str(e)}") | |
| import traceback | |
| traceback.print_exc() | |
| yield f"\n\n**Backend Error:** {str(e)}\n\nPlease ensure your Space has the GOOGLE_API_KEY secret set." | |
| # βββ Singleton pattern for reuse ββββββββββββββββββββββββββββ | |
| _chain_instance = None | |
| def get_chain(): | |
| """Get or create the RAG chain (singleton).""" | |
| global _chain_instance | |
| if _chain_instance is None: | |
| vector_store = load_vector_store() | |
| _chain_instance = build_rag_chain(vector_store) | |
| return _chain_instance | |