Update agent.py
Browse files
agent.py
CHANGED
@@ -1,10 +1,11 @@
|
|
1 |
-
|
2 |
-
import
|
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,590 +15,282 @@ from langchain_core.tools import tool
|
|
14 |
from langgraph.prebuilt import ToolExecutor
|
15 |
from langgraph.graph import StateGraph, END
|
16 |
|
17 |
-
|
|
|
|
|
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 |
-
# ---
|
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 |
-
# ---
|
54 |
-
|
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 |
-
|
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 |
-
|
72 |
-
|
73 |
-
|
74 |
-
|
75 |
-
|
76 |
-
|
77 |
-
|
78 |
-
|
79 |
-
|
80 |
-
|
81 |
-
|
82 |
-
|
83 |
-
|
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:
|
101 |
-
|
102 |
-
)
|
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 |
-
|
123 |
-
|
124 |
-
|
125 |
-
|
126 |
-
|
127 |
-
|
128 |
-
|
129 |
-
|
130 |
-
|
131 |
-
|
132 |
-
|
133 |
-
|
134 |
-
|
135 |
-
|
136 |
-
|
137 |
-
)
|
138 |
-
|
139 |
-
|
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 |
-
|
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 |
-
|
188 |
-
|
189 |
-
|
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", "")
|
196 |
-
|
197 |
-
|
198 |
-
|
199 |
-
|
200 |
-
|
201 |
-
|
202 |
-
|
203 |
-
|
204 |
-
|
205 |
-
|
206 |
-
|
207 |
-
|
208 |
-
|
209 |
-
|
210 |
-
|
211 |
-
|
212 |
-
|
213 |
-
|
214 |
-
|
215 |
-
|
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 |
-
|
226 |
-
|
227 |
-
|
228 |
-
|
229 |
-
|
230 |
-
|
231 |
-
|
232 |
-
|
233 |
-
|
234 |
-
|
235 |
-
|
236 |
-
|
237 |
-
|
238 |
-
|
239 |
-
|
240 |
-
|
241 |
-
|
242 |
-
|
243 |
-
|
244 |
-
|
245 |
-
return list(set(flags))
|
246 |
|
247 |
|
248 |
def format_patient_data_for_prompt(data: dict) -> str:
|
249 |
-
|
250 |
-
|
251 |
-
|
252 |
-
if
|
253 |
-
|
254 |
-
|
255 |
-
|
256 |
-
|
257 |
-
|
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:
|
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 |
-
|
328 |
-
current_medications
|
329 |
-
|
330 |
-
|
331 |
-
"""
|
332 |
-
|
333 |
-
""
|
334 |
-
|
335 |
-
|
336 |
-
|
337 |
-
|
338 |
-
|
339 |
-
|
340 |
-
|
341 |
-
|
342 |
-
|
343 |
-
|
344 |
-
|
345 |
-
|
346 |
-
|
347 |
-
|
348 |
-
|
349 |
-
|
350 |
-
|
351 |
-
|
352 |
-
|
353 |
-
|
354 |
-
warnings.append(f"
|
355 |
-
|
356 |
-
|
357 |
-
|
358 |
-
|
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 |
-
|
392 |
-
|
393 |
-
|
394 |
-
|
395 |
-
|
396 |
-
|
397 |
-
|
398 |
-
#
|
399 |
-
|
400 |
-
|
401 |
-
|
402 |
-
)
|
403 |
-
|
404 |
-
|
405 |
-
|
406 |
-
|
407 |
-
|
408 |
-
|
409 |
-
]
|
410 |
-
|
411 |
-
|
412 |
-
|
413 |
-
|
414 |
-
|
415 |
-
|
416 |
-
|
417 |
-
|
418 |
-
|
419 |
-
|
420 |
-
|
421 |
-
|
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'] =
|
477 |
-
|
478 |
-
|
479 |
-
|
480 |
-
|
481 |
-
|
482 |
-
|
483 |
-
|
484 |
-
|
485 |
-
|
486 |
-
|
487 |
-
|
488 |
-
|
489 |
-
|
490 |
-
|
491 |
-
|
492 |
-
|
493 |
-
|
494 |
-
|
495 |
-
|
496 |
-
|
497 |
-
|
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 ==
|
528 |
-
|
529 |
-
break
|
530 |
-
|
531 |
-
|
532 |
-
|
533 |
-
|
534 |
-
|
535 |
-
|
536 |
-
|
537 |
-
|
538 |
-
|
539 |
-
|
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 |
-
|
557 |
-
|
558 |
-
|
559 |
-
if
|
560 |
-
|
561 |
-
return 'end_conversation_turn'
|
562 |
-
|
563 |
-
|
564 |
def after_tools_router(state: AgentState) -> str:
|
565 |
-
|
566 |
-
|
567 |
-
return
|
|
|
568 |
|
569 |
-
# --- ClinicalAgent
|
570 |
class ClinicalAgent:
|
571 |
def __init__(self):
|
572 |
-
|
573 |
-
|
574 |
-
|
575 |
-
|
576 |
-
|
577 |
-
|
578 |
-
|
579 |
-
|
580 |
-
|
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 |
-
}
|
|
|
1 |
+
# agent.py
|
2 |
+
import requests
|
3 |
import json
|
4 |
+
import re
|
5 |
+
import os
|
6 |
+
import operator
|
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 |
from langgraph.prebuilt import ToolExecutor
|
16 |
from langgraph.graph import StateGraph, END
|
17 |
|
18 |
+
from typing import Optional, List, Dict, Any, TypedDict, Annotated
|
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 & Constants ---
|
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 engaged in an interactive consultation... [SYSTEM PROMPT OMITTED FOR BREVITY]
|
33 |
"""
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
34 |
|
35 |
+
# --- API Constants & Helper Functions ---
|
36 |
+
# ... (Keep get_rxcui, get_openfda_label, search_text_list implementations) ...
|
37 |
+
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"
|
|
|
|
|
38 |
@lru_cache(maxsize=256)
|
39 |
def get_rxcui(drug_name: str) -> Optional[str]:
|
40 |
+
if not drug_name or not isinstance(drug_name, str): return None; drug_name = drug_name.strip();
|
41 |
+
if not drug_name: return None; print(f"RxNorm Lookup for: '{drug_name}'");
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
42 |
try:
|
43 |
+
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();
|
44 |
+
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
|
45 |
+
else:
|
46 |
+
params = {"name": drug_name}; response = requests.get(f"{RXNORM_API_BASE}/drugs.json", params=params, timeout=10); response.raise_for_status(); data = response.json();
|
47 |
+
if data and "drugGroup" in data and "conceptGroup" in data["drugGroup"]:
|
48 |
+
for group in data["drugGroup"]["conceptGroup"]:
|
49 |
+
if group.get("tty") in ["SBD", "SCD", "GPCK", "BPCK", "IN", "MIN", "PIN"]:
|
50 |
+
if "conceptProperties" in group and group["conceptProperties"]: rxcui = group["conceptProperties"][0].get("rxcui");
|
51 |
+
if rxcui: print(f" Found RxCUI (via /drugs): {rxcui} for '{drug_name}'"); return rxcui
|
52 |
+
print(f" RxCUI not found for '{drug_name}'."); return None
|
53 |
+
except requests.exceptions.RequestException as e: print(f" Error fetching RxCUI for '{drug_name}': {e}"); return None
|
54 |
+
except json.JSONDecodeError as e: print(f" Error decoding RxNorm JSON response for '{drug_name}': {e}"); return None
|
55 |
+
except Exception as e: print(f" Unexpected error in get_rxcui for '{drug_name}': {e}"); return None
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
56 |
@lru_cache(maxsize=128)
|
57 |
+
def get_openfda_label(rxcui: Optional[str] = None, drug_name: Optional[str] = None) -> Optional[dict]:
|
58 |
+
if not rxcui and not drug_name: return None; print(f"OpenFDA Label Lookup for: RXCUI={rxcui}, Name={drug_name}"); search_terms = []
|
59 |
+
if rxcui: search_terms.append(f'spl_rxnorm_code:"{rxcui}" OR openfda.rxcui:"{rxcui}"')
|
60 |
+
if drug_name: search_terms.append(f'(openfda.brand_name:"{drug_name.lower()}" OR openfda.generic_name:"{drug_name.lower()}")')
|
61 |
+
search_query = " OR ".join(search_terms); params = {"search": search_query, "limit": 1};
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
62 |
try:
|
63 |
+
response = requests.get(OPENFDA_API_BASE, params=params, timeout=15); response.raise_for_status(); data = response.json();
|
64 |
+
if data and "results" in data and data["results"]: print(f" Found OpenFDA label for query: {search_query}"); return data["results"][0]
|
65 |
+
print(f" No OpenFDA label found for query: {search_query}"); return None
|
66 |
+
except requests.exceptions.RequestException as e: print(f" Error fetching OpenFDA label: {e}"); return None
|
67 |
+
except json.JSONDecodeError as e: print(f" Error decoding OpenFDA JSON response: {e}"); return None
|
68 |
+
except Exception as e: print(f" Unexpected error in get_openfda_label: {e}"); return None
|
69 |
+
def search_text_list(text_list: Optional[List[str]], search_terms: List[str]) -> List[str]:
|
70 |
+
found_snippets = [];
|
71 |
+
if not text_list or not search_terms: return found_snippets; search_terms_lower = [str(term).lower() for term in search_terms if term];
|
72 |
+
for text_item in text_list:
|
73 |
+
if not isinstance(text_item, str): continue; text_item_lower = text_item.lower();
|
74 |
+
for term in search_terms_lower:
|
75 |
+
if term in text_item_lower:
|
76 |
+
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];
|
77 |
+
snippet = re.sub(f"({re.escape(term)})", r"**\1**", snippet, count=1, flags=re.IGNORECASE) # Highlight match
|
78 |
+
found_snippets.append(f"...{snippet}...")
|
79 |
+
break # Only report first match per text item
|
80 |
+
return found_snippets
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
81 |
|
82 |
# --- Clinical Helper Functions ---
|
|
|
83 |
def parse_bp(bp_string: str) -> Optional[tuple[int, int]]:
|
84 |
+
if not isinstance(bp_string, str): return None; match = re.match(r"(\d{1,3})\s*/\s*(\d{1,3})", bp_string.strip());
|
85 |
+
if match: return int(match.group(1)), int(match.group(2)); return None
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
86 |
|
87 |
+
# CORRECTED check_red_flags function (again)
|
88 |
def check_red_flags(patient_data: dict) -> List[str]:
|
89 |
+
"""Checks patient data against predefined red flags."""
|
90 |
+
flags = []
|
91 |
+
if not patient_data: return flags
|
92 |
+
symptoms = patient_data.get("hpi", {}).get("symptoms", [])
|
|
|
|
|
|
|
|
|
93 |
vitals = patient_data.get("vitals", {})
|
94 |
+
history = patient_data.get("pmh", {}).get("conditions", "")
|
95 |
+
symptoms_lower = [str(s).lower() for s in symptoms if isinstance(s, str)]
|
96 |
+
|
97 |
+
# Symptom Flags (Separate lines)
|
98 |
+
if "chest pain" in symptoms_lower: flags.append("Red Flag: Chest Pain reported.")
|
99 |
+
if "shortness of breath" in symptoms_lower: flags.append("Red Flag: Shortness of Breath reported.")
|
100 |
+
if "severe headache" in symptoms_lower: flags.append("Red Flag: Severe Headache reported.")
|
101 |
+
if "sudden vision loss" in symptoms_lower: flags.append("Red Flag: Sudden Vision Loss reported.")
|
102 |
+
if "weakness on one side" in symptoms_lower: flags.append("Red Flag: Unilateral Weakness reported (potential stroke).")
|
103 |
+
if "hemoptysis" in symptoms_lower: flags.append("Red Flag: Hemoptysis (coughing up blood).")
|
104 |
+
if "syncope" in symptoms_lower: flags.append("Red Flag: Syncope (fainting).")
|
105 |
+
|
106 |
+
# Vital Sign Flags
|
107 |
+
if vitals:
|
108 |
+
temp = vitals.get("temp_c"); hr = vitals.get("hr_bpm"); rr = vitals.get("rr_rpm")
|
109 |
+
spo2 = vitals.get("spo2_percent"); bp_str = vitals.get("bp_mmhg")
|
110 |
+
|
111 |
+
# CORRECTED Vital Sign Checks - Separate Lines
|
112 |
+
if temp is not None and temp >= 38.5:
|
113 |
+
flags.append(f"Red Flag: Fever ({temp}°C).")
|
114 |
+
if hr is not None and hr >= 120:
|
|
|
|
|
|
|
|
|
|
|
|
|
115 |
flags.append(f"Red Flag: Tachycardia ({hr} bpm).")
|
116 |
+
if hr is not None and hr <= 50:
|
117 |
flags.append(f"Red Flag: Bradycardia ({hr} bpm).")
|
118 |
+
if rr is not None and rr >= 24:
|
119 |
+
flags.append(f"Red Flag: Tachypnea ({rr} rpm).")
|
120 |
+
if spo2 is not None and spo2 <= 92:
|
121 |
+
flags.append(f"Red Flag: Hypoxia ({spo2}%).")
|
122 |
+
if bp_str:
|
123 |
+
bp = parse_bp(bp_str)
|
124 |
+
if bp:
|
125 |
+
if bp[0] >= 180 or bp[1] >= 110:
|
126 |
+
flags.append(f"Red Flag: Hypertensive Urgency/Emergency (BP: {bp_str} mmHg).")
|
127 |
+
if bp[0] <= 90 or bp[1] <= 60:
|
128 |
+
flags.append(f"Red Flag: Hypotension (BP: {bp_str} mmHg).")
|
129 |
+
|
130 |
+
# History Flags
|
131 |
+
if history and isinstance(history, str):
|
132 |
+
history_lower = history.lower()
|
133 |
+
if "history of mi" in history_lower and "chest pain" in symptoms_lower:
|
134 |
+
flags.append("Red Flag: History of MI with current Chest Pain.")
|
135 |
+
if "history of dvt/pe" in history_lower and "shortness of breath" in symptoms_lower:
|
136 |
+
flags.append("Red Flag: History of DVT/PE with current Shortness of Breath.")
|
137 |
+
|
138 |
+
return list(set(flags)) # Unique flags
|
139 |
|
140 |
|
141 |
def format_patient_data_for_prompt(data: dict) -> str:
|
142 |
+
# ... (Keep Corrected Implementation) ...
|
143 |
+
if not data: return "No patient data provided."; prompt_str = "";
|
144 |
+
for key, value in data.items(): section_title = key.replace('_', ' ').title();
|
145 |
+
if isinstance(value, dict) and value: has_content = any(sub_value for sub_value in value.values());
|
146 |
+
if has_content: prompt_str += f"**{section_title}:**\n";
|
147 |
+
for sub_key, sub_value in value.items():
|
148 |
+
if sub_value: prompt_str += f" - {sub_key.replace('_', ' ').title()}: {sub_value}\n"
|
149 |
+
elif isinstance(value, list) and value: prompt_str += f"**{section_title}:** {', '.join(map(str, value))}\n"
|
150 |
+
elif value and not isinstance(value, dict): prompt_str += f"**{section_title}:** {value}\n";
|
151 |
+
return prompt_str.strip()
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
152 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
153 |
|
154 |
# --- Tool Definitions ---
|
155 |
+
# ... (Keep Pydantic Models and Tool Function implementations as before) ...
|
156 |
+
class LabOrderInput(BaseModel): test_name: str = Field(...); reason: str = Field(...); priority: str = Field("Routine")
|
157 |
+
class PrescriptionInput(BaseModel): medication_name: str = Field(...); dosage: str = Field(...); route: str = Field(...); frequency: str = Field(...); duration: str = Field("As directed"); reason: str = Field(...)
|
158 |
+
class InteractionCheckInput(BaseModel): potential_prescription: str = Field(...); current_medications: Optional[List[str]] = Field(None); allergies: Optional[List[str]] = Field(None)
|
159 |
+
class FlagRiskInput(BaseModel): risk_description: str = Field(...); urgency: str = Field("High")
|
160 |
+
|
161 |
@tool("order_lab_test", args_schema=LabOrderInput)
|
162 |
def order_lab_test(test_name: str, reason: str, priority: str = "Routine") -> str:
|
163 |
+
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}"})
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
164 |
@tool("prescribe_medication", args_schema=PrescriptionInput)
|
165 |
+
def prescribe_medication(medication_name: str, dosage: str, route: str, frequency: str, duration: str, reason: str) -> str:
|
166 |
+
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}"})
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
167 |
@tool("check_drug_interactions", args_schema=InteractionCheckInput)
|
168 |
+
def check_drug_interactions(potential_prescription: str, current_medications: Optional[List[str]] = None, allergies: Optional[List[str]] = None) -> str:
|
169 |
+
print(f"\n--- Executing REAL check_drug_interactions ---"); print(f"Checking potential prescription: '{potential_prescription}'"); warnings = []; potential_med_lower = potential_prescription.lower().strip();
|
170 |
+
current_meds_list = current_medications or []; allergies_list = allergies or []; current_med_names_lower = [];
|
171 |
+
for med in current_meds_list: match = re.match(r"^\s*([a-zA-Z\-]+)", str(med));
|
172 |
+
if match: current_med_names_lower.append(match.group(1).lower());
|
173 |
+
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}");
|
174 |
+
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);
|
175 |
+
if not potential_rxcui and not potential_label: warnings.append(f"INFO: Could not reliably identify '{potential_prescription}'. Checks may be incomplete.");
|
176 |
+
print(" Step 2: Performing Allergy Check...");
|
177 |
+
for allergy in allergies_lower:
|
178 |
+
if allergy == potential_med_lower: warnings.append(f"CRITICAL ALLERGY (Name Match): Patient allergic to '{allergy}'. Potential prescription is '{potential_prescription}'.");
|
179 |
+
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}'.");
|
180 |
+
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}'.");
|
181 |
+
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}'.");
|
182 |
+
if potential_label: contraindications = potential_label.get("contraindications"); warnings_section = potential_label.get("warnings_and_cautions") or potential_label.get("warnings");
|
183 |
+
if contraindications: allergy_mentions_ci = search_text_list(contraindications, allergies_lower);
|
184 |
+
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)}");
|
185 |
+
if warnings_section: allergy_mentions_warn = search_text_list(warnings_section, allergies_lower);
|
186 |
+
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)}");
|
187 |
+
print(" Step 3: Performing Drug-Drug Interaction Check...");
|
188 |
+
if potential_rxcui or potential_label:
|
189 |
+
for current_med_name in current_med_names_lower:
|
190 |
+
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];
|
191 |
+
if current_rxcui: search_terms_for_current.append(current_rxcui); search_terms_for_potential = [potential_med_lower];
|
192 |
+
if potential_rxcui: search_terms_for_potential.append(potential_rxcui); interaction_found_flag = False;
|
193 |
+
if potential_label and potential_label.get("drug_interactions"): interaction_mentions = search_text_list(potential_label.get("drug_interactions"), search_terms_for_current);
|
194 |
+
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;
|
195 |
+
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);
|
196 |
+
if interaction_mentions: warnings.append(f"Potential Interaction ({current_med_name.capitalize()} Label): Mentions '{potential_prescription.capitalize()}'. Snippets: {'; '.join(interaction_mentions)}");
|
197 |
+
else: warnings.append(f"INFO: Drug-drug interaction check skipped for '{potential_prescription}' as it could not be identified via RxNorm/OpenFDA.");
|
198 |
+
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";
|
199 |
+
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 ---");
|
200 |
+
return json.dumps({"status": status, "message": message, "warnings": final_warnings})
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
201 |
@tool("flag_risk", args_schema=FlagRiskInput)
|
202 |
def flag_risk(risk_description: str, urgency: str) -> str:
|
203 |
+
print(f"Executing flag_risk: {risk_description}, Urgency: {urgency}"); return json.dumps({"status": "flagged", "message": f"Risk '{risk_description}' flagged with {urgency} urgency."})
|
204 |
+
search_tool = TavilySearchResults(max_results=MAX_SEARCH_RESULTS, name="tavily_search_results")
|
205 |
+
all_tools = [order_lab_test, prescribe_medication, check_drug_interactions, flag_risk, search_tool]
|
206 |
+
|
207 |
+
# --- LangGraph State & Nodes ---
|
208 |
+
class AgentState(TypedDict): messages: Annotated[list[Any], operator.add]; patient_data: Optional[dict]; summary: Optional[str]; interaction_warnings: Optional[List[str]]
|
209 |
+
llm = ChatGroq(temperature=AGENT_TEMPERATURE, model=AGENT_MODEL_NAME); model_with_tools = llm.bind_tools(all_tools); tool_executor = ToolExecutor(all_tools)
|
210 |
+
def agent_node(state: AgentState):
|
211 |
+
# ... (Keep implementation) ...
|
212 |
+
print("\n---AGENT NODE---"); current_messages = state['messages'];
|
213 |
+
if not current_messages or not isinstance(current_messages[0], SystemMessage): print("Prepending System Prompt."); current_messages = [SystemMessage(content=ClinicalPrompts.SYSTEM_PROMPT)] + current_messages;
|
214 |
+
print(f"Invoking LLM with {len(current_messages)} messages.");
|
215 |
+
try: response = model_with_tools.invoke(current_messages); print(f"Agent Raw Response Type: {type(response)}");
|
216 |
+
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.");
|
217 |
+
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]};
|
218 |
+
return {"messages": [response]}
|
219 |
+
def tool_node(state: AgentState):
|
220 |
+
# ... (Keep implementation) ...
|
221 |
+
print("\n---TOOL NODE---"); tool_messages = []; last_message = state['messages'][-1]; interaction_warnings_found = [];
|
222 |
+
if not isinstance(last_message, AIMessage) or not getattr(last_message, 'tool_calls', None): print("Warning: Tool node called unexpectedly."); return {"messages": [], "interaction_warnings": None};
|
223 |
+
tool_calls = last_message.tool_calls; print(f"Tool calls received: {json.dumps(tool_calls, indent=2)}"); prescriptions_requested = {}; interaction_checks_requested = {};
|
224 |
+
for call in tool_calls: tool_name = call.get('name'); tool_args = call.get('args', {});
|
225 |
+
if tool_name == 'prescribe_medication': med_name = tool_args.get('medication_name', '').lower();
|
226 |
+
if med_name: prescriptions_requested[med_name] = call;
|
227 |
+
elif tool_name == 'check_drug_interactions': potential_med = tool_args.get('potential_prescription', '').lower();
|
228 |
+
if potential_med: interaction_checks_requested[potential_med] = call;
|
229 |
+
valid_tool_calls_for_execution = []; blocked_ids = set();
|
230 |
+
for med_name, prescribe_call in prescriptions_requested.items():
|
231 |
+
if med_name not in interaction_checks_requested: print(f"**SAFETY VIOLATION (Agent): Prescribe '{med_name}' blocked - no interaction check requested.**"); 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']);
|
232 |
+
valid_tool_calls_for_execution = [call for call in tool_calls if call['id'] not in blocked_ids];
|
233 |
+
patient_data = state.get("patient_data", {}); patient_meds_full = patient_data.get("medications", {}).get("current", []); patient_allergies = patient_data.get("allergies", []);
|
234 |
+
for call in valid_tool_calls_for_execution:
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
235 |
if call['name'] == 'check_drug_interactions':
|
236 |
+
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']}");
|
237 |
+
if valid_tool_calls_for_execution: print(f"Attempting execution: {[c['name'] for c in valid_tool_calls_for_execution]}");
|
238 |
+
try: responses = tool_executor.batch(valid_tool_calls_for_execution, return_exceptions=True);
|
239 |
+
for call, resp in zip(valid_tool_calls_for_execution, responses): tool_call_id = call['id']; tool_name = call['name'];
|
240 |
+
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(); 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));
|
241 |
+
if isinstance(resp, AttributeError) and "'dict' object has no attribute 'tool'" in error_str: print("\n *** DETECTED SPECIFIC ATTRIBUTE ERROR *** \n");
|
242 |
+
else:
|
243 |
+
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));
|
244 |
+
if tool_name == "check_drug_interactions": # Extract warnings
|
245 |
+
try: result_data = json.loads(content_str);
|
246 |
+
if result_data.get("status") == "warning" and result_data.get("warnings"): print(f" Interaction check returned warnings: {result_data['warnings']}"); interaction_warnings_found.extend(result_data["warnings"]);
|
247 |
+
except Exception as e: print(f" Error processing interaction check result: {e}");
|
248 |
+
except Exception as e: # Outer exception handling...
|
249 |
+
print(f"CRITICAL TOOL NODE ERROR: {e}"); traceback.print_exc(); 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];
|
250 |
+
print(f"Returning {len(tool_messages)} tool messages. Warnings: {bool(interaction_warnings_found)}")
|
251 |
+
return {"messages": tool_messages, "interaction_warnings": interaction_warnings_found or None} # Return messages AND warnings
|
252 |
+
def reflection_node(state: AgentState):
|
253 |
+
# ... (Keep implementation) ...
|
254 |
+
print("\n---REFLECTION NODE---")
|
255 |
+
interaction_warnings = state.get("interaction_warnings")
|
256 |
+
if not interaction_warnings: print("Warning: Reflection node called without warnings."); return {"messages": [], "interaction_warnings": None};
|
257 |
+
print(f"Reviewing interaction warnings: {interaction_warnings}"); triggering_ai_message = None; relevant_tool_call_ids = set();
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
258 |
for msg in reversed(state['messages']):
|
259 |
+
if isinstance(msg, ToolMessage) and msg.name == "check_drug_interactions": relevant_tool_call_ids.add(msg.tool_call_id);
|
260 |
+
if isinstance(msg, AIMessage) and msg.tool_calls:
|
261 |
+
if any(tc['id'] in relevant_tool_call_ids for tc in msg.tool_calls): triggering_ai_message = msg; break;
|
262 |
+
if not triggering_ai_message: print("Error: Could not find triggering AI message for reflection."); return {"messages": [AIMessage(content="Internal Error: Reflection context missing.")], "interaction_warnings": None};
|
263 |
+
original_plan_proposal_context = triggering_ai_message.content;
|
264 |
+
reflection_prompt_text = f"""You are SynapseAI, performing a critical safety review... [PROMPT OMITTED FOR BREVITY]""" # Use full prompt
|
265 |
+
reflection_messages = [SystemMessage(content="Perform focused safety review based on interaction warnings."), HumanMessage(content=reflection_prompt_text)];
|
266 |
+
print("Invoking LLM for reflection...");
|
267 |
+
try: reflection_response = llm.invoke(reflection_messages); print(f"Reflection Response: {reflection_response.content}"); final_ai_message = AIMessage(content=reflection_response.content);
|
268 |
+
except Exception as e: print(f"ERROR during reflection: {e}"); traceback.print_exc(); final_ai_message = AIMessage(content=f"Error during safety reflection: {e}");
|
269 |
+
return {"messages": [final_ai_message], "interaction_warnings": None} # Return reflection response, clear warnings
|
270 |
+
|
271 |
+
# --- Graph Routing Logic ---
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
272 |
def should_continue(state: AgentState) -> str:
|
273 |
+
# ... (Keep implementation) ...
|
274 |
+
print("\n---ROUTING DECISION (Agent Output)---"); last_message = state['messages'][-1] if state['messages'] else None;
|
275 |
+
if not isinstance(last_message, AIMessage): return "end_conversation_turn";
|
276 |
+
if "Sorry, an internal error occurred" in last_message.content: return "end_conversation_turn";
|
277 |
+
if getattr(last_message, 'tool_calls', None): return "continue_tools"; else: return "end_conversation_turn";
|
|
|
|
|
|
|
278 |
def after_tools_router(state: AgentState) -> str:
|
279 |
+
# ... (Keep implementation) ...
|
280 |
+
print("\n---ROUTING DECISION (After Tools)---");
|
281 |
+
if state.get("interaction_warnings"): print("Routing: Warnings found -> Reflection"); return "reflect_on_warnings";
|
282 |
+
else: print("Routing: No warnings -> Agent"); return "continue_to_agent";
|
283 |
|
284 |
+
# --- ClinicalAgent Class ---
|
285 |
class ClinicalAgent:
|
286 |
def __init__(self):
|
287 |
+
# ... (Keep graph compilation) ...
|
288 |
+
workflow = StateGraph(AgentState); workflow.add_node("agent", agent_node); workflow.add_node("tools", tool_node); workflow.add_node("reflection", reflection_node)
|
289 |
+
workflow.set_entry_point("agent"); workflow.add_conditional_edges("agent", should_continue, {"continue_tools": "tools", "end_conversation_turn": END})
|
290 |
+
workflow.add_conditional_edges("tools", after_tools_router, {"reflect_on_warnings": "reflection", "continue_to_agent": "agent"})
|
291 |
+
workflow.add_edge("reflection", "agent"); self.graph_app = workflow.compile(); print("ClinicalAgent initialized and LangGraph compiled.")
|
292 |
+
def invoke_turn(self, state: Dict) -> Dict:
|
293 |
+
# ... (Keep implementation) ...
|
294 |
+
print(f"Invoking graph with state keys: {state.keys()}");
|
295 |
+
try: final_state = self.graph_app.invoke(state, {"recursion_limit": 15}); final_state.setdefault('summary', state.get('summary')); final_state.setdefault('interaction_warnings', None); return final_state
|
296 |
+
except Exception as e: print(f"CRITICAL ERROR during graph invocation: {type(e).__name__} - {e}"); traceback.print_exc(); error_msg = AIMessage(content=f"Sorry, error occurred: {e}"); return {"messages": state.get('messages', []) + [error_msg], "patient_data": state.get('patient_data'), "summary": state.get('summary'), "interaction_warnings": None}
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|