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