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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
Khalifa University Library RAG Backend
|
| 3 |
+
LangChain + FAISS + FastAPI on Hugging Face Spaces
|
| 4 |
+
|
| 5 |
+
This app:
|
| 6 |
+
1. Loads scraped library pages from the 'knowledge/' folder
|
| 7 |
+
2. Chunks and embeds them using OpenAI embeddings
|
| 8 |
+
3. Stores in a FAISS vector store
|
| 9 |
+
4. Exposes a /rag endpoint that retrieves relevant chunks and generates grounded answers
|
| 10 |
+
|
| 11 |
+
Environment variables (set as HF Space Secrets):
|
| 12 |
+
OPENAI_API_KEY — for embeddings + LLM
|
| 13 |
+
"""
|
| 14 |
+
|
| 15 |
+
import os
|
| 16 |
+
import glob
|
| 17 |
+
from contextlib import asynccontextmanager
|
| 18 |
+
from fastapi import FastAPI
|
| 19 |
+
from fastapi.middleware.cors import CORSMiddleware
|
| 20 |
+
from pydantic import BaseModel
|
| 21 |
+
|
| 22 |
+
from langchain_openai import OpenAIEmbeddings, ChatOpenAI
|
| 23 |
+
from langchain_community.vectorstores import FAISS
|
| 24 |
+
from langchain.text_splitter import RecursiveCharacterTextSplitter
|
| 25 |
+
from langchain.chains import RetrievalQA
|
| 26 |
+
from langchain.prompts import PromptTemplate
|
| 27 |
+
from langchain.schema import Document
|
| 28 |
+
|
| 29 |
+
# ===== CONFIG =====
|
| 30 |
+
KNOWLEDGE_DIR = "knowledge"
|
| 31 |
+
FAISS_INDEX_PATH = "faiss_index"
|
| 32 |
+
CHUNK_SIZE = 800
|
| 33 |
+
CHUNK_OVERLAP = 100
|
| 34 |
+
EMBEDDING_MODEL = "text-embedding-3-small"
|
| 35 |
+
LLM_MODEL = "gpt-4o-mini"
|
| 36 |
+
TOP_K = 5
|
| 37 |
+
|
| 38 |
+
# ===== GLOBAL STATE =====
|
| 39 |
+
qa_chain = None
|
| 40 |
+
vectorstore = None
|
| 41 |
+
|
| 42 |
+
|
| 43 |
+
def load_documents():
|
| 44 |
+
"""Load all .txt files from the knowledge directory."""
|
| 45 |
+
docs = []
|
| 46 |
+
files = glob.glob(os.path.join(KNOWLEDGE_DIR, "*.txt"))
|
| 47 |
+
print(f"Found {len(files)} knowledge files")
|
| 48 |
+
|
| 49 |
+
for filepath in files:
|
| 50 |
+
try:
|
| 51 |
+
with open(filepath, "r", encoding="utf-8") as f:
|
| 52 |
+
content = f.read()
|
| 53 |
+
|
| 54 |
+
# Extract metadata from first two lines
|
| 55 |
+
lines = content.split("\n", 3)
|
| 56 |
+
source = ""
|
| 57 |
+
title = ""
|
| 58 |
+
text = content
|
| 59 |
+
|
| 60 |
+
for line in lines[:2]:
|
| 61 |
+
if line.startswith("SOURCE:"):
|
| 62 |
+
source = line.replace("SOURCE:", "").strip()
|
| 63 |
+
elif line.startswith("TITLE:"):
|
| 64 |
+
title = line.replace("TITLE:", "").strip()
|
| 65 |
+
|
| 66 |
+
if source or title:
|
| 67 |
+
text = "\n".join(lines[2:]).strip()
|
| 68 |
+
|
| 69 |
+
docs.append(Document(
|
| 70 |
+
page_content=text,
|
| 71 |
+
metadata={"source": source, "title": title, "file": os.path.basename(filepath)}
|
| 72 |
+
))
|
| 73 |
+
except Exception as e:
|
| 74 |
+
print(f"Error loading {filepath}: {e}")
|
| 75 |
+
|
| 76 |
+
print(f"Loaded {len(docs)} documents")
|
| 77 |
+
return docs
|
| 78 |
+
|
| 79 |
+
|
| 80 |
+
def build_vectorstore(docs):
|
| 81 |
+
"""Chunk documents and create FAISS vector store."""
|
| 82 |
+
splitter = RecursiveCharacterTextSplitter(
|
| 83 |
+
chunk_size=CHUNK_SIZE,
|
| 84 |
+
chunk_overlap=CHUNK_OVERLAP,
|
| 85 |
+
separators=["\n\n", "\n", ". ", " ", ""]
|
| 86 |
+
)
|
| 87 |
+
chunks = splitter.split_documents(docs)
|
| 88 |
+
print(f"Split into {len(chunks)} chunks")
|
| 89 |
+
|
| 90 |
+
embeddings = OpenAIEmbeddings(model=EMBEDDING_MODEL)
|
| 91 |
+
|
| 92 |
+
# Try to load existing index first
|
| 93 |
+
if os.path.exists(FAISS_INDEX_PATH):
|
| 94 |
+
print("Loading existing FAISS index...")
|
| 95 |
+
store = FAISS.load_local(FAISS_INDEX_PATH, embeddings, allow_dangerous_deserialization=True)
|
| 96 |
+
print(f"Loaded FAISS index with {store.index.ntotal} vectors")
|
| 97 |
+
return store
|
| 98 |
+
|
| 99 |
+
# Build new index
|
| 100 |
+
print("Building new FAISS index...")
|
| 101 |
+
store = FAISS.from_documents(chunks, embeddings)
|
| 102 |
+
store.save_local(FAISS_INDEX_PATH)
|
| 103 |
+
print(f"Created FAISS index with {store.index.ntotal} vectors")
|
| 104 |
+
return store
|
| 105 |
+
|
| 106 |
+
|
| 107 |
+
def build_chain(store):
|
| 108 |
+
"""Build the LangChain RetrievalQA chain."""
|
| 109 |
+
llm = ChatOpenAI(model=LLM_MODEL, temperature=0.2, max_tokens=500)
|
| 110 |
+
|
| 111 |
+
prompt_template = PromptTemplate(
|
| 112 |
+
input_variables=["context", "question"],
|
| 113 |
+
template="""You are the Khalifa University Library AI Assistant in Abu Dhabi, UAE.
|
| 114 |
+
KU means Khalifa University, NOT Kuwait University.
|
| 115 |
+
|
| 116 |
+
Use ONLY the following context from the Khalifa University Library website to answer the question.
|
| 117 |
+
If the context doesn't contain enough information, say "I don't have specific information about this in our library knowledge base" and suggest contacting Ask a Librarian at https://library.ku.ac.ae/AskUs
|
| 118 |
+
|
| 119 |
+
Always include relevant URLs from the context when available.
|
| 120 |
+
Keep answers concise (2-4 sentences) and helpful.
|
| 121 |
+
|
| 122 |
+
Context:
|
| 123 |
+
{context}
|
| 124 |
+
|
| 125 |
+
Question: {question}
|
| 126 |
+
|
| 127 |
+
Answer:"""
|
| 128 |
+
)
|
| 129 |
+
|
| 130 |
+
chain = RetrievalQA.from_chain_type(
|
| 131 |
+
llm=llm,
|
| 132 |
+
chain_type="stuff",
|
| 133 |
+
retriever=store.as_retriever(search_kwargs={"k": TOP_K}),
|
| 134 |
+
chain_type_kwargs={"prompt": prompt_template},
|
| 135 |
+
return_source_documents=True,
|
| 136 |
+
)
|
| 137 |
+
return chain
|
| 138 |
+
|
| 139 |
+
|
| 140 |
+
# ===== STARTUP =====
|
| 141 |
+
@asynccontextmanager
|
| 142 |
+
async def lifespan(app: FastAPI):
|
| 143 |
+
global qa_chain, vectorstore
|
| 144 |
+
print("=== Starting KU Library RAG Backend ===")
|
| 145 |
+
|
| 146 |
+
docs = load_documents()
|
| 147 |
+
if docs:
|
| 148 |
+
vectorstore = build_vectorstore(docs)
|
| 149 |
+
qa_chain = build_chain(vectorstore)
|
| 150 |
+
print("RAG chain ready!")
|
| 151 |
+
else:
|
| 152 |
+
print("WARNING: No knowledge files found. RAG will not work.")
|
| 153 |
+
print(f"Please add .txt files to the '{KNOWLEDGE_DIR}/' directory.")
|
| 154 |
+
|
| 155 |
+
yield
|
| 156 |
+
|
| 157 |
+
print("Shutting down...")
|
| 158 |
+
|
| 159 |
+
|
| 160 |
+
# ===== FASTAPI APP =====
|
| 161 |
+
app = FastAPI(title="KU Library RAG", lifespan=lifespan)
|
| 162 |
+
|
| 163 |
+
app.add_middleware(
|
| 164 |
+
CORSMiddleware,
|
| 165 |
+
allow_origins=["*"], # Restrict to your domains in production
|
| 166 |
+
allow_methods=["POST", "GET"],
|
| 167 |
+
allow_headers=["*"],
|
| 168 |
+
)
|
| 169 |
+
|
| 170 |
+
|
| 171 |
+
class QueryRequest(BaseModel):
|
| 172 |
+
question: str
|
| 173 |
+
top_k: int = 5
|
| 174 |
+
|
| 175 |
+
|
| 176 |
+
class SourceDoc(BaseModel):
|
| 177 |
+
title: str
|
| 178 |
+
source: str
|
| 179 |
+
snippet: str
|
| 180 |
+
|
| 181 |
+
|
| 182 |
+
class QueryResponse(BaseModel):
|
| 183 |
+
answer: str
|
| 184 |
+
sources: list[SourceDoc]
|
| 185 |
+
error: str | None = None
|
| 186 |
+
|
| 187 |
+
|
| 188 |
+
@app.get("/")
|
| 189 |
+
def health():
|
| 190 |
+
return {
|
| 191 |
+
"status": "ok",
|
| 192 |
+
"rag_ready": qa_chain is not None,
|
| 193 |
+
"service": "KU Library RAG Backend",
|
| 194 |
+
}
|
| 195 |
+
|
| 196 |
+
|
| 197 |
+
@app.post("/rag", response_model=QueryResponse)
|
| 198 |
+
async def rag_query(req: QueryRequest):
|
| 199 |
+
if not qa_chain:
|
| 200 |
+
return QueryResponse(
|
| 201 |
+
answer="RAG system not initialized. Knowledge base may be empty.",
|
| 202 |
+
sources=[],
|
| 203 |
+
error="No knowledge files loaded"
|
| 204 |
+
)
|
| 205 |
+
|
| 206 |
+
try:
|
| 207 |
+
result = qa_chain.invoke({"query": req.question})
|
| 208 |
+
answer = result.get("result", "No answer generated.")
|
| 209 |
+
source_docs = result.get("source_documents", [])
|
| 210 |
+
|
| 211 |
+
sources = []
|
| 212 |
+
seen = set()
|
| 213 |
+
for doc in source_docs:
|
| 214 |
+
src = doc.metadata.get("source", "")
|
| 215 |
+
title = doc.metadata.get("title", "")
|
| 216 |
+
key = src or title
|
| 217 |
+
if key and key not in seen:
|
| 218 |
+
seen.add(key)
|
| 219 |
+
sources.append(SourceDoc(
|
| 220 |
+
title=title,
|
| 221 |
+
source=src,
|
| 222 |
+
snippet=doc.page_content[:200] + "..."
|
| 223 |
+
))
|
| 224 |
+
|
| 225 |
+
return QueryResponse(answer=answer, sources=sources)
|
| 226 |
+
|
| 227 |
+
except Exception as e:
|
| 228 |
+
return QueryResponse(
|
| 229 |
+
answer="Sorry, I encountered an error processing your question.",
|
| 230 |
+
sources=[],
|
| 231 |
+
error=str(e)
|
| 232 |
+
)
|
| 233 |
+
|
| 234 |
+
|
| 235 |
+
@app.post("/rebuild")
|
| 236 |
+
async def rebuild_index():
|
| 237 |
+
"""Force rebuild the FAISS index from knowledge files."""
|
| 238 |
+
global qa_chain, vectorstore
|
| 239 |
+
try:
|
| 240 |
+
if os.path.exists(FAISS_INDEX_PATH):
|
| 241 |
+
import shutil
|
| 242 |
+
shutil.rmtree(FAISS_INDEX_PATH)
|
| 243 |
+
|
| 244 |
+
docs = load_documents()
|
| 245 |
+
if not docs:
|
| 246 |
+
return {"error": "No knowledge files found"}
|
| 247 |
+
|
| 248 |
+
vectorstore = build_vectorstore(docs)
|
| 249 |
+
qa_chain = build_chain(vectorstore)
|
| 250 |
+
return {"status": "ok", "chunks": vectorstore.index.ntotal}
|
| 251 |
+
except Exception as e:
|
| 252 |
+
return {"error": str(e)}
|