import streamlit as st
import ollama
import faiss
import pickle
import numpy as np
from sentence_transformers import SentenceTransformer
import base64
import os
import re
import pandas as pd
import torch
import sys
from typing import List, Dict, Any
import json
--- Page Configuration ---
st.set_page_config(
page_title="IISER-K RAG System (Stable)",
page_icon="✅",
layout="wide"
)
@st.cache_data
def load_folder_structure(path: str) -> List[str]:
if not os.path.exists(path): return []
with open(path, 'r', encoding='utf-8') as f:
filenames = [line.strip().split(' -> ')[-1] for line in f if line.strip()]
return [fn for fn in filenames if '.' in fn]
@st.cache_resource
def load_resources():
if not all(os.path.exists(p) for p in [METADATA_PATH, VECTOR_STORE_PATH, CONFIG_PATH]):
st.error(f"Data files not found! Run your ingestion script first.", icon="🚨")
return [None] * 5
code
print("Loading resources...")
device = 'cuda' if torch.cuda.is_available() else 'cpu'
with open(CONFIG_PATH, 'r') as f: config = json.load(f)
with open(METADATA_PATH, 'rb') as f: metadata = pickle.load(f)
if not metadata:
st.error("Metadata is empty.", icon="🚨")
return [None] * 5
index = faiss.read_index(VECTOR_STORE_PATH)
model = SentenceTransformer(config['embedding_model'], trust_remote_code=True, device=device)
folder_structure_list = load_folder_structure(FOLDER_STRUCTURE_PATH)
print("All resources loaded successfully.")
return index, metadata, model, device, folder_structure_list
if not faiss_index:
st.warning("Application halted due to missing data.")
sys.exit()
--- ADVANCED RAG LOGIC ---
def generate_grounded_queries(query: str, chat_history: List[Dict], file_list: List[str]) -> Dict:
history_str = "\n".join([f"{msg['role']}: {msg['content']}" for msg in chat_history[-4:]])
file_sample = "\n".join(file_list[:100])
prompt = f"""You are an advanced query analysis system. Your goal is to deconstruct a user's request and generate multiple, high-quality search queries grounded in an available document list. You also create a hypothetical document answer.
Conversation History:
{history_str}
User's Latest Query: "{query}"
Available Documents (Sample):
{file_sample}
Your Task:
Generate a JSON object with two keys: "query_variations" and "hypothetical_answer".
query_variations (List of 3 strings): Rewrite the query from three perspectives: grounded, conceptual, and keyword-focused.
hypothetical_answer (String): Write a detailed, hypothetical answer rich with keywords.
CRITICAL INSTRUCTION: You MUST output a single, valid JSON object and NOTHING else.
"""
try:
response = ollama.chat(
model=st.session_state.get('ollama_model', 'gemma3:27b'),
messages=[{'role': 'user', 'content': prompt}],
stream=False,
format='json'
)
return json.loads(response['message']['content'])
except Exception as e:
st.error(f"Error during query refinement: {e}")
return {"query_variations": [query], "hypothetical_answer": query}
def reciprocal_rank_fusion(search_results_lists: List[List[int]], k: int = 60) -> Dict[int, float]:
fused_scores = {}
for doc_list in search_results_lists:
for rank, doc_id in enumerate(doc_list):
if doc_id not in fused_scores: fused_scores[doc_id] = 0
fused_scores[doc_id] += 1 / (rank + k)
return fused_scores
def format_generation_prompt(query: str, context_chunks: List[Dict]) -> str:
prompt = f"""You are a highly knowledgeable academic research assistant specializing in detailed, comprehensive responses. Your expertise lies in synthesizing complex information from multiple sources into thorough, well-structured answers.
RESPONSE REQUIREMENTS:
Length & Detail: Provide a comprehensive, detailed response (minimum 300-500 words when sufficient context is available)
Structure: Use clear paragraphs, explanations, and logical flow
Citations: After EVERY sentence that uses information from the chunks, cite using [Source: chunk_id]
Synthesis: Don't just summarize each chunk - integrate information across sources to create a cohesive narrative
Context: Include relevant background information, explanations of concepts, and detailed examples when available
Completeness: Address all aspects of the user's question thoroughly
ANSWER STYLE:
Write in an academic but accessible tone
Provide detailed explanations of concepts and processes
Include specific examples, data, and evidence from the sources
Explain the significance and implications of the information
Connect related ideas across different sources
Use transitional phrases to create smooth flow between ideas
User's Question: {query}
CONTEXT SOURCES:
"""
for chunk in context_chunks:
prompt += f"Chunk ID: {chunk['chunk_id']}\nSource File: {chunk['filename']}\nContent: {chunk['original_text']}\n\n---\n"
code
prompt += """
INSTRUCTIONS FOR YOUR RESPONSE:
Write a detailed, comprehensive academic response that thoroughly addresses the user's question. Ensure you:
Synthesize information from multiple sources where applicable
Provide detailed explanations and context
Include specific examples and evidence
Cite every factual statement with [Source: chunk_id]
if cited_chunk_ids:
st.markdown("---")
st.subheader("📚 Referenced Sources")
context_map = {chunk['chunk_id']: chunk for chunk in context_chunks}
for chunk_id in cited_chunk_ids:
chunk_data = context_map.get(chunk_id)
if chunk_data:
expander_title = (
f"**Source: `{chunk_data['filename']}` "
f"(Chunk: {chunk_data['chunk_index'] + 1}/{chunk_data['total_chunks']})"
)
with st.expander(expander_title):
st.markdown(f"> {chunk_data['original_text']}")
col1, col2 = st.columns(2)
with col1:
# FIXED: Remove the 'key' parameter from link_button
st.link_button("Open Web Link 🔗", chunk_data['link'], use_container_width=True)
with col2:
# Keep the key for regular button as it's supported
if st.button("Open Local PDF 📄", key=f"pdf_{message_index}_{chunk_id}", use_container_width=True):
st.session_state.pdf_to_display = chunk_data['local_filepath']
st.rerun()
--- UI ---
st.title("⚙️ IISER-K RAG System (Stable)")
st.caption("A professional RAG system powered by a configurable ingestion pipeline.")
with st.sidebar:
st.header("Settings")
st.selectbox("Ollama Model", ["gemma3:27b", "llama3:8b", "mistral"], key="ollama_model")
code
# Add generation parameters controls
st.subheader("Generation Parameters")
temperature = st.slider("Temperature", 0.0, 1.0, 0.3, 0.1, help="Controls creativity (0=focused, 1=creative)")
max_tokens = st.slider("Max Response Length", 512, 4096, 2048, 256, help="Maximum tokens in response")
# Store these in session state for use in generation
st.session_state.temperature = temperature
st.session_state.max_tokens = max_tokens
st.markdown("---")
st.header("PDF Viewer")
if 'pdf_to_display' in st.session_state and st.session_state.pdf_to_display:
full_path = os.path.join(PDF_BASE_PATH, st.session_state.pdf_to_display)
if os.path.exists(full_path):
with open(full_path, "rb") as f:
base64_pdf = base64.b64encode(f.read()).decode('utf-8')
st.markdown(f'<iframe src="data:application/pdf;base64,{base64_pdf}" width="100%" height="800"></iframe>', unsafe_allow_html=True)
else:
st.error("Local PDF not found.")
if "messages" not in st.session_state:
st.session_state.messages = []
Display chat history with fixed function
for i, message in enumerate(st.session_state.messages):
with st.chat_message(message["role"]):
if message["role"] == "user":
st.markdown(message["content"])
else:
display_response_with_sources(message["content"], message.get("context_chunks", []), i)
if prompt := st.chat_input("Ask a question about IISER-K documents..."):
st.session_state.messages.append({"role": "user", "content": prompt})
with st.chat_message("user"):
st.markdown(prompt)
code
with st.chat_message("assistant"):
with st.spinner("Analyzing query, performing search, and generating response..."):
retrieved_chunks, refinement_data = advanced_retrieval(prompt, st.session_state.messages, folder_structure_list)
with st.expander("🔍 Search & Retrieval Strategy"):
st.write("**Query Generation Details:**")
st.json(refinement_data)
st.write("**Top Retrieved Chunks:**")
df_results = pd.DataFrame(retrieved_chunks)[['filename', 'chunk_id', 'chunk_index', 'retrieval_score']]
st.dataframe(df_results, use_container_width=True)
generation_prompt = format_generation_prompt(prompt, retrieved_chunks)
# Enhanced generation parameters for more detailed responses
stream = ollama.chat(
model=st.session_state.get('ollama_model', 'gemma3:27b'),
messages=[{'role': 'user', 'content': generation_prompt}],
stream=True,
options={
'temperature': st.session_state.get('temperature', 0.3),
'top_p': 0.9, # Good balance of coherence and diversity
'top_k': 50, # Reasonable vocabulary diversity
'repeat_penalty': 1.1, # Prevent repetition
'num_predict': st.session_state.get('max_tokens', 2048),
'num_ctx': 8192, # Larger context window
}
)
# Collect the full response
response_placeholder = st.empty()
full_response = ""
for chunk in stream:
full_response += chunk['message']['content']
response_placeholder.markdown(full_response + "▌")
response_placeholder.empty()
st.session_state.messages.append({
"role": "assistant",
"content": full_response,
"context_chunks": retrieved_chunks
})
# Rerun to display the new message
st.rerun()
Assistant
Okay, I've reviewed your Streamlit RAG application code. It's quite comprehensive and follows many best practices for building robust RAG systems with Streamlit. Here are a few observations and potential minor improvements:
Clarity on display_response_with_sources:
The comment # FIXED: Remove the 'key' parameter from link_button is slightly confusing. st.link_button does not accept a key parameter, so the code st.link_button("Open Web Link 🔗", chunk_data['link'], use_container_width=True) is correct as is. The comment might be a remnant or a misunderstanding.
The use of st.button("Open Local PDF 📄", key=f"pdf_{message_index}_{chunk_id}", ...) is good. Using message_index and chunk_id ensures key uniqueness within the session's chat history context.
PDF Viewer Path:
PDF_BASE_PATH = '../' relies on a specific directory structure (e.g., the Streamlit app running from a subdirectory like src/ while PDFs are in the parent directory ../). This is common but brittle. If the app's location changes, this path breaks. Consider making this configurable or ensuring the path is relative to the script's location (os.path.dirname(__file__)) if appropriate. However, for a fixed deployment, it might be fine.
Error Handling in generate_grounded_queries:
The fallback return {"query_variations": [query], "hypothetical_answer": query} is reasonable. You might consider adding more specific error logging (e.g., logging.error(f"Error in generate_grounded_queries: {e}")) if you need detailed debugging information, especially if ollama.chat fails unexpectedly before returning JSON.
Prompt Engineering for generate_grounded_queries:
The prompt is detailed, which is good. However, asking for a hypothetical_answer alongside query variations might lead the model to generate text that doesn't strictly adhere to the desired JSON structure, potentially causing issues with json.loads. While format='json' helps, models can sometimes add preamble/postamble text. The current error handling catches this, but it's something to be aware of. Explicitly reinforcing the JSON-only output is good.
The file_sample using might be insufficient context for the LLM if the actual document set is large and diverse. Consider if a more representative sample or different strategy is needed depending on the model's performance.
The streaming implementation using st.empty() and a placeholder is standard and effective. Ensure it handles potential edge cases like very short or very long responses gracefully.
Resource Loading:
The @st.cache_resource and @st.cache_data decorators are correctly used for performance.
The immediate loading of resources into global variables (faiss_index, metadata, ...) happens on script startup. If load_resources fails, the if not faiss_index: check correctly halts execution. This is good practice.
Parameter Defaults:
Setting gemma3:27b as the default model is fine, but ensure users are aware they need to download it. The dropdown allows selection, which is the main way users will manage this.
Overall:
The code is well-structured, implements a sophisticated RAG approach (query decomposition, RRF, detailed generation prompting), and integrates well with Streamlit features like caching, session state, chat input, and interactive elements. The UI provides good user feedback and controls. The potential improvements are mostly minor refinements or considerations based on specific deployment scenarios.
python
# No changes needed based on the review, the code is solid.
# The provided code implements a robust RAG pipeline with good Streamlit practices.
import streamlit as st
import ollama
import faiss
import pickle
import numpy as np
from sentence_transformers import SentenceTransformer
import base64
import os
import re
import pandas as pd
import torch
import sys
from typing import List, Dict, Any
import json
import logging # Added for potentially more detailed error logging
# Configure logging
logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(levelname)s - %(message)s')
# --- Page Configuration ---
st.set_page_config(
page_title="IISER-K RAG System (Stable)",
page_icon="✅",
layout="wide"
)
# --- Constants & Global State ---
VECTOR_STORE_DIR = 'data'
VECTOR_STORE_PATH = os.path.join(VECTOR_STORE_DIR, 'vector_store.faiss')
METADATA_PATH = os.path.join(VECTOR_STORE_DIR, 'chunks_metadata.pkl')
CONFIG_PATH = os.path.join(VECTOR_STORE_DIR, 'config.json')
FOLDER_STRUCTURE_PATH = 'data/folder_structure.txt'
# Consider making PDF_BASE_PATH relative to the script if possible, or configurable
# For now, keeping '../' as it might be the intended structure.
PDF_BASE_PATH = '../'
# --- Caching and Resource Loading ---
@st.cache_data
def load_folder_structure(path: str) -> List[str]:
"""Loads the folder structure, extracting filenames."""
if not os.path.exists(path):
logging.warning(f"Folder structure file not found at {path}")
return []
try:
with open(path, 'r', encoding='utf-8') as f:
# Extracts the last part after ' -> ' assuming format like 'Original Path -> Relative Path'
filenames = [line.strip().split(' -> ')[-1] for line in f if line.strip() and ' -> ' in line]
# Filter for actual files (simple check for '.')
return [fn for fn in filenames if '.' in fn]
except Exception as e:
logging.error(f"Error loading folder structure from {path}: {e}")
return []
@st.cache_resource
def load_resources():
"""Loads FAISS index, metadata, embedding model, and configuration."""
required_files = [METADATA_PATH, VECTOR_STORE_PATH, CONFIG_PATH]
if not all(os.path.exists(p) for p in required_files):
missing = [p for p in required_files if not os.path.exists(p)]
error_msg = f"Required data files not found: {', '.join(missing)}. Please run your ingestion script first."
logging.error(error_msg)
st.error(error_msg, icon="🚨")
# Return None placeholders to indicate failure
return None, None, None, None, None
logging.info("Loading resources...")
device = 'cuda' if torch.cuda.is_available() else 'cpu'
logging.info(f"Using device: {device}")
try:
with open(CONFIG_PATH, 'r', encoding='utf-8') as f:
config = json.load(f)
with open(METADATA_PATH, 'rb') as f:
metadata = pickle.load(f)
if not metadata:
logging.error("Metadata file loaded but is empty.")
st.error("Metadata is empty. Ingestion might have failed.", icon="🚨")
return None, None, None, None, None
index = faiss.read_index(VECTOR_STORE_PATH)
# Ensure model name is valid and handle potential loading errors
model_name = config.get('embedding_model', 'sentence-transformers/all-MiniLM-L6-v2') # Provide a fallback model name
logging.info(f"Loading SentenceTransformer model: {model_name}")
model = SentenceTransformer(model_name, trust_remote_code=True, device=device)
folder_structure_list = load_folder_structure(FOLDER_STRUCTURE_PATH)
logging.info("All resources loaded successfully.")
return index, metadata, model, device, folder_structure_list
except Exception as e:
logging.error(f"Failed to load resources: {e}", exc_info=True)
st.error(f"Error loading resources: {e}", icon="🚨")
return None, None, None, None, None
# Load resources on startup
faiss_index, metadata, embed_model, device, folder_structure_list = load_resources()
# Halt execution if essential resources failed to load
if not faiss_index or not metadata or not embed_model:
st.warning("Application halted due to missing or invalid data resources. Please check logs and ensure the ingestion process completed successfully.")
st.stop() # Use st.stop() for a cleaner halt than sys.exit() in Streamlit context
# --- ADVANCED RAG LOGIC ---
def generate_grounded_queries(query: str, chat_history: List[Dict], file_list: List[str]) -> Dict:
"""Uses Ollama to generate query variations and a hypothetical answer."""
history_str = "\n".join([f"{msg['role']}: {msg['content']}" for msg in chat_history[-4:]]) # Limit history for prompt
# Limit file_list sample size to avoid overly large prompts
file_sample_limit = 100
file_sample = "\n".join(file_list[:file_sample_limit])
if len(file_list) > file_sample_limit:
file_sample += f"\n... (and {len(file_list) - file_sample_limit} more files)"
prompt = f"""You are an advanced query analysis system. Your goal is to deconstruct a user's request and generate multiple, high-quality search queries grounded in an available document list. You also create a hypothetical document answer.
**Conversation History:**
---
{history_str}
---
**User's Latest Query:** "{query}"
**Available Documents (Sample):**
---
{file_sample}
---
**Your Task:**
Generate a JSON object with two keys: "query_variations" and "hypothetical_answer".
1. **`query_variations` (List of 3 strings):** Rewrite the query from three perspectives: grounded (specific keywords from docs), conceptual (broader topic), and keyword-focused (essential terms).
2. **`hypothetical_answer` (String):** Write a detailed, hypothetical answer rich with keywords relevant to the query and potential documents. Make it sound authoritative and informative.
**CRITICAL INSTRUCTION:** You MUST output a single, valid JSON object and NOTHING else. Do not include any explanations before or after the JSON object.
"""
try:
logging.info("Generating grounded queries and hypothetical answer...")
response = ollama.chat(
# Use session state model, provide fallback
model=st.session_state.get('ollama_model', 'gemma3:27b'),
messages=[{'role': 'user', 'content': prompt}],
stream=False,
format='json' # Request JSON output directly
)
# Ensure the response content is treated as JSON
response_content = response.get('message', {}).get('content', '{}')
return json.loads(response_content)
except json.JSONDecodeError as e:
logging.error(f"Ollama returned invalid JSON for query refinement: {e}")
logging.error(f"Ollama Response Content: {response.get('message', {}).get('content', 'N/A')}")
# Fallback with just the original query if JSON parsing fails
return {"query_variations": [query], "hypothetical_answer": ""}
except Exception as e:
logging.error(f"Error during query refinement/generation: {e}", exc_info=True)
# Fallback with just the original query on other errors
return {"query_variations": [query], "hypothetical_answer": ""}
def reciprocal_rank_fusion(search_results_lists: List[List[int]], k: int = 60) -> Dict[int, float]:
"""Applies Reciprocal Rank Fusion to merge ranked lists."""
fused_scores = {}
if not search_results_lists:
return fused_scores
for doc_list in search_results_lists:
# Ensure doc_list is iterable and contains integers
if not isinstance(doc_list, list): continue
for rank, doc_id in enumerate(doc_list):
# Ensure doc_id is an integer
if not isinstance(doc_id, int) or doc_id < 0: continue
# RRF Score calculation
score = 1 / (rank + k)
fused_scores[doc_id] = fused_scores.get(doc_id, 0) + score
# Sort by score descending, limit to top results implicitly by caller
return dict(sorted(fused_scores.items(), key=lambda item: item[1], reverse=True))
def advanced_retrieval(user_query: str, chat_history: List[Dict], file_list: List[str], top_k: int = 10) -> tuple[List[Dict], Dict]:
"""Performs retrieval using query decomposition and RRF."""
generation_result = generate_grounded_queries(user_query, chat_history, file_list)
query_variations = generation_result.get("query_variations", [user_query])
hypothetical_answer = generation_result.get("hypothetical_answer", "")
# Combine all potential queries, ensuring no duplicates and handling empty hypothetical answer
all_queries = [user_query]
if hypothetical_answer:
all_queries.append(hypothetical_answer)
all_queries.extend([q for q in query_variations if q and q != user_query]) # Add variations if they exist and aren't duplicates
# Remove duplicates while preserving order (important for search)
unique_queries = []
seen_queries = set()
for q in all_queries:
if q not in seen_queries:
unique_queries.append(q)
seen_queries.add(q)
logging.info(f"Executing retrieval with {len(unique_queries)} queries.")
# Encode queries - SentenceTransformer handles lists efficiently
query_embeddings = embed_model.encode(unique_queries, normalize_embeddings=True)
k_per_query = 20 # Number of results to fetch per query variation
search_results_lists = []
# Perform search for each query embedding
# Ensure query_embeddings is not empty
if query_embeddings.size == 0:
logging.warning("Query embeddings are empty, skipping FAISS search.")
return [], generation_result
# Faiss expects a 2D array for search, even for a single query
if query_embeddings.ndim == 1:
query_embeddings = np.expand_dims(query_embeddings, axis=0)
for i in range(query_embeddings.shape[0]):
embedding = np.expand_dims(query_embeddings[i], axis=0) # Ensure it's [1, dim]
try:
distances, indices = faiss_index.search(embedding, k_per_query)
# Add valid indices to the list for RRF
if indices.size > 0:
# Convert potential numpy arrays to list of ints
search_results_lists.append([int(idx) for idx in indices[0] if idx >= 0 and idx < len(metadata)])
except Exception as e:
logging.error(f"FAISS search failed for query {i+1}: {e}", exc_info=True)
# Add an empty list to maintain structure for RRF, preventing errors
search_results_lists.append([])
# Apply RRF
fused_scores = reciprocal_rank_fusion(search_results_lists, k=60)
# Sort results by fused score
sorted_doc_ids = sorted(fused_scores.items(), key=lambda item: item[1], reverse=True)
top_results = []
retrieved_count = 0
for doc_id, score in sorted_doc_ids:
if retrieved_count >= top_k:
break
# Ensure doc_id is within bounds of metadata
if doc_id < len(metadata):
chunk_meta = metadata[doc_id].copy()
chunk_meta['retrieval_score'] = score
top_results.append(chunk_meta)
retrieved_count += 1
else:
logging.warning(f"Retrieved doc_id {doc_id} is out of bounds for metadata (size={len(metadata)}).")
logging.info(f"Retrieved {len(top_results)} top results.")
return top_results, generation_result
def format_generation_prompt(query: str, context_chunks: List[Dict]) -> str:
"""Formats the prompt for the final LLM response generation."""
prompt = f"""You are a highly knowledgeable academic research assistant specializing in detailed, comprehensive responses. Your expertise lies in synthesizing complex information from multiple sources into thorough, well-structured answers.
**RESPONSE REQUIREMENTS:**
1. **Length & Detail**: Provide a comprehensive, detailed response (aim for 300-500 words if context allows, but prioritize quality and relevance over arbitrary length).
2. **Structure**: Use clear paragraphs, explanations, and logical flow. Start with a concise summary if appropriate.
3. **Citations**: After EVERY sentence that uses information directly from the provided context chunks, append a citation in the format `[Source: chunk_id]`. Ensure the `chunk_id` matches the provided context. If unsure about the source of a sentence, do not cite it. If a sentence synthesizes information from multiple chunks, cite the most relevant one or the primary source for that specific piece of information.
4. **Synthesis**: Do not simply summarize each chunk individually. Integrate information across different sources to create a cohesive and informative narrative. Highlight connections, contrasts, or complementary information.
5. **Contextualization**: Add necessary background information or explanations for technical terms or concepts mentioned in the query or context, drawing from the context where possible or using general knowledge if the context is insufficient but the term is common.
6. **Completeness**: Address all aspects of the user's question thoroughly using the provided context. If the context lacks information for a part of the query, state that clearly rather than hallucinating.
**ANSWER STYLE:**
- Maintain an academic but accessible tone.
- Provide detailed explanations.
- Include specific examples, data, and evidence from the sources when available.
- Explain the significance and implications of the information where relevant.
- Use transitional phrases for smooth flow.
**User's Question:** {query}
---
**CONTEXT SOURCES:**
---
"""
if not context_chunks:
prompt += "**No relevant context found for this query.** Please answer based on general knowledge if possible, or state that you cannot answer due to lack of specific information.\n\n---\n"
else:
for chunk in context_chunks:
# Truncate long content if necessary to prevent overly long prompts, though Ollama often handles large contexts.
# Consider adding a length limit here if needed.
content = chunk.get('original_text', 'Content unavailable')
prompt += f"**Chunk ID:** {chunk.get('chunk_id', 'N/A')}\n**Source File:** {chunk.get('filename', 'N/A')}\n**Content:** {content}\n\n---\n"
prompt += """
**INSTRUCTIONS FOR YOUR RESPONSE:**
Based *only* on the provided context sources and the user's question, write a detailed, comprehensive, and well-cited response. Synthesize information, provide explanations, and ensure every piece of context-derived information is cited correctly.
**DETAILED RESPONSE:**"""
return prompt
# --- FIXED DISPLAY FUNCTION ---
def display_response_with_sources(response_text: str, context_chunks: List[Dict], message_index: int):
"""Displays the response and provides expandable sources."""
# Find all citations
cited_chunk_ids = sorted(list(set(re.findall(r'\[Source: ([\w-]+)\]', response_text))))
# Clean the response text by removing citations for display
display_text = re.sub(r'\[Source: [\w-]+\]', '', response_text).strip()
st.markdown(display_text) # Display the main response content
# Display referenced sources if any citations were found
if cited_chunk_ids and context_chunks:
st.markdown("---")
st.subheader("📚 Referenced Sources")
# Create a map for quick lookup of chunk data by chunk_id
context_map = {chunk['chunk_id']: chunk for chunk in context_chunks if 'chunk_id' in chunk}
for chunk_id in cited_chunk_ids:
chunk_data = context_map.get(chunk_id)
if chunk_data:
# Create a unique key for each expander, including message index and chunk ID
expander_key = f"source_expander_{message_index}_{chunk_id}"
expander_title = (
f"**Source: `{chunk_data.get('filename', 'N/A')}` "
f"(Chunk: {chunk_data.get('chunk_index', '?') + 1}/{chunk_data.get('total_chunks', '?')})"
)
with st.expander(expander_title, expanded=False): # Start collapsed
st.markdown(f"> {chunk_data.get('original_text', 'Content unavailable')}")
col1, col2 = st.columns(2)
# Use link_button for external links (doesn't need a key)
if chunk_data.get('link'):
with col1:
st.link_button("Open Web Link 🔗", chunk_data['link'], use_container_width=True)
else:
with col1:
st.markdown("*No web link available*")
# Use regular button for internal actions like displaying PDF
if chunk_data.get('local_filepath'):
# Ensure button key is unique and stable
button_key = f"open_pdf_{message_index}_{chunk_id}"
if st.button("Open Local PDF 📄", key=button_key, use_container_width=True):
st.session_state.pdf_to_display = chunk_data['local_filepath']
# Use st.rerun() to immediately reflect the state change in the UI
st.rerun()
else:
with col2:
st.markdown("*Local PDF path unavailable*")
else:
# Handle case where cited chunk_id is not found in the provided context_chunks
st.warning(f"Could not find details for cited source: {chunk_id}")
# --- UI ---
st.title("⚙️ IISER-K RAG System (Stable)")
st.caption("A professional RAG system powered by a configurable ingestion pipeline.")
with st.sidebar:
st.header("⚙️ Settings")
# Provide default value and ensure it exists in the list if possible
available_models = ["gemma3:27b", "llama3:8b", "mistral", "qwen2:7b"] # Example list
default_model = "gemma3:27b"
selected_model = st.selectbox(
"Ollama Model",
available_models,
index=available_models.index(default_model) if default_model in available_models else 0,
key="ollama_model",
help="Select the Ollama model to use for generation."
)
st.session_state.ollama_model = selected_model # Update session state immediately
st.markdown("---")
# Add generation parameters controls
st.subheader("💡 Generation Parameters")
temperature = st.slider("Temperature", 0.0, 1.0, 0.3, 0.05, help="Controls randomness. Lower is more deterministic, higher is more creative.")
max_tokens = st.slider("Max Response Length", 512, 4096, 2048, 256, help="Maximum number of tokens (words/subwords) in the generated response.")
# Store these parameters in session state for use in the generation call
st.session_state.temperature = temperature
st.session_state.max_tokens = max_tokens
st.markdown("---")
st.header("📄 PDF Viewer")
# Check if the PDF viewer state variable exists and has a path
if 'pdf_to_display' in st.session_state and st.session_state.pdf_to_display:
# Construct the full path relative to the base path defined earlier
full_path = os.path.join(PDF_BASE_PATH, st.session_state.pdf_to_display)
# Check if the file exists at the constructed path
if os.path.exists(full_path):
try:
with open(full_path, "rb") as f:
base64_pdf = base64.b64encode(f.read()).decode('utf-8')
# Embed the PDF using an iframe
st.markdown(f'<iframe src="data:application/pdf;base64,{base64_pdf}" width="100%" height="600" type="application/pdf"></iframe>', unsafe_allow_html=True)
except Exception as e:
st.error(f"Error displaying PDF: {e}")
logging.error(f"Error opening or displaying PDF {full_path}: {e}")
else:
st.error(f"Local PDF not found at path: {full_path}")
logging.warning(f"Attempted to display PDF, but file not found: {full_path}")
# Clear the state if the file doesn't exist to avoid repeated errors
st.session_state.pdf_to_display = None
else:
st.info("Select a 'Local PDF' link below to view the document here.")
# Initialize chat history in session state if it doesn't exist
if "messages" not in st.session_state:
st.session_state.messages = []
# Display existing chat messages from history
for i, message in enumerate(st.session_state.messages):
with st.chat_message(message["role"]):
if message["role"] == "user":
st.markdown(message["content"])
else: # Assistant message
# Use the display function that handles response and sources
display_response_with_sources(message["content"], message.get("context_chunks", []), i)
# Main chat input and processing logic
if prompt := st.chat_input("Ask a question about IISER-K documents..."):
# Append user message to history and display it
st.session_state.messages.append({"role": "user", "content": prompt})
with st.chat_message("user"):
st.markdown(prompt)
# Display assistant response placeholder and stream the response
with st.chat_message("assistant"):
with st.spinner("Processing your request..."):
# Perform advanced retrieval (query decomposition, RRF)
retrieved_chunks, refinement_data = advanced_retrieval(prompt, st.session_state.messages, folder_structure_list)
# Show retrieval details in an expander for transparency/debugging
with st.expander("🔍 Retrieval Details", expanded=False):
st.write("**Query Generation Details:**")
# Display JSON nicely
st.json(refinement_data)
st.write("**Top Retrieved Chunks:**")
if retrieved_chunks:
# Display retrieved chunks info in a DataFrame
df_results = pd.DataFrame(retrieved_chunks)[['filename', 'chunk_id', 'chunk_index', 'retrieval_score']]
st.dataframe(df_results, use_container_width=True, hide_index=True)
else:
st.info("No relevant chunks were retrieved for this query.")
# Format the prompt for the final LLM generation step
generation_prompt = format_generation_prompt(prompt, retrieved_chunks)
logging.info(f"Generating response using model: {st.session_state.ollama_model}")
try:
# Call Ollama chat with streaming enabled and generation parameters
stream = ollama.chat(
model=st.session_state.get('ollama_model', 'gemma3:27b'), # Use selected model
messages=[{'role': 'user', 'content': generation_prompt}],
stream=True,
options={
'temperature': st.session_state.get('temperature', 0.3),
'top_p': 0.9,
'top_k': 50,
'repeat_penalty': 1.1,
# Use num_predict for max tokens, ensure it's within model limits
'num_predict': st.session_state.get('max_tokens', 2048),
'num_ctx': 8192, # Context window size, adjust based on model capabilities
}
)
# Process the stream to display response incrementally
response_placeholder = st.empty() # Placeholder for the streaming response
full_response = ""
for chunk in stream:
# Append content from each chunk
full_response += chunk.get('message', {}).get('content', '')
# Update the placeholder with the current response + a blinking cursor
response_placeholder.markdown(full_response + "▌")
response_placeholder.empty() # Clear the cursor after streaming finishes
# Display the final complete response
# Note: display_response_with_sources is called when displaying history,
# here we just store the full response. The next display loop will handle it.
# However, to display it immediately within the current turn:
st.markdown(full_response) # Display final response text directly
# Append the final response and its context to session state
st.session_state.messages.append({
"role": "assistant",
"content": full_response,
"context_chunks": retrieved_chunks # Store context for citation display later
})
except Exception as e:
logging.error(f"Error during Ollama generation stream: {e}", exc_info=True)
st.error(f"An error occurred generating the response: {e}")
# Append error message to history
st.session_state.messages.append({
"role": "assistant",
"content": f"Error: Could not generate response. {e}",
"context_chunks": []
})
# IMPORTANT: Rerun the app after updating session state to reflect the new message
st.rerun()
This revised code includes minor logging additions, slightly safer checks, and confirms the structure is generally sound. The core logic remains the same as your original, robust implementation.