File size: 3,987 Bytes
a07eca7 1e0a666 b45a383 a07eca7 c2d817c b45a383 1e0a666 8193dd6 2ff7a15 8193dd6 1e0a666 b45a383 1e0a666 a07eca7 c2d817c 1e0a666 a07eca7 1e0a666 a07eca7 b45a383 1e0a666 756340c 8193dd6 756340c 8193dd6 756340c 8193dd6 756340c 1e0a666 756340c 1e0a666 a07eca7 1e0a666 a07eca7 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 | 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)}")
|