File size: 3,265 Bytes
1f046cf
 
 
 
 
 
 
 
 
 
 
 
ec17a93
1f046cf
 
 
ec17a93
aa1c072
 
 
 
 
 
 
ec17a93
aa1c072
 
 
 
 
1f046cf
ec17a93
1f046cf
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
aa1c072
 
 
3a77dd9
 
 
 
 
1f046cf
 
aa1c072
 
 
720c2e4
 
 
aa1c072
720c2e4
 
 
 
 
 
 
 
 
49910f5
720c2e4
1
2
3
4
5
6
7
8
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
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
import streamlit as st
import os
from langchain_groq import ChatGroq
from langchain.embeddings import HuggingFaceEmbeddings
from langchain.text_splitter import RecursiveCharacterTextSplitter
from langchain.chains.combine_documents import create_stuff_documents_chain
from langchain_core.prompts import ChatPromptTemplate
from langchain.chains import create_retrieval_chain
from langchain_community.vectorstores import FAISS
from langchain_community.document_loaders import PyPDFDirectoryLoader
import time

# Retrieve API keys from environment variables
huggingfacehub_api_token = os.getenv("HUGGINGFACEHUB_API_TOKEN")
groq_api_key = os.getenv("GROQ_API_KEY")

# Check if keys are retrieved correctly
if not huggingfacehub_api_token:
    st.error("HUGGINGFACEHUB_API_TOKEN environment variable is not set")
    st.stop()
if not groq_api_key:
    st.error("GROQ_API_KEY environment variable is not set")
    st.stop()

# Initialize ChatGroq LLM with error handling
try:
    llm = ChatGroq(api_key=groq_api_key, model_name="Llama3-8b-8192")
except Exception as e:
    st.error(f"Failed to initialize ChatGroq LLM: {e}")
    st.stop()


st.title("DataScience Chatgroq With Llama3")

prompt = ChatPromptTemplate.from_template(
"""
Answer the questions based on the provided context only.
Please provide the most accurate response based on the question.
<context>
{context}
<context>
Questions: {input}
"""
)

def vector_embedding():
    if "vectors" not in st.session_state:
        st.session_state.embeddings = HuggingFaceEmbeddings()
        st.session_state.loader = PyPDFDirectoryLoader("./Data_Science")  # Data Ingestion
        st.session_state.docs = st.session_state.loader.load()  # Document Loading
        st.session_state.text_splitter = RecursiveCharacterTextSplitter(chunk_size=1000, chunk_overlap=200)  # Chunk Creation
        st.session_state.final_documents = st.session_state.text_splitter.split_documents(st.session_state.docs[:20])  # Splitting
        st.session_state.vectors = FAISS.from_documents(st.session_state.final_documents, st.session_state.embeddings)  # Vector HuggingFace embeddings
        st.write("Vector Store DB Is Ready")
    else:
        st.write("Vectors already initialized.")
        
prompt1 = st.text_input("Enter Your Question From Documents")

if st.button("Documents Embedding"):
    vector_embedding()

if prompt1:
    if "vectors" not in st.session_state:
        st.error("Vectors are not initialized. Please click 'Documents Embedding' first.")
    else:
        document_chain = create_stuff_documents_chain(llm, prompt)
        retriever = st.session_state.vectors.as_retriever()
        retrieval_chain = create_retrieval_chain(retriever, document_chain)
        try:
            start = time.process_time()
            response = retrieval_chain.invoke({'input': prompt1})
            st.write("Response time: ", time.process_time() - start)
            st.write(response['answer'])

            with st.expander("Document Similarity Search"):
                for i, doc in enumerate(response["context"]):
                    st.write(doc.page_content)
                    st.write("--------------------------------")
        except Exception as e:
            st.error(f"Failed to retrieve the answer: {e}")