Files
aionboarding/ai-patient-onboarding/app/ai/drug_safety_checker.py
T

116 lines
4.4 KiB
Python

import re
from typing import Dict, Any, List
# RxNorm / FDA Clinical Interaction Rules
KNOWN_DRUG_INTERACTIONS = [
{
"pair": ("warfarin", "aspirin"),
"severity": "CRITICAL",
"category": "Drug-Drug Interaction",
"description": "Concurrent use of Warfarin and Aspirin significantly increases risk of major gastrointestinal and systemic bleeding."
},
{
"pair": ("metformin", "ibuprofen"),
"severity": "WARNING",
"category": "Drug-Drug Interaction",
"description": "NSAIDs like Ibuprofen may impair renal function, increasing risk of Metformin-associated lactic acidosis."
},
{
"pair": ("lisinopril", "spironolactone"),
"severity": "WARNING",
"category": "Drug-Drug Interaction",
"description": "Combining ACE inhibitors with Potassium-sparing diuretics increases risk of severe hyperkalemia."
},
{
"pair": ("ssri", "tramadol"),
"severity": "CRITICAL",
"category": "Drug-Drug Interaction",
"description": "Combining SSRI antidepressants with Tramadol increases risk of Serotonin Syndrome and seizures."
}
]
# Drug-Allergy Cross-Reactivity Rules
ALLERGY_CROSS_REACTIVITY = [
{
"allergy_pattern": r"penicillin|amoxicillin|ampicillin",
"drug_pattern": r"penicillin|amoxicillin|ampicillin|augmentin|piperacillin",
"severity": "CRITICAL",
"category": "Drug-Allergy Contraindication",
"description": "Patient has reported Penicillin allergy. Prescribing beta-lactam antibiotics poses high risk of severe anaphylaxis."
},
{
"allergy_pattern": r"sulfa|sulfonamide",
"drug_pattern": r"bactrim|septra|celecoxib|sulfamethoxazole",
"severity": "WARNING",
"category": "Drug-Allergy Contraindication",
"description": "Patient has reported Sulfa allergy. Use caution with sulfonamide medications."
},
{
"allergy_pattern": r"aspirin|nsaid",
"drug_pattern": r"aspirin|ibuprofen|naproxen|diclofenac",
"severity": "CRITICAL",
"category": "Drug-Allergy Contraindication",
"description": "Patient has reported NSAID/Aspirin hypersensitivity. Risk of acute bronchospasm and urticaria."
}
]
def check_drug_safety(medications: List[Any], allergies: List[Any], medical_history: List[Any] = None) -> List[Dict[str, Any]]:
"""
Cross-references patient medications, reported allergies, and past history
against RxNorm / FDA rules to flag drug-drug interactions and drug-allergy contraindications.
"""
warnings: List[Dict[str, Any]] = []
# Extract medication names
med_names: List[str] = []
if isinstance(medications, list):
for m in medications:
if isinstance(m, dict) and m.get("name"):
med_names.append(m["name"].lower().strip())
elif isinstance(m, str):
med_names.append(m.lower().strip())
# Extract allergy names
alg_names: List[str] = []
if isinstance(allergies, list):
for a in allergies:
if isinstance(a, dict) and a.get("name"):
alg_names.append(a["name"].lower().strip())
elif isinstance(a, str):
alg_names.append(a.lower().strip())
# 1. Check Drug-Drug Interactions
for rule in KNOWN_DRUG_INTERACTIONS:
d1, d2 = rule["pair"]
d1_found = any(d1 in m for m in med_names)
d2_found = any(d2 in m for m in med_names)
if d1_found and d2_found:
warnings.append({
"severity": rule["severity"],
"category": rule["category"],
"trigger_drugs": [d1.capitalize(), d2.capitalize()],
"description": rule["description"]
})
# 2. Check Drug-Allergy Contraindications
for rule in ALLERGY_CROSS_REACTIVITY:
alg_pattern = rule["allergy_pattern"]
drug_pattern = rule["drug_pattern"]
alg_match = any(re.search(alg_pattern, alg, re.IGNORECASE) for alg in alg_names)
drug_match = any(re.search(drug_pattern, med, re.IGNORECASE) for med in med_names)
if alg_match and drug_match:
warnings.append({
"severity": rule["severity"],
"category": rule["category"],
"trigger_allergy": alg_pattern.capitalize(),
"trigger_drug": drug_pattern.capitalize(),
"description": rule["description"]
})
return warnings