import os from dotenv import load_dotenv import streamlit as st import google.generativeai as genai from langchain_community.document_loaders import TextLoader from langchain.text_splitter import RecursiveCharacterTextSplitter from langchain.embeddings import HuggingFaceEmbeddings from langchain_community.vectorstores import FAISS # --- Initial Configuration --- load_dotenv() genai.configure(api_key=os.getenv('GEMINI_API_KEY')) model = genai.GenerativeModel("gemini-1.5-flash") print("Model loaded successfully. 🎊🥳") embeddings = HuggingFaceEmbeddings(model_name="sentence-transformers/all-MiniLM-L6-v2", model_kwargs={'device': 'cpu'}) print("Embeddings model loaded successfully. 🎊🥳") # --- Vector Store Setup --- DB_FAISS_PATH = "ml.faiss_index" vectorstore = None try: doc = TextLoader("mlbookcontent.txt", encoding="utf-8") document = doc.load() if not document: raise ValueError("No document found in the text file.") else: # Use only the RecursiveCharacterTextSplitter for better chunking text_splitter = RecursiveCharacterTextSplitter( chunk_size=1000, chunk_overlap=200, length_function=len, ) texts = text_splitter.split_documents(document) if os.path.exists(DB_FAISS_PATH): vectorstore = FAISS.load_local(DB_FAISS_PATH, embeddings, allow_dangerous_deserialization=True) print("Vector store loaded from local path. 🥳") else: vectorstore = FAISS.from_documents(texts, embeddings) vectorstore.save_local(DB_FAISS_PATH) print("Vector store created and saved. 🎉🎊") except Exception as e: st.error(f"Error during document processing: {e}") raise RuntimeError(f"Failed to initialize vectorstore: {e}") # __________Backend Logic (Corrected)_________ def generate_response(query): """ Generates a response based on the query, using RAG if relevant keywords are found. """ keywords = [ "Machine learning", "Artificial Intelligence", "Deep Learning", "Neural Networks", "Computer Vision", "Natural Language Processing", "Reinforcement Learning", "Supervised Learning", "Unsupervised Learning", "Semi-Supervised Learning", "Generative Models", "ML", "AI", "NLP", "CV" ] query_is_relevant = any(keyword.lower() in query.lower() for keyword in keywords) prompt = "" if query_is_relevant and vectorstore: relevant_docs = vectorstore.similarity_search(query, k=3) if relevant_docs: context = "\n\n".join([doc.page_content for doc in relevant_docs]) prompt = f""" You are an expert in the field of Machine Learning and Artificial Intelligence. Use ONLY the following context to answer the user's question. Do not use any external knowledge. If the answer is not in the context, politely state that you cannot find the information in the provided document. Context: {context} Question: {query} """ else: query_is_relevant = False if not query_is_relevant: prompt = f""" You are an expert in the field of Machine Learning and Artificial Intelligence. Answer the question based on your general knowledge. Question: {query} """ try: response = model.generate_content(prompt) return response.text.strip() except Exception as e: return f"Sorry, an error occurred while generating the response: {e}" # __________Frontend Setup_________ # -------------------- STREAMLIT UI -------------------- st.set_page_config(page_title="RAG Chatbot", page_icon="🤖", layout="wide") # Dark Theme CSS st.markdown(""" """, unsafe_allow_html=True) # -------------------- SIDEBAR -------------------- with st.sidebar: st.markdown("
", unsafe_allow_html=True) st.markdown("", unsafe_allow_html=True) st.markdown("