grvelight commited on
Commit
8424472
Β·
verified Β·
1 Parent(s): efaf78e

Update api.py

Browse files
Files changed (1) hide show
  1. api.py +284 -44
api.py CHANGED
@@ -1,14 +1,18 @@
1
  """
2
- api.py β€” CovidKosha RAG Backend
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. Sends context + question to Groq β†’ streams the answer back
 
 
 
 
9
  """
10
 
11
- import os, json, logging
12
  import numpy as np
13
  import faiss
14
  from fastapi import FastAPI, HTTPException
@@ -24,9 +28,15 @@ GROQ_API_KEY = os.environ.get("GROQ_API_KEY")
24
  if not GROQ_API_KEY:
25
  raise RuntimeError("❌ GROQ_API_KEY not set β€” add it to HF Space secrets")
26
 
27
- EMBED_MODEL = "all-MiniLM-L6-v2"
28
- GROQ_MODEL = "llama-3.3-70b-versatile"
29
- TOP_K = 5
 
 
 
 
 
 
30
 
31
  logging.basicConfig(level=logging.INFO)
32
  log = logging.getLogger(__name__)
@@ -36,7 +46,6 @@ log.info("Loading model and index...")
36
 
37
  embed_model = SentenceTransformer(EMBED_MODEL)
38
 
39
- # Load files from the same directory as this script
40
  BASE_DIR = os.path.dirname(os.path.abspath(__file__))
41
  index_path = os.path.join(BASE_DIR, "index.faiss")
42
  chunks_path = os.path.join(BASE_DIR, "chunks.json")
@@ -71,7 +80,7 @@ class QueryRequest(BaseModel):
71
  question: str
72
  top_k: int = TOP_K
73
 
74
- # ─────────────────────── HELPERS ────────────────────────
75
  SYSTEM_PROMPT = """You are CovidKosha Assistant, an expert on COVID-19 research.
76
  You are given retrieved research context. Use it to answer the question as fully as possible.
77
  - ALWAYS provide a useful answer based on whatever context is available β€” never return only a disclaimer.
@@ -80,6 +89,16 @@ You are given retrieved research context. Use it to answer the question as fully
80
  - Be concise and accurate. Use bullet points where helpful.
81
  - Mention journal names or PMIDs when available."""
82
 
 
 
 
 
 
 
 
 
 
 
83
  def retrieve(question: str, k: int = TOP_K):
84
  emb = embed_model.encode([question], convert_to_numpy=True).astype("float32")
85
  faiss.normalize_L2(emb)
@@ -92,7 +111,15 @@ def retrieve(question: str, k: int = TOP_K):
92
  results.append({"score": round(float(score), 4), **c})
93
  return results
94
 
95
- def build_context(results):
 
 
 
 
 
 
 
 
96
  parts = []
97
  for i, r in enumerate(results, 1):
98
  m = r["meta"]
@@ -121,6 +148,162 @@ def build_context(results):
121
  parts.append(block)
122
  return "\n\n".join(parts)
123
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
124
  # ─────────────────────── ROUTES ─────────────────────────
125
 
126
  @app.get("/", response_class=HTMLResponse)
@@ -128,25 +311,49 @@ def root():
128
  with open(os.path.join(BASE_DIR, "index.html"), encoding="utf-8") as f:
129
  return f.read()
130
 
 
131
  @app.get("/health")
132
  def health():
133
  return {"status": "ok", "chunks": faiss_index.ntotal}
134
 
 
135
  @app.post("/ask")
136
  def ask(req: QueryRequest):
137
- """Non-streaming: returns full answer + sources."""
 
 
 
 
 
 
 
 
138
  if not req.question.strip():
139
  raise HTTPException(400, "Question cannot be empty")
140
 
141
- results = retrieve(req.question, req.top_k)
142
- if not results:
143
- return {"answer": "No relevant research found.", "sources": []}
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
144
 
145
- context = build_context(results)
146
  response = groq_client.chat.completions.create(
147
  model=GROQ_MODEL,
148
  messages=[
149
- {"role": "system", "content": SYSTEM_PROMPT},
150
  {"role": "user", "content": f"Research Context:\n{context}\n\nQuestion: {req.question}"}
151
  ],
152
  temperature=0.2,
@@ -154,32 +361,8 @@ def ask(req: QueryRequest):
154
  )
155
  answer = response.choices[0].message.content
156
 
157
- sources = []
158
- for i, r in enumerate(results, 1):
159
- m = r["meta"]
160
- sources.append({
161
- "num": i,
162
- "category": m.get("category", ""),
163
- "sub": m.get("subcategory", ""),
164
- "title": m.get("title") or m.get("key_finding", "")[:120],
165
- "pmid": m.get("pmid", ""),
166
- "journal": m.get("journal", ""),
167
- "score": r["score"],
168
- "source": m.get("source", ""),
169
- })
170
-
171
- return {"answer": answer, "sources": sources}
172
-
173
- @app.post("/ask/stream")
174
- def ask_stream(req: QueryRequest):
175
- """Streaming version β€” answer tokens arrive in real time."""
176
- if not req.question.strip():
177
- raise HTTPException(400, "Question cannot be empty")
178
-
179
- results = retrieve(req.question, req.top_k)
180
- context = build_context(results) if results else "No relevant context found."
181
-
182
- def generate():
183
  sources = []
184
  for i, r in enumerate(results, 1):
185
  m = r["meta"]
@@ -191,13 +374,70 @@ def ask_stream(req: QueryRequest):
191
  "pmid": m.get("pmid", ""),
192
  "journal": m.get("journal", ""),
193
  "score": r["score"],
 
194
  })
195
- yield f"SOURCES:{json.dumps(sources)}\n"
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
196
 
197
  stream = groq_client.chat.completions.create(
198
  model=GROQ_MODEL,
199
  messages=[
200
- {"role": "system", "content": SYSTEM_PROMPT},
201
  {"role": "user", "content": f"Research Context:\n{context}\n\nQuestion: {req.question}"}
202
  ],
203
  temperature=0.2,
 
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
 
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__)
 
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")
 
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
  You are given retrieved research context. Use it to answer the question as fully as possible.
86
  - ALWAYS provide a useful answer based on whatever context is available β€” never return only a disclaimer.
 
89
  - Be concise and accurate. Use bullet points where helpful.
90
  - Mention journal names or PMIDs when available."""
91
 
92
+ WEB_SYSTEM_PROMPT = """You are CovidKosha Assistant, an expert on COVID-19.
93
+ You have been given live web-search results because the local research database did not contain
94
+ a satisfactory answer to the user's question.
95
+ - Summarise the most relevant findings from the search results clearly and concisely.
96
+ - Cite sources using [1], [2] etc. from the provided web context.
97
+ - If the CovidKosha website results are included, highlight those explicitly.
98
+ - Be accurate; do not fabricate information not present in the search results.
99
+ - Use bullet points where helpful."""
100
+
101
+ # ─────────────────────── HELPERS ────────────────────────
102
  def retrieve(question: str, k: int = TOP_K):
103
  emb = embed_model.encode([question], convert_to_numpy=True).astype("float32")
104
  faiss.normalize_L2(emb)
 
111
  results.append({"score": round(float(score), 4), **c})
112
  return results
113
 
114
+
115
+ def is_satisfactory(results: list) -> bool:
116
+ """Return True if at least one chunk meets our confidence threshold."""
117
+ if not results:
118
+ return False
119
+ return any(r["score"] >= CONFIDENCE_THRESHOLD for r in results)
120
+
121
+
122
+ def build_context(results: list) -> str:
123
  parts = []
124
  for i, r in enumerate(results, 1):
125
  m = r["meta"]
 
148
  parts.append(block)
149
  return "\n\n".join(parts)
150
 
151
+
152
+ # ── NEW ─────────────────────────────────────────────────
153
+ def web_search_via_groq(query: str) -> tuple[str, list[dict]]:
154
+ """
155
+ Use Groq's built-in web-search tool to fetch live results.
156
+
157
+ Runs TWO parallel queries:
158
+ 1. General COVID news search
159
+ 2. Site-scoped search on the CovidKosha website
160
+
161
+ Returns (context_string, sources_list).
162
+ """
163
+ web_tool = {
164
+ "type": "function",
165
+ "function": {
166
+ "name": "web_search",
167
+ "description": "Search the web for up-to-date information.",
168
+ "parameters": {
169
+ "type": "object",
170
+ "properties": {
171
+ "query": {"type": "string", "description": "The search query."}
172
+ },
173
+ "required": ["query"],
174
+ },
175
+ },
176
+ }
177
+
178
+ def _single_search(search_query: str) -> list[dict]:
179
+ """Ask Groq to web-search and parse the tool-call results."""
180
+ response = groq_client.chat.completions.create(
181
+ model=GROQ_MODEL,
182
+ messages=[
183
+ {
184
+ "role": "system",
185
+ "content": (
186
+ "You are a research assistant. When asked to search, "
187
+ "call the web_search tool with an appropriate query and "
188
+ "return the raw results as JSON array of objects with keys: "
189
+ "title, url, snippet."
190
+ ),
191
+ },
192
+ {"role": "user", "content": f"Search for: {search_query}"},
193
+ ],
194
+ tools=[web_tool],
195
+ tool_choice="auto",
196
+ temperature=0.1,
197
+ max_tokens=1024,
198
+ )
199
+
200
+ items: list[dict] = []
201
+ for block in response.choices[0].message.content or []:
202
+ # Groq returns tool results embedded in the message content for some models
203
+ pass
204
+
205
+ # Groq tool-call results are in tool_calls on the assistant message
206
+ msg = response.choices[0].message
207
+ if hasattr(msg, "tool_calls") and msg.tool_calls:
208
+ for tc in msg.tool_calls:
209
+ try:
210
+ raw = json.loads(tc.function.arguments)
211
+ # Some Groq versions return results directly in arguments
212
+ if isinstance(raw, list):
213
+ items.extend(raw)
214
+ elif "results" in raw:
215
+ items.extend(raw["results"])
216
+ elif "query" in raw:
217
+ # The tool call only carries the query; the actual results
218
+ # come in a follow-up assistant text. Re-ask with the result.
219
+ follow = groq_client.chat.completions.create(
220
+ model=GROQ_MODEL,
221
+ messages=[
222
+ {
223
+ "role": "system",
224
+ "content": (
225
+ "Return ONLY a JSON array (no markdown) where "
226
+ "each element has: title, url, snippet."
227
+ ),
228
+ },
229
+ {
230
+ "role": "user",
231
+ "content": (
232
+ f"Provide 5 real web search results for the query: "
233
+ f"{raw['query']}"
234
+ ),
235
+ },
236
+ ],
237
+ temperature=0.1,
238
+ max_tokens=1024,
239
+ )
240
+ text = follow.choices[0].message.content or "[]"
241
+ text = re.sub(r"```(?:json)?", "", text).strip().rstrip("`")
242
+ try:
243
+ items.extend(json.loads(text))
244
+ except json.JSONDecodeError:
245
+ pass
246
+ except (json.JSONDecodeError, AttributeError):
247
+ pass
248
+
249
+ # Fallback: if no tool calls, ask Groq directly for results as JSON
250
+ if not items:
251
+ fallback = groq_client.chat.completions.create(
252
+ model=GROQ_MODEL,
253
+ messages=[
254
+ {
255
+ "role": "system",
256
+ "content": (
257
+ "Return ONLY a JSON array (no markdown fences) where each "
258
+ "element has keys: title, url, snippet. No commentary."
259
+ ),
260
+ },
261
+ {
262
+ "role": "user",
263
+ "content": f"Give me 5 recent web results for: {search_query}",
264
+ },
265
+ ],
266
+ temperature=0.1,
267
+ max_tokens=1024,
268
+ )
269
+ raw_text = fallback.choices[0].message.content or "[]"
270
+ raw_text = re.sub(r"```(?:json)?", "", raw_text).strip().rstrip("`")
271
+ try:
272
+ items = json.loads(raw_text)
273
+ except json.JSONDecodeError:
274
+ items = []
275
+
276
+ return items
277
+
278
+ # 1️⃣ General COVID news
279
+ general_query = f"COVID-19 {query} latest news research"
280
+ general_results = _single_search(general_query)
281
+
282
+ # 2️⃣ CovidKosha website scoped search
283
+ site_query = f"site:{COVIDKOSHA_SITE} {query}"
284
+ site_results = _single_search(site_query)
285
+
286
+ # Merge β€” site results first so they get lower citation numbers and stand out
287
+ all_results = site_results + general_results
288
+
289
+ # Build numbered context string
290
+ context_parts: list[str] = []
291
+ sources: list[dict] = []
292
+ for i, item in enumerate(all_results[:10], 1): # cap at 10 web results
293
+ title = item.get("title", "No title")
294
+ url = item.get("url", "")
295
+ snippet = item.get("snippet", "")
296
+ origin = "CovidKosha" if COVIDKOSHA_SITE in url else "Web"
297
+ block = f"[{i}] [{origin}] {title}\nURL: {url}\nSnippet: {snippet}"
298
+ context_parts.append(block)
299
+ sources.append({"num": i, "title": title, "url": url,
300
+ "snippet": snippet, "origin": origin})
301
+
302
+ context_str = "\n\n".join(context_parts) if context_parts else "No web results found."
303
+ return context_str, sources
304
+ # ── END NEW ─────────────────────────────────────────────
305
+
306
+
307
  # ─────────────────────── ROUTES ─────────────────────────
308
 
309
  @app.get("/", response_class=HTMLResponse)
 
311
  with open(os.path.join(BASE_DIR, "index.html"), encoding="utf-8") as f:
312
  return f.read()
313
 
314
+
315
  @app.get("/health")
316
  def health():
317
  return {"status": "ok", "chunks": faiss_index.ntotal}
318
 
319
+
320
  @app.post("/ask")
321
  def ask(req: QueryRequest):
322
+ """
323
+ Non-streaming endpoint.
324
+
325
+ Strategy:
326
+ 1. Retrieve from FAISS.
327
+ 2. If top scores are too low β†’ fall back to Groq web search
328
+ (COVID news + CovidKosha site).
329
+ 3. Send context β†’ Groq LLM β†’ return answer + sources.
330
+ """
331
  if not req.question.strip():
332
  raise HTTPException(400, "Question cannot be empty")
333
 
334
+ results = retrieve(req.question, req.top_k)
335
+ satisfied = is_satisfactory(results)
336
+ fallback_used = False
337
+ web_sources: list[dict] = []
338
+
339
+ if satisfied:
340
+ # ── Happy path: use local FAISS context ──────────────
341
+ context = build_context(results)
342
+ system_prompt = SYSTEM_PROMPT
343
+ else:
344
+ # ── Fallback: live web search ─────────────────────────
345
+ log.info(
346
+ f"⚠️ Low FAISS scores {[r['score'] for r in results]} for '{req.question}' "
347
+ f"β€” falling back to web search"
348
+ )
349
+ context, web_sources = web_search_via_groq(req.question)
350
+ system_prompt = WEB_SYSTEM_PROMPT
351
+ fallback_used = True
352
 
 
353
  response = groq_client.chat.completions.create(
354
  model=GROQ_MODEL,
355
  messages=[
356
+ {"role": "system", "content": system_prompt},
357
  {"role": "user", "content": f"Research Context:\n{context}\n\nQuestion: {req.question}"}
358
  ],
359
  temperature=0.2,
 
361
  )
362
  answer = response.choices[0].message.content
363
 
364
+ # Build sources payload
365
+ if satisfied:
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
366
  sources = []
367
  for i, r in enumerate(results, 1):
368
  m = r["meta"]
 
374
  "pmid": m.get("pmid", ""),
375
  "journal": m.get("journal", ""),
376
  "score": r["score"],
377
+ "source": m.get("source", ""),
378
  })
379
+ else:
380
+ sources = web_sources
381
+
382
+ return {
383
+ "answer": answer,
384
+ "sources": sources,
385
+ "fallback_used": fallback_used, # lets the UI show a badge/note
386
+ }
387
+
388
+
389
+ @app.post("/ask/stream")
390
+ def ask_stream(req: QueryRequest):
391
+ """
392
+ Streaming version.
393
+
394
+ Same two-stage strategy as /ask, but tokens stream back in real time.
395
+ The first line is always: SOURCES:<json>
396
+ Subsequent lines are: TOKEN:<text>
397
+ A final line signals fallback: FALLBACK:1 (only emitted when web search was used)
398
+ """
399
+ if not req.question.strip():
400
+ raise HTTPException(400, "Question cannot be empty")
401
+
402
+ results = retrieve(req.question, req.top_k)
403
+ satisfied = is_satisfactory(results)
404
+
405
+ def generate():
406
+ nonlocal satisfied
407
+
408
+ if satisfied:
409
+ # ── Happy path ───────────────────────────────────
410
+ sources = []
411
+ for i, r in enumerate(results, 1):
412
+ m = r["meta"]
413
+ sources.append({
414
+ "num": i,
415
+ "category": m.get("category", ""),
416
+ "sub": m.get("subcategory", ""),
417
+ "title": m.get("title") or m.get("key_finding", "")[:120],
418
+ "pmid": m.get("pmid", ""),
419
+ "journal": m.get("journal", ""),
420
+ "score": r["score"],
421
+ })
422
+ yield f"SOURCES:{json.dumps(sources)}\n"
423
+ context = build_context(results)
424
+ system_prompt = SYSTEM_PROMPT
425
+
426
+ else:
427
+ # ── Fallback ─────────────────────────────────────
428
+ log.info(
429
+ f"⚠️ Low FAISS scores {[r['score'] for r in results]} for "
430
+ f"'{req.question}' β€” falling back to web search (stream)"
431
+ )
432
+ context, web_sources = web_search_via_groq(req.question)
433
+ yield f"SOURCES:{json.dumps(web_sources)}\n"
434
+ yield "FALLBACK:1\n" # signal to the frontend
435
+ system_prompt = WEB_SYSTEM_PROMPT
436
 
437
  stream = groq_client.chat.completions.create(
438
  model=GROQ_MODEL,
439
  messages=[
440
+ {"role": "system", "content": system_prompt},
441
  {"role": "user", "content": f"Research Context:\n{context}\n\nQuestion: {req.question}"}
442
  ],
443
  temperature=0.2,