Update app.py
Browse files
app.py
CHANGED
|
@@ -1,377 +1,135 @@
|
|
| 1 |
-
|
| 2 |
-
|
| 3 |
-
|
| 4 |
-
This Gradio app compares:
|
| 5 |
-
1) LLM-Only (sampling) — answers directly from the model (can hallucinate)
|
| 6 |
-
2) RAG (strict deterministic) — retrieves context and answers ONLY from that context
|
| 7 |
-
- Deterministic decoding (no sampling)
|
| 8 |
-
- One-sentence answers, no explanations, no brackets/citations
|
| 9 |
-
- Guardrail for the "female US presidents" query
|
| 10 |
-
- Post-clean to remove any instruction echoes or meta-talk
|
| 11 |
-
"""
|
| 12 |
|
| 13 |
-
import os
|
| 14 |
-
import
|
| 15 |
-
|
| 16 |
-
from
|
| 17 |
|
|
|
|
|
|
|
|
|
|
|
|
|
| 18 |
from sentence_transformers import SentenceTransformer
|
| 19 |
-
|
| 20 |
|
| 21 |
# ----------------------------
|
| 22 |
-
#
|
| 23 |
# ----------------------------
|
| 24 |
-
|
| 25 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 26 |
|
| 27 |
-
CHUNK_SIZE = 50
|
| 28 |
-
CHUNK_OVERLAP = 5
|
| 29 |
-
TOP_K = 3
|
| 30 |
|
| 31 |
# ----------------------------
|
| 32 |
# Utilities
|
| 33 |
# ----------------------------
|
| 34 |
-
def
|
| 35 |
-
"""
|
| 36 |
-
|
| 37 |
-
|
| 38 |
-
|
| 39 |
-
"""Split long text into overlapping chunks for retrieval."""
|
| 40 |
-
text = normalize_ws(text)
|
| 41 |
-
if len(text) <= chunk_size:
|
| 42 |
-
return [text]
|
| 43 |
-
chunks, start = [], 0
|
| 44 |
-
while start < len(text):
|
| 45 |
-
end = min(len(text), start + chunk_size)
|
| 46 |
-
chunks.append(text[start:end])
|
| 47 |
-
if end == len(text):
|
| 48 |
-
break
|
| 49 |
-
start = max(0, end - overlap)
|
| 50 |
-
return chunks
|
| 51 |
-
|
| 52 |
-
def read_txt_or_md(file_obj: io.BytesIO, filename: str) -> str:
|
| 53 |
-
"""Read .txt/.md files as UTF-8; ignore other types for classroom simplicity."""
|
| 54 |
-
ext = os.path.splitext(filename.lower())[1]
|
| 55 |
-
if ext not in [".txt", ".md"]:
|
| 56 |
-
return ""
|
| 57 |
try:
|
| 58 |
-
|
|
|
|
|
|
|
|
|
|
| 59 |
except Exception:
|
| 60 |
-
|
| 61 |
-
|
| 62 |
-
|
| 63 |
-
|
| 64 |
-
|
| 65 |
-
|
| 66 |
-
|
| 67 |
-
|
| 68 |
-
|
| 69 |
-
|
| 70 |
-
|
| 71 |
-
|
| 72 |
-
|
| 73 |
-
|
| 74 |
-
|
| 75 |
-
|
| 76 |
-
|
| 77 |
-
|
| 78 |
-
|
| 79 |
-
|
| 80 |
-
|
| 81 |
-
|
| 82 |
-
|
| 83 |
-
|
| 84 |
-
|
| 85 |
-
|
| 86 |
-
|
| 87 |
-
|
| 88 |
-
|
| 89 |
-
|
| 90 |
-
|
| 91 |
-
|
| 92 |
-
|
| 93 |
-
|
| 94 |
-
|
| 95 |
-
|
| 96 |
-
|
| 97 |
-
|
| 98 |
-
|
| 99 |
-
|
| 100 |
-
|
| 101 |
-
|
| 102 |
-
|
| 103 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 104 |
|
| 105 |
-
embeds = embedder.encode(chunks, convert_to_numpy=True, normalize_embeddings=True)
|
| 106 |
-
d = embeds.shape[1]
|
| 107 |
-
index = faiss.IndexFlatIP(d) # inner product; with normalized vectors = cosine similarity
|
| 108 |
-
index.add(embeds)
|
| 109 |
-
|
| 110 |
-
return cls(
|
| 111 |
-
corpus_docs=seed_docs,
|
| 112 |
-
corpus_chunks=chunks,
|
| 113 |
-
embedder=embedder,
|
| 114 |
-
d=d,
|
| 115 |
-
index=index,
|
| 116 |
-
matrix=embeds
|
| 117 |
-
)
|
| 118 |
-
|
| 119 |
-
def add_documents(self, new_docs: List[str]):
|
| 120 |
-
"""Add user-provided docs: clean → chunk → embed → index."""
|
| 121 |
-
clean = [normalize_ws(x) for x in new_docs if x and normalize_ws(x)]
|
| 122 |
-
if not clean:
|
| 123 |
-
return
|
| 124 |
-
self.corpus_docs.extend(clean)
|
| 125 |
-
|
| 126 |
-
new_chunks = []
|
| 127 |
-
for doc in clean:
|
| 128 |
-
new_chunks.extend(chunk_text(doc))
|
| 129 |
-
if not new_chunks:
|
| 130 |
-
return
|
| 131 |
-
|
| 132 |
-
new_embeds = self.embedder.encode(new_chunks, convert_to_numpy=True, normalize_embeddings=True)
|
| 133 |
-
self.index.add(new_embeds)
|
| 134 |
-
|
| 135 |
-
import numpy as np
|
| 136 |
-
self.matrix = np.vstack([self.matrix, new_embeds]) if self.matrix is not None else new_embeds
|
| 137 |
-
self.corpus_chunks.extend(new_chunks)
|
| 138 |
-
|
| 139 |
-
def retrieve(self, query: str, k: int = TOP_K) -> List[Tuple[float, str]]:
|
| 140 |
-
"""Return top-k (score, chunk) pairs for the query."""
|
| 141 |
-
if not query.strip() or len(self.corpus_chunks) == 0:
|
| 142 |
-
return []
|
| 143 |
-
q = self.embedder.encode([normalize_ws(query)], convert_to_numpy=True, normalize_embeddings=True)
|
| 144 |
-
scores, idxs = self.index.search(q, min(k, len(self.corpus_chunks)))
|
| 145 |
-
hits = []
|
| 146 |
-
for score, idx in zip(scores[0], idxs[0]):
|
| 147 |
-
if idx == -1:
|
| 148 |
-
continue
|
| 149 |
-
hits.append((float(score), self.corpus_chunks[idx]))
|
| 150 |
-
return hits
|
| 151 |
|
| 152 |
# ----------------------------
|
| 153 |
-
#
|
| 154 |
-
# ----------------------------
|
| 155 |
-
embedder = SentenceTransformer(EMBED_MODEL_ID)
|
| 156 |
-
rag_store = RAGStore.create(embedder)
|
| 157 |
-
generator = pipeline("text2text-generation", model=GEN_MODEL_ID)
|
| 158 |
-
|
| 159 |
-
# ----------------------------
|
| 160 |
-
# LLM-only (sampling) — baseline
|
| 161 |
-
# ----------------------------
|
| 162 |
-
def generate_llm_only(question: str, max_new_tokens: int = 128, temperature: float = 0.6, top_p: float = 0.9) -> str:
|
| 163 |
-
if not question.strip():
|
| 164 |
-
return "Please enter a question."
|
| 165 |
-
out = generator(
|
| 166 |
-
question.strip(),
|
| 167 |
-
max_new_tokens=int(max_new_tokens),
|
| 168 |
-
do_sample=True,
|
| 169 |
-
temperature=float(temperature),
|
| 170 |
-
top_p=float(top_p),
|
| 171 |
-
)
|
| 172 |
-
return out[0]["generated_text"]
|
| 173 |
-
|
| 174 |
-
# ----------------------------
|
| 175 |
-
# STRICT deterministic RAG (concise + clean, no brackets)
|
| 176 |
# ----------------------------
|
| 177 |
STRICT_RAG_SYSTEM = (
|
| 178 |
-
|
| 179 |
-
|
| 180 |
-
"Do not include citations, brackets, or numbers in your answer. "
|
| 181 |
-
"If the context does not contain the answer, reply exactly: "
|
| 182 |
-
"\"I don't know based on the provided context.\" "
|
| 183 |
-
"Do not explain your reasoning. Do not include any extra text."
|
| 184 |
-
)
|
| 185 |
-
|
| 186 |
-
def _mentions_no_female_president(text: str) -> bool:
|
| 187 |
-
t = text.lower()
|
| 188 |
-
return ("never had a female president" in t) or ("no female president" in t)
|
| 189 |
-
|
| 190 |
-
def _female_president_guard(question: str, context_chunks: List[str]) -> Optional[str]:
|
| 191 |
-
"""
|
| 192 |
-
If user asks about female US presidents and our context asserts 'none',
|
| 193 |
-
return the definitive answer immediately.
|
| 194 |
-
"""
|
| 195 |
-
q = question.lower()
|
| 196 |
-
if ("female" in q or "woman" in q or "women" in q) and ("president" in q) and ("united states" in q or "u.s." in q or "us " in q):
|
| 197 |
-
combined = " ".join(context_chunks).lower()
|
| 198 |
-
if _mentions_no_female_president(combined):
|
| 199 |
-
return "As of 2025, the United States has never had a female president."
|
| 200 |
-
return None
|
| 201 |
-
|
| 202 |
-
def _post_clean(answer: str) -> str:
|
| 203 |
-
"""
|
| 204 |
-
Remove any instruction echoes or meta-justifications.
|
| 205 |
-
Keep only the first sentence; strip brackets/quotes; normalize spaces.
|
| 206 |
-
"""
|
| 207 |
-
a = answer.strip()
|
| 208 |
-
|
| 209 |
-
# Trim if model echoed "Answer:" or instruction
|
| 210 |
-
if "Answer:" in a:
|
| 211 |
-
a = a.split("Answer:", 1)[-1].strip()
|
| 212 |
-
|
| 213 |
-
lowers = a.lower()
|
| 214 |
-
bad_starts = [
|
| 215 |
-
"answer only using the provided context",
|
| 216 |
-
"you are a careful assistant",
|
| 217 |
-
"this answer is correct",
|
| 218 |
-
"based solely",
|
| 219 |
-
"therefore,",
|
| 220 |
-
"therefore "
|
| 221 |
-
]
|
| 222 |
-
for bs in bad_starts:
|
| 223 |
-
if lowers.startswith(bs):
|
| 224 |
-
a = a.split(".", 1)[-1].strip() or a
|
| 225 |
-
break
|
| 226 |
-
|
| 227 |
-
# Strip bracketed numeric citations like [1], [23], etc.
|
| 228 |
-
a = re.sub(r"\s*\[\d+\]\s*", " ", a).strip()
|
| 229 |
-
|
| 230 |
-
# Keep only the first sentence
|
| 231 |
-
if "." in a:
|
| 232 |
-
a = a.split(".", 1)[0].strip() + "."
|
| 233 |
-
|
| 234 |
-
# Strip surrounding quotes
|
| 235 |
-
a = a.strip(" \"'")
|
| 236 |
-
|
| 237 |
-
# Normalize internal whitespace
|
| 238 |
-
a = normalize_ws(a)
|
| 239 |
-
|
| 240 |
-
# If post-clean left us empty or only brackets, abstain
|
| 241 |
-
if not a or re.fullmatch(r"\[\d+\]", a):
|
| 242 |
-
a = "I don't know based on the provided context."
|
| 243 |
-
|
| 244 |
-
return a
|
| 245 |
-
|
| 246 |
-
def generate_rag_strict(question: str, k: int = TOP_K, max_new_tokens: int = 80):
|
| 247 |
-
if not question.strip():
|
| 248 |
-
return "Please enter a question.", []
|
| 249 |
-
|
| 250 |
-
# 1) Retrieve
|
| 251 |
-
hits = rag_store.retrieve(question, k=k)
|
| 252 |
-
chunks = [c for _, c in hits]
|
| 253 |
-
|
| 254 |
-
# 2) Guardrail: female-president question
|
| 255 |
-
override = _female_president_guard(question, chunks)
|
| 256 |
-
if override is not None:
|
| 257 |
-
return override, hits
|
| 258 |
-
|
| 259 |
-
# 3) Build context with bullets (no bracket labels)
|
| 260 |
-
context = "\n\n".join([f"- {c}" for c in chunks]) if chunks else ""
|
| 261 |
-
|
| 262 |
-
# 4) Build strict prompt
|
| 263 |
-
prompt = (
|
| 264 |
-
f"{STRICT_RAG_SYSTEM}\n\n"
|
| 265 |
-
f"Context:\n{context}\n\n"
|
| 266 |
-
f"Question: {question.strip()}\n"
|
| 267 |
-
f"Answer:"
|
| 268 |
-
)
|
| 269 |
-
|
| 270 |
-
# 5) Deterministic decoding (no sampling)
|
| 271 |
-
out = generator(
|
| 272 |
-
prompt,
|
| 273 |
-
max_new_tokens=int(max_new_tokens),
|
| 274 |
-
do_sample=False, # no randomness
|
| 275 |
-
num_beams=4, # explore a few safe paths
|
| 276 |
-
early_stopping=True,
|
| 277 |
-
length_penalty=0.9,
|
| 278 |
-
no_repeat_ngram_size=3,
|
| 279 |
-
)
|
| 280 |
-
raw = out[0]["generated_text"]
|
| 281 |
-
|
| 282 |
-
# 6) Post-clean the model text (remove echoes/explanations/brackets)
|
| 283 |
-
answer = _post_clean(raw)
|
| 284 |
-
|
| 285 |
-
# 7) Enforce abstention if no context present
|
| 286 |
-
if not context.strip() and "i don't know based on the provided context" not in answer.lower():
|
| 287 |
-
answer = "I don't know based on the provided context."
|
| 288 |
-
|
| 289 |
-
return answer, hits
|
| 290 |
-
|
| 291 |
-
# ----------------------------
|
| 292 |
-
# Gradio UI
|
| 293 |
-
# ----------------------------
|
| 294 |
-
with gr.Blocks(fill_height=True, analytics_enabled=False) as demo:
|
| 295 |
-
gr.Markdown(
|
| 296 |
-
"# 🔎 Retrieval-Augmented Generation (RAG) — Presidents Edition\n"
|
| 297 |
-
"Compare **LLM-only** (sampling) vs **RAG-grounded** (strict & deterministic). "
|
| 298 |
-
"Add more facts to the corpus at left, then ask questions at right.\n\n"
|
| 299 |
-
"_Tip: keep outputs short on CPU. This demo may be incorrect; always verify facts._"
|
| 300 |
-
)
|
| 301 |
-
|
| 302 |
-
with gr.Row():
|
| 303 |
-
# Left: corpus management
|
| 304 |
-
with gr.Column(scale=1):
|
| 305 |
-
gr.Markdown("### 📚 Corpus\nPaste text or upload .txt/.md to add to the knowledge base.")
|
| 306 |
-
paste_box = gr.Textbox(lines=8, label="Paste text (optional)")
|
| 307 |
-
upload = gr.File(label="Upload .txt or .md", file_types=[".txt", ".md"], file_count="multiple")
|
| 308 |
-
add_btn = gr.Button("Add to Corpus", variant="secondary")
|
| 309 |
-
corpus_count = gr.Markdown(f"**Chunks indexed:** {len(rag_store.corpus_chunks)}")
|
| 310 |
-
|
| 311 |
-
# Right: Q&A panels
|
| 312 |
-
with gr.Column(scale=2):
|
| 313 |
-
question = gr.Textbox(
|
| 314 |
-
label="Your question",
|
| 315 |
-
placeholder="Example: Who is the current president of the United States?",
|
| 316 |
-
lines=3
|
| 317 |
-
)
|
| 318 |
-
|
| 319 |
-
with gr.Row():
|
| 320 |
-
# LLM-only (sampling)
|
| 321 |
-
with gr.Column():
|
| 322 |
-
gr.Markdown("#### 🤖 LLM-Only (Sampling)")
|
| 323 |
-
max_new_llm = gr.Slider(32, 256, value=128, step=8, label="Max new tokens")
|
| 324 |
-
temp_llm = gr.Slider(0.0, 1.5, value=0.6, step=0.05, label="Temperature")
|
| 325 |
-
topp_llm = gr.Slider(0.1, 1.0, value=0.9, step=0.05, label="Top-p")
|
| 326 |
-
llm_btn = gr.Button("Generate (LLM-Only)")
|
| 327 |
-
llm_out = gr.Textbox(label="LLM-Only Answer", lines=8)
|
| 328 |
-
|
| 329 |
-
# RAG (strict deterministic)
|
| 330 |
-
with gr.Column():
|
| 331 |
-
gr.Markdown("#### 📎 RAG-Grounded (Strict Deterministic)")
|
| 332 |
-
topk = gr.Slider(1, 8, value=3, step=1, label="Top-K chunks")
|
| 333 |
-
max_new_rag = gr.Slider(32, 256, value=80, step=8, label="Max new tokens")
|
| 334 |
-
temp_rag = gr.Slider(0.0, 1.5, value=0.6, step=0.05, label="Temperature (unused)", interactive=False)
|
| 335 |
-
topp_rag = gr.Slider(0.1, 1.0, value=0.9, step=0.05, label="Top-p (unused)", interactive=False)
|
| 336 |
-
rag_btn = gr.Button("Generate (RAG)")
|
| 337 |
-
rag_out = gr.Textbox(label="RAG Answer", lines=8)
|
| 338 |
-
retrieved = gr.Markdown("")
|
| 339 |
-
|
| 340 |
-
# ---------------- Callbacks ----------------
|
| 341 |
-
def _add_to_corpus(pasted: str, files: List[gr.File]) -> str:
|
| 342 |
-
"""Add pasted text and uploaded files to the corpus; update chunk count."""
|
| 343 |
-
docs = []
|
| 344 |
-
if pasted and pasted.strip():
|
| 345 |
-
docs.append(pasted)
|
| 346 |
-
if files:
|
| 347 |
-
for f in files:
|
| 348 |
-
try:
|
| 349 |
-
with open(f.name, "rb") as fh:
|
| 350 |
-
content = read_txt_or_md(io.BytesIO(fh.read()), f.name)
|
| 351 |
-
if content:
|
| 352 |
-
docs.append(content)
|
| 353 |
-
except Exception:
|
| 354 |
-
continue
|
| 355 |
-
if docs:
|
| 356 |
-
rag_store.add_documents(docs)
|
| 357 |
-
return f"**Chunks indexed:** {len(rag_store.corpus_chunks)}"
|
| 358 |
-
|
| 359 |
-
def _llm_only(q, mx, t, p):
|
| 360 |
-
return generate_llm_only(q, mx, t, p)
|
| 361 |
-
|
| 362 |
-
def _rag(q, k, mx, _t_unused, _p_unused):
|
| 363 |
-
ans, hits = generate_rag_strict(q, k=int(k), max_new_tokens=int(mx))
|
| 364 |
-
if hits:
|
| 365 |
-
md = "##### Retrieved Chunks\n" + "\n".join([f"- (score={score:.3f}) {chunk}" for score, chunk in hits])
|
| 366 |
-
else:
|
| 367 |
-
md = "_No chunks retrieved._"
|
| 368 |
-
return ans, md
|
| 369 |
-
|
| 370 |
-
# Wire UI
|
| 371 |
-
add_btn.click(_add_to_corpus, inputs=[paste_box, upload], outputs=[corpus_count])
|
| 372 |
-
llm_btn.click(_llm_only, inputs=[question, max_new_llm, temp_llm, topp_llm], outputs=[llm_out])
|
| 373 |
-
rag_btn.click(_rag, inputs=[question, topk, max_new_rag, temp_rag, topp_rag], outputs=[rag_out, retrieved])
|
| 374 |
-
|
| 375 |
-
# Launch (HF Spaces will run this automatically)
|
| 376 |
-
if __name__ == "__main__":
|
| 377 |
-
demo.launch()
|
|
|
|
| 1 |
+
# app.py — ITC 754 Gradio demo (Deterministic + RAG with Beams & Length Penalty)
|
| 2 |
+
# Place in: ~/ITC754/hf-demo/app.py
|
| 3 |
+
# Corpus: ~/ITC754/hf-demo/corpus/ (put a few .txt files here)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 4 |
|
| 5 |
+
import os
|
| 6 |
+
import glob
|
| 7 |
+
import hashlib
|
| 8 |
+
from typing import List, Dict, Any, Optional
|
| 9 |
|
| 10 |
+
import numpy as np
|
| 11 |
+
import faiss
|
| 12 |
+
import gradio as gr
|
| 13 |
+
from transformers import AutoTokenizer, AutoModelForCausalLM, pipeline
|
| 14 |
from sentence_transformers import SentenceTransformer
|
| 15 |
+
|
| 16 |
|
| 17 |
# ----------------------------
|
| 18 |
+
# Model configuration
|
| 19 |
# ----------------------------
|
| 20 |
+
GEN_MODEL_NAME = os.getenv("GEN_MODEL_NAME", "microsoft/Phi-3-mini-4k-instruct")
|
| 21 |
+
EMB_MODEL_NAME = os.getenv("EMB_MODEL_NAME", "sentence-transformers/all-MiniLM-L6-v2")
|
| 22 |
+
|
| 23 |
+
_tok = None
|
| 24 |
+
_mdl = None
|
| 25 |
+
_pipe = None
|
| 26 |
+
_emb = None
|
| 27 |
+
_faiss = None
|
| 28 |
+
_docs: List[Dict[str, Any]] = []
|
| 29 |
|
|
|
|
|
|
|
|
|
|
| 30 |
|
| 31 |
# ----------------------------
|
| 32 |
# Utilities
|
| 33 |
# ----------------------------
|
| 34 |
+
def seed_all(seed: Optional[int]) -> None:
|
| 35 |
+
"""Best-effort seeding that works even if torch isn't present."""
|
| 36 |
+
import random
|
| 37 |
+
s = 0 if seed is None else seed
|
| 38 |
+
random.seed(s)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 39 |
try:
|
| 40 |
+
import torch
|
| 41 |
+
torch.manual_seed(s)
|
| 42 |
+
if torch.cuda.is_available():
|
| 43 |
+
torch.cuda.manual_seed_all(s)
|
| 44 |
except Exception:
|
| 45 |
+
pass
|
| 46 |
+
|
| 47 |
+
|
| 48 |
+
def get_pipe():
|
| 49 |
+
"""Lazy-load a simple text-generation pipeline."""
|
| 50 |
+
global _pipe, _tok, _mdl
|
| 51 |
+
if _pipe is None:
|
| 52 |
+
_tok = AutoTokenizer.from_pretrained(GEN_MODEL_NAME)
|
| 53 |
+
_mdl = AutoModelForCausalLM.from_pretrained(GEN_MODEL_NAME)
|
| 54 |
+
_pipe = pipeline("text-generation", model=_mdl, tokenizer=_tok)
|
| 55 |
+
return _pipe
|
| 56 |
+
|
| 57 |
+
|
| 58 |
+
def load_corpus(cdir: str = "./corpus") -> List[Dict[str, Any]]:
|
| 59 |
+
"""Load *.txt corpus files into memory."""
|
| 60 |
+
os.makedirs(cdir, exist_ok=True)
|
| 61 |
+
out: List[Dict[str, Any]] = []
|
| 62 |
+
for p in sorted(glob.glob(os.path.join(cdir, "*.txt"))):
|
| 63 |
+
try:
|
| 64 |
+
with open(p, "r", encoding="utf-8", errors="ignore") as f:
|
| 65 |
+
txt = f.read().strip()
|
| 66 |
+
if txt:
|
| 67 |
+
out.append(
|
| 68 |
+
{"id": hashlib.sha1(p.encode()).hexdigest()[:8], "text": txt, "path": p}
|
| 69 |
+
)
|
| 70 |
+
except Exception:
|
| 71 |
+
# Skip unreadable files
|
| 72 |
+
pass
|
| 73 |
+
return out
|
| 74 |
+
|
| 75 |
+
|
| 76 |
+
def get_emb():
|
| 77 |
+
"""Lazy-load the sentence embedding model."""
|
| 78 |
+
global _emb
|
| 79 |
+
if _emb is None:
|
| 80 |
+
_emb = SentenceTransformer(EMB_MODEL_NAME)
|
| 81 |
+
return _emb
|
| 82 |
+
|
| 83 |
+
|
| 84 |
+
def embed(texts: List[str]) -> np.ndarray:
|
| 85 |
+
"""Create normalized embeddings (cosine similarity via inner product)."""
|
| 86 |
+
E = get_emb()
|
| 87 |
+
vec = E.encode(texts, normalize_embeddings=True, convert_to_numpy=True)
|
| 88 |
+
return vec.astype(np.float32)
|
| 89 |
+
|
| 90 |
+
|
| 91 |
+
def build_index(docs: List[Dict[str, Any]]) -> None:
|
| 92 |
+
"""Build an inner-product FAISS index."""
|
| 93 |
+
global _faiss
|
| 94 |
+
if not docs:
|
| 95 |
+
# Placeholder index with default dim used by MiniLM
|
| 96 |
+
_faiss = faiss.IndexFlatIP(384)
|
| 97 |
+
return
|
| 98 |
+
V = embed([d["text"] for d in docs])
|
| 99 |
+
_faiss = faiss.IndexFlatIP(V.shape[1])
|
| 100 |
+
_faiss.add(V)
|
| 101 |
+
|
| 102 |
+
|
| 103 |
+
def retrieve(q: str, k: int = 4) -> List[Dict[str, Any]]:
|
| 104 |
+
"""Return top-k docs with similarity scores."""
|
| 105 |
+
global _docs, _faiss
|
| 106 |
+
if _faiss is None or not _docs:
|
| 107 |
+
return []
|
| 108 |
+
qv = embed([q])
|
| 109 |
+
scores, idxs = _faiss.search(qv, min(k, len(_docs)))
|
| 110 |
+
out: List[Dict[str, Any]] = []
|
| 111 |
+
for s, i in zip(scores[0], idxs[0]):
|
| 112 |
+
if i < 0:
|
| 113 |
+
continue
|
| 114 |
+
d = dict(_docs[i])
|
| 115 |
+
d["score"] = float(s)
|
| 116 |
+
out.append(d)
|
| 117 |
+
return out
|
| 118 |
+
|
| 119 |
+
|
| 120 |
+
def fmt_ctx(snips: List[Dict[str, Any]]) -> str:
|
| 121 |
+
"""Label retrieved chunks [C1], [C2], ... for inline citations."""
|
| 122 |
+
lines: List[str] = []
|
| 123 |
+
for i, s in enumerate(snips, 1):
|
| 124 |
+
lines.append(f"[C{i}] (doc={s['id']}, score={s['score']:.3f})")
|
| 125 |
+
lines.append(s["text"].strip())
|
| 126 |
+
lines.append("") # blank line between items
|
| 127 |
+
return "\n".join(lines).strip()
|
| 128 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 129 |
|
| 130 |
# ----------------------------
|
| 131 |
+
# RAG prompt (relaxed strict)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 132 |
# ----------------------------
|
| 133 |
STRICT_RAG_SYSTEM = (
|
| 134 |
+
'Role: You are a careful assistant. Your first duty is factual fidelity to the provided CONTEXT; '
|
| 135 |
+
'your second
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|