from fastapi import APIRouter, HTTPException, Request from pydantic import BaseModel, ValidationError from app.model_loader import load_qa_pipeline from app.utils import get_index_from_text import json import re router = APIRouter() qa_pipeline = load_qa_pipeline() # Glossary dictionary (expand as needed) glossary = { "what can you do": "As ElimSoul Q&A I can navigate through your documents and provide explanations. All you need is to upload your document then ask me a question from the document and I will answer.", "what are you": "I am ElimSoul Q&A (Question and Answer) AI assistant, created by Juslin Waka the founder of ElimSoul. How may I help you today? Note: You need to upload your document then ask me a question from the document and I will answer.", "who are you": "I am ElimSoul Q&A (Question and Answer) AI assistant, created by Juslin Waka the founder of ElimSoul. How may I help you today? Note: You need to upload your document then ask me a question from the document and I will answer.", "holistic": "Holistic development means nurturing every aspect of a child's growth—emotional, intellectual, spiritual, physical, and social.", "empowerment": "Empowerment refers to giving people the tools, resources, and confidence they need to take control of their lives.", "AI": "AI stands for Artificial Intelligence, which enables computers to perform tasks that usually require human intelligence.", "spiritual": "Spiritual development involves growth in a person's beliefs, values, ethics, and connection to a higher purpose." } class AskRequest(BaseModel): question: str document: str def clean_input_string(raw: str) -> str: # Replace invalid control characters except newline and tab return re.sub(r'[\x00-\x08\x0B\x0C\x0E-\x1F\x7F]', '', raw) @router.post("/ask") async def ask_question(request: Request): try: raw_body = await request.body() try: # Try normal JSON parsing payload = AskRequest.parse_raw(raw_body) except ValidationError as ve: # Try cleaning and parsing again cleaned_str = clean_input_string(raw_body.decode("utf-8")) try: payload = AskRequest.parse_raw(cleaned_str) except Exception: raise HTTPException(status_code=422, detail="Invalid JSON format, possibly due to unescaped characters or broken structure.") index = get_index_from_text(payload.document) query_engine = index.as_query_engine(similarity_top_k=3) context_response = query_engine.query(payload.question) answer = qa_pipeline({ "context": str(context_response), "question": payload.question }) confidence = answer.get("score", 0.0) final_answer = answer.get("answer", "").strip() # Fallback if confidence is low or no good answer if confidence < 0.2 or not final_answer or final_answer.lower() == payload.question.lower(): for key in glossary: if key.lower() in payload.question.lower(): return { "answer": glossary[key], "confidence": "Glossary match", "context": "Definition pulled from built-in glossary." } return { "answer": "The document does not provide a clear answer to this question.", "confidence": confidence, "context": str(context_response), "suggestion": "Try rephrasing your question or asking about a key concept, like 'What is empowerment?'" } return { "answer": final_answer, "confidence": confidence, "context": str(context_response) } except HTTPException as e: raise e except Exception as e: raise HTTPException(status_code=500, detail=f"Unexpected error: {str(e)}")