deepa / api.py
grvelight's picture
Update api.py
3e26fdd verified
Raw History Blame Contribute Delete
18 kB
"""
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")