VishnuRamDebyez commited on
Commit
837bb12
·
verified ·
1 Parent(s): 3c76929

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +74 -48
app.py CHANGED
@@ -9,62 +9,88 @@ from langchain_community.vectorstores import FAISS
9
  from langchain_community.document_loaders import PyPDFDirectoryLoader
10
  from langchain_google_genai import GoogleGenerativeAIEmbeddings
11
  from dotenv import load_dotenv
12
- import os
13
- load_dotenv()
14
 
15
- ## load the GROQ And OpenAI API
 
16
 
17
- groq_api_key=os.getenv('groqapi')
18
- os.environ["GOOGLE_API_KEY"]=os.getenv("GOOGLE_API_KEY")
19
 
20
- st.title("Legal Assistant")
 
 
21
 
22
- llm=ChatGroq(groq_api_key=groq_api_key,
23
- model_name="Llama3-8b-8192")
24
 
25
- prompt=ChatPromptTemplate.from_template(
26
- """
27
- Answer the questions based on the provided context only.
28
- Please provide the most accurate response based on the question
29
- <context>
30
- {context}
31
- <context>
32
- Questions:{input}
33
 
34
- """
 
 
 
 
 
 
 
 
 
 
 
35
  )
36
 
 
37
  def vector_embedding():
38
-
39
- if "vectors" not in st.session_state:
40
-
41
- st.session_state.embeddings=GoogleGenerativeAIEmbeddings(model = "models/embedding-001")
42
- st.session_state.loader=PyPDFDirectoryLoader("./new") ## Data Ingestion
43
- st.session_state.docs=st.session_state.loader.load() ## Document Loading
44
- st.session_state.text_splitter=RecursiveCharacterTextSplitter(chunk_size=1000,chunk_overlap=200) ## Chunk Creation
45
- st.session_state.final_documents=st.session_state.text_splitter.split_documents(st.session_state.docs[:20]) #splitting
46
- st.session_state.vectors=FAISS.from_documents(st.session_state.final_documents,st.session_state.embeddings) #vector OpenAI embeddings
47
-
48
- vector_embedding()
49
-
50
-
51
-
52
- prompt1=st.text_input("Enter Your Question From Doduments")
53
-
54
-
55
-
56
-
57
- import time
58
-
59
-
 
 
 
 
 
 
 
 
 
 
 
 
 
 
60
 
61
  if prompt1:
62
- document_chain=create_stuff_documents_chain(llm,prompt)
63
- retriever=st.session_state.vectors.as_retriever()
64
- retrieval_chain=create_retrieval_chain(retriever,document_chain)
65
- start=time.process_time()
66
- response=retrieval_chain.invoke({'input':prompt1})
67
- print("Response time :",time.process_time()-start)
68
- st.write(response['answer'])
69
-
70
-
 
 
 
 
 
 
 
9
  from langchain_community.document_loaders import PyPDFDirectoryLoader
10
  from langchain_google_genai import GoogleGenerativeAIEmbeddings
11
  from dotenv import load_dotenv
12
+ import time
 
13
 
14
+ # Load environment variables
15
+ load_dotenv()
16
 
17
+ groq_api_key = os.getenv('groqapi')
18
+ google_api_key = os.getenv("GOOGLE_API_KEY")
19
 
20
+ if not groq_api_key or not google_api_key:
21
+ st.error("API keys are missing. Please check your environment variables.")
22
+ st.stop()
23
 
24
+ os.environ["GOOGLE_API_KEY"] = google_api_key
 
25
 
26
+ st.title("Legal Assistant")
 
 
 
 
 
 
 
27
 
28
+ # Initialize LLM
29
+ llm = ChatGroq(groq_api_key=groq_api_key, model_name="Llama3-8b-8192")
30
+
31
+ prompt = ChatPromptTemplate.from_template(
32
+ """
33
+ Answer the questions based on the provided context only.
34
+ Please provide the most accurate response based on the question.
35
+ <context>
36
+ {context}
37
+ <context>
38
+ Questions: {input}
39
+ """
40
  )
41
 
42
+ @st.cache_resource
43
  def vector_embedding():
44
+ embeddings = GoogleGenerativeAIEmbeddings(model="models/embedding-001")
45
+ loader = PyPDFDirectoryLoader("./new")
46
+
47
+ # Check if directory exists
48
+ if not os.path.exists("./new"):
49
+ st.error("The directory './new' does not exist. Please provide the correct path.")
50
+ st.stop()
51
+
52
+ docs = loader.load()
53
+ if not docs:
54
+ st.error("No PDF files found in the './new' directory.")
55
+ st.stop()
56
+
57
+ text_splitter = RecursiveCharacterTextSplitter(chunk_size=1000, chunk_overlap=200)
58
+ final_documents = text_splitter.split_documents(docs[:20])
59
+ vectors = FAISS.from_documents(final_documents, embeddings)
60
+ return vectors
61
+
62
+ st.session_state.vectors = vector_embedding()
63
+
64
+ # Initialize chat history
65
+ if "chat_history" not in st.session_state:
66
+ st.session_state.chat_history = []
67
+
68
+ # Sidebar for chat history
69
+ with st.sidebar:
70
+ st.title("Chat History")
71
+ if st.session_state.chat_history:
72
+ for idx, chat in enumerate(st.session_state.chat_history):
73
+ st.write(f"Q{idx+1}: {chat['question']}")
74
+ st.write(f"A{idx+1}: {chat['answer']}")
75
+ else:
76
+ st.write("No chat history yet.")
77
+
78
+ # User input for question
79
+ prompt1 = st.text_input("Enter Your Question From Documents")
80
 
81
  if prompt1:
82
+ with st.spinner("Retrieving the best answer..."):
83
+ document_chain = create_stuff_documents_chain(llm, prompt)
84
+ retriever = st.session_state.vectors.as_retriever()
85
+ retrieval_chain = create_retrieval_chain(retriever, document_chain)
86
+
87
+ start = time.process_time()
88
+ response = retrieval_chain.invoke({'input': prompt1})
89
+ elapsed_time = time.process_time() - start
90
+
91
+ answer = response.get('answer', "No answer found.")
92
+ st.success(f"Response Time: {elapsed_time:.2f} seconds")
93
+ st.write(answer)
94
+
95
+ # Store the question and answer in chat history
96
+ st.session_state.chat_history.append({"question": prompt1, "answer": answer})