DrishtiSharma commited on
Commit
297a3b3
Β·
verified Β·
1 Parent(s): caff312

Create content_key_issue_fixed.py

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