Update app.py
Browse files
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 |
-
|
| 79 |
-
|
| 80 |
-
|
| 81 |
-
|
| 82 |
-
|
| 83 |
-
st.
|
| 84 |
-
|
| 85 |
-
|
| 86 |
-
|
| 87 |
-
|
| 88 |
-
|
| 89 |
-
|
| 90 |
-
|
| 91 |
-
|
| 92 |
-
|
| 93 |
-
|
| 94 |
-
|
| 95 |
-
|
| 96 |
-
|
| 97 |
-
|
| 98 |
-
|
| 99 |
-
|
| 100 |
-
|
| 101 |
-
|
| 102 |
-
|
| 103 |
-
|
| 104 |
-
|
| 105 |
-
|
| 106 |
-
|
| 107 |
-
|
| 108 |
-
|
| 109 |
-
|
| 110 |
-
|
| 111 |
-
|
| 112 |
-
|
| 113 |
-
|
| 114 |
-
|
| 115 |
-
|
| 116 |
-
|
| 117 |
-
|
| 118 |
-
|
| 119 |
-
|
| 120 |
-
|
| 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 |
+
|