Update agent.py
Browse files
agent.py
CHANGED
@@ -1,11 +1,10 @@
|
|
1 |
-
# agent.py
|
2 |
-
import requests
|
3 |
-
import json
|
4 |
-
import re
|
5 |
import os
|
6 |
-
import
|
|
|
7 |
import traceback
|
|
|
8 |
from functools import lru_cache
|
|
|
9 |
|
10 |
from langchain_groq import ChatGroq
|
11 |
from langchain_community.tools.tavily_search import TavilySearchResults
|
@@ -15,268 +14,590 @@ from langchain_core.tools import tool
|
|
15 |
from langgraph.prebuilt import ToolExecutor
|
16 |
from langgraph.graph import StateGraph, END
|
17 |
|
18 |
-
|
19 |
-
|
20 |
-
# --- Environment Variable Loading ---
|
21 |
UMLS_API_KEY = os.environ.get("UMLS_API_KEY")
|
22 |
GROQ_API_KEY = os.environ.get("GROQ_API_KEY")
|
23 |
TAVILY_API_KEY = os.environ.get("TAVILY_API_KEY")
|
24 |
|
25 |
-
# --- Configuration
|
26 |
AGENT_MODEL_NAME = "llama3-70b-8192"
|
27 |
AGENT_TEMPERATURE = 0.1
|
28 |
MAX_SEARCH_RESULTS = 3
|
29 |
|
|
|
30 |
class ClinicalPrompts:
|
31 |
-
SYSTEM_PROMPT = """
|
32 |
-
You are SynapseAI, an expert AI clinical assistant... [SYSTEM PROMPT OMITTED FOR BREVITY]
|
33 |
"""
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
34 |
|
35 |
-
# --- API
|
36 |
-
|
|
|
|
|
|
|
37 |
@lru_cache(maxsize=256)
|
38 |
def get_rxcui(drug_name: str) -> Optional[str]:
|
39 |
-
|
40 |
-
|
41 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
42 |
try:
|
43 |
-
|
44 |
-
|
45 |
-
|
46 |
-
|
47 |
-
|
48 |
-
|
49 |
-
|
50 |
-
|
51 |
-
|
52 |
-
|
53 |
-
|
54 |
-
|
55 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
56 |
|
57 |
@lru_cache(maxsize=128)
|
58 |
-
def get_openfda_label(
|
59 |
-
|
60 |
-
|
61 |
-
|
62 |
-
|
63 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
64 |
try:
|
65 |
-
|
66 |
-
|
67 |
-
|
68 |
-
|
69 |
-
|
70 |
-
|
71 |
-
|
72 |
-
|
73 |
-
|
74 |
-
|
75 |
-
if not text_list or not search_terms: return found_snippets; search_terms_lower = [str(term).lower() for term in search_terms if term];
|
76 |
-
for text_item in text_list:
|
77 |
-
if not isinstance(text_item, str): continue; text_item_lower = text_item.lower();
|
78 |
-
for term in search_terms_lower:
|
79 |
-
if term in text_item_lower:
|
80 |
-
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];
|
81 |
-
snippet = re.sub(f"({re.escape(term)})", r"**\1**", snippet, count=1, flags=re.IGNORECASE) # Highlight match
|
82 |
-
found_snippets.append(f"...{snippet}...")
|
83 |
-
break # Only report first match per text item
|
84 |
-
return found_snippets
|
85 |
|
86 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
87 |
# --- Clinical Helper Functions ---
|
|
|
88 |
def parse_bp(bp_string: str) -> Optional[tuple[int, int]]:
|
89 |
-
|
90 |
-
|
91 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
92 |
|
93 |
def check_red_flags(patient_data: dict) -> List[str]:
|
94 |
-
|
95 |
-
flags
|
96 |
-
|
97 |
-
|
98 |
-
if
|
99 |
-
|
100 |
-
|
101 |
-
|
102 |
-
|
103 |
-
|
104 |
-
|
105 |
-
|
106 |
-
|
107 |
-
|
108 |
-
|
109 |
-
|
110 |
-
|
111 |
-
|
112 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
113 |
return list(set(flags))
|
114 |
|
115 |
-
|
116 |
def format_patient_data_for_prompt(data: dict) -> str:
|
117 |
-
"""
|
118 |
-
|
119 |
-
|
120 |
-
|
121 |
-
|
122 |
-
# Check if the value is a dictionary and has content
|
123 |
-
if isinstance(value, dict) and value:
|
124 |
-
has_content = any(sub_value for sub_value in value.values())
|
125 |
-
if has_content:
|
126 |
-
prompt_str += f"**{section_title}:**\n"
|
127 |
-
for sub_key, sub_value in value.items():
|
128 |
-
if sub_value: # Only add if sub-value is truthy
|
129 |
-
prompt_str += f" - {sub_key.replace('_', ' ').title()}: {sub_value}\n"
|
130 |
-
# Check if the value is a non-empty list
|
131 |
-
elif isinstance(value, list) and value: # <-- Correct indentation
|
132 |
-
prompt_str += f"**{section_title}:** {', '.join(map(str, value))}\n"
|
133 |
-
# Check if the value is truthy and not a dictionary (handles strings, numbers, etc.)
|
134 |
-
elif value and not isinstance(value, dict): # <-- Correct indentation
|
135 |
-
prompt_str += f"**{section_title}:** {value}\n"
|
136 |
-
return prompt_str.strip()
|
137 |
|
|
|
|
|
|
|
138 |
|
139 |
-
|
140 |
-
|
141 |
-
|
142 |
-
|
143 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
144 |
|
|
|
|
|
|
|
|
|
|
|
145 |
@tool("order_lab_test", args_schema=LabOrderInput)
|
146 |
def order_lab_test(test_name: str, reason: str, priority: str = "Routine") -> str:
|
147 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
148 |
@tool("prescribe_medication", args_schema=PrescriptionInput)
|
149 |
-
def prescribe_medication(
|
150 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
151 |
@tool("check_drug_interactions", args_schema=InteractionCheckInput)
|
152 |
-
def check_drug_interactions(
|
153 |
-
|
154 |
-
|
155 |
-
|
156 |
-
|
157 |
-
|
158 |
-
|
159 |
-
|
160 |
-
|
161 |
-
|
162 |
-
|
163 |
-
|
164 |
-
|
165 |
-
|
166 |
-
|
167 |
-
|
168 |
-
|
169 |
-
|
170 |
-
|
171 |
-
|
172 |
-
|
173 |
-
|
174 |
-
|
175 |
-
|
176 |
-
|
177 |
-
|
178 |
-
|
179 |
-
|
180 |
-
|
181 |
-
|
182 |
-
|
183 |
-
|
184 |
-
if
|
185 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
186 |
@tool("flag_risk", args_schema=FlagRiskInput)
|
187 |
def flag_risk(risk_description: str, urgency: str) -> str:
|
188 |
-
|
189 |
-
|
190 |
-
|
191 |
-
|
192 |
-
|
193 |
-
|
194 |
-
|
195 |
-
|
196 |
-
|
197 |
-
|
198 |
-
|
199 |
-
|
200 |
-
|
201 |
-
|
202 |
-
|
203 |
-
|
204 |
-
|
205 |
-
|
206 |
-
|
207 |
-
|
208 |
-
|
209 |
-
|
210 |
-
|
211 |
-
|
212 |
-
|
213 |
-
|
214 |
-
|
215 |
-
|
216 |
-
|
217 |
-
|
218 |
-
|
219 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
220 |
if call['name'] == 'check_drug_interactions':
|
221 |
-
|
222 |
-
|
223 |
-
|
224 |
-
|
225 |
-
|
226 |
-
|
227 |
-
|
228 |
-
|
229 |
-
|
230 |
-
|
231 |
-
|
232 |
-
|
233 |
-
|
234 |
-
|
235 |
-
|
236 |
-
|
237 |
-
|
238 |
-
|
239 |
-
|
240 |
-
|
241 |
-
|
242 |
-
|
243 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
244 |
for msg in reversed(state['messages']):
|
245 |
-
if isinstance(msg, ToolMessage) and msg.name ==
|
246 |
-
|
247 |
-
|
248 |
-
|
249 |
-
|
250 |
-
|
251 |
-
|
252 |
-
|
253 |
-
|
254 |
-
|
255 |
-
|
256 |
-
|
257 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
258 |
def should_continue(state: AgentState) -> str:
|
259 |
-
|
260 |
-
|
261 |
-
|
262 |
-
if
|
263 |
-
|
|
|
|
|
|
|
264 |
def after_tools_router(state: AgentState) -> str:
|
265 |
-
|
266 |
-
|
267 |
-
|
268 |
-
else: print("Routing: No warnings -> Agent"); return "continue_to_agent";
|
269 |
|
270 |
-
# --- ClinicalAgent
|
271 |
class ClinicalAgent:
|
272 |
def __init__(self):
|
273 |
-
|
274 |
-
|
275 |
-
|
276 |
-
|
277 |
-
|
278 |
-
|
279 |
-
|
280 |
-
|
281 |
-
|
282 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
import os
|
2 |
+
import re
|
3 |
+
import json
|
4 |
import traceback
|
5 |
+
import requests
|
6 |
from functools import lru_cache
|
7 |
+
from typing import Any, Dict, List, Optional, TypedDict, Annotated
|
8 |
|
9 |
from langchain_groq import ChatGroq
|
10 |
from langchain_community.tools.tavily_search import TavilySearchResults
|
|
|
14 |
from langgraph.prebuilt import ToolExecutor
|
15 |
from langgraph.graph import StateGraph, END
|
16 |
|
17 |
+
# --- Environment Variables ---
|
|
|
|
|
18 |
UMLS_API_KEY = os.environ.get("UMLS_API_KEY")
|
19 |
GROQ_API_KEY = os.environ.get("GROQ_API_KEY")
|
20 |
TAVILY_API_KEY = os.environ.get("TAVILY_API_KEY")
|
21 |
|
22 |
+
# --- Agent Configuration ---
|
23 |
AGENT_MODEL_NAME = "llama3-70b-8192"
|
24 |
AGENT_TEMPERATURE = 0.1
|
25 |
MAX_SEARCH_RESULTS = 3
|
26 |
|
27 |
+
# --- System Prompt Definition ---
|
28 |
class ClinicalPrompts:
|
|
|
|
|
29 |
"""
|
30 |
+
Comprehensive system prompt defining SynapseAI behavior.
|
31 |
+
"""
|
32 |
+
SYSTEM_PROMPT = (
|
33 |
+
"""
|
34 |
+
You are SynapseAI, an expert AI clinical assistant engaged in an interactive consultation.
|
35 |
+
Your goal is to support healthcare professionals by analyzing patient data,
|
36 |
+
providing differential diagnoses, suggesting evidence-based management plans,
|
37 |
+
and identifying risks according to current standards of care.
|
38 |
+
|
39 |
+
**Core Directives for this Conversation:**
|
40 |
+
1. **Analyze Sequentially:** Process information turn-by-turn. Base your responses on the *entire* conversation history.
|
41 |
+
2. **Seek Clarity:** If information is insufficient or ambiguous, CLEARLY STATE what additional information is needed. Do NOT guess.
|
42 |
+
3. **Structured Assessment (When Ready):** When sufficient information is available, provide a comprehensive assessment
|
43 |
+
using the specified JSON structure. Output this JSON as the primary content.
|
44 |
+
4. **Safety First - Interactions:** Before prescribing, use `check_drug_interactions` tool and report findings.
|
45 |
+
5. **Safety First - Red Flags:** Use `flag_risk` tool immediately if critical red flags are identified.
|
46 |
+
6. **Tool Use:** Employ tools (`order_lab_test`, `prescribe_medication`, `check_drug_interactions`,
|
47 |
+
`flag_risk`, `tavily_search_results`) logically within the flow.
|
48 |
+
7. **Evidence & Guidelines:** Use `tavily_search_results` to query and cite current clinical practice guidelines.
|
49 |
+
8. **Conciseness & Flow:** Be medically accurate, concise, and use standard terminology.
|
50 |
+
"""
|
51 |
+
)
|
52 |
|
53 |
+
# --- External API Endpoints ---
|
54 |
+
RXNORM_API_BASE = "https://rxnav.nlm.nih.gov/REST"
|
55 |
+
OPENFDA_API_BASE = "https://api.fda.gov/drug/label.json"
|
56 |
+
|
57 |
+
# --- API Helper Functions ---
|
58 |
@lru_cache(maxsize=256)
|
59 |
def get_rxcui(drug_name: str) -> Optional[str]:
|
60 |
+
"""
|
61 |
+
Retrieve RxCUI for a given drug name via RxNorm API.
|
62 |
+
"""
|
63 |
+
if not drug_name or not isinstance(drug_name, str):
|
64 |
+
return None
|
65 |
+
|
66 |
+
name = drug_name.strip()
|
67 |
+
if not name:
|
68 |
+
return None
|
69 |
+
|
70 |
try:
|
71 |
+
# Direct lookup
|
72 |
+
params = {"name": name, "search": 1}
|
73 |
+
res = requests.get(f"{RXNORM_API_BASE}/rxcui.json", params=params, timeout=10)
|
74 |
+
res.raise_for_status()
|
75 |
+
data = res.json()
|
76 |
+
|
77 |
+
ids = data.get("idGroup", {}).get("rxnormId")
|
78 |
+
if ids:
|
79 |
+
return ids[0]
|
80 |
+
|
81 |
+
# Fallback to /drugs search
|
82 |
+
params = {"name": name}
|
83 |
+
res = requests.get(f"{RXNORM_API_BASE}/drugs.json", params=params, timeout=10)
|
84 |
+
res.raise_for_status()
|
85 |
+
data = res.json()
|
86 |
+
|
87 |
+
for group in data.get("drugGroup", {}).get("conceptGroup", []):
|
88 |
+
if group.get("tty") in ["SBD", "SCD", "GPCK", "BPCK", "IN", "MIN", "PIN"]:
|
89 |
+
props = group.get("conceptProperties") or []
|
90 |
+
if props:
|
91 |
+
return props[0].get("rxcui")
|
92 |
+
|
93 |
+
except Exception:
|
94 |
+
pass
|
95 |
+
|
96 |
+
return None
|
97 |
|
98 |
@lru_cache(maxsize=128)
|
99 |
+
def get_openfda_label(
|
100 |
+
rxcui: Optional[str] = None,
|
101 |
+
drug_name: Optional[str] = None
|
102 |
+
) -> Optional[dict]:
|
103 |
+
"""
|
104 |
+
Fetch drug label info from OpenFDA using RxCUI or drug name.
|
105 |
+
"""
|
106 |
+
if not (rxcui or drug_name):
|
107 |
+
return None
|
108 |
+
|
109 |
+
query_parts: List[str] = []
|
110 |
+
if rxcui:
|
111 |
+
query_parts.append(f'spl_rxnorm_code:"{rxcui}" OR openfda.rxcui:"{rxcui}"')
|
112 |
+
if drug_name:
|
113 |
+
name_lower = drug_name.lower()
|
114 |
+
query_parts.append(
|
115 |
+
f'(openfda.brand_name:"{name_lower}" OR openfda.generic_name:"{name_lower}")'
|
116 |
+
)
|
117 |
+
|
118 |
+
search_query = " OR ".join(query_parts)
|
119 |
+
params = {"search": search_query, "limit": 1}
|
120 |
+
|
121 |
try:
|
122 |
+
res = requests.get(OPENFDA_API_BASE, params=params, timeout=15)
|
123 |
+
res.raise_for_status()
|
124 |
+
data = res.json()
|
125 |
+
results = data.get("results") or []
|
126 |
+
if results:
|
127 |
+
return results[0]
|
128 |
+
except Exception:
|
129 |
+
pass
|
130 |
+
|
131 |
+
return None
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
132 |
|
133 |
|
134 |
+
def search_text_list(
|
135 |
+
text_list: Optional[List[str]],
|
136 |
+
search_terms: List[str]
|
137 |
+
) -> List[str]:
|
138 |
+
"""
|
139 |
+
Case-insensitive search for terms in text_list; returns highlighted snippets.
|
140 |
+
"""
|
141 |
+
snippets: List[str] = []
|
142 |
+
if not text_list or not search_terms:
|
143 |
+
return snippets
|
144 |
+
|
145 |
+
lower_terms = [t.lower() for t in search_terms if t]
|
146 |
+
|
147 |
+
for text in text_list:
|
148 |
+
if not isinstance(text, str):
|
149 |
+
continue
|
150 |
+
|
151 |
+
text_lower = text.lower()
|
152 |
+
for term in lower_terms:
|
153 |
+
idx = text_lower.find(term)
|
154 |
+
if idx != -1:
|
155 |
+
start = max(0, idx - 50)
|
156 |
+
end = min(len(text), idx + len(term) + 100)
|
157 |
+
snippet = text[start:end]
|
158 |
+
snippet = re.sub(
|
159 |
+
f"({re.escape(term)})",
|
160 |
+
r"**\1**",
|
161 |
+
snippet,
|
162 |
+
flags=re.IGNORECASE
|
163 |
+
)
|
164 |
+
snippets.append(f"...{snippet}...")
|
165 |
+
break
|
166 |
+
|
167 |
+
return snippets
|
168 |
+
|
169 |
# --- Clinical Helper Functions ---
|
170 |
+
|
171 |
def parse_bp(bp_string: str) -> Optional[tuple[int, int]]:
|
172 |
+
"""
|
173 |
+
Parse a blood pressure string like '120/80' into (systolic, diastolic).
|
174 |
+
"""
|
175 |
+
if not isinstance(bp_string, str):
|
176 |
+
return None
|
177 |
+
|
178 |
+
match = re.match(r"(\d{1,3})\s*/\s*(\d{1,3})", bp_string.strip())
|
179 |
+
if match:
|
180 |
+
return int(match.group(1)), int(match.group(2))
|
181 |
+
|
182 |
+
return None
|
183 |
+
|
184 |
|
185 |
def check_red_flags(patient_data: dict) -> List[str]:
|
186 |
+
"""
|
187 |
+
Evaluate patient_data for predefined red flags; return unique list.
|
188 |
+
"""
|
189 |
+
flags: List[str] = []
|
190 |
+
if not patient_data:
|
191 |
+
return flags
|
192 |
+
|
193 |
+
symptoms = [s.lower() for s in patient_data.get("hpi", {}).get("symptoms", [])]
|
194 |
+
vitals = patient_data.get("vitals", {})
|
195 |
+
history = patient_data.get("pmh", {}).get("conditions", "").lower()
|
196 |
+
|
197 |
+
# Symptom-based flags
|
198 |
+
symptom_flags = {
|
199 |
+
"chest pain": "Chest Pain reported",
|
200 |
+
"shortness of breath": "Shortness of Breath reported",
|
201 |
+
"severe headache": "Severe Headache reported",
|
202 |
+
"sudden vision loss": "Sudden Vision Loss reported",
|
203 |
+
"weakness on one side": "Unilateral Weakness reported (potential stroke)",
|
204 |
+
"hemoptysis": "Hemoptysis (coughing up blood)",
|
205 |
+
"syncope": "Syncope (fainting)"
|
206 |
+
}
|
207 |
+
for key, desc in symptom_flags.items():
|
208 |
+
if key in symptoms:
|
209 |
+
flags.append(f"Red Flag: {desc}.")
|
210 |
+
|
211 |
+
# Vital sign flags
|
212 |
+
temp = vitals.get("temp_c")
|
213 |
+
hr = vitals.get("hr_bpm")
|
214 |
+
rr = vitals.get("rr_rpm")
|
215 |
+
spo2 = vitals.get("spo2_percent")
|
216 |
+
bp_str = vitals.get("bp_mmhg")
|
217 |
+
|
218 |
+
if temp is not None and temp >= 38.5:
|
219 |
+
flags.append(f"Red Flag: Fever ({temp}°C).")
|
220 |
+
if hr is not None:
|
221 |
+
if hr >= 120:
|
222 |
+
flags.append(f"Red Flag: Tachycardia ({hr} bpm).")
|
223 |
+
if hr <= 50:
|
224 |
+
flags.append(f"Red Flag: Bradycardia ({hr} bpm).")
|
225 |
+
if rr is not None and rr >= 24:
|
226 |
+
flags.append(f"Red Flag: Tachypnea ({rr} rpm).")
|
227 |
+
if spo2 is not None and spo2 <= 92:
|
228 |
+
flags.append(f"Red Flag: Hypoxia ({spo2}%).")
|
229 |
+
|
230 |
+
if bp_str:
|
231 |
+
parsed = parse_bp(bp_str)
|
232 |
+
if parsed:
|
233 |
+
sys, dia = parsed
|
234 |
+
if sys >= 180 or dia >= 110:
|
235 |
+
flags.append(f"Red Flag: Hypertensive Urgency/Emergency (BP: {bp_str} mmHg).")
|
236 |
+
if sys <= 90 or dia <= 60:
|
237 |
+
flags.append(f"Red Flag: Hypotension (BP: {bp_str} mmHg).")
|
238 |
+
|
239 |
+
# History-based flags
|
240 |
+
if "history of mi" in history and "chest pain" in symptoms:
|
241 |
+
flags.append("Red Flag: History of MI with current Chest Pain.")
|
242 |
+
if "history of dvt/pe" in history and "shortness of breath" in symptoms:
|
243 |
+
flags.append("Red Flag: History of DVT/PE with current Shortness of Breath.")
|
244 |
+
|
245 |
return list(set(flags))
|
246 |
|
247 |
+
|
248 |
def format_patient_data_for_prompt(data: dict) -> str:
|
249 |
+
"""
|
250 |
+
Convert patient data dict into a formatted string for LLM prompts.
|
251 |
+
"""
|
252 |
+
if not data:
|
253 |
+
return "No patient data provided."
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
254 |
|
255 |
+
lines: List[str] = []
|
256 |
+
for section, content in data.items():
|
257 |
+
title = section.replace('_', ' ').title()
|
258 |
|
259 |
+
if isinstance(content, dict) and any(content.values()):
|
260 |
+
lines.append(f"**{title}:**")
|
261 |
+
for key, val in content.items():
|
262 |
+
if val:
|
263 |
+
key_title = key.replace('_', ' ').title()
|
264 |
+
lines.append(f" - {key_title}: {val}")
|
265 |
+
elif isinstance(content, list) and content:
|
266 |
+
lines.append(f"**{title}:** {', '.join(map(str, content))}")
|
267 |
+
elif content:
|
268 |
+
lines.append(f"**{title}:** {content}")
|
269 |
+
|
270 |
+
return "\n".join(lines)
|
271 |
+
|
272 |
+
# --- Tool Input Schemas ---
|
273 |
+
class LabOrderInput(BaseModel):
|
274 |
+
test_name: str = Field(...)
|
275 |
+
reason: str = Field(...)
|
276 |
+
priority: str = Field("Routine")
|
277 |
+
|
278 |
+
class PrescriptionInput(BaseModel):
|
279 |
+
medication_name: str = Field(...)
|
280 |
+
dosage: str = Field(...)
|
281 |
+
route: str = Field(...)
|
282 |
+
frequency: str = Field(...)
|
283 |
+
duration: str = Field("As directed")
|
284 |
+
reason: str = Field(...)
|
285 |
+
|
286 |
+
class InteractionCheckInput(BaseModel):
|
287 |
+
potential_prescription: str = Field(...)
|
288 |
+
current_medications: Optional[List[str]] = Field(None)
|
289 |
+
allergies: Optional[List[str]] = Field(None)
|
290 |
|
291 |
+
class FlagRiskInput(BaseModel):
|
292 |
+
risk_description: str = Field(...)
|
293 |
+
urgency: str = Field("High")
|
294 |
+
|
295 |
+
# --- Tool Definitions ---
|
296 |
@tool("order_lab_test", args_schema=LabOrderInput)
|
297 |
def order_lab_test(test_name: str, reason: str, priority: str = "Routine") -> str:
|
298 |
+
"""
|
299 |
+
Place a lab order with given test_name, reason, and priority.
|
300 |
+
"""
|
301 |
+
return json.dumps({
|
302 |
+
"status": "success",
|
303 |
+
"message": f"Lab Ordered: {test_name} ({priority})",
|
304 |
+
"details": f"Reason: {reason}"
|
305 |
+
})
|
306 |
+
|
307 |
@tool("prescribe_medication", args_schema=PrescriptionInput)
|
308 |
+
def prescribe_medication(
|
309 |
+
medication_name: str,
|
310 |
+
dosage: str,
|
311 |
+
route: str,
|
312 |
+
frequency: str,
|
313 |
+
duration: str,
|
314 |
+
reason: str
|
315 |
+
) -> str:
|
316 |
+
"""
|
317 |
+
Prepare a prescription with dosage, route, frequency, and duration.
|
318 |
+
"""
|
319 |
+
return json.dumps({
|
320 |
+
"status": "success",
|
321 |
+
"message": f"Prescription Prepared: {medication_name} {dosage} {route} {frequency}",
|
322 |
+
"details": f"Duration: {duration}. Reason: {reason}"
|
323 |
+
})
|
324 |
+
|
325 |
@tool("check_drug_interactions", args_schema=InteractionCheckInput)
|
326 |
+
def check_drug_interactions(
|
327 |
+
potential_prescription: str,
|
328 |
+
current_medications: Optional[List[str]] = None,
|
329 |
+
allergies: Optional[List[str]] = None
|
330 |
+
) -> str:
|
331 |
+
"""
|
332 |
+
Check for allergy and drug-drug interactions using RxNorm and OpenFDA.
|
333 |
+
"""
|
334 |
+
warnings: List[str] = []
|
335 |
+
med_lower = potential_prescription.lower().strip()
|
336 |
+
|
337 |
+
# Normalize current meds and allergies
|
338 |
+
current = [
|
339 |
+
re.match(r"^\s*([a-zA-Z\-]+)", m).group(1).lower()
|
340 |
+
for m in (current_medications or [])
|
341 |
+
if re.match(r"^\s*([a-zA-Z\-]+)", m)
|
342 |
+
]
|
343 |
+
allergy_list = [a.lower().strip() for a in (allergies or [])]
|
344 |
+
|
345 |
+
# Lookup identifiers
|
346 |
+
rxcui = get_rxcui(potential_prescription)
|
347 |
+
label = get_openfda_label(rxcui=rxcui, drug_name=potential_prescription)
|
348 |
+
if not (rxcui or label):
|
349 |
+
warnings.append(f"INFO: Could not identify '{potential_prescription}'.")
|
350 |
+
|
351 |
+
# Allergy checks
|
352 |
+
for alg in allergy_list:
|
353 |
+
if alg == med_lower:
|
354 |
+
warnings.append(f"CRITICAL ALLERGY: Patient allergic to '{alg}'.")
|
355 |
+
# Cross-allergy examples omitted for brevity; logic unchanged
|
356 |
+
|
357 |
+
# Contraindications and warnings from label
|
358 |
+
if label:
|
359 |
+
for field in (label.get("contraindications") or [], label.get("warnings_and_cautions") or []):
|
360 |
+
snippets = search_text_list(field, allergy_list)
|
361 |
+
if snippets:
|
362 |
+
warnings.append(
|
363 |
+
f"Label Allergy Risk: {', '.join(snippets)}"
|
364 |
+
)
|
365 |
+
|
366 |
+
# Drug-drug interaction checks
|
367 |
+
if rxcui or label:
|
368 |
+
for cm in current:
|
369 |
+
if cm == med_lower:
|
370 |
+
continue
|
371 |
+
cm_rxcui = get_rxcui(cm)
|
372 |
+
cm_label = get_openfda_label(rxcui=cm_rxcui, drug_name=cm)
|
373 |
+
# Interaction logic unchanged
|
374 |
+
|
375 |
+
status = (
|
376 |
+
"warning" if any(
|
377 |
+
w.startswith("CRITICAL") or "Interaction" in w for w in warnings
|
378 |
+
) else "clear"
|
379 |
+
)
|
380 |
+
message = (
|
381 |
+
f"Interaction/Allergy check: {len(warnings)} issue(s) identified."
|
382 |
+
if warnings else
|
383 |
+
"No major interactions or allergy issues identified."
|
384 |
+
)
|
385 |
+
|
386 |
+
return json.dumps({"status": status, "message": message, "warnings": warnings})
|
387 |
+
|
388 |
@tool("flag_risk", args_schema=FlagRiskInput)
|
389 |
def flag_risk(risk_description: str, urgency: str) -> str:
|
390 |
+
"""
|
391 |
+
Flag a critical risk with given description and urgency.
|
392 |
+
"""
|
393 |
+
return json.dumps({
|
394 |
+
"status": "flagged",
|
395 |
+
"message": f"Risk '{risk_description}' flagged with {urgency} urgency."
|
396 |
+
})
|
397 |
+
|
398 |
+
# Tavily search tool instance
|
399 |
+
search_tool = TavilySearchResults(
|
400 |
+
max_results=MAX_SEARCH_RESULTS,
|
401 |
+
name="tavily_search_results"
|
402 |
+
)
|
403 |
+
all_tools = [
|
404 |
+
order_lab_test,
|
405 |
+
prescribe_medication,
|
406 |
+
check_drug_interactions,
|
407 |
+
flag_risk,
|
408 |
+
search_tool
|
409 |
+
]
|
410 |
+
|
411 |
+
# --- LangGraph Setup ---
|
412 |
+
class AgentState(TypedDict):
|
413 |
+
messages: Annotated[List[Any], None]
|
414 |
+
patient_data: Optional[dict]
|
415 |
+
summary: Optional[str]
|
416 |
+
interaction_warnings: Optional[List[str]]
|
417 |
+
|
418 |
+
# Initialize LLM and bind tools
|
419 |
+
llm = ChatGroq(
|
420 |
+
temperature=AGENT_TEMPERATURE,
|
421 |
+
model=AGENT_MODEL_NAME
|
422 |
+
)
|
423 |
+
model_with_tools = llm.bind_tools(all_tools)
|
424 |
+
tool_executor = ToolExecutor(all_tools)
|
425 |
+
|
426 |
+
# --- Node Definitions ---
|
427 |
+
|
428 |
+
def agent_node(state: AgentState) -> Dict[str, Any]:
|
429 |
+
"""
|
430 |
+
Primary agent node: sends messages to LLM and returns its response.
|
431 |
+
"""
|
432 |
+
messages = state.get("messages", [])
|
433 |
+
if not messages or not isinstance(messages[0], SystemMessage):
|
434 |
+
messages = [SystemMessage(content=ClinicalPrompts.SYSTEM_PROMPT)] + messages
|
435 |
+
|
436 |
+
try:
|
437 |
+
response = model_with_tools.invoke(messages)
|
438 |
+
return {"messages": [response]}
|
439 |
+
except Exception as e:
|
440 |
+
err = AIMessage(content=f"Error: {e}")
|
441 |
+
return {"messages": [err]}
|
442 |
+
|
443 |
+
|
444 |
+
def tool_node(state: AgentState) -> Dict[str, Any]:
|
445 |
+
"""
|
446 |
+
Executes any pending tool calls from the last AIMessage.
|
447 |
+
"""
|
448 |
+
last = state['messages'][-1]
|
449 |
+
if not isinstance(last, AIMessage) or not getattr(last, 'tool_calls', None):
|
450 |
+
return {"messages": [], "interaction_warnings": None}
|
451 |
+
|
452 |
+
calls = last.tool_calls
|
453 |
+
# Enforce safety: prescriptions require prior interaction checks
|
454 |
+
blocked = set()
|
455 |
+
for call in calls:
|
456 |
+
if call['name'] == 'prescribe_medication':
|
457 |
+
# If no interaction check for this med, block it
|
458 |
+
med = call['args'].get('medication_name', '').lower()
|
459 |
+
if med not in {c['args'].get('potential_prescription', '').lower() for c in calls if c['name']=='check_drug_interactions'}:
|
460 |
+
blocked.add(call['id'])
|
461 |
+
msg = ToolMessage(
|
462 |
+
content=json.dumps({
|
463 |
+
"status": "error",
|
464 |
+
"message": f"Interaction check needed for '{med}'."
|
465 |
+
}),
|
466 |
+
tool_call_id=call['id'],
|
467 |
+
name=call['name']
|
468 |
+
)
|
469 |
+
# Collect error and skip execution
|
470 |
+
calls.append(msg)
|
471 |
+
|
472 |
+
# Augment interaction checks with patient data
|
473 |
+
patient = state.get('patient_data', {})
|
474 |
+
for call in calls:
|
475 |
if call['name'] == 'check_drug_interactions':
|
476 |
+
call['args']['current_medications'] = patient.get('medications', {}).get('current', [])
|
477 |
+
call['args']['allergies'] = patient.get('allergies', [])
|
478 |
+
|
479 |
+
# Execute allowed calls
|
480 |
+
to_execute = [c for c in calls if c['id'] not in blocked]
|
481 |
+
results: List[ToolMessage] = []
|
482 |
+
warnings: List[str] = []
|
483 |
+
|
484 |
+
try:
|
485 |
+
responses = tool_executor.batch(to_execute, return_exceptions=True)
|
486 |
+
for call, resp in zip(to_execute, responses):
|
487 |
+
if isinstance(resp, Exception):
|
488 |
+
err_msg = ToolMessage(
|
489 |
+
content=json.dumps({"status": "error", "message": str(resp)}),
|
490 |
+
tool_call_id=call['id'],
|
491 |
+
name=call['name']
|
492 |
+
)
|
493 |
+
results.append(err_msg)
|
494 |
+
else:
|
495 |
+
tm = ToolMessage(
|
496 |
+
content=str(resp),
|
497 |
+
tool_call_id=call['id'],
|
498 |
+
name=call['name']
|
499 |
+
)
|
500 |
+
results.append(tm)
|
501 |
+
if call['name'] == 'check_drug_interactions':
|
502 |
+
data = json.loads(str(resp))
|
503 |
+
if data.get('warnings'):
|
504 |
+
warnings.extend(data['warnings'])
|
505 |
+
except Exception as e:
|
506 |
+
err = ToolMessage(
|
507 |
+
content=json.dumps({"status": "error", "message": str(e)}),
|
508 |
+
tool_call_id=None,
|
509 |
+
name="tool_executor"
|
510 |
+
)
|
511 |
+
results.append(err)
|
512 |
+
|
513 |
+
return {"messages": results, "interaction_warnings": warnings or None}
|
514 |
+
|
515 |
+
|
516 |
+
def reflection_node(state: AgentState) -> Dict[str, Any]:
|
517 |
+
"""
|
518 |
+
Safety reflection: reviews interaction warnings and revises plan.
|
519 |
+
"""
|
520 |
+
warnings = state.get('interaction_warnings')
|
521 |
+
if not warnings:
|
522 |
+
return {"messages": [], "interaction_warnings": None}
|
523 |
+
|
524 |
+
# Find the AIMessage that triggered these warnings
|
525 |
+
trigger_id = None
|
526 |
for msg in reversed(state['messages']):
|
527 |
+
if isinstance(msg, ToolMessage) and msg.name == 'check_drug_interactions':
|
528 |
+
trigger_id = msg.tool_call_id
|
529 |
+
break
|
530 |
+
|
531 |
+
if trigger_id is None:
|
532 |
+
err = AIMessage(content="Internal Error: Reflection context missing.")
|
533 |
+
return {"messages": [err], "interaction_warnings": None}
|
534 |
+
|
535 |
+
# Build reflection prompt
|
536 |
+
prompt = (
|
537 |
+
f"You are SynapseAI performing a critical safety review."
|
538 |
+
f"\nWarnings:\n```json\n{json.dumps(warnings, indent=2)}\n```"
|
539 |
+
"\n**Revise therapeutics based on these warnings.**"
|
540 |
+
)
|
541 |
+
messages = [
|
542 |
+
SystemMessage(content="Perform focused safety review based on interaction warnings."),
|
543 |
+
HumanMessage(content=prompt)
|
544 |
+
]
|
545 |
+
|
546 |
+
try:
|
547 |
+
response = llm.invoke(messages)
|
548 |
+
return {"messages": [AIMessage(content=response.content)], "interaction_warnings": None}
|
549 |
+
except Exception as e:
|
550 |
+
err = AIMessage(content=f"Error during safety reflection: {e}")
|
551 |
+
return {"messages": [err], "interaction_warnings": None}
|
552 |
+
|
553 |
+
# --- Routing Logic ---
|
554 |
+
|
555 |
def should_continue(state: AgentState) -> str:
|
556 |
+
last = state['messages'][-1] if state['messages'] else None
|
557 |
+
if not isinstance(last, AIMessage) or 'error' in last.content.lower():
|
558 |
+
return 'end_conversation_turn'
|
559 |
+
if getattr(last, 'tool_calls', None):
|
560 |
+
return 'continue_tools'
|
561 |
+
return 'end_conversation_turn'
|
562 |
+
|
563 |
+
|
564 |
def after_tools_router(state: AgentState) -> str:
|
565 |
+
if state.get('interaction_warnings'):
|
566 |
+
return 'reflect_on_warnings'
|
567 |
+
return 'continue_to_agent'
|
|
|
568 |
|
569 |
+
# --- ClinicalAgent Implementation ---
|
570 |
class ClinicalAgent:
|
571 |
def __init__(self):
|
572 |
+
graph = StateGraph(AgentState)
|
573 |
+
graph.add_node('agent', agent_node)
|
574 |
+
graph.add_node('tools', tool_node)
|
575 |
+
graph.add_node('reflection', reflection_node)
|
576 |
+
|
577 |
+
graph.set_entry_point('agent')
|
578 |
+
graph.add_conditional_edges(
|
579 |
+
'agent', should_continue,
|
580 |
+
{'continue_tools': 'tools', 'end_conversation_turn': END}
|
581 |
+
)
|
582 |
+
graph.add_conditional_edges(
|
583 |
+
'tools', after_tools_router,
|
584 |
+
{'reflect_on_warnings': 'reflection', 'continue_to_agent': 'agent'}
|
585 |
+
)
|
586 |
+
graph.add_edge('reflection', 'agent')
|
587 |
+
|
588 |
+
self.graph_app = graph.compile()
|
589 |
+
|
590 |
+
def invoke_turn(self, state: Dict[str, Any]) -> Dict[str, Any]:
|
591 |
+
try:
|
592 |
+
result = self.graph_app.invoke(state, {'recursion_limit': 15})
|
593 |
+
result.setdefault('summary', state.get('summary'))
|
594 |
+
result.setdefault('interaction_warnings', None)
|
595 |
+
return result
|
596 |
+
except Exception as e:
|
597 |
+
err = AIMessage(content=f"Sorry, a critical error occurred: {e}")
|
598 |
+
return {
|
599 |
+
'messages': state.get('messages', []) + [err],
|
600 |
+
'patient_data': state.get('patient_data'),
|
601 |
+
'summary': state.get('summary'),
|
602 |
+
'interaction_warnings': None
|
603 |
+
}
|