Update final.py
Browse files
final.py
CHANGED
|
@@ -1,130 +1,131 @@
|
|
| 1 |
-
import os
|
| 2 |
-
import streamlit as st
|
| 3 |
-
from langchain.embeddings import HuggingFaceEmbeddings
|
| 4 |
-
from langchain.chains import RetrievalQA
|
| 5 |
-
from langchain_community.vectorstores import FAISS
|
| 6 |
-
from langchain_core.prompts import PromptTemplate
|
| 7 |
-
from langchain_huggingface import HuggingFaceEndpoint
|
| 8 |
-
from dotenv import load_dotenv, find_dotenv
|
| 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 |
-
If the
|
| 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 |
-
st.
|
| 122 |
-
|
| 123 |
-
|
| 124 |
-
|
| 125 |
-
|
| 126 |
-
|
| 127 |
-
st.
|
| 128 |
-
|
| 129 |
-
|
| 130 |
-
|
|
|
|
|
|
| 1 |
+
import os
|
| 2 |
+
import streamlit as st
|
| 3 |
+
from langchain.embeddings import HuggingFaceEmbeddings
|
| 4 |
+
from langchain.chains import RetrievalQA
|
| 5 |
+
from langchain_community.vectorstores import FAISS
|
| 6 |
+
from langchain_core.prompts import PromptTemplate
|
| 7 |
+
from langchain_huggingface import HuggingFaceEndpoint
|
| 8 |
+
from dotenv import load_dotenv, find_dotenv
|
| 9 |
+
|
| 10 |
+
|
| 11 |
+
# β
Load environment variables
|
| 12 |
+
load_dotenv(find_dotenv())
|
| 13 |
+
|
| 14 |
+
# β
FAISS Database Path
|
| 15 |
+
DB_FAISS_PATH = "vectorstore/db_faiss"
|
| 16 |
+
|
| 17 |
+
@st.cache_resource
|
| 18 |
+
def get_vectorstore():
|
| 19 |
+
"""Loads the FAISS vector store with embeddings."""
|
| 20 |
+
try:
|
| 21 |
+
embedding_model = HuggingFaceEmbeddings(model_name='sentence-transformers/all-MiniLM-L6-v2')
|
| 22 |
+
return FAISS.load_local(DB_FAISS_PATH, embedding_model, allow_dangerous_deserialization=True)
|
| 23 |
+
except Exception as e:
|
| 24 |
+
st.error(f"β οΈ Error loading vector store: {str(e)}")
|
| 25 |
+
return None
|
| 26 |
+
|
| 27 |
+
@st.cache_resource
|
| 28 |
+
def load_llm():
|
| 29 |
+
"""Loads the Hugging Face LLM model for text generation."""
|
| 30 |
+
HUGGINGFACE_REPO_ID = "mistralai/Mistral-7B-Instruct-v0.3"
|
| 31 |
+
HF_TOKEN = os.getenv("HF_TOKEN")
|
| 32 |
+
|
| 33 |
+
if not HF_TOKEN:
|
| 34 |
+
st.error("β οΈ Hugging Face API token is missing. Please check your environment variables.")
|
| 35 |
+
return None
|
| 36 |
+
|
| 37 |
+
try:
|
| 38 |
+
return HuggingFaceEndpoint(
|
| 39 |
+
repo_id=HUGGINGFACE_REPO_ID,
|
| 40 |
+
task="text-generation",
|
| 41 |
+
temperature=0.3,
|
| 42 |
+
model_kwargs={"token": HF_TOKEN, "max_length": 256}
|
| 43 |
+
)
|
| 44 |
+
except Exception as e:
|
| 45 |
+
st.error(f"β οΈ Error loading LLM: {str(e)}")
|
| 46 |
+
return None
|
| 47 |
+
|
| 48 |
+
def set_custom_prompt():
|
| 49 |
+
"""Defines the chatbot's behavior with a custom prompt template."""
|
| 50 |
+
return PromptTemplate(
|
| 51 |
+
template="""
|
| 52 |
+
You are an SEO chatbot with advanced knowledge. Answer based **strictly** on the provided documents.
|
| 53 |
+
|
| 54 |
+
If the answer is in the context, provide a **clear, professional, and concise** response with sources.
|
| 55 |
+
If the question is **outside the given context**, politely decline:
|
| 56 |
+
|
| 57 |
+
**"I'm sorry, but I can only provide answers based on the available documents."**
|
| 58 |
+
|
| 59 |
+
**Context:** {context}
|
| 60 |
+
**Question:** {question}
|
| 61 |
+
|
| 62 |
+
**Answer:**
|
| 63 |
+
""",
|
| 64 |
+
input_variables=["context", "question"]
|
| 65 |
+
)
|
| 66 |
+
|
| 67 |
+
def generate_response(prompt, vectorstore, llm):
|
| 68 |
+
"""Retrieves relevant documents and generates a response from the LLM."""
|
| 69 |
+
if not vectorstore or not llm:
|
| 70 |
+
return "β Unable to process your request due to initialization issues."
|
| 71 |
+
|
| 72 |
+
try:
|
| 73 |
+
qa_chain = RetrievalQA.from_chain_type(
|
| 74 |
+
llm=llm,
|
| 75 |
+
chain_type="stuff",
|
| 76 |
+
retriever=vectorstore.as_retriever(search_kwargs={'k': 3}),
|
| 77 |
+
return_source_documents=True,
|
| 78 |
+
chain_type_kwargs={'prompt': set_custom_prompt()}
|
| 79 |
+
)
|
| 80 |
+
|
| 81 |
+
response_data = qa_chain.invoke({'query': prompt})
|
| 82 |
+
result = response_data.get("result", "")
|
| 83 |
+
source_documents = response_data.get("source_documents", [])
|
| 84 |
+
|
| 85 |
+
if not result or not source_documents:
|
| 86 |
+
return "β Sorry, but I can only provide answers based on the available documents."
|
| 87 |
+
|
| 88 |
+
formatted_sources = "\n\nπ **Sources:**" + "".join(
|
| 89 |
+
[f"\n- {doc.metadata.get('source', 'Unknown')} (Page: {doc.metadata.get('page', 'N/A')})" for doc in source_documents]
|
| 90 |
+
)
|
| 91 |
+
return f"{result}{formatted_sources}"
|
| 92 |
+
|
| 93 |
+
except Exception as e:
|
| 94 |
+
return f"β οΈ **Error:** {str(e)}"
|
| 95 |
+
|
| 96 |
+
def main():
|
| 97 |
+
"""Runs the Streamlit chatbot application."""
|
| 98 |
+
st.title("π§ Brainmines SEO Chatbot - Your AI Assistant for SEO Queries π")
|
| 99 |
+
|
| 100 |
+
# β
Load vector store and LLM
|
| 101 |
+
vectorstore = get_vectorstore()
|
| 102 |
+
llm = load_llm()
|
| 103 |
+
|
| 104 |
+
if not vectorstore or not llm:
|
| 105 |
+
st.error("β οΈ Failed to initialize vector store or LLM. Please check configurations.")
|
| 106 |
+
return
|
| 107 |
+
|
| 108 |
+
# β
Initialize session state
|
| 109 |
+
if "messages" not in st.session_state:
|
| 110 |
+
st.session_state.messages = [
|
| 111 |
+
{"role": "assistant", "content": "Hello! π I'm here to assist you with SEO-related queries. π"},
|
| 112 |
+
]
|
| 113 |
+
|
| 114 |
+
# β
Display chat history
|
| 115 |
+
for message in st.session_state.messages:
|
| 116 |
+
st.chat_message(message["role"]).markdown(message["content"])
|
| 117 |
+
|
| 118 |
+
prompt = st.chat_input("π¬ Enter your SEO question here")
|
| 119 |
+
|
| 120 |
+
if prompt:
|
| 121 |
+
st.chat_message("user").markdown(prompt)
|
| 122 |
+
st.session_state.messages.append({"role": "user", "content": prompt})
|
| 123 |
+
|
| 124 |
+
with st.spinner("Thinking... π€"):
|
| 125 |
+
response = generate_response(prompt, vectorstore, llm)
|
| 126 |
+
|
| 127 |
+
st.chat_message("assistant").markdown(response)
|
| 128 |
+
st.session_state.messages.append({"role": "assistant", "content": response})
|
| 129 |
+
|
| 130 |
+
if __name__ == "__main__":
|
| 131 |
+
main()
|