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
+
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("Download and Process 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 |
+
try:
|
| 136 |
+
vector_store = Chroma(
|
| 137 |
+
persist_directory=VECTOR_DB_PATH,
|
| 138 |
+
collection_name="deepseek_collection",
|
| 139 |
+
embedding_function=HuggingFaceEmbeddings(model_name="nomic-ai/modernbert-embed-base")
|
| 140 |
+
)
|
| 141 |
+
st.success("β
Vector store loaded successfully!")
|
| 142 |
+
return vector_store
|
| 143 |
+
except Exception as e:
|
| 144 |
+
st.error(f"β Failed to load vector store: {e}")
|
| 145 |
+
return None # Return None if there's an error
|
| 146 |
+
|
| 147 |
+
if st.session_state.chunked and not st.session_state.vector_created:
|
| 148 |
+
with st.spinner("Creating vector store..."):
|
| 149 |
+
try:
|
| 150 |
+
if st.session_state.vector_store is None: # Prevent unnecessary reloading
|
| 151 |
+
st.session_state.vector_store = load_vector_store()
|
| 152 |
+
|
| 153 |
+
if len(st.session_state.vector_store.get()["documents"]) == 0: # Prevent duplicate insertions
|
| 154 |
+
st.session_state.vector_store.add_documents(st.session_state.documents)
|
| 155 |
+
|
| 156 |
+
num_documents = len(st.session_state.vector_store.get()["documents"])
|
| 157 |
+
st.session_state.vector_created = True
|
| 158 |
+
st.success(f"β
**Vector Store Created!** Total documents stored: {num_documents}")
|
| 159 |
+
except Exception as e:
|
| 160 |
+
st.error(f"β Error creating vector store: {e}")
|
| 161 |
+
|
| 162 |
+
# Debugging Logs
|
| 163 |
+
st.write("π **PDF Loaded:**", st.session_state.pdf_loaded)
|
| 164 |
+
st.write("πΉ **Chunked:**", st.session_state.chunked)
|
| 165 |
+
st.write("π **Vector Store Created:**", st.session_state.vector_created)
|
| 166 |
+
|
| 167 |
+
|
| 168 |
+
# ----------------- Query Input -----------------
|
| 169 |
+
query = st.text_input("π Ask a question about the document:")
|
| 170 |
+
if query:
|
| 171 |
+
with st.spinner("π Retrieving relevant context..."):
|
| 172 |
+
if st.session_state.vector_store is None:
|
| 173 |
+
st.error("β Vector store is not initialized. Ensure document processing and chunking are completed.")
|
| 174 |
+
else:
|
| 175 |
+
retriever = st.session_state.vector_store.as_retriever(search_type="similarity", search_kwargs={"k": 5})
|
| 176 |
+
|
| 177 |
+
contexts = retriever.invoke(query)
|
| 178 |
+
# Debugging: Check what was retrieved
|
| 179 |
+
st.write("Retrieved Contexts:", contexts)
|
| 180 |
+
st.write("Number of Contexts:", len(contexts))
|
| 181 |
+
|
| 182 |
+
context = [d.page_content for d in contexts]
|
| 183 |
+
# Debugging: Check extracted context
|
| 184 |
+
st.write("Extracted Context (page_content):", context)
|
| 185 |
+
st.write("Number of Extracted Contexts:", len(context))
|
| 186 |
+
|
| 187 |
+
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.
|
| 188 |
+
Analyze the provided QUERY AND CONTEXT to determine if each Ccontent in the CONTEXT LIST contains Relevant information to answer the QUERY.
|
| 189 |
+
|
| 190 |
+
Guidelines:
|
| 191 |
+
1. The content must not introduce new information beyond what's provided in the QUERY.
|
| 192 |
+
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).
|
| 193 |
+
3. Be vigilant for subtle misattributions or conflations of information, even if the date or other details are correct.
|
| 194 |
+
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.
|
| 195 |
+
|
| 196 |
+
Analyze the text thoroughly and assign a relevancy score 0 or 1 where:
|
| 197 |
+
- 0: The content has all the necessary information to answer the QUERY
|
| 198 |
+
- 1: The content does not has the necessary information to answer the QUERY
|
| 199 |
+
|
| 200 |
+
```
|
| 201 |
+
EXAMPLE:
|
| 202 |
+
INPUT (for context only, not to be used for faithfulness evaluation):
|
| 203 |
+
What is the capital of France?
|
| 204 |
+
|
| 205 |
+
CONTEXT:
|
| 206 |
+
['France is a country in Western Europe. Its capital is Paris, which is known for landmarks like the Eiffel Tower.',
|
| 207 |
+
'Mr. Naveen patnaik has been the chief minister of Odisha for consequetive 5 terms']
|
| 208 |
+
|
| 209 |
+
OUTPUT:
|
| 210 |
+
The Context has sufficient information to answer the query.
|
| 211 |
+
|
| 212 |
+
RESPONSE:
|
| 213 |
+
{{"score":0}}
|
| 214 |
+
```
|
| 215 |
+
|
| 216 |
+
CONTENT LIST:
|
| 217 |
+
{context}
|
| 218 |
+
|
| 219 |
+
QUERY:
|
| 220 |
+
{retriever_query}
|
| 221 |
+
Provide your verdict in JSON format with a single key 'score' and no preamble or explanation:
|
| 222 |
+
[{{"content:1,"score": <your score either 0 or 1>,"Reasoning":<why you have chose the score as 0 or 1>}},
|
| 223 |
+
{{"content:2,"score": <your score either 0 or 1>,"Reasoning":<why you have chose the score as 0 or 1>}},
|
| 224 |
+
...]
|
| 225 |
+
"""
|
| 226 |
+
|
| 227 |
+
context_relevancy_checker_prompt = PromptTemplate(input_variables=["retriever_query","context"],template=relevancy_prompt)
|
| 228 |
+
|
| 229 |
+
relevant_prompt = PromptTemplate(
|
| 230 |
+
input_variables=["relevancy_response"],
|
| 231 |
+
template="""
|
| 232 |
+
Your main task is to analyze the json structure as a part of the Relevancy Response.
|
| 233 |
+
Review the Relevancy Response and do the following:-
|
| 234 |
+
(1) Look at the Json Structure content
|
| 235 |
+
(2) Analyze the 'score' key in the Json Structure content.
|
| 236 |
+
(3) pick the value of 'content' key against those 'score' key value which has 0.
|
| 237 |
+
|
| 238 |
+
Relevancy Response:
|
| 239 |
+
{relevancy_response}
|
| 240 |
+
|
| 241 |
+
Provide your verdict in JSON format with a single key 'content number' and no preamble or explanation:
|
| 242 |
+
[{{"content":<content number>}}]
|
| 243 |
+
"""
|
| 244 |
+
)
|
| 245 |
+
|
| 246 |
+
context_prompt = PromptTemplate(
|
| 247 |
+
input_variables=["context_number"],
|
| 248 |
+
template="""
|
| 249 |
+
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:-
|
| 250 |
+
(1) Look at the output from the Relevant Context Picker Agent.
|
| 251 |
+
(2) Analyze the 'content' key in the Json Structure format({{"content":<<content_number>>}}).
|
| 252 |
+
(3) Retrieve the value of 'content' key and pick up the context corresponding to that element from the Content List provided.
|
| 253 |
+
(4) Pass the retrieved context for each corresponing element number referred in the 'Context Number Response'
|
| 254 |
+
|
| 255 |
+
Context Number Response:
|
| 256 |
+
{context_number}
|
| 257 |
+
|
| 258 |
+
Content List:
|
| 259 |
+
{context}
|
| 260 |
+
|
| 261 |
+
Provide your verdict in JSON format with a two key 'relevant_content' and 'context_number' no preamble or explanation:
|
| 262 |
+
[{{"context_number":<content1>,"relevant_content":<content corresponing to that element 1 in the Content List>}},
|
| 263 |
+
{{"context_number":<content4>,"relevant_content":<content corresponing to that element 4 in the Content List>}},
|
| 264 |
+
...
|
| 265 |
+
]
|
| 266 |
+
"""
|
| 267 |
+
)
|
| 268 |
+
|
| 269 |
+
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
|
| 270 |
+
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'.
|
| 271 |
+
|
| 272 |
+
QUERY:
|
| 273 |
+
{query}
|
| 274 |
+
|
| 275 |
+
CONTEXT
|
| 276 |
+
{context}
|
| 277 |
+
|
| 278 |
+
ANSWER:
|
| 279 |
+
"""
|
| 280 |
+
|
| 281 |
+
context_relevancy_evaluation_chain = LLMChain(llm=llm_judge, prompt=context_relevancy_checker_prompt, output_key="relevancy_response")
|
| 282 |
+
|
| 283 |
+
response_crisis = context_relevancy_evaluation_chain.invoke({"context":context,"retriever_query":query})
|
| 284 |
+
|
| 285 |
+
pick_relevant_context_chain = LLMChain(llm=llm_judge, prompt=relevant_prompt, output_key="context_number")
|
| 286 |
+
|
| 287 |
+
relevant_response = pick_relevant_context_chain.invoke({"relevancy_response":response_crisis['relevancy_response']})
|
| 288 |
+
|
| 289 |
+
relevant_contexts_chain = LLMChain(llm=llm_judge, prompt=context_prompt, output_key="relevant_contexts")
|
| 290 |
+
|
| 291 |
+
contexts = relevant_contexts_chain.invoke({"context_number":relevant_response['context_number'],"context":context})
|
| 292 |
+
|
| 293 |
+
final_prompt = PromptTemplate(input_variables=["query","context"],template=rag_prompt)
|
| 294 |
+
|
| 295 |
+
response_chain = LLMChain(llm=rag_llm,prompt=final_prompt,output_key="final_response")
|
| 296 |
+
|
| 297 |
+
response = response_chain.invoke({"query":query,"context":contexts['relevant_contexts']})
|
| 298 |
+
|
| 299 |
+
# Orchestrate using SequentialChain
|
| 300 |
+
context_management_chain = SequentialChain(
|
| 301 |
+
chains=[context_relevancy_evaluation_chain ,pick_relevant_context_chain, relevant_contexts_chain,response_chain],
|
| 302 |
+
input_variables=["context","retriever_query","query"],
|
| 303 |
+
output_variables=["relevancy_response", "context_number","relevant_contexts","final_response"]
|
| 304 |
+
)
|
| 305 |
+
|
| 306 |
+
final_output = context_management_chain({"context":context,"retriever_query":query,"query":query})
|
| 307 |
+
|
| 308 |
+
st.subheader('final_output["relevancy_response"]')
|
| 309 |
+
st.json(final_output["relevancy_response"] )
|
| 310 |
+
|
| 311 |
+
st.subheader('final_output["context_number"]')
|
| 312 |
+
st.json(final_output["context_number"])
|
| 313 |
+
|
| 314 |
+
st.subheader('final_output["relevant_contexts"]')
|
| 315 |
+
st.json(final_output["relevant_contexts"])
|
| 316 |
+
|
| 317 |
+
st.subheader('final_output["final_response"]')
|
| 318 |
+
st.json(final_output["final_response"])
|