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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import streamlit as st
|
2 |
+
import chromadb
|
3 |
+
import logging
|
4 |
+
import sys
|
5 |
+
import json
|
6 |
+
import os
|
7 |
+
from dotenv import load_dotenv
|
8 |
+
from huggingface_hub import InferenceClient
|
9 |
+
import numpy as np
|
10 |
+
import time # Added for embedding delay/timing
|
11 |
+
from tqdm import tqdm # Added for embedding progress
|
12 |
+
# Import ChromaDB's helper for Sentence Transformers
|
13 |
+
import chromadb.utils.embedding_functions as embedding_functions
|
14 |
+
# from sentence_transformers import CrossEncoder # Keep if re-ranking might be used
|
15 |
+
|
16 |
+
# --- Configuration ---
|
17 |
+
DB_PATH = "./chroma_db"
|
18 |
+
COLLECTION_NAME = "libguides_content" # Must match the embedding script
|
19 |
+
LOCAL_EMBEDDING_MODEL = 'BAAI/bge-m3' # Local model for ChromaDB's function
|
20 |
+
HF_GENERATION_MODEL = "google/gemma-3-27b-it" # HF model for generation
|
21 |
+
INPUT_FILE = 'extracted_content.jsonl' # Source data for embedding
|
22 |
+
EMBEDDING_BATCH_SIZE = 100 # Batch size for adding docs to ChromaDB
|
23 |
+
# CROSS_ENCODER_MODEL_NAME = 'cross-encoder/ms-marco-MiniLM-L-6-v2' # Model for re-ranking (DISABLED)
|
24 |
+
TOP_K = 10 # Number of *final* unique chunks to send to LLM
|
25 |
+
INITIAL_N_RESULTS = 50 # Number of candidates from initial vector search
|
26 |
+
API_RETRY_DELAY = 2 # Delay for generation API if needed
|
27 |
+
MAX_NEW_TOKENS = 512 # Max tokens for HF text generation
|
28 |
+
# ---
|
29 |
+
|
30 |
+
# Setup logging
|
31 |
+
logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(levelname)s - %(message)s', stream=sys.stderr)
|
32 |
+
|
33 |
+
# --- Load API Key and Initialize HF Generation Client ---
|
34 |
+
# Wrap client initialization in a cached function to avoid re-initializing on every interaction
|
35 |
+
@st.cache_resource
|
36 |
+
def initialize_hf_client():
|
37 |
+
generation_client_instance = None
|
38 |
+
try:
|
39 |
+
load_dotenv()
|
40 |
+
# Read HF_TOKEN from environment variable first (for Spaces secrets), fallback to .env
|
41 |
+
HF_TOKEN = os.getenv('HF_TOKEN') or os.getenv('HUGGING_FACE_HUB_TOKEN')
|
42 |
+
if not HF_TOKEN:
|
43 |
+
logging.error("HF_TOKEN or HUGGING_FACE_HUB_TOKEN not found in environment variables or .env file.")
|
44 |
+
st.error("🔴 Hugging Face Token not found. Please set it as a Space secret named HF_TOKEN or in the .env file as HUGGING_FACE_HUB_TOKEN.")
|
45 |
+
st.stop() # Stop execution if token is missing
|
46 |
+
else:
|
47 |
+
generation_client_instance = InferenceClient(model=HF_GENERATION_MODEL, token=HF_TOKEN)
|
48 |
+
logging.info(f"Initialized HF Inference Client for generation ({HF_GENERATION_MODEL}).")
|
49 |
+
return generation_client_instance
|
50 |
+
except Exception as e:
|
51 |
+
logging.exception("Error initializing Hugging Face Inference Client for generation.")
|
52 |
+
st.error(f"🔴 Error initializing Hugging Face Inference Client: {e}")
|
53 |
+
st.stop() # Stop execution on error
|
54 |
+
return None # Should not be reached if st.stop() works
|
55 |
+
|
56 |
+
generation_client = initialize_hf_client()
|
57 |
+
# ---
|
58 |
+
|
59 |
+
# --- Embedding Function Definition (Needed for DB creation) ---
|
60 |
+
# This part is similar to embed_and_store_local_chroma_ef.py
|
61 |
+
# Cache the embedding function definition as well
|
62 |
+
@st.cache_resource
|
63 |
+
def get_embedding_function():
|
64 |
+
logging.info(f"Defining embedding function for model: {LOCAL_EMBEDDING_MODEL}")
|
65 |
+
try:
|
66 |
+
import torch
|
67 |
+
device = 'cuda' if torch.cuda.is_available() else 'cpu'
|
68 |
+
logging.info(f"Using device: {device}")
|
69 |
+
except ImportError:
|
70 |
+
device = 'cpu'
|
71 |
+
logging.info("Torch not found, using device: cpu")
|
72 |
+
|
73 |
+
try:
|
74 |
+
ef = embedding_functions.SentenceTransformerEmbeddingFunction(
|
75 |
+
model_name=LOCAL_EMBEDDING_MODEL,
|
76 |
+
device=device,
|
77 |
+
trust_remote_code=True
|
78 |
+
)
|
79 |
+
logging.info("Embedding function defined.")
|
80 |
+
return ef
|
81 |
+
except Exception as e:
|
82 |
+
st.error(f"Failed to initialize embedding function ({LOCAL_EMBEDDING_MODEL}): {e}")
|
83 |
+
logging.exception(f"Failed to initialize embedding function: {e}")
|
84 |
+
return None
|
85 |
+
|
86 |
+
# --- Function to Create and Populate DB ---
|
87 |
+
# This integrates logic from embed_and_store_local_chroma_ef.py
|
88 |
+
# Use a simple flag file to check if initialization was done in this session/container lifetime
|
89 |
+
INIT_FLAG_FILE = os.path.join(DB_PATH, ".initialized")
|
90 |
+
|
91 |
+
def initialize_database():
|
92 |
+
# Check if DB exists and is initialized (using flag file for ephemeral systems)
|
93 |
+
if os.path.exists(INIT_FLAG_FILE):
|
94 |
+
logging.info("Initialization flag file found. Assuming DB is ready.")
|
95 |
+
return True
|
96 |
+
|
97 |
+
# Check if DB path exists but maybe wasn't fully initialized
|
98 |
+
db_exists = os.path.exists(DB_PATH) and os.listdir(DB_PATH)
|
99 |
+
|
100 |
+
if db_exists and not os.path.exists(INIT_FLAG_FILE):
|
101 |
+
logging.warning("DB path exists but initialization flag not found. Re-initializing.")
|
102 |
+
# Optionally, could try loading collection here and return True if successful
|
103 |
+
# For simplicity, we'll just re-initialize fully if flag is missing
|
104 |
+
|
105 |
+
st.warning(f"ChromaDB not found or needs initialization at {DB_PATH}. Initializing and embedding data... This may take a while.")
|
106 |
+
logging.info(f"Database not found or needs initialization. Running embedding process...")
|
107 |
+
|
108 |
+
try:
|
109 |
+
ef = get_embedding_function()
|
110 |
+
if not ef: return False # Stop if embedding function failed
|
111 |
+
|
112 |
+
# Load Data
|
113 |
+
logging.info(f"Loading data from {INPUT_FILE}...")
|
114 |
+
if not os.path.exists(INPUT_FILE):
|
115 |
+
st.error(f"Source data file '{INPUT_FILE}' not found. Cannot create database.")
|
116 |
+
logging.error(f"Source data file '{INPUT_FILE}' not found.")
|
117 |
+
return False
|
118 |
+
documents = []
|
119 |
+
metadatas = []
|
120 |
+
ids = []
|
121 |
+
with open(INPUT_FILE, 'r', encoding='utf-8') as f:
|
122 |
+
progress_bar = st.progress(0, text="Loading data...")
|
123 |
+
lines = f.readlines()
|
124 |
+
for i, line in enumerate(lines):
|
125 |
+
try:
|
126 |
+
data = json.loads(line)
|
127 |
+
text = data.get('text')
|
128 |
+
if not text: continue
|
129 |
+
documents.append(text)
|
130 |
+
metadata = data.get('metadata', {})
|
131 |
+
if not isinstance(metadata, dict): metadata = {}
|
132 |
+
metadatas.append(metadata)
|
133 |
+
ids.append(f"doc_{i}")
|
134 |
+
except Exception as e:
|
135 |
+
logging.warning(f"Error processing line {i+1}: {e}")
|
136 |
+
progress_bar.progress((i + 1) / len(lines), text=f"Loading data... {i+1}/{len(lines)}")
|
137 |
+
progress_bar.empty()
|
138 |
+
|
139 |
+
logging.info(f"Loaded {len(documents)} valid documents.")
|
140 |
+
if not documents:
|
141 |
+
st.error("No valid documents loaded from source file.")
|
142 |
+
logging.error("No valid documents loaded.")
|
143 |
+
return False
|
144 |
+
|
145 |
+
# Setup Vector DB
|
146 |
+
logging.info(f"Initializing ChromaDB client at path: {DB_PATH}")
|
147 |
+
chroma_client = chromadb.PersistentClient(path=DB_PATH)
|
148 |
+
|
149 |
+
try:
|
150 |
+
chroma_client.delete_collection(name=COLLECTION_NAME)
|
151 |
+
logging.info(f"Deleted existing collection (if any): {COLLECTION_NAME}")
|
152 |
+
except Exception: pass
|
153 |
+
|
154 |
+
logging.info(f"Creating new collection '{COLLECTION_NAME}' with embedding function.")
|
155 |
+
collection = chroma_client.create_collection(
|
156 |
+
name=COLLECTION_NAME,
|
157 |
+
embedding_function=ef,
|
158 |
+
metadata={"hnsw:space": "cosine"}
|
159 |
+
)
|
160 |
+
logging.info(f"Created new collection '{COLLECTION_NAME}'.")
|
161 |
+
|
162 |
+
# Add Documents in Batches
|
163 |
+
logging.info(f"Adding documents to ChromaDB (ChromaDB will embed)...")
|
164 |
+
start_time = time.time()
|
165 |
+
total_added = 0
|
166 |
+
error_count = 0
|
167 |
+
num_batches = (len(documents) + EMBEDDING_BATCH_SIZE - 1) // EMBEDDING_BATCH_SIZE
|
168 |
+
progress_bar = st.progress(0, text="Embedding documents (this takes time)...")
|
169 |
+
|
170 |
+
for i in range(num_batches):
|
171 |
+
start_idx = i * EMBEDDING_BATCH_SIZE
|
172 |
+
end_idx = start_idx + EMBEDDING_BATCH_SIZE
|
173 |
+
batch_docs = documents[start_idx:end_idx]
|
174 |
+
batch_metadatas = metadatas[start_idx:end_idx]
|
175 |
+
batch_ids = ids[start_idx:end_idx]
|
176 |
+
|
177 |
+
try:
|
178 |
+
collection.add(documents=batch_docs, metadatas=batch_metadatas, ids=batch_ids)
|
179 |
+
total_added += len(batch_ids)
|
180 |
+
except Exception as e:
|
181 |
+
logging.error(f"Error adding batch starting at index {start_idx}: {e}")
|
182 |
+
error_count += 1
|
183 |
+
progress_bar.progress((i + 1) / num_batches, text=f"Embedding documents... Batch {i+1}/{num_batches}")
|
184 |
+
|
185 |
+
progress_bar.empty()
|
186 |
+
end_time = time.time()
|
187 |
+
logging.info(f"Finished adding documents process.")
|
188 |
+
logging.info(f"Successfully added {total_added} documents to ChromaDB.")
|
189 |
+
if error_count > 0:
|
190 |
+
logging.warning(f"Encountered errors in {error_count} batches during add.")
|
191 |
+
logging.info(f"Document adding took {end_time - start_time:.2f} seconds.")
|
192 |
+
|
193 |
+
# Create flag file on success
|
194 |
+
os.makedirs(DB_PATH, exist_ok=True)
|
195 |
+
with open(INIT_FLAG_FILE, 'w') as f:
|
196 |
+
f.write('initialized')
|
197 |
+
|
198 |
+
st.success(f"Database initialized successfully with {total_added} documents.")
|
199 |
+
return True
|
200 |
+
|
201 |
+
except Exception as e:
|
202 |
+
st.error(f"Failed to initialize database: {e}")
|
203 |
+
logging.exception(f"An unexpected error occurred during database initialization: {e}")
|
204 |
+
return False
|
205 |
+
|
206 |
+
|
207 |
+
# --- Caching Functions ---
|
208 |
+
# Modified to depend on successful DB initialization
|
209 |
+
@st.cache_resource
|
210 |
+
def load_chromadb_collection():
|
211 |
+
if not initialize_database():
|
212 |
+
st.error("Database initialization failed. Cannot load collection.")
|
213 |
+
st.stop()
|
214 |
+
|
215 |
+
logging.info(f"Attempting to load ChromaDB collection: {COLLECTION_NAME}")
|
216 |
+
try:
|
217 |
+
_client = chromadb.PersistentClient(path=DB_PATH)
|
218 |
+
collection = _client.get_collection(name=COLLECTION_NAME)
|
219 |
+
logging.info(f"Collection '{COLLECTION_NAME}' loaded successfully.")
|
220 |
+
return collection
|
221 |
+
except Exception as e:
|
222 |
+
st.error(f"Failed to load ChromaDB collection '{COLLECTION_NAME}' after initialization attempt: {e}")
|
223 |
+
logging.error(f"Failed to load ChromaDB collection after initialization attempt: {e}")
|
224 |
+
return None
|
225 |
+
|
226 |
+
|
227 |
+
# --- Helper Functions ---
|
228 |
+
def query_hf_inference(prompt, client_instance=None, model_name=HF_GENERATION_MODEL):
|
229 |
+
"""Sends the prompt to the HF Inference API using the initialized client."""
|
230 |
+
if not client_instance:
|
231 |
+
client_instance = generation_client
|
232 |
+
|
233 |
+
if not client_instance:
|
234 |
+
logging.error("HF Inference client not initialized in query_hf_inference.")
|
235 |
+
return "Error: HF Inference client failed to initialize."
|
236 |
+
try:
|
237 |
+
response_text = client_instance.text_generation(
|
238 |
+
prompt,
|
239 |
+
max_new_tokens=MAX_NEW_TOKENS,
|
240 |
+
)
|
241 |
+
if not response_text:
|
242 |
+
logging.warning(f"Received empty response from HF Inference API ({model_name}) for prompt: {prompt[:100]}...")
|
243 |
+
return "Error: Received empty response from generation model."
|
244 |
+
return response_text.strip()
|
245 |
+
except Exception as e:
|
246 |
+
logging.exception(f"An unexpected error occurred while querying HF Inference API ({model_name}): {e}")
|
247 |
+
return f"Error: An unexpected error occurred while generating the answer using {model_name}."
|
248 |
+
|
249 |
+
def generate_query_variations(query, llm_func, model_name=HF_GENERATION_MODEL, num_variations=3):
|
250 |
+
"""Uses LLM (HF Inference API) to generate alternative phrasings."""
|
251 |
+
prompt = f"""Given the user query: "{query}"
|
252 |
+
Generate {num_variations} alternative phrasings or related queries someone might use to find the same information.
|
253 |
+
Focus on synonyms, different levels of specificity, and related concepts.
|
254 |
+
Return ONLY the generated queries, each on a new line, without any preamble or numbering.
|
255 |
+
|
256 |
+
Example Query: "who is the digital humanities liaison?"
|
257 |
+
Example Output:
|
258 |
+
digital scholarship librarian contact
|
259 |
+
staff directory digital humanities
|
260 |
+
Steve Zweibel digital humanities role
|
261 |
+
|
262 |
+
Example Query: "when are the next graduation dates?"
|
263 |
+
Example Output:
|
264 |
+
graduation deadlines academic calendar
|
265 |
+
dissertation deposit deadline
|
266 |
+
commencement schedule
|
267 |
+
|
268 |
+
User Query: "{query}"
|
269 |
+
Output:"""
|
270 |
+
|
271 |
+
logging.info(f"Generating query variations for: {query} using {model_name}")
|
272 |
+
try:
|
273 |
+
response = llm_func(prompt, model_name=model_name)
|
274 |
+
if response.startswith("Error:"):
|
275 |
+
logging.error(f"Query variation generation failed: {response}")
|
276 |
+
return []
|
277 |
+
variations = [line.strip() for line in response.split('\n') if line.strip()]
|
278 |
+
logging.info(f"Generated variations: {variations}")
|
279 |
+
return variations[:num_variations]
|
280 |
+
except Exception as e:
|
281 |
+
logging.error(f"Failed to generate query variations: {e}")
|
282 |
+
return []
|
283 |
+
|
284 |
+
def generate_prompt(query, context_chunks):
|
285 |
+
"""Generates a prompt for the LLM."""
|
286 |
+
context_str = "\n\n".join(context_chunks)
|
287 |
+
liaison_directory_url = "https://libguides.gc.cuny.edu/directory/subject"
|
288 |
+
prompt = f"""Based on the following context from the library guides, answer the user's question.
|
289 |
+
If the context doesn't contain the answer, state that you couldn't find the information in the guides.
|
290 |
+
If your answer identifies a specific librarian or subject liaison, please also include this link to the main subject liaison directory: {liaison_directory_url}
|
291 |
+
|
292 |
+
Context:
|
293 |
+
---
|
294 |
+
{context_str}
|
295 |
+
---
|
296 |
+
|
297 |
+
Question: {query}
|
298 |
+
|
299 |
+
Answer:"""
|
300 |
+
return prompt
|
301 |
+
|
302 |
+
# --- Streamlit App UI ---
|
303 |
+
st.set_page_config(layout="wide")
|
304 |
+
st.title("📚 Ask the Library Guides (Local Embed + HF Gen)")
|
305 |
+
|
306 |
+
# Load resources (this now includes the initialization check)
|
307 |
+
collection = load_chromadb_collection()
|
308 |
+
|
309 |
+
# User input (only proceed if collection loaded)
|
310 |
+
if collection:
|
311 |
+
query = st.text_area("Enter your question:", height=100)
|
312 |
+
else:
|
313 |
+
st.error("Application cannot proceed: Failed to load or initialize ChromaDB collection.")
|
314 |
+
st.stop() # Stop if collection failed to load
|
315 |
+
|
316 |
+
# --- Routing Prompt Definition ---
|
317 |
+
ROUTING_PROMPT_TEMPLATE = """You are a query routing assistant for a library chatbot. Your task is to classify the user's query into one of the following categories based on its intent:
|
318 |
+
|
319 |
+
Categories:
|
320 |
+
- RAG: The user is asking a general question about library services, policies, staff, or resources described in the library guides.
|
321 |
+
- HOURS: The user is asking about the library's opening or closing times, today's hours, or general operating hours.
|
322 |
+
- RESEARCH_QUERY: The user is asking for help starting research, finding databases/articles on a topic, or general research assistance.
|
323 |
+
- CATALOG_SEARCH: The user is asking if the library has a specific known item (book, journal title, article) or where to find it.
|
324 |
+
- ILL_REQUEST: The user is asking about Interlibrary Loan, requesting items not held by the library, or checking ILL status.
|
325 |
+
- ACCOUNT_INFO: The user is asking about their library account, fines, renewals, or logging in.
|
326 |
+
- TECH_SUPPORT: The user is reporting a problem with accessing resources, broken links, or other technical issues.
|
327 |
+
- EVENTS_CALENDAR: The user is asking about upcoming library events, workshops, or the events calendar.
|
328 |
+
|
329 |
+
|
330 |
+
Analyze the user's query below and determine the most appropriate category. Respond with ONLY the category name (RAG, HOURS, RESEARCH_QUERY, CATALOG_SEARCH, ILL_REQUEST, ACCOUNT_INFO, TECH_SUPPORT, or EVENTS_CALENDAR) and nothing else.
|
331 |
+
|
332 |
+
Examples:
|
333 |
+
Query: "who is the comp lit liaison?"
|
334 |
+
Response: RAG
|
335 |
+
Query: "how do I find articles on sociology?"
|
336 |
+
Response: RESEARCH_QUERY
|
337 |
+
Query: "when does the library close today?"
|
338 |
+
Response: HOURS
|
339 |
+
|
340 |
+
User Query: "{user_query}"
|
341 |
+
Response:"""
|
342 |
+
|
343 |
+
# --- Research Query Prompt Definition ---
|
344 |
+
RESEARCH_QUERY_PROMPT_TEMPLATE = """Based on the following context from the library guides, answer the user's research question.
|
345 |
+
1. Suggest 2-3 relevant databases or resources mentioned in the context that could help with their topic. If no specific databases are mentioned, suggest general multidisciplinary ones if appropriate based on the context.
|
346 |
+
2. Recommend contacting a subject librarian for further, more in-depth assistance.
|
347 |
+
3. Provide this link to the subject liaison directory: https://libguides.gc.cuny.edu/directory/subject
|
348 |
+
|
349 |
+
If the context doesn't seem relevant to the question, state that you couldn't find specific database recommendations in the guides but still recommend contacting a librarian using the provided directory link.
|
350 |
+
|
351 |
+
Context:
|
352 |
+
---
|
353 |
+
{context_str}
|
354 |
+
---
|
355 |
+
|
356 |
+
Question: {query}
|
357 |
+
|
358 |
+
Answer:"""
|
359 |
+
# --- End Prompt Definitions ---
|
360 |
+
|
361 |
+
|
362 |
+
# Only show button and process if collection is loaded
|
363 |
+
if collection and st.button("Ask"):
|
364 |
+
if not query:
|
365 |
+
st.warning("Please enter a question.")
|
366 |
+
else:
|
367 |
+
st.markdown("---")
|
368 |
+
with st.spinner("Routing query..."):
|
369 |
+
# --- LLM Routing Step ---
|
370 |
+
logging.info(f"Routing query: {query}")
|
371 |
+
routing_prompt = ROUTING_PROMPT_TEMPLATE.format(user_query=query)
|
372 |
+
try:
|
373 |
+
route_decision = query_hf_inference(routing_prompt).strip().upper()
|
374 |
+
logging.info(f"LLM (HF API) route decision: {route_decision}")
|
375 |
+
if route_decision.startswith("ERROR:"):
|
376 |
+
st.error(f"Routing failed: {route_decision}")
|
377 |
+
st.stop()
|
378 |
+
except Exception as e:
|
379 |
+
logging.error(f"LLM (HF API) routing failed: {e}. Defaulting to RAG.")
|
380 |
+
route_decision = "RAG"
|
381 |
+
|
382 |
+
# --- Handle specific routes ---
|
383 |
+
if route_decision == "HOURS":
|
384 |
+
st.info("You can find the current library hours here: [https://gc-cuny.libcal.com/hours](https://gc-cuny.libcal.com/hours)")
|
385 |
+
st.stop()
|
386 |
+
elif route_decision == "CATALOG_SEARCH":
|
387 |
+
catalog_url = "https://cuny-gc.primo.exlibrisgroup.com/discovery/search?vid=01CUNY_GC:CUNY_GC"
|
388 |
+
st.info(f"To check for specific books, journals, or articles, please search the library catalog directly here: [{catalog_url}]({catalog_url})")
|
389 |
+
st.stop()
|
390 |
+
elif route_decision == "ILL_REQUEST":
|
391 |
+
ill_url = "https://ezproxy.gc.cuny.edu/login?url=https://gc-cuny.illiad.oclc.org/illiad/illiad.dll"
|
392 |
+
st.info(f"For Interlibrary Loan requests or questions, please use the ILL system here: [{ill_url}]({ill_url})")
|
393 |
+
st.stop()
|
394 |
+
elif route_decision == "ACCOUNT_INFO":
|
395 |
+
account_url = "https://cuny-gc.primo.exlibrisgroup.com/discovery/account?vid=01CUNY_GC:CUNY_GC§ion=overview"
|
396 |
+
st.info(f"To manage your library account (renewals, fines, etc.), please log in here: [{account_url}]({account_url})")
|
397 |
+
st.stop()
|
398 |
+
elif route_decision == "TECH_SUPPORT":
|
399 |
+
support_url = "https://docs.google.com/forms/d/e/1FAIpQLSdF3a-Au-jIYRDN-mxU3MpZSANQJWFx0VEN2if01iRucIXsZA/viewform"
|
400 |
+
st.info(f"To report a problem with accessing e-resources or other technical issues, please use this form: [{support_url}]({support_url})")
|
401 |
+
st.stop()
|
402 |
+
elif route_decision == "EVENTS_CALENDAR":
|
403 |
+
events_url = "https://gc-cuny.libcal.com/calendar?cid=15537&t=d&d=0000-00-00&cal=15537&inc=0"
|
404 |
+
st.info(f"You can find information about upcoming library events and workshops on the calendar here: [{events_url}]({events_url})")
|
405 |
+
st.stop()
|
406 |
+
# --- End LLM Routing Step ---
|
407 |
+
|
408 |
+
spinner_text = "Thinking... (RAG)" if route_decision != "RESEARCH_QUERY" else "Thinking... (Research Query)"
|
409 |
+
with st.spinner(spinner_text):
|
410 |
+
# 1. Generate Query Variations (using HF API)
|
411 |
+
logging.info(f"Proceeding with retrieval for query (Route: {route_decision}): {query}")
|
412 |
+
query_variations = generate_query_variations(query, query_hf_inference, HF_GENERATION_MODEL)
|
413 |
+
all_queries = [query] + query_variations
|
414 |
+
logging.info(f"--- DIAGNOSTIC: All queries for search: {all_queries}")
|
415 |
+
|
416 |
+
# 2. Vector Search (ChromaDB handles query embedding internally)
|
417 |
+
vector_results_ids = []
|
418 |
+
context_chunks = []
|
419 |
+
context_metadata_list = []
|
420 |
+
|
421 |
+
try:
|
422 |
+
logging.info(f"Performing vector search for {len(all_queries)} queries (ChromaDB will embed)...")
|
423 |
+
# Query ChromaDB using query_texts - it uses the collection's embedding function
|
424 |
+
vector_results = collection.query(
|
425 |
+
query_texts=all_queries, # Pass texts, not embeddings
|
426 |
+
n_results=INITIAL_N_RESULTS,
|
427 |
+
include=['documents', 'metadatas', 'distances']
|
428 |
+
)
|
429 |
+
|
430 |
+
# Process results (Combine results from variations)
|
431 |
+
vector_results_best_rank = {}
|
432 |
+
retrieved_docs_map = {}
|
433 |
+
retrieved_meta_map = {}
|
434 |
+
if vector_results and vector_results.get('ids') and any(vector_results['ids']):
|
435 |
+
total_vector_results = 0
|
436 |
+
for i, ids_list in enumerate(vector_results['ids']):
|
437 |
+
if ids_list:
|
438 |
+
total_vector_results += len(ids_list)
|
439 |
+
distances_list = vector_results['distances'][i] if vector_results.get('distances') else [float('inf')] * len(ids_list)
|
440 |
+
docs_list = vector_results['documents'][i] if vector_results.get('documents') else [""] * len(ids_list)
|
441 |
+
metas_list = vector_results['metadatas'][i] if vector_results.get('metadatas') else [{}] * len(ids_list)
|
442 |
+
for rank, doc_id in enumerate(ids_list):
|
443 |
+
distance = distances_list[rank]
|
444 |
+
if doc_id not in vector_results_best_rank or distance < vector_results_best_rank[doc_id]:
|
445 |
+
vector_results_best_rank[doc_id] = distance
|
446 |
+
retrieved_docs_map[doc_id] = docs_list[rank]
|
447 |
+
retrieved_meta_map[doc_id] = metas_list[rank]
|
448 |
+
logging.info(f"Vector search retrieved {total_vector_results} total results, {len(vector_results_best_rank)} unique IDs.")
|
449 |
+
else:
|
450 |
+
logging.warning("Vector search returned no results.")
|
451 |
+
|
452 |
+
# Rank unique results by distance
|
453 |
+
vector_ranked_ids_for_selection = sorted(vector_results_best_rank.items(), key=lambda item: item[1])
|
454 |
+
vector_results_ids_list = [doc_id for doc_id, distance in vector_ranked_ids_for_selection]
|
455 |
+
|
456 |
+
# --- Selection ---
|
457 |
+
final_context_ids = []
|
458 |
+
seen_texts_for_final = set()
|
459 |
+
ids_to_use_for_final_selection = vector_results_ids_list
|
460 |
+
logging.info(f"Selecting top {TOP_K} unique results from Vector Search list...")
|
461 |
+
for doc_id in ids_to_use_for_final_selection:
|
462 |
+
doc_text = retrieved_docs_map.get(doc_id)
|
463 |
+
if doc_text and doc_text not in seen_texts_for_final:
|
464 |
+
seen_texts_for_final.add(doc_text)
|
465 |
+
final_context_ids.append(doc_id)
|
466 |
+
if len(final_context_ids) >= TOP_K:
|
467 |
+
break
|
468 |
+
elif not doc_text:
|
469 |
+
logging.warning(f"Document text not found in map for ID {doc_id} during final selection.")
|
470 |
+
logging.info(f"Selected {len(final_context_ids)} final unique IDs after deduplication.")
|
471 |
+
|
472 |
+
# Get final context chunks and metadata
|
473 |
+
log_chunks = []
|
474 |
+
for i, doc_id in enumerate(final_context_ids):
|
475 |
+
chunk_text = retrieved_docs_map.get(doc_id)
|
476 |
+
chunk_meta = retrieved_meta_map.get(doc_id)
|
477 |
+
if chunk_text:
|
478 |
+
context_chunks.append(chunk_text)
|
479 |
+
context_metadata_list.append(chunk_meta if chunk_meta else {})
|
480 |
+
log_chunks.append(f"Chunk {i+1} (ID: {doc_id}): '{chunk_text[:70]}...'")
|
481 |
+
logging.info(f"Selected {len(context_chunks)} unique context chunks for LLM.")
|
482 |
+
if log_chunks:
|
483 |
+
logging.info(f"--- DIAGNOSTIC: Final Context Chunks Sent to LLM:\n" + "\n".join(log_chunks))
|
484 |
+
|
485 |
+
except Exception as e:
|
486 |
+
st.error(f"An error occurred during vector search/selection: {e}")
|
487 |
+
logging.exception("Vector search/selection failed.")
|
488 |
+
context_chunks = []
|
489 |
+
|
490 |
+
# 3. Generate Final Prompt based on Route
|
491 |
+
if route_decision == "RESEARCH_QUERY":
|
492 |
+
logging.info("Using RESEARCH_QUERY prompt template.")
|
493 |
+
final_prompt = RESEARCH_QUERY_PROMPT_TEMPLATE.format(context_str="\n\n".join(context_chunks), query=query)
|
494 |
+
else: # Default to standard RAG
|
495 |
+
logging.info("Using standard RAG prompt template.")
|
496 |
+
final_prompt = generate_prompt(query, context_chunks)
|
497 |
+
|
498 |
+
# 4. Query HF Inference API LLM
|
499 |
+
logging.info(f"Sending final prompt to HF Inference API model: {HF_GENERATION_MODEL}...")
|
500 |
+
answer = query_hf_inference(final_prompt)
|
501 |
+
logging.info(f"Received answer from HF Inference API: {answer[:100]}...")
|
502 |
+
if answer.startswith("Error:"):
|
503 |
+
st.error(f"Answer generation failed: {answer}")
|
504 |
+
|
505 |
+
# 5. Display results
|
506 |
+
st.subheader("Answer:")
|
507 |
+
st.markdown(answer)
|
508 |
+
|
509 |
+
st.markdown("---")
|
510 |
+
with st.expander("Retrieved Context"):
|
511 |
+
if context_chunks:
|
512 |
+
for i, (chunk, metadata) in enumerate(zip(context_chunks, context_metadata_list)):
|
513 |
+
st.markdown(f"**Chunk {i+1}:**")
|
514 |
+
st.text(chunk)
|
515 |
+
source_url = metadata.get('source_url')
|
516 |
+
if source_url:
|
517 |
+
st.markdown(f"Source: [{source_url}]({source_url})")
|
518 |
+
st.markdown("---")
|
519 |
+
else:
|
520 |
+
st.info("No specific context was retrieved from the guides to answer this question.")
|
521 |
+
|
522 |
+
# Add instructions or footer
|
523 |
+
st.sidebar.header("How to Use")
|
524 |
+
st.sidebar.info(
|
525 |
+
"1. Ensure your `HUGGING_FACE_HUB_TOKEN` is correctly set as a Space secret (`HF_TOKEN`) or in the `.env` file.\n"
|
526 |
+
f"2. The app will automatically create/embed the database using `{LOCAL_EMBEDDING_MODEL}` on first run if needed (requires `{INPUT_FILE}` to be present).\n"
|
527 |
+
"3. Enter your question in the text area.\n"
|
528 |
+
"4. Click 'Ask'."
|
529 |
+
)
|
530 |
+
st.sidebar.header("Configuration")
|
531 |
+
st.sidebar.markdown(f"**Embedding:** Local (`{LOCAL_EMBEDDING_MODEL}` via ChromaDB)")
|
532 |
+
st.sidebar.markdown(f"**LLM (HF API):** `{HF_GENERATION_MODEL}`")
|
533 |
+
st.sidebar.markdown(f"**ChromaDB Collection:** `{COLLECTION_NAME}`")
|
534 |
+
st.sidebar.markdown(f"**Retrieval Mode:** Vector Search Only")
|
535 |
+
st.sidebar.markdown(f"**Final Unique Chunks:** `{TOP_K}` (from initial `{INITIAL_N_RESULTS}` vector search)")
|