mgbam commited on
Commit
9cecafe
Β·
verified Β·
1 Parent(s): e7e593a

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +238 -132
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 # Import necessary components
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
- # 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()
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)" # Defined in agent.py
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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: 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
  if "agent" not in st.session_state:
50
- try:
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
- # --- Patient Data Input Sidebar ---
58
  with st.sidebar:
59
- st.header("πŸ“„ Patient Intake Form")
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
- # Compile data...
73
- current_meds_list = [med.strip() for med in current_meds_str.split('\n') if med.strip()]
74
- current_med_names_only = [];
75
- for med in current_meds_list: match = re.match(r"^\s*([a-zA-Z\-]+)", med);
76
- if match: current_med_names_only.append(match.group(1).lower())
77
- allergies_list = []
78
- for a in allergies_str.split(','): cleaned_allergy = a.strip();
79
- 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)
80
- # Update patient data in session state
81
- 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} }
82
- # Call check_red_flags from agent module
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
- # --- Main Chat Interface Area ---
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"): st.markdown(msg.content)
 
99
  elif isinstance(msg, AIMessage):
100
  with st.chat_message("assistant"):
101
- ai_content = msg.content; structured_output = None
102
- try: # JSON Parsing logic...
103
- json_match = re.search(r"```json\s*(\{.*?\})\s*```", ai_content, re.DOTALL | re.IGNORECASE)
104
- if json_match: json_str = json_match.group(1); prefix = ai_content[:json_match.start()].strip(); suffix = ai_content[json_match.end():].strip();
105
- if prefix: st.markdown(prefix); structured_output = json.loads(json_str);
106
- if suffix: st.markdown(suffix)
107
- elif ai_content.strip().startswith("{") and ai_content.strip().endswith("}"): structured_output = json.loads(ai_content); ai_content = ""
108
- else: st.markdown(ai_content)
109
- except Exception as e: st.markdown(ai_content); print(f"Error parsing/displaying AI JSON: {e}")
110
-
111
- if structured_output and isinstance(structured_output, dict): # Structured JSON display logic...
112
- st.divider(); st.subheader("πŸ“Š AI Analysis & Recommendations")
113
- cols = st.columns(2);
114
- with cols[0]: # Assessment, DDx, Risk
115
- st.markdown("**Assessment:**"); st.markdown(f"> {structured_output.get('assessment', 'N/A')}")
116
- st.markdown("**Differential Diagnosis:**"); ddx = structured_output.get('differential_diagnosis', []);
117
- 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]
118
- else: st.info("No DDx provided.")
119
-
120
- # Risk Assessment Display (CORRECTED - Separate lines)
121
- st.markdown(f"**Risk Assessment:**")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
122
  risk = structured_output.get('risk_assessment', {})
123
- flags = risk.get('identified_red_flags', [])
124
- concerns = risk.get("immediate_concerns", [])
125
- comps = risk.get("potential_complications", [])
126
-
127
- if flags:
128
- st.warning(f"**Flags:** {', '.join(flags)}")
129
- if concerns:
130
- st.warning(f"**Concerns:** {', '.join(concerns)}")
131
- if comps:
132
- st.info(f"**Potential Complications:** {', '.join(comps)}")
133
- # Add a message if no risks were highlighted by the AI assessment
134
- if not flags and not concerns and not comps:
135
- st.success("No specific risks highlighted in this AI assessment.")
136
-
137
- with cols[1]: # Plan
138
- st.markdown("**Recommended Plan:**"); plan = structured_output.get('recommended_plan', {});
139
- 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("")
140
-
141
- # Rationale & Interaction Summary
142
- st.markdown("**Rationale & Guideline Check:**"); st.markdown(f"> {structured_output.get('rationale_summary', 'N/A')}")
143
- interaction_summary = structured_output.get("interaction_check_summary", "");
144
- if interaction_summary: st.markdown("**Interaction Check Summary:**"); st.markdown(f"> {interaction_summary}");
 
 
 
 
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
- tool_name_display = getattr(msg, 'name', 'tool_execution')
157
- with st.chat_message(tool_name_display, avatar="πŸ› οΈ"):
158
- try: # Tool message display logic...
159
- 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");
160
- if tool_name_display == "flag_risk" and status == "flagged": st.error(f"🚨 **RISK FLAGGED:** {message}", icon="🚨") # Show flag in UI too
161
- elif status == "success" or status == "clear": st.success(f"{message}", icon="βœ…")
162
- elif status == "warning": st.warning(f"{message}", icon="⚠️");
163
- if warnings and isinstance(warnings, list): st.caption("Details:"); [st.caption(f"- {warn}") for warn in warnings]
164
- else: st.error(f"{message}", icon="❌") # Assume error if not known status
165
- if details: st.caption(f"Details: {details}")
166
- except json.JSONDecodeError: st.info(f"{msg.content}") # Display raw if not JSON
167
- except Exception as e: st.error(f"Error displaying tool message: {e}", icon="❌"); st.caption(f"Raw content: {msg.content}")
168
-
169
- # --- Chat Input Logic ---
170
- if prompt := st.chat_input("Your message or follow-up query..."):
171
- if not st.session_state.patient_data: st.warning("Please load patient data first."); st.stop()
172
- if 'agent' not in st.session_state or not st.session_state.agent: st.error("Agent not initialized. Check logs."); st.stop()
 
173
 
174
- user_message = HumanMessage(content=prompt); st.session_state.messages.append(user_message)
175
- with st.chat_message("user"): st.markdown(prompt)
176
- current_state_dict = {"messages": st.session_state.messages, "patient_data": st.session_state.patient_data, "summary": st.session_state.get("summary"), "interaction_warnings": None}
 
 
 
 
 
 
 
 
 
 
 
 
177
  with st.spinner("SynapseAI is processing..."):
178
  try:
179
- final_state = st.session_state.agent.invoke_turn(current_state_dict)
180
  st.session_state.messages = final_state.get('messages', [])
181
  st.session_state.summary = final_state.get('summary')
182
- except Exception as e: print(f"CRITICAL ERROR: {e}"); traceback.print_exc(); st.error(f"Error: {e}"); st.session_state.messages.append(AIMessage(content=f"Error processing request: {e}"))
 
 
 
183
  st.rerun()
184
 
185
  # Disclaimer
186
- st.markdown("---"); st.warning("**Disclaimer:** SynapseAI is for demonstration...")
 
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()