-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathApp.py
83 lines (71 loc) · 3.18 KB
/
App.py
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
import logging
import os
import requests
import streamlit as st
from dotenv import load_dotenv
from frontend.src.components.Header import AppHeader
from frontend.src.components.Message import Message
# Load Environment Variables
load_dotenv(".env")
# Set Up Logging
logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(levelname)s - %(message)s')
class ChatbotUI:
def __init__(self) -> None:
self.title = os.getenv("TITLE", "KnowGenius (AI-Chatbot)")
self.chatbot_api = os.getenv("CHATBOT_API")
self.AppHeader = AppHeader
self.Message = Message
def Initialize_Messages(self) -> None:
"""Initialize Session State Messages."""
if "messages" not in st.session_state:
st.session_state.messages = [
{"role": "assistant", "content": "Hey there!"},
{"role": "assistant", "content": "I'm General Expertise & Navigation Intelligence Utility System! KnowGenius!"},
{"role": "assistant", "content": "I'm a General Knowledge Expert."},
{"role": "assistant", "content": "Ask your question?"}
]
logging.info("Session state messages initialized.")
def Messages(self) -> None:
"""Render All Messages from Session State."""
try:
for message in st.session_state.messages:
if message["role"] == "user":
self.Message(message["content"], is_user=True)
else:
self.Message(message["content"])
except Exception:
logging.error('An error occurred while rendering messages', exc_info=True)
st.error("An Error Occured!")
def User_Input(self) -> None:
"""Capture and Handle User Input."""
try:
prompt = st.chat_input("Message KnowGenius...")
if prompt:
self.Message(prompt, is_user=True)
st.session_state.messages.append({"role": "user", "content": prompt})
with st.spinner("Thinking..."):
try:
response = requests.post(self.chatbot_api, json={'query': prompt})
response_json = response.json()
response_text = response_json.get('response', "An Error Occured!")
except Exception:
logging.error("Error while communicating with Chatbot API", exc_info=True)
response_text = "An Error Occured!"
self.Message(response_text)
st.session_state.messages.append({"role": "assistant", "content": response_text})
except Exception:
logging.error('An error occurred while handling user input', exc_info=True)
st.error("An Error Occured!")
def run(self) -> None:
"""Run the Chatbot UI."""
try:
self.AppHeader(self.title)
self.Initialize_Messages()
self.Messages()
self.User_Input()
except Exception:
logging.error('An error occurred during application execution', exc_info=True)
st.error("An Error Occured!")
if __name__ == '__main__':
app = ChatbotUI()
app.run()