Update app.py
Browse files
app.py
CHANGED
@@ -1,3 +1,4 @@
|
|
|
|
1 |
import streamlit as st
|
2 |
import requests
|
3 |
import json
|
@@ -11,7 +12,7 @@ from dotenv import load_dotenv
|
|
11 |
from langchain_groq import ChatGroq
|
12 |
from langchain_community.tools.tavily_search import TavilySearchResults
|
13 |
from langchain_core.messages import HumanMessage, SystemMessage, AIMessage, ToolMessage
|
14 |
-
# from langchain_core.prompts import ChatPromptTemplate # Not explicitly used
|
15 |
from langchain_core.pydantic_v1 import BaseModel, Field
|
16 |
from langchain_core.tools import tool
|
17 |
from langgraph.prebuilt import ToolExecutor
|
@@ -20,398 +21,200 @@ from langgraph.graph import StateGraph, END
|
|
20 |
from typing import Optional, List, Dict, Any, TypedDict, Annotated
|
21 |
|
22 |
# --- Environment Variable Loading & Validation ---
|
23 |
-
load_dotenv()
|
24 |
-
|
25 |
UMLS_API_KEY = os.environ.get("UMLS_API_KEY")
|
26 |
GROQ_API_KEY = os.environ.get("GROQ_API_KEY")
|
27 |
TAVILY_API_KEY = os.environ.get("TAVILY_API_KEY")
|
28 |
-
|
29 |
-
# Stop execution if essential keys are missing (crucial for HF Spaces)
|
30 |
missing_keys = []
|
31 |
if not UMLS_API_KEY: missing_keys.append("UMLS_API_KEY")
|
32 |
if not GROQ_API_KEY: missing_keys.append("GROQ_API_KEY")
|
33 |
if not TAVILY_API_KEY: missing_keys.append("TAVILY_API_KEY")
|
34 |
-
|
35 |
-
if missing_keys:
|
36 |
-
# Use st.error which stops execution in recent Streamlit versions
|
37 |
-
st.error(f"Missing required API Key(s): {', '.join(missing_keys)}. Please set them in Hugging Face Space Secrets or your environment variables.")
|
38 |
-
# Ensure execution stops if st.error doesn't automatically do it in the environment
|
39 |
-
st.stop()
|
40 |
-
|
41 |
|
42 |
# --- Configuration & Constants ---
|
43 |
-
class ClinicalAppSettings:
|
44 |
-
|
45 |
-
|
46 |
-
MODEL_NAME = "llama3-70b-8192" # Groq Llama3 70b
|
47 |
-
TEMPERATURE = 0.1
|
48 |
-
MAX_SEARCH_RESULTS = 3
|
49 |
-
|
50 |
-
class ClinicalPrompts:
|
51 |
-
# System prompt remains the same as the previous version, emphasizing structured output,
|
52 |
-
# safety checks, guideline search, and conversational flow.
|
53 |
-
SYSTEM_PROMPT = """
|
54 |
-
You are SynapseAI, an expert AI clinical assistant engaged in an interactive consultation.
|
55 |
-
Your goal is to support healthcare professionals by analyzing patient data, providing differential diagnoses, suggesting evidence-based management plans, and identifying risks according to current standards of care.
|
56 |
-
|
57 |
-
**Core Directives for this Conversation:**
|
58 |
-
1. **Analyze Sequentially:** Process information turn-by-turn. Base your responses on the *entire* conversation history.
|
59 |
-
2. **Seek Clarity:** If the provided information is insufficient or ambiguous for a safe assessment, CLEARLY STATE what specific additional information or clarification is needed. Do NOT guess or make unsafe assumptions.
|
60 |
-
3. **Structured Assessment (When Ready):** When you have sufficient information and have performed necessary checks (like interactions, guideline searches), provide a comprehensive assessment using the following JSON structure. Output this JSON structure as the primary content of your response when you are providing the full analysis. Do NOT output incomplete JSON. If you need to ask a question or perform a tool call first, do that instead of outputting this structure.
|
61 |
-
```json
|
62 |
-
{
|
63 |
-
"assessment": "Concise summary of the patient's presentation and key findings based on the conversation.",
|
64 |
-
"differential_diagnosis": [
|
65 |
-
{"diagnosis": "Primary Diagnosis", "likelihood": "High/Medium/Low", "rationale": "Supporting evidence from conversation..."},
|
66 |
-
{"diagnosis": "Alternative Diagnosis 1", "likelihood": "Medium/Low", "rationale": "Supporting/Refuting evidence..."},
|
67 |
-
{"diagnosis": "Alternative Diagnosis 2", "likelihood": "Low", "rationale": "Why it's less likely but considered..."}
|
68 |
-
],
|
69 |
-
"risk_assessment": {
|
70 |
-
"identified_red_flags": ["List any triggered red flags based on input and analysis"],
|
71 |
-
"immediate_concerns": ["Specific urgent issues requiring attention (e.g., sepsis risk, ACS rule-out)"],
|
72 |
-
"potential_complications": ["Possible future issues based on presentation"]
|
73 |
-
},
|
74 |
-
"recommended_plan": {
|
75 |
-
"investigations": ["List specific lab tests or imaging required. Use 'order_lab_test' tool."],
|
76 |
-
"therapeutics": ["Suggest specific treatments or prescriptions. Use 'prescribe_medication' tool. MUST check interactions first using 'check_drug_interactions'."],
|
77 |
-
"consultations": ["Recommend specialist consultations if needed."],
|
78 |
-
"patient_education": ["Key points for patient communication."]
|
79 |
-
},
|
80 |
-
"rationale_summary": "Justification for assessment/plan. **Crucially, if relevant (e.g., ACS, sepsis, common infections), use 'tavily_search_results' to find and cite current clinical practice guidelines (e.g., 'latest ACC/AHA chest pain guidelines 202X', 'Surviving Sepsis Campaign guidelines') supporting your recommendations.** Include summary of guideline findings here.",
|
81 |
-
"interaction_check_summary": "Summary of findings from 'check_drug_interactions' if performed."
|
82 |
-
}
|
83 |
-
```
|
84 |
-
4. **Safety First - Interactions:** BEFORE suggesting a new prescription via `prescribe_medication`, you MUST FIRST use `check_drug_interactions` in a preceding or concurrent tool call. Report the findings from the interaction check. If significant interactions exist, modify the plan or state the contraindication clearly.
|
85 |
-
5. **Safety First - Red Flags:** Use the `flag_risk` tool IMMEDIATELY if critical red flags requiring urgent action are identified at any point in the conversation.
|
86 |
-
6. **Tool Use:** Employ tools (`order_lab_test`, `prescribe_medication`, `check_drug_interactions`, `flag_risk`, `tavily_search_results`) logically within the conversational flow. Wait for tool results before proceeding if the result is needed for the next step (e.g., wait for interaction check before confirming prescription in the structured JSON).
|
87 |
-
7. **Evidence & Guidelines:** Actively use `tavily_search_results` not just for general knowledge, but specifically to query for and incorporate **current clinical practice guidelines** relevant to the patient's presentation (e.g., chest pain, shortness of breath, suspected infection). Summarize findings in the `rationale_summary` when providing the structured output.
|
88 |
-
8. **Conciseness & Flow:** Be medically accurate and concise. Use standard terminology. Respond naturally in conversation (asking questions, acknowledging info) until ready for the full structured JSON output.
|
89 |
"""
|
90 |
|
91 |
-
# ---
|
92 |
-
|
93 |
-
RXNORM_API_BASE = "https://rxnav.nlm.nih.gov/REST"
|
94 |
-
|
95 |
-
|
96 |
-
@lru_cache(maxsize=256) # Cache RxCUI lookups
|
97 |
def get_rxcui(drug_name: str) -> Optional[str]:
|
98 |
-
|
99 |
-
if not drug_name
|
100 |
-
drug_name = drug_name.strip()
|
101 |
-
if not drug_name: return None
|
102 |
-
|
103 |
-
print(f"RxNorm Lookup for: '{drug_name}'")
|
104 |
try:
|
105 |
-
params = {"name": drug_name, "search": 1}
|
106 |
-
|
107 |
-
|
108 |
-
|
109 |
-
if data and "idGroup" in data and "rxnormId" in data["idGroup"]:
|
110 |
-
rxcui = data["idGroup"]["rxnormId"][0]
|
111 |
-
print(f" Found RxCUI: {rxcui} for '{drug_name}'")
|
112 |
-
return rxcui
|
113 |
-
else: # Fallback search
|
114 |
-
params = {"name": drug_name}; response = requests.get(f"{RXNORM_API_BASE}/drugs.json", params=params, timeout=10)
|
115 |
-
response.raise_for_status(); data = response.json()
|
116 |
if data and "drugGroup" in data and "conceptGroup" in data["drugGroup"]:
|
117 |
for group in data["drugGroup"]["conceptGroup"]:
|
118 |
if group.get("tty") in ["SBD", "SCD", "GPCK", "BPCK", "IN", "MIN", "PIN"]:
|
119 |
-
if "conceptProperties" in group and group["conceptProperties"]:
|
120 |
-
|
121 |
-
|
122 |
-
print(f" RxCUI not found for '{drug_name}'.")
|
123 |
-
return None
|
124 |
except requests.exceptions.RequestException as e: print(f" Error fetching RxCUI for '{drug_name}': {e}"); return None
|
125 |
except json.JSONDecodeError as e: print(f" Error decoding RxNorm JSON response for '{drug_name}': {e}"); return None
|
126 |
except Exception as e: print(f" Unexpected error in get_rxcui for '{drug_name}': {e}"); return None
|
127 |
-
|
128 |
-
@lru_cache(maxsize=128) # Cache OpenFDA lookups
|
129 |
def get_openfda_label(rxcui: Optional[str] = None, drug_name: Optional[str] = None) -> Optional[dict]:
|
130 |
-
|
131 |
-
if not rxcui and not drug_name: return None
|
132 |
-
print(f"OpenFDA Label Lookup for: RXCUI={rxcui}, Name={drug_name}")
|
133 |
-
search_terms = []
|
134 |
if rxcui: search_terms.append(f'spl_rxnorm_code:"{rxcui}" OR openfda.rxcui:"{rxcui}"')
|
135 |
if drug_name: search_terms.append(f'(openfda.brand_name:"{drug_name.lower()}" OR openfda.generic_name:"{drug_name.lower()}")')
|
136 |
-
search_query = " OR ".join(search_terms); params = {"search": search_query, "limit": 1}
|
137 |
try:
|
138 |
-
response = requests.get(OPENFDA_API_BASE, params=params, timeout=15)
|
139 |
-
response.raise_for_status(); data = response.json()
|
140 |
if data and "results" in data and data["results"]: print(f" Found OpenFDA label for query: {search_query}"); return data["results"][0]
|
141 |
print(f" No OpenFDA label found for query: {search_query}"); return None
|
142 |
except requests.exceptions.RequestException as e: print(f" Error fetching OpenFDA label: {e}"); return None
|
143 |
except json.JSONDecodeError as e: print(f" Error decoding OpenFDA JSON response: {e}"); return None
|
144 |
except Exception as e: print(f" Unexpected error in get_openfda_label: {e}"); return None
|
145 |
-
|
146 |
def search_text_list(text_list: Optional[List[str]], search_terms: List[str]) -> List[str]:
|
147 |
-
|
148 |
-
found_snippets = []
|
149 |
-
if not text_list or not search_terms: return found_snippets
|
150 |
-
search_terms_lower = [str(term).lower() for term in search_terms if term]
|
151 |
for text_item in text_list:
|
152 |
-
if not isinstance(text_item, str): continue
|
153 |
-
text_item_lower = text_item.lower()
|
154 |
for term in search_terms_lower:
|
155 |
if term in text_item_lower:
|
156 |
-
start_index = text_item_lower.find(term); snippet_start = max(0, start_index - 50)
|
157 |
-
|
158 |
-
snippet = snippet.replace(term, f"**{term}**", 1); found_snippets.append(f"...{snippet}...")
|
159 |
-
break
|
160 |
return found_snippets
|
161 |
|
162 |
-
# --- Other Helper Functions ---
|
163 |
-
def parse_bp(bp_string: str) -> Optional[tuple[int, int]]:
|
164 |
-
"""Parses BP string like '120/80' into (systolic, diastolic) integers."""
|
165 |
-
if not isinstance(bp_string, str): return None
|
166 |
-
match = re.match(r"(\d{1,3})\s*/\s*(\d{1,3})", bp_string.strip())
|
167 |
-
if match: return int(match.group(1)), int(match.group(2))
|
168 |
-
return None
|
169 |
|
|
|
|
|
|
|
|
|
|
|
170 |
def check_red_flags(patient_data: dict) -> List[str]:
|
171 |
-
|
172 |
-
flags = []
|
173 |
-
if
|
174 |
-
|
175 |
-
|
176 |
-
|
177 |
-
|
178 |
-
|
179 |
-
|
180 |
-
if
|
181 |
-
if "
|
182 |
-
if "
|
183 |
-
if "weakness on one side" in symptoms_lower: flags.append("Red Flag: Unilateral Weakness reported (potential stroke).")
|
184 |
-
if "hemoptysis" in symptoms_lower: flags.append("Red Flag: Hemoptysis (coughing up blood).")
|
185 |
-
if "syncope" in symptoms_lower: flags.append("Red Flag: Syncope (fainting).")
|
186 |
-
|
187 |
-
if vitals:
|
188 |
-
temp = vitals.get("temp_c"); hr = vitals.get("hr_bpm"); rr = vitals.get("rr_rpm")
|
189 |
-
spo2 = vitals.get("spo2_percent"); bp_str = vitals.get("bp_mmhg")
|
190 |
-
if temp is not None and temp >= 38.5: flags.append(f"Red Flag: Fever ({temp}Β°C).")
|
191 |
-
if hr is not None and hr >= 120: flags.append(f"Red Flag: Tachycardia ({hr} bpm).")
|
192 |
-
if hr is not None and hr <= 50: flags.append(f"Red Flag: Bradycardia ({hr} bpm).")
|
193 |
-
if rr is not None and rr >= 24: flags.append(f"Red Flag: Tachypnea ({rr} rpm).")
|
194 |
-
if spo2 is not None and spo2 <= 92: flags.append(f"Red Flag: Hypoxia ({spo2}%).")
|
195 |
-
if bp_str:
|
196 |
-
bp = parse_bp(bp_str)
|
197 |
-
if bp:
|
198 |
-
if bp[0] >= 180 or bp[1] >= 110: flags.append(f"Red Flag: Hypertensive Urgency/Emergency (BP: {bp_str} mmHg).")
|
199 |
-
if bp[0] <= 90 or bp[1] <= 60: flags.append(f"Red Flag: Hypotension (BP: {bp_str} mmHg).")
|
200 |
-
|
201 |
-
if history and isinstance(history, str):
|
202 |
-
history_lower = history.lower()
|
203 |
-
if "history of mi" in history_lower and "chest pain" in symptoms_lower: flags.append("Red Flag: History of MI with current Chest Pain.")
|
204 |
-
if "history of dvt/pe" in history_lower and "shortness of breath" in symptoms_lower: flags.append("Red Flag: History of DVT/PE with current Shortness of Breath.")
|
205 |
-
|
206 |
return list(set(flags))
|
207 |
-
|
208 |
def format_patient_data_for_prompt(data: dict) -> str:
|
209 |
-
|
210 |
-
|
211 |
-
|
212 |
-
|
213 |
-
|
214 |
-
if
|
215 |
-
|
216 |
-
|
217 |
-
prompt_str += f"**{section_title}:**\n"
|
218 |
-
for sub_key, sub_value in value.items():
|
219 |
-
if sub_value: prompt_str += f" - {sub_key.replace('_', ' ').title()}: {sub_value}\n"
|
220 |
-
elif isinstance(value, list) and value:
|
221 |
-
prompt_str += f"**{section_title}:** {', '.join(map(str, value))}\n"
|
222 |
-
elif value and not isinstance(value, dict):
|
223 |
-
prompt_str += f"**{section_title}:** {value}\n"
|
224 |
return prompt_str.strip()
|
225 |
|
226 |
|
227 |
# --- Tool Definitions ---
|
|
|
|
|
|
|
|
|
228 |
|
229 |
-
# Pydantic models
|
230 |
-
class LabOrderInput(BaseModel):
|
231 |
-
test_name: str = Field(..., description="Specific name of the lab test or panel (e.g., 'CBC', 'BMP', 'Troponin I', 'Urinalysis', 'D-dimer').")
|
232 |
-
reason: str = Field(..., description="Clinical justification for ordering the test (e.g., 'Rule out infection', 'Assess renal function', 'Evaluate for ACS', 'Assess for PE').")
|
233 |
-
priority: str = Field("Routine", description="Priority of the test (e.g., 'STAT', 'Routine').")
|
234 |
-
|
235 |
-
class PrescriptionInput(BaseModel):
|
236 |
-
medication_name: str = Field(..., description="Name of the medication.")
|
237 |
-
dosage: str = Field(..., description="Dosage amount and unit (e.g., '500 mg', '10 mg', '81 mg').")
|
238 |
-
route: str = Field(..., description="Route of administration (e.g., 'PO', 'IV', 'IM', 'Topical', 'SL').")
|
239 |
-
frequency: str = Field(..., description="How often the medication should be taken (e.g., 'BID', 'QDaily', 'Q4-6H PRN', 'once').")
|
240 |
-
duration: str = Field("As directed", description="Duration of treatment (e.g., '7 days', '1 month', 'Ongoing', 'Until follow-up').")
|
241 |
-
reason: str = Field(..., description="Clinical indication for the prescription.")
|
242 |
-
|
243 |
-
class InteractionCheckInput(BaseModel):
|
244 |
-
potential_prescription: str = Field(..., description="The name of the NEW medication being considered for prescribing.")
|
245 |
-
current_medications: Optional[List[str]] = Field(None, description="List of patient's current medication names (populated from state).")
|
246 |
-
allergies: Optional[List[str]] = Field(None, description="List of patient's known allergies (populated from state).")
|
247 |
-
|
248 |
-
class FlagRiskInput(BaseModel):
|
249 |
-
risk_description: str = Field(..., description="Specific critical risk identified (e.g., 'Suspected Sepsis', 'Acute Coronary Syndrome', 'Stroke Alert').")
|
250 |
-
urgency: str = Field("High", description="Urgency level (e.g., 'Critical', 'High', 'Moderate').")
|
251 |
-
|
252 |
-
# Tool functions
|
253 |
@tool("order_lab_test", args_schema=LabOrderInput)
|
254 |
def order_lab_test(test_name: str, reason: str, priority: str = "Routine") -> str:
|
255 |
-
""
|
256 |
-
print(f"Executing order_lab_test: {test_name}, Reason: {reason}, Priority: {priority}")
|
257 |
-
return json.dumps({"status": "success", "message": f"Lab Ordered: {test_name} ({priority})", "details": f"Reason: {reason}"})
|
258 |
-
|
259 |
@tool("prescribe_medication", args_schema=PrescriptionInput)
|
260 |
def prescribe_medication(medication_name: str, dosage: str, route: str, frequency: str, duration: str, reason: str) -> str:
|
261 |
-
"""
|
262 |
-
print(f"Executing prescribe_medication: {medication_name} {dosage}...")
|
263 |
-
return json.dumps({"status": "success", "message": f"Prescription Prepared: {medication_name} {dosage} {route} {frequency}", "details": f"Duration: {duration}. Reason: {reason}"})
|
264 |
-
|
265 |
@tool("check_drug_interactions", args_schema=InteractionCheckInput)
|
266 |
def check_drug_interactions(potential_prescription: str, current_medications: Optional[List[str]] = None, allergies: Optional[List[str]] = None) -> str:
|
267 |
-
|
268 |
-
|
269 |
-
|
270 |
-
""
|
271 |
-
|
272 |
-
print(f"
|
273 |
-
|
274 |
-
|
275 |
-
current_meds_list = current_medications or []; allergies_list = allergies or []
|
276 |
-
current_med_names_lower = []
|
277 |
-
for med in current_meds_list:
|
278 |
-
match = re.match(r"^\s*([a-zA-Z\-]+)", str(med));
|
279 |
-
if match: current_med_names_lower.append(match.group(1).lower())
|
280 |
-
allergies_lower = [str(a).lower().strip() for a in allergies_list if a]
|
281 |
-
print(f" Against Current Meds (names): {current_med_names_lower}"); print(f" Against Allergies: {allergies_lower}")
|
282 |
-
|
283 |
-
print(f" Step 1: Normalizing '{potential_prescription}'..."); potential_rxcui = get_rxcui(potential_prescription)
|
284 |
-
potential_label = get_openfda_label(rxcui=potential_rxcui, drug_name=potential_prescription)
|
285 |
-
if not potential_rxcui and not potential_label: warnings.append(f"INFO: Could not reliably identify '{potential_prescription}'. Checks may be incomplete.")
|
286 |
-
|
287 |
print(" Step 2: Performing Allergy Check...");
|
288 |
for allergy in allergies_lower:
|
289 |
-
if allergy == potential_med_lower: warnings.append(f"CRITICAL ALLERGY (Name Match): Patient allergic to '{allergy}'. Potential prescription is '{potential_prescription}'.")
|
290 |
-
elif allergy in ["penicillin", "pcns"] and potential_med_lower in ["amoxicillin", "ampicillin", "augmentin", "piperacillin"]: warnings.append(f"POTENTIAL CROSS-ALLERGY: Patient allergic to Penicillin. High risk with '{potential_prescription}'.")
|
291 |
-
elif allergy == "sulfa" and potential_med_lower in ["sulfamethoxazole", "bactrim", "sulfasalazine"]: warnings.append(f"POTENTIAL CROSS-ALLERGY: Patient allergic to Sulfa. High risk with '{potential_prescription}'.")
|
292 |
-
elif allergy in ["nsaids", "aspirin"] and potential_med_lower in ["ibuprofen", "naproxen", "ketorolac", "diclofenac"]: warnings.append(f"POTENTIAL CROSS-ALLERGY: Patient allergic to NSAIDs/Aspirin. Risk with '{potential_prescription}'.")
|
293 |
-
if potential_label:
|
294 |
-
|
295 |
-
|
296 |
-
|
297 |
-
|
298 |
-
|
299 |
-
allergy_mentions_warn = search_text_list(warnings_section, allergies_lower)
|
300 |
-
if allergy_mentions_warn: warnings.append(f"ALLERGY RISK (Warning Found): Label for '{potential_prescription}' mentions warnings potentially related to patient allergies: {'; '.join(allergy_mentions_warn)}")
|
301 |
-
|
302 |
-
print(" Step 3: Performing Drug-Drug Interaction Check...")
|
303 |
if potential_rxcui or potential_label:
|
304 |
for current_med_name in current_med_names_lower:
|
305 |
-
if not current_med_name or current_med_name == potential_med_lower: continue
|
306 |
-
|
307 |
-
|
308 |
-
|
309 |
-
if
|
310 |
-
|
311 |
-
if
|
312 |
-
|
313 |
-
|
314 |
-
|
315 |
-
if interaction_mentions: warnings.append(f"Potential Interaction ({potential_prescription.capitalize()} Label): Mentions '{current_med_name.capitalize()}'. Snippets: {'; '.join(interaction_mentions)}"); interaction_found_flag = True
|
316 |
-
if current_label and current_label.get("drug_interactions") and not interaction_found_flag:
|
317 |
-
interaction_mentions = search_text_list(current_label.get("drug_interactions"), search_terms_for_potential)
|
318 |
-
if interaction_mentions: warnings.append(f"Potential Interaction ({current_med_name.capitalize()} Label): Mentions '{potential_prescription.capitalize()}'. Snippets: {'; '.join(interaction_mentions)}")
|
319 |
-
else: warnings.append(f"INFO: Drug-drug interaction check skipped for '{potential_prescription}' as it could not be identified via RxNorm/OpenFDA.")
|
320 |
-
|
321 |
-
final_warnings = list(set(warnings)); status = "warning" if any("CRITICAL" in w or "Interaction" in w or "RISK" in w for w in final_warnings) else "clear"
|
322 |
-
if not final_warnings: status = "clear"
|
323 |
-
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."
|
324 |
-
print(f"--- Interaction Check Complete for '{potential_prescription}' ---")
|
325 |
return json.dumps({"status": status, "message": message, "warnings": final_warnings})
|
326 |
-
|
327 |
@tool("flag_risk", args_schema=FlagRiskInput)
|
328 |
def flag_risk(risk_description: str, urgency: str) -> str:
|
329 |
-
"""
|
330 |
-
print(f"Executing flag_risk: {risk_description}, Urgency: {urgency}")
|
331 |
-
st.error(f"π¨ **{urgency.upper()} RISK FLAGGED by AI:** {risk_description}", icon="π¨")
|
332 |
-
return json.dumps({"status": "flagged", "message": f"Risk '{risk_description}' flagged with {urgency} urgency."})
|
333 |
-
|
334 |
-
# Initialize Search Tool
|
335 |
search_tool = TavilySearchResults(max_results=ClinicalAppSettings.MAX_SEARCH_RESULTS, name="tavily_search_results")
|
336 |
|
337 |
# --- LangGraph Setup ---
|
338 |
-
class AgentState(TypedDict):
|
339 |
-
messages: Annotated[list[Any], operator.add]; patient_data: Optional[dict]
|
340 |
tools = [order_lab_test, prescribe_medication, check_drug_interactions, flag_risk, search_tool]
|
341 |
tool_executor = ToolExecutor(tools)
|
342 |
model = ChatGroq(temperature=ClinicalAppSettings.TEMPERATURE, model=ClinicalAppSettings.MODEL_NAME)
|
343 |
model_with_tools = model.bind_tools(tools)
|
344 |
|
345 |
-
# --- Graph Nodes ---
|
|
|
346 |
def agent_node(state: AgentState):
|
347 |
-
print("\n---AGENT NODE---")
|
348 |
-
current_messages =
|
349 |
-
|
350 |
-
|
351 |
-
print(f"
|
352 |
-
|
353 |
-
response = model_with_tools.invoke(current_messages)
|
354 |
-
print(f"Agent Raw Response Type: {type(response)}")
|
355 |
-
if hasattr(response, 'tool_calls') and response.tool_calls: print(f"Agent Response Tool Calls: {response.tool_calls}")
|
356 |
-
else: print("Agent Response: No tool calls.")
|
357 |
-
except Exception as e:
|
358 |
-
print(f"ERROR in agent_node during LLM invocation: {type(e).__name__} - {e}"); traceback.print_exc()
|
359 |
-
error_message = AIMessage(content=f"Sorry, an internal error occurred while processing the request: {type(e).__name__}")
|
360 |
-
return {"messages": [error_message]}
|
361 |
return {"messages": [response]}
|
362 |
-
|
363 |
def tool_node(state: AgentState):
|
364 |
-
print("\n---TOOL NODE---")
|
365 |
-
|
366 |
-
|
367 |
-
|
368 |
-
|
369 |
-
prescriptions_requested =
|
370 |
-
|
371 |
-
|
372 |
-
|
373 |
-
if med_name: prescriptions_requested[med_name] = call
|
374 |
-
elif tool_name == 'check_drug_interactions': potential_med = tool_args.get('potential_prescription', '').lower()
|
375 |
-
if potential_med: interaction_checks_requested[potential_med] = call
|
376 |
-
valid_tool_calls_for_execution = []; blocked_ids = set()
|
377 |
for med_name, prescribe_call in prescriptions_requested.items():
|
378 |
-
if med_name not in interaction_checks_requested:
|
379 |
-
|
380 |
-
|
381 |
-
tool_messages.append(error_msg); blocked_ids.add(prescribe_call['id'])
|
382 |
-
valid_tool_calls_for_execution = [call for call in tool_calls if call['id'] not in blocked_ids]
|
383 |
-
patient_data = state.get("patient_data", {}); patient_meds_full = patient_data.get("medications", {}).get("current", []); patient_allergies = patient_data.get("allergies", [])
|
384 |
for call in valid_tool_calls_for_execution:
|
385 |
-
|
386 |
-
|
387 |
-
|
388 |
-
|
389 |
-
|
390 |
-
|
391 |
-
|
392 |
-
|
393 |
-
|
394 |
-
if isinstance(resp, Exception):
|
395 |
-
error_type = type(resp).__name__; error_str = str(resp); print(f"ERROR executing tool '{tool_name}' (ID: {tool_call_id}): {error_type} - {error_str}"); traceback.print_exc()
|
396 |
-
st.error(f"Error executing action '{tool_name}': {error_type}"); error_content = json.dumps({"status": "error", "message": f"Failed to execute '{tool_name}': {error_type} - {error_str}"})
|
397 |
-
tool_messages.append(ToolMessage(content=error_content, tool_call_id=tool_call_id, name=tool_name))
|
398 |
-
if isinstance(resp, AttributeError) and "'dict' object has no attribute 'tool'" in error_str: print("\n *** DETECTED SPECIFIC ATTRIBUTE ERROR ('dict' object has no attribute 'tool') *** \n")
|
399 |
-
else:
|
400 |
-
print(f"Tool '{tool_name}' (ID: {tool_call_id}) executed successfully."); content_str = str(resp); tool_messages.append(ToolMessage(content=content_str, tool_call_id=tool_call_id, name=tool_name))
|
401 |
-
except Exception as e:
|
402 |
-
print(f"CRITICAL UNEXPECTED ERROR within tool_node logic: {type(e).__name__} - {e}"); traceback.print_exc(); st.error(f"Critical internal error processing actions: {e}")
|
403 |
-
error_content = json.dumps({"status": "error", "message": f"Internal error processing tools: {e}"}); processed_ids = {msg.tool_call_id for msg in tool_messages}
|
404 |
-
for call in valid_tool_calls_for_execution:
|
405 |
-
if call['id'] not in processed_ids: tool_messages.append(ToolMessage(content=error_content, tool_call_id=call['id'], name=call['name']))
|
406 |
print(f"Returning {len(tool_messages)} tool messages."); return {"messages": tool_messages}
|
407 |
|
408 |
# --- Graph Edges (Routing Logic) ---
|
409 |
def should_continue(state: AgentState) -> str:
|
410 |
-
print("\n---ROUTING DECISION---"); last_message = state['messages'][-1] if state['messages'] else None
|
411 |
-
if not isinstance(last_message, AIMessage): return "end_conversation_turn"
|
412 |
-
if "Sorry, an internal error occurred" in last_message.content: return "end_conversation_turn"
|
413 |
-
if getattr(last_message, 'tool_calls', None): return "continue_tools"
|
414 |
-
else: return "end_conversation_turn"
|
415 |
|
416 |
# --- Graph Definition & Compilation ---
|
417 |
workflow = StateGraph(AgentState); workflow.add_node("agent", agent_node); workflow.add_node("tools", tool_node)
|
@@ -430,16 +233,16 @@ def main():
|
|
430 |
# --- Patient Data Input Sidebar ---
|
431 |
with st.sidebar:
|
432 |
st.header("π Patient Intake Form")
|
433 |
-
# Input fields (
|
434 |
st.subheader("Demographics"); age = st.number_input("Age", 0, 120, 55); sex = st.selectbox("Sex", ["Male", "Female", "Other"])
|
435 |
-
st.subheader("HPI"); chief_complaint = st.text_input("Chief Complaint", "Chest pain"); hpi_details = st.text_area("HPI Details", "55 y/o male...", height=
|
436 |
-
st.subheader("History"); pmh = st.text_area("PMH", "HTN, HLD, DM2, MI"); psh = st.text_area("PSH", "Appendectomy")
|
437 |
-
st.subheader("Meds & Allergies"); current_meds_str = st.text_area("Current Meds", "Lisinopril 10mg daily\nMetformin 1000mg BID
|
438 |
st.subheader("Social/Family"); social_history = st.text_area("SH", "Smoker"); family_history = st.text_area("FHx", "Father MI")
|
439 |
st.subheader("Vitals & Exam"); col1, col2 = st.columns(2);
|
440 |
with col1: temp_c = st.number_input("Temp C", 35.0, 42.0, 36.8, format="%.1f"); hr_bpm = st.number_input("HR", 30, 250, 95); rr_rpm = st.number_input("RR", 5, 50, 18)
|
441 |
with col2: bp_mmhg = st.text_input("BP", "155/90"); spo2_percent = st.number_input("SpO2", 70, 100, 96); pain_scale = st.slider("Pain", 0, 10, 8)
|
442 |
-
exam_notes = st.text_area("Exam Notes", "Awake, alert...", height=
|
443 |
|
444 |
if st.button("Start/Update Consultation"):
|
445 |
current_meds_list = [med.strip() for med in current_meds_str.split('\n') if med.strip()]
|
@@ -447,65 +250,65 @@ def main():
|
|
447 |
for med in current_meds_list: match = re.match(r"^\s*([a-zA-Z\-]+)", med);
|
448 |
if match: current_med_names_only.append(match.group(1).lower())
|
449 |
allergies_list = []
|
450 |
-
for a in allergies_str.split(','):
|
451 |
-
|
452 |
-
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)
|
453 |
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} }
|
454 |
-
red_flags = check_red_flags(st.session_state.patient_data); st.sidebar.markdown("---")
|
455 |
if red_flags: st.sidebar.warning("**Initial Red Flags:**"); [st.sidebar.warning(f"- {flag.replace('Red Flag: ','')}") for flag in red_flags]
|
456 |
else: st.sidebar.success("No immediate red flags.")
|
457 |
-
initial_prompt = "Initiate consultation
|
458 |
st.session_state.messages = [HumanMessage(content=initial_prompt)]; st.success("Patient data loaded/updated.")
|
459 |
|
460 |
# --- Main Chat Interface Area ---
|
461 |
st.header("π¬ Clinical Consultation")
|
462 |
-
# Display loop -
|
463 |
for msg in st.session_state.messages:
|
464 |
if isinstance(msg, HumanMessage):
|
465 |
with st.chat_message("user"): st.markdown(msg.content) # No key
|
466 |
elif isinstance(msg, AIMessage):
|
467 |
with st.chat_message("assistant"): # No key
|
468 |
ai_content = msg.content; structured_output = None
|
469 |
-
try:
|
470 |
json_match = re.search(r"```json\s*(\{.*?\})\s*```", ai_content, re.DOTALL | re.IGNORECASE)
|
471 |
-
if json_match:
|
472 |
-
|
473 |
-
|
474 |
-
|
475 |
-
if suffix: st.markdown(suffix)
|
476 |
-
elif ai_content.strip().startswith("{") and ai_content.strip().endswith("}"):
|
477 |
-
structured_output = json.loads(ai_content); ai_content = ""
|
478 |
else: st.markdown(ai_content)
|
479 |
except Exception as e: st.markdown(ai_content); print(f"Error parsing/displaying AI JSON: {e}")
|
480 |
-
if structured_output and isinstance(structured_output, dict):
|
481 |
-
st.divider(); st.subheader("π AI Analysis & Recommendations")
|
482 |
-
cols = st.columns(2)
|
483 |
-
with cols[0]:
|
484 |
-
|
485 |
-
|
486 |
-
|
487 |
-
|
488 |
-
|
489 |
-
|
490 |
-
|
491 |
-
|
492 |
-
|
493 |
-
|
494 |
-
st.markdown("**Recommended Plan:**"); plan = structured_output.get('recommended_plan', {})
|
495 |
-
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("")
|
496 |
-
st.markdown("**Rationale & Guideline Check:**"); st.markdown(f"> {structured_output.get('rationale_summary', 'N/A')}")
|
497 |
-
interaction_summary = structured_output.get("interaction_check_summary", "")
|
498 |
-
if interaction_summary: st.markdown("**Interaction Check Summary:**"); st.markdown(f"> {interaction_summary}")
|
499 |
-
st.divider()
|
500 |
if getattr(msg, 'tool_calls', None):
|
501 |
-
with st.expander("π οΈ AI requested actions", expanded=False):
|
502 |
-
|
503 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
504 |
elif isinstance(msg, ToolMessage):
|
505 |
tool_name_display = getattr(msg, 'name', 'tool_execution')
|
506 |
with st.chat_message(tool_name_display, avatar="π οΈ"): # No key
|
507 |
try: # Tool message display logic...
|
508 |
-
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")
|
509 |
if status == "success" or status == "clear" or status == "flagged": st.success(f"{message}", icon="β
" if status != "flagged" else "π¨")
|
510 |
elif status == "warning": st.warning(f"{message}", icon="β οΈ");
|
511 |
if warnings and isinstance(warnings, list): st.caption("Details:"); [st.caption(f"- {warn}") for warn in warnings]
|
@@ -518,14 +321,14 @@ def main():
|
|
518 |
if prompt := st.chat_input("Your message or follow-up query..."):
|
519 |
if not st.session_state.patient_data: st.warning("Please load patient data first."); st.stop()
|
520 |
user_message = HumanMessage(content=prompt); st.session_state.messages.append(user_message)
|
521 |
-
with st.chat_message("user"): st.markdown(prompt)
|
522 |
current_state = AgentState(messages=st.session_state.messages, patient_data=st.session_state.patient_data)
|
523 |
with st.spinner("SynapseAI is thinking..."):
|
524 |
try:
|
525 |
final_state = st.session_state.graph_app.invoke(current_state, {"recursion_limit": 15})
|
526 |
-
st.session_state.messages = final_state['messages']
|
527 |
except Exception as e: print(f"CRITICAL ERROR: {e}"); traceback.print_exc(); st.error(f"Error: {e}")
|
528 |
-
st.rerun()
|
529 |
|
530 |
# Disclaimer
|
531 |
st.markdown("---"); st.warning("**Disclaimer:** SynapseAI is for demonstration...")
|
|
|
1 |
+
# -*- coding: utf-8 -*-
|
2 |
import streamlit as st
|
3 |
import requests
|
4 |
import json
|
|
|
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
|
|
|
21 |
from typing import Optional, List, Dict, Any, TypedDict, Annotated
|
22 |
|
23 |
# --- Environment Variable Loading & Validation ---
|
24 |
+
load_dotenv()
|
|
|
25 |
UMLS_API_KEY = os.environ.get("UMLS_API_KEY")
|
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: missing_keys.append("UMLS_API_KEY")
|
30 |
if not GROQ_API_KEY: missing_keys.append("GROQ_API_KEY")
|
31 |
if not TAVILY_API_KEY: missing_keys.append("TAVILY_API_KEY")
|
32 |
+
if missing_keys: st.error(f"Missing API Key(s): {', '.join(missing_keys)}."); st.stop()
|
|
|
|
|
|
|
|
|
|
|
|
|
33 |
|
34 |
# --- Configuration & Constants ---
|
35 |
+
class ClinicalAppSettings: APP_TITLE = "SynapseAI (UMLS/FDA Integrated)"; PAGE_LAYOUT = "wide"; MODEL_NAME = "llama3-70b-8192"; TEMPERATURE = 0.1; MAX_SEARCH_RESULTS = 3
|
36 |
+
class ClinicalPrompts: SYSTEM_PROMPT = """
|
37 |
+
You are SynapseAI, an expert AI clinical assistant engaged in an interactive consultation... [SYSTEM PROMPT REMAINS THE SAME - OMITTED FOR BREVITY]
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
38 |
"""
|
39 |
|
40 |
+
# --- API Helper Functions (get_rxcui, get_openfda_label, search_text_list) ---
|
41 |
+
# ... (Keep these functions exactly as they were in the previous 'full code' response) ...
|
42 |
+
UMLS_AUTH_ENDPOINT = "https://utslogin.nlm.nih.gov/cas/v1/api-key"; RXNORM_API_BASE = "https://rxnav.nlm.nih.gov/REST"; OPENFDA_API_BASE = "https://api.fda.gov/drug/label.json"
|
43 |
+
@lru_cache(maxsize=256)
|
|
|
|
|
44 |
def get_rxcui(drug_name: str) -> Optional[str]:
|
45 |
+
if not drug_name or not isinstance(drug_name, str): return None; drug_name = drug_name.strip();
|
46 |
+
if not drug_name: return None; print(f"RxNorm Lookup for: '{drug_name}'");
|
|
|
|
|
|
|
|
|
47 |
try:
|
48 |
+
params = {"name": drug_name, "search": 1}; response = requests.get(f"{RXNORM_API_BASE}/rxcui.json", params=params, timeout=10); response.raise_for_status(); data = response.json();
|
49 |
+
if data and "idGroup" in data and "rxnormId" in data["idGroup"]: rxcui = data["idGroup"]["rxnormId"][0]; print(f" Found RxCUI: {rxcui} for '{drug_name}'"); return rxcui
|
50 |
+
else:
|
51 |
+
params = {"name": drug_name}; response = requests.get(f"{RXNORM_API_BASE}/drugs.json", params=params, timeout=10); response.raise_for_status(); data = response.json();
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
52 |
if data and "drugGroup" in data and "conceptGroup" in data["drugGroup"]:
|
53 |
for group in data["drugGroup"]["conceptGroup"]:
|
54 |
if group.get("tty") in ["SBD", "SCD", "GPCK", "BPCK", "IN", "MIN", "PIN"]:
|
55 |
+
if "conceptProperties" in group and group["conceptProperties"]: rxcui = group["conceptProperties"][0].get("rxcui");
|
56 |
+
if rxcui: print(f" Found RxCUI (via /drugs): {rxcui} for '{drug_name}'"); return rxcui
|
57 |
+
print(f" RxCUI not found for '{drug_name}'."); return None
|
|
|
|
|
58 |
except requests.exceptions.RequestException as e: print(f" Error fetching RxCUI for '{drug_name}': {e}"); return None
|
59 |
except json.JSONDecodeError as e: print(f" Error decoding RxNorm JSON response for '{drug_name}': {e}"); return None
|
60 |
except Exception as e: print(f" Unexpected error in get_rxcui for '{drug_name}': {e}"); return None
|
61 |
+
@lru_cache(maxsize=128)
|
|
|
62 |
def get_openfda_label(rxcui: Optional[str] = None, drug_name: Optional[str] = None) -> Optional[dict]:
|
63 |
+
if not rxcui and not drug_name: return None; print(f"OpenFDA Label Lookup for: RXCUI={rxcui}, Name={drug_name}"); search_terms = []
|
|
|
|
|
|
|
64 |
if rxcui: search_terms.append(f'spl_rxnorm_code:"{rxcui}" OR openfda.rxcui:"{rxcui}"')
|
65 |
if drug_name: search_terms.append(f'(openfda.brand_name:"{drug_name.lower()}" OR openfda.generic_name:"{drug_name.lower()}")')
|
66 |
+
search_query = " OR ".join(search_terms); params = {"search": search_query, "limit": 1};
|
67 |
try:
|
68 |
+
response = requests.get(OPENFDA_API_BASE, params=params, timeout=15); response.raise_for_status(); data = response.json();
|
|
|
69 |
if data and "results" in data and data["results"]: print(f" Found OpenFDA label for query: {search_query}"); return data["results"][0]
|
70 |
print(f" No OpenFDA label found for query: {search_query}"); return None
|
71 |
except requests.exceptions.RequestException as e: print(f" Error fetching OpenFDA label: {e}"); return None
|
72 |
except json.JSONDecodeError as e: print(f" Error decoding OpenFDA JSON response: {e}"); return None
|
73 |
except Exception as e: print(f" Unexpected error in get_openfda_label: {e}"); return None
|
|
|
74 |
def search_text_list(text_list: Optional[List[str]], search_terms: List[str]) -> List[str]:
|
75 |
+
found_snippets = [];
|
76 |
+
if not text_list or not search_terms: return found_snippets; search_terms_lower = [str(term).lower() for term in search_terms if term];
|
|
|
|
|
77 |
for text_item in text_list:
|
78 |
+
if not isinstance(text_item, str): continue; text_item_lower = text_item.lower();
|
|
|
79 |
for term in search_terms_lower:
|
80 |
if term in text_item_lower:
|
81 |
+
start_index = text_item_lower.find(term); snippet_start = max(0, start_index - 50); snippet_end = min(len(text_item), start_index + len(term) + 100); snippet = text_item[snippet_start:snippet_end];
|
82 |
+
snippet = snippet.replace(term, f"**{term}**", 1); found_snippets.append(f"...{snippet}..."); break
|
|
|
|
|
83 |
return found_snippets
|
84 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
85 |
|
86 |
+
# --- Other Helper Functions (parse_bp, check_red_flags, format_patient_data_for_prompt) ---
|
87 |
+
# ... (Keep these functions exactly as they were) ...
|
88 |
+
def parse_bp(bp_string: str) -> Optional[tuple[int, int]]:
|
89 |
+
if not isinstance(bp_string, str): return None; match = re.match(r"(\d{1,3})\s*/\s*(\d{1,3})", bp_string.strip());
|
90 |
+
if match: return int(match.group(1)), int(match.group(2)); return None
|
91 |
def check_red_flags(patient_data: dict) -> List[str]:
|
92 |
+
flags = [];
|
93 |
+
if not patient_data: return flags; symptoms = patient_data.get("hpi", {}).get("symptoms", []); vitals = patient_data.get("vitals", {}); history = patient_data.get("pmh", {}).get("conditions", ""); symptoms_lower = [str(s).lower() for s in symptoms if isinstance(s, str)];
|
94 |
+
if "chest pain" in symptoms_lower: flags.append("Red Flag: Chest Pain reported."); if "shortness of breath" in symptoms_lower: flags.append("Red Flag: Shortness of Breath reported."); if "severe headache" in symptoms_lower: flags.append("Red Flag: Severe Headache reported."); if "sudden vision loss" in symptoms_lower: flags.append("Red Flag: Sudden Vision Loss reported."); if "weakness on one side" in symptoms_lower: flags.append("Red Flag: Unilateral Weakness reported (potential stroke)."); if "hemoptysis" in symptoms_lower: flags.append("Red Flag: Hemoptysis (coughing up blood)."); if "syncope" in symptoms_lower: flags.append("Red Flag: Syncope (fainting).");
|
95 |
+
if vitals: temp = vitals.get("temp_c"); hr = vitals.get("hr_bpm"); rr = vitals.get("rr_rpm"); spo2 = vitals.get("spo2_percent"); bp_str = vitals.get("bp_mmhg");
|
96 |
+
if temp is not None and temp >= 38.5: flags.append(f"Red Flag: Fever ({temp}Β°C)."); if hr is not None and hr >= 120: flags.append(f"Red Flag: Tachycardia ({hr} bpm)."); if hr is not None and hr <= 50: flags.append(f"Red Flag: Bradycardia ({hr} bpm)."); if rr is not None and rr >= 24: flags.append(f"Red Flag: Tachypnea ({rr} rpm)."); if spo2 is not None and spo2 <= 92: flags.append(f"Red Flag: Hypoxia ({spo2}%).");
|
97 |
+
if bp_str: bp = parse_bp(bp_str);
|
98 |
+
if bp:
|
99 |
+
if bp[0] >= 180 or bp[1] >= 110: flags.append(f"Red Flag: Hypertensive Urgency/Emergency (BP: {bp_str} mmHg).");
|
100 |
+
if bp[0] <= 90 or bp[1] <= 60: flags.append(f"Red Flag: Hypotension (BP: {bp_str} mmHg).");
|
101 |
+
if history and isinstance(history, str): history_lower = history.lower();
|
102 |
+
if "history of mi" in history_lower and "chest pain" in symptoms_lower: flags.append("Red Flag: History of MI with current Chest Pain.");
|
103 |
+
if "history of dvt/pe" in history_lower and "shortness of breath" in symptoms_lower: flags.append("Red Flag: History of DVT/PE with current Shortness of Breath.");
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
104 |
return list(set(flags))
|
|
|
105 |
def format_patient_data_for_prompt(data: dict) -> str:
|
106 |
+
if not data: return "No patient data provided."; prompt_str = "";
|
107 |
+
for key, value in data.items(): section_title = key.replace('_', ' ').title();
|
108 |
+
if isinstance(value, dict) and value: has_content = any(sub_value for sub_value in value.values());
|
109 |
+
if has_content: prompt_str += f"**{section_title}:**\n";
|
110 |
+
for sub_key, sub_value in value.items():
|
111 |
+
if sub_value: prompt_str += f" - {sub_key.replace('_', ' ').title()}: {sub_value}\n"
|
112 |
+
elif isinstance(value, list) and value: prompt_str += f"**{section_title}:** {', '.join(map(str, value))}\n"
|
113 |
+
elif value and not isinstance(value, dict): prompt_str += f"**{section_title}:** {value}\n";
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
114 |
return prompt_str.strip()
|
115 |
|
116 |
|
117 |
# --- Tool Definitions ---
|
118 |
+
class LabOrderInput(BaseModel): test_name: str = Field(...); reason: str = Field(...); priority: str = Field("Routine")
|
119 |
+
class PrescriptionInput(BaseModel): medication_name: str = Field(...); dosage: str = Field(...); route: str = Field(...); frequency: str = Field(...); duration: str = Field("As directed"); reason: str = Field(...)
|
120 |
+
class InteractionCheckInput(BaseModel): potential_prescription: str = Field(...); current_medications: Optional[List[str]] = Field(None); allergies: Optional[List[str]] = Field(None)
|
121 |
+
class FlagRiskInput(BaseModel): risk_description: str = Field(...); urgency: str = Field("High")
|
122 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
123 |
@tool("order_lab_test", args_schema=LabOrderInput)
|
124 |
def order_lab_test(test_name: str, reason: str, priority: str = "Routine") -> str:
|
125 |
+
print(f"Executing order_lab_test: {test_name}, Reason: {reason}, Priority: {priority}"); return json.dumps({"status": "success", "message": f"Lab Ordered: {test_name} ({priority})", "details": f"Reason: {reason}"})
|
|
|
|
|
|
|
126 |
@tool("prescribe_medication", args_schema=PrescriptionInput)
|
127 |
def prescribe_medication(medication_name: str, dosage: str, route: str, frequency: str, duration: str, reason: str) -> str:
|
128 |
+
print(f"Executing prescribe_medication: {medication_name} {dosage}..."); return json.dumps({"status": "success", "message": f"Prescription Prepared: {medication_name} {dosage} {route} {frequency}", "details": f"Duration: {duration}. Reason: {reason}"})
|
|
|
|
|
|
|
129 |
@tool("check_drug_interactions", args_schema=InteractionCheckInput)
|
130 |
def check_drug_interactions(potential_prescription: str, current_medications: Optional[List[str]] = None, allergies: Optional[List[str]] = None) -> str:
|
131 |
+
# ... (Keep the FULL implementation of the NEW check_drug_interactions using API helpers) ...
|
132 |
+
print(f"\n--- Executing REAL check_drug_interactions ---"); print(f"Checking potential prescription: '{potential_prescription}'"); warnings = []; potential_med_lower = potential_prescription.lower().strip();
|
133 |
+
current_meds_list = current_medications or []; allergies_list = allergies or []; current_med_names_lower = [];
|
134 |
+
for med in current_meds_list: match = re.match(r"^\s*([a-zA-Z\-]+)", str(med));
|
135 |
+
if match: current_med_names_lower.append(match.group(1).lower());
|
136 |
+
allergies_lower = [str(a).lower().strip() for a in allergies_list if a]; print(f" Against Current Meds (names): {current_med_names_lower}"); print(f" Against Allergies: {allergies_lower}");
|
137 |
+
print(f" Step 1: Normalizing '{potential_prescription}'..."); potential_rxcui = get_rxcui(potential_prescription); potential_label = get_openfda_label(rxcui=potential_rxcui, drug_name=potential_prescription);
|
138 |
+
if not potential_rxcui and not potential_label: warnings.append(f"INFO: Could not reliably identify '{potential_prescription}'. Checks may be incomplete.");
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
139 |
print(" Step 2: Performing Allergy Check...");
|
140 |
for allergy in allergies_lower:
|
141 |
+
if allergy == potential_med_lower: warnings.append(f"CRITICAL ALLERGY (Name Match): Patient allergic to '{allergy}'. Potential prescription is '{potential_prescription}'.");
|
142 |
+
elif allergy in ["penicillin", "pcns"] and potential_med_lower in ["amoxicillin", "ampicillin", "augmentin", "piperacillin"]: warnings.append(f"POTENTIAL CROSS-ALLERGY: Patient allergic to Penicillin. High risk with '{potential_prescription}'.");
|
143 |
+
elif allergy == "sulfa" and potential_med_lower in ["sulfamethoxazole", "bactrim", "sulfasalazine"]: warnings.append(f"POTENTIAL CROSS-ALLERGY: Patient allergic to Sulfa. High risk with '{potential_prescription}'.");
|
144 |
+
elif allergy in ["nsaids", "aspirin"] and potential_med_lower in ["ibuprofen", "naproxen", "ketorolac", "diclofenac"]: warnings.append(f"POTENTIAL CROSS-ALLERGY: Patient allergic to NSAIDs/Aspirin. Risk with '{potential_prescription}'.");
|
145 |
+
if potential_label: contraindications = potential_label.get("contraindications"); warnings_section = potential_label.get("warnings_and_cautions") or potential_label.get("warnings");
|
146 |
+
if contraindications: allergy_mentions_ci = search_text_list(contraindications, allergies_lower);
|
147 |
+
if allergy_mentions_ci: warnings.append(f"ALLERGY RISK (Contraindication Found): Label for '{potential_prescription}' mentions contraindication potentially related to patient allergies: {'; '.join(allergy_mentions_ci)}");
|
148 |
+
if warnings_section: allergy_mentions_warn = search_text_list(warnings_section, allergies_lower);
|
149 |
+
if allergy_mentions_warn: warnings.append(f"ALLERGY RISK (Warning Found): Label for '{potential_prescription}' mentions warnings potentially related to patient allergies: {'; '.join(allergy_mentions_warn)}");
|
150 |
+
print(" Step 3: Performing Drug-Drug Interaction Check...");
|
|
|
|
|
|
|
|
|
151 |
if potential_rxcui or potential_label:
|
152 |
for current_med_name in current_med_names_lower:
|
153 |
+
if not current_med_name or current_med_name == potential_med_lower: continue; print(f" Checking interaction between '{potential_prescription}' and '{current_med_name}'..."); current_rxcui = get_rxcui(current_med_name); current_label = get_openfda_label(rxcui=current_rxcui, drug_name=current_med_name); search_terms_for_current = [current_med_name];
|
154 |
+
if current_rxcui: search_terms_for_current.append(current_rxcui); search_terms_for_potential = [potential_med_lower];
|
155 |
+
if potential_rxcui: search_terms_for_potential.append(potential_rxcui); interaction_found_flag = False;
|
156 |
+
if potential_label and potential_label.get("drug_interactions"): interaction_mentions = search_text_list(potential_label.get("drug_interactions"), search_terms_for_current);
|
157 |
+
if interaction_mentions: warnings.append(f"Potential Interaction ({potential_prescription.capitalize()} Label): Mentions '{current_med_name.capitalize()}'. Snippets: {'; '.join(interaction_mentions)}"); interaction_found_flag = True;
|
158 |
+
if current_label and current_label.get("drug_interactions") and not interaction_found_flag: interaction_mentions = search_text_list(current_label.get("drug_interactions"), search_terms_for_potential);
|
159 |
+
if interaction_mentions: warnings.append(f"Potential Interaction ({current_med_name.capitalize()} Label): Mentions '{potential_prescription.capitalize()}'. Snippets: {'; '.join(interaction_mentions)}");
|
160 |
+
else: warnings.append(f"INFO: Drug-drug interaction check skipped for '{potential_prescription}' as it could not be identified via RxNorm/OpenFDA.");
|
161 |
+
final_warnings = list(set(warnings)); status = "warning" if any("CRITICAL" in w or "Interaction" in w or "RISK" in w for w in final_warnings) else "clear";
|
162 |
+
if not final_warnings: status = "clear"; 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."; print(f"--- Interaction Check Complete for '{potential_prescription}' ---");
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
163 |
return json.dumps({"status": status, "message": message, "warnings": final_warnings})
|
|
|
164 |
@tool("flag_risk", args_schema=FlagRiskInput)
|
165 |
def flag_risk(risk_description: str, urgency: str) -> str:
|
166 |
+
print(f"Executing flag_risk: {risk_description}, Urgency: {urgency}"); st.error(f"π¨ **{urgency.upper()} RISK FLAGGED by AI:** {risk_description}", icon="π¨"); return json.dumps({"status": "flagged", "message": f"Risk '{risk_description}' flagged with {urgency} urgency."})
|
|
|
|
|
|
|
|
|
|
|
167 |
search_tool = TavilySearchResults(max_results=ClinicalAppSettings.MAX_SEARCH_RESULTS, name="tavily_search_results")
|
168 |
|
169 |
# --- LangGraph Setup ---
|
170 |
+
class AgentState(TypedDict): messages: Annotated[list[Any], operator.add]; patient_data: Optional[dict]
|
|
|
171 |
tools = [order_lab_test, prescribe_medication, check_drug_interactions, flag_risk, search_tool]
|
172 |
tool_executor = ToolExecutor(tools)
|
173 |
model = ChatGroq(temperature=ClinicalAppSettings.TEMPERATURE, model=ClinicalAppSettings.MODEL_NAME)
|
174 |
model_with_tools = model.bind_tools(tools)
|
175 |
|
176 |
+
# --- Graph Nodes (agent_node, tool_node) ---
|
177 |
+
# ... (Keep agent_node and tool_node functions exactly as they were in the last 'full code' response) ...
|
178 |
def agent_node(state: AgentState):
|
179 |
+
print("\n---AGENT NODE---"); current_messages = state['messages'];
|
180 |
+
if not current_messages or not isinstance(current_messages[0], SystemMessage): print("Prepending System Prompt."); current_messages = [SystemMessage(content=ClinicalPrompts.SYSTEM_PROMPT)] + current_messages;
|
181 |
+
print(f"Invoking LLM with {len(current_messages)} messages.");
|
182 |
+
try: response = model_with_tools.invoke(current_messages); print(f"Agent Raw Response Type: {type(response)}");
|
183 |
+
if hasattr(response, 'tool_calls') and response.tool_calls: print(f"Agent Response Tool Calls: {response.tool_calls}"); else: print("Agent Response: No tool calls.");
|
184 |
+
except Exception as e: print(f"ERROR in agent_node: {e}"); traceback.print_exc(); error_message = AIMessage(content=f"Error: {e}"); return {"messages": [error_message]};
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
185 |
return {"messages": [response]}
|
|
|
186 |
def tool_node(state: AgentState):
|
187 |
+
print("\n---TOOL NODE---"); tool_messages = []; last_message = state['messages'][-1];
|
188 |
+
if not isinstance(last_message, AIMessage) or not getattr(last_message, 'tool_calls', None): print("Warning: Tool node called unexpectedly."); return {"messages": []};
|
189 |
+
tool_calls = last_message.tool_calls; print(f"Tool calls received: {json.dumps(tool_calls, indent=2)}"); prescriptions_requested = {}; interaction_checks_requested = {};
|
190 |
+
for call in tool_calls: tool_name = call.get('name'); tool_args = call.get('args', {});
|
191 |
+
if tool_name == 'prescribe_medication': med_name = tool_args.get('medication_name', '').lower();
|
192 |
+
if med_name: prescriptions_requested[med_name] = call;
|
193 |
+
elif tool_name == 'check_drug_interactions': potential_med = tool_args.get('potential_prescription', '').lower();
|
194 |
+
if potential_med: interaction_checks_requested[potential_med] = call;
|
195 |
+
valid_tool_calls_for_execution = []; blocked_ids = set();
|
|
|
|
|
|
|
|
|
196 |
for med_name, prescribe_call in prescriptions_requested.items():
|
197 |
+
if med_name not in interaction_checks_requested: st.error(f"**Safety Violation:** AI tried to prescribe '{med_name}' without check."); error_msg = ToolMessage(content=json.dumps({"status": "error", "message": f"Interaction check needed for '{med_name}'."}), tool_call_id=prescribe_call['id'], name=prescribe_call['name']); tool_messages.append(error_msg); blocked_ids.add(prescribe_call['id']);
|
198 |
+
valid_tool_calls_for_execution = [call for call in tool_calls if call['id'] not in blocked_ids];
|
199 |
+
patient_data = state.get("patient_data", {}); patient_meds_full = patient_data.get("medications", {}).get("current", []); patient_allergies = patient_data.get("allergies", []);
|
|
|
|
|
|
|
200 |
for call in valid_tool_calls_for_execution:
|
201 |
+
if call['name'] == 'check_drug_interactions':
|
202 |
+
if 'args' not in call: call['args'] = {}; call['args']['current_medications'] = patient_meds_full; call['args']['allergies'] = patient_allergies; print(f"Augmented interaction check args for call ID {call['id']}");
|
203 |
+
if valid_tool_calls_for_execution: print(f"Attempting execution: {[c['name'] for c in valid_tool_calls_for_execution]}");
|
204 |
+
try: responses = tool_executor.batch(valid_tool_calls_for_execution, return_exceptions=True);
|
205 |
+
for call, resp in zip(valid_tool_calls_for_execution, responses): tool_call_id = call['id']; tool_name = call['name'];
|
206 |
+
if isinstance(resp, Exception): error_type = type(resp).__name__; error_str = str(resp); print(f"ERROR executing tool '{tool_name}': {error_type} - {error_str}"); traceback.print_exc(); st.error(f"Error: {error_type}"); error_content = json.dumps({"status": "error", "message": f"Failed: {error_type} - {error_str}"}); tool_messages.append(ToolMessage(content=error_content, tool_call_id=tool_call_id, name=tool_name));
|
207 |
+
if isinstance(resp, AttributeError) and "'dict' object has no attribute 'tool'" in error_str: print("\n *** DETECTED SPECIFIC ATTRIBUTE ERROR *** \n");
|
208 |
+
else: print(f"Tool '{tool_name}' executed."); content_str = str(resp); tool_messages.append(ToolMessage(content=content_str, tool_call_id=tool_call_id, name=tool_name));
|
209 |
+
except Exception as e: print(f"CRITICAL TOOL NODE ERROR: {e}"); traceback.print_exc(); st.error(f"Critical error: {e}"); error_content = json.dumps({"status": "error", "message": f"Internal error: {e}"}); processed_ids = {msg.tool_call_id for msg in tool_messages}; [tool_messages.append(ToolMessage(content=error_content, tool_call_id=call['id'], name=call['name'])) for call in valid_tool_calls_for_execution if call['id'] not in processed_ids];
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
210 |
print(f"Returning {len(tool_messages)} tool messages."); return {"messages": tool_messages}
|
211 |
|
212 |
# --- Graph Edges (Routing Logic) ---
|
213 |
def should_continue(state: AgentState) -> str:
|
214 |
+
print("\n---ROUTING DECISION---"); last_message = state['messages'][-1] if state['messages'] else None;
|
215 |
+
if not isinstance(last_message, AIMessage): return "end_conversation_turn";
|
216 |
+
if "Sorry, an internal error occurred" in last_message.content: return "end_conversation_turn";
|
217 |
+
if getattr(last_message, 'tool_calls', None): return "continue_tools"; else: return "end_conversation_turn";
|
|
|
218 |
|
219 |
# --- Graph Definition & Compilation ---
|
220 |
workflow = StateGraph(AgentState); workflow.add_node("agent", agent_node); workflow.add_node("tools", tool_node)
|
|
|
233 |
# --- Patient Data Input Sidebar ---
|
234 |
with st.sidebar:
|
235 |
st.header("π Patient Intake Form")
|
236 |
+
# Input fields... (Using shorter versions for brevity, assume full fields are here)
|
237 |
st.subheader("Demographics"); age = st.number_input("Age", 0, 120, 55); sex = st.selectbox("Sex", ["Male", "Female", "Other"])
|
238 |
+
st.subheader("HPI"); chief_complaint = st.text_input("Chief Complaint", "Chest pain"); hpi_details = st.text_area("HPI Details", "55 y/o male...", height=100); symptoms = st.multiselect("Symptoms", ["Nausea", "Diaphoresis", "SOB", "Dizziness"], default=["Nausea", "Diaphoresis"])
|
239 |
+
st.subheader("History"); pmh = st.text_area("PMH", "HTN, HLD, DM2, History of MI"); psh = st.text_area("PSH", "Appendectomy")
|
240 |
+
st.subheader("Meds & Allergies"); current_meds_str = st.text_area("Current Meds", "Lisinopril 10mg daily\nMetformin 1000mg BID"); allergies_str = st.text_area("Allergies", "Penicillin (rash)")
|
241 |
st.subheader("Social/Family"); social_history = st.text_area("SH", "Smoker"); family_history = st.text_area("FHx", "Father MI")
|
242 |
st.subheader("Vitals & Exam"); col1, col2 = st.columns(2);
|
243 |
with col1: temp_c = st.number_input("Temp C", 35.0, 42.0, 36.8, format="%.1f"); hr_bpm = st.number_input("HR", 30, 250, 95); rr_rpm = st.number_input("RR", 5, 50, 18)
|
244 |
with col2: bp_mmhg = st.text_input("BP", "155/90"); spo2_percent = st.number_input("SpO2", 70, 100, 96); pain_scale = st.slider("Pain", 0, 10, 8)
|
245 |
+
exam_notes = st.text_area("Exam Notes", "Awake, alert...", height=50)
|
246 |
|
247 |
if st.button("Start/Update Consultation"):
|
248 |
current_meds_list = [med.strip() for med in current_meds_str.split('\n') if med.strip()]
|
|
|
250 |
for med in current_meds_list: match = re.match(r"^\s*([a-zA-Z\-]+)", med);
|
251 |
if match: current_med_names_only.append(match.group(1).lower())
|
252 |
allergies_list = []
|
253 |
+
for a in allergies_str.split(','): cleaned_allergy = a.strip();
|
254 |
+
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)
|
|
|
255 |
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} }
|
256 |
+
red_flags = check_red_flags(st.session_state.patient_data); st.sidebar.markdown("---");
|
257 |
if red_flags: st.sidebar.warning("**Initial Red Flags:**"); [st.sidebar.warning(f"- {flag.replace('Red Flag: ','')}") for flag in red_flags]
|
258 |
else: st.sidebar.success("No immediate red flags.")
|
259 |
+
initial_prompt = "Initiate consultation. Review patient data and begin analysis."
|
260 |
st.session_state.messages = [HumanMessage(content=initial_prompt)]; st.success("Patient data loaded/updated.")
|
261 |
|
262 |
# --- Main Chat Interface Area ---
|
263 |
st.header("π¬ Clinical Consultation")
|
264 |
+
# Display loop - SyntaxError Fixed
|
265 |
for msg in st.session_state.messages:
|
266 |
if isinstance(msg, HumanMessage):
|
267 |
with st.chat_message("user"): st.markdown(msg.content) # No key
|
268 |
elif isinstance(msg, AIMessage):
|
269 |
with st.chat_message("assistant"): # No key
|
270 |
ai_content = msg.content; structured_output = None
|
271 |
+
try: # JSON Parsing logic...
|
272 |
json_match = re.search(r"```json\s*(\{.*?\})\s*```", ai_content, re.DOTALL | re.IGNORECASE)
|
273 |
+
if json_match: json_str = json_match.group(1); prefix = ai_content[:json_match.start()].strip(); suffix = ai_content[json_match.end():].strip();
|
274 |
+
if prefix: st.markdown(prefix); structured_output = json.loads(json_str);
|
275 |
+
if suffix: st.markdown(suffix)
|
276 |
+
elif ai_content.strip().startswith("{") and ai_content.strip().endswith("}"): structured_output = json.loads(ai_content); ai_content = ""
|
|
|
|
|
|
|
277 |
else: st.markdown(ai_content)
|
278 |
except Exception as e: st.markdown(ai_content); print(f"Error parsing/displaying AI JSON: {e}")
|
279 |
+
if structured_output and isinstance(structured_output, dict): # Structured JSON display logic...
|
280 |
+
st.divider(); st.subheader("π AI Analysis & Recommendations")
|
281 |
+
cols = st.columns(2);
|
282 |
+
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', []);
|
283 |
+
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]
|
284 |
+
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",[])
|
285 |
+
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)}");
|
286 |
+
if not flags and not concerns: st.success("No major risks highlighted.")
|
287 |
+
with cols[1]: st.markdown("**Recommended Plan:**"); plan = structured_output.get('recommended_plan', {});
|
288 |
+
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("")
|
289 |
+
st.markdown("**Rationale & Guideline Check:**"); st.markdown(f"> {structured_output.get('rationale_summary', 'N/A')}"); interaction_summary = structured_output.get("interaction_check_summary", "");
|
290 |
+
if interaction_summary: st.markdown("**Interaction Check Summary:**"); st.markdown(f"> {interaction_summary}"); st.divider()
|
291 |
+
|
292 |
+
# CORRECTED Tool Call Display Block
|
|
|
|
|
|
|
|
|
|
|
|
|
293 |
if getattr(msg, 'tool_calls', None):
|
294 |
+
with st.expander("π οΈ AI requested actions", expanded=False):
|
295 |
+
if msg.tool_calls: # Check if list is not empty
|
296 |
+
for tc in msg.tool_calls:
|
297 |
+
try:
|
298 |
+
# Properly indented try block content
|
299 |
+
st.code(f"Action: {tc.get('name', 'Unknown Tool')}\nArgs: {json.dumps(tc.get('args', {}), indent=2)}", language="json")
|
300 |
+
except Exception as display_e:
|
301 |
+
# Properly indented except block content
|
302 |
+
st.error(f"Could not display tool call arguments properly: {display_e}", icon="β οΈ")
|
303 |
+
# Provide a fallback display
|
304 |
+
st.code(f"Action: {tc.get('name', 'Unknown Tool')}\nRaw Args: {tc.get('args')}") # Show raw args if JSON fails
|
305 |
+
else:
|
306 |
+
st.caption("_No actions requested in this turn._")
|
307 |
elif isinstance(msg, ToolMessage):
|
308 |
tool_name_display = getattr(msg, 'name', 'tool_execution')
|
309 |
with st.chat_message(tool_name_display, avatar="π οΈ"): # No key
|
310 |
try: # Tool message display logic...
|
311 |
+
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");
|
312 |
if status == "success" or status == "clear" or status == "flagged": st.success(f"{message}", icon="β
" if status != "flagged" else "π¨")
|
313 |
elif status == "warning": st.warning(f"{message}", icon="β οΈ");
|
314 |
if warnings and isinstance(warnings, list): st.caption("Details:"); [st.caption(f"- {warn}") for warn in warnings]
|
|
|
321 |
if prompt := st.chat_input("Your message or follow-up query..."):
|
322 |
if not st.session_state.patient_data: st.warning("Please load patient data first."); st.stop()
|
323 |
user_message = HumanMessage(content=prompt); st.session_state.messages.append(user_message)
|
324 |
+
with st.chat_message("user"): st.markdown(prompt)
|
325 |
current_state = AgentState(messages=st.session_state.messages, patient_data=st.session_state.patient_data)
|
326 |
with st.spinner("SynapseAI is thinking..."):
|
327 |
try:
|
328 |
final_state = st.session_state.graph_app.invoke(current_state, {"recursion_limit": 15})
|
329 |
+
st.session_state.messages = final_state['messages']
|
330 |
except Exception as e: print(f"CRITICAL ERROR: {e}"); traceback.print_exc(); st.error(f"Error: {e}")
|
331 |
+
st.rerun()
|
332 |
|
333 |
# Disclaimer
|
334 |
st.markdown("---"); st.warning("**Disclaimer:** SynapseAI is for demonstration...")
|