Update app.py
Browse files
app.py
CHANGED
@@ -14,21 +14,17 @@ 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 |
# --- Environment Variable Loading & Validation ---
|
18 |
load_dotenv()
|
19 |
# Check keys required by agent.py are present before initializing the agent
|
20 |
UMLS_API_KEY = os.environ.get("UMLS_API_KEY")
|
21 |
GROQ_API_KEY = os.environ.get("GROQ_API_KEY")
|
22 |
TAVILY_API_KEY = os.environ.get("TAVILY_API_KEY")
|
23 |
-
|
24 |
missing_keys = []
|
25 |
-
if not UMLS_API_KEY:
|
26 |
-
|
27 |
-
if not
|
28 |
-
missing_keys.append("GROQ_API_KEY")
|
29 |
-
if not TAVILY_API_KEY:
|
30 |
-
missing_keys.append("TAVILY_API_KEY")
|
31 |
-
|
32 |
if missing_keys:
|
33 |
st.error(f"Missing required API Key(s): {', '.join(missing_keys)}. Please set them in Hugging Face Space Secrets or environment variables.")
|
34 |
st.stop()
|
@@ -37,7 +33,8 @@ if missing_keys:
|
|
37 |
class ClinicalAppSettings:
|
38 |
APP_TITLE = "SynapseAI (UMLS/FDA Integrated)"
|
39 |
PAGE_LAYOUT = "wide"
|
40 |
-
MODEL_NAME_DISPLAY = "Llama3-70b (via Groq)"
|
|
|
41 |
|
42 |
# --- Streamlit UI ---
|
43 |
def main():
|
@@ -46,13 +43,9 @@ def main():
|
|
46 |
st.caption(f"Interactive Assistant | LangGraph/Groq/Tavily/UMLS/OpenFDA | Model: {ClinicalAppSettings.MODEL_NAME_DISPLAY}")
|
47 |
|
48 |
# Initialize session state
|
49 |
-
if "messages" not in st.session_state:
|
50 |
-
|
51 |
-
if "
|
52 |
-
st.session_state.patient_data = None
|
53 |
-
if "summary" not in st.session_state:
|
54 |
-
st.session_state.summary = None
|
55 |
-
|
56 |
# Initialize the agent instance only once
|
57 |
if "agent" not in st.session_state:
|
58 |
try:
|
@@ -64,104 +57,40 @@ def main():
|
|
64 |
traceback.print_exc()
|
65 |
st.stop()
|
66 |
|
|
|
67 |
# --- Patient Data Input Sidebar ---
|
68 |
with st.sidebar:
|
69 |
st.header("π Patient Intake Form")
|
70 |
# Input fields... (Using shorter versions for brevity, assume full fields are here)
|
71 |
-
st.subheader("Demographics")
|
72 |
-
|
73 |
-
|
74 |
-
|
75 |
-
st.subheader("
|
76 |
-
|
77 |
-
|
78 |
-
|
79 |
-
"Symptoms",
|
80 |
-
["Nausea", "Diaphoresis", "SOB", "Dizziness", "Severe Headache", "Syncope", "Hemoptysis"],
|
81 |
-
default=["Nausea", "Diaphoresis"],
|
82 |
-
key="sb_sym"
|
83 |
-
)
|
84 |
-
|
85 |
-
st.subheader("History")
|
86 |
-
pmh = st.text_area("PMH", "HTN, HLD, DM2, History of MI", key="sb_pmh")
|
87 |
-
psh = st.text_area("PSH", "Appendectomy", key="sb_psh")
|
88 |
-
|
89 |
-
st.subheader("Meds & Allergies")
|
90 |
-
current_meds_str = st.text_area(
|
91 |
-
"Current Meds",
|
92 |
-
"Lisinopril 10mg daily\nMetformin 1000mg BID\nWarfarin 5mg daily",
|
93 |
-
key="sb_meds"
|
94 |
-
)
|
95 |
-
allergies_str = st.text_area("Allergies", "Penicillin (rash), Aspirin", key="sb_allergies") # Added Warfarin/Aspirin for testing
|
96 |
-
|
97 |
-
st.subheader("Social/Family")
|
98 |
-
social_history = st.text_area("SH", "Smoker", key="sb_sh")
|
99 |
-
family_history = st.text_area("FHx", "Father MI", key="sb_fhx")
|
100 |
-
|
101 |
-
st.subheader("Vitals & Exam")
|
102 |
-
col1, col2 = st.columns(2)
|
103 |
-
with col1:
|
104 |
-
temp_c = st.number_input("Temp C", 35.0, 42.0, 36.8, format="%.1f", key="sb_temp")
|
105 |
-
hr_bpm = st.number_input("HR", 30, 250, 95, key="sb_hr")
|
106 |
-
rr_rpm = st.number_input("RR", 5, 50, 18, key="sb_rr")
|
107 |
-
with col2:
|
108 |
-
bp_mmhg = st.text_input("BP", "155/90", key="sb_bp")
|
109 |
-
spo2_percent = st.number_input("SpO2", 70, 100, 96, key="sb_spo2")
|
110 |
-
pain_scale = st.slider("Pain", 0, 10, 8, key="sb_pain")
|
111 |
exam_notes = st.text_area("Exam Notes", "Awake, alert...", height=50, key="sb_exam")
|
112 |
|
113 |
if st.button("Start/Update Consultation", key="sb_start"):
|
114 |
# Compile data...
|
115 |
current_meds_list = [med.strip() for med in current_meds_str.split('\n') if med.strip()]
|
116 |
-
current_med_names_only = []
|
117 |
-
for med in current_meds_list:
|
118 |
-
|
119 |
-
if match:
|
120 |
-
current_med_names_only.append(match.group(1).lower())
|
121 |
-
|
122 |
allergies_list = []
|
123 |
-
for a in allergies_str.split(','):
|
124 |
-
|
125 |
-
if cleaned_allergy:
|
126 |
-
match = re.match(r"^\s*([a-zA-Z\-\s/]+)(?:\s*\(.*\))?", cleaned_allergy)
|
127 |
-
name_part = match.group(1).strip().lower() if match else cleaned_allergy.lower()
|
128 |
-
allergies_list.append(name_part)
|
129 |
-
|
130 |
# Update patient data in session state
|
131 |
-
st.session_state.patient_data = {
|
132 |
-
"demographics": {"age": age, "sex": sex},
|
133 |
-
"hpi": {"chief_complaint": chief_complaint, "details": hpi_details, "symptoms": symptoms},
|
134 |
-
"pmh": {"conditions": pmh},
|
135 |
-
"psh": {"procedures": psh},
|
136 |
-
"medications": {"current": current_meds_list, "names_only": current_med_names_only},
|
137 |
-
"allergies": allergies_list,
|
138 |
-
"social_history": {"details": social_history},
|
139 |
-
"family_history": {"details": family_history},
|
140 |
-
"vitals": {
|
141 |
-
"temp_c": temp_c,
|
142 |
-
"hr_bpm": hr_bpm,
|
143 |
-
"bp_mmhg": bp_mmhg,
|
144 |
-
"rr_rpm": rr_rpm,
|
145 |
-
"spo2_percent": spo2_percent,
|
146 |
-
"pain_scale": pain_scale
|
147 |
-
},
|
148 |
-
"exam_findings": {"notes": exam_notes}
|
149 |
-
}
|
150 |
-
|
151 |
# Call check_red_flags from agent module
|
152 |
-
red_flags = check_red_flags(st.session_state.patient_data)
|
153 |
-
st.sidebar.
|
154 |
-
|
155 |
-
st.sidebar.warning("**Initial Red Flags:**")
|
156 |
-
for flag in red_flags:
|
157 |
-
st.sidebar.warning(f"- {flag.replace('Red Flag: ', '')}")
|
158 |
-
else:
|
159 |
-
st.sidebar.success("No immediate red flags.")
|
160 |
-
|
161 |
# Reset conversation and summary on new intake
|
162 |
initial_prompt = "Initiate consultation. Review patient data and begin analysis."
|
163 |
st.session_state.messages = [HumanMessage(content=initial_prompt)]
|
164 |
-
st.session_state.summary = None
|
165 |
st.success("Patient data loaded/updated.")
|
166 |
# Rerun might be needed if the main area should clear or update based on new data
|
167 |
st.rerun()
|
@@ -171,157 +100,71 @@ def main():
|
|
171 |
# Display loop
|
172 |
for msg in st.session_state.messages:
|
173 |
if isinstance(msg, HumanMessage):
|
174 |
-
with st.chat_message("user"):
|
175 |
-
st.markdown(msg.content)
|
176 |
elif isinstance(msg, AIMessage):
|
177 |
with st.chat_message("assistant"):
|
178 |
-
ai_content = msg.content
|
179 |
-
|
180 |
-
try:
|
181 |
-
# JSON Parsing logic...
|
182 |
json_match = re.search(r"```json\s*(\{.*?\})\s*```", ai_content, re.DOTALL | re.IGNORECASE)
|
183 |
-
if json_match:
|
184 |
-
|
185 |
-
|
186 |
-
|
187 |
-
|
188 |
-
|
189 |
-
|
190 |
-
|
191 |
-
|
192 |
-
|
193 |
-
|
194 |
-
|
195 |
-
|
196 |
-
|
197 |
-
|
198 |
-
st.markdown(
|
199 |
-
|
200 |
-
|
201 |
-
if structured_output and isinstance(structured_output, dict):
|
202 |
-
# Structured JSON display logic...
|
203 |
-
st.divider()
|
204 |
-
st.subheader("π AI Analysis & Recommendations")
|
205 |
-
cols = st.columns(2)
|
206 |
-
with cols[0]:
|
207 |
-
st.markdown("**Assessment:**")
|
208 |
-
st.markdown(f"> {structured_output.get('assessment', 'N/A')}")
|
209 |
-
st.markdown("**Differential Diagnosis:**")
|
210 |
-
ddx = structured_output.get('differential_diagnosis', [])
|
211 |
-
if ddx:
|
212 |
-
for item in ddx:
|
213 |
-
likelihood = item.get('likelihood', 'Low')
|
214 |
-
if likelihood and likelihood[0] in 'HML':
|
215 |
-
medal = "π₯" if likelihood[0] == 'H' else "π₯" if likelihood[0] == 'M' else "π₯"
|
216 |
-
else:
|
217 |
-
medal = "?"
|
218 |
-
expander_title = f"{medal} {item.get('diagnosis', 'Unknown')} ({likelihood})"
|
219 |
-
with st.expander(expander_title):
|
220 |
-
st.write(f"**Rationale:** {item.get('rationale', 'N/A')}")
|
221 |
-
else:
|
222 |
-
st.info("No DDx provided.")
|
223 |
-
st.markdown("**Risk Assessment:**")
|
224 |
-
risk = structured_output.get('risk_assessment', {})
|
225 |
-
flags = risk.get('identified_red_flags', [])
|
226 |
-
concerns = risk.get("immediate_concerns", [])
|
227 |
-
comps = risk.get("potential_complications", [])
|
228 |
-
if flags:
|
229 |
-
st.warning(f"**Flags:** {', '.join(flags)}")
|
230 |
-
if concerns:
|
231 |
-
st.warning(f"**Concerns:** {', '.join(concerns)}")
|
232 |
-
if comps:
|
233 |
-
st.info(f"**Potential Complications:** {', '.join(comps)}")
|
234 |
-
if not flags and not concerns:
|
235 |
-
st.success("No major risks highlighted.")
|
236 |
-
with cols[1]:
|
237 |
-
st.markdown("**Recommended Plan:**")
|
238 |
-
plan = structured_output.get('recommended_plan', {})
|
239 |
-
for section in ["investigations", "therapeutics", "consultations", "patient_education"]:
|
240 |
-
st.markdown(f"_{section.replace('_', ' ').capitalize()}:_")
|
241 |
-
items = plan.get(section)
|
242 |
-
if items and isinstance(items, list):
|
243 |
-
for item in items:
|
244 |
-
st.markdown(f"- {item}")
|
245 |
-
elif items:
|
246 |
-
st.markdown(f"- {items}")
|
247 |
-
else:
|
248 |
-
st.markdown("_None_")
|
249 |
-
st.markdown("")
|
250 |
-
st.markdown("**Rationale & Guideline Check:**")
|
251 |
-
st.markdown(f"> {structured_output.get('rationale_summary', 'N/A')}")
|
252 |
-
interaction_summary = structured_output.get("interaction_check_summary", "")
|
253 |
-
if interaction_summary:
|
254 |
-
st.markdown("**Interaction Check Summary:**")
|
255 |
-
st.markdown(f"> {interaction_summary}")
|
256 |
-
st.divider()
|
257 |
|
258 |
# Tool Call Display
|
259 |
if getattr(msg, 'tool_calls', None):
|
260 |
-
|
261 |
-
|
262 |
for tc in msg.tool_calls:
|
263 |
-
try:
|
264 |
-
|
265 |
-
|
266 |
-
language="json"
|
267 |
-
)
|
268 |
-
except Exception as display_e:
|
269 |
-
st.error(f"Could not display tool call args: {display_e}", icon="β οΈ")
|
270 |
-
st.code(f"Action: {tc.get('name', 'Unknown Tool')}\nRaw Args: {tc.get('args')}")
|
271 |
-
else:
|
272 |
-
st.caption("_No actions requested._")
|
273 |
elif isinstance(msg, ToolMessage):
|
274 |
tool_name_display = getattr(msg, 'name', 'tool_execution')
|
275 |
with st.chat_message(tool_name_display, avatar="π οΈ"):
|
276 |
-
try:
|
277 |
-
|
278 |
-
tool_data = json.loads(msg.content)
|
279 |
-
status = tool_data.get("status", "info")
|
280 |
-
message = tool_data.get("message", msg.content)
|
281 |
-
details = tool_data.get("details")
|
282 |
-
warnings = tool_data.get("warnings")
|
283 |
# Display flagged risks immediately if the tool signals it
|
284 |
if tool_name_display == "flag_risk" and status == "flagged":
|
285 |
-
|
286 |
-
elif status
|
287 |
-
|
288 |
-
|
289 |
-
|
290 |
-
|
291 |
-
|
292 |
-
|
293 |
-
st.caption("Details:")
|
294 |
-
for warn in warnings:
|
295 |
-
st.caption(f"- {warn}")
|
296 |
-
if details:
|
297 |
-
st.caption(f"Details: {details}")
|
298 |
-
except json.JSONDecodeError:
|
299 |
-
st.info(f"{msg.content}")
|
300 |
-
except Exception as e:
|
301 |
-
st.error(f"Error displaying tool message: {e}", icon="β")
|
302 |
-
st.caption(f"Raw content: {msg.content}")
|
303 |
|
304 |
# --- Chat Input Logic ---
|
305 |
if prompt := st.chat_input("Your message or follow-up query..."):
|
306 |
-
if not st.session_state.patient_data:
|
307 |
-
|
308 |
-
st.stop()
|
309 |
-
if 'agent' not in st.session_state or not st.session_state.agent:
|
310 |
-
st.error("Agent not initialized. Check logs.")
|
311 |
-
st.stop()
|
312 |
|
313 |
# Append user message and display immediately
|
314 |
user_message = HumanMessage(content=prompt)
|
315 |
st.session_state.messages.append(user_message)
|
316 |
-
with st.chat_message("user"):
|
317 |
-
st.markdown(prompt)
|
318 |
|
319 |
# Prepare state for the agent
|
320 |
current_state_dict = {
|
321 |
"messages": st.session_state.messages,
|
322 |
"patient_data": st.session_state.patient_data,
|
323 |
"summary": st.session_state.get("summary"),
|
324 |
-
"interaction_warnings": None
|
325 |
}
|
326 |
|
327 |
# Invoke the agent's graph for one turn
|
@@ -345,8 +188,7 @@ def main():
|
|
345 |
st.rerun()
|
346 |
|
347 |
# Disclaimer
|
348 |
-
st.markdown("---")
|
349 |
-
st.warning("**Disclaimer:** SynapseAI is for demonstration...")
|
350 |
|
351 |
if __name__ == "__main__":
|
352 |
-
main()
|
|
|
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 |
# Check keys required by agent.py are present before initializing the agent
|
21 |
UMLS_API_KEY = os.environ.get("UMLS_API_KEY")
|
22 |
GROQ_API_KEY = os.environ.get("GROQ_API_KEY")
|
23 |
TAVILY_API_KEY = os.environ.get("TAVILY_API_KEY")
|
|
|
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()
|
|
|
33 |
class ClinicalAppSettings:
|
34 |
APP_TITLE = "SynapseAI (UMLS/FDA Integrated)"
|
35 |
PAGE_LAYOUT = "wide"
|
36 |
+
MODEL_NAME_DISPLAY = "Llama3-70b (via Groq)" # Defined in agent.py
|
37 |
+
|
38 |
|
39 |
# --- Streamlit UI ---
|
40 |
def main():
|
|
|
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: st.session_state.messages = []
|
47 |
+
if "patient_data" not in st.session_state: st.session_state.patient_data = None
|
48 |
+
if "summary" not in st.session_state: st.session_state.summary = None
|
|
|
|
|
|
|
|
|
49 |
# Initialize the agent instance only once
|
50 |
if "agent" not in st.session_state:
|
51 |
try:
|
|
|
57 |
traceback.print_exc()
|
58 |
st.stop()
|
59 |
|
60 |
+
|
61 |
# --- Patient Data Input Sidebar ---
|
62 |
with st.sidebar:
|
63 |
st.header("π Patient Intake Form")
|
64 |
# Input fields... (Using shorter versions for brevity, assume full fields are here)
|
65 |
+
st.subheader("Demographics"); age = st.number_input("Age", 0, 120, 55, key="sb_age"); sex = st.selectbox("Sex", ["Male", "Female", "Other"], key="sb_sex")
|
66 |
+
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")
|
67 |
+
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")
|
68 |
+
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") # Added Warfarin/Aspirin for testing
|
69 |
+
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")
|
70 |
+
st.subheader("Vitals & Exam"); col1, col2 = st.columns(2);
|
71 |
+
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")
|
72 |
+
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")
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
73 |
exam_notes = st.text_area("Exam Notes", "Awake, alert...", height=50, key="sb_exam")
|
74 |
|
75 |
if st.button("Start/Update Consultation", key="sb_start"):
|
76 |
# Compile data...
|
77 |
current_meds_list = [med.strip() for med in current_meds_str.split('\n') if med.strip()]
|
78 |
+
current_med_names_only = [];
|
79 |
+
for med in current_meds_list: match = re.match(r"^\s*([a-zA-Z\-]+)", med);
|
80 |
+
if match: current_med_names_only.append(match.group(1).lower())
|
|
|
|
|
|
|
81 |
allergies_list = []
|
82 |
+
for a in allergies_str.split(','): cleaned_allergy = a.strip();
|
83 |
+
if cleaned_allergy: match = re.match(r"^\s*([a-zA-Z\-\s/]+)(?:\s*\(.*\))?", cleaned_allergy); name_part = match.group(1).strip().lower() if match else cleaned_allergy.lower(); allergies_list.append(name_part)
|
|
|
|
|
|
|
|
|
|
|
84 |
# Update patient data in session state
|
85 |
+
st.session_state.patient_data = { "demographics": {"age": age, "sex": sex}, "hpi": {"chief_complaint": chief_complaint, "details": hpi_details, "symptoms": symptoms}, "pmh": {"conditions": pmh}, "psh": {"procedures": psh}, "medications": {"current": current_meds_list, "names_only": current_med_names_only}, "allergies": allergies_list, "social_history": {"details": social_history}, "family_history": {"details": family_history}, "vitals": { "temp_c": temp_c, "hr_bpm": hr_bpm, "bp_mmhg": bp_mmhg, "rr_rpm": rr_rpm, "spo2_percent": spo2_percent, "pain_scale": pain_scale}, "exam_findings": {"notes": exam_notes} }
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
86 |
# Call check_red_flags from agent module
|
87 |
+
red_flags = check_red_flags(st.session_state.patient_data); st.sidebar.markdown("---");
|
88 |
+
if red_flags: st.sidebar.warning("**Initial Red Flags:**"); [st.sidebar.warning(f"- {flag.replace('Red Flag: ','')}") for flag in red_flags]
|
89 |
+
else: st.sidebar.success("No immediate red flags.")
|
|
|
|
|
|
|
|
|
|
|
|
|
90 |
# Reset conversation and summary on new intake
|
91 |
initial_prompt = "Initiate consultation. Review patient data and begin analysis."
|
92 |
st.session_state.messages = [HumanMessage(content=initial_prompt)]
|
93 |
+
st.session_state.summary = None # Reset summary
|
94 |
st.success("Patient data loaded/updated.")
|
95 |
# Rerun might be needed if the main area should clear or update based on new data
|
96 |
st.rerun()
|
|
|
100 |
# Display loop
|
101 |
for msg in st.session_state.messages:
|
102 |
if isinstance(msg, HumanMessage):
|
103 |
+
with st.chat_message("user"): st.markdown(msg.content)
|
|
|
104 |
elif isinstance(msg, AIMessage):
|
105 |
with st.chat_message("assistant"):
|
106 |
+
ai_content = msg.content; structured_output = None
|
107 |
+
try: # JSON Parsing logic...
|
|
|
|
|
108 |
json_match = re.search(r"```json\s*(\{.*?\})\s*```", ai_content, re.DOTALL | re.IGNORECASE)
|
109 |
+
if json_match: json_str = json_match.group(1); prefix = ai_content[:json_match.start()].strip(); suffix = ai_content[json_match.end():].strip();
|
110 |
+
if prefix: st.markdown(prefix); structured_output = json.loads(json_str);
|
111 |
+
if suffix: st.markdown(suffix)
|
112 |
+
elif ai_content.strip().startswith("{") and ai_content.strip().endswith("}"): structured_output = json.loads(ai_content); ai_content = ""
|
113 |
+
else: st.markdown(ai_content) # Display non-JSON content
|
114 |
+
except Exception as e: st.markdown(ai_content); print(f"Error parsing/displaying AI JSON: {e}")
|
115 |
+
if structured_output and isinstance(structured_output, dict): # Structured JSON display logic...
|
116 |
+
st.divider(); st.subheader("π AI Analysis & Recommendations")
|
117 |
+
cols = st.columns(2);
|
118 |
+
with cols[0]: st.markdown("**Assessment:**"); st.markdown(f"> {structured_output.get('assessment', 'N/A')}"); st.markdown("**Differential Diagnosis:**"); ddx = structured_output.get('differential_diagnosis', []);
|
119 |
+
if ddx: [st.expander(f"{'π₯π₯π₯'[('High','Medium','Low').index(item.get('likelihood','Low')[0])] if item.get('likelihood','?')[0] in 'HML' else '?'} {item.get('diagnosis', 'Unknown')} ({item.get('likelihood','?')})").write(f"**Rationale:** {item.get('rationale', 'N/A')}") for item in ddx]
|
120 |
+
else: st.info("No DDx provided."); st.markdown("**Risk Assessment:**"); risk = structured_output.get('risk_assessment', {}); flags=risk.get('identified_red_flags',[]); concerns=risk.get("immediate_concerns",[]); comps=risk.get("potential_complications",[])
|
121 |
+
if flags: st.warning(f"**Flags:** {', '.join(flags)}"); if concerns: st.warning(f"**Concerns:** {', '.join(concerns)}"); if comps: st.info(f"**Potential Complications:** {', '.join(comps)}");
|
122 |
+
if not flags and not concerns: st.success("No major risks highlighted.")
|
123 |
+
with cols[1]: st.markdown("**Recommended Plan:**"); plan = structured_output.get('recommended_plan', {});
|
124 |
+
for section in ["investigations","therapeutics","consultations","patient_education"]: st.markdown(f"_{section.replace('_',' ').capitalize()}:_"); items = plan.get(section); [st.markdown(f"- {item}") for item in items] if items and isinstance(items, list) else (st.markdown(f"- {items}") if items else st.markdown("_None_")); st.markdown("")
|
125 |
+
st.markdown("**Rationale & Guideline Check:**"); st.markdown(f"> {structured_output.get('rationale_summary', 'N/A')}"); interaction_summary = structured_output.get("interaction_check_summary", "");
|
126 |
+
if interaction_summary: st.markdown("**Interaction Check Summary:**"); st.markdown(f"> {interaction_summary}"); st.divider()
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
127 |
|
128 |
# Tool Call Display
|
129 |
if getattr(msg, 'tool_calls', None):
|
130 |
+
with st.expander("π οΈ AI requested actions", expanded=False):
|
131 |
+
if msg.tool_calls:
|
132 |
for tc in msg.tool_calls:
|
133 |
+
try: st.code(f"Action: {tc.get('name', 'Unknown Tool')}\nArgs: {json.dumps(tc.get('args', {}), indent=2)}", language="json")
|
134 |
+
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')}")
|
135 |
+
else: st.caption("_No actions requested._")
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
136 |
elif isinstance(msg, ToolMessage):
|
137 |
tool_name_display = getattr(msg, 'name', 'tool_execution')
|
138 |
with st.chat_message(tool_name_display, avatar="π οΈ"):
|
139 |
+
try: # Tool message display logic...
|
140 |
+
tool_data = json.loads(msg.content); status = tool_data.get("status", "info"); message = tool_data.get("message", msg.content); details = tool_data.get("details"); warnings = tool_data.get("warnings");
|
|
|
|
|
|
|
|
|
|
|
141 |
# Display flagged risks immediately if the tool signals it
|
142 |
if tool_name_display == "flag_risk" and status == "flagged":
|
143 |
+
st.error(f"π¨ **RISK FLAGGED:** {message}", icon="π¨") # Show flag in UI too
|
144 |
+
elif status == "success" or status == "clear": st.success(f"{message}", icon="β
")
|
145 |
+
elif status == "warning": st.warning(f"{message}", icon="β οΈ");
|
146 |
+
if warnings and isinstance(warnings, list): st.caption("Details:"); [st.caption(f"- {warn}") for warn in warnings]
|
147 |
+
else: st.error(f"{message}", icon="β") # Assume error if not known status
|
148 |
+
if details: st.caption(f"Details: {details}")
|
149 |
+
except json.JSONDecodeError: st.info(f"{msg.content}") # Display raw if not JSON
|
150 |
+
except Exception as e: st.error(f"Error displaying tool message: {e}", icon="β"); st.caption(f"Raw content: {msg.content}")
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
151 |
|
152 |
# --- Chat Input Logic ---
|
153 |
if prompt := st.chat_input("Your message or follow-up query..."):
|
154 |
+
if not st.session_state.patient_data: st.warning("Please load patient data first."); st.stop()
|
155 |
+
if 'agent' not in st.session_state or not st.session_state.agent: st.error("Agent not initialized. Check logs."); st.stop()
|
|
|
|
|
|
|
|
|
156 |
|
157 |
# Append user message and display immediately
|
158 |
user_message = HumanMessage(content=prompt)
|
159 |
st.session_state.messages.append(user_message)
|
160 |
+
with st.chat_message("user"): st.markdown(prompt)
|
|
|
161 |
|
162 |
# Prepare state for the agent
|
163 |
current_state_dict = {
|
164 |
"messages": st.session_state.messages,
|
165 |
"patient_data": st.session_state.patient_data,
|
166 |
"summary": st.session_state.get("summary"),
|
167 |
+
"interaction_warnings": None # Start clean
|
168 |
}
|
169 |
|
170 |
# Invoke the agent's graph for one turn
|
|
|
188 |
st.rerun()
|
189 |
|
190 |
# Disclaimer
|
191 |
+
st.markdown("---"); st.warning("**Disclaimer:** SynapseAI is for demonstration...")
|
|
|
192 |
|
193 |
if __name__ == "__main__":
|
194 |
+
main()
|