File size: 13,101 Bytes
788074d
b34efbf
 
 
 
9cecafe
b34efbf
 
9cecafe
a3ddee2
9cecafe
 
4b23857
b731976
9cecafe
b731976
 
a3ddee2
b731976
 
b34efbf
 
71db5de
9cecafe
 
 
 
99a7bc0
9988477
b731976
99a7bc0
fb3e96c
99a7bc0
bb53fca
9cecafe
 
 
 
 
 
 
a3ddee2
9cecafe
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
a3ddee2
 
 
9cecafe
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
a3ddee2
9cecafe
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
6b6515d
9cecafe
4258926
 
 
b731976
 
 
9cecafe
 
 
 
 
 
b731976
9cecafe
6b6515d
9cecafe
4258926
9cecafe
b731976
9cecafe
 
 
 
 
 
 
 
 
 
 
99a7bc0
b731976
9988477
9cecafe
4258926
9988477
4258926
9cecafe
 
4258926
6b2d9f7
9cecafe
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
a3ddee2
9cecafe
 
 
 
 
 
 
 
a3ddee2
9cecafe
 
 
 
 
 
 
 
 
 
 
 
4b23857
9cecafe
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
a3ddee2
9cecafe
 
 
4b23857
99a7bc0
4258926
9cecafe
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
b731976
9cecafe
 
 
 
 
 
 
 
 
 
 
 
 
 
 
b731976
31ea2bf
9cecafe
b731976
 
9cecafe
a3ddee2
9cecafe
 
71db5de
31ea2bf
9988477
9cecafe
 
b564942
 
a3ddee2
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
import streamlit as st
import json
import re
import os
import traceback
import logging
from dotenv import load_dotenv

# Configure logging
logger = logging.getLogger(__name__)
logging.basicConfig(level=logging.INFO)

# Import agent logic and message types
try:
    from agent import ClinicalAgent, AgentState, check_red_flags
    from langchain_core.messages import HumanMessage, AIMessage, ToolMessage
except ImportError as e:
    logger.exception("Failed to import from agent.py")
    st.error(f"Failed to import from agent.py: {e}. Make sure agent.py is in the same directory.")
    st.stop()

# --- Environment Variable Loading & Validation ---
load_dotenv()
required_keys = ["UMLS_API_KEY", "GROQ_API_KEY", "TAVILY_API_KEY"]
missing = [key for key in required_keys if not os.getenv(key)]
if missing:
    st.error(f"Missing required API Key(s): {', '.join(missing)}. Please set them in environment variables.")
    st.stop()

# --- App Configuration ---
class ClinicalAppSettings:
    APP_TITLE = "SynapseAI"
    PAGE_LAYOUT = "wide"
    MODEL_NAME_DISPLAY = "Llama3-70b (via Groq)"

# Cache the agent to avoid re-initialization on each rerun
@st.cache_resource
def get_agent():
    try:
        return ClinicalAgent()
    except Exception as e:
        logger.exception("Failed to initialize ClinicalAgent")
        st.error(f"Failed to initialize Clinical Agent: {e}. Check API keys and dependencies.")
        st.stop()

# Sidebar patient intake helper
def load_patient_intake():
    st.header("πŸ“„ Patient Intake Form")
    # Demographics
    age = st.number_input("Age", min_value=0, max_value=120, value=55, key="sb_age")
    sex = st.selectbox("Sex", ["Male", "Female", "Other"], key="sb_sex")

    # 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"
    )

    # History
    pmh = st.text_area("PMH", "HTN, HLD, DM2, History of MI", key="sb_pmh")
    psh = st.text_area("PSH", "Appendectomy", key="sb_psh")

    # 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")

    # Social/Family
    social_history = st.text_area("SH", "Smoker", key="sb_sh")
    family_history = st.text_area("FHx", "Father MI", key="sb_fhx")

    # Vitals & Exam
    col1, col2 = st.columns(2)
    with col1:
        temp_c = st.number_input("Temp C", min_value=35.0, max_value=42.0, value=36.8, format="%.1f", key="sb_temp")
        hr_bpm = st.number_input("HR", min_value=30, max_value=250, value=95, key="sb_hr")
        rr_rpm = st.number_input("RR", min_value=5, max_value=50, value=18, key="sb_rr")
    with col2:
        bp_mmhg = st.text_input("BP", "155/90", key="sb_bp")
        spo2_percent = st.number_input("SpO2", min_value=70, max_value=100, value=96, key="sb_spo2")
        pain_scale = st.slider("Pain", min_value=0, max_value=10, value=8, key="sb_pain")

    # Updated minimum height to 68px to satisfy Streamlit requirement
    exam_notes = st.text_area("Exam Notes", "Awake, alert...", height=68, key="sb_exam")

    # Process meds and allergies with comprehensions
    current_meds_list = [m.strip() for m in current_meds_str.splitlines() if m.strip()]
    current_med_names_only = [
        m.group(1).lower()
        for med in current_meds_list
        if (m := re.match(r"^\s*([A-Za-z-]+)", med))
    ]
    allergies_list = [
        (m.group(1).strip().lower() if (m := re.match(r"^\s*([A-Za-z\s/-]+)", a.strip())) else a.strip().lower())
        for a in allergies_str.split(",")
        if a.strip()
    ]

    # Parse blood pressure
    bp_sys, bp_dia = None, None
    if "/" in bp_mmhg:
        try:
            bp_sys, bp_dia = map(int, bp_mmhg.split("/"))
        except ValueError:
            logger.warning(f"Unable to parse BP '{bp_mmhg}'")

    return {
        "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,
            "bp_sys": bp_sys,
            "bp_dia": bp_dia,
            "rr_rpm": rr_rpm,
            "spo2_percent": spo2_percent,
            "pain_scale": pain_scale
        },
        "exam_findings": {"notes": exam_notes},
    }

# Main application
def main():
    st.set_page_config(page_title=ClinicalAppSettings.APP_TITLE, layout=ClinicalAppSettings.PAGE_LAYOUT)
    st.title(f"🩺 {ClinicalAppSettings.APP_TITLE}")
    st.caption(f"Interactive Assistant | LangGraph/Groq/Tavily/UMLS/OpenFDA | Model: {ClinicalAppSettings.MODEL_NAME_DISPLAY}")

    # Initialize session state
    if "messages" not in st.session_state:
        st.session_state.messages = []
    if "patient_data" not in st.session_state:
        st.session_state.patient_data = None
    if "summary" not in st.session_state:
        st.session_state.summary = None
    if "agent" not in st.session_state:
        st.session_state.agent = get_agent()

    # Sidebar intake
    with st.sidebar:
        patient_data = load_patient_intake()
        if st.button("Start/Update Consultation", key="sb_start"):
            st.session_state.patient_data = patient_data
            red_flags = check_red_flags(patient_data)
            st.sidebar.markdown("---")
            if red_flags:
                st.sidebar.warning("**Initial Red Flags:**")
                for flag in red_flags:
                    st.sidebar.warning(f"- {flag.replace('Red Flag: ', '')}")
            else:
                st.sidebar.success("No immediate red flags.")
            st.session_state.messages = [HumanMessage(content="Initiate consultation. Review patient data and begin analysis.")]
            st.session_state.summary = None
            st.success("Patient data loaded/updated.")
            st.rerun()

    # Chat area
    st.header("πŸ’¬ Clinical Consultation")
    for msg in st.session_state.messages:
        if isinstance(msg, HumanMessage):
            with st.chat_message("user"):
                st.markdown(msg.content)
        elif isinstance(msg, AIMessage):
            with st.chat_message("assistant"):
                ai_content = msg.content
                structured_output = None
                try:
                    match = re.search(r"```json\s*(\{.*?\})\s*```", ai_content, re.DOTALL | re.IGNORECASE)
                    if match:
                        payload = match.group(1)
                        structured_output = json.loads(payload)
                        prefix = ai_content[:match.start()].strip()
                        suffix = ai_content[match.end():].strip()
                        if prefix:
                            st.markdown(prefix)
                        if suffix:
                            st.markdown(suffix)
                    else:
                        st.markdown(ai_content)
                except (AttributeError, json.JSONDecodeError) as e:
                    logger.warning(f"JSON parse error: {e}")
                    st.markdown(ai_content)

                if structured_output and isinstance(structured_output, dict):
                    st.divider()
                    # Display structured JSON sections
                    cols = st.columns(2)
                    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', [])
                        if ddx:
                            for item in ddx:
                                likelihood = item.get('likelihood', 'Low')
                                icon = 'πŸ₯‡' if likelihood == 'High' else ('πŸ₯ˆ' if likelihood == 'Medium' else 'πŸ₯‰')
                                with st.expander(f"{icon} {item.get('diagnosis', 'Unknown')} ({likelihood})"):
                                    st.write(f"**Rationale:** {item.get('rationale', 'N/A')}")
                        else:
                            st.info("No DDx provided.")

                        st.markdown("**Risk Assessment:**")
                        risk = structured_output.get('risk_assessment', {})
                        for key, style in [('identified_red_flags', st.warning), ('immediate_concerns', st.warning), ('potential_complications', st.info)]:
                            items = risk.get(key, [])
                            if items:
                                style(f"**{key.replace('_', ' ').capitalize()}:** {', '.join(items)}")
                        if not any(risk.get(k) for k in ['identified_red_flags', 'immediate_concerns', 'potential_complications']):
                            st.success("No specific risks highlighted.")

                    with cols[1]:
                        st.markdown("**Recommended Plan:**")
                        plan = structured_output.get('recommended_plan', {})
                        for section in ["investigations","therapeutics","consultations","patient_education"]:
                            st.markdown(f"_{section.replace('_',' ').capitalize()}:_")
                            items = plan.get(section)
                            if isinstance(items, list):
                                for it in items:
                                    st.markdown(f"- {it}")
                            elif items:
                                st.markdown(f"- {items}")
                            else:
                                st.markdown("_None_")

                    st.markdown("**Rationale & Guideline Check:**")
                    st.markdown(f"> {structured_output.get('rationale_summary', 'N/A')}")
                    if interaction := structured_output.get('interaction_check_summary'):
                        st.markdown("**Interaction Check Summary:**")
                        st.markdown(f"> {interaction}")
                    st.divider()

        elif isinstance(msg, ToolMessage):
            tool_name = getattr(msg, 'name', 'tool_execution')
            with st.chat_message(tool_name, avatar="πŸ› οΈ"):
                try:
                    data = json.loads(msg.content)
                    status = data.get('status', 'info')
                    message = data.get('message', msg.content)
                    if tool_name == "flag_risk" and status == "flagged":
                        st.error(f"🚨 **RISK FLAGGED:** {message}")
                    elif status in ("success", "clear"):
                        st.success(message)
                    elif status == "warning":
                        st.warning(message)
                    else:
                        st.error(message)
                    if details := data.get('details'):
                        st.caption(f"Details: {details}")
                except json.JSONDecodeError:
                    st.info(msg.content)

    # --- Chat Input ---
    if prompt := st.chat_input("Your message or follow-up query..."):
        if not st.session_state.patient_data:
            st.warning("Please load patient data first.")
            st.stop()
        user_msg = HumanMessage(content=prompt)
        st.session_state.messages.append(user_msg)
        with st.chat_message("user"):
            st.markdown(prompt)
        current_state = {
            "messages": st.session_state.messages,
            "patient_data": st.session_state.patient_data,
            "summary": st.session_state.summary,
            "interaction_warnings": None
        }
        with st.spinner("SynapseAI is processing..."):
            try:
                final_state = st.session_state.agent.invoke_turn(current_state)
                st.session_state.messages = final_state.get('messages', [])
                st.session_state.summary = final_state.get('summary')
            except Exception as e:
                logger.exception("Error during agent.invoke_turn")
                st.error(f"Error: {e}")
                st.session_state.messages.append(AIMessage(content=f"Error processing request: {e}"))
        st.rerun()

    # Disclaimer
    st.markdown("---")
    st.warning("**Disclaimer:** SynapseAI is for demonstration only and not for clinical use.")

if __name__ == "__main__":
    main()