DrishtiSharma commited on
Commit
fb5706e
Β·
verified Β·
1 Parent(s): f0de8dd

Create content_key_fixed_button_and_enter_support.py

Browse files
lab/content_key_fixed_button_and_enter_support.py ADDED
@@ -0,0 +1,304 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+ # Function to download and process the PDF
47
+ def download_pdf():
48
+ if st.session_state.pdf_url and not st.session_state.pdf_path:
49
+ with st.spinner("Downloading PDF..."):
50
+ try:
51
+ response = requests.get(st.session_state.pdf_url)
52
+ if response.status_code == 200:
53
+ st.session_state.pdf_path = "temp.pdf"
54
+ with open(st.session_state.pdf_path, "wb") as f:
55
+ f.write(response.content)
56
+
57
+ # Reset processing state
58
+ st.session_state.pdf_loaded = False
59
+ st.session_state.chunked = False
60
+ st.session_state.vector_created = False
61
+
62
+ st.success("βœ… PDF Downloaded Successfully!")
63
+ else:
64
+ st.error("❌ Failed to download PDF. Check the URL.")
65
+ except Exception as e:
66
+ st.error(f"❌ Error downloading PDF: {e}")
67
+
68
+ if pdf_source == "Upload a PDF file":
69
+ uploaded_file = st.file_uploader("Upload your PDF file", type="pdf")
70
+ if uploaded_file:
71
+ st.session_state.pdf_path = "temp.pdf"
72
+ with open(st.session_state.pdf_path, "wb") as f:
73
+ f.write(uploaded_file.getbuffer())
74
+ st.session_state.pdf_loaded = False
75
+ st.session_state.chunked = False
76
+ st.session_state.vector_created = False
77
+
78
+ elif pdf_source == "Enter a PDF URL":
79
+ # βœ… Text input with Enter support
80
+ st.text_input("Enter PDF URL:", value="https://arxiv.org/pdf/2406.06998", key="pdf_url", on_change=download_pdf)
81
+
82
+ # βœ… Button support
83
+ if st.button("Load PDF"):
84
+ download_pdf()
85
+
86
+
87
+ # Step 2: Load & Process PDF (Only Once)
88
+ if st.session_state.pdf_path and not st.session_state.pdf_loaded:
89
+ with st.spinner("Loading PDF..."):
90
+ try:
91
+ loader = PDFPlumberLoader(st.session_state.pdf_path)
92
+ docs = loader.load()
93
+ st.session_state.documents = docs
94
+ st.session_state.pdf_loaded = True
95
+ st.success(f"βœ… **PDF Loaded!** Total Pages: {len(docs)}")
96
+ except Exception as e:
97
+ st.error(f"❌ Error processing PDF: {e}")
98
+
99
+ # Load Cached Chunks if Available
100
+ def load_chunks():
101
+ if os.path.exists(CHUNKS_FILE):
102
+ with open(CHUNKS_FILE, "rb") as f:
103
+ return pickle.load(f)
104
+ return None
105
+
106
+ if not st.session_state.chunked: # Ensure chunking only happens once
107
+ cached_chunks = load_chunks()
108
+ if cached_chunks:
109
+ st.session_state.documents = cached_chunks
110
+ st.session_state.chunked = True
111
+
112
+ # Step 3: Chunking (Only Happens Once)
113
+ if st.session_state.pdf_loaded and not st.session_state.chunked:
114
+ with st.spinner("Chunking the document..."):
115
+ try:
116
+ model_name = "nomic-ai/modernbert-embed-base"
117
+ embedding_model = HuggingFaceEmbeddings(model_name=model_name, model_kwargs={'device': 'cpu'})
118
+ text_splitter = SemanticChunker(embedding_model)
119
+
120
+ if st.session_state.documents:
121
+ documents = text_splitter.split_documents(st.session_state.documents)
122
+ st.session_state.documents = documents
123
+ st.session_state.chunked = True
124
+
125
+ # Save chunks for persistence
126
+ with open(CHUNKS_FILE, "wb") as f:
127
+ pickle.dump(documents, f)
128
+
129
+ st.success(f"βœ… **Document Chunked!** Total Chunks: {len(documents)}")
130
+ except Exception as e:
131
+ st.error(f"❌ Error chunking document: {e}")
132
+
133
+ # Step 4: Setup Vectorstore
134
+ def load_vector_store():
135
+ return Chroma(persist_directory=VECTOR_DB_PATH, collection_name="deepseek_collection", embedding_function=HuggingFaceEmbeddings(model_name="nomic-ai/modernbert-embed-base"))
136
+
137
+ if st.session_state.chunked and not st.session_state.vector_created:
138
+ with st.spinner("Creating vector store..."):
139
+ try:
140
+ if st.session_state.vector_store is None: # Prevent unnecessary reloading
141
+ st.session_state.vector_store = load_vector_store()
142
+
143
+ if len(st.session_state.vector_store.get()["documents"]) == 0: # Prevent duplicate insertions
144
+ st.session_state.vector_store.add_documents(st.session_state.documents)
145
+
146
+ num_documents = len(st.session_state.vector_store.get()["documents"])
147
+ st.session_state.vector_created = True
148
+ st.success(f"βœ… **Vector Store Created!** Total documents stored: {num_documents}")
149
+ except Exception as e:
150
+ st.error(f"❌ Error creating vector store: {e}")
151
+
152
+ # Debugging Logs
153
+ st.write("πŸ“„ **PDF Loaded:**", st.session_state.pdf_loaded)
154
+ st.write("πŸ”Ή **Chunked:**", st.session_state.chunked)
155
+ st.write("πŸ“‚ **Vector Store Created:**", st.session_state.vector_created)
156
+
157
+
158
+ # ----------------- Query Input -----------------
159
+ query = st.text_input("πŸ” Ask a question about the document:")
160
+ if query:
161
+ with st.spinner("πŸ”„ Retrieving relevant context..."):
162
+ retriever = st.session_state.vector_store.as_retriever(search_type="similarity", search_kwargs={"k": 5})
163
+ contexts = retriever.invoke(query)
164
+ # Debugging: Check what was retrieved
165
+ st.write("Retrieved Contexts:", contexts)
166
+ st.write("Number of Contexts:", len(contexts))
167
+
168
+ context = [d.page_content for d in contexts]
169
+ # Debugging: Check extracted context
170
+ st.write("Extracted Context (page_content):", context)
171
+ st.write("Number of Extracted Contexts:", len(context))
172
+
173
+ 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.
174
+ Analyze the provided QUERY AND CONTEXT to determine if each Ccontent in the CONTEXT LIST contains Relevant information to answer the QUERY.
175
+
176
+ Guidelines:
177
+ 1. The content must not introduce new information beyond what's provided in the QUERY.
178
+ 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).
179
+ 3. Be vigilant for subtle misattributions or conflations of information, even if the date or other details are correct.
180
+ 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.
181
+
182
+ Analyze the text thoroughly and assign a relevancy score 0 or 1 where:
183
+ - 0: The content has all the necessary information to answer the QUERY
184
+ - 1: The content does not has the necessary information to answer the QUERY
185
+
186
+ ```
187
+ EXAMPLE:
188
+ INPUT (for context only, not to be used for faithfulness evaluation):
189
+ What is the capital of France?
190
+
191
+ CONTEXT:
192
+ ['France is a country in Western Europe. Its capital is Paris, which is known for landmarks like the Eiffel Tower.',
193
+ 'Mr. Naveen patnaik has been the chief minister of Odisha for consequetive 5 terms']
194
+
195
+ OUTPUT:
196
+ The Context has sufficient information to answer the query.
197
+
198
+ RESPONSE:
199
+ {{"score":0}}
200
+ ```
201
+
202
+ CONTENT LIST:
203
+ {context}
204
+
205
+ QUERY:
206
+ {retriever_query}
207
+ Provide your verdict in JSON format with a single key 'score' and no preamble or explanation:
208
+ [{{"content:1,"score": <your score either 0 or 1>,"Reasoning":<why you have chose the score as 0 or 1>}},
209
+ {{"content:2,"score": <your score either 0 or 1>,"Reasoning":<why you have chose the score as 0 or 1>}},
210
+ ...]
211
+ """
212
+
213
+ context_relevancy_checker_prompt = PromptTemplate(input_variables=["retriever_query","context"],template=relevancy_prompt)
214
+
215
+ relevant_prompt = PromptTemplate(
216
+ input_variables=["relevancy_response"],
217
+ template="""
218
+ Your main task is to analyze the json structure as a part of the Relevancy Response.
219
+ Review the Relevancy Response and do the following:-
220
+ (1) Look at the Json Structure content
221
+ (2) Analyze the 'score' key in the Json Structure content.
222
+ (3) pick the value of 'content' key against those 'score' key value which has 0.
223
+
224
+ Relevancy Response:
225
+ {relevancy_response}
226
+
227
+ Provide your verdict in JSON format with a single key 'content number' and no preamble or explanation:
228
+ [{{"content":<content number>}}]
229
+ """
230
+ )
231
+
232
+ context_prompt = PromptTemplate(
233
+ input_variables=["context_number"],
234
+ template="""
235
+ You 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:-
236
+ (1) Look at the output from the Relevant Context Picker Agent.
237
+ (2) Analyze the 'content' key in the Json Structure format({{"content":<<content_number>>}}).
238
+ (3) Retrieve the value of 'content' key and pick up the context corresponding to that element from the Content List provided.
239
+ (4) Pass the retrieved context for each corresponing element number referred in the 'Context Number Response'
240
+
241
+ Context Number Response:
242
+ {context_number}
243
+
244
+ Content List:
245
+ {context}
246
+
247
+ Provide your verdict in JSON format with a two key 'relevant_content' and 'context_number' no preamble or explanation:
248
+ [{{"context_number":<content1>,"relevant_content":<content corresponing to that element 1 in the Content List>}},
249
+ {{"context_number":<content4>,"relevant_content":<content corresponing to that element 4 in the Content List>}},
250
+ ...
251
+ ]
252
+ """
253
+ )
254
+
255
+ rag_prompt = """ You are ahelpful assistant very profiient in formulating clear and meaningful answers from the context provided.Based on the CONTEXT Provided ,Please formulate
256
+ 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'.
257
+
258
+ QUERY:
259
+ {query}
260
+
261
+ CONTEXT
262
+ {context}
263
+
264
+ ANSWER:
265
+ """
266
+
267
+ context_relevancy_evaluation_chain = LLMChain(llm=llm_judge, prompt=context_relevancy_checker_prompt, output_key="relevancy_response")
268
+
269
+ response_crisis = context_relevancy_evaluation_chain.invoke({"context":context,"retriever_query":query})
270
+
271
+ pick_relevant_context_chain = LLMChain(llm=llm_judge, prompt=relevant_prompt, output_key="context_number")
272
+
273
+ relevant_response = pick_relevant_context_chain.invoke({"relevancy_response":response_crisis['relevancy_response']})
274
+
275
+ relevant_contexts_chain = LLMChain(llm=llm_judge, prompt=context_prompt, output_key="relevant_contexts")
276
+
277
+ contexts = relevant_contexts_chain.invoke({"context_number":relevant_response['context_number'],"context":context})
278
+
279
+ final_prompt = PromptTemplate(input_variables=["query","context"],template=rag_prompt)
280
+
281
+ response_chain = LLMChain(llm=rag_llm,prompt=final_prompt,output_key="final_response")
282
+
283
+ response = response_chain.invoke({"query":query,"context":contexts['relevant_contexts']})
284
+
285
+ # Orchestrate using SequentialChain
286
+ context_management_chain = SequentialChain(
287
+ chains=[context_relevancy_evaluation_chain ,pick_relevant_context_chain, relevant_contexts_chain,response_chain],
288
+ input_variables=["context","retriever_query","query"],
289
+ output_variables=["relevancy_response", "context_number","relevant_contexts","final_response"]
290
+ )
291
+
292
+ final_output = context_management_chain({"context":context,"retriever_query":query,"query":query})
293
+
294
+ st.subheader('final_output["relevancy_response"]')
295
+ st.json(final_output["relevancy_response"] )
296
+
297
+ st.subheader('final_output["context_number"]')
298
+ st.json(final_output["context_number"])
299
+
300
+ st.subheader('final_output["relevant_contexts"]')
301
+ st.json(final_output["relevant_contexts"])
302
+
303
+ st.subheader('final_output["final_response"]')
304
+ st.json(final_output["final_response"])