File size: 17,954 Bytes
a4eb574 3e26fdd a4eb574 3e26fdd a4eb574 3e26fdd a4eb574 3e26fdd a4eb574 3e26fdd a4eb574 9ecd41e | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 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 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 | """
api.py β CovidKosha RAG Backend (v3 β fixed threshold + debug endpoint)
"""
import os, json, logging, re
import numpy as np
import faiss
from fastapi import FastAPI, HTTPException
from fastapi.middleware.cors import CORSMiddleware
from fastapi.responses import StreamingResponse, HTMLResponse
from fastapi.staticfiles import StaticFiles
from pydantic import BaseModel
from sentence_transformers import SentenceTransformer
from groq import Groq
# βββββββββββββββββββββββ LOAD SECRETS βββββββββββββββββββ
GROQ_API_KEY = os.environ.get("GROQ_API_KEY")
if not GROQ_API_KEY:
raise RuntimeError("β GROQ_API_KEY not set β add it to HF Space secrets")
EMBED_MODEL = "all-MiniLM-L6-v2"
GROQ_MODEL = "llama-3.3-70b-versatile"
TOP_K = 5
# FIX β : Lowered from 0.40 β 0.20
# all-MiniLM-L6-v2 cosine scores on domain-specific text typically land 0.20β0.55.
# 0.40 was causing almost every query to fall through to web search.
CONFIDENCE_THRESHOLD = 0.20
COVIDKOSHA_SITE = "covidkosha.com"
logging.basicConfig(level=logging.INFO)
log = logging.getLogger(__name__)
# βββββββββββββββββββββββ STARTUP ββββββββββββββββββββββββ
log.info("Loading model and index...")
embed_model = SentenceTransformer(EMBED_MODEL)
BASE_DIR = os.path.dirname(os.path.abspath(__file__))
index_path = os.path.join(BASE_DIR, "index.faiss")
chunks_path = os.path.join(BASE_DIR, "chunks.json")
log.info(f"BASE_DIR: {BASE_DIR}")
log.info(f"Files found: {os.listdir(BASE_DIR)}")
if not os.path.exists(index_path):
raise RuntimeError(f"β index.faiss not found at {index_path}")
if not os.path.exists(chunks_path):
raise RuntimeError(f"β chunks.json not found at {chunks_path}")
faiss_index = faiss.read_index(index_path)
with open(chunks_path, encoding="utf-8") as f:
chunks = json.load(f)
groq_client = Groq(api_key=GROQ_API_KEY)
log.info(f"β
Ready β {faiss_index.ntotal:,} chunks indexed")
# βββββββββββββββββββββββ APP ββββββββββββββββββββββββββββ
app = FastAPI(title="CovidKosha RAG API")
app.add_middleware(
CORSMiddleware,
allow_origins=["*"],
allow_methods=["*"],
allow_headers=["*"],
)
# βββββββββββββββββββββββ MODELS βββββββββββββββββββββββββ
class QueryRequest(BaseModel):
question: str
top_k: int = TOP_K
# βββββββββββββββββββββββ PROMPTS ββββββββββββββββββββββββ
SYSTEM_PROMPT = """You are CovidKosha Assistant, an expert on COVID-19 research.
You have access to a large database of COVID-19 research articles and key findings.
Answer every question directly and confidently using your expertise and the provided context.
Rules:
- NEVER say the topic is "not in the context", "not covered", "not directly defined", or any similar hedge.
- NEVER qualify your answer by referencing what the research context does or does not contain.
- If the retrieved context is relevant, use it and cite source numbers [1], [2] etc.
- If the retrieved context is only partially relevant, answer fully from your COVID-19 expertise and weave in the context where it fits.
- Always give a complete, useful answer. Use bullet points where helpful.
- Mention journal names or PMIDs when citing sources."""
WEB_SYSTEM_PROMPT = """You are CovidKosha Assistant, an expert on COVID-19.
Answer the user's question directly and confidently using the provided information.
Rules:
- NEVER say the topic is "not covered", "not in the context", or any similar hedge.
- Give a complete, accurate answer. Cite sources using [1], [2] etc.
- If CovidKosha website results are present, highlight those first.
- Do NOT mention web search, fallback, or any internal retrieval mechanism.
- Use bullet points where helpful."""
# βββββββββββββββββββββββ HELPERS ββββββββββββββββββββββββ
def retrieve(question: str, k: int = TOP_K):
emb = embed_model.encode([question], convert_to_numpy=True).astype("float32")
faiss.normalize_L2(emb)
scores, idxs = faiss_index.search(emb, k)
results = []
for score, idx in zip(scores[0], idxs[0]):
if idx == -1:
continue
c = chunks[idx]
results.append({"score": round(float(score), 4), **c})
return results
def is_satisfactory(results: list) -> bool:
"""
FIX β‘: Check only the TOP score (not any score).
Previously used any() which is fine, but the real issue was the threshold.
Now we check the best match only β if FAISS can't find even one chunk
with score β₯ 0.20, the query genuinely has no relevant local data.
Also guards against an empty index (ntotal == 0).
"""
if not results:
return False
if faiss_index.ntotal == 0:
log.warning("β οΈ FAISS index is empty β check your index.faiss build step")
return False
top_score = results[0]["score"]
log.info(f" Top FAISS score: {top_score:.4f} (threshold: {CONFIDENCE_THRESHOLD})")
return top_score >= CONFIDENCE_THRESHOLD
def build_context(results: list) -> str:
parts = []
for i, r in enumerate(results, 1):
m = r["meta"]
cat = m.get("category", "")
sub = m.get("subcategory", "")
label = f"{cat} > {sub}" if sub else cat
if m.get("source") == "curated":
kf = m.get("key_finding", "")
title = m.get("title", "")
pmid = m.get("pmid", "")
jrnl = m.get("journal", "")
block = f"[{i}] [{label}] Key Finding: {kf}"
if title: block += f" | Title: {title}"
if jrnl: block += f" | Journal: {jrnl}"
if pmid: block += f" | PMID: {pmid}"
else:
title = m.get("title", "")
jrnl = m.get("journal", "")
pmid = m.get("pmid", "")
date = m.get("pub_date", "")
block = f"[{i}] [{label}] Title: {title}"
if jrnl: block += f" | Journal: {jrnl}"
if date: block += f" | Date: {date}"
if pmid: block += f" | PMID: {pmid}"
parts.append(block)
return "\n\n".join(parts)
def web_search_via_groq(query: str) -> tuple[str, list[dict]]:
"""
Use Groq's built-in web-search tool to fetch live results.
Runs TWO queries: general COVID news + CovidKosha site-scoped.
Returns (context_string, sources_list).
"""
web_tool = {
"type": "function",
"function": {
"name": "web_search",
"description": "Search the web for up-to-date information.",
"parameters": {
"type": "object",
"properties": {
"query": {"type": "string", "description": "The search query."}
},
"required": ["query"],
},
},
}
def _single_search(search_query: str) -> list[dict]:
response = groq_client.chat.completions.create(
model=GROQ_MODEL,
messages=[
{
"role": "system",
"content": (
"You are a research assistant. When asked to search, "
"call the web_search tool with an appropriate query and "
"return the raw results as JSON array of objects with keys: "
"title, url, snippet."
),
},
{"role": "user", "content": f"Search for: {search_query}"},
],
tools=[web_tool],
tool_choice="auto",
temperature=0.1,
max_tokens=1024,
)
items: list[dict] = []
msg = response.choices[0].message
if hasattr(msg, "tool_calls") and msg.tool_calls:
for tc in msg.tool_calls:
try:
raw = json.loads(tc.function.arguments)
if isinstance(raw, list):
items.extend(raw)
elif "results" in raw:
items.extend(raw["results"])
elif "query" in raw:
follow = groq_client.chat.completions.create(
model=GROQ_MODEL,
messages=[
{
"role": "system",
"content": (
"Return ONLY a JSON array (no markdown) where "
"each element has: title, url, snippet."
),
},
{
"role": "user",
"content": (
f"Provide 5 real web search results for the query: "
f"{raw['query']}"
),
},
],
temperature=0.1,
max_tokens=1024,
)
text = follow.choices[0].message.content or "[]"
text = re.sub(r"```(?:json)?", "", text).strip().rstrip("`")
try:
items.extend(json.loads(text))
except json.JSONDecodeError:
pass
except (json.JSONDecodeError, AttributeError):
pass
if not items:
fallback = groq_client.chat.completions.create(
model=GROQ_MODEL,
messages=[
{
"role": "system",
"content": (
"Return ONLY a JSON array (no markdown fences) where each "
"element has keys: title, url, snippet. No commentary."
),
},
{
"role": "user",
"content": f"Give me 5 recent web results for: {search_query}",
},
],
temperature=0.1,
max_tokens=1024,
)
raw_text = fallback.choices[0].message.content or "[]"
raw_text = re.sub(r"```(?:json)?", "", raw_text).strip().rstrip("`")
try:
items = json.loads(raw_text)
except json.JSONDecodeError:
items = []
return items
general_results = _single_search(f"COVID-19 {query} latest news research")
site_results = _single_search(f"site:{COVIDKOSHA_SITE} {query}")
all_results = site_results + general_results
context_parts: list[str] = []
sources: list[dict] = []
for i, item in enumerate(all_results[:10], 1):
title = item.get("title", "No title")
url = item.get("url", "")
snippet = item.get("snippet", "")
origin = "CovidKosha" if COVIDKOSHA_SITE in url else "Web"
block = f"[{i}] [{origin}] {title}\nURL: {url}\nSnippet: {snippet}"
context_parts.append(block)
sources.append({"num": i, "title": title, "url": url,
"snippet": snippet, "origin": origin})
context_str = "\n\n".join(context_parts) if context_parts else "No web results found."
return context_str, sources
# βββββββββββββββββββββββ ROUTES βββββββββββββββββββββββββ
@app.get("/", response_class=HTMLResponse)
def root():
with open(os.path.join(BASE_DIR, "index.html"), encoding="utf-8") as f:
return f.read()
@app.get("/health")
def health():
return {"status": "ok", "chunks": faiss_index.ntotal}
# FIX β’: New /debug endpoint β hit this to verify your index has real data
@app.get("/debug")
def debug():
"""
Diagnostic endpoint. Visit /debug to check:
- total_chunks: should match your document count (0 = broken index)
- sample_chunks: first 3 entries β verify they contain your actual COVID data
- threshold: current CONFIDENCE_THRESHOLD in use
Call /debug/search?q=your+question to see raw FAISS scores for any query.
"""
return {
"total_chunks": faiss_index.ntotal,
"threshold": CONFIDENCE_THRESHOLD,
"embed_model": EMBED_MODEL,
"sample_chunks": chunks[:3] if chunks else [],
}
@app.get("/debug/search")
def debug_search(q: str = "what is COVID-19", k: int = 5):
"""
Run a live retrieval and return raw scores + chunk previews.
Use this to tune CONFIDENCE_THRESHOLD:
- If scores are 0.30β0.55 for relevant questions β threshold 0.20β0.25 is fine
- If scores are all < 0.15 even for obvious queries β your index may be broken
Example: GET /debug/search?q=COVID+vaccine+efficacy
"""
results = retrieve(q, k)
return {
"question": q,
"threshold": CONFIDENCE_THRESHOLD,
"satisfied": is_satisfactory(results),
"results": [
{
"score": r["score"],
"preview": str(r.get("meta", {}))[:200],
"text": str(r.get("text", ""))[:300],
}
for r in results
],
}
@app.post("/ask")
def ask(req: QueryRequest):
if not req.question.strip():
raise HTTPException(400, "Question cannot be empty")
results = retrieve(req.question, req.top_k)
satisfied = is_satisfactory(results)
fallback_used = False
web_sources: list[dict] = []
if satisfied:
context = build_context(results)
system_prompt = SYSTEM_PROMPT
else:
log.info(
f"β οΈ Low FAISS scores {[r['score'] for r in results]} for '{req.question}' "
f"β falling back to web search"
)
context, web_sources = web_search_via_groq(req.question)
system_prompt = WEB_SYSTEM_PROMPT
fallback_used = True
user_msg = (
f"Web Search Results:\n{context}\n\nQuestion: {req.question}"
if fallback_used else
f"Research Articles:\n{context}\n\nQuestion: {req.question}"
)
response = groq_client.chat.completions.create(
model=GROQ_MODEL,
messages=[
{"role": "system", "content": system_prompt},
{"role": "user", "content": user_msg}
],
temperature=0.2,
max_tokens=1024,
)
answer = response.choices[0].message.content
if satisfied:
sources = []
for i, r in enumerate(results, 1):
m = r["meta"]
sources.append({
"num": i,
"category": m.get("category", ""),
"sub": m.get("subcategory", ""),
"title": m.get("title") or m.get("key_finding", "")[:120],
"pmid": m.get("pmid", ""),
"journal": m.get("journal", ""),
"score": r["score"],
"source": m.get("source", ""),
})
else:
sources = web_sources
return {
"answer": answer,
"sources": sources,
"fallback_used": fallback_used,
}
@app.post("/ask/stream")
def ask_stream(req: QueryRequest):
if not req.question.strip():
raise HTTPException(400, "Question cannot be empty")
results = retrieve(req.question, req.top_k)
satisfied = is_satisfactory(results)
def generate():
nonlocal satisfied
if satisfied:
sources = []
for i, r in enumerate(results, 1):
m = r["meta"]
sources.append({
"num": i,
"category": m.get("category", ""),
"sub": m.get("subcategory", ""),
"title": m.get("title") or m.get("key_finding", "")[:120],
"pmid": m.get("pmid", ""),
"journal": m.get("journal", ""),
"score": r["score"],
})
yield f"SOURCES:{json.dumps(sources)}\n"
context = build_context(results)
system_prompt = SYSTEM_PROMPT
user_msg = f"Research Articles:\n{context}\n\nQuestion: {req.question}"
else:
log.info(
f"β οΈ Low FAISS scores {[r['score'] for r in results]} for "
f"'{req.question}' β falling back to web search (stream)"
)
context, web_sources = web_search_via_groq(req.question)
yield f"SOURCES:{json.dumps(web_sources)}\n"
yield "FALLBACK:1\n"
system_prompt = WEB_SYSTEM_PROMPT
user_msg = f"Web Search Results:\n{context}\n\nQuestion: {req.question}"
stream = groq_client.chat.completions.create(
model=GROQ_MODEL,
messages=[
{"role": "system", "content": system_prompt},
{"role": "user", "content": user_msg}
],
temperature=0.2,
max_tokens=1024,
stream=True,
)
for chunk in stream:
delta = chunk.choices[0].delta.content
if delta:
yield f"TOKEN:{delta}"
return StreamingResponse(generate(), media_type="text/plain") |