Update app.py
Browse files
app.py
CHANGED
|
@@ -12,6 +12,7 @@ from dotenv import load_dotenv
|
|
| 12 |
from langchain_groq import ChatGroq
|
| 13 |
from langchain_community.tools.tavily_search import TavilySearchResults
|
| 14 |
from langchain_core.messages import HumanMessage, SystemMessage, AIMessage, ToolMessage
|
|
|
|
| 15 |
from langchain_core.pydantic_v1 import BaseModel, Field
|
| 16 |
from langchain_core.tools import tool
|
| 17 |
from langgraph.prebuilt import ToolExecutor
|
|
@@ -25,82 +26,146 @@ UMLS_API_KEY = os.environ.get("UMLS_API_KEY")
|
|
| 25 |
GROQ_API_KEY = os.environ.get("GROQ_API_KEY")
|
| 26 |
TAVILY_API_KEY = os.environ.get("TAVILY_API_KEY")
|
| 27 |
missing_keys = []
|
| 28 |
-
if not UMLS_API_KEY:
|
| 29 |
-
|
| 30 |
-
if not
|
| 31 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 32 |
|
| 33 |
# --- Configuration & Constants ---
|
| 34 |
-
class ClinicalAppSettings:
|
| 35 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 36 |
You are SynapseAI, an expert AI clinical assistant engaged in an interactive consultation... [SYSTEM PROMPT REMAINS THE SAME - OMITTED FOR BREVITY]
|
| 37 |
"""
|
| 38 |
|
| 39 |
# --- API Helper Functions (get_rxcui, get_openfda_label, search_text_list) ---
|
| 40 |
-
|
| 41 |
-
|
|
|
|
|
|
|
| 42 |
@lru_cache(maxsize=256)
|
| 43 |
def get_rxcui(drug_name: str) -> Optional[str]:
|
| 44 |
-
if not drug_name or not isinstance(drug_name, str):
|
| 45 |
-
|
| 46 |
-
|
| 47 |
-
|
| 48 |
-
|
| 49 |
-
|
| 50 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 51 |
if data and "drugGroup" in data and "conceptGroup" in data["drugGroup"]:
|
| 52 |
for group in data["drugGroup"]["conceptGroup"]:
|
| 53 |
if group.get("tty") in ["SBD", "SCD", "GPCK", "BPCK", "IN", "MIN", "PIN"]:
|
| 54 |
-
if "conceptProperties" in group and group["conceptProperties"]:
|
| 55 |
-
|
| 56 |
-
|
| 57 |
-
|
| 58 |
-
|
| 59 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 60 |
@lru_cache(maxsize=128)
|
| 61 |
def get_openfda_label(rxcui: Optional[str] = None, drug_name: Optional[str] = None) -> Optional[dict]:
|
| 62 |
-
if not rxcui and not drug_name:
|
| 63 |
-
|
| 64 |
-
|
| 65 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 66 |
try:
|
| 67 |
-
response = requests.get(OPENFDA_API_BASE, params=params, timeout=15)
|
| 68 |
-
|
| 69 |
-
|
| 70 |
-
|
| 71 |
-
|
| 72 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 73 |
def search_text_list(text_list: Optional[List[str]], search_terms: List[str]) -> List[str]:
|
| 74 |
-
found_snippets = []
|
| 75 |
-
if not text_list or not search_terms:
|
|
|
|
|
|
|
| 76 |
for text_item in text_list:
|
| 77 |
-
if not isinstance(text_item, str):
|
|
|
|
|
|
|
| 78 |
for term in search_terms_lower:
|
| 79 |
if term in text_item_lower:
|
| 80 |
-
start_index = text_item_lower.find(term)
|
| 81 |
-
|
| 82 |
-
|
|
|
|
|
|
|
| 83 |
found_snippets.append(f"...{snippet}...")
|
| 84 |
-
break
|
| 85 |
return found_snippets
|
| 86 |
|
| 87 |
|
| 88 |
-
# --- Other Helper Functions ---
|
| 89 |
def parse_bp(bp_string: str) -> Optional[tuple[int, int]]:
|
| 90 |
-
if not isinstance(bp_string, str):
|
| 91 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
| 92 |
|
| 93 |
-
# CORRECTED check_red_flags function
|
| 94 |
def check_red_flags(patient_data: dict) -> List[str]:
|
| 95 |
-
"""Checks patient data against predefined red flags."""
|
| 96 |
flags = []
|
| 97 |
-
if not patient_data:
|
|
|
|
| 98 |
symptoms = patient_data.get("hpi", {}).get("symptoms", [])
|
| 99 |
vitals = patient_data.get("vitals", {})
|
| 100 |
history = patient_data.get("pmh", {}).get("conditions", "")
|
| 101 |
symptoms_lower = [str(s).lower() for s in symptoms if isinstance(s, str)]
|
| 102 |
-
|
| 103 |
-
# Symptom Flags (CORRECTED - Separate lines)
|
| 104 |
if "chest pain" in symptoms_lower:
|
| 105 |
flags.append("Red Flag: Chest Pain reported.")
|
| 106 |
if "shortness of breath" in symptoms_lower:
|
|
@@ -115,260 +180,548 @@ def check_red_flags(patient_data: dict) -> List[str]:
|
|
| 115 |
flags.append("Red Flag: Hemoptysis (coughing up blood).")
|
| 116 |
if "syncope" in symptoms_lower:
|
| 117 |
flags.append("Red Flag: Syncope (fainting).")
|
| 118 |
-
|
| 119 |
-
# Vital Sign Flags
|
| 120 |
if vitals:
|
| 121 |
-
temp = vitals.get("temp_c")
|
| 122 |
-
|
| 123 |
-
|
| 124 |
-
|
| 125 |
-
|
| 126 |
-
|
| 127 |
-
if
|
| 128 |
-
|
| 129 |
-
|
| 130 |
-
|
| 131 |
-
|
| 132 |
-
|
| 133 |
-
|
| 134 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 135 |
if history and isinstance(history, str):
|
| 136 |
history_lower = history.lower()
|
| 137 |
if "history of mi" in history_lower and "chest pain" in symptoms_lower:
|
| 138 |
flags.append("Red Flag: History of MI with current Chest Pain.")
|
| 139 |
if "history of dvt/pe" in history_lower and "shortness of breath" in symptoms_lower:
|
| 140 |
-
|
| 141 |
-
|
| 142 |
-
return list(set(flags))
|
| 143 |
|
| 144 |
def format_patient_data_for_prompt(data: dict) -> str:
|
| 145 |
-
|
| 146 |
-
|
| 147 |
-
|
| 148 |
-
|
| 149 |
-
|
| 150 |
-
|
| 151 |
-
|
| 152 |
-
|
| 153 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 154 |
return prompt_str.strip()
|
| 155 |
|
| 156 |
|
| 157 |
# --- Tool Definitions ---
|
| 158 |
-
class LabOrderInput(BaseModel):
|
| 159 |
-
|
| 160 |
-
|
| 161 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 162 |
|
| 163 |
@tool("order_lab_test", args_schema=LabOrderInput)
|
| 164 |
def order_lab_test(test_name: str, reason: str, priority: str = "Routine") -> str:
|
| 165 |
-
print(f"Executing order_lab_test: {test_name}, Reason: {reason}, Priority: {priority}")
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 166 |
@tool("prescribe_medication", args_schema=PrescriptionInput)
|
| 167 |
def prescribe_medication(medication_name: str, dosage: str, route: str, frequency: str, duration: str, reason: str) -> str:
|
| 168 |
-
print(f"Executing prescribe_medication: {medication_name} {dosage}...")
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 169 |
@tool("check_drug_interactions", args_schema=InteractionCheckInput)
|
| 170 |
def check_drug_interactions(potential_prescription: str, current_medications: Optional[List[str]] = None, allergies: Optional[List[str]] = None) -> str:
|
| 171 |
-
|
| 172 |
-
print(f"
|
| 173 |
-
|
| 174 |
-
|
| 175 |
-
|
| 176 |
-
|
| 177 |
-
|
| 178 |
-
|
| 179 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 180 |
for allergy in allergies_lower:
|
| 181 |
-
if allergy == potential_med_lower:
|
| 182 |
-
|
| 183 |
-
elif allergy
|
| 184 |
-
|
| 185 |
-
|
| 186 |
-
|
| 187 |
-
|
| 188 |
-
|
| 189 |
-
if
|
| 190 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 191 |
if potential_rxcui or potential_label:
|
| 192 |
for current_med_name in current_med_names_lower:
|
| 193 |
-
if not current_med_name or current_med_name == potential_med_lower:
|
| 194 |
-
|
| 195 |
-
|
| 196 |
-
|
| 197 |
-
|
| 198 |
-
|
| 199 |
-
if
|
| 200 |
-
|
| 201 |
-
|
| 202 |
-
|
| 203 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 204 |
@tool("flag_risk", args_schema=FlagRiskInput)
|
| 205 |
def flag_risk(risk_description: str, urgency: str) -> str:
|
| 206 |
-
print(f"Executing flag_risk: {risk_description}, Urgency: {urgency}")
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 207 |
search_tool = TavilySearchResults(max_results=ClinicalAppSettings.MAX_SEARCH_RESULTS, name="tavily_search_results")
|
| 208 |
|
| 209 |
# --- LangGraph Setup ---
|
| 210 |
-
class AgentState(TypedDict):
|
|
|
|
|
|
|
|
|
|
| 211 |
tools = [order_lab_test, prescribe_medication, check_drug_interactions, flag_risk, search_tool]
|
| 212 |
tool_executor = ToolExecutor(tools)
|
| 213 |
model = ChatGroq(temperature=ClinicalAppSettings.TEMPERATURE, model=ClinicalAppSettings.MODEL_NAME)
|
| 214 |
model_with_tools = model.bind_tools(tools)
|
| 215 |
|
| 216 |
# --- Graph Nodes (agent_node, tool_node) ---
|
| 217 |
-
# ... (Keep these functions exactly as they were) ...
|
| 218 |
def agent_node(state: AgentState):
|
| 219 |
-
print("\n---AGENT NODE---")
|
| 220 |
-
|
| 221 |
-
|
| 222 |
-
|
| 223 |
-
|
| 224 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 225 |
return {"messages": [response]}
|
|
|
|
| 226 |
def tool_node(state: AgentState):
|
| 227 |
-
print("\n---TOOL NODE---")
|
| 228 |
-
|
| 229 |
-
|
| 230 |
-
|
| 231 |
-
|
| 232 |
-
|
| 233 |
-
|
| 234 |
-
|
| 235 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 236 |
for med_name, prescribe_call in prescriptions_requested.items():
|
| 237 |
-
if med_name not in interaction_checks_requested:
|
| 238 |
-
|
| 239 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 240 |
for call in valid_tool_calls_for_execution:
|
| 241 |
if call['name'] == 'check_drug_interactions':
|
| 242 |
-
if 'args' not in call:
|
| 243 |
-
|
| 244 |
-
|
| 245 |
-
|
| 246 |
-
|
| 247 |
-
if
|
| 248 |
-
|
| 249 |
-
|
| 250 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 251 |
|
| 252 |
# --- Graph Edges (Routing Logic) ---
|
| 253 |
def should_continue(state: AgentState) -> str:
|
| 254 |
-
print("\n---ROUTING DECISION---")
|
| 255 |
-
|
| 256 |
-
if
|
| 257 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 258 |
|
| 259 |
# --- Graph Definition & Compilation ---
|
| 260 |
-
workflow = StateGraph(AgentState)
|
| 261 |
-
workflow.
|
| 262 |
-
workflow.
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 263 |
|
| 264 |
# --- Streamlit UI ---
|
| 265 |
def main():
|
| 266 |
st.set_page_config(page_title=ClinicalAppSettings.APP_TITLE, layout=ClinicalAppSettings.PAGE_LAYOUT)
|
| 267 |
st.title(f"π©Ί {ClinicalAppSettings.APP_TITLE}")
|
| 268 |
st.caption(f"Interactive Assistant | LangGraph/Groq/Tavily/UMLS/OpenFDA | Model: {ClinicalAppSettings.MODEL_NAME}")
|
| 269 |
-
if "messages" not in st.session_state:
|
| 270 |
-
|
| 271 |
-
if "
|
|
|
|
|
|
|
|
|
|
| 272 |
|
| 273 |
# --- Patient Data Input Sidebar ---
|
| 274 |
with st.sidebar:
|
| 275 |
st.header("π Patient Intake Form")
|
| 276 |
-
# Input fields...
|
| 277 |
-
st.subheader("Demographics")
|
| 278 |
-
|
| 279 |
-
|
| 280 |
-
st.subheader("
|
| 281 |
-
|
| 282 |
-
st.
|
| 283 |
-
|
| 284 |
-
|
| 285 |
-
|
| 286 |
-
|
| 287 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 288 |
current_meds_list = [med.strip() for med in current_meds_str.split('\n') if med.strip()]
|
| 289 |
-
current_med_names_only = []
|
| 290 |
-
for med in current_meds_list:
|
| 291 |
-
|
|
|
|
|
|
|
| 292 |
allergies_list = []
|
| 293 |
-
for a in allergies_str.split(','):
|
| 294 |
-
|
| 295 |
-
|
| 296 |
-
|
| 297 |
-
|
| 298 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 299 |
initial_prompt = "Initiate consultation. Review patient data and begin analysis."
|
| 300 |
-
st.session_state.messages = [HumanMessage(content=initial_prompt)]
|
|
|
|
| 301 |
|
| 302 |
# --- Main Chat Interface Area ---
|
| 303 |
st.header("π¬ Clinical Consultation")
|
| 304 |
-
# Display loop -
|
| 305 |
for msg in st.session_state.messages:
|
| 306 |
if isinstance(msg, HumanMessage):
|
| 307 |
-
with st.chat_message("user"):
|
|
|
|
| 308 |
elif isinstance(msg, AIMessage):
|
| 309 |
with st.chat_message("assistant"):
|
| 310 |
-
ai_content = msg.content
|
| 311 |
-
|
|
|
|
| 312 |
json_match = re.search(r"```json\s*(\{.*?\})\s*```", ai_content, re.DOTALL | re.IGNORECASE)
|
| 313 |
-
if json_match:
|
| 314 |
-
|
| 315 |
-
|
| 316 |
-
|
| 317 |
-
|
| 318 |
-
|
| 319 |
-
|
| 320 |
-
|
| 321 |
-
|
| 322 |
-
|
| 323 |
-
|
| 324 |
-
|
| 325 |
-
|
| 326 |
-
|
| 327 |
-
|
| 328 |
-
|
| 329 |
-
|
| 330 |
-
|
| 331 |
-
|
| 332 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 333 |
if getattr(msg, 'tool_calls', None):
|
| 334 |
-
|
| 335 |
-
|
| 336 |
for tc in msg.tool_calls:
|
| 337 |
try:
|
| 338 |
st.code(f"Action: {tc.get('name', 'Unknown Tool')}\nArgs: {json.dumps(tc.get('args', {}), indent=2)}", language="json")
|
| 339 |
except Exception as display_e:
|
| 340 |
-
st.error(f"Could not display tool call
|
| 341 |
st.code(f"Action: {tc.get('name', 'Unknown Tool')}\nRaw Args: {tc.get('args')}")
|
| 342 |
-
|
| 343 |
-
st.caption("_No actions requested._")
|
| 344 |
elif isinstance(msg, ToolMessage):
|
| 345 |
tool_name_display = getattr(msg, 'name', 'tool_execution')
|
| 346 |
-
with st.chat_message(tool_name_display, avatar="π οΈ"):
|
| 347 |
-
try:
|
| 348 |
-
tool_data = json.loads(msg.content)
|
| 349 |
-
|
| 350 |
-
|
| 351 |
-
|
| 352 |
-
|
| 353 |
-
if
|
| 354 |
-
|
| 355 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 356 |
|
| 357 |
# --- Chat Input Logic ---
|
| 358 |
if prompt := st.chat_input("Your message or follow-up query..."):
|
| 359 |
-
if not st.session_state.patient_data:
|
| 360 |
-
|
| 361 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
| 362 |
current_state = AgentState(messages=st.session_state.messages, patient_data=st.session_state.patient_data)
|
| 363 |
with st.spinner("SynapseAI is thinking..."):
|
| 364 |
try:
|
| 365 |
final_state = st.session_state.graph_app.invoke(current_state, {"recursion_limit": 15})
|
| 366 |
st.session_state.messages = final_state['messages']
|
| 367 |
-
except Exception as e:
|
|
|
|
|
|
|
|
|
|
| 368 |
st.rerun()
|
| 369 |
|
| 370 |
# Disclaimer
|
| 371 |
-
st.markdown("---")
|
|
|
|
| 372 |
|
| 373 |
if __name__ == "__main__":
|
| 374 |
-
main()
|
|
|
|
| 12 |
from langchain_groq import ChatGroq
|
| 13 |
from langchain_community.tools.tavily_search import TavilySearchResults
|
| 14 |
from langchain_core.messages import HumanMessage, SystemMessage, AIMessage, ToolMessage
|
| 15 |
+
# from langchain_core.prompts import ChatPromptTemplate # Not explicitly used
|
| 16 |
from langchain_core.pydantic_v1 import BaseModel, Field
|
| 17 |
from langchain_core.tools import tool
|
| 18 |
from langgraph.prebuilt import ToolExecutor
|
|
|
|
| 26 |
GROQ_API_KEY = os.environ.get("GROQ_API_KEY")
|
| 27 |
TAVILY_API_KEY = os.environ.get("TAVILY_API_KEY")
|
| 28 |
missing_keys = []
|
| 29 |
+
if not UMLS_API_KEY:
|
| 30 |
+
missing_keys.append("UMLS_API_KEY")
|
| 31 |
+
if not GROQ_API_KEY:
|
| 32 |
+
missing_keys.append("GROQ_API_KEY")
|
| 33 |
+
if not TAVILY_API_KEY:
|
| 34 |
+
missing_keys.append("TAVILY_API_KEY")
|
| 35 |
+
if missing_keys:
|
| 36 |
+
st.error(f"Missing API Key(s): {', '.join(missing_keys)}.")
|
| 37 |
+
st.stop()
|
| 38 |
|
| 39 |
# --- Configuration & Constants ---
|
| 40 |
+
class ClinicalAppSettings:
|
| 41 |
+
APP_TITLE = "SynapseAI (UMLS/FDA Integrated)"
|
| 42 |
+
PAGE_LAYOUT = "wide"
|
| 43 |
+
MODEL_NAME = "llama3-70b-8192"
|
| 44 |
+
TEMPERATURE = 0.1
|
| 45 |
+
MAX_SEARCH_RESULTS = 3
|
| 46 |
+
|
| 47 |
+
class ClinicalPrompts:
|
| 48 |
+
SYSTEM_PROMPT = """
|
| 49 |
You are SynapseAI, an expert AI clinical assistant engaged in an interactive consultation... [SYSTEM PROMPT REMAINS THE SAME - OMITTED FOR BREVITY]
|
| 50 |
"""
|
| 51 |
|
| 52 |
# --- API Helper Functions (get_rxcui, get_openfda_label, search_text_list) ---
|
| 53 |
+
UMLS_AUTH_ENDPOINT = "https://utslogin.nlm.nih.gov/cas/v1/api-key"
|
| 54 |
+
RXNORM_API_BASE = "https://rxnav.nlm.nih.gov/REST"
|
| 55 |
+
OPENFDA_API_BASE = "https://api.fda.gov/drug/label.json"
|
| 56 |
+
|
| 57 |
@lru_cache(maxsize=256)
|
| 58 |
def get_rxcui(drug_name: str) -> Optional[str]:
|
| 59 |
+
if not drug_name or not isinstance(drug_name, str):
|
| 60 |
+
return None
|
| 61 |
+
drug_name = drug_name.strip()
|
| 62 |
+
if not drug_name:
|
| 63 |
+
return None
|
| 64 |
+
print(f"RxNorm Lookup for: '{drug_name}'")
|
| 65 |
+
try:
|
| 66 |
+
params = {"name": drug_name, "search": 1}
|
| 67 |
+
response = requests.get(f"{RXNORM_API_BASE}/rxcui.json", params=params, timeout=10)
|
| 68 |
+
response.raise_for_status()
|
| 69 |
+
data = response.json()
|
| 70 |
+
if data and "idGroup" in data and "rxnormId" in data["idGroup"]:
|
| 71 |
+
rxcui = data["idGroup"]["rxnormId"][0]
|
| 72 |
+
print(f" Found RxCUI: {rxcui} for '{drug_name}'")
|
| 73 |
+
return rxcui
|
| 74 |
+
else:
|
| 75 |
+
params = {"name": drug_name}
|
| 76 |
+
response = requests.get(f"{RXNORM_API_BASE}/drugs.json", params=params, timeout=10)
|
| 77 |
+
response.raise_for_status()
|
| 78 |
+
data = response.json()
|
| 79 |
if data and "drugGroup" in data and "conceptGroup" in data["drugGroup"]:
|
| 80 |
for group in data["drugGroup"]["conceptGroup"]:
|
| 81 |
if group.get("tty") in ["SBD", "SCD", "GPCK", "BPCK", "IN", "MIN", "PIN"]:
|
| 82 |
+
if "conceptProperties" in group and group["conceptProperties"]:
|
| 83 |
+
rxcui = group["conceptProperties"][0].get("rxcui")
|
| 84 |
+
if rxcui:
|
| 85 |
+
print(f" Found RxCUI (via /drugs): {rxcui} for '{drug_name}'")
|
| 86 |
+
return rxcui
|
| 87 |
+
print(f" RxCUI not found for '{drug_name}'.")
|
| 88 |
+
return None
|
| 89 |
+
except requests.exceptions.RequestException as e:
|
| 90 |
+
print(f" Error fetching RxCUI for '{drug_name}': {e}")
|
| 91 |
+
return None
|
| 92 |
+
except json.JSONDecodeError as e:
|
| 93 |
+
print(f" Error decoding RxNorm JSON response for '{drug_name}': {e}")
|
| 94 |
+
return None
|
| 95 |
+
except Exception as e:
|
| 96 |
+
print(f" Unexpected error in get_rxcui for '{drug_name}': {e}")
|
| 97 |
+
return None
|
| 98 |
+
|
| 99 |
@lru_cache(maxsize=128)
|
| 100 |
def get_openfda_label(rxcui: Optional[str] = None, drug_name: Optional[str] = None) -> Optional[dict]:
|
| 101 |
+
if not rxcui and not drug_name:
|
| 102 |
+
return None
|
| 103 |
+
print(f"OpenFDA Label Lookup for: RXCUI={rxcui}, Name={drug_name}")
|
| 104 |
+
search_terms = []
|
| 105 |
+
if rxcui:
|
| 106 |
+
search_terms.append(f'spl_rxnorm_code:"{rxcui}" OR openfda.rxcui:"{rxcui}"')
|
| 107 |
+
if drug_name:
|
| 108 |
+
search_terms.append(f'(openfda.brand_name:"{drug_name.lower()}" OR openfda.generic_name:"{drug_name.lower()}")')
|
| 109 |
+
search_query = " OR ".join(search_terms)
|
| 110 |
+
params = {"search": search_query, "limit": 1}
|
| 111 |
try:
|
| 112 |
+
response = requests.get(OPENFDA_API_BASE, params=params, timeout=15)
|
| 113 |
+
response.raise_for_status()
|
| 114 |
+
data = response.json()
|
| 115 |
+
if data and "results" in data and data["results"]:
|
| 116 |
+
print(f" Found OpenFDA label for query: {search_query}")
|
| 117 |
+
return data["results"][0]
|
| 118 |
+
print(f" No OpenFDA label found for query: {search_query}")
|
| 119 |
+
return None
|
| 120 |
+
except requests.exceptions.RequestException as e:
|
| 121 |
+
print(f" Error fetching OpenFDA label: {e}")
|
| 122 |
+
return None
|
| 123 |
+
except json.JSONDecodeError as e:
|
| 124 |
+
print(f" Error decoding OpenFDA JSON response: {e}")
|
| 125 |
+
return None
|
| 126 |
+
except Exception as e:
|
| 127 |
+
print(f" Unexpected error in get_openfda_label: {e}")
|
| 128 |
+
return None
|
| 129 |
+
|
| 130 |
def search_text_list(text_list: Optional[List[str]], search_terms: List[str]) -> List[str]:
|
| 131 |
+
found_snippets = []
|
| 132 |
+
if not text_list or not search_terms:
|
| 133 |
+
return found_snippets
|
| 134 |
+
search_terms_lower = [str(term).lower() for term in search_terms if term]
|
| 135 |
for text_item in text_list:
|
| 136 |
+
if not isinstance(text_item, str):
|
| 137 |
+
continue
|
| 138 |
+
text_item_lower = text_item.lower()
|
| 139 |
for term in search_terms_lower:
|
| 140 |
if term in text_item_lower:
|
| 141 |
+
start_index = text_item_lower.find(term)
|
| 142 |
+
snippet_start = max(0, start_index - 50)
|
| 143 |
+
snippet_end = min(len(text_item), start_index + len(term) + 100)
|
| 144 |
+
snippet = text_item[snippet_start:snippet_end]
|
| 145 |
+
snippet = snippet.replace(term, f"**{term}**", 1)
|
| 146 |
found_snippets.append(f"...{snippet}...")
|
| 147 |
+
break
|
| 148 |
return found_snippets
|
| 149 |
|
| 150 |
|
| 151 |
+
# --- Other Helper Functions (parse_bp, check_red_flags, format_patient_data_for_prompt) ---
|
| 152 |
def parse_bp(bp_string: str) -> Optional[tuple[int, int]]:
|
| 153 |
+
if not isinstance(bp_string, str):
|
| 154 |
+
return None
|
| 155 |
+
match = re.match(r"(\d{1,3})\s*/\s*(\d{1,3})", bp_string.strip())
|
| 156 |
+
if match:
|
| 157 |
+
return int(match.group(1)), int(match.group(2))
|
| 158 |
+
return None
|
| 159 |
|
|
|
|
| 160 |
def check_red_flags(patient_data: dict) -> List[str]:
|
|
|
|
| 161 |
flags = []
|
| 162 |
+
if not patient_data:
|
| 163 |
+
return flags
|
| 164 |
symptoms = patient_data.get("hpi", {}).get("symptoms", [])
|
| 165 |
vitals = patient_data.get("vitals", {})
|
| 166 |
history = patient_data.get("pmh", {}).get("conditions", "")
|
| 167 |
symptoms_lower = [str(s).lower() for s in symptoms if isinstance(s, str)]
|
| 168 |
+
|
|
|
|
| 169 |
if "chest pain" in symptoms_lower:
|
| 170 |
flags.append("Red Flag: Chest Pain reported.")
|
| 171 |
if "shortness of breath" in symptoms_lower:
|
|
|
|
| 180 |
flags.append("Red Flag: Hemoptysis (coughing up blood).")
|
| 181 |
if "syncope" in symptoms_lower:
|
| 182 |
flags.append("Red Flag: Syncope (fainting).")
|
| 183 |
+
|
|
|
|
| 184 |
if vitals:
|
| 185 |
+
temp = vitals.get("temp_c")
|
| 186 |
+
hr = vitals.get("hr_bpm")
|
| 187 |
+
rr = vitals.get("rr_rpm")
|
| 188 |
+
spo2 = vitals.get("spo2_percent")
|
| 189 |
+
bp_str = vitals.get("bp_mmhg")
|
| 190 |
+
|
| 191 |
+
if temp is not None and temp >= 38.5:
|
| 192 |
+
flags.append(f"Red Flag: Fever ({temp}Β°C).")
|
| 193 |
+
if hr is not None and hr >= 120:
|
| 194 |
+
flags.append(f"Red Flag: Tachycardia ({hr} bpm).")
|
| 195 |
+
if hr is not None and hr <= 50:
|
| 196 |
+
flags.append(f"Red Flag: Bradycardia ({hr} bpm).")
|
| 197 |
+
if rr is not None and rr >= 24:
|
| 198 |
+
flags.append(f"Red Flag: Tachypnea ({rr} rpm).")
|
| 199 |
+
if spo2 is not None and spo2 <= 92:
|
| 200 |
+
flags.append(f"Red Flag: Hypoxia ({spo2}%).")
|
| 201 |
+
|
| 202 |
+
if bp_str:
|
| 203 |
+
bp = parse_bp(bp_str)
|
| 204 |
+
if bp:
|
| 205 |
+
if bp[0] >= 180 or bp[1] >= 110:
|
| 206 |
+
flags.append(f"Red Flag: Hypertensive Urgency/Emergency (BP: {bp_str} mmHg).")
|
| 207 |
+
if bp[0] <= 90 or bp[1] <= 60:
|
| 208 |
+
flags.append(f"Red Flag: Hypotension (BP: {bp_str} mmHg).")
|
| 209 |
+
|
| 210 |
if history and isinstance(history, str):
|
| 211 |
history_lower = history.lower()
|
| 212 |
if "history of mi" in history_lower and "chest pain" in symptoms_lower:
|
| 213 |
flags.append("Red Flag: History of MI with current Chest Pain.")
|
| 214 |
if "history of dvt/pe" in history_lower and "shortness of breath" in symptoms_lower:
|
| 215 |
+
flags.append("Red Flag: History of DVT/PE with current Shortness of Breath.")
|
| 216 |
+
|
| 217 |
+
return list(set(flags))
|
| 218 |
|
| 219 |
def format_patient_data_for_prompt(data: dict) -> str:
|
| 220 |
+
if not data:
|
| 221 |
+
return "No patient data provided."
|
| 222 |
+
prompt_str = ""
|
| 223 |
+
for key, value in data.items():
|
| 224 |
+
section_title = key.replace('_', ' ').title()
|
| 225 |
+
if isinstance(value, dict) and value:
|
| 226 |
+
has_content = any(sub_value for sub_value in value.values())
|
| 227 |
+
if has_content:
|
| 228 |
+
prompt_str += f"**{section_title}:**\n"
|
| 229 |
+
for sub_key, sub_value in value.items():
|
| 230 |
+
if sub_value:
|
| 231 |
+
prompt_str += f" - {sub_key.replace('_', ' ').title()}: {sub_value}\n"
|
| 232 |
+
elif isinstance(value, list) and value:
|
| 233 |
+
prompt_str += f"**{section_title}:** {', '.join(map(str, value))}\n"
|
| 234 |
+
elif value and not isinstance(value, dict):
|
| 235 |
+
prompt_str += f"**{section_title}:** {value}\n"
|
| 236 |
return prompt_str.strip()
|
| 237 |
|
| 238 |
|
| 239 |
# --- Tool Definitions ---
|
| 240 |
+
class LabOrderInput(BaseModel):
|
| 241 |
+
test_name: str = Field(...)
|
| 242 |
+
reason: str = Field(...)
|
| 243 |
+
priority: str = Field("Routine")
|
| 244 |
+
|
| 245 |
+
class PrescriptionInput(BaseModel):
|
| 246 |
+
medication_name: str = Field(...)
|
| 247 |
+
dosage: str = Field(...)
|
| 248 |
+
route: str = Field(...)
|
| 249 |
+
frequency: str = Field(...)
|
| 250 |
+
duration: str = Field("As directed")
|
| 251 |
+
reason: str = Field(...)
|
| 252 |
+
|
| 253 |
+
class InteractionCheckInput(BaseModel):
|
| 254 |
+
potential_prescription: str = Field(...)
|
| 255 |
+
current_medications: Optional[List[str]] = Field(None)
|
| 256 |
+
allergies: Optional[List[str]] = Field(None)
|
| 257 |
+
|
| 258 |
+
class FlagRiskInput(BaseModel):
|
| 259 |
+
risk_description: str = Field(...)
|
| 260 |
+
urgency: str = Field("High")
|
| 261 |
|
| 262 |
@tool("order_lab_test", args_schema=LabOrderInput)
|
| 263 |
def order_lab_test(test_name: str, reason: str, priority: str = "Routine") -> str:
|
| 264 |
+
print(f"Executing order_lab_test: {test_name}, Reason: {reason}, Priority: {priority}")
|
| 265 |
+
return json.dumps({
|
| 266 |
+
"status": "success",
|
| 267 |
+
"message": f"Lab Ordered: {test_name} ({priority})",
|
| 268 |
+
"details": f"Reason: {reason}"
|
| 269 |
+
})
|
| 270 |
+
|
| 271 |
@tool("prescribe_medication", args_schema=PrescriptionInput)
|
| 272 |
def prescribe_medication(medication_name: str, dosage: str, route: str, frequency: str, duration: str, reason: str) -> str:
|
| 273 |
+
print(f"Executing prescribe_medication: {medication_name} {dosage}...")
|
| 274 |
+
return json.dumps({
|
| 275 |
+
"status": "success",
|
| 276 |
+
"message": f"Prescription Prepared: {medication_name} {dosage} {route} {frequency}",
|
| 277 |
+
"details": f"Duration: {duration}. Reason: {reason}"
|
| 278 |
+
})
|
| 279 |
+
|
| 280 |
@tool("check_drug_interactions", args_schema=InteractionCheckInput)
|
| 281 |
def check_drug_interactions(potential_prescription: str, current_medications: Optional[List[str]] = None, allergies: Optional[List[str]] = None) -> str:
|
| 282 |
+
print(f"\n--- Executing REAL check_drug_interactions ---")
|
| 283 |
+
print(f"Checking potential prescription: '{potential_prescription}'")
|
| 284 |
+
warnings = []
|
| 285 |
+
potential_med_lower = potential_prescription.lower().strip()
|
| 286 |
+
current_meds_list = current_medications or []
|
| 287 |
+
allergies_list = allergies or []
|
| 288 |
+
current_med_names_lower = []
|
| 289 |
+
for med in current_meds_list:
|
| 290 |
+
match = re.match(r"^\s*([a-zA-Z\-]+)", str(med))
|
| 291 |
+
if match:
|
| 292 |
+
current_med_names_lower.append(match.group(1).lower())
|
| 293 |
+
allergies_lower = [str(a).lower().strip() for a in allergies_list if a]
|
| 294 |
+
print(f" Against Current Meds (names): {current_med_names_lower}")
|
| 295 |
+
print(f" Against Allergies: {allergies_lower}")
|
| 296 |
+
print(f" Step 1: Normalizing '{potential_prescription}'...")
|
| 297 |
+
potential_rxcui = get_rxcui(potential_prescription)
|
| 298 |
+
potential_label = get_openfda_label(rxcui=potential_rxcui, drug_name=potential_prescription)
|
| 299 |
+
if not potential_rxcui and not potential_label:
|
| 300 |
+
warnings.append(f"INFO: Could not reliably identify '{potential_prescription}'. Checks may be incomplete.")
|
| 301 |
+
print(" Step 2: Performing Allergy Check...")
|
| 302 |
for allergy in allergies_lower:
|
| 303 |
+
if allergy == potential_med_lower:
|
| 304 |
+
warnings.append(f"CRITICAL ALLERGY (Name Match): Patient allergic to '{allergy}'. Potential prescription is '{potential_prescription}'.")
|
| 305 |
+
elif allergy in ["penicillin", "pcns"] and potential_med_lower in ["amoxicillin", "ampicillin", "augmentin", "piperacillin"]:
|
| 306 |
+
warnings.append(f"POTENTIAL CROSS-ALLERGY: Patient allergic to Penicillin. High risk with '{potential_prescription}'.")
|
| 307 |
+
elif allergy == "sulfa" and potential_med_lower in ["sulfamethoxazole", "bactrim", "sulfasalazine"]:
|
| 308 |
+
warnings.append(f"POTENTIAL CROSS-ALLERGY: Patient allergic to Sulfa. High risk with '{potential_prescription}'.")
|
| 309 |
+
elif allergy in ["nsaids", "aspirin"] and potential_med_lower in ["ibuprofen", "naproxen", "ketorolac", "diclofenac"]:
|
| 310 |
+
warnings.append(f"POTENTIAL CROSS-ALLERGY: Patient allergic to NSAIDs/Aspirin. Risk with '{potential_prescription}'.")
|
| 311 |
+
if potential_label:
|
| 312 |
+
contraindications = potential_label.get("contraindications")
|
| 313 |
+
warnings_section = potential_label.get("warnings_and_cautions") or potential_label.get("warnings")
|
| 314 |
+
if contraindications:
|
| 315 |
+
allergy_mentions_ci = search_text_list(contraindications, allergies_lower)
|
| 316 |
+
if allergy_mentions_ci:
|
| 317 |
+
warnings.append(f"ALLERGY RISK (Contraindication Found): Label for '{potential_prescription}' mentions contraindication potentially related to patient allergies: {'; '.join(allergy_mentions_ci)}")
|
| 318 |
+
if warnings_section:
|
| 319 |
+
allergy_mentions_warn = search_text_list(warnings_section, allergies_lower)
|
| 320 |
+
if allergy_mentions_warn:
|
| 321 |
+
warnings.append(f"ALLERGY RISK (Warning Found): Label for '{potential_prescription}' mentions warnings potentially related to patient allergies: {'; '.join(allergy_mentions_warn)}")
|
| 322 |
+
print(" Step 3: Performing Drug-Drug Interaction Check...")
|
| 323 |
if potential_rxcui or potential_label:
|
| 324 |
for current_med_name in current_med_names_lower:
|
| 325 |
+
if not current_med_name or current_med_name == potential_med_lower:
|
| 326 |
+
continue
|
| 327 |
+
print(f" Checking interaction between '{potential_prescription}' and '{current_med_name}'...")
|
| 328 |
+
current_rxcui = get_rxcui(current_med_name)
|
| 329 |
+
current_label = get_openfda_label(rxcui=current_rxcui, drug_name=current_med_name)
|
| 330 |
+
search_terms_for_current = [current_med_name]
|
| 331 |
+
if current_rxcui:
|
| 332 |
+
search_terms_for_current.append(current_rxcui)
|
| 333 |
+
search_terms_for_potential = [potential_med_lower]
|
| 334 |
+
if potential_rxcui:
|
| 335 |
+
search_terms_for_potential.append(potential_rxcui)
|
| 336 |
+
interaction_found_flag = False
|
| 337 |
+
if potential_label and potential_label.get("drug_interactions"):
|
| 338 |
+
interaction_mentions = search_text_list(potential_label.get("drug_interactions"), search_terms_for_current)
|
| 339 |
+
if interaction_mentions:
|
| 340 |
+
warnings.append(f"Potential Interaction ({potential_prescription.capitalize()} Label): Mentions '{current_med_name.capitalize()}'. Snippets: {'; '.join(interaction_mentions)}")
|
| 341 |
+
interaction_found_flag = True
|
| 342 |
+
if current_label and current_label.get("drug_interactions") and not interaction_found_flag:
|
| 343 |
+
interaction_mentions = search_text_list(current_label.get("drug_interactions"), search_terms_for_potential)
|
| 344 |
+
if interaction_mentions:
|
| 345 |
+
warnings.append(f"Potential Interaction ({current_med_name.capitalize()} Label): Mentions '{potential_prescription.capitalize()}'. Snippets: {'; '.join(interaction_mentions)}")
|
| 346 |
+
else:
|
| 347 |
+
warnings.append(f"INFO: Drug-drug interaction check skipped for '{potential_prescription}' as it could not be identified via RxNorm/OpenFDA.")
|
| 348 |
+
final_warnings = list(set(warnings))
|
| 349 |
+
status = "warning" if any("CRITICAL" in w or "Interaction" in w or "RISK" in w for w in final_warnings) else "clear"
|
| 350 |
+
if not final_warnings:
|
| 351 |
+
status = "clear"
|
| 352 |
+
message = f"Interaction/Allergy check for '{potential_prescription}': {len(final_warnings)} potential issue(s) identified using RxNorm/OpenFDA." if final_warnings else f"No major interactions or allergy issues identified for '{potential_prescription}' based on RxNorm/OpenFDA lookup."
|
| 353 |
+
print(f"--- Interaction Check Complete for '{potential_prescription}' ---")
|
| 354 |
+
return json.dumps({
|
| 355 |
+
"status": status,
|
| 356 |
+
"message": message,
|
| 357 |
+
"warnings": final_warnings
|
| 358 |
+
})
|
| 359 |
+
|
| 360 |
@tool("flag_risk", args_schema=FlagRiskInput)
|
| 361 |
def flag_risk(risk_description: str, urgency: str) -> str:
|
| 362 |
+
print(f"Executing flag_risk: {risk_description}, Urgency: {urgency}")
|
| 363 |
+
st.error(f"π¨ **{urgency.upper()} RISK FLAGGED by AI:** {risk_description}", icon="π¨")
|
| 364 |
+
return json.dumps({
|
| 365 |
+
"status": "flagged",
|
| 366 |
+
"message": f"Risk '{risk_description}' flagged with {urgency} urgency."
|
| 367 |
+
})
|
| 368 |
+
|
| 369 |
search_tool = TavilySearchResults(max_results=ClinicalAppSettings.MAX_SEARCH_RESULTS, name="tavily_search_results")
|
| 370 |
|
| 371 |
# --- LangGraph Setup ---
|
| 372 |
+
class AgentState(TypedDict):
|
| 373 |
+
messages: Annotated[list[Any], operator.add]
|
| 374 |
+
patient_data: Optional[dict]
|
| 375 |
+
|
| 376 |
tools = [order_lab_test, prescribe_medication, check_drug_interactions, flag_risk, search_tool]
|
| 377 |
tool_executor = ToolExecutor(tools)
|
| 378 |
model = ChatGroq(temperature=ClinicalAppSettings.TEMPERATURE, model=ClinicalAppSettings.MODEL_NAME)
|
| 379 |
model_with_tools = model.bind_tools(tools)
|
| 380 |
|
| 381 |
# --- Graph Nodes (agent_node, tool_node) ---
|
|
|
|
| 382 |
def agent_node(state: AgentState):
|
| 383 |
+
print("\n---AGENT NODE---")
|
| 384 |
+
current_messages = state['messages']
|
| 385 |
+
if not current_messages or not isinstance(current_messages[0], SystemMessage):
|
| 386 |
+
print("Prepending System Prompt.")
|
| 387 |
+
current_messages = [SystemMessage(content=ClinicalPrompts.SYSTEM_PROMPT)] + current_messages
|
| 388 |
+
print(f"Invoking LLM with {len(current_messages)} messages.")
|
| 389 |
+
try:
|
| 390 |
+
response = model_with_tools.invoke(current_messages)
|
| 391 |
+
print(f"Agent Raw Response Type: {type(response)}")
|
| 392 |
+
if hasattr(response, 'tool_calls') and response.tool_calls:
|
| 393 |
+
print(f"Agent Response Tool Calls: {response.tool_calls}")
|
| 394 |
+
else:
|
| 395 |
+
print("Agent Response: No tool calls.")
|
| 396 |
+
except Exception as e:
|
| 397 |
+
print(f"ERROR in agent_node: {e}")
|
| 398 |
+
traceback.print_exc()
|
| 399 |
+
error_message = AIMessage(content=f"Error: {e}")
|
| 400 |
+
return {"messages": [error_message]}
|
| 401 |
return {"messages": [response]}
|
| 402 |
+
|
| 403 |
def tool_node(state: AgentState):
|
| 404 |
+
print("\n---TOOL NODE---")
|
| 405 |
+
tool_messages = []
|
| 406 |
+
last_message = state['messages'][-1]
|
| 407 |
+
if not isinstance(last_message, AIMessage) or not getattr(last_message, 'tool_calls', None):
|
| 408 |
+
print("Warning: Tool node called unexpectedly.")
|
| 409 |
+
return {"messages": []}
|
| 410 |
+
tool_calls = last_message.tool_calls
|
| 411 |
+
print(f"Tool calls received: {json.dumps(tool_calls, indent=2)}")
|
| 412 |
+
prescriptions_requested = {}
|
| 413 |
+
interaction_checks_requested = {}
|
| 414 |
+
for call in tool_calls:
|
| 415 |
+
tool_name = call.get('name')
|
| 416 |
+
tool_args = call.get('args', {})
|
| 417 |
+
if tool_name == 'prescribe_medication':
|
| 418 |
+
med_name = tool_args.get('medication_name', '').lower()
|
| 419 |
+
if med_name:
|
| 420 |
+
prescriptions_requested[med_name] = call
|
| 421 |
+
elif tool_name == 'check_drug_interactions':
|
| 422 |
+
potential_med = tool_args.get('potential_prescription', '').lower()
|
| 423 |
+
if potential_med:
|
| 424 |
+
interaction_checks_requested[potential_med] = call
|
| 425 |
+
valid_tool_calls_for_execution = []
|
| 426 |
+
blocked_ids = set()
|
| 427 |
for med_name, prescribe_call in prescriptions_requested.items():
|
| 428 |
+
if med_name not in interaction_checks_requested:
|
| 429 |
+
st.error(f"**Safety Violation:** AI tried to prescribe '{med_name}' without check.")
|
| 430 |
+
error_msg = ToolMessage(content=json.dumps({
|
| 431 |
+
"status": "error",
|
| 432 |
+
"message": f"Interaction check needed for '{med_name}'."
|
| 433 |
+
}), tool_call_id=prescribe_call['id'], name=prescribe_call['name'])
|
| 434 |
+
tool_messages.append(error_msg)
|
| 435 |
+
blocked_ids.add(prescribe_call['id'])
|
| 436 |
+
valid_tool_calls_for_execution = [call for call in tool_calls if call['id'] not in blocked_ids]
|
| 437 |
+
patient_data = state.get("patient_data", {})
|
| 438 |
+
patient_meds_full = patient_data.get("medications", {}).get("current", [])
|
| 439 |
+
patient_allergies = patient_data.get("allergies", [])
|
| 440 |
for call in valid_tool_calls_for_execution:
|
| 441 |
if call['name'] == 'check_drug_interactions':
|
| 442 |
+
if 'args' not in call:
|
| 443 |
+
call['args'] = {}
|
| 444 |
+
call['args']['current_medications'] = patient_meds_full
|
| 445 |
+
call['args']['allergies'] = patient_allergies
|
| 446 |
+
print(f"Augmented interaction check args for call ID {call['id']}")
|
| 447 |
+
if valid_tool_calls_for_execution:
|
| 448 |
+
print(f"Attempting execution: {[c['name'] for c in valid_tool_calls_for_execution]}")
|
| 449 |
+
try:
|
| 450 |
+
responses = tool_executor.batch(valid_tool_calls_for_execution, return_exceptions=True)
|
| 451 |
+
for call, resp in zip(valid_tool_calls_for_execution, responses):
|
| 452 |
+
tool_call_id = call['id']
|
| 453 |
+
tool_name = call['name']
|
| 454 |
+
if isinstance(resp, Exception):
|
| 455 |
+
error_type = type(resp).__name__
|
| 456 |
+
error_str = str(resp)
|
| 457 |
+
print(f"ERROR executing tool '{tool_name}': {error_type} - {error_str}")
|
| 458 |
+
traceback.print_exc()
|
| 459 |
+
st.error(f"Error: {error_type}")
|
| 460 |
+
error_content = json.dumps({"status": "error", "message": f"Failed: {error_type} - {error_str}"})
|
| 461 |
+
tool_messages.append(ToolMessage(content=error_content, tool_call_id=tool_call_id, name=tool_name))
|
| 462 |
+
else:
|
| 463 |
+
print(f"Tool '{tool_name}' executed.")
|
| 464 |
+
content_str = str(resp)
|
| 465 |
+
tool_messages.append(ToolMessage(content=content_str, tool_call_id=tool_call_id, name=tool_name))
|
| 466 |
+
except Exception as e:
|
| 467 |
+
print(f"CRITICAL TOOL NODE ERROR: {e}")
|
| 468 |
+
traceback.print_exc()
|
| 469 |
+
st.error(f"Critical error: {e}")
|
| 470 |
+
error_content = json.dumps({"status": "error", "message": f"Internal error: {e}"})
|
| 471 |
+
processed_ids = {msg.tool_call_id for msg in tool_messages}
|
| 472 |
+
[tool_messages.append(ToolMessage(content=error_content, tool_call_id=call['id'], name=call['name']))
|
| 473 |
+
for call in valid_tool_calls_for_execution if call['id'] not in processed_ids]
|
| 474 |
+
print(f"Returning {len(tool_messages)} tool messages.")
|
| 475 |
+
return {"messages": tool_messages}
|
| 476 |
|
| 477 |
# --- Graph Edges (Routing Logic) ---
|
| 478 |
def should_continue(state: AgentState) -> str:
|
| 479 |
+
print("\n---ROUTING DECISION---")
|
| 480 |
+
last_message = state['messages'][-1] if state['messages'] else None
|
| 481 |
+
if not isinstance(last_message, AIMessage):
|
| 482 |
+
return "end_conversation_turn"
|
| 483 |
+
if "Sorry, an internal error occurred" in last_message.content:
|
| 484 |
+
return "end_conversation_turn"
|
| 485 |
+
if getattr(last_message, 'tool_calls', None):
|
| 486 |
+
return "continue_tools"
|
| 487 |
+
else:
|
| 488 |
+
return "end_conversation_turn"
|
| 489 |
|
| 490 |
# --- Graph Definition & Compilation ---
|
| 491 |
+
workflow = StateGraph(AgentState)
|
| 492 |
+
workflow.add_node("agent", agent_node)
|
| 493 |
+
workflow.add_node("tools", tool_node)
|
| 494 |
+
workflow.set_entry_point("agent")
|
| 495 |
+
workflow.add_conditional_edges("agent", should_continue, {"continue_tools": "tools", "end_conversation_turn": END})
|
| 496 |
+
workflow.add_edge("tools", "agent")
|
| 497 |
+
app = workflow.compile()
|
| 498 |
+
print("LangGraph compiled successfully.")
|
| 499 |
|
| 500 |
# --- Streamlit UI ---
|
| 501 |
def main():
|
| 502 |
st.set_page_config(page_title=ClinicalAppSettings.APP_TITLE, layout=ClinicalAppSettings.PAGE_LAYOUT)
|
| 503 |
st.title(f"π©Ί {ClinicalAppSettings.APP_TITLE}")
|
| 504 |
st.caption(f"Interactive Assistant | LangGraph/Groq/Tavily/UMLS/OpenFDA | Model: {ClinicalAppSettings.MODEL_NAME}")
|
| 505 |
+
if "messages" not in st.session_state:
|
| 506 |
+
st.session_state.messages = []
|
| 507 |
+
if "patient_data" not in st.session_state:
|
| 508 |
+
st.session_state.patient_data = None
|
| 509 |
+
if "graph_app" not in st.session_state:
|
| 510 |
+
st.session_state.graph_app = app
|
| 511 |
|
| 512 |
# --- Patient Data Input Sidebar ---
|
| 513 |
with st.sidebar:
|
| 514 |
st.header("π Patient Intake Form")
|
| 515 |
+
# Input fields... (Using shorter versions for brevity, assume full fields are here)
|
| 516 |
+
st.subheader("Demographics")
|
| 517 |
+
age = st.number_input("Age", 0, 120, 55)
|
| 518 |
+
sex = st.selectbox("Sex", ["Male", "Female", "Other"])
|
| 519 |
+
st.subheader("HPI")
|
| 520 |
+
chief_complaint = st.text_input("Chief Complaint", "Chest pain")
|
| 521 |
+
hpi_details = st.text_area("HPI Details", "55 y/o male...", height=100)
|
| 522 |
+
symptoms = st.multiselect("Symptoms", ["Nausea", "Diaphoresis", "SOB", "Dizziness"], default=["Nausea", "Diaphoresis"])
|
| 523 |
+
st.subheader("History")
|
| 524 |
+
pmh = st.text_area("PMH", "HTN, HLD, DM2, History of MI")
|
| 525 |
+
psh = st.text_area("PSH", "Appendectomy")
|
| 526 |
+
st.subheader("Meds & Allergies")
|
| 527 |
+
current_meds_str = st.text_area("Current Meds", "Lisinopril 10mg daily\nMetformin 1000mg BID")
|
| 528 |
+
allergies_str = st.text_area("Allergies", "Penicillin (rash)")
|
| 529 |
+
st.subheader("Social/Family")
|
| 530 |
+
social_history = st.text_area("SH", "Smoker")
|
| 531 |
+
family_history = st.text_area("FHx", "Father MI")
|
| 532 |
+
st.subheader("Vitals & Exam")
|
| 533 |
+
col1, col2 = st.columns(2)
|
| 534 |
+
with col1:
|
| 535 |
+
temp_c = st.number_input("Temp C", 35.0, 42.0, 36.8, format="%.1f")
|
| 536 |
+
hr_bpm = st.number_input("HR", 30, 250, 95)
|
| 537 |
+
rr_rpm = st.number_input("RR", 5, 50, 18)
|
| 538 |
+
with col2:
|
| 539 |
+
bp_mmhg = st.text_input("BP", "155/90")
|
| 540 |
+
spo2_percent = st.number_input("SpO2", 70, 100, 96)
|
| 541 |
+
pain_scale = st.slider("Pain", 0, 10, 8)
|
| 542 |
+
exam_notes = st.text_area("Exam Notes", "Awake, alert...", height=50)
|
| 543 |
+
|
| 544 |
+
if st.button("Start/Update Consultation"):
|
| 545 |
current_meds_list = [med.strip() for med in current_meds_str.split('\n') if med.strip()]
|
| 546 |
+
current_med_names_only = []
|
| 547 |
+
for med in current_meds_list:
|
| 548 |
+
match = re.match(r"^\s*([a-zA-Z\-]+)", med)
|
| 549 |
+
if match:
|
| 550 |
+
current_med_names_only.append(match.group(1).lower())
|
| 551 |
allergies_list = []
|
| 552 |
+
for a in allergies_str.split(','):
|
| 553 |
+
cleaned_allergy = a.strip()
|
| 554 |
+
if cleaned_allergy:
|
| 555 |
+
match = re.match(r"^\s*([a-zA-Z\-\s/]+)(?:\s*\(.*\))?", cleaned_allergy)
|
| 556 |
+
name_part = match.group(1).strip().lower() if match else cleaned_allergy.lower()
|
| 557 |
+
allergies_list.append(name_part)
|
| 558 |
+
st.session_state.patient_data = {
|
| 559 |
+
"demographics": {"age": age, "sex": sex},
|
| 560 |
+
"hpi": {"chief_complaint": chief_complaint, "details": hpi_details, "symptoms": symptoms},
|
| 561 |
+
"pmh": {"conditions": pmh},
|
| 562 |
+
"psh": {"procedures": psh},
|
| 563 |
+
"medications": {"current": current_meds_list, "names_only": current_med_names_only},
|
| 564 |
+
"allergies": allergies_list,
|
| 565 |
+
"social_history": {"details": social_history},
|
| 566 |
+
"family_history": {"details": family_history},
|
| 567 |
+
"vitals": {
|
| 568 |
+
"temp_c": temp_c,
|
| 569 |
+
"hr_bpm": hr_bpm,
|
| 570 |
+
"bp_mmhg": bp_mmhg,
|
| 571 |
+
"rr_rpm": rr_rpm,
|
| 572 |
+
"spo2_percent": spo2_percent,
|
| 573 |
+
"pain_scale": pain_scale
|
| 574 |
+
},
|
| 575 |
+
"exam_findings": {"notes": exam_notes}
|
| 576 |
+
}
|
| 577 |
+
red_flags = check_red_flags(st.session_state.patient_data)
|
| 578 |
+
st.sidebar.markdown("---")
|
| 579 |
+
if red_flags:
|
| 580 |
+
st.sidebar.warning("**Initial Red Flags:**")
|
| 581 |
+
[st.sidebar.warning(f"- {flag.replace('Red Flag: ','')}") for flag in red_flags]
|
| 582 |
+
else:
|
| 583 |
+
st.sidebar.success("No immediate red flags.")
|
| 584 |
initial_prompt = "Initiate consultation. Review patient data and begin analysis."
|
| 585 |
+
st.session_state.messages = [HumanMessage(content=initial_prompt)]
|
| 586 |
+
st.success("Patient data loaded/updated.")
|
| 587 |
|
| 588 |
# --- Main Chat Interface Area ---
|
| 589 |
st.header("π¬ Clinical Consultation")
|
| 590 |
+
# Display loop - SyntaxError Fixed
|
| 591 |
for msg in st.session_state.messages:
|
| 592 |
if isinstance(msg, HumanMessage):
|
| 593 |
+
with st.chat_message("user"):
|
| 594 |
+
st.markdown(msg.content) # No key
|
| 595 |
elif isinstance(msg, AIMessage):
|
| 596 |
with st.chat_message("assistant"):
|
| 597 |
+
ai_content = msg.content
|
| 598 |
+
structured_output = None
|
| 599 |
+
try:
|
| 600 |
json_match = re.search(r"```json\s*(\{.*?\})\s*```", ai_content, re.DOTALL | re.IGNORECASE)
|
| 601 |
+
if json_match:
|
| 602 |
+
json_str = json_match.group(1)
|
| 603 |
+
prefix = ai_content[:json_match.start()].strip()
|
| 604 |
+
suffix = ai_content[json_match.end():].strip()
|
| 605 |
+
if prefix:
|
| 606 |
+
st.markdown(prefix)
|
| 607 |
+
structured_output = json.loads(json_str)
|
| 608 |
+
if suffix:
|
| 609 |
+
st.markdown(suffix)
|
| 610 |
+
elif ai_content.strip().startswith("{") and ai_content.strip().endswith("}"):
|
| 611 |
+
structured_output = json.loads(ai_content)
|
| 612 |
+
ai_content = ""
|
| 613 |
+
else:
|
| 614 |
+
st.markdown(ai_content)
|
| 615 |
+
except Exception as e:
|
| 616 |
+
st.markdown(ai_content)
|
| 617 |
+
print(f"Error parsing/displaying AI JSON: {e}")
|
| 618 |
+
if structured_output and isinstance(structured_output, dict):
|
| 619 |
+
st.divider()
|
| 620 |
+
st.subheader("π AI Analysis & Recommendations")
|
| 621 |
+
cols = st.columns(2)
|
| 622 |
+
with cols[0]:
|
| 623 |
+
st.markdown("**Assessment:**")
|
| 624 |
+
st.markdown(f"> {structured_output.get('assessment', 'N/A')}")
|
| 625 |
+
st.markdown("**Differential Diagnosis:**")
|
| 626 |
+
ddx = structured_output.get('differential_diagnosis', [])
|
| 627 |
+
if ddx:
|
| 628 |
+
[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]
|
| 629 |
+
else:
|
| 630 |
+
st.info("No DDx provided.")
|
| 631 |
+
st.markdown("**Risk Assessment:**")
|
| 632 |
+
risk = structured_output.get('risk_assessment', {})
|
| 633 |
+
flags = risk.get('identified_red_flags', [])
|
| 634 |
+
concerns = risk.get("immediate_concerns", [])
|
| 635 |
+
comps = risk.get("potential_complications", [])
|
| 636 |
+
if flags:
|
| 637 |
+
st.warning(f"**Flags:** {', '.join(flags)}")
|
| 638 |
+
if concerns:
|
| 639 |
+
st.warning(f"**Concerns:** {', '.join(concerns)}")
|
| 640 |
+
if comps:
|
| 641 |
+
st.info(f"**Potential Complications:** {', '.join(comps)}")
|
| 642 |
+
if not flags and not concerns:
|
| 643 |
+
st.success("No major risks highlighted.")
|
| 644 |
+
with cols[1]:
|
| 645 |
+
st.markdown("**Recommended Plan:**")
|
| 646 |
+
plan = structured_output.get('recommended_plan', {})
|
| 647 |
+
for section in ["investigations","therapeutics","consultations","patient_education"]:
|
| 648 |
+
st.markdown(f"_{section.replace('_',' ').capitalize()}:_")
|
| 649 |
+
items = plan.get(section)
|
| 650 |
+
if items and isinstance(items, list):
|
| 651 |
+
[st.markdown(f"- {item}") for item in items]
|
| 652 |
+
elif items:
|
| 653 |
+
st.markdown(f"- {items}")
|
| 654 |
+
else:
|
| 655 |
+
st.markdown("_None_")
|
| 656 |
+
st.markdown("")
|
| 657 |
+
st.markdown("**Rationale & Guideline Check:**")
|
| 658 |
+
st.markdown(f"> {structured_output.get('rationale_summary', 'N/A')}")
|
| 659 |
+
interaction_summary = structured_output.get("interaction_check_summary", "")
|
| 660 |
+
if interaction_summary:
|
| 661 |
+
st.markdown("**Interaction Check Summary:**")
|
| 662 |
+
st.markdown(f"> {interaction_summary}")
|
| 663 |
+
st.divider()
|
| 664 |
+
|
| 665 |
if getattr(msg, 'tool_calls', None):
|
| 666 |
+
with st.expander("π οΈ AI requested actions", expanded=False):
|
| 667 |
+
if msg.tool_calls:
|
| 668 |
for tc in msg.tool_calls:
|
| 669 |
try:
|
| 670 |
st.code(f"Action: {tc.get('name', 'Unknown Tool')}\nArgs: {json.dumps(tc.get('args', {}), indent=2)}", language="json")
|
| 671 |
except Exception as display_e:
|
| 672 |
+
st.error(f"Could not display tool call arguments properly: {display_e}", icon="β οΈ")
|
| 673 |
st.code(f"Action: {tc.get('name', 'Unknown Tool')}\nRaw Args: {tc.get('args')}")
|
| 674 |
+
else:
|
| 675 |
+
st.caption("_No actions requested in this turn._")
|
| 676 |
elif isinstance(msg, ToolMessage):
|
| 677 |
tool_name_display = getattr(msg, 'name', 'tool_execution')
|
| 678 |
+
with st.chat_message(tool_name_display, avatar="π οΈ"):
|
| 679 |
+
try:
|
| 680 |
+
tool_data = json.loads(msg.content)
|
| 681 |
+
status = tool_data.get("status", "info")
|
| 682 |
+
message = tool_data.get("message", msg.content)
|
| 683 |
+
details = tool_data.get("details")
|
| 684 |
+
warnings = tool_data.get("warnings")
|
| 685 |
+
if status == "success" or status == "clear" or status == "flagged":
|
| 686 |
+
st.success(f"{message}", icon="β
" if status != "flagged" else "π¨")
|
| 687 |
+
elif status == "warning":
|
| 688 |
+
st.warning(f"{message}", icon="β οΈ")
|
| 689 |
+
if warnings and isinstance(warnings, list):
|
| 690 |
+
st.caption("Details:")
|
| 691 |
+
[st.caption(f"- {warn}") for warn in warnings]
|
| 692 |
+
else:
|
| 693 |
+
st.error(f"{message}", icon="β")
|
| 694 |
+
if details:
|
| 695 |
+
st.caption(f"Details: {details}")
|
| 696 |
+
except json.JSONDecodeError:
|
| 697 |
+
st.info(f"{msg.content}")
|
| 698 |
+
except Exception as e:
|
| 699 |
+
st.error(f"Error displaying tool message: {e}", icon="β")
|
| 700 |
+
st.caption(f"Raw content: {msg.content}")
|
| 701 |
|
| 702 |
# --- Chat Input Logic ---
|
| 703 |
if prompt := st.chat_input("Your message or follow-up query..."):
|
| 704 |
+
if not st.session_state.patient_data:
|
| 705 |
+
st.warning("Please load patient data first.")
|
| 706 |
+
st.stop()
|
| 707 |
+
user_message = HumanMessage(content=prompt)
|
| 708 |
+
st.session_state.messages.append(user_message)
|
| 709 |
+
with st.chat_message("user"):
|
| 710 |
+
st.markdown(prompt)
|
| 711 |
current_state = AgentState(messages=st.session_state.messages, patient_data=st.session_state.patient_data)
|
| 712 |
with st.spinner("SynapseAI is thinking..."):
|
| 713 |
try:
|
| 714 |
final_state = st.session_state.graph_app.invoke(current_state, {"recursion_limit": 15})
|
| 715 |
st.session_state.messages = final_state['messages']
|
| 716 |
+
except Exception as e:
|
| 717 |
+
print(f"CRITICAL ERROR: {e}")
|
| 718 |
+
traceback.print_exc()
|
| 719 |
+
st.error(f"Error: {e}")
|
| 720 |
st.rerun()
|
| 721 |
|
| 722 |
# Disclaimer
|
| 723 |
+
st.markdown("---")
|
| 724 |
+
st.warning("**Disclaimer:** SynapseAI is for demonstration...")
|
| 725 |
|
| 726 |
if __name__ == "__main__":
|
| 727 |
+
main()
|