Update pages/2_Consult.py
Browse files- pages/2_Consult.py +64 -119
pages/2_Consult.py
CHANGED
@@ -10,49 +10,45 @@ from agent import get_agent_executor # This now returns the OpenAI-based agent e
|
|
10 |
from models import ChatMessage, ChatSession
|
11 |
from models.db import get_session_context
|
12 |
from services.logger import app_logger
|
13 |
-
from services.metrics import log_consultation_start
|
14 |
|
15 |
# --- Authentication Check ---
|
16 |
if not st.session_state.get("authenticated_user_id"):
|
17 |
st.warning("Please log in to access the consultation page.")
|
18 |
try:
|
19 |
-
st.switch_page("app.py")
|
20 |
except st.errors.StreamlitAPIException:
|
21 |
-
# This can happen if st.switch_page is called when not in a multipage app context (e.g. dev)
|
22 |
st.info("Please navigate to the main login page.")
|
23 |
-
st.stop()
|
24 |
|
25 |
authenticated_user_id = st.session_state.get("authenticated_user_id")
|
26 |
-
authenticated_username = st.session_state.get("authenticated_username", "User")
|
27 |
app_logger.info(f"User '{authenticated_username}' (ID: {authenticated_user_id}) accessed Consult page.")
|
28 |
|
29 |
# --- Initialize Agent ---
|
30 |
-
# This will now initialize the OpenAI agent via get_agent_executor() from agent.py
|
31 |
try:
|
32 |
agent_executor = get_agent_executor()
|
33 |
app_logger.info("OpenAI-based agent executor initialized successfully for Consult page.")
|
34 |
-
except ValueError as e:
|
35 |
st.error(f"AI Agent Initialization Error: {e}")
|
36 |
app_logger.critical(f"Fatal: AI Agent could not be initialized in Consult page: {e}", exc_info=True)
|
37 |
st.info("Please ensure the OPENAI_API_KEY is correctly configured in the application settings (Hugging Face Secrets).")
|
38 |
st.stop()
|
39 |
-
except Exception as e:
|
40 |
st.error(f"An unexpected error occurred while initializing the AI Agent: {e}")
|
41 |
app_logger.critical(f"Fatal: Unexpected AI Agent initialization error: {e}", exc_info=True)
|
42 |
st.stop()
|
43 |
|
44 |
-
|
45 |
# --- Session State for Consult Page ---
|
46 |
-
# Using more descriptive key for the patient context dictionary
|
47 |
if 'current_consult_patient_context_dict' not in st.session_state:
|
48 |
st.session_state.current_consult_patient_context_dict = {}
|
49 |
if 'consult_context_submitted' not in st.session_state:
|
50 |
st.session_state.consult_context_submitted = False
|
51 |
|
52 |
-
# --- Helper Functions ---
|
53 |
-
|
54 |
-
|
55 |
-
|
56 |
messages = []
|
57 |
app_logger.debug(f"Loading agent chat history from DB for session_id: {session_id}")
|
58 |
try:
|
@@ -63,15 +59,13 @@ def load_chat_history_for_agent(session_id: int) -> List[Any]: # List of LangCha
|
|
63 |
if msg.role == "user": messages.append(HumanMessage(content=msg.content))
|
64 |
elif msg.role == "assistant": messages.append(AIMessage(content=msg.content))
|
65 |
elif msg.role == "system": messages.append(SystemMessage(content=msg.content))
|
66 |
-
# ToolMessages are usually part of agent_scratchpad, not general chat_history for invoke
|
67 |
app_logger.debug(f"Loaded {len(messages)} LangChain messages for agent history (session {session_id}).")
|
68 |
except Exception as e:
|
69 |
app_logger.error(f"Error loading chat history for session {session_id}: {e}", exc_info=True)
|
70 |
-
st.toast(f"Error loading
|
71 |
return messages
|
72 |
|
73 |
def save_chat_message_to_db(session_id: int, role: str, content: str, tool_call_id: Optional[str]=None, tool_name: Optional[str]=None):
|
74 |
-
"""Saves a chat message to the database."""
|
75 |
app_logger.debug(f"Saving message to DB for session {session_id}: Role='{role}', Content snippet='{content[:50]}...'")
|
76 |
try:
|
77 |
with get_session_context() as db:
|
@@ -79,176 +73,127 @@ def save_chat_message_to_db(session_id: int, role: str, content: str, tool_call_
|
|
79 |
session_id=session_id, role=role, content=content, timestamp=datetime.utcnow(),
|
80 |
tool_call_id=tool_call_id, tool_name=tool_name
|
81 |
)
|
82 |
-
db.add(chat_message_obj)
|
83 |
app_logger.info(f"Message (Role: {role}) saved to DB for session {session_id}.")
|
84 |
except Exception as e:
|
85 |
app_logger.error(f"Error saving chat message to DB for session {session_id}: {e}", exc_info=True)
|
86 |
st.toast(f"Error saving message: {e}", icon="β οΈ")
|
87 |
|
88 |
-
|
89 |
def update_chat_session_with_context_summary_in_db(session_id: int, context_summary: str):
|
90 |
-
"""Updates the ChatSession record with the patient context summary."""
|
91 |
try:
|
92 |
with get_session_context() as db:
|
93 |
-
session_to_update = db.get(ChatSession, session_id)
|
94 |
if session_to_update:
|
95 |
session_to_update.patient_context_summary = context_summary
|
96 |
-
db.add(session_to_update)
|
97 |
app_logger.info(f"Updated ChatSession {session_id} with patient context summary in DB.")
|
98 |
else:
|
99 |
app_logger.error(f"Could not find ChatSession {session_id} in DB to update context summary.")
|
100 |
except Exception as e:
|
101 |
app_logger.error(f"Error updating chat session {session_id} context summary: {e}", exc_info=True)
|
102 |
-
st.toast(f"Error saving context
|
103 |
-
|
104 |
|
105 |
# --- Page Logic ---
|
106 |
st.title("AI Consultation Room")
|
107 |
st.markdown(f"Interacting as: **{authenticated_username}**")
|
108 |
-
# Prominent disclaimer on the consult page itself
|
109 |
st.warning(f"**Reminder & Disclaimer:** {settings.MAIN_DISCLAIMER_LONG} {settings.SIMULATION_DISCLAIMER}")
|
110 |
|
111 |
-
|
112 |
chat_session_id = st.session_state.get("current_chat_session_id")
|
113 |
if not chat_session_id:
|
114 |
-
st.error("Error: No active chat session ID found.
|
115 |
app_logger.critical(f"User '{authenticated_username}' (ID: {authenticated_user_id}) on Consult page encountered MISSING current_chat_session_id.")
|
116 |
st.stop()
|
117 |
|
118 |
# --- Patient Context Input Form ---
|
119 |
if not st.session_state.consult_context_submitted:
|
120 |
st.subheader("Step 1: Provide Patient Context (Optional, Use Simulated Data Only)")
|
121 |
-
|
122 |
-
|
|
|
123 |
age_in = st.number_input("Patient Age (Simulated)", min_value=0, max_value=120, step=1, value=None, help="Leave blank if not applicable.")
|
124 |
-
|
125 |
-
|
126 |
-
|
127 |
-
|
128 |
-
meds_in = st.text_area("Current Medications (Simulated)", height=100, placeholder="e.g., Metformin 500mg BID, Lisinopril 10mg OD, Salbutamol inhaler PRN")
|
129 |
submit_context_btn = st.form_submit_button("Start Consult with this Context")
|
130 |
|
131 |
if submit_context_btn:
|
132 |
-
raw_context = {
|
133 |
-
|
134 |
-
"Key Medical History": hist_in, "Current Medications": meds_in,
|
135 |
-
}
|
136 |
-
# Filter out None/empty/"Not Specified" values for a cleaner context dictionary
|
137 |
-
filtered_context_dict = {
|
138 |
-
k: v for k, v in raw_context.items()
|
139 |
-
if v is not None and str(v).strip() and \
|
140 |
-
(isinstance(v, str) and v.lower() != "not specified") and \
|
141 |
-
(isinstance(v, int) and v > 0 or not isinstance(v, int)) # ensure age > 0 if int
|
142 |
-
}
|
143 |
st.session_state.current_consult_patient_context_dict = filtered_context_dict
|
144 |
-
|
145 |
-
if filtered_context_dict:
|
146 |
-
context_summary_str = "; ".join([f"{k}: {v}" for k, v in filtered_context_dict.items()])
|
147 |
-
else:
|
148 |
-
context_summary_str = "No specific patient context was provided for this session."
|
149 |
-
|
150 |
update_chat_session_with_context_summary_in_db(chat_session_id, context_summary_str)
|
151 |
-
# Save a system message to DB indicating context was set for this session
|
152 |
save_chat_message_to_db(chat_session_id, "system", f"Initial Patient Context Set: {context_summary_str}")
|
153 |
-
|
154 |
st.session_state.consult_context_submitted = True
|
155 |
app_logger.info(f"Patient context submitted for session {chat_session_id}: {context_summary_str}")
|
156 |
-
st.rerun()
|
157 |
-
st.stop()
|
158 |
|
159 |
-
# --- Chat Interface
|
160 |
st.subheader("Step 2: Interact with AI Health Navigator")
|
161 |
-
agent_history_key = f"agent_chat_history_{chat_session_id}"
|
162 |
|
163 |
-
# Initialize or load agent's chat history (list of LangChain messages)
|
164 |
if agent_history_key not in st.session_state:
|
165 |
st.session_state[agent_history_key] = load_chat_history_for_agent(chat_session_id)
|
166 |
-
if not st.session_state[agent_history_key]:
|
167 |
-
try:
|
168 |
-
|
169 |
-
|
170 |
-
|
171 |
-
|
172 |
-
|
173 |
-
|
174 |
-
|
175 |
-
initial_ai_message_content += " I have noted the patient context you provided."
|
176 |
-
|
177 |
-
# Add initial AI message to agent's history and save to DB
|
178 |
-
st.session_state[agent_history_key].append(AIMessage(content=initial_ai_message_content))
|
179 |
-
save_chat_message_to_db(chat_session_id, "assistant", initial_ai_message_content)
|
180 |
-
app_logger.info(f"Initialized new consultation (session {chat_session_id}) with a greeting.")
|
181 |
-
|
182 |
-
# Display chat messages for UI (fetch fresh from DB for UI consistency)
|
183 |
-
# This uses a scrollable container.
|
184 |
chat_display_container = st.container(height=450)
|
185 |
with chat_display_container:
|
|
|
186 |
with get_session_context() as db:
|
187 |
stmt = select(ChatMessage).where(ChatMessage.session_id == chat_session_id).order_by(ChatMessage.timestamp)
|
188 |
ui_messages_from_db = db.exec(stmt).all()
|
189 |
-
for
|
190 |
-
if
|
191 |
-
avatar_icon = "π§ββοΈ" if
|
192 |
-
if
|
193 |
-
with st.chat_message(
|
194 |
-
st.markdown(
|
195 |
-
|
196 |
-
# Chat input from user
|
197 |
if user_prompt := st.chat_input("Ask the AI... (e.g., 'What is hypertension?')"):
|
198 |
-
|
199 |
-
|
200 |
-
with st.chat_message("user", avatar="π€"):
|
201 |
-
st.markdown(user_prompt)
|
202 |
-
|
203 |
save_chat_message_to_db(chat_session_id, "user", user_prompt)
|
204 |
st.session_state[agent_history_key].append(HumanMessage(content=user_prompt))
|
205 |
|
206 |
-
|
207 |
-
with chat_display_container: # Add AI response to the container
|
208 |
with st.chat_message("assistant", avatar="π§ββοΈ"):
|
209 |
-
|
210 |
-
|
211 |
-
|
212 |
try:
|
213 |
-
# Prepare patient context string for the agent
|
214 |
patient_context_dict = st.session_state.get('current_consult_patient_context_dict', {})
|
215 |
-
if patient_context_dict
|
216 |
-
|
217 |
-
patient_context_str_for_invoke = "; ".join(context_parts_for_invoke)
|
218 |
-
else: # If no context was provided or all fields were empty/default
|
219 |
-
patient_context_str_for_invoke = "No specific patient context was provided by the user for this interaction."
|
220 |
-
|
221 |
-
# These are the keys expected by the OpenAI Functions Agent prompt
|
222 |
invoke_payload = {
|
223 |
"input": user_prompt,
|
224 |
-
"chat_history": st.session_state[agent_history_key],
|
225 |
"patient_context": patient_context_str_for_invoke
|
226 |
}
|
227 |
app_logger.debug(f"Invoking OpenAI agent with payload: {invoke_payload}")
|
228 |
-
|
229 |
-
thinking_message.markdown("AI is thinking...") # Update spinner text
|
230 |
-
|
231 |
response = agent_executor.invoke(invoke_payload)
|
232 |
-
|
233 |
-
ai_response_content = response.get('output', "I could not generate a valid response at this time.")
|
234 |
if not isinstance(ai_response_content, str): ai_response_content = str(ai_response_content)
|
235 |
|
236 |
app_logger.info(f"OpenAI Agent response for session {chat_session_id}: '{ai_response_content[:100]}...'")
|
237 |
-
|
238 |
-
st.markdown(ai_response_content)
|
239 |
-
|
240 |
save_chat_message_to_db(chat_session_id, "assistant", ai_response_content)
|
241 |
st.session_state[agent_history_key].append(AIMessage(content=ai_response_content))
|
242 |
-
|
243 |
except Exception as e:
|
244 |
app_logger.error(f"Error during OpenAI agent invocation for session {chat_session_id}: {e}", exc_info=True)
|
245 |
error_type_name = type(e).__name__
|
246 |
-
user_friendly_error = f"Sorry, an error occurred ({error_type_name}). Please try rephrasing
|
247 |
-
|
248 |
-
st.error(user_friendly_error)
|
249 |
-
|
250 |
db_error_msg = f"System encountered an error: {error_type_name}. Details logged."
|
251 |
save_chat_message_to_db(chat_session_id, "assistant", db_error_msg)
|
252 |
-
st.session_state[agent_history_key].append(AIMessage(content=f"Note
|
253 |
-
|
254 |
-
st.rerun() # Rerun to ensure the new messages are at the bottom of the scrollable container
|
|
|
10 |
from models import ChatMessage, ChatSession
|
11 |
from models.db import get_session_context
|
12 |
from services.logger import app_logger
|
13 |
+
from services.metrics import log_consultation_start
|
14 |
|
15 |
# --- Authentication Check ---
|
16 |
if not st.session_state.get("authenticated_user_id"):
|
17 |
st.warning("Please log in to access the consultation page.")
|
18 |
try:
|
19 |
+
st.switch_page("app.py")
|
20 |
except st.errors.StreamlitAPIException:
|
|
|
21 |
st.info("Please navigate to the main login page.")
|
22 |
+
st.stop()
|
23 |
|
24 |
authenticated_user_id = st.session_state.get("authenticated_user_id")
|
25 |
+
authenticated_username = st.session_state.get("authenticated_username", "User")
|
26 |
app_logger.info(f"User '{authenticated_username}' (ID: {authenticated_user_id}) accessed Consult page.")
|
27 |
|
28 |
# --- Initialize Agent ---
|
|
|
29 |
try:
|
30 |
agent_executor = get_agent_executor()
|
31 |
app_logger.info("OpenAI-based agent executor initialized successfully for Consult page.")
|
32 |
+
except ValueError as e:
|
33 |
st.error(f"AI Agent Initialization Error: {e}")
|
34 |
app_logger.critical(f"Fatal: AI Agent could not be initialized in Consult page: {e}", exc_info=True)
|
35 |
st.info("Please ensure the OPENAI_API_KEY is correctly configured in the application settings (Hugging Face Secrets).")
|
36 |
st.stop()
|
37 |
+
except Exception as e:
|
38 |
st.error(f"An unexpected error occurred while initializing the AI Agent: {e}")
|
39 |
app_logger.critical(f"Fatal: Unexpected AI Agent initialization error: {e}", exc_info=True)
|
40 |
st.stop()
|
41 |
|
|
|
42 |
# --- Session State for Consult Page ---
|
|
|
43 |
if 'current_consult_patient_context_dict' not in st.session_state:
|
44 |
st.session_state.current_consult_patient_context_dict = {}
|
45 |
if 'consult_context_submitted' not in st.session_state:
|
46 |
st.session_state.consult_context_submitted = False
|
47 |
|
48 |
+
# --- Helper Functions (load_chat_history_for_agent, save_chat_message_to_db, update_chat_session_with_context_summary_in_db) ---
|
49 |
+
# ... (These functions are identical to the previous full 2_Consult.py provided - no changes needed here for this specific error) ...
|
50 |
+
@st.cache_data(ttl=30, show_spinner=False, max_entries=10)
|
51 |
+
def load_chat_history_for_agent(session_id: int) -> List[Any]:
|
52 |
messages = []
|
53 |
app_logger.debug(f"Loading agent chat history from DB for session_id: {session_id}")
|
54 |
try:
|
|
|
59 |
if msg.role == "user": messages.append(HumanMessage(content=msg.content))
|
60 |
elif msg.role == "assistant": messages.append(AIMessage(content=msg.content))
|
61 |
elif msg.role == "system": messages.append(SystemMessage(content=msg.content))
|
|
|
62 |
app_logger.debug(f"Loaded {len(messages)} LangChain messages for agent history (session {session_id}).")
|
63 |
except Exception as e:
|
64 |
app_logger.error(f"Error loading chat history for session {session_id}: {e}", exc_info=True)
|
65 |
+
st.toast(f"Error loading history: {e}", icon="β οΈ")
|
66 |
return messages
|
67 |
|
68 |
def save_chat_message_to_db(session_id: int, role: str, content: str, tool_call_id: Optional[str]=None, tool_name: Optional[str]=None):
|
|
|
69 |
app_logger.debug(f"Saving message to DB for session {session_id}: Role='{role}', Content snippet='{content[:50]}...'")
|
70 |
try:
|
71 |
with get_session_context() as db:
|
|
|
73 |
session_id=session_id, role=role, content=content, timestamp=datetime.utcnow(),
|
74 |
tool_call_id=tool_call_id, tool_name=tool_name
|
75 |
)
|
76 |
+
db.add(chat_message_obj)
|
77 |
app_logger.info(f"Message (Role: {role}) saved to DB for session {session_id}.")
|
78 |
except Exception as e:
|
79 |
app_logger.error(f"Error saving chat message to DB for session {session_id}: {e}", exc_info=True)
|
80 |
st.toast(f"Error saving message: {e}", icon="β οΈ")
|
81 |
|
|
|
82 |
def update_chat_session_with_context_summary_in_db(session_id: int, context_summary: str):
|
|
|
83 |
try:
|
84 |
with get_session_context() as db:
|
85 |
+
session_to_update = db.get(ChatSession, session_id)
|
86 |
if session_to_update:
|
87 |
session_to_update.patient_context_summary = context_summary
|
88 |
+
db.add(session_to_update)
|
89 |
app_logger.info(f"Updated ChatSession {session_id} with patient context summary in DB.")
|
90 |
else:
|
91 |
app_logger.error(f"Could not find ChatSession {session_id} in DB to update context summary.")
|
92 |
except Exception as e:
|
93 |
app_logger.error(f"Error updating chat session {session_id} context summary: {e}", exc_info=True)
|
94 |
+
st.toast(f"Error saving context: {e}", icon="β οΈ")
|
|
|
95 |
|
96 |
# --- Page Logic ---
|
97 |
st.title("AI Consultation Room")
|
98 |
st.markdown(f"Interacting as: **{authenticated_username}**")
|
|
|
99 |
st.warning(f"**Reminder & Disclaimer:** {settings.MAIN_DISCLAIMER_LONG} {settings.SIMULATION_DISCLAIMER}")
|
100 |
|
|
|
101 |
chat_session_id = st.session_state.get("current_chat_session_id")
|
102 |
if not chat_session_id:
|
103 |
+
st.error("Error: No active chat session ID found. Please try logging out and back in.")
|
104 |
app_logger.critical(f"User '{authenticated_username}' (ID: {authenticated_user_id}) on Consult page encountered MISSING current_chat_session_id.")
|
105 |
st.stop()
|
106 |
|
107 |
# --- Patient Context Input Form ---
|
108 |
if not st.session_state.consult_context_submitted:
|
109 |
st.subheader("Step 1: Provide Patient Context (Optional, Use Simulated Data Only)")
|
110 |
+
# ... (Form logic remains the same as previous full version of 2_Consult.py) ...
|
111 |
+
with st.form(key="patient_context_form_consult_page_openai_v2"): # Unique key
|
112 |
+
st.markdown("**Crucial Reminder: Use only anonymized, simulated data. Do NOT enter real PHI.**")
|
113 |
age_in = st.number_input("Patient Age (Simulated)", min_value=0, max_value=120, step=1, value=None, help="Leave blank if not applicable.")
|
114 |
+
gender_in = st.selectbox("Patient Gender (Simulated)", ["Not Specified", "Male", "Female", "Other"], index=0)
|
115 |
+
cc_in = st.text_area("Chief Complaint / Reason for Consult (Simulated)", height=100, placeholder="e.g., Persistent cough")
|
116 |
+
hist_in = st.text_area("Key Medical History (Simulated)", height=100, placeholder="e.g., Type 2 Diabetes")
|
117 |
+
meds_in = st.text_area("Current Medications (Simulated)", height=100, placeholder="e.g., Metformin")
|
|
|
118 |
submit_context_btn = st.form_submit_button("Start Consult with this Context")
|
119 |
|
120 |
if submit_context_btn:
|
121 |
+
raw_context = {"Age": age_in, "Gender": gender_in, "Chief Complaint": cc_in, "Key Medical History": hist_in, "Current Medications": meds_in}
|
122 |
+
filtered_context_dict = { k: v for k, v in raw_context.items() if v is not None and str(v).strip() and (isinstance(v, str) and v.lower() != "not specified") and (isinstance(v, int) and v > 0 or not isinstance(v, int))}
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
123 |
st.session_state.current_consult_patient_context_dict = filtered_context_dict
|
124 |
+
context_summary_str = "; ".join([f"{k}: {v}" for k, v in filtered_context_dict.items()]) if filtered_context_dict else "No specific patient context was provided."
|
|
|
|
|
|
|
|
|
|
|
125 |
update_chat_session_with_context_summary_in_db(chat_session_id, context_summary_str)
|
|
|
126 |
save_chat_message_to_db(chat_session_id, "system", f"Initial Patient Context Set: {context_summary_str}")
|
|
|
127 |
st.session_state.consult_context_submitted = True
|
128 |
app_logger.info(f"Patient context submitted for session {chat_session_id}: {context_summary_str}")
|
129 |
+
st.rerun()
|
130 |
+
st.stop()
|
131 |
|
132 |
+
# --- Chat Interface ---
|
133 |
st.subheader("Step 2: Interact with AI Health Navigator")
|
134 |
+
agent_history_key = f"agent_chat_history_{chat_session_id}"
|
135 |
|
|
|
136 |
if agent_history_key not in st.session_state:
|
137 |
st.session_state[agent_history_key] = load_chat_history_for_agent(chat_session_id)
|
138 |
+
if not st.session_state[agent_history_key]:
|
139 |
+
try: log_consultation_start(user_id=authenticated_user_id, session_id=chat_session_id)
|
140 |
+
except Exception as e_metric: app_logger.warning(f"Failed log_consultation_start: {e_metric}")
|
141 |
+
initial_ai_msg = "Hello! I am your AI Health Navigator. How can I assist you today?"
|
142 |
+
if st.session_state.get('current_consult_patient_context_dict'):
|
143 |
+
initial_ai_msg += " I have noted the patient context you provided."
|
144 |
+
st.session_state[agent_history_key].append(AIMessage(content=initial_ai_msg))
|
145 |
+
save_chat_message_to_db(chat_session_id, "assistant", initial_ai_msg)
|
146 |
+
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
147 |
chat_display_container = st.container(height=450)
|
148 |
with chat_display_container:
|
149 |
+
# ... (Chat message display loop - same as previous full version) ...
|
150 |
with get_session_context() as db:
|
151 |
stmt = select(ChatMessage).where(ChatMessage.session_id == chat_session_id).order_by(ChatMessage.timestamp)
|
152 |
ui_messages_from_db = db.exec(stmt).all()
|
153 |
+
for msg_db in ui_messages_from_db: # Renamed msg to msg_db to avoid conflict
|
154 |
+
if msg_db.role == "system": continue
|
155 |
+
avatar_icon = "π§ββοΈ" if msg_db.role == "assistant" else "π€"
|
156 |
+
if msg_db.role == "tool": avatar_icon = "π οΈ"
|
157 |
+
with st.chat_message(msg_db.role, avatar=avatar_icon):
|
158 |
+
st.markdown(msg_db.content)
|
159 |
+
|
|
|
160 |
if user_prompt := st.chat_input("Ask the AI... (e.g., 'What is hypertension?')"):
|
161 |
+
with chat_display_container:
|
162 |
+
with st.chat_message("user", avatar="π€"): st.markdown(user_prompt)
|
|
|
|
|
|
|
163 |
save_chat_message_to_db(chat_session_id, "user", user_prompt)
|
164 |
st.session_state[agent_history_key].append(HumanMessage(content=user_prompt))
|
165 |
|
166 |
+
with chat_display_container:
|
|
|
167 |
with st.chat_message("assistant", avatar="π§ββοΈ"):
|
168 |
+
thinking_msg_placeholder = st.empty()
|
169 |
+
thinking_msg_placeholder.markdown("β")
|
|
|
170 |
try:
|
|
|
171 |
patient_context_dict = st.session_state.get('current_consult_patient_context_dict', {})
|
172 |
+
patient_context_str_for_invoke = "; ".join([f"{k}: {v}" for k,v in patient_context_dict.items()]) if patient_context_dict else "No specific patient context provided."
|
173 |
+
|
|
|
|
|
|
|
|
|
|
|
174 |
invoke_payload = {
|
175 |
"input": user_prompt,
|
176 |
+
"chat_history": st.session_state[agent_history_key],
|
177 |
"patient_context": patient_context_str_for_invoke
|
178 |
}
|
179 |
app_logger.debug(f"Invoking OpenAI agent with payload: {invoke_payload}")
|
180 |
+
thinking_msg_placeholder.markdown("AI is thinking...")
|
|
|
|
|
181 |
response = agent_executor.invoke(invoke_payload)
|
182 |
+
ai_response_content = response.get('output', "Could not generate a response.")
|
|
|
183 |
if not isinstance(ai_response_content, str): ai_response_content = str(ai_response_content)
|
184 |
|
185 |
app_logger.info(f"OpenAI Agent response for session {chat_session_id}: '{ai_response_content[:100]}...'")
|
186 |
+
thinking_msg_placeholder.empty()
|
187 |
+
st.markdown(ai_response_content)
|
|
|
188 |
save_chat_message_to_db(chat_session_id, "assistant", ai_response_content)
|
189 |
st.session_state[agent_history_key].append(AIMessage(content=ai_response_content))
|
|
|
190 |
except Exception as e:
|
191 |
app_logger.error(f"Error during OpenAI agent invocation for session {chat_session_id}: {e}", exc_info=True)
|
192 |
error_type_name = type(e).__name__
|
193 |
+
user_friendly_error = f"Sorry, an error occurred ({error_type_name}). Please try rephrasing or contact support."
|
194 |
+
thinking_msg_placeholder.empty()
|
195 |
+
st.error(user_friendly_error)
|
|
|
196 |
db_error_msg = f"System encountered an error: {error_type_name}. Details logged."
|
197 |
save_chat_message_to_db(chat_session_id, "assistant", db_error_msg)
|
198 |
+
st.session_state[agent_history_key].append(AIMessage(content=f"Note: Error ({error_type_name})."))
|
199 |
+
st.rerun()
|
|