mgbam commited on
Commit
23d48f5
Β·
verified Β·
1 Parent(s): a2143ab

Create agent.py

Browse files
Files changed (1) hide show
  1. agent.py +191 -0
agent.py ADDED
@@ -0,0 +1,191 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # app.py
2
+ import streamlit as st
3
+ import json
4
+ import re
5
+ import os
6
+ from dotenv import load_dotenv
7
+
8
+ # Import agent logic and message types
9
+ from agent import ClinicalAgent, AgentState, check_red_flags # Import necessary components
10
+ from langchain_core.messages import HumanMessage, AIMessage, ToolMessage
11
+
12
+ # --- Environment Variable Loading & Validation ---
13
+ load_dotenv()
14
+ # Check keys required by agent.py are present before initializing the agent
15
+ UMLS_API_KEY = os.environ.get("UMLS_API_KEY")
16
+ GROQ_API_KEY = os.environ.get("GROQ_API_KEY")
17
+ TAVILY_API_KEY = os.environ.get("TAVILY_API_KEY")
18
+ missing_keys = []
19
+ if not UMLS_API_KEY: missing_keys.append("UMLS_API_KEY")
20
+ if not GROQ_API_KEY: missing_keys.append("GROQ_API_KEY")
21
+ if not TAVILY_API_KEY: missing_keys.append("TAVILY_API_KEY")
22
+ if missing_keys:
23
+ st.error(f"Missing required API Key(s): {', '.join(missing_keys)}. Please set them in Hugging Face Space Secrets or environment variables.")
24
+ st.stop()
25
+
26
+ # --- App Configuration ---
27
+ class ClinicalAppSettings:
28
+ APP_TITLE = "SynapseAI (UMLS/FDA Integrated)"
29
+ PAGE_LAYOUT = "wide"
30
+ # Model name is now primarily defined in agent.py, but can keep for display
31
+ MODEL_NAME_DISPLAY = "Llama3-70b (via Groq)"
32
+
33
+
34
+ # --- Streamlit UI ---
35
+ def main():
36
+ st.set_page_config(page_title=ClinicalAppSettings.APP_TITLE, layout=ClinicalAppSettings.PAGE_LAYOUT)
37
+ st.title(f"🩺 {ClinicalAppSettings.APP_TITLE}")
38
+ st.caption(f"Interactive Assistant | LangGraph/Groq/Tavily/UMLS/OpenFDA | Model: {ClinicalAppSettings.MODEL_NAME_DISPLAY}")
39
+
40
+ # Initialize session state
41
+ if "messages" not in st.session_state: st.session_state.messages = []
42
+ if "patient_data" not in st.session_state: st.session_state.patient_data = None
43
+ # Summary state for future memory enhancement
44
+ if "summary" not in st.session_state: st.session_state.summary = None
45
+ # Initialize the agent instance only once
46
+ if "agent" not in st.session_state:
47
+ try:
48
+ st.session_state.agent = ClinicalAgent()
49
+ print("ClinicalAgent successfully initialized in Streamlit session state.")
50
+ except Exception as e:
51
+ st.error(f"Failed to initialize Clinical Agent: {e}. Check API keys and dependencies.")
52
+ print(f"ERROR Initializing ClinicalAgent: {e}")
53
+ traceback.print_exc()
54
+ st.stop()
55
+
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
+ # Rerun might be needed if the main area should clear or update based on new data
92
+ st.rerun()
93
+
94
+ # --- Main Chat Interface Area ---
95
+ st.header("πŸ’¬ Clinical Consultation")
96
+ # Display loop - Uses messages from st.session_state
97
+ for msg in st.session_state.messages: # Removed enumerate and key
98
+ if isinstance(msg, HumanMessage):
99
+ with st.chat_message("user"): st.markdown(msg.content)
100
+ elif isinstance(msg, AIMessage):
101
+ with st.chat_message("assistant"):
102
+ # ... (Keep the detailed AI message display logic, including JSON parsing) ...
103
+ ai_content = msg.content; structured_output = None
104
+ try: # JSON Parsing logic...
105
+ json_match = re.search(r"```json\s*(\{.*?\})\s*```", ai_content, re.DOTALL | re.IGNORECASE)
106
+ if json_match: json_str = json_match.group(1); prefix = ai_content[:json_match.start()].strip(); suffix = ai_content[json_match.end():].strip();
107
+ if prefix: st.markdown(prefix); structured_output = json.loads(json_str);
108
+ if suffix: st.markdown(suffix)
109
+ elif ai_content.strip().startswith("{") and ai_content.strip().endswith("}"): structured_output = json.loads(ai_content); ai_content = ""
110
+ else: st.markdown(ai_content) # Display non-JSON content
111
+ except Exception as e: st.markdown(ai_content); print(f"Error parsing/displaying AI JSON: {e}")
112
+ if structured_output and isinstance(structured_output, dict): # Structured JSON display logic...
113
+ st.divider(); st.subheader("πŸ“Š AI Analysis & Recommendations")
114
+ # ... (Keep detailed JSON display logic for assessment, ddx, plan, etc.) ...
115
+ cols = st.columns(2);
116
+ 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', []);
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."); 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",[])
119
+ 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)}");
120
+ if not flags and not concerns: st.success("No major risks highlighted.")
121
+ with cols[1]: st.markdown("**Recommended Plan:**"); plan = structured_output.get('recommended_plan', {});
122
+ 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("")
123
+ st.markdown("**Rationale & Guideline Check:**"); st.markdown(f"> {structured_output.get('rationale_summary', 'N/A')}"); interaction_summary = structured_output.get("interaction_check_summary", "");
124
+ if interaction_summary: st.markdown("**Interaction Check Summary:**"); st.markdown(f"> {interaction_summary}"); st.divider()
125
+
126
+ # Tool Call Display
127
+ if getattr(msg, 'tool_calls', None):
128
+ with st.expander("πŸ› οΈ AI requested actions", expanded=False):
129
+ if msg.tool_calls:
130
+ for tc in msg.tool_calls:
131
+ try: st.code(f"Action: {tc.get('name', 'Unknown Tool')}\nArgs: {json.dumps(tc.get('args', {}), indent=2)}", language="json")
132
+ 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')}")
133
+ else: st.caption("_No actions requested._")
134
+ elif isinstance(msg, ToolMessage):
135
+ tool_name_display = getattr(msg, 'name', 'tool_execution')
136
+ with st.chat_message(tool_name_display, avatar="πŸ› οΈ"):
137
+ # ... (Keep ToolMessage display logic) ...
138
+ try:
139
+ 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");
140
+ if status == "success" or status == "clear" or status == "flagged": st.success(f"{message}", icon="βœ…" if status != "flagged" else "🚨")
141
+ elif status == "warning": st.warning(f"{message}", icon="⚠️");
142
+ if warnings and isinstance(warnings, list): st.caption("Details:"); [st.caption(f"- {warn}") for warn in warnings]
143
+ else: st.error(f"{message}", icon="❌") # Assume error if not known status
144
+ if details: st.caption(f"Details: {details}")
145
+ except json.JSONDecodeError: st.info(f"{msg.content}") # Display raw if not JSON
146
+ except Exception as e: st.error(f"Error displaying tool message: {e}", icon="❌"); st.caption(f"Raw content: {msg.content}")
147
+
148
+
149
+ # --- Chat Input Logic ---
150
+ if prompt := st.chat_input("Your message or follow-up query..."):
151
+ if not st.session_state.patient_data: st.warning("Please load patient data first."); st.stop()
152
+ if not st.session_state.agent: st.error("Agent not initialized. Check logs."); st.stop() # Add check for agent
153
+
154
+ # Append user message and display immediately
155
+ user_message = HumanMessage(content=prompt)
156
+ st.session_state.messages.append(user_message)
157
+ with st.chat_message("user"): st.markdown(prompt)
158
+
159
+ # Prepare state for the agent, including existing messages and patient data
160
+ current_state_dict = {
161
+ "messages": st.session_state.messages,
162
+ "patient_data": st.session_state.patient_data,
163
+ "summary": st.session_state.get("summary"), # Include summary if implemented
164
+ "interaction_warnings": None # Always start turn with no pending warnings
165
+ }
166
+
167
+ # Invoke the agent's graph for one turn
168
+ with st.spinner("SynapseAI is thinking..."):
169
+ try:
170
+ # Call the agent instance's method
171
+ final_state = st.session_state.agent.invoke_turn(current_state_dict)
172
+
173
+ # Update Streamlit session state from the returned agent state
174
+ st.session_state.messages = final_state.get('messages', [])
175
+ st.session_state.summary = final_state.get('summary') # Update summary if implemented
176
+
177
+ except Exception as e:
178
+ print(f"CRITICAL ERROR during agent invocation: {type(e).__name__} - {e}")
179
+ traceback.print_exc()
180
+ st.error(f"An error occurred during processing: {e}", icon="❌")
181
+ # Optionally append an error message to the chat display
182
+ # st.session_state.messages.append(AIMessage(content=f"Error processing request: {e}"))
183
+
184
+ # Rerun Streamlit script to update the chat display
185
+ st.rerun()
186
+
187
+ # Disclaimer
188
+ st.markdown("---"); st.warning("**Disclaimer:** SynapseAI is for demonstration...")
189
+
190
+ if __name__ == "__main__":
191
+ main()