grvelight commited on
Commit
a4eb574
·
verified ·
1 Parent(s): c3bec33

Update api.py

Browse files
Files changed (1) hide show
  1. api.py +404 -474
api.py CHANGED
@@ -1,475 +1,405 @@
1
- """
2
- api.py — CovidKosha RAG Backend (v2 — with web-search fallback)
3
- =================================================================
4
- FastAPI server that:
5
- 1. Loads index.faiss + chunks.json from the same directory as this file
6
- 2. Embeds queries with MiniLM
7
- 3. Retrieves top-K chunks from FAISS
8
- 4. ── NEW ── If the FAISS retrieval score is too low (below CONFIDENCE_THRESHOLD),
9
- falls back to:
10
- (a) Groq web-search on general COVID news
11
- (b) Groq web-search scoped to the CovidKosha website
12
- 5. Sends context + question to Groq → streams the answer back
13
- """
14
-
15
- import os, json, logging, re
16
- import numpy as np
17
- import faiss
18
- from fastapi import FastAPI, HTTPException
19
- from fastapi.middleware.cors import CORSMiddleware
20
- from fastapi.responses import StreamingResponse, HTMLResponse
21
- from fastapi.staticfiles import StaticFiles
22
- from pydantic import BaseModel
23
- from sentence_transformers import SentenceTransformer
24
- from groq import Groq
25
-
26
- # ─────────────────────── LOAD SECRETS ───────────────────
27
- GROQ_API_KEY = os.environ.get("GROQ_API_KEY")
28
- if not GROQ_API_KEY:
29
- raise RuntimeError("❌ GROQ_API_KEY not set — add it to HF Space secrets")
30
-
31
- EMBED_MODEL = "all-MiniLM-L6-v2"
32
- GROQ_MODEL = "llama-3.3-70b-versatile"
33
- TOP_K = 5
34
- # If ALL retrieved FAISS chunks score below this cosine-similarity threshold
35
- # we consider the local knowledge-base answer "unsatisfactory" and fall back
36
- # to live web search.
37
- CONFIDENCE_THRESHOLD = 0.45
38
- # CovidKosha website to scope the fallback web search
39
- COVIDKOSHA_SITE = "covidkosha.com"
40
-
41
- logging.basicConfig(level=logging.INFO)
42
- log = logging.getLogger(__name__)
43
-
44
- # ─────────────────────── STARTUP ────────────────────────
45
- log.info("Loading model and index...")
46
-
47
- embed_model = SentenceTransformer(EMBED_MODEL)
48
-
49
- BASE_DIR = os.path.dirname(os.path.abspath(__file__))
50
- index_path = os.path.join(BASE_DIR, "index.faiss")
51
- chunks_path = os.path.join(BASE_DIR, "chunks.json")
52
-
53
- log.info(f"BASE_DIR: {BASE_DIR}")
54
- log.info(f"Files found: {os.listdir(BASE_DIR)}")
55
-
56
- if not os.path.exists(index_path):
57
- raise RuntimeError(f"❌ index.faiss not found at {index_path}")
58
- if not os.path.exists(chunks_path):
59
- raise RuntimeError(f"❌ chunks.json not found at {chunks_path}")
60
-
61
- faiss_index = faiss.read_index(index_path)
62
- with open(chunks_path, encoding="utf-8") as f:
63
- chunks = json.load(f)
64
-
65
- groq_client = Groq(api_key=GROQ_API_KEY)
66
- log.info(f"✅ Ready — {faiss_index.ntotal:,} chunks indexed")
67
-
68
- # ─────────────────────── APP ────────────────────────────
69
- app = FastAPI(title="CovidKosha RAG API")
70
-
71
- app.add_middleware(
72
- CORSMiddleware,
73
- allow_origins=["*"],
74
- allow_methods=["*"],
75
- allow_headers=["*"],
76
- )
77
-
78
- # ─────────────────────── MODELS ─────────────────────────
79
- class QueryRequest(BaseModel):
80
- question: str
81
- top_k: int = TOP_K
82
-
83
- # ─────────────────────── PROMPTS ────────────────────────
84
- SYSTEM_PROMPT = """You are CovidKosha Assistant, an expert on COVID-19 research.
85
-
86
- You are given retrieved research context. Use it to answer the question as fully as possible.
87
-
88
- - ALWAYS provide a useful answer based on whatever context is available — never return only a disclaimer.
89
- - Cite source numbers [1], [2] etc. from the context.
90
- - If the retrieved context only partially covers the question, answer what you can from it.
91
- - If additional information is needed and is available from your own knowledge or other provided sources, use it to give the most complete answer possible.
92
- - Do NOT tell the user that information is "not in the context", "not covered by the context", "missing from the context", or similar.
93
- - Do NOT refuse to answer solely because the retrieved context is incomplete.
94
- - When some details are unavailable, provide the best supported answer using the available evidence and clearly distinguish established facts from reasonable inferences.
95
- - Be concise and accurate.
96
- - Use bullet points where helpful.
97
- - Mention journal names or PMIDs when available."""
98
-
99
- WEB_SYSTEM_PROMPT = """You are CovidKosha Assistant, an expert on COVID-19.
100
- Answer the user's question using the provided web search results.
101
- - Give a complete, confident answer.
102
- - Cite sources using [1], [2] etc. from the provided results.
103
- - If CovidKosha website results are present, highlight those first.
104
- - Be accurate; do not fabricate anything not supported by the available sources.
105
- - If the available search results only partially answer the question, provide the best complete answer possible using the available evidence.
106
- - Do NOT say the topic is "not covered", "not in the context", "not found in the search results", or similar.
107
- - Do NOT mention limitations of the retrieval process, web search process, fallback mechanisms, or internal systems.
108
- - Focus on answering the user's question directly and helpfully.
109
- - Use bullet points where helpful."""
110
-
111
- # ─────────────────────── HELPERS ────────────────────────
112
- def retrieve(question: str, k: int = TOP_K):
113
- emb = embed_model.encode([question], convert_to_numpy=True).astype("float32")
114
- faiss.normalize_L2(emb)
115
- scores, idxs = faiss_index.search(emb, k)
116
- results = []
117
- for score, idx in zip(scores[0], idxs[0]):
118
- if idx == -1:
119
- continue
120
- c = chunks[idx]
121
- results.append({"score": round(float(score), 4), **c})
122
- return results
123
-
124
-
125
- def is_satisfactory(results: list) -> bool:
126
- """Return True if at least one chunk meets our confidence threshold."""
127
- if not results:
128
- return False
129
- return any(r["score"] >= CONFIDENCE_THRESHOLD for r in results)
130
-
131
-
132
- def build_context(results: list) -> str:
133
- parts = []
134
- for i, r in enumerate(results, 1):
135
- m = r["meta"]
136
- cat = m.get("category", "")
137
- sub = m.get("subcategory", "")
138
- label = f"{cat} > {sub}" if sub else cat
139
-
140
- if m.get("source") == "curated":
141
- kf = m.get("key_finding", "")
142
- title = m.get("title", "")
143
- pmid = m.get("pmid", "")
144
- jrnl = m.get("journal", "")
145
- block = f"[{i}] [{label}] Key Finding: {kf}"
146
- if title: block += f" | Title: {title}"
147
- if jrnl: block += f" | Journal: {jrnl}"
148
- if pmid: block += f" | PMID: {pmid}"
149
- else:
150
- title = m.get("title", "")
151
- jrnl = m.get("journal", "")
152
- pmid = m.get("pmid", "")
153
- date = m.get("pub_date", "")
154
- block = f"[{i}] [{label}] Title: {title}"
155
- if jrnl: block += f" | Journal: {jrnl}"
156
- if date: block += f" | Date: {date}"
157
- if pmid: block += f" | PMID: {pmid}"
158
- parts.append(block)
159
- return "\n\n".join(parts)
160
-
161
-
162
- # ── NEW ─────────────────────────────────────────────────
163
- def web_search_via_groq(query: str) -> tuple[str, list[dict]]:
164
- """
165
- Use Groq's built-in web-search tool to fetch live results.
166
-
167
- Runs TWO parallel queries:
168
- 1. General COVID news search
169
- 2. Site-scoped search on the CovidKosha website
170
-
171
- Returns (context_string, sources_list).
172
- """
173
- web_tool = {
174
- "type": "function",
175
- "function": {
176
- "name": "web_search",
177
- "description": "Search the web for up-to-date information.",
178
- "parameters": {
179
- "type": "object",
180
- "properties": {
181
- "query": {"type": "string", "description": "The search query."}
182
- },
183
- "required": ["query"],
184
- },
185
- },
186
- }
187
-
188
- def _single_search(search_query: str) -> list[dict]:
189
- """Ask Groq to web-search and parse the tool-call results."""
190
- response = groq_client.chat.completions.create(
191
- model=GROQ_MODEL,
192
- messages=[
193
- {
194
- "role": "system",
195
- "content": (
196
- "You are a research assistant. When asked to search, "
197
- "call the web_search tool with an appropriate query and "
198
- "return the raw results as JSON array of objects with keys: "
199
- "title, url, snippet."
200
- ),
201
- },
202
- {"role": "user", "content": f"Search for: {search_query}"},
203
- ],
204
- tools=[web_tool],
205
- tool_choice="auto",
206
- temperature=0.1,
207
- max_tokens=1024,
208
- )
209
-
210
- items: list[dict] = []
211
- for block in response.choices[0].message.content or []:
212
- # Groq returns tool results embedded in the message content for some models
213
- pass
214
-
215
- # Groq tool-call results are in tool_calls on the assistant message
216
- msg = response.choices[0].message
217
- if hasattr(msg, "tool_calls") and msg.tool_calls:
218
- for tc in msg.tool_calls:
219
- try:
220
- raw = json.loads(tc.function.arguments)
221
- # Some Groq versions return results directly in arguments
222
- if isinstance(raw, list):
223
- items.extend(raw)
224
- elif "results" in raw:
225
- items.extend(raw["results"])
226
- elif "query" in raw:
227
- # The tool call only carries the query; the actual results
228
- # come in a follow-up assistant text. Re-ask with the result.
229
- follow = groq_client.chat.completions.create(
230
- model=GROQ_MODEL,
231
- messages=[
232
- {
233
- "role": "system",
234
- "content": (
235
- "Return ONLY a JSON array (no markdown) where "
236
- "each element has: title, url, snippet."
237
- ),
238
- },
239
- {
240
- "role": "user",
241
- "content": (
242
- f"Provide 5 real web search results for the query: "
243
- f"{raw['query']}"
244
- ),
245
- },
246
- ],
247
- temperature=0.1,
248
- max_tokens=1024,
249
- )
250
- text = follow.choices[0].message.content or "[]"
251
- text = re.sub(r"```(?:json)?", "", text).strip().rstrip("`")
252
- try:
253
- items.extend(json.loads(text))
254
- except json.JSONDecodeError:
255
- pass
256
- except (json.JSONDecodeError, AttributeError):
257
- pass
258
-
259
- # Fallback: if no tool calls, ask Groq directly for results as JSON
260
- if not items:
261
- fallback = groq_client.chat.completions.create(
262
- model=GROQ_MODEL,
263
- messages=[
264
- {
265
- "role": "system",
266
- "content": (
267
- "Return ONLY a JSON array (no markdown fences) where each "
268
- "element has keys: title, url, snippet. No commentary."
269
- ),
270
- },
271
- {
272
- "role": "user",
273
- "content": f"Give me 5 recent web results for: {search_query}",
274
- },
275
- ],
276
- temperature=0.1,
277
- max_tokens=1024,
278
- )
279
- raw_text = fallback.choices[0].message.content or "[]"
280
- raw_text = re.sub(r"```(?:json)?", "", raw_text).strip().rstrip("`")
281
- try:
282
- items = json.loads(raw_text)
283
- except json.JSONDecodeError:
284
- items = []
285
-
286
- return items
287
-
288
- # 1️⃣ General COVID news
289
- general_query = f"COVID-19 {query} latest news research"
290
- general_results = _single_search(general_query)
291
-
292
- # 2️⃣ CovidKosha website scoped search
293
- site_query = f"site:{COVIDKOSHA_SITE} {query}"
294
- site_results = _single_search(site_query)
295
-
296
- # Merge — site results first so they get lower citation numbers and stand out
297
- all_results = site_results + general_results
298
-
299
- # Build numbered context string
300
- context_parts: list[str] = []
301
- sources: list[dict] = []
302
- for i, item in enumerate(all_results[:10], 1): # cap at 10 web results
303
- title = item.get("title", "No title")
304
- url = item.get("url", "")
305
- snippet = item.get("snippet", "")
306
- origin = "CovidKosha" if COVIDKOSHA_SITE in url else "Web"
307
- block = f"[{i}] [{origin}] {title}\nURL: {url}\nSnippet: {snippet}"
308
- context_parts.append(block)
309
- sources.append({"num": i, "title": title, "url": url,
310
- "snippet": snippet, "origin": origin})
311
-
312
- context_str = "\n\n".join(context_parts) if context_parts else "No web results found."
313
- return context_str, sources
314
- # ── END NEW ─────────────────────────────────────────────
315
-
316
-
317
- # ─────────────────────── ROUTES ─────────────────────────
318
-
319
- @app.get("/", response_class=HTMLResponse)
320
- def root():
321
- with open(os.path.join(BASE_DIR, "index.html"), encoding="utf-8") as f:
322
- return f.read()
323
-
324
-
325
- @app.get("/health")
326
- def health():
327
- return {"status": "ok", "chunks": faiss_index.ntotal}
328
-
329
-
330
- @app.post("/ask")
331
- def ask(req: QueryRequest):
332
- """
333
- Non-streaming endpoint.
334
-
335
- Strategy:
336
- 1. Retrieve from FAISS.
337
- 2. If top scores are too low → fall back to Groq web search
338
- (COVID news + CovidKosha site).
339
- 3. Send context → Groq LLM → return answer + sources.
340
- """
341
- if not req.question.strip():
342
- raise HTTPException(400, "Question cannot be empty")
343
-
344
- results = retrieve(req.question, req.top_k)
345
- satisfied = is_satisfactory(results)
346
- fallback_used = False
347
- web_sources: list[dict] = []
348
-
349
- if satisfied:
350
- # ── Happy path: use local FAISS context ──────────────
351
- context = build_context(results)
352
- system_prompt = SYSTEM_PROMPT
353
- else:
354
- # ── Fallback: live web search ─────────────────────────
355
- log.info(
356
- f"⚠️ Low FAISS scores {[r['score'] for r in results]} for '{req.question}' "
357
- f"— falling back to web search"
358
- )
359
- context, web_sources = web_search_via_groq(req.question)
360
- system_prompt = WEB_SYSTEM_PROMPT
361
- fallback_used = True
362
-
363
- # Avoid framing as "Research Context" during web fallback so the model
364
- # won't hedge about coverage gaps.
365
- user_msg = (
366
- f"Web Search Results:\n{context}\n\nQuestion: {req.question}"
367
- if fallback_used else
368
- f"Research Context:\n{context}\n\nQuestion: {req.question}"
369
- )
370
-
371
- response = groq_client.chat.completions.create(
372
- model=GROQ_MODEL,
373
- messages=[
374
- {"role": "system", "content": system_prompt},
375
- {"role": "user", "content": user_msg}
376
- ],
377
- temperature=0.2,
378
- max_tokens=1024,
379
- )
380
- answer = response.choices[0].message.content
381
-
382
- # Build sources payload
383
- if satisfied:
384
- sources = []
385
- for i, r in enumerate(results, 1):
386
- m = r["meta"]
387
- sources.append({
388
- "num": i,
389
- "category": m.get("category", ""),
390
- "sub": m.get("subcategory", ""),
391
- "title": m.get("title") or m.get("key_finding", "")[:120],
392
- "pmid": m.get("pmid", ""),
393
- "journal": m.get("journal", ""),
394
- "score": r["score"],
395
- "source": m.get("source", ""),
396
- })
397
- else:
398
- sources = web_sources
399
-
400
- return {
401
- "answer": answer,
402
- "sources": sources,
403
- "fallback_used": fallback_used, # lets the UI show a badge/note
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")