alperensn commited on
Commit
3827871
·
verified ·
1 Parent(s): ec0c897

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +131 -121
app.py CHANGED
@@ -1,121 +1,131 @@
1
- # =================================================================================
2
- # app.py: Main application file for the Streamlit web interface
3
- # =================================================================================
4
- import streamlit as st
5
- from dotenv import load_dotenv
6
-
7
- # Load environment variables from .env file
8
- load_dotenv()
9
-
10
- # Import the modules we've created
11
- import config
12
- import rag_pipeline # Now using the LlamaIndex pipeline
13
-
14
- # --- Page Configuration ---
15
- st.set_page_config(
16
- page_title="PharmaBot",
17
- page_icon="🤖",
18
- layout="wide",
19
- initial_sidebar_state="expanded",
20
- )
21
-
22
- # --- State Management ---
23
- def initialize_state():
24
- """Initializes session state variables."""
25
- if "messages" not in st.session_state:
26
- st.session_state.messages = [{"role": "assistant", "content": "Welcome to PharmaBot! How can I help you today?"}]
27
- if "query_engine" not in st.session_state:
28
- st.session_state.query_engine = None
29
- if "initialized" not in st.session_state:
30
- st.session_state.initialized = False
31
-
32
- # --- UI Components ---
33
- def setup_sidebar():
34
- """Sets up the sidebar with app information."""
35
- with st.sidebar:
36
- st.header("About PharmaBot")
37
- st.info(
38
- "PharmaBot is an AI assistant designed to answer questions about "
39
- "pharmaceuticals based on a knowledge base of RAG documents. "
40
- "It uses a Retrieval-Augmented Generation (RAG) pipeline to provide accurate, "
41
- "context-aware answers."
42
- )
43
- st.warning("**Disclaimer: I am an AI assistant, not a medical professional. This information is for educational purposes only. Please consult with a qualified healthcare provider for any health concerns or before making any medical decisions.**"
44
- )
45
- st.markdown("---")
46
- st.header("Technical Details")
47
- st.markdown(
48
- f"""
49
- - **LLM Model:** `{config.LLM_MODEL_ID}`
50
- - **Embedding Model:** `{config.EMBEDDING_MODEL_NAME}`
51
- - **Vector Type:** `LLama Index Vector Store`
52
- - **Vector Store:** `{config.VECTOR_STORE_PATH}`
53
- """
54
- )
55
-
56
- def display_chat_history():
57
- """Displays the chat history."""
58
- for message in st.session_state.messages:
59
- with st.chat_message(message["role"]):
60
- st.write(message["content"])
61
-
62
- def handle_user_input(chat_engine):
63
- """Handles user input and displays the response."""
64
- if prompt := st.chat_input("Ask me anything about pharmaceuticals..."):
65
- st.session_state.messages.append({"role": "user", "content": prompt})
66
- with st.chat_message("user"):
67
- st.write(prompt)
68
-
69
- with st.chat_message("assistant"):
70
- with st.spinner("Thinking..."):
71
- response = chat_engine.chat(prompt)
72
- st.write(str(response))
73
-
74
- st.session_state.messages.append({"role": "assistant", "content": str(response)})
75
-
76
- import time
77
-
78
- # --- Main Application Logic ---
79
- def main():
80
- """Main function to run the Streamlit app."""
81
- st.set_page_config(page_title="PharmaBot Assistant", page_icon="💊")
82
- initialize_state()
83
- st.title("💊 PharmaBot: Your AI Pharmaceutical Assistant")
84
- setup_sidebar()
85
-
86
- # Initialize the RAG pipeline if it hasn't been already
87
- if not st.session_state.initialized:
88
- with st.status("Initializing the RAG pipeline...", expanded=True) as status:
89
- try:
90
- status.write("Step 1/3: Initializing LLM and embedding models...")
91
- rag_pipeline.initialize_llm_and_embed_model()
92
-
93
- status.write("Step 2/3: Loading vector index from storage...")
94
- index = rag_pipeline.load_vector_index()
95
-
96
- status.write("Step 3/3: Building the conversational chat engine...")
97
- st.session_state.query_engine = rag_pipeline.build_query_engine(index)
98
-
99
- st.session_state.initialized = True
100
- status.update(label="Initialization Complete!", state="complete", expanded=False)
101
- time.sleep(1) # Brief pause to show completion
102
-
103
- except FileNotFoundError as e:
104
- status.update(label="Initialization Failed", state="error")
105
- st.error(f"Error: {e}. Please make sure the vector store is built.")
106
- st.warning("To build the vector store, run `python build_knowledge_base.py` from your terminal.")
107
- return
108
- except Exception as e:
109
- status.update(label="Initialization Failed", state="error")
110
- st.error(f"An unexpected error occurred during initialization: {e}")
111
- return
112
- st.rerun()
113
-
114
- # Display chat and handle input if initialized
115
- if st.session_state.initialized:
116
- display_chat_history()
117
- handle_user_input(st.session_state.query_engine)
118
-
119
- if __name__ == "__main__":
120
- main()
121
-
 
 
 
 
 
 
 
 
 
 
 
1
+ # =================================================================================
2
+ # app.py: Main application file for the Streamlit web interface
3
+ # =================================================================================
4
+ import streamlit as st
5
+ from dotenv import load_dotenv
6
+
7
+ # Load environment variables from .env file
8
+ load_dotenv()
9
+
10
+ # Import the modules we've created
11
+ import config
12
+ import rag_pipeline # Now using the LlamaIndex pipeline
13
+
14
+ # --- Page Configuration ---
15
+ st.set_page_config(
16
+ page_title="PharmaBot",
17
+ page_icon="🤖",
18
+ layout="wide",
19
+ initial_sidebar_state="expanded",
20
+ )
21
+
22
+ # --- State Management ---
23
+ def initialize_state():
24
+ """Initializes session state variables."""
25
+ if "messages" not in st.session_state:
26
+ st.session_state.messages = [{"role": "assistant", "content": "Welcome to PharmaBot! How can I help you today?"}]
27
+ if "query_engine" not in st.session_state:
28
+ st.session_state.query_engine = None
29
+ if "initialized" not in st.session_state:
30
+ st.session_state.initialized = False
31
+
32
+ # --- UI Components ---
33
+ def setup_sidebar():
34
+ """Sets up the sidebar with app information."""
35
+ with st.sidebar:
36
+ st.header("About PharmaBot")
37
+ st.info(
38
+ "PharmaBot is an AI assistant designed to answer questions about "
39
+ "pharmaceuticals based on a knowledge base of RAG documents. "
40
+ "It uses a Retrieval-Augmented Generation (RAG) pipeline to provide accurate, "
41
+ "context-aware answers."
42
+ )
43
+ st.warning("**Disclaimer: I am an AI assistant, not a medical professional. This information is for educational purposes only. Please consult with a qualified healthcare provider for any health concerns or before making any medical decisions.**"
44
+ )
45
+ st.markdown("---")
46
+ st.header("Technical Details")
47
+ st.markdown(
48
+ f"""
49
+ - **LLM Model:** `{config.LLM_MODEL_ID}`
50
+ - **Embedding Model:** `{config.EMBEDDING_MODEL_NAME}`
51
+ - **Vector Type:** `LLama Index Vector Store`
52
+ - **Vector Store:** `{config.VECTOR_STORE_PATH}`
53
+ """
54
+ )
55
+
56
+ def display_chat_history():
57
+ """Displays the chat history."""
58
+ for message in st.session_state.messages:
59
+ with st.chat_message(message["role"]):
60
+ st.write(message["content"])
61
+
62
+ def handle_user_input(chat_engine):
63
+ """Handles user input and displays the response."""
64
+ if prompt := st.chat_input("Ask me anything about pharmaceuticals..."):
65
+ st.session_state.messages.append({"role": "user", "content": prompt})
66
+ with st.chat_message("user"):
67
+ st.write(prompt)
68
+
69
+ with st.chat_message("assistant"):
70
+ with st.spinner("Thinking..."):
71
+ response = chat_engine.chat(prompt)
72
+ st.write(str(response))
73
+
74
+ st.session_state.messages.append({"role": "assistant", "content": str(response)})
75
+
76
+ import time
77
+ from build_knowledge_base import build_vector_store
78
+ import os
79
+
80
+ # --- Main Application Logic ---
81
+ def main():
82
+ """Main function to run the Streamlit app."""
83
+ st.set_page_config(page_title="PharmaBot Assistant", page_icon="💊")
84
+ initialize_state()
85
+ st.title("💊 PharmaBot: Your AI Pharmaceutical Assistant")
86
+ setup_sidebar()
87
+
88
+ # Initialize the RAG pipeline if it hasn't been already
89
+ if not st.session_state.initialized:
90
+ # Check if the vector store needs to be built
91
+ if not os.path.exists(config.LLAMA_INDEX_STORE_PATH):
92
+ with st.status("Knowledge base not found. Building now...", expanded=True) as status:
93
+ try:
94
+ status.write("This is a one-time setup and may take a few minutes...")
95
+ build_vector_store()
96
+ status.update(label="Knowledge base built successfully!", state="complete", expanded=False)
97
+ time.sleep(2)
98
+ except Exception as e:
99
+ status.update(label="Build Failed", state="error", expanded=True)
100
+ st.error(f"An error occurred while building the knowledge base: {e}")
101
+ st.stop()
102
+
103
+ with st.status("Initializing the RAG pipeline...", expanded=True) as status:
104
+ try:
105
+ status.write("Step 1/3: Initializing LLM and embedding models...")
106
+ rag_pipeline.initialize_llm_and_embed_model()
107
+
108
+ status.write("Step 2/3: Loading vector index from storage...")
109
+ index = rag_pipeline.load_vector_index()
110
+
111
+ status.write("Step 3/3: Building the conversational chat engine...")
112
+ st.session_state.query_engine = rag_pipeline.build_query_engine(index)
113
+
114
+ st.session_state.initialized = True
115
+ status.update(label="Initialization Complete!", state="complete", expanded=False)
116
+ time.sleep(1) # Brief pause to show completion
117
+
118
+ except Exception as e:
119
+ status.update(label="Initialization Failed", state="error")
120
+ st.error(f"An unexpected error occurred during initialization: {e}")
121
+ return
122
+ st.rerun()
123
+
124
+ # Display chat and handle input if initialized
125
+ if st.session_state.initialized:
126
+ display_chat_history()
127
+ handle_user_input(st.session_state.query_engine)
128
+
129
+ if __name__ == "__main__":
130
+ main()
131
+