Update app.py
Browse files
app.py
CHANGED
@@ -1,189 +1,295 @@
|
|
1 |
-
# app.py
|
2 |
import streamlit as st
|
3 |
import json
|
4 |
import re
|
5 |
import os
|
6 |
import traceback
|
|
|
7 |
from dotenv import load_dotenv
|
8 |
|
|
|
|
|
|
|
|
|
9 |
# Import agent logic and message types
|
10 |
try:
|
11 |
-
from agent import ClinicalAgent, AgentState, check_red_flags
|
12 |
from langchain_core.messages import HumanMessage, AIMessage, ToolMessage
|
13 |
except ImportError as e:
|
|
|
14 |
st.error(f"Failed to import from agent.py: {e}. Make sure agent.py is in the same directory.")
|
15 |
st.stop()
|
16 |
|
17 |
-
|
18 |
# --- Environment Variable Loading & Validation ---
|
19 |
load_dotenv()
|
20 |
-
|
21 |
-
|
22 |
-
|
23 |
-
|
24 |
-
missing_keys = []
|
25 |
-
if not UMLS_API_KEY: missing_keys.append("UMLS_API_KEY")
|
26 |
-
if not GROQ_API_KEY: missing_keys.append("GROQ_API_KEY")
|
27 |
-
if not TAVILY_API_KEY: missing_keys.append("TAVILY_API_KEY")
|
28 |
-
if missing_keys:
|
29 |
-
st.error(f"Missing required API Key(s): {', '.join(missing_keys)}. Please set them in Hugging Face Space Secrets or environment variables.")
|
30 |
st.stop()
|
31 |
|
32 |
# --- App Configuration ---
|
33 |
class ClinicalAppSettings:
|
34 |
APP_TITLE = "SynapseAI (UMLS/FDA Integrated)"
|
35 |
PAGE_LAYOUT = "wide"
|
36 |
-
MODEL_NAME_DISPLAY = "Llama3-70b (via Groq)"
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
37 |
|
|
|
38 |
|
39 |
-
# --- Streamlit UI ---
|
40 |
def main():
|
41 |
st.set_page_config(page_title=ClinicalAppSettings.APP_TITLE, layout=ClinicalAppSettings.PAGE_LAYOUT)
|
42 |
st.title(f"π©Ί {ClinicalAppSettings.APP_TITLE}")
|
43 |
st.caption(f"Interactive Assistant | LangGraph/Groq/Tavily/UMLS/OpenFDA | Model: {ClinicalAppSettings.MODEL_NAME_DISPLAY}")
|
44 |
|
45 |
# Initialize session state
|
46 |
-
if "messages" not in st.session_state:
|
47 |
-
|
48 |
-
if "
|
|
|
|
|
|
|
49 |
if "agent" not in st.session_state:
|
50 |
-
|
51 |
-
st.session_state.agent = ClinicalAgent()
|
52 |
-
print("ClinicalAgent successfully initialized in Streamlit session state.")
|
53 |
-
except Exception as e:
|
54 |
-
st.error(f"Failed to initialize Clinical Agent: {e}. Check API keys and dependencies.")
|
55 |
-
print(f"ERROR Initializing ClinicalAgent: {e}"); traceback.print_exc(); st.stop()
|
56 |
|
57 |
-
#
|
58 |
with st.sidebar:
|
59 |
-
|
60 |
-
# Input fields... (Assume full fields as before)
|
61 |
-
st.subheader("Demographics"); age = st.number_input("Age", 0, 120, 55, key="sb_age"); sex = st.selectbox("Sex", ["Male", "Female", "Other"], key="sb_sex")
|
62 |
-
st.subheader("HPI"); chief_complaint = st.text_input("Chief Complaint", "Chest pain", key="sb_cc"); hpi_details = st.text_area("HPI Details", "55 y/o male...", height=100, key="sb_hpi"); symptoms = st.multiselect("Symptoms", ["Nausea", "Diaphoresis", "SOB", "Dizziness", "Severe Headache", "Syncope", "Hemoptysis"], default=["Nausea", "Diaphoresis"], key="sb_sym")
|
63 |
-
st.subheader("History"); pmh = st.text_area("PMH", "HTN, HLD, DM2, History of MI", key="sb_pmh"); psh = st.text_area("PSH", "Appendectomy", key="sb_psh")
|
64 |
-
st.subheader("Meds & Allergies"); current_meds_str = st.text_area("Current Meds", "Lisinopril 10mg daily\nMetformin 1000mg BID\nWarfarin 5mg daily", key="sb_meds"); allergies_str = st.text_area("Allergies", "Penicillin (rash), Aspirin", key="sb_allergies")
|
65 |
-
st.subheader("Social/Family"); social_history = st.text_area("SH", "Smoker", key="sb_sh"); family_history = st.text_area("FHx", "Father MI", key="sb_fhx")
|
66 |
-
st.subheader("Vitals & Exam"); col1, col2 = st.columns(2);
|
67 |
-
with col1: temp_c = st.number_input("Temp C", 35.0, 42.0, 36.8, format="%.1f", key="sb_temp"); hr_bpm = st.number_input("HR", 30, 250, 95, key="sb_hr"); rr_rpm = st.number_input("RR", 5, 50, 18, key="sb_rr")
|
68 |
-
with col2: bp_mmhg = st.text_input("BP", "155/90", key="sb_bp"); spo2_percent = st.number_input("SpO2", 70, 100, 96, key="sb_spo2"); pain_scale = st.slider("Pain", 0, 10, 8, key="sb_pain")
|
69 |
-
exam_notes = st.text_area("Exam Notes", "Awake, alert...", height=50, key="sb_exam")
|
70 |
-
|
71 |
if st.button("Start/Update Consultation", key="sb_start"):
|
72 |
-
|
73 |
-
|
74 |
-
|
75 |
-
|
76 |
-
|
77 |
-
|
78 |
-
|
79 |
-
|
80 |
-
|
81 |
-
st.session_state.
|
82 |
-
|
83 |
-
red_flags = check_red_flags(st.session_state.patient_data); st.sidebar.markdown("---");
|
84 |
-
if red_flags: st.sidebar.warning("**Initial Red Flags:**"); [st.sidebar.warning(f"- {flag.replace('Red Flag: ','')}") for flag in red_flags]
|
85 |
-
else: st.sidebar.success("No immediate red flags.")
|
86 |
-
# Reset conversation and summary on new intake
|
87 |
-
initial_prompt = "Initiate consultation. Review patient data and begin analysis."
|
88 |
-
st.session_state.messages = [HumanMessage(content=initial_prompt)]
|
89 |
-
st.session_state.summary = None # Reset summary
|
90 |
st.success("Patient data loaded/updated.")
|
91 |
st.rerun()
|
92 |
|
93 |
-
#
|
94 |
st.header("π¬ Clinical Consultation")
|
95 |
-
# Display loop
|
96 |
for msg in st.session_state.messages:
|
97 |
if isinstance(msg, HumanMessage):
|
98 |
-
with st.chat_message("user"):
|
|
|
99 |
elif isinstance(msg, AIMessage):
|
100 |
with st.chat_message("assistant"):
|
101 |
-
ai_content = msg.content
|
102 |
-
|
103 |
-
|
104 |
-
|
105 |
-
if
|
106 |
-
|
107 |
-
|
108 |
-
|
109 |
-
|
110 |
-
|
111 |
-
|
112 |
-
|
113 |
-
|
114 |
-
|
115 |
-
st.markdown(
|
116 |
-
|
117 |
-
|
118 |
-
|
119 |
-
|
120 |
-
|
121 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
122 |
risk = structured_output.get('risk_assessment', {})
|
123 |
-
|
124 |
-
|
125 |
-
|
126 |
-
|
127 |
-
if
|
128 |
-
st.
|
129 |
-
|
130 |
-
|
131 |
-
|
132 |
-
|
133 |
-
|
134 |
-
|
135 |
-
|
136 |
-
|
137 |
-
|
138 |
-
|
139 |
-
|
140 |
-
|
141 |
-
|
142 |
-
|
143 |
-
|
144 |
-
|
|
|
|
|
|
|
|
|
145 |
st.divider()
|
146 |
|
147 |
-
# Tool Call Display
|
148 |
-
if getattr(msg, 'tool_calls', None):
|
149 |
-
with st.expander("π οΈ AI requested actions", expanded=False):
|
150 |
-
if msg.tool_calls:
|
151 |
-
for tc in msg.tool_calls:
|
152 |
-
try: st.code(f"Action: {tc.get('name', 'Unknown Tool')}\nArgs: {json.dumps(tc.get('args', {}), indent=2)}", language="json")
|
153 |
-
except Exception as display_e: st.error(f"Could not display tool call args: {display_e}", icon="β οΈ"); st.code(f"Action: {tc.get('name', 'Unknown Tool')}\nRaw Args: {tc.get('args')}")
|
154 |
-
else: st.caption("_No actions requested._")
|
155 |
elif isinstance(msg, ToolMessage):
|
156 |
-
|
157 |
-
with st.chat_message(
|
158 |
-
try:
|
159 |
-
|
160 |
-
|
161 |
-
|
162 |
-
|
163 |
-
|
164 |
-
|
165 |
-
|
166 |
-
|
167 |
-
|
168 |
-
|
169 |
-
|
170 |
-
|
171 |
-
|
172 |
-
|
|
|
173 |
|
174 |
-
|
175 |
-
|
176 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
177 |
with st.spinner("SynapseAI is processing..."):
|
178 |
try:
|
179 |
-
final_state = st.session_state.agent.invoke_turn(
|
180 |
st.session_state.messages = final_state.get('messages', [])
|
181 |
st.session_state.summary = final_state.get('summary')
|
182 |
-
except Exception as e:
|
|
|
|
|
|
|
183 |
st.rerun()
|
184 |
|
185 |
# Disclaimer
|
186 |
-
st.markdown("---")
|
|
|
187 |
|
188 |
if __name__ == "__main__":
|
189 |
main()
|
|
|
|
|
1 |
import streamlit as st
|
2 |
import json
|
3 |
import re
|
4 |
import os
|
5 |
import traceback
|
6 |
+
import logging
|
7 |
from dotenv import load_dotenv
|
8 |
|
9 |
+
# Configure logging
|
10 |
+
tlogging = logging.getLogger(__name__)
|
11 |
+
logging.basicConfig(level=logging.INFO)
|
12 |
+
|
13 |
# Import agent logic and message types
|
14 |
try:
|
15 |
+
from agent import ClinicalAgent, AgentState, check_red_flags
|
16 |
from langchain_core.messages import HumanMessage, AIMessage, ToolMessage
|
17 |
except ImportError as e:
|
18 |
+
logging.exception("Failed to import from agent.py")
|
19 |
st.error(f"Failed to import from agent.py: {e}. Make sure agent.py is in the same directory.")
|
20 |
st.stop()
|
21 |
|
|
|
22 |
# --- Environment Variable Loading & Validation ---
|
23 |
load_dotenv()
|
24 |
+
required_keys = ["UMLS_API_KEY", "GROQ_API_KEY", "TAVILY_API_KEY"]
|
25 |
+
missing = [key for key in required_keys if not os.getenv(key)]
|
26 |
+
if missing:
|
27 |
+
st.error(f"Missing required API Key(s): {', '.join(missing)}. Please set them in environment variables.")
|
|
|
|
|
|
|
|
|
|
|
|
|
28 |
st.stop()
|
29 |
|
30 |
# --- App Configuration ---
|
31 |
class ClinicalAppSettings:
|
32 |
APP_TITLE = "SynapseAI (UMLS/FDA Integrated)"
|
33 |
PAGE_LAYOUT = "wide"
|
34 |
+
MODEL_NAME_DISPLAY = "Llama3-70b (via Groq)"
|
35 |
+
|
36 |
+
# Cache the agent to avoid re-initialization on each rerun
|
37 |
+
@st.cache_resource
|
38 |
+
def get_agent():
|
39 |
+
try:
|
40 |
+
return ClinicalAgent()
|
41 |
+
except Exception as e:
|
42 |
+
logging.exception("Failed to initialize ClinicalAgent")
|
43 |
+
st.error(f"Failed to initialize Clinical Agent: {e}. Check API keys and dependencies.")
|
44 |
+
st.stop()
|
45 |
+
|
46 |
+
# Sidebar patient intake helper
|
47 |
+
def load_patient_intake():
|
48 |
+
st.header("π Patient Intake Form")
|
49 |
+
# Demographics
|
50 |
+
age = st.number_input("Age", min_value=0, max_value=120, value=55, key="sb_age")
|
51 |
+
sex = st.selectbox("Sex", ["Male", "Female", "Other"], key="sb_sex")
|
52 |
+
|
53 |
+
# HPI
|
54 |
+
chief_complaint = st.text_input("Chief Complaint", "Chest pain", key="sb_cc")
|
55 |
+
hpi_details = st.text_area("HPI Details", "55 y/o male...", height=100, key="sb_hpi")
|
56 |
+
symptoms = st.multiselect(
|
57 |
+
"Symptoms",
|
58 |
+
["Nausea", "Diaphoresis", "SOB", "Dizziness", "Severe Headache", "Syncope", "Hemoptysis"],
|
59 |
+
default=["Nausea", "Diaphoresis"],
|
60 |
+
key="sb_sym"
|
61 |
+
)
|
62 |
+
|
63 |
+
# History
|
64 |
+
pmh = st.text_area("PMH", "HTN, HLD, DM2, History of MI", key="sb_pmh")
|
65 |
+
psh = st.text_area("PSH", "Appendectomy", key="sb_psh")
|
66 |
+
|
67 |
+
# Meds & Allergies
|
68 |
+
current_meds_str = st.text_area(
|
69 |
+
"Current Meds",
|
70 |
+
"Lisinopril 10mg daily\nMetformin 1000mg BID\nWarfarin 5mg daily",
|
71 |
+
key="sb_meds"
|
72 |
+
)
|
73 |
+
allergies_str = st.text_area("Allergies", "Penicillin (rash), Aspirin", key="sb_allergies")
|
74 |
+
|
75 |
+
# Social/Family
|
76 |
+
social_history = st.text_area("SH", "Smoker", key="sb_sh")
|
77 |
+
family_history = st.text_area("FHx", "Father MI", key="sb_fhx")
|
78 |
+
|
79 |
+
# Vitals & Exam
|
80 |
+
col1, col2 = st.columns(2)
|
81 |
+
with col1:
|
82 |
+
temp_c = st.number_input("Temp C", min_value=35.0, max_value=42.0, value=36.8, format="%.1f", key="sb_temp")
|
83 |
+
hr_bpm = st.number_input("HR", min_value=30, max_value=250, value=95, key="sb_hr")
|
84 |
+
rr_rpm = st.number_input("RR", min_value=5, max_value=50, value=18, key="sb_rr")
|
85 |
+
with col2:
|
86 |
+
bp_mmhg = st.text_input("BP", "155/90", key="sb_bp")
|
87 |
+
spo2_percent = st.number_input("SpO2", min_value=70, max_value=100, value=96, key="sb_spo2")
|
88 |
+
pain_scale = st.slider("Pain", min_value=0, max_value=10, value=8, key="sb_pain")
|
89 |
+
exam_notes = st.text_area("Exam Notes", "Awake, alert...", height=50, key="sb_exam")
|
90 |
+
|
91 |
+
# Process meds and allergies with comprehensions
|
92 |
+
current_meds_list = [m.strip() for m in current_meds_str.splitlines() if m.strip()]
|
93 |
+
current_med_names_only = [
|
94 |
+
m.group(1).lower()
|
95 |
+
for med in current_meds_list
|
96 |
+
if (m := re.match(r"^\s*([A-Za-z-]+)", med))
|
97 |
+
]
|
98 |
+
allergies_list = [
|
99 |
+
(m.group(1).strip().lower() if (m := re.match(r"^\s*([A-Za-z\s/-]+)", a.strip())) else a.strip().lower())
|
100 |
+
for a in allergies_str.split(",")
|
101 |
+
if a.strip()
|
102 |
+
]
|
103 |
+
|
104 |
+
# Parse blood pressure
|
105 |
+
bp_sys, bp_dia = None, None
|
106 |
+
if "/" in bp_mmhg:
|
107 |
+
try:
|
108 |
+
bp_sys, bp_dia = map(int, bp_mmhg.split("/"))
|
109 |
+
except ValueError:
|
110 |
+
logging.warning(f"Unable to parse BP '{bp_mmhg}'")
|
111 |
+
|
112 |
+
return {
|
113 |
+
"demographics": {"age": age, "sex": sex},
|
114 |
+
"hpi": {"chief_complaint": chief_complaint, "details": hpi_details, "symptoms": symptoms},
|
115 |
+
"pmh": {"conditions": pmh},
|
116 |
+
"psh": {"procedures": psh},
|
117 |
+
"medications": {"current": current_meds_list, "names_only": current_med_names_only},
|
118 |
+
"allergies": allergies_list,
|
119 |
+
"social_history": {"details": social_history},
|
120 |
+
"family_history": {"details": family_history},
|
121 |
+
"vitals": {
|
122 |
+
"temp_c": temp_c,
|
123 |
+
"hr_bpm": hr_bpm,
|
124 |
+
"bp_mmhg": bp_mmhg,
|
125 |
+
"bp_sys": bp_sys,
|
126 |
+
"bp_dia": bp_dia,
|
127 |
+
"rr_rpm": rr_rpm,
|
128 |
+
"spo2_percent": spo2_percent,
|
129 |
+
"pain_scale": pain_scale
|
130 |
+
},
|
131 |
+
"exam_findings": {"notes": exam_notes},
|
132 |
+
}
|
133 |
|
134 |
+
# Main application
|
135 |
|
|
|
136 |
def main():
|
137 |
st.set_page_config(page_title=ClinicalAppSettings.APP_TITLE, layout=ClinicalAppSettings.PAGE_LAYOUT)
|
138 |
st.title(f"π©Ί {ClinicalAppSettings.APP_TITLE}")
|
139 |
st.caption(f"Interactive Assistant | LangGraph/Groq/Tavily/UMLS/OpenFDA | Model: {ClinicalAppSettings.MODEL_NAME_DISPLAY}")
|
140 |
|
141 |
# Initialize session state
|
142 |
+
if "messages" not in st.session_state:
|
143 |
+
st.session_state.messages = []
|
144 |
+
if "patient_data" not in st.session_state:
|
145 |
+
st.session_state.patient_data = None
|
146 |
+
if "summary" not in st.session_state:
|
147 |
+
st.session_state.summary = None
|
148 |
if "agent" not in st.session_state:
|
149 |
+
st.session_state.agent = get_agent()
|
|
|
|
|
|
|
|
|
|
|
150 |
|
151 |
+
# Sidebar intake
|
152 |
with st.sidebar:
|
153 |
+
patient_data = load_patient_intake()
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
154 |
if st.button("Start/Update Consultation", key="sb_start"):
|
155 |
+
st.session_state.patient_data = patient_data
|
156 |
+
red_flags = check_red_flags(patient_data)
|
157 |
+
st.sidebar.markdown("---")
|
158 |
+
if red_flags:
|
159 |
+
st.sidebar.warning("**Initial Red Flags:**")
|
160 |
+
for flag in red_flags:
|
161 |
+
st.sidebar.warning(f"- {flag.replace('Red Flag: ', '')}")
|
162 |
+
else:
|
163 |
+
st.sidebar.success("No immediate red flags.")
|
164 |
+
st.session_state.messages = [HumanMessage(content="Initiate consultation. Review patient data and begin analysis.")]
|
165 |
+
st.session_state.summary = None
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
166 |
st.success("Patient data loaded/updated.")
|
167 |
st.rerun()
|
168 |
|
169 |
+
# Chat area
|
170 |
st.header("π¬ Clinical Consultation")
|
|
|
171 |
for msg in st.session_state.messages:
|
172 |
if isinstance(msg, HumanMessage):
|
173 |
+
with st.chat_message("user"):
|
174 |
+
st.markdown(msg.content)
|
175 |
elif isinstance(msg, AIMessage):
|
176 |
with st.chat_message("assistant"):
|
177 |
+
ai_content = msg.content
|
178 |
+
structured_output = None
|
179 |
+
try:
|
180 |
+
match = re.search(r"```json\s*(\{.*?\})\s*```", ai_content, re.DOTALL | re.IGNORECASE)
|
181 |
+
if match:
|
182 |
+
payload = match.group(1)
|
183 |
+
structured_output = json.loads(payload)
|
184 |
+
prefix = ai_content[:match.start()].strip()
|
185 |
+
suffix = ai_content[match.end():].strip()
|
186 |
+
if prefix:
|
187 |
+
st.markdown(prefix)
|
188 |
+
if suffix:
|
189 |
+
st.markdown(suffix)
|
190 |
+
else:
|
191 |
+
st.markdown(ai_content)
|
192 |
+
except (AttributeError, json.JSONDecodeError) as e:
|
193 |
+
logging.warning(f"JSON parse error: {e}")
|
194 |
+
st.markdown(ai_content)
|
195 |
+
|
196 |
+
if structured_output and isinstance(structured_output, dict):
|
197 |
+
st.divider()
|
198 |
+
# Display structured JSON sections
|
199 |
+
cols = st.columns(2)
|
200 |
+
with cols[0]:
|
201 |
+
st.markdown("**Assessment:**")
|
202 |
+
st.markdown(f"> {structured_output.get('assessment', 'N/A')}" )
|
203 |
+
st.markdown("**Differential Diagnosis:**")
|
204 |
+
ddx = structured_output.get('differential_diagnosis', [])
|
205 |
+
if ddx:
|
206 |
+
for item in ddx:
|
207 |
+
likelihood = item.get('likelihood', 'Low')
|
208 |
+
icon = 'π₯' if likelihood == 'High' else ('π₯' if likelihood == 'Medium' else 'π₯')
|
209 |
+
with st.expander(f"{icon} {item.get('diagnosis', 'Unknown')} ({likelihood})"):
|
210 |
+
st.write(f"**Rationale:** {item.get('rationale', 'N/A')}")
|
211 |
+
else:
|
212 |
+
st.info("No DDx provided.")
|
213 |
+
|
214 |
+
st.markdown("**Risk Assessment:**")
|
215 |
risk = structured_output.get('risk_assessment', {})
|
216 |
+
for key, style in [('identified_red_flags', st.warning), ('immediate_concerns', st.warning), ('potential_complications', st.info)]:
|
217 |
+
items = risk.get(key, [])
|
218 |
+
if items:
|
219 |
+
style(f"**{key.replace('_', ' ').capitalize()}:** {', '.join(items)}")
|
220 |
+
if not any(risk.get(k) for k in ['identified_red_flags', 'immediate_concerns', 'potential_complications']):
|
221 |
+
st.success("No specific risks highlighted.")
|
222 |
+
|
223 |
+
with cols[1]:
|
224 |
+
st.markdown("**Recommended Plan:**")
|
225 |
+
plan = structured_output.get('recommended_plan', {})
|
226 |
+
for section in ["investigations","therapeutics","consultations","patient_education"]:
|
227 |
+
st.markdown(f"_{section.replace('_',' ').capitalize()}:_")
|
228 |
+
items = plan.get(section)
|
229 |
+
if isinstance(items, list):
|
230 |
+
for it in items:
|
231 |
+
st.markdown(f"- {it}")
|
232 |
+
elif items:
|
233 |
+
st.markdown(f"- {items}")
|
234 |
+
else:
|
235 |
+
st.markdown("_None_")
|
236 |
+
|
237 |
+
st.markdown("**Rationale & Guideline Check:**")
|
238 |
+
st.markdown(f"> {structured_output.get('rationale_summary', 'N/A')}" )
|
239 |
+
if interaction := structured_output.get('interaction_check_summary'):
|
240 |
+
st.markdown("**Interaction Check Summary:**")
|
241 |
+
st.markdown(f"> {interaction}")
|
242 |
st.divider()
|
243 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
244 |
elif isinstance(msg, ToolMessage):
|
245 |
+
tool_name = getattr(msg, 'name', 'tool_execution')
|
246 |
+
with st.chat_message(tool_name, avatar="π οΈ"):
|
247 |
+
try:
|
248 |
+
data = json.loads(msg.content)
|
249 |
+
status = data.get('status', 'info')
|
250 |
+
message = data.get('message', msg.content)
|
251 |
+
if tool_name == "flag_risk" and status == "flagged":
|
252 |
+
st.error(f"π¨ **RISK FLAGGED:** {message}")
|
253 |
+
elif status in ("success", "clear"):
|
254 |
+
st.success(message)
|
255 |
+
elif status == "warning":
|
256 |
+
st.warning(message)
|
257 |
+
else:
|
258 |
+
st.error(message)
|
259 |
+
if details := data.get('details'):
|
260 |
+
st.caption(f"Details: {details}")
|
261 |
+
except json.JSONDecodeError:
|
262 |
+
st.info(msg.content)
|
263 |
|
264 |
+
# --- Chat Input ---
|
265 |
+
if prompt := st.chat_input("Your message or follow-up query..."):
|
266 |
+
if not st.session_state.patient_data:
|
267 |
+
st.warning("Please load patient data first.")
|
268 |
+
st.stop()
|
269 |
+
user_msg = HumanMessage(content=prompt)
|
270 |
+
st.session_state.messages.append(user_msg)
|
271 |
+
with st.chat_message("user"):
|
272 |
+
st.markdown(prompt)
|
273 |
+
current_state = {
|
274 |
+
"messages": st.session_state.messages,
|
275 |
+
"patient_data": st.session_state.patient_data,
|
276 |
+
"summary": st.session_state.summary,
|
277 |
+
"interaction_warnings": None
|
278 |
+
}
|
279 |
with st.spinner("SynapseAI is processing..."):
|
280 |
try:
|
281 |
+
final_state = st.session_state.agent.invoke_turn(current_state)
|
282 |
st.session_state.messages = final_state.get('messages', [])
|
283 |
st.session_state.summary = final_state.get('summary')
|
284 |
+
except Exception as e:
|
285 |
+
logging.exception("Error during agent.invoke_turn")
|
286 |
+
st.error(f"Error: {e}")
|
287 |
+
st.session_state.messages.append(AIMessage(content=f"Error processing request: {e}"))
|
288 |
st.rerun()
|
289 |
|
290 |
# Disclaimer
|
291 |
+
st.markdown("---")
|
292 |
+
st.warning("**Disclaimer:** SynapseAI is for demonstration only and not for clinical use.")
|
293 |
|
294 |
if __name__ == "__main__":
|
295 |
main()
|