1+ import logging
12from fastapi import APIRouter , HTTPException
23from app .schemas import ChatRequest , ChatResponse , DocumentRead
34from app .utils .rag import retrieve_relevant_documents , ask_gemini , ask_gemini_with_grounding , is_audit_related
45
6+ logger = logging .getLogger (__name__ )
57router = APIRouter ()
68
79CONFIDENCE_THRESHOLD = 0.65
@@ -17,19 +19,28 @@ async def chat(request: ChatRequest):
1719 if not request .question .strip ():
1820 raise HTTPException (status_code = 400 , detail = "Question cannot be empty." )
1921
22+ logger .info ("Question received: %r" , request .question )
23+
2024 if not await is_audit_related (request .question ):
25+ logger .info ("Rejected as non-audit-related" )
2126 return ChatResponse (answer = NON_AUDIT_RESPONSE , sources = [])
2227
2328 try :
2429 relevant = await retrieve_relevant_documents (request .question , top_k = 8 )
2530 except Exception as exc :
31+ logger .error ("Vector search failed: %s" , exc )
2632 raise HTTPException (status_code = 502 , detail = f"Vector search failed: { exc } " )
2733
34+ top_score = max ((doc .score for doc in relevant ), default = 0.0 )
35+ logger .info ("Retrieved %d docs, top score=%.3f" , len (relevant ), top_score )
36+
2837 if _is_confident (relevant ):
38+ logger .info ("Confidence threshold met — answering from Qdrant context" )
2939 try :
3040 snippets = [f"Title: { doc .title } \n Content: { doc .content } " for doc in relevant ]
3141 answer = await ask_gemini (request .question , snippets )
3242 except RuntimeError as exc :
43+ logger .error ("Gemini chat failed: %s" , exc )
3344 raise HTTPException (status_code = 502 , detail = f"LLM request failed: { exc } " )
3445
3546 return ChatResponse (
@@ -40,9 +51,11 @@ async def chat(request: ChatRequest):
4051 ],
4152 )
4253
54+ logger .info ("Confidence threshold not met — falling back to Gemini web grounding" )
4355 try :
4456 answer = await ask_gemini_with_grounding (request .question )
4557 except RuntimeError as exc :
58+ logger .error ("Gemini grounding failed: %s" , exc )
4659 raise HTTPException (status_code = 502 , detail = f"LLM request failed: { exc } " )
4760
4861 return ChatResponse (answer = answer , sources = [])
0 commit comments