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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import os
|
2 |
+
import requests
|
3 |
+
import streamlit as st
|
4 |
+
import pickle
|
5 |
+
from langchain.chains import LLMChain
|
6 |
+
from langchain.prompts import PromptTemplate
|
7 |
+
from langchain_groq import ChatGroq
|
8 |
+
from langchain.document_loaders import PDFPlumberLoader
|
9 |
+
from langchain_experimental.text_splitter import SemanticChunker
|
10 |
+
from langchain_huggingface import HuggingFaceEmbeddings
|
11 |
+
from langchain_chroma import Chroma
|
12 |
+
from langchain.chains import SequentialChain, LLMChain
|
13 |
+
|
14 |
+
# Set API Keys
|
15 |
+
os.environ["GROQ_API_KEY"] = st.secrets.get("GROQ_API_KEY", "")
|
16 |
+
|
17 |
+
# Load LLM models
|
18 |
+
llm_judge = ChatGroq(model="deepseek-r1-distill-llama-70b")
|
19 |
+
rag_llm = ChatGroq(model="mixtral-8x7b-32768")
|
20 |
+
|
21 |
+
llm_judge.verbose = True
|
22 |
+
rag_llm.verbose = True
|
23 |
+
|
24 |
+
VECTOR_DB_PATH = "/tmp/chroma_db"
|
25 |
+
CHUNKS_FILE = "/tmp/chunks.pkl"
|
26 |
+
|
27 |
+
# Session State Initialization
|
28 |
+
if "vector_store" not in st.session_state:
|
29 |
+
st.session_state.vector_store = None
|
30 |
+
if "documents" not in st.session_state:
|
31 |
+
st.session_state.documents = None
|
32 |
+
if "pdf_path" not in st.session_state:
|
33 |
+
st.session_state.pdf_path = None
|
34 |
+
if "pdf_loaded" not in st.session_state:
|
35 |
+
st.session_state.pdf_loaded = False
|
36 |
+
if "chunked" not in st.session_state:
|
37 |
+
st.session_state.chunked = False
|
38 |
+
if "vector_created" not in st.session_state:
|
39 |
+
st.session_state.vector_created = False
|
40 |
+
|
41 |
+
st.title("Blah-2")
|
42 |
+
|
43 |
+
# Step 1: Choose PDF Source
|
44 |
+
pdf_source = st.radio("Upload or provide a link to a PDF:", ["Enter a PDF URL", "Upload a PDF file"], index=0, horizontal=True)
|
45 |
+
|
46 |
+
if pdf_source == "Upload a PDF file":
|
47 |
+
uploaded_file = st.file_uploader("Upload your PDF file", type="pdf")
|
48 |
+
if uploaded_file:
|
49 |
+
st.session_state.pdf_path = "temp.pdf"
|
50 |
+
with open(st.session_state.pdf_path, "wb") as f:
|
51 |
+
f.write(uploaded_file.getbuffer())
|
52 |
+
st.session_state.pdf_loaded = False
|
53 |
+
st.session_state.chunked = False
|
54 |
+
st.session_state.vector_created = False
|
55 |
+
|
56 |
+
elif pdf_source == "Enter a PDF URL":
|
57 |
+
pdf_url = st.text_input("Enter PDF URL:", value="https://arxiv.org/pdf/2406.06998", key="pdf_url", on_change=lambda: st.session_state.update(trigger_download=True))
|
58 |
+
|
59 |
+
# Button OR Enter key will trigger download
|
60 |
+
if st.button("Download and Process PDF") or st.session_state.get("trigger_download", False):
|
61 |
+
with st.spinner("Downloading PDF..."):
|
62 |
+
try:
|
63 |
+
response = requests.get(pdf_url)
|
64 |
+
if response.status_code == 200:
|
65 |
+
st.session_state.pdf_path = "temp.pdf"
|
66 |
+
with open(st.session_state.pdf_path, "wb") as f:
|
67 |
+
f.write(response.content)
|
68 |
+
|
69 |
+
# Reset states
|
70 |
+
st.session_state.pdf_loaded = False
|
71 |
+
st.session_state.chunked = False
|
72 |
+
st.session_state.vector_created = False
|
73 |
+
st.session_state.trigger_download = False # Reset trigger
|
74 |
+
|
75 |
+
st.success("β
PDF Downloaded Successfully!")
|
76 |
+
else:
|
77 |
+
st.error("β Failed to download PDF. Check the URL.")
|
78 |
+
except Exception as e:
|
79 |
+
st.error(f"β Error downloading PDF: {e}")
|
80 |
+
|
81 |
+
|
82 |
+
# Step 2: Load & Process PDF (Only Once)
|
83 |
+
if st.session_state.pdf_path and not st.session_state.pdf_loaded:
|
84 |
+
with st.spinner("Loading PDF..."):
|
85 |
+
try:
|
86 |
+
loader = PDFPlumberLoader(st.session_state.pdf_path)
|
87 |
+
docs = loader.load()
|
88 |
+
st.session_state.documents = docs
|
89 |
+
st.session_state.pdf_loaded = True
|
90 |
+
st.success(f"β
**PDF Loaded!** Total Pages: {len(docs)}")
|
91 |
+
except Exception as e:
|
92 |
+
st.error(f"β Error processing PDF: {e}")
|
93 |
+
|
94 |
+
# Load Cached Chunks if Available
|
95 |
+
def load_chunks():
|
96 |
+
if os.path.exists(CHUNKS_FILE):
|
97 |
+
with open(CHUNKS_FILE, "rb") as f:
|
98 |
+
return pickle.load(f)
|
99 |
+
return None
|
100 |
+
|
101 |
+
if not st.session_state.chunked: # Ensure chunking only happens once
|
102 |
+
cached_chunks = load_chunks()
|
103 |
+
if cached_chunks:
|
104 |
+
st.session_state.documents = cached_chunks
|
105 |
+
st.session_state.chunked = True
|
106 |
+
|
107 |
+
# Step 3: Chunking (Only Happens Once)
|
108 |
+
if st.session_state.pdf_loaded and not st.session_state.chunked:
|
109 |
+
with st.spinner("Chunking the document..."):
|
110 |
+
try:
|
111 |
+
model_name = "nomic-ai/modernbert-embed-base"
|
112 |
+
embedding_model = HuggingFaceEmbeddings(model_name=model_name, model_kwargs={'device': 'cpu'})
|
113 |
+
text_splitter = SemanticChunker(embedding_model)
|
114 |
+
|
115 |
+
if st.session_state.documents:
|
116 |
+
documents = text_splitter.split_documents(st.session_state.documents)
|
117 |
+
st.session_state.documents = documents
|
118 |
+
st.session_state.chunked = True
|
119 |
+
|
120 |
+
# Save chunks for persistence
|
121 |
+
with open(CHUNKS_FILE, "wb") as f:
|
122 |
+
pickle.dump(documents, f)
|
123 |
+
|
124 |
+
st.success(f"β
**Document Chunked!** Total Chunks: {len(documents)}")
|
125 |
+
except Exception as e:
|
126 |
+
st.error(f"β Error chunking document: {e}")
|
127 |
+
|
128 |
+
# Step 4: Setup Vectorstore
|
129 |
+
def load_vector_store():
|
130 |
+
return Chroma(persist_directory=VECTOR_DB_PATH, collection_name="deepseek_collection", embedding_function=HuggingFaceEmbeddings(model_name="nomic-ai/modernbert-embed-base"))
|
131 |
+
|
132 |
+
if st.session_state.chunked and not st.session_state.vector_created:
|
133 |
+
with st.spinner("Creating vector store..."):
|
134 |
+
try:
|
135 |
+
if st.session_state.vector_store is None: # Prevent unnecessary reloading
|
136 |
+
st.session_state.vector_store = load_vector_store()
|
137 |
+
|
138 |
+
if len(st.session_state.vector_store.get()["documents"]) == 0: # Prevent duplicate insertions
|
139 |
+
st.session_state.vector_store.add_documents(st.session_state.documents)
|
140 |
+
|
141 |
+
num_documents = len(st.session_state.vector_store.get()["documents"])
|
142 |
+
st.session_state.vector_created = True
|
143 |
+
st.success(f"β
**Vector Store Created!** Total documents stored: {num_documents}")
|
144 |
+
except Exception as e:
|
145 |
+
st.error(f"β Error creating vector store: {e}")
|
146 |
+
|
147 |
+
# Debugging Logs
|
148 |
+
#st.write("π **PDF Loaded:**", st.session_state.pdf_loaded)
|
149 |
+
#st.write("πΉ **Chunked:**", st.session_state.chunked)
|
150 |
+
#st.write("π **Vector Store Created:**", st.session_state.vector_created)
|
151 |
+
|
152 |
+
|
153 |
+
# ----------------- Query Input -----------------
|
154 |
+
query = None
|
155 |
+
|
156 |
+
# Check if a valid PDF URL has been entered (but not processed yet)
|
157 |
+
pdf_url_entered = bool(st.session_state.get("pdf_url")) # Checks if text is in the input box
|
158 |
+
|
159 |
+
# No PDF Provided Yet
|
160 |
+
if not st.session_state.pdf_path and not pdf_url_entered:
|
161 |
+
st.info("π₯ **Please upload a PDF or enter a valid URL to proceed.**")
|
162 |
+
|
163 |
+
# PDF URL Exists but Not Processed Yet (Only show if URL exists but hasn't been downloaded)
|
164 |
+
elif pdf_url_entered and not st.session_state.pdf_loaded:
|
165 |
+
st.warning("β οΈ **PDF URL detected! Click 'Download and Process PDF' to proceed.**")
|
166 |
+
|
167 |
+
# Processing in Progress
|
168 |
+
elif st.session_state.get("trigger_download", False) and (
|
169 |
+
not st.session_state.pdf_loaded or not st.session_state.chunked or not st.session_state.vector_created
|
170 |
+
):
|
171 |
+
st.info("β³ **Processing your document... Please wait.**")
|
172 |
+
|
173 |
+
# β
Step 4: Processing Complete, Ready for Questions
|
174 |
+
elif st.session_state.pdf_loaded and st.session_state.chunked and st.session_state.vector_created:
|
175 |
+
st.success("π **Processing complete! You can now ask questions.**")
|
176 |
+
query = st.text_input("π **Ask a question about the document:**")
|
177 |
+
|
178 |
+
if query:
|
179 |
+
with st.spinner("π Retrieving relevant context..."):
|
180 |
+
retriever = st.session_state.vector_store.as_retriever(search_type="similarity", search_kwargs={"k": 3})
|
181 |
+
contexts = retriever.invoke(query)
|
182 |
+
# Debugging: Check what was retrieved
|
183 |
+
st.write("Retrieved Contexts:", contexts)
|
184 |
+
st.write("Number of Contexts:", len(contexts))
|
185 |
+
|
186 |
+
context = [d.page_content for d in contexts]
|
187 |
+
# Debugging: Check extracted context
|
188 |
+
st.write("Extracted Context (page_content):", context)
|
189 |
+
st.write("Number of Extracted Contexts:", len(context))
|
190 |
+
|
191 |
+
relevancy_prompt = """You are an expert judge tasked with evaluating whether the EACH OF THE CONTEXT provided in the CONTEXT LIST is self sufficient to answer the QUERY asked.
|
192 |
+
Analyze the provided QUERY AND CONTEXT to determine if each Ccontent in the CONTEXT LIST contains Relevant information to answer the QUERY.
|
193 |
+
|
194 |
+
Guidelines:
|
195 |
+
1. The content must not introduce new information beyond what's provided in the QUERY.
|
196 |
+
2. Pay close attention to the subject of statements. Ensure that attributes, actions, or dates are correctly associated with the right entities (e.g., a person vs. a TV show they star in).
|
197 |
+
3. Be vigilant for subtle misattributions or conflations of information, even if the date or other details are correct.
|
198 |
+
4. Check that the content in the CONTEXT LIST doesn't oversimplify or generalize information in a way that changes the meaning of the QUERY.
|
199 |
+
|
200 |
+
Analyze the text thoroughly and assign a relevancy score 0 or 1 where:
|
201 |
+
- 0: The content has all the necessary information to answer the QUERY
|
202 |
+
- 1: The content does not has the necessary information to answer the QUERY
|
203 |
+
|
204 |
+
```
|
205 |
+
EXAMPLE:
|
206 |
+
INPUT (for context only, not to be used for faithfulness evaluation):
|
207 |
+
What is the capital of France?
|
208 |
+
|
209 |
+
CONTEXT:
|
210 |
+
['France is a country in Western Europe. Its capital is Paris, which is known for landmarks like the Eiffel Tower.',
|
211 |
+
'Mr. Naveen patnaik has been the chief minister of Odisha for consequetive 5 terms']
|
212 |
+
|
213 |
+
OUTPUT:
|
214 |
+
The Context has sufficient information to answer the query.
|
215 |
+
|
216 |
+
RESPONSE:
|
217 |
+
{{"score":0}}
|
218 |
+
```
|
219 |
+
|
220 |
+
CONTENT LIST:
|
221 |
+
{context}
|
222 |
+
|
223 |
+
QUERY:
|
224 |
+
{retriever_query}
|
225 |
+
Provide your verdict in JSON format with a single key 'score' and no preamble or explanation:
|
226 |
+
[{{"content:1,"score": <your score either 0 or 1>,"Reasoning":<why you have chose the score as 0 or 1>}},
|
227 |
+
{{"content:2,"score": <your score either 0 or 1>,"Reasoning":<why you have chose the score as 0 or 1>}},
|
228 |
+
...]
|
229 |
+
"""
|
230 |
+
|
231 |
+
context_relevancy_checker_prompt = PromptTemplate(input_variables=["retriever_query","context"],template=relevancy_prompt)
|
232 |
+
|
233 |
+
relevant_prompt = PromptTemplate(
|
234 |
+
input_variables=["relevancy_response"],
|
235 |
+
template="""
|
236 |
+
Your main task is to analyze the json structure as a part of the Relevancy Response.
|
237 |
+
Review the Relevancy Response and do the following:-
|
238 |
+
(1) Look at the Json Structure content
|
239 |
+
(2) Analyze the 'score' key in the Json Structure content.
|
240 |
+
(3) pick the value of 'content' key against those 'score' key value which has 0.
|
241 |
+
|
242 |
+
Relevancy Response:
|
243 |
+
{relevancy_response}
|
244 |
+
|
245 |
+
Provide your verdict in JSON format with a single key 'content number' and no preamble or explanation:
|
246 |
+
[{{"content":<content number>}}]
|
247 |
+
"""
|
248 |
+
)
|
249 |
+
|
250 |
+
context_prompt = PromptTemplate(
|
251 |
+
input_variables=["context_number"],
|
252 |
+
template="""
|
253 |
+
Your main task is to analyze the json structure as a part of the Context Number Response and the list of Contexts provided in the 'Content List' and perform the following steps:-
|
254 |
+
(1) Look at the output from the Relevant Context Picker Agent.
|
255 |
+
(2) Analyze the 'content' key in the Json Structure format({{"content":<<content_number>>}}).
|
256 |
+
(3) Retrieve the value of 'content' key and pick up the context corresponding to that element from the Content List provided.
|
257 |
+
(4) Pass the retrieved context for each corresponing element number referred in the 'Context Number Response'
|
258 |
+
|
259 |
+
Context Number Response:
|
260 |
+
{context_number}
|
261 |
+
|
262 |
+
Content List:
|
263 |
+
{context}
|
264 |
+
|
265 |
+
Provide your verdict in JSON format with a two key 'relevant_content' and 'context_number' no preamble or explanation:
|
266 |
+
[{{"context_number":<content1>,"relevant_content":<content corresponing to that element 1 in the Content List>}},
|
267 |
+
{{"context_number":<content4>,"relevant_content":<content corresponing to that element 4 in the Content List>}},
|
268 |
+
...
|
269 |
+
]
|
270 |
+
"""
|
271 |
+
)
|
272 |
+
|
273 |
+
rag_prompt = """ You are a helpful assistant very profiient in formulating clear and meaningful answers from the context provided.Based on the CONTEXT Provided ,Please formulate
|
274 |
+
a clear concise and meaningful answer for the QUERY asked.Please refrain from making up your own answer in case the COTEXT provided is not sufficient to answer the QUERY.In such a situation please respond as 'I do not know'.
|
275 |
+
|
276 |
+
QUERY:
|
277 |
+
{query}
|
278 |
+
|
279 |
+
CONTEXT
|
280 |
+
{context}
|
281 |
+
|
282 |
+
ANSWER:
|
283 |
+
"""
|
284 |
+
|
285 |
+
context_relevancy_evaluation_chain = LLMChain(llm=llm_judge, prompt=context_relevancy_checker_prompt, output_key="relevancy_response")
|
286 |
+
|
287 |
+
response_crisis = context_relevancy_evaluation_chain.invoke({"context":context,"retriever_query":query})
|
288 |
+
|
289 |
+
pick_relevant_context_chain = LLMChain(llm=llm_judge, prompt=relevant_prompt, output_key="context_number")
|
290 |
+
|
291 |
+
relevant_response = pick_relevant_context_chain.invoke({"relevancy_response":response_crisis['relevancy_response']})
|
292 |
+
|
293 |
+
relevant_contexts_chain = LLMChain(llm=llm_judge, prompt=context_prompt, output_key="relevant_contexts")
|
294 |
+
|
295 |
+
contexts = relevant_contexts_chain.invoke({"context_number":relevant_response['context_number'],"context":context})
|
296 |
+
|
297 |
+
final_prompt = PromptTemplate(input_variables=["query","context"],template=rag_prompt)
|
298 |
+
|
299 |
+
response_chain = LLMChain(llm=rag_llm,prompt=final_prompt,output_key="final_response")
|
300 |
+
|
301 |
+
response = response_chain.invoke({"query":query,"context":contexts['relevant_contexts']})
|
302 |
+
|
303 |
+
# Orchestrate using SequentialChain
|
304 |
+
context_management_chain = SequentialChain(
|
305 |
+
chains=[context_relevancy_evaluation_chain ,pick_relevant_context_chain, relevant_contexts_chain,response_chain],
|
306 |
+
input_variables=["context","retriever_query","query"],
|
307 |
+
output_variables=["relevancy_response", "context_number","relevant_contexts","final_response"]
|
308 |
+
)
|
309 |
+
|
310 |
+
final_output = context_management_chain({"context":context,"retriever_query":query,"query":query})
|
311 |
+
|
312 |
+
st.subheader('final_output["relevancy_response"]')
|
313 |
+
st.write(final_output["relevancy_response"] )
|
314 |
+
|
315 |
+
st.subheader('final_output["context_number"]')
|
316 |
+
st.write(final_output["context_number"])
|
317 |
+
|
318 |
+
st.subheader('final_output["relevant_contexts"]')
|
319 |
+
st.write(final_output["relevant_contexts"])
|
320 |
+
|
321 |
+
st.subheader('final_output["final_response"]')
|
322 |
+
st.write(final_output["final_response"])
|