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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 prompts import rag_prompt, relevancy_prompt, relevant_context_picker_prompt, response_synth
|
| 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:", ["Upload a PDF file", "Enter a PDF URL"], 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:")
|
| 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 |
+
# ----------------- Run Individual Chains Explicitly -----------------
|
| 161 |
+
|
| 162 |
+
context_relevancy_checker_prompt = PromptTemplate(input_variables=["retriever_query","context"],template=relevancy_prompt)
|
| 163 |
+
|
| 164 |
+
if "context_relevancy_evaluation_chain" in st.session_state:
|
| 165 |
+
del st.session_state["context_relevancy_evaluation_chain"]
|
| 166 |
+
|
| 167 |
+
|
| 168 |
+
|
| 169 |
+
context_relevancy_evaluation_chain = LLMChain( llm=llm_judge, prompt=PromptTemplate(input_variables=["retriever_query","context"],template=relevancy_prompt), output_key="relevancy_response" )
|
| 170 |
+
|
| 171 |
+
st.write("π Debugging Expected Keys for `context_relevancy_evaluation_chain`:")
|
| 172 |
+
st.write(context_relevancy_evaluation_chain.input_keys)
|
| 173 |
+
|
| 174 |
+
response_crisis = context_relevancy_evaluation_chain.invoke({"context":context,"retriever_query":query})
|
| 175 |
+
|
| 176 |
+
relevant_prompt = relevant_prompt = PromptTemplate(input_variables=["relevancy_response"], template= relevant_context_picker_prompt)
|
| 177 |
+
|
| 178 |
+
pick_relevant_context_chain = LLMChain(llm=llm_judge, prompt=relevant_prompt, output_key="context_number")
|
| 179 |
+
|
| 180 |
+
relevant_response = pick_relevant_context_chain.invoke({"relevancy_response":response_crisis['relevancy_response']})
|
| 181 |
+
|
| 182 |
+
context_prompt = PromptTemplate(input_variables=["context_number"],template=response_synth)
|
| 183 |
+
|
| 184 |
+
relevant_contexts_chain = LLMChain(llm=llm_judge, prompt=context_prompt, output_key="relevant_contexts")
|
| 185 |
+
|
| 186 |
+
contexts = relevant_contexts_chain.invoke({"context_number":relevant_response['context_number'],"context":context})
|
| 187 |
+
|
| 188 |
+
#temp
|
| 189 |
+
st.subheader("Relevant Contexts")
|
| 190 |
+
st.json(contexts['relevant_contexts'])
|
| 191 |
+
|
| 192 |
+
response_chain = LLMChain(llm=rag_llm,prompt=final_prompt,output_key="final_response")
|
| 193 |
+
|
| 194 |
+
|
| 195 |
+
#temp
|
| 196 |
+
st.subheader("Response Chain")
|
| 197 |
+
st.json(response_chain)
|
| 198 |
+
|
| 199 |
+
#response = chain.invoke({"query":query,"context":contexts['relevant_contexts']})
|
| 200 |
+
|
| 201 |
+
#temp
|
| 202 |
+
#st.subheader("blah response")
|
| 203 |
+
#st.json(response.content)
|
| 204 |
+
|
| 205 |
+
# Orchestrate using SequentialChain
|
| 206 |
+
context_management_chain = SequentialChain(
|
| 207 |
+
chains=[context_relevancy_evaluation_chain ,pick_relevant_context_chain, relevant_contexts_chain,response_chain],
|
| 208 |
+
input_variables=["context","retriever_query","query"],
|
| 209 |
+
output_variables=["relevancy_response", "context_number","relevant_contexts","final_response"]
|
| 210 |
+
)
|
| 211 |
+
final_output = context_management_chain({"context":context,"retriever_query":query,"query":query})
|
| 212 |
+
st.subheader("Final Output from Context Management chain")
|
| 213 |
+
st.json(final_output)
|
| 214 |
+
|
| 215 |
+
st.subheader("Context of Final Output from Context Management chain")
|
| 216 |
+
st.json(final_output['context'])
|
| 217 |
+
|
| 218 |
+
st.header("Relevancy Response")
|
| 219 |
+
st.json(final_output['relevancy_response'])
|
| 220 |
+
|
| 221 |
+
st.subheader("Relevant Context")
|
| 222 |
+
st.json(final_output['relevant_contexts'])
|
| 223 |
+
|
| 224 |
+
response = chain.invoke({"query":query,"context":final_output['relevant_contexts']})
|
| 225 |
+
|
| 226 |
+
st.subheader("Final Response")
|
| 227 |
+
st.json(response.content)
|
| 228 |
+
|
| 229 |
+
# ----------------- Display All Outputs -----------------
|
| 230 |
+
#st.subheader("response_crisis")
|
| 231 |
+
#st.json((response_crisis))
|
| 232 |
+
|
| 233 |
+
#st.subheader("response_crisis['relevancy_response']")
|
| 234 |
+
#st.json((response_crisis['relevancy_response']))
|
| 235 |
+
|
| 236 |
+
|
| 237 |
+
|
| 238 |
+
#st.markdown("### Context Relevancy Evaluation")
|
| 239 |
+
#st.json(response_crisis["relevancy_response"])
|
| 240 |
+
|
| 241 |
+
#st.markdown("### Picked Relevant Contexts")
|
| 242 |
+
#st.json(relevant_response["context_number"])
|
| 243 |
+
|
| 244 |
+
#st.markdown("### Extracted Relevant Contexts")
|
| 245 |
+
#st.json(contexts["relevant_contexts"])
|
| 246 |
+
|
| 247 |
+
#st.subheader("context_relevancy_evaluation_chain Statement")
|
| 248 |
+
#st.json(final_response["relevancy_response"])
|
| 249 |
+
|
| 250 |
+
#st.subheader("pick_relevant_context_chain Statement")
|
| 251 |
+
#st.json(final_response["context_number"])
|
| 252 |
+
|
| 253 |
+
#st.subheader("relevant_contexts_chain Statement")
|
| 254 |
+
#st.json(final_response["relevant_contexts"])
|
| 255 |
+
|
| 256 |
+
#st.subheader("RAG Response Statement")
|
| 257 |
+
#st.json(final_response["final_response"])
|