Skip to content

Commit

Permalink
custom error messages
Browse files Browse the repository at this point in the history
  • Loading branch information
HemanthSai7 committed Dec 13, 2023
1 parent e79e7c8 commit 262bd24
Show file tree
Hide file tree
Showing 7 changed files with 130 additions and 8 deletions.
27 changes: 27 additions & 0 deletions StudybotAPI/backend/core/ExceptionHandlers.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
from backend import app
from .Exceptions import *

from fastapi.responses import JSONResponse
from fastapi.requests import Request
from fastapi import status

@app.exception_handler(ModelDeployingException)
async def model_deploying_exception_handler(request: Request, exc: ModelDeployingException):
return JSONResponse(
status_code=status.HTTP_503_SERVICE_UNAVAILABLE,
content=repr(exc)
)

@app.exception_handler(InfoNotProvidedException)
async def info_not_provided_exception_handler(request: Request, exc: InfoNotProvidedException):
return JSONResponse(
status_code=status.HTTP_400_BAD_REQUEST,
content=repr(exc)
)

@app.exception_handler(DataNotUploadedException)
async def data_not_uploaded_exception_handler(request: Request, exc: DataNotUploadedException):
return JSONResponse(
status_code=status.HTTP_400_BAD_REQUEST,
content=repr(exc)
)
64 changes: 64 additions & 0 deletions StudybotAPI/backend/core/Exceptions.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,64 @@
from backend.schemas import FrontendResponseModel


class ModelDeployingException(Exception):
def __init__(self, response_result: FrontendResponseModel):
self.response_result = response_result
self.set_status()
super(ModelDeployingException, self).__init__()

def set_status(self):
self.response_result["status"] = "Error"
self.response_result["message"][0]="Model is deploying. Please try again later."

def __repr__(self):
return f"exception.ModelDeployingException()"



class InfoNotProvidedException(Exception):
def __init__(self, response_result: FrontendResponseModel, message: str):
self.response_result = response_result
self.message = message
self.set_status()
super(InfoNotProvidedException, self).__init__(message)

def set_status(self):
self.response_result["status"] = "Error"
self.response_result["message"][0] = "Information not provided."
self.response_result["message"].append(self.message)

def __repr__(self):
return f"exception.InfoNotProvidedException()"


class DataNotUploadedException(Exception):
def __init__(self, response_result: FrontendResponseModel):
self.response_result = response_result
self.set_status()
super(ModelDeployingException, self).__init__()

def set_status(self):
self.response_result["status"] = "Error"
self.response_result["message"].append(
"Data not uploaded. Please upload a file."
)

def __repr__(self):
return f"exception.DataNotUploadedException()"


class PdfLoaderException(Exception):
def __init__(self, response_result: FrontendResponseModel):
self.response_result = response_result
self.set_status()
super(ModelDeployingException, self).__init__()

def set_status(self):
self.response_result["status"] = "Error"
self.response_result["message"].append(
"PDF Loader Exception. Please try again."
)

def __repr__(self):
return f"exception.PdfLoaderException()"
10 changes: 8 additions & 2 deletions StudybotAPI/backend/retriever/ops.py
Original file line number Diff line number Diff line change
@@ -1,10 +1,16 @@
from backend.schemas import *

from backend.core.Exceptions import *
from backend.core.ExceptionHandlers import *
from backend import app

from clarifai_grpc.grpc.api.status import status_code_pb2

def ops_inference(response_result: FrontendResponseModel, question: str):

if question == "":
raise InfoNotProvidedException(response_result, "Come on, I'm not telepathic. I can't read your mind. Please provide me with a question.")

try:
llm_response = app.state.qa_chain(question)
output = Inference(
Expand All @@ -14,5 +20,5 @@ def ops_inference(response_result: FrontendResponseModel, question: str):

response_result["result"] = output.dict()
except Exception as e:
response_result["message"] = "error"
response_result["result"] = str(e)
response_result["status"] = "error"
response_result["message"].append(str(e))
18 changes: 14 additions & 4 deletions StudybotAPI/backend/routes.py
Original file line number Diff line number Diff line change
Expand Up @@ -28,26 +28,36 @@ def api_home():
return {"detail": "Welcome to Studybot API"}


@app.post("/api/upload", summary="Upload", tags=["Resource Server"])
@app.post("/api/upload", response_model=DataResponseModel,summary="Upload", tags=["Resource Server"])
def upload_data(bg_tasks: BackgroundTasks, file: UploadFile = File(...)):

response_result = {
"status": "success",
"message": ["Data uploaded successfully."]
}

try:
suffix = Path(file.filename).suffix
with NamedTemporaryFile(delete=False, suffix=suffix) as tmp:
shutil.copyfileobj(file.file, tmp)
tmp_path = os.path.join(os.getcwd(), tmp.name)
except Exception as e:
return e
response_result["status"] = "error"
response_result["message"][0]=str(e)
raise DataNotUploadedException(response_result)

finally:
file.file.close()

# path = os.path.join(os.getcwd(), file.filename)
bg_tasks.add_task(llm_chain_loader, DATA_PATH=tmp_path)
return response_result


@app.post("/api/inference",summary="Inference",response_model=FrontendResponseModel,tags=["Resource Server"])
def inference(data: Chat):
response_result = {
"message": "success",
"status": "success",
"message": [""],
"result": {}
}

Expand Down
8 changes: 7 additions & 1 deletion StudybotAPI/backend/schemas/FrontendResponseSchema.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,12 @@
from typing import List
from pydantic import BaseModel


class FrontendResponseModel(BaseModel):
message: str
status: str
message: List[str]
result: dict

class DataResponseModel(BaseModel):
status: str
message: List[str]
1 change: 1 addition & 0 deletions frontend/requirements.txt
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
streamlit
10 changes: 9 additions & 1 deletion frontend/🏡_Home.py
Original file line number Diff line number Diff line change
@@ -1,13 +1,21 @@
import streamlit as st

import requests

# from studybot import qa_chain
# st.write(qa_chain)

upload_pdf = st.file_uploader("Upload PDF", type="pdf")
if upload_pdf is not None:
files = {"file": upload_pdf}
response = requests.post("https://hemanthsai7-studybotapi.hf.space/api/upload", files=files)
st.write(response)

query=st.text_input("Question", key="question")
st.write(st.session_state)

if st.button("Ask"):
# answer = qa_chain(query)
answer = st.session_state["qa_chain"](query)
answer = requests.post("https://hemanthsai7-studybotapi.hf.space/api/inference", json={"promptMessage": query}).json()
st.write(answer)
# st.session_state["question"] = ""

0 comments on commit 262bd24

Please sign in to comment.